Index: ps/trunk/source/tools/XpartaMuPP/EcheLOn.py =================================================================== --- ps/trunk/source/tools/XpartaMuPP/EcheLOn.py (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/EcheLOn.py (nonexistent) @@ -1,795 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -"""Copyright (C) 2018 Wildfire Games. - * This file is part of 0 A.D. - * - * 0 A.D. is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version. - * - * 0 A.D. is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with 0 A.D. If not, see . -""" - -import logging, time, traceback -from optparse import OptionParser - -import sleekxmpp -from sleekxmpp.stanza import Iq -from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin, ET -from sleekxmpp.xmlstream.handler import Callback -from sleekxmpp.xmlstream.matcher import StanzaPath - -from sqlalchemy import func - -from LobbyRanking import session as db, Game, Player, PlayerInfo -from ELO import get_rating_adjustment -# Rating that new players should be inserted into the -# database with, before they've played any games. -leaderboard_default_rating = 1200 - -## Class that contains and manages leaderboard data ## -class LeaderboardList(): - def __init__(self, room): - self.room = room - self.lastRated = "" - - def getProfile(self, JID): - """ - Retrieves the profile for the specified JID - """ - stats = {} - player = db.query(Player).filter(Player.jid.ilike(str(JID))) - - if not player.first(): - return - - queried_player = player.first() - playerID = queried_player.id - if queried_player.rating != -1: - stats['rating'] = str(queried_player.rating) - rank = db.query(Player).filter(Player.rating >= queried_player.rating).count() - stats['rank'] = str(rank) - - if queried_player.highest_rating != -1: - stats['highestRating'] = str(queried_player.highest_rating) - - gamesPlayed = db.query(PlayerInfo).filter_by(player_id=playerID).count() - wins = db.query(Game).filter_by(winner_id=playerID).count() - stats['totalGamesPlayed'] = str(gamesPlayed) - stats['wins'] = str(wins) - stats['losses'] = str(gamesPlayed - wins) - return stats - - def getOrCreatePlayer(self, JID): - """ - Stores a player(JID) in the database if they don't yet exist. - Returns either the newly created instance of - the Player model, or the one that already - exists in the database. - """ - players = db.query(Player).filter(Player.jid.ilike(str(JID))) - if not players.first(): - player = Player(jid=str(JID), rating=-1) - db.add(player) - db.commit() - return player - return players.first() - - def removePlayer(self, JID): - """ - Remove a player(JID) from database. - Returns the player that was removed, or None - if that player didn't exist. - """ - players = db.query(Player).filter(Player.jid.ilike(str(JID))) - player = players.first() - if not player: - return None - players.delete() - return player - - def addGame(self, gamereport): - """ - Adds a game to the database and updates the data - on a player(JID) from game results. - Returns the created Game object, or None if - the creation failed for any reason. - Side effects: - Inserts a new Game instance into the database. - """ - # Discard any games still in progress. - if any(map(lambda state: state == 'active', - dict.values(gamereport['playerStates']))): - return None - - players = map(lambda jid: db.query(Player).filter(Player.jid.ilike(str(jid))).first(), - dict.keys(gamereport['playerStates'])) - - winning_jid = list(dict.keys({jid: state for jid, state in - gamereport['playerStates'].items() - if state == 'won'}))[0] - - def get(stat, jid): - return gamereport[stat][jid] - - singleStats = {'timeElapsed', 'mapName', 'teamsLocked', 'matchID'} - totalScoreStats = {'economyScore', 'militaryScore', 'totalScore'} - resourceStats = {'foodGathered', 'foodUsed', 'woodGathered', 'woodUsed', - 'stoneGathered', 'stoneUsed', 'metalGathered', 'metalUsed', 'vegetarianFoodGathered', - 'treasuresCollected', 'lootCollected', 'tributesSent', 'tributesReceived'} - unitsStats = {'totalUnitsTrained', 'totalUnitsLost', 'enemytotalUnitsKilled', 'infantryUnitsTrained', - 'infantryUnitsLost', 'enemyInfantryUnitsKilled', 'workerUnitsTrained', 'workerUnitsLost', - 'enemyWorkerUnitsKilled', 'femaleCitizenUnitsTrained', 'femaleCitizenUnitsLost', 'enemyFemaleCitizenUnitsKilled', - 'cavalryUnitsTrained', 'cavalryUnitsLost', 'enemyCavalryUnitsKilled', 'championUnitsTrained', - 'championUnitsLost', 'enemyChampionUnitsKilled', 'heroUnitsTrained', 'heroUnitsLost', - 'enemyHeroUnitsKilled', 'shipUnitsTrained', 'shipUnitsLost', 'enemyShipUnitsKilled', 'traderUnitsTrained', - 'traderUnitsLost', 'enemyTraderUnitsKilled'} - buildingsStats = {'totalBuildingsConstructed', 'totalBuildingsLost', 'enemytotalBuildingsDestroyed', - 'civCentreBuildingsConstructed', 'civCentreBuildingsLost', 'enemyCivCentreBuildingsDestroyed', - 'houseBuildingsConstructed', 'houseBuildingsLost', 'enemyHouseBuildingsDestroyed', - 'economicBuildingsConstructed', 'economicBuildingsLost', 'enemyEconomicBuildingsDestroyed', - 'outpostBuildingsConstructed', 'outpostBuildingsLost', 'enemyOutpostBuildingsDestroyed', - 'militaryBuildingsConstructed', 'militaryBuildingsLost', 'enemyMilitaryBuildingsDestroyed', - 'fortressBuildingsConstructed', 'fortressBuildingsLost', 'enemyFortressBuildingsDestroyed', - 'wonderBuildingsConstructed', 'wonderBuildingsLost', 'enemyWonderBuildingsDestroyed'} - marketStats = {'woodBought', 'foodBought', 'stoneBought', 'metalBought', 'tradeIncome'} - miscStats = {'civs', 'teams', 'percentMapExplored'} - - stats = totalScoreStats | resourceStats | unitsStats | buildingsStats | marketStats | miscStats - playerInfos = [] - for player in players: - jid = player.jid - playerinfo = PlayerInfo(player=player) - for reportname in stats: - setattr(playerinfo, reportname, get(reportname, jid.lower())) - playerInfos.append(playerinfo) - - game = Game(map=gamereport['mapName'], duration=int(gamereport['timeElapsed']), teamsLocked=bool(gamereport['teamsLocked']), matchID=gamereport['matchID']) - game.players.extend(players) - game.player_info.extend(playerInfos) - game.winner = db.query(Player).filter(Player.jid.ilike(str(winning_jid))).first() - db.add(game) - db.commit() - return game - - def verifyGame(self, gamereport): - """ - Returns a boolean based on whether the game should be rated. - Here, we can specify the criteria for rated games. - """ - winning_jids = list(dict.keys({jid: state for jid, state in - gamereport['playerStates'].items() - if state == 'won'})) - # We only support 1v1s right now. TODO: Support team games. - if len(winning_jids) * 2 > len(dict.keys(gamereport['playerStates'])): - # More than half the people have won. This is not a balanced team game or duel. - return False - if len(dict.keys(gamereport['playerStates'])) != 2: - return False - return True - - def rateGame(self, game): - """ - Takes a game with 2 players and alters their ratings - based on the result of the game. - Returns self. - Side effects: - Changes the game's players' ratings in the database. - """ - player1 = game.players[0] - player2 = game.players[1] - # TODO: Support draws. Since it's impossible to draw in the game currently, - # the database model, and therefore this code, requires a winner. - # The Elo implementation does not, however. - result = 1 if player1 == game.winner else -1 - # Player's ratings are -1 unless they have played a rated game. - if player1.rating == -1: - player1.rating = leaderboard_default_rating - if player2.rating == -1: - player2.rating = leaderboard_default_rating - - rating_adjustment1 = int(get_rating_adjustment(player1.rating, player2.rating, - len(player1.games), len(player2.games), result)) - rating_adjustment2 = int(get_rating_adjustment(player2.rating, player1.rating, - len(player2.games), len(player1.games), result * -1)) - if result == 1: - resultQualitative = "won" - elif result == 0: - resultQualitative = "drew" - else: - resultQualitative = "lost" - name1 = '@'.join(player1.jid.split('@')[:-1]) - name2 = '@'.join(player2.jid.split('@')[:-1]) - self.lastRated = "A rated game has ended. %s %s against %s. Rating Adjustment: %s (%s -> %s) and %s (%s -> %s)."%(name1, - resultQualitative, name2, name1, player1.rating, player1.rating + rating_adjustment1, - name2, player2.rating, player2.rating + rating_adjustment2) - player1.rating += rating_adjustment1 - player2.rating += rating_adjustment2 - if not player1.highest_rating: - player1.highest_rating = -1 - if not player2.highest_rating: - player2.highest_rating = -1 - if player1.rating > player1.highest_rating: - player1.highest_rating = player1.rating - if player2.rating > player2.highest_rating: - player2.highest_rating = player2.rating - db.commit() - return self - - def getLastRatedMessage(self): - """ - Gets the string of the last rated game. Triggers an update - chat for the bot. - """ - return self.lastRated - - def addAndRateGame(self, gamereport): - """ - Calls addGame and if the game has only two - players, also calls rateGame. - Returns the result of addGame. - """ - game = self.addGame(gamereport) - if game and self.verifyGame(gamereport): - self.rateGame(game) - else: - self.lastRated = "" - return game - - def getBoard(self): - """ - Returns a dictionary of player rankings to - JIDs for sending. - """ - board = {} - players = db.query(Player).filter(Player.rating != -1).order_by(Player.rating.desc()).limit(100).all() - for rank, player in enumerate(players): - board[player.jid] = {'name': '@'.join(player.jid.split('@')[:-1]), 'rating': str(player.rating)} - return board - - def getRatingList(self, nicks): - """ - Returns a rating list of players - currently in the lobby by nick - because the client can't link - JID to nick conveniently. - """ - ratinglist = {} - players = db.query(Player.jid, Player.rating).filter(func.upper(Player.jid).in_([ str(JID).upper() for JID in list(nicks) ])) - for player in players: - rating = str(player.rating) if player.rating != -1 else '' - for JID in list(nicks): - if JID.upper() == player.jid.upper(): - ratinglist[nicks[JID]] = {'name': nicks[JID], 'rating': rating} - break - return ratinglist - -## Class which manages different game reports from clients ## -## and calls leaderboard functions as appropriate. ## -class ReportManager(): - def __init__(self, leaderboard): - self.leaderboard = leaderboard - self.interimReportTracker = [] - self.interimJIDTracker = [] - - def addReport(self, JID, rawGameReport): - """ - Adds a game to the interface between a raw report - and the leaderboard database. - """ - # cleanRawGameReport is a copy of rawGameReport with all reporter specific information removed. - cleanRawGameReport = rawGameReport.copy() - del cleanRawGameReport["playerID"] - - if cleanRawGameReport not in self.interimReportTracker: - # Store the game. - appendIndex = len(self.interimReportTracker) - self.interimReportTracker.append(cleanRawGameReport) - # Initilize the JIDs and store the initial JID. - numPlayers = self.getNumPlayers(rawGameReport) - JIDs = [None] * numPlayers - if numPlayers - int(rawGameReport["playerID"]) > -1: - JIDs[int(rawGameReport["playerID"])-1] = str(JID).lower() - self.interimJIDTracker.append(JIDs) - else: - # We get the index at which the JIDs coresponding to the game are stored. - index = self.interimReportTracker.index(cleanRawGameReport) - # We insert the new report JID into the ascending list of JIDs for the game. - JIDs = self.interimJIDTracker[index] - if len(JIDs) - int(rawGameReport["playerID"]) > -1: - JIDs[int(rawGameReport["playerID"])-1] = str(JID).lower() - self.interimJIDTracker[index] = JIDs - - self.checkFull() - - def expandReport(self, rawGameReport, JIDs): - """ - Takes an raw game report and re-formats it into - Python data structures leaving JIDs empty. - Returns a processed gameReport of type dict. - """ - processedGameReport = {} - for key in rawGameReport: - if rawGameReport[key].find(",") == -1: - processedGameReport[key] = rawGameReport[key] - else: - split = rawGameReport[key].split(",") - # Remove the false split positive. - split.pop() - statToJID = {} - for i, part in enumerate(split): - statToJID[JIDs[i]] = part - processedGameReport[key] = statToJID - return processedGameReport - - def checkFull(self): - """ - Searches internal database to check if enough - reports have been submitted to add a game to - the leaderboard. If so, the report will be - interpolated and addAndRateGame will be - called with the result. - """ - i = 0 - length = len(self.interimReportTracker) - while(i < length): - numPlayers = self.getNumPlayers(self.interimReportTracker[i]) - numReports = 0 - for JID in self.interimJIDTracker[i]: - if JID != None: - numReports += 1 - if numReports == numPlayers: - try: - self.leaderboard.addAndRateGame(self.expandReport(self.interimReportTracker[i], self.interimJIDTracker[i])) - except: - traceback.print_exc() - del self.interimJIDTracker[i] - del self.interimReportTracker[i] - length -= 1 - else: - i += 1 - self.leaderboard.lastRated = "" - - def getNumPlayers(self, rawGameReport): - """ - Computes the number of players in a raw gameReport. - Returns int, the number of players. - """ - # Find a key in the report which holds values for multiple players. - for key in rawGameReport: - if rawGameReport[key].find(",") != -1: - # Count the number of values, minus one for the false split positive. - return len(rawGameReport[key].split(","))-1 - # Return -1 in case of failure. - return -1 - -## Class for custom player stanza extension ## -class PlayerXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:player' - interfaces = set(('game', 'online')) - sub_interfaces = interfaces - plugin_attrib = 'player' - - def addPlayerOnline(self, player): - playerXml = ET.fromstring("%s" % player) - self.xml.append(playerXml) - -## Class for custom boardlist and ratinglist stanza extension ## -class BoardListXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:boardlist' - interfaces = set(('board', 'command', 'recipient')) - sub_interfaces = interfaces - plugin_attrib = 'boardlist' - def addCommand(self, command): - commandXml = ET.fromstring("%s" % command) - self.xml.append(commandXml) - def addRecipient(self, recipient): - recipientXml = ET.fromstring("%s" % recipient) - self.xml.append(recipientXml) - def addItem(self, name, rating): - itemXml = ET.Element("board", {"name": name, "rating": rating}) - self.xml.append(itemXml) - -## Class for custom gamereport stanza extension ## -class GameReportXmppPlugin(ElementBase): - name = 'report' - namespace = 'jabber:iq:gamereport' - plugin_attrib = 'gamereport' - interfaces = ('game', 'sender') - sub_interfaces = interfaces - def addSender(self, sender): - senderXml = ET.fromstring("%s" % sender) - self.xml.append(senderXml) - def getGame(self): - """ - Required to parse incoming stanzas with this - extension. - """ - game = self.xml.find('{%s}game' % self.namespace) - data = {} - for key, item in game.items(): - data[key] = item - return data - -## Class for custom profile ## -class ProfileXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:profile' - interfaces = set(('profile', 'command', 'recipient')) - sub_interfaces = interfaces - plugin_attrib = 'profile' - def addCommand(self, command): - commandXml = ET.fromstring("%s" % command) - self.xml.append(commandXml) - def addRecipient(self, recipient): - recipientXml = ET.fromstring("%s" % recipient) - self.xml.append(recipientXml) - def addItem(self, player, rating, highestRating, rank, totalGamesPlayed, wins, losses): - itemXml = ET.Element("profile", {"player": player, "rating": rating, "highestRating": highestRating, - "rank" : rank, "totalGamesPlayed" : totalGamesPlayed, "wins" : wins, - "losses" : losses}) - self.xml.append(itemXml) - -## Main class which handles IQ data and sends new data ## -class EcheLOn(sleekxmpp.ClientXMPP): - """ - A simple list provider - """ - def __init__(self, sjid, password, room, nick): - sleekxmpp.ClientXMPP.__init__(self, sjid, password) - self.sjid = sjid - self.room = room - self.nick = nick - self.ratingListCache = {} - self.ratingCacheReload = True - self.boardListCache = {} - self.boardCacheReload = True - - # Init leaderboard object - self.leaderboard = LeaderboardList(room) - - # gameReport to leaderboard abstraction - self.reportManager = ReportManager(self.leaderboard) - - # Store mapping of nicks and XmppIDs, attached via presence stanza - self.nicks = {} - - self.lastLeft = "" - - register_stanza_plugin(Iq, PlayerXmppPlugin) - register_stanza_plugin(Iq, BoardListXmppPlugin) - register_stanza_plugin(Iq, GameReportXmppPlugin) - register_stanza_plugin(Iq, ProfileXmppPlugin) - - self.register_handler(Callback('Iq Player', - StanzaPath('iq/player'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq Boardlist', - StanzaPath('iq/boardlist'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq GameReport', - StanzaPath('iq/gamereport'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq Profile', - StanzaPath('iq/profile'), - self.iqhandler, - instream=True)) - - self.add_event_handler("session_start", self.start) - self.add_event_handler("muc::%s::got_online" % self.room, self.muc_online) - self.add_event_handler("muc::%s::got_offline" % self.room, self.muc_offline) - - def start(self, event): - """ - Process the session_start event - """ - self.plugin['xep_0045'].joinMUC(self.room, self.nick) - self.send_presence() - self.get_roster() - logging.info("EcheLOn started") - - def muc_online(self, presence): - """ - Process presence stanza from a chat room. - """ - if presence['muc']['nick'] != self.nick: - # If it doesn't already exist, store player JID mapped to their nick. - if str(presence['muc']['jid']) not in self.nicks: - self.nicks[str(presence['muc']['jid'])] = presence['muc']['nick'] - # Check the jid isn't already in the lobby. - logging.debug("Client '%s' connected with a nick of '%s'." %(presence['muc']['jid'], presence['muc']['nick'])) - - def muc_offline(self, presence): - """ - Process presence stanza from a chat room. - """ - # Clean up after a player leaves - if presence['muc']['nick'] != self.nick: - # Remove them from the local player list. - self.lastLeft = str(presence['muc']['jid']) - if str(presence['muc']['jid']) in self.nicks: - del self.nicks[str(presence['muc']['jid'])] - - def iqhandler(self, iq): - """ - Handle the custom stanzas - This method should be very robust because we could receive anything - """ - if iq['type'] == 'error': - logging.error('iqhandler error' + iq['error']['condition']) - #self.disconnect() - elif iq['type'] == 'get': - """ - Request lists. - """ - if 'boardlist' in iq.loaded_plugins: - command = iq['boardlist']['command'] - recipient = iq['boardlist']['recipient'] - if command == 'getleaderboard': - try: - self.sendBoardList(iq['from'], recipient) - except: - traceback.print_exc() - logging.error("Failed to process leaderboardlist request from %s" % iq['from'].bare) - elif command == 'getratinglist': - try: - self.sendRatingList(iq['from']); - except: - traceback.print_exc() - else: - logging.error("Failed to process boardlist request from %s" % iq['from'].bare) - elif 'profile' in iq.loaded_plugins: - command = iq['profile']['command'] - recipient = iq['profile']['recipient'] - try: - self.sendProfile(iq['from'], command, recipient) - except: - try: - self.sendProfileNotFound(iq['from'], command, recipient) - except: - logging.debug("No record found for %s" % command) - else: - logging.error("Unknown 'get' type stanza request from %s" % iq['from'].bare) - elif iq['type'] == 'result': - """ - Iq successfully received - """ - pass - elif iq['type'] == 'set': - if 'gamereport' in iq.loaded_plugins: - """ - Client is reporting end of game statistics - """ - if iq['gamereport']['sender']: - sender = iq['gamereport']['sender'] - else: - sender = iq['from'] - try: - self.leaderboard.getOrCreatePlayer(iq['gamereport']['sender']) - self.reportManager.addReport(sender, iq['gamereport']['game']) - if self.leaderboard.getLastRatedMessage() != "": - self.ratingCacheReload = True - self.boardCacheReload = True - self.send_message(mto=self.room, mbody=self.leaderboard.getLastRatedMessage(), mtype="groupchat", - mnick=self.nick) - self.sendRatingList(iq['from']) - except: - traceback.print_exc() - logging.error("Failed to update game statistics for %s" % iq['from'].bare) - elif 'player' in iq.loaded_plugins: - player = iq['player']['online'] - #try: - self.leaderboard.getOrCreatePlayer(player) - #except: - #logging.debug("Could not create new user %s" % player) - else: - logging.error("Failed to process stanza type '%s' received from %s" % iq['type'], iq['from'].bare) - - def sendBoardList(self, to, recipient): - """ - Send the whole leaderboard list. - If no target is passed the boardlist is broadcasted - to all clients. - """ - ## See if we can squeak by with the cached version. - # Leaderboard cache is reloaded upon a new rated game being rated. - if self.boardCacheReload: - self.boardListCache = self.leaderboard.getBoard() - self.boardCacheReload = False - - stz = BoardListXmppPlugin() - iq = self.Iq() - iq['type'] = 'result' - for i in self.boardListCache: - stz.addItem(self.boardListCache[i]['name'], self.boardListCache[i]['rating']) - stz.addCommand('boardlist') - stz.addRecipient(recipient) - iq.setPayload(stz) - ## Check recipient exists - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send boardlist to" % str(to)) - return - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send leaderboard list") - - def sendRatingList(self, to): - """ - Send the rating list. - """ - ## Attempt to use the cache. - # Cache is invalidated when a new game is rated or a uncached player - # comes online. - if self.ratingCacheReload: - self.ratingListCache = self.leaderboard.getRatingList(self.nicks) - self.ratingCacheReload = False - else: - for JID in list(self.nicks): - if JID not in self.ratingListCache: - self.ratingListCache = self.leaderboard.getRatingList(self.nicks) - self.ratingCacheReload = False - break - - stz = BoardListXmppPlugin() - iq = self.Iq() - iq['type'] = 'result' - for i in self.ratingListCache: - stz.addItem(self.ratingListCache[i]['name'], self.ratingListCache[i]['rating']) - stz.addCommand('ratinglist') - iq.setPayload(stz) - ## Check recipient exists - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send ratinglist to" % str(to)) - return - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send rating list") - - def sendProfile(self, to, player, recipient): - """ - Send the player profile to a specified target. - """ - if to == "": - logging.error("Failed to send profile") - return - - online = False; - ## Pull stats and add it to the stanza - for JID in list(self.nicks): - if self.nicks[JID] == player: - stats = self.leaderboard.getProfile(JID) - online = True - break - - if online == False: - stats = self.leaderboard.getProfile(player + "@" + str(recipient).split('@')[1]) - stz = ProfileXmppPlugin() - iq = self.Iq() - iq['type'] = 'result' - - stz.addItem(player, stats['rating'], stats['highestRating'], stats['rank'], stats['totalGamesPlayed'], stats['wins'], stats['losses']) - stz.addCommand(player) - stz.addRecipient(recipient) - iq.setPayload(stz) - ## Check recipient exists - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send profile to" % str(to)) - return - - ## Set additional IQ attributes - iq['to'] = to - - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - traceback.print_exc() - logging.error("Failed to send profile") - - def sendProfileNotFound(self, to, player, recipient): - """ - Send a profile not-found error to a specified target. - """ - stz = ProfileXmppPlugin() - iq = self.Iq() - iq['type'] = 'result' - - filler = str(0) - stz.addItem(player, str(-2), filler, filler, filler, filler, filler) - stz.addCommand(player) - stz.addRecipient(recipient) - iq.setPayload(stz) - ## Check recipient exists - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send profile to" % str(to)) - return - - ## Set additional IQ attributes - iq['to'] = to - - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - traceback.print_exc() - logging.error("Failed to send profile") - -## Main Program ## -if __name__ == '__main__': - # Setup the command line arguments. - optp = OptionParser() - - # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) - - # EcheLOn configuration options - optp.add_option('-m', '--domain', help='set EcheLOn domain', - action='store', dest='xdomain', - default="lobby.wildfiregames.com") - optp.add_option('-l', '--login', help='set EcheLOn login', - action='store', dest='xlogin', - default="EcheLOn") - optp.add_option('-p', '--password', help='set EcheLOn password', - action='store', dest='xpassword', - default="XXXXXX") - optp.add_option('-n', '--nickname', help='set EcheLOn nickname', - action='store', dest='xnickname', - default="Ratings") - optp.add_option('-r', '--room', help='set muc room to join', - action='store', dest='xroom', - default="arena") - - # ejabberd server options - optp.add_option('-s', '--server', help='address of the ejabberd server', - action='store', dest='xserver', - default="localhost") - optp.add_option('-t', '--disable-tls', help='Pass this argument to connect without TLS encryption', - action='store_true', dest='xdisabletls', - default=False) - - opts, args = optp.parse_args() - - # Setup logging. - logging.basicConfig(level=opts.loglevel, - format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') - - # EcheLOn - xmpp = EcheLOn(opts.xlogin+'@'+opts.xdomain+'/CC', opts.xpassword, opts.xroom+'@conference.'+opts.xdomain, opts.xnickname) - xmpp.register_plugin('xep_0030') # Service Discovery - xmpp.register_plugin('xep_0004') # Data Forms - xmpp.register_plugin('xep_0045') # Multi-User Chat # used - xmpp.register_plugin('xep_0060') # PubSub - xmpp.register_plugin('xep_0199') # XMPP Ping - - if xmpp.connect((opts.xserver, 5222), True, not opts.xdisabletls): - xmpp.process(threaded=False) - else: - logging.error("Unable to connect") Property changes on: ps/trunk/source/tools/XpartaMuPP/EcheLOn.py ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/ELO.py =================================================================== --- ps/trunk/source/tools/XpartaMuPP/ELO.py (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/ELO.py (nonexistent) @@ -1,90 +0,0 @@ -"""Copyright (C) 2014 Wildfire Games. - * This file is part of 0 A.D. - * - * 0 A.D. is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version. - * - * 0 A.D. is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with 0 A.D. If not, see . -""" - -############ Constants ############ -# Difference between two ratings such that it is -# regarded as a "sure win" for the higher player. -# No points are gained or lost for such a game. -elo_sure_win_difference = 600.0 - -# Lower ratings "move faster" and change more -# dramatically than higher ones. Anything rating above -# this value moves at the same rate as this value. -elo_k_factor_constant_rating = 2200.0 - -# This preset number of games is the number of games -# where a player is considered "stable". -# Rating volatility is constant after this number. -volatility_constant = 20.0 - -# Fair rating adjustment loses against inflation -# This constant will battle inflation. -# NOTE: This can be adjusted as needed by a -# bot/server administrator -anti_inflation = 0.015 - -############ Functions ############ -def get_rating_adjustment(rating, opponent_rating, games_played, opponent_games_played, result): - """ - Calculates the rating adjustment after a 1v1 game finishes using simplified ELO. - - Arguments: - rating, opponent_rating - Ratings of the players before this game. - games_played, opponent_games_played - Number of games each player has played - before this game. - result - 1 for the first player (rating, games_played) won, 0 for draw, or - -1 for the second player (opponent_rating, opponent_games_played) won. - - Returns: - The integer that should be subtracted from the loser's rating and added - to the winner's rating to get their new ratings. - - TODO: Team games. - """ - player_volatility = (min(games_played, volatility_constant) / volatility_constant + 0.25) / 1.25 - rating_k_factor = 50.0 * (min(rating, elo_k_factor_constant_rating) / elo_k_factor_constant_rating + 1.0) / 2.0 - volatility = rating_k_factor * player_volatility - difference = opponent_rating - rating - if result == 1: - return round(max(0, (difference + result * elo_sure_win_difference) / volatility - anti_inflation)) - elif result == -1: - return round(min(0, (difference + result * elo_sure_win_difference) / volatility - anti_inflation)) - else: - return round(difference / volatility - anti_inflation) - -# Inflation test - A slightly negative is better than a slightly positive -# Lower rated players stop playing more often than higher rated players -# Uncomment to test. -# In this example, two evenly matched players play for 150000 games. -""" -from random import randrange -r1start = 1600 -r2start = 1600 -r1 = r1start -r2 = r2start -for x in range(0, 150000): - res = randrange(3)-1 # How often one wins against the other - if res >= 1: - res = 1 - elif res <= -1: - res = -1 - r1gain = get_rating_adjustment(r1, r2, 20, 20, res) - r2gain = get_rating_adjustment(r2, r1, 20, 20, -1 * res) - r1 += r1gain - r2 += r2gain -print(str(r1) + " " + str(r2) + " : " + str(r1 + r2-r1start - r2start)) -""" Property changes on: ps/trunk/source/tools/XpartaMuPP/ELO.py ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/XpartaMuPP.py =================================================================== --- ps/trunk/source/tools/XpartaMuPP/XpartaMuPP.py (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/XpartaMuPP.py (nonexistent) @@ -1,663 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -"""Copyright (C) 2018 Wildfire Games. - * This file is part of 0 A.D. - * - * 0 A.D. is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version. - * - * 0 A.D. is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with 0 A.D. If not, see . -""" - -import logging, time, traceback -from optparse import OptionParser - -import sleekxmpp -from sleekxmpp.stanza import Iq -from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin, ET -from sleekxmpp.xmlstream.handler import Callback -from sleekxmpp.xmlstream.matcher import StanzaPath - -## Class to tracks all games in the lobby ## -class GameList(): - def __init__(self): - self.gameList = {} - def addGame(self, JID, data): - """ - Add a game - """ - data['players-init'] = data['players'] - data['nbp-init'] = data['nbp'] - data['state'] = 'init' - self.gameList[str(JID)] = data - def removeGame(self, JID): - """ - Remove a game attached to a JID - """ - del self.gameList[str(JID)] - def getAllGames(self): - """ - Returns all games - """ - return self.gameList - def changeGameState(self, JID, data): - """ - Switch game state between running and waiting - """ - JID = str(JID) - if JID in self.gameList: - if self.gameList[JID]['nbp-init'] > data['nbp']: - logging.debug("change game (%s) state from %s to %s", JID, self.gameList[JID]['state'], 'waiting') - self.gameList[JID]['state'] = 'waiting' - else: - logging.debug("change game (%s) state from %s to %s", JID, self.gameList[JID]['state'], 'running') - self.gameList[JID]['state'] = 'running' - self.gameList[JID]['nbp'] = data['nbp'] - self.gameList[JID]['players'] = data['players'] - if 'startTime' not in self.gameList[JID]: - self.gameList[JID]['startTime'] = str(round(time.time())) - -## Class for custom player stanza extension ## -class PlayerXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:player' - interfaces = set(('online')) - sub_interfaces = interfaces - plugin_attrib = 'player' - - def addPlayerOnline(self, player): - playerXml = ET.fromstring("%s" % player) - self.xml.append(playerXml) - -## Class for custom gamelist stanza extension ## -class GameListXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:gamelist' - interfaces = set(('game', 'command')) - sub_interfaces = interfaces - plugin_attrib = 'gamelist' - - def addGame(self, data): - itemXml = ET.Element("game", data) - self.xml.append(itemXml) - - def getGame(self): - """ - Required to parse incoming stanzas with this - extension. - """ - game = self.xml.find('{%s}game' % self.namespace) - data = {} - for key, item in game.items(): - data[key] = item - return data - -## Class for custom boardlist and ratinglist stanza extension ## -class BoardListXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:boardlist' - interfaces = set(('board', 'command', 'recipient')) - sub_interfaces = interfaces - plugin_attrib = 'boardlist' - def addCommand(self, command): - commandXml = ET.fromstring("%s" % command) - self.xml.append(commandXml) - def addRecipient(self, recipient): - recipientXml = ET.fromstring("%s" % recipient) - self.xml.append(recipientXml) - def addItem(self, name, rating): - itemXml = ET.Element("board", {"name": name, "rating": rating}) - self.xml.append(itemXml) - -## Class for custom gamereport stanza extension ## -class GameReportXmppPlugin(ElementBase): - name = 'report' - namespace = 'jabber:iq:gamereport' - plugin_attrib = 'gamereport' - interfaces = ('game', 'sender') - sub_interfaces = interfaces - def addSender(self, sender): - senderXml = ET.fromstring("%s" % sender) - self.xml.append(senderXml) - def addGame(self, gr): - game = ET.fromstring(str(gr)).find('{%s}game' % self.namespace) - self.xml.append(game) - def getGame(self): - """ - Required to parse incoming stanzas with this - extension. - """ - game = self.xml.find('{%s}game' % self.namespace) - data = {} - for key, item in game.items(): - data[key] = item - return data - -## Class for custom profile ## -class ProfileXmppPlugin(ElementBase): - name = 'query' - namespace = 'jabber:iq:profile' - interfaces = set(('profile', 'command', 'recipient')) - sub_interfaces = interfaces - plugin_attrib = 'profile' - def addCommand(self, command): - commandXml = ET.fromstring("%s" % command) - self.xml.append(commandXml) - def addRecipient(self, recipient): - recipientXml = ET.fromstring("%s" % recipient) - self.xml.append(recipientXml) - def addItem(self, player, rating, highestRating, rank, totalGamesPlayed, wins, losses): - itemXml = ET.Element("profile", {"player": player, "rating": rating, "highestRating": highestRating, - "rank" : rank, "totalGamesPlayed" : totalGamesPlayed, "wins" : wins, - "losses" : losses}) - self.xml.append(itemXml) - -## Main class which handles IQ data and sends new data ## -class XpartaMuPP(sleekxmpp.ClientXMPP): - """ - A simple list provider - """ - def __init__(self, sjid, password, room, nick, ratingsbot): - sleekxmpp.ClientXMPP.__init__(self, sjid, password) - self.sjid = sjid - self.room = room - self.nick = nick - self.ratingsBotWarned = False - - self.ratingsBot = ratingsbot - # Game collection - self.gameList = GameList() - - # Store mapping of nicks and XmppIDs, attached via presence stanza - self.nicks = {} - self.presences = {} # Obselete when XEP-0060 is implemented. - - self.lastLeft = "" - - register_stanza_plugin(Iq, PlayerXmppPlugin) - register_stanza_plugin(Iq, GameListXmppPlugin) - register_stanza_plugin(Iq, BoardListXmppPlugin) - register_stanza_plugin(Iq, GameReportXmppPlugin) - register_stanza_plugin(Iq, ProfileXmppPlugin) - - self.register_handler(Callback('Iq Player', - StanzaPath('iq/player'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq Gamelist', - StanzaPath('iq/gamelist'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq Boardlist', - StanzaPath('iq/boardlist'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq GameReport', - StanzaPath('iq/gamereport'), - self.iqhandler, - instream=True)) - self.register_handler(Callback('Iq Profile', - StanzaPath('iq/profile'), - self.iqhandler, - instream=True)) - - self.add_event_handler("session_start", self.start) - self.add_event_handler("muc::%s::got_online" % self.room, self.muc_online) - self.add_event_handler("muc::%s::got_offline" % self.room, self.muc_offline) - self.add_event_handler("groupchat_message", self.muc_message) - self.add_event_handler("changed_status", self.presence_change) - - def start(self, event): - """ - Process the session_start event - """ - self.plugin['xep_0045'].joinMUC(self.room, self.nick) - self.send_presence() - self.get_roster() - logging.info("XpartaMuPP started") - - def muc_online(self, presence): - """ - Process presence stanza from a chat room. - """ - if self.ratingsBot in self.nicks: - self.relayRatingListRequest(self.ratingsBot) - self.relayPlayerOnline(presence['muc']['jid']) - if presence['muc']['nick'] != self.nick: - # If it doesn't already exist, store player JID mapped to their nick. - if str(presence['muc']['jid']) not in self.nicks: - self.nicks[str(presence['muc']['jid'])] = presence['muc']['nick'] - self.presences[str(presence['muc']['jid'])] = "available" - # Check the jid isn't already in the lobby. - # Send Gamelist to new player. - self.sendGameList(presence['muc']['jid']) - logging.debug("Client '%s' connected with a nick of '%s'." %(presence['muc']['jid'], presence['muc']['nick'])) - - def muc_offline(self, presence): - """ - Process presence stanza from a chat room. - """ - # Clean up after a player leaves - if presence['muc']['nick'] != self.nick: - # Delete any games they were hosting. - for JID in self.gameList.getAllGames(): - if JID == str(presence['muc']['jid']): - self.gameList.removeGame(JID) - self.sendGameList() - break - # Remove them from the local player list. - self.lastLeft = str(presence['muc']['jid']) - if str(presence['muc']['jid']) in self.nicks: - del self.nicks[str(presence['muc']['jid'])] - del self.presences[str(presence['muc']['jid'])] - if presence['muc']['nick'] == self.ratingsBot: - self.ratingsBotWarned = False - - def muc_message(self, msg): - """ - Process new messages from the chatroom. - """ - if msg['mucnick'] != self.nick and self.nick.lower() in msg['body'].lower(): - self.send_message(mto=msg['from'].bare, - mbody="I am the administrative bot in this lobby and cannot participate in any games.", - mtype='groupchat') - - def presence_change(self, presence): - """ - Processes presence change - """ - prefix = "%s/" % self.room - nick = str(presence['from']).replace(prefix, "") - for JID in self.nicks: - if self.nicks[JID] == nick: - if self.presences[JID] == 'dnd' and (str(presence['type']) == "available" or str(presence['type']) == "away"): - self.sendGameList(JID) - self.relayBoardListRequest(JID) - self.presences[JID] = str(presence['type']) - break - - - def iqhandler(self, iq): - """ - Handle the custom stanzas - This method should be very robust because we could receive anything - """ - if iq['type'] == 'error': - logging.error('iqhandler error' + iq['error']['condition']) - #self.disconnect() - elif iq['type'] == 'get': - """ - Request lists. - """ - # Send lists/register on leaderboard; depreciated once muc_online - # can send lists/register automatically on joining the room. - if 'boardlist' in iq.loaded_plugins: - command = iq['boardlist']['command'] - try: - self.relayBoardListRequest(iq['from']) - except: - traceback.print_exc() - logging.error("Failed to process leaderboardlist request from %s" % iq['from'].bare) - elif 'profile' in iq.loaded_plugins: - command = iq['profile']['command'] - try: - self.relayProfileRequest(iq['from'], command) - except: - pass - else: - logging.error("Unknown 'get' type stanza request from %s" % iq['from'].bare) - elif iq['type'] == 'result': - """ - Iq successfully received - """ - if 'boardlist' in iq.loaded_plugins: - recipient = iq['boardlist']['recipient'] - self.relayBoardList(iq['boardlist'], recipient) - elif 'profile' in iq.loaded_plugins: - recipient = iq['profile']['recipient'] - player = iq['profile']['command'] - self.relayProfile(iq['profile'], player, recipient) - else: - pass - elif iq['type'] == 'set': - if 'gamelist' in iq.loaded_plugins: - """ - Register-update / unregister a game - """ - command = iq['gamelist']['command'] - if command == 'register': - # Add game - try: - if iq['from'] in self.nicks: - self.gameList.addGame(iq['from'], iq['gamelist']['game']) - self.sendGameList() - except: - traceback.print_exc() - logging.error("Failed to process game registration data") - elif command == 'unregister': - # Remove game - try: - self.gameList.removeGame(iq['from']) - self.sendGameList() - except: - traceback.print_exc() - logging.error("Failed to process game unregistration data") - - elif command == 'changestate': - # Change game status (waiting/running) - try: - self.gameList.changeGameState(iq['from'], iq['gamelist']['game']) - self.sendGameList() - except: - traceback.print_exc() - logging.error("Failed to process changestate data. Trying to add game") - try: - if iq['from'] in self.nicks: - self.gameList.addGame(iq['from'], iq['gamelist']['game']) - self.sendGameList() - except: - pass - else: - logging.error("Failed to process command '%s' received from %s" % command, iq['from'].bare) - elif 'gamereport' in iq.loaded_plugins: - """ - Client is reporting end of game statistics - """ - try: - self.relayGameReport(iq['gamereport'], iq['from']) - except: - traceback.print_exc() - logging.error("Failed to update game statistics for %s" % iq['from'].bare) - else: - logging.error("Failed to process stanza type '%s' received from %s" % iq['type'], iq['from'].bare) - - def sendGameList(self, to = ""): - """ - Send a massive stanza with the whole game list. - If no target is passed the gamelist is broadcasted - to all clients. - """ - games = self.gameList.getAllGames() - - stz = GameListXmppPlugin() - - ## Pull games and add each to the stanza - for JIDs in games: - g = games[JIDs] - stz.addGame(g) - - ## Set additional IQ attributes - iq = self.Iq() - iq['type'] = 'result' - iq.setPayload(stz) - if to == "": - for JID in list(self.presences): - if self.presences[JID] != "available" and self.presences[JID] != "away": - continue - iq['to'] = JID - - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send game list") - else: - ## Check recipient exists - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send gamelist to." % str(to)) - return - iq['to'] = to - - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send game list") - - def relayBoardListRequest(self, recipient): - """ - Send a boardListRequest to EcheLOn. - """ - to = self.ratingsBot - if to not in self.nicks: - self.warnRatingsBotOffline() - return - stz = BoardListXmppPlugin() - iq = self.Iq() - iq['type'] = 'get' - stz.addCommand('getleaderboard') - stz.addRecipient(recipient) - iq.setPayload(stz) - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send leaderboard list request") - - def relayRatingListRequest(self, recipient): - """ - Send a ratingListRequest to EcheLOn. - """ - to = self.ratingsBot - if to not in self.nicks: - self.warnRatingsBotOffline() - return - stz = BoardListXmppPlugin() - iq = self.Iq() - iq['type'] = 'get' - stz.addCommand('getratinglist') - iq.setPayload(stz) - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send rating list request") - - def relayProfileRequest(self, recipient, player): - """ - Send a profileRequest to EcheLOn. - """ - to = self.ratingsBot - if to not in self.nicks: - self.warnRatingsBotOffline() - return - stz = ProfileXmppPlugin() - iq = self.Iq() - iq['type'] = 'get' - stz.addCommand(player) - stz.addRecipient(recipient) - iq.setPayload(stz) - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send profile request") - - def relayPlayerOnline(self, jid): - """ - Tells EcheLOn that someone comes online. - """ - ## Check recipient exists - to = self.ratingsBot - if to not in self.nicks: - return - stz = PlayerXmppPlugin() - iq = self.Iq() - iq['type'] = 'set' - stz.addPlayerOnline(jid) - iq.setPayload(stz) - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send player muc online") - - def relayGameReport(self, data, sender): - """ - Relay a game report to EcheLOn. - """ - to = self.ratingsBot - if to not in self.nicks: - self.warnRatingsBotOffline() - return - stz = GameReportXmppPlugin() - stz.addGame(data) - stz.addSender(sender) - iq = self.Iq() - iq['type'] = 'set' - iq.setPayload(stz) - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send game report request") - - def relayBoardList(self, boardList, to = ""): - """ - Send the whole leaderboard list. - If no target is passed the boardlist is broadcasted - to all clients. - """ - iq = self.Iq() - iq['type'] = 'result' - iq.setPayload(boardList) - ## Check recipient exists - if to == "": - # Rating List - for JID in list(self.presences): - if self.presences[JID] != "available" and self.presences[JID] != "away": - continue - ## Set additional IQ attributes - iq['to'] = JID - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send rating list") - else: - # Leaderboard or targeted rating list - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send boardlist to" % str(to)) - return - ## Set additional IQ attributes - iq['to'] = to - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - logging.error("Failed to send leaderboard list") - - def relayProfile(self, data, player, to): - """ - Send the player profile to a specified target. - """ - if to == "": - logging.error("Failed to send profile, target unspecified") - return - - iq = self.Iq() - iq['type'] = 'result' - iq.setPayload(data) - ## Check recipient exists - if str(to) not in self.nicks: - logging.error("No player with the XmPP ID '%s' known to send profile to" % str(to)) - return - - ## Set additional IQ attributes - iq['to'] = to - - ## Try sending the stanza - try: - iq.send(block=False, now=True) - except: - traceback.print_exc() - logging.error("Failed to send profile") - - def warnRatingsBotOffline(self): - """ - Warns that the ratings bot is offline. - """ - if not self.ratingsBotWarned: - logging.warn("Ratings bot '%s' is offline" % str(self.ratingsBot)) - self.ratingsBotWarned = True - -## Main Program ## -if __name__ == '__main__': - # Setup the command line arguments. - optp = OptionParser() - - # Output verbosity options. - optp.add_option('-q', '--quiet', help='set logging to ERROR', - action='store_const', dest='loglevel', - const=logging.ERROR, default=logging.INFO) - optp.add_option('-d', '--debug', help='set logging to DEBUG', - action='store_const', dest='loglevel', - const=logging.DEBUG, default=logging.INFO) - optp.add_option('-v', '--verbose', help='set logging to COMM', - action='store_const', dest='loglevel', - const=5, default=logging.INFO) - - # XpartaMuPP configuration options - optp.add_option('-m', '--domain', help='set xpartamupp domain', - action='store', dest='xdomain', - default="lobby.wildfiregames.com") - optp.add_option('-l', '--login', help='set xpartamupp login', - action='store', dest='xlogin', - default="xpartamupp") - optp.add_option('-p', '--password', help='set xpartamupp password', - action='store', dest='xpassword', - default="XXXXXX") - optp.add_option('-n', '--nickname', help='set xpartamupp nickname', - action='store', dest='xnickname', - default="WFGbot") - optp.add_option('-r', '--room', help='set muc room to join', - action='store', dest='xroom', - default="arena") - optp.add_option('-e', '--elo', help='set rating bot username', - action='store', dest='xratingsbot', - default="disabled") - - # ejabberd server options - optp.add_option('-s', '--server', help='address of the ejabberd server', - action='store', dest='xserver', - default="localhost") - optp.add_option('-t', '--disable-tls', help='Pass this argument to connect without TLS encryption', - action='store_true', dest='xdisabletls', - default=False) - - opts, args = optp.parse_args() - - # Setup logging. - logging.basicConfig(level=opts.loglevel, - format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') - - # XpartaMuPP - xmpp = XpartaMuPP(opts.xlogin+'@'+opts.xdomain+'/CC', opts.xpassword, opts.xroom+'@conference.'+opts.xdomain, opts.xnickname, opts.xratingsbot+'@'+opts.xdomain+'/CC') - xmpp.register_plugin('xep_0030') # Service Discovery - xmpp.register_plugin('xep_0004') # Data Forms - xmpp.register_plugin('xep_0045') # Multi-User Chat # used - xmpp.register_plugin('xep_0060') # PubSub - xmpp.register_plugin('xep_0199') # XMPP Ping - - if xmpp.connect((opts.xserver, 5222), True, not opts.xdisabletls): - xmpp.process(threaded=False) - else: - logging.error("Unable to connect") Property changes on: ps/trunk/source/tools/XpartaMuPP/XpartaMuPP.py ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/LobbyRanking.py =================================================================== --- ps/trunk/source/tools/XpartaMuPP/LobbyRanking.py (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/LobbyRanking.py (nonexistent) @@ -1,140 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -"""Copyright (C) 2013 Wildfire Games. - * This file is part of 0 A.D. - * - * 0 A.D. is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version. - * - * 0 A.D. is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with 0 A.D. If not, see . -""" - -import sqlalchemy -from sqlalchemy import Column, ForeignKey, Integer, String, Boolean -from sqlalchemy.orm import relationship, sessionmaker -from sqlalchemy.ext.declarative import declarative_base - -engine = sqlalchemy.create_engine('sqlite:///lobby_rankings.sqlite3') -Session = sessionmaker(bind=engine) -session = Session() -Base = declarative_base() - -class Player(Base): - __tablename__ = 'players' - - id = Column(Integer, primary_key=True) - jid = Column(String(255)) - rating = Column(Integer) - highest_rating = Column(Integer) - games = relationship('Game', secondary='players_info') - # These two relations really only exist to satisfy the linkage - # between PlayerInfo and Player and Game and player. - games_info = relationship('PlayerInfo', backref='player') - games_won = relationship('Game', backref='winner') - -class PlayerInfo(Base): - __tablename__ = 'players_info' - - id = Column(Integer, primary_key=True) - player_id = Column(Integer, ForeignKey('players.id')) - game_id = Column(Integer, ForeignKey('games.id')) - civs = Column(String(20)) - teams = Column(Integer) - economyScore = Column(Integer) - militaryScore = Column(Integer) - totalScore = Column(Integer) - foodGathered = Column(Integer) - foodUsed = Column(Integer) - woodGathered = Column(Integer) - woodUsed = Column(Integer) - stoneGathered = Column(Integer) - stoneUsed = Column(Integer) - metalGathered = Column(Integer) - metalUsed = Column(Integer) - vegetarianFoodGathered = Column(Integer) - treasuresCollected = Column(Integer) - lootCollected = Column(Integer) - tributesSent = Column(Integer) - tributesReceived = Column(Integer) - totalUnitsTrained = Column(Integer) - totalUnitsLost = Column(Integer) - enemytotalUnitsKilled = Column(Integer) - infantryUnitsTrained = Column(Integer) - infantryUnitsLost = Column(Integer) - enemyInfantryUnitsKilled = Column(Integer) - workerUnitsTrained = Column(Integer) - workerUnitsLost = Column(Integer) - enemyWorkerUnitsKilled = Column(Integer) - femaleCitizenUnitsTrained = Column(Integer) - femaleCitizenUnitsLost = Column(Integer) - enemyFemaleCitizenUnitsKilled = Column(Integer) - cavalryUnitsTrained = Column(Integer) - cavalryUnitsLost = Column(Integer) - enemyCavalryUnitsKilled = Column(Integer) - championUnitsTrained = Column(Integer) - championUnitsLost = Column(Integer) - enemyChampionUnitsKilled = Column(Integer) - heroUnitsTrained = Column(Integer) - heroUnitsLost = Column(Integer) - enemyHeroUnitsKilled = Column(Integer) - shipUnitsTrained = Column(Integer) - shipUnitsLost = Column(Integer) - enemyShipUnitsKilled = Column(Integer) - traderUnitsTrained = Column(Integer) - traderUnitsLost = Column(Integer) - enemyTraderUnitsKilled = Column(Integer) - totalBuildingsConstructed = Column(Integer) - totalBuildingsLost = Column(Integer) - enemytotalBuildingsDestroyed = Column(Integer) - civCentreBuildingsConstructed = Column(Integer) - civCentreBuildingsLost = Column(Integer) - enemyCivCentreBuildingsDestroyed = Column(Integer) - houseBuildingsConstructed = Column(Integer) - houseBuildingsLost = Column(Integer) - enemyHouseBuildingsDestroyed = Column(Integer) - economicBuildingsConstructed = Column(Integer) - economicBuildingsLost = Column(Integer) - enemyEconomicBuildingsDestroyed = Column(Integer) - outpostBuildingsConstructed = Column(Integer) - outpostBuildingsLost = Column(Integer) - enemyOutpostBuildingsDestroyed = Column(Integer) - militaryBuildingsConstructed = Column(Integer) - militaryBuildingsLost = Column(Integer) - enemyMilitaryBuildingsDestroyed = Column(Integer) - fortressBuildingsConstructed = Column(Integer) - fortressBuildingsLost = Column(Integer) - enemyFortressBuildingsDestroyed = Column(Integer) - wonderBuildingsConstructed = Column(Integer) - wonderBuildingsLost = Column(Integer) - enemyWonderBuildingsDestroyed = Column(Integer) - woodBought = Column(Integer) - foodBought = Column(Integer) - stoneBought = Column(Integer) - metalBought = Column(Integer) - tradeIncome = Column(Integer) - percentMapExplored = Column(Integer) - -class Game(Base): - __tablename__ = 'games' - - id = Column(Integer, primary_key=True) - map = Column(String(80)) - duration = Column(Integer) - teamsLocked = Column(Boolean) - matchID = Column(String(20)) - winner_id = Column(Integer, ForeignKey('players.id')) - player_info = relationship('PlayerInfo', backref='game') - players = relationship('Player', secondary='players_info') - - -if __name__ == '__main__': - Base.metadata.create_all(engine) - Property changes on: ps/trunk/source/tools/XpartaMuPP/LobbyRanking.py ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/ejabberd_example.yml =================================================================== --- ps/trunk/source/tools/XpartaMuPP/ejabberd_example.yml (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/ejabberd_example.yml (nonexistent) @@ -1,855 +0,0 @@ -### -###' ejabberd configuration file -### -### - -### The parameters used in this configuration file are explained in more detail -### in the ejabberd Installation and Operation Guide. -### Please consult the Guide in case of doubts, it is included with -### your copy of ejabberd, and is also available online at -### http://www.process-one.net/en/ejabberd/docs/ - -### The configuration file is written in YAML. -### Refer to http://en.wikipedia.org/wiki/YAML for the brief description. -### However, ejabberd treats different literals as different types: -### -### - unquoted or single-quoted strings. They are called "atoms". -### Example: dog, 'Jupiter', '3.14159', YELLOW -### -### - numeric literals. Example: 3, -45.0, .0 -### -### - quoted or folded strings. -### Examples of quoted string: "Lizzard", "orange". -### Example of folded string: -### > Art thou not Romeo, -### and a Montague? ---- -###. ======= -###' LOGGING - -## -## loglevel: Verbosity of log files generated by ejabberd. -## 0: No ejabberd log at all (not recommended) -## 1: Critical -## 2: Error -## 3: Warning -## 4: Info -## 5: Debug -## -loglevel: 4 - -## -## rotation: Disable ejabberd's internal log rotation, as the Debian package -## uses logrotate(8). -log_rotate_size: 0 -log_rotate_date: "" - -## -## overload protection: If you want to limit the number of messages per second -## allowed from error_logger, which is a good idea if you want to avoid a flood -## of messages when system is overloaded, you can set a limit. -## 100 is ejabberd's default. -log_rate_limit: 100 - -## -## watchdog_admins: Only useful for developers: if an ejabberd process -## consumes a lot of memory, send live notifications to these XMPP -## accounts. -## -## watchdog_admins: -## - "bob@example.com" - -###. =============== -###' NODE PARAMETERS - -## -## net_ticktime: Specifies net_kernel tick time in seconds. This options must have -## identical value on all nodes, and in most cases shouldn't be changed at all from -## default value. -## -## net_ticktime: 60 - -###. ================ -###' SERVED HOSTNAMES - -## -## hosts: Domains served by ejabberd. -## You can define one or several, for example: -## hosts: -## - "example.net" -## - "example.com" -## - "example.org" -## -hosts: - - "localhost" - -## -## route_subdomains: Delegate subdomains to other XMPP servers. -## For example, if this ejabberd serves example.org and you want -## to allow communication with an XMPP server called im.example.org. -## -## route_subdomains: s2s - -###. ============ -###' Certificates - -## List all available PEM files containing certificates for your domains, -## chains of certificates or certificate keys. Full chains will be built -## automatically by ejabberd. -## -certfiles: - - "/etc/ejabberd/ejabberd.pem" - -## If your system provides only a single CA file (CentOS/FreeBSD): -## ca_file: "/etc/ssl/certs/ca-bundle.pem" - -###. ================= -###' TLS configuration - -## Note that the following configuration is the default -## configuration of the TLS driver, so you don't need to -## uncomment it. -## -define_macro: - 'TLS_CIPHERS': "HIGH:!aNULL:!eNULL:!3DES:@STRENGTH" - 'TLS_OPTIONS': - - "no_sslv2" - - "no_sslv3" - - "no_tlsv1" - - "cipher_server_preference" - - "no_compression" - ## 'DH_FILE': "/path/to/dhparams.pem" # generated with: openssl dhparam -out dhparams.pem 2048 - -## c2s_dhfile: 'DH_FILE' -## s2s_dhfile: 'DH_FILE' -c2s_ciphers: 'TLS_CIPHERS' -s2s_ciphers: 'TLS_CIPHERS' -c2s_protocol_options: 'TLS_OPTIONS' -s2s_protocol_options: 'TLS_OPTIONS' - -###. =============== -###' LISTENING PORTS - -## -## listen: The ports ejabberd will listen on, which service each is handled -## by and what options to start it with. -## -listen: - - - port: 5222 - ip: "0.0.0.0" - module: ejabberd_c2s - starttls: true - starttls_required: false - protocol_options: 'TLS_OPTIONS' - max_stanza_size: 1048576 - shaper: c2s_shaper - access: c2s - - ## port: 5269 - ## ip: "::" - ## module: ejabberd_s2s_in - - - - port: 5280 - ip: "127.0.0.1" - module: ejabberd_http - request_handlers: - "/ws": ejabberd_http_ws - "/bosh": mod_bosh - "/api": mod_http_api - ## "/pub/archive": mod_http_fileserver - web_admin: true - ## register: true - ## captcha: true - tls: true - protocol_options: 'TLS_OPTIONS' - - ## - ## ejabberd_service: Interact with external components (transports, ...) - ## - ## - - ## port: 8888 - ## ip: "::" - ## module: ejabberd_service - ## access: all - ## shaper_rule: fast - ## ip: "127.0.0.1" - ## privilege_access: - ## roster: "both" - ## message: "outgoing" - ## presence: "roster" - ## delegations: - ## "urn:xmpp:mam:1": - ## filtering: ["node"] - ## "http://jabber.org/protocol/pubsub": - ## filtering: [] - ## hosts: - ## "icq.example.org": - ## password: "secret" - ## "sms.example.org": - ## password: "secret" - - ## - ## ejabberd_stun: Handles STUN Binding requests - ## - - - port: 3478 - transport: udp - module: ejabberd_stun - - ## - ## To handle XML-RPC requests that provide admin credentials: - ## - ## - - ## port: 4560 - ## ip: "::" - ## module: ejabberd_xmlrpc - ## maxsessions: 10 - ## timeout: 5000 - ## access_commands: - ## admin: - ## commands: all - ## options: [] - - ## - ## To enable secure http upload - ## - ## - - ## port: 5444 - ## ip: "::" - ## module: ejabberd_http - ## request_handlers: - ## "": mod_http_upload - ## tls: true - ## protocol_options: 'TLS_OPTIONS' - ## dhfile: 'DH_FILE' - ## ciphers: 'TLS_CIPHERS' - -## Disabling digest-md5 SASL authentication. digest-md5 requires plain-text -## password storage (see auth_password_format option). -disable_sasl_mechanisms: "digest-md5" - -###. ================== -###' S2S GLOBAL OPTIONS - -## -## s2s_use_starttls: Enable STARTTLS for S2S connections. -## Allowed values are: false, optional or required -## You must specify 'certfiles' option -## -s2s_use_starttls: required - -## -## S2S whitelist or blacklist -## -## Default s2s policy for undefined hosts. -## -## s2s_access: s2s - -## -## Outgoing S2S options -## -## Preferred address families (which to try first) and connect timeout -## in seconds. -## -## outgoing_s2s_families: -## - ipv4 -## - ipv6 -## outgoing_s2s_timeout: 190 - -###. ============== -###' AUTHENTICATION - -## -## auth_method: Method used to authenticate the users. -## The default method is the internal. -## If you want to use a different method, -## comment this line and enable the correct ones. -## -auth_method: internal - -## -## Store the plain passwords or hashed for SCRAM: -## auth_password_format: plain -auth_password_format: scram -## -## Define the FQDN if ejabberd doesn't detect it: -## fqdn: "server3.example.com" - -## -## Authentication using external script -## Make sure the script is executable by ejabberd. -## -## auth_method: external -## extauth_program: "/path/to/authentication/script" - -## -## Authentication using SQL -## Remember to setup a database in the next section. -## -## auth_method: sql - -## -## Authentication using PAM -## -## auth_method: pam -## pam_service: "pamservicename" - -## -## Authentication using LDAP -## -## auth_method: ldap -## -## List of LDAP servers: -## ldap_servers: -## - "lw" -## -## Encryption of connection to LDAP servers: -## ldap_encrypt: none -## ldap_encrypt: tls -## -## Port to connect to on LDAP servers: -## ldap_port: 389 -## ldap_port: 636 -## -## LDAP manager: -## ldap_rootdn: "dc=example,dc=com" -## -## Password of LDAP manager: -## ldap_password: "******" -## -## Search base of LDAP directory: -## ldap_base: "dc=example,dc=com" -## -## LDAP attribute that holds user ID: -## ldap_uids: -## - "mail": "%u@mail.example.org" -## -## LDAP filter: -## ldap_filter: "(objectClass=shadowAccount)" - -## -## Anonymous login support: -## auth_method: anonymous -## anonymous_protocol: sasl_anon | login_anon | both -## allow_multiple_connections: true | false -## -## host_config: -## "public.example.org": -## auth_method: anonymous -## allow_multiple_connections: false -## anonymous_protocol: sasl_anon -## -## To use both anonymous and internal authentication: -## -## host_config: -## "public.example.org": -## auth_method: -## - internal -## - anonymous - -###. ============== -###' DATABASE SETUP - -## ejabberd by default uses the internal Mnesia database, -## so you do not necessarily need this section. -## This section provides configuration examples in case -## you want to use other database backends. -## Please consult the ejabberd Guide for details on database creation. - -## -## MySQL server: -## -## sql_type: mysql -## sql_server: "server" -## sql_database: "database" -## sql_username: "username" -## sql_password: "password" -## -## If you want to specify the port: -## sql_port: 1234 - -## -## PostgreSQL server: -## -## sql_type: pgsql -## sql_server: "server" -## sql_database: "database" -## sql_username: "username" -## sql_password: "password" -## -## If you want to specify the port: -## sql_port: 1234 -## -## If you use PostgreSQL, have a large database, and need a -## faster but inexact replacement for "select count(*) from users" -## -## pgsql_users_number_estimate: true - -## -## SQLite: -## -## sql_type: sqlite -## sql_database: "/path/to/database.db" - -## -## ODBC compatible or MSSQL server: -## -## sql_type: odbc -## sql_server: "DSN=ejabberd;UID=ejabberd;PWD=ejabberd" - -## -## Number of connections to open to the database for each virtual host -## -## sql_pool_size: 10 - -## -## Interval to make a dummy SQL request to keep the connections to the -## database alive. Specify in seconds: for example 28800 means 8 hours -## -## sql_keepalive_interval: undefined - -###. =============== -###' TRAFFIC SHAPERS - -shaper: - ## - ## The "normal" shaper limits traffic speed to 1000 B/s - ## - normal: 1000 - - ## - ## The "fast" shaper limits traffic speed to 50000 B/s - ## - fast: 50000 - -## -## This option specifies the maximum number of elements in the queue -## of the FSM. Refer to the documentation for details. -## -max_fsm_queue: 10000 - -###. ==================== -###' ACCESS CONTROL LISTS -acl: - ## - ## The 'admin' ACL grants administrative privileges to XMPP accounts. - ## You can put here as many accounts as you want. - ## - admin: - user: - - "admin@localhost" - - ## Don't use a regex, to prevent others from obtaining permissions after registering such an account. - bots: - - user: "echelon23@localhost" - - user: "wfgbot23@localhost" - - # Keep playernames short and easily typeable for everyone - validname: - user_regexp: "^[0-9A-Za-z._-]{1,20}$" - - ## - ## Blocked users - ## - ## blocked: - ## user: - ## - "baduser@example.org" - ## - "test" - - ## Local users: don't modify this. - ## - local: - user_regexp: "" - - ## - ## More examples of ACLs - ## - ## jabberorg: - ## server: - ## - "jabber.org" - ## aleksey: - ## user: - ## - "aleksey@jabber.ru" - ## test: - ## user_regexp: "^test" - ## user_glob: "test*" - - ## - ## Loopback network - ## - loopback: - ip: - - "127.0.0.0/8" - - "::1/128" - - "::FFFF:127.0.0.1/128" - - ## - ## Bad XMPP servers - ## - ## bad_servers: - ## server: - ## - "xmpp.zombie.org" - ## - "xmpp.spam.com" - -## -## Define specific ACLs in a virtual host. -## -## host_config: -## "localhost": -## acl: -## admin: -## user: -## - "bob-local@localhost" - -###. ============ -###' SHAPER RULES - -shaper_rules: - ## Maximum number of simultaneous sessions allowed for a single user: - max_user_sessions: 10 - ## Maximum number of offline messages that users can have: - max_user_offline_messages: - - 5000: admin - - 100 - ## For C2S connections, all users except admins use the "normal" shaper - c2s_shaper: - - none: admin - - none: bots - - normal - ## All S2S connections use the "fast" shaper - s2s_shaper: fast - -###. ============ -###' ACCESS RULES -access_rules: - ## This rule allows access only for local users: - local: - - allow: local - ## Only non-blocked users can use c2s connections: - c2s: - - deny: blocked - - allow - ## Only admins can send announcement messages: - announce: - - allow: admin - ## Only admins can use the configuration interface: - configure: - - allow: admin - ## Expected by the ipstamp module for XpartaMuPP - ipbots: - - allow: bots - muc_admin: - - allow: admin - ## Bots must be able to create nodes for games, ratings and boards lists - pubsub_createnode: - - allow: admin - - allow: bots - ## In-band registration allows registration of any possible username. - ## To disable in-band registration, replace 'allow' with 'deny'. - register: - - deny: blocked - - allow: validname - ## Only allow to register from localhost - trusted_network: - - allow: loopback - ## Do not establish S2S connections with bad servers - ## If you enable this you also have to uncomment "s2s_access: s2s" - ## s2s: - ## - deny: - ## - ip: "XXX.XXX.XXX.XXX/32" - ## - deny: - ## - ip: "XXX.XXX.XXX.XXX/32" - ## - allow - -## =============== -## API PERMISSIONS -## =============== -## -## This section allows you to define who and using what method -## can execute commands offered by ejabberd. -## -## By default "console commands" section allow executing all commands -## issued using ejabberdctl command, and "admin access" section allows -## users in admin acl that connect from 127.0.0.1 to execute all -## commands except start and stop with any available access method -## (ejabberdctl, http-api, xmlrpc depending what is enabled on server). -## -## If you remove "console commands" there will be one added by -## default allowing executing all commands, but if you just change -## permissions in it, version from config file will be used instead -## of default one. -## -api_permissions: - "console commands": - from: - - ejabberd_ctl - who: all - what: "*" - "admin access": - who: - - access: - - allow: - - acl: loopback - - acl: admin - - oauth: - - scope: "ejabberd:admin" - - access: - - allow: - - acl: loopback - - acl: admin - what: - - "*" - - "!stop" - - "!start" - "public commands": - who: - - ip: "127.0.0.1/8" - what: - - "status" - - "connected_users_number" - -## By default the frequency of account registrations from the same IP -## is limited to 1 account every 10 minutes. To disable, specify: infinity -registration_timeout: 3600 - -## -## Define specific Access Rules in a virtual host. -## -## host_config: -## "localhost": -## access: -## c2s: -## - allow: admin -## - deny -## register: -## - deny - -###. ================ -###' DEFAULT LANGUAGE - -## -## language: Default language used for server messages. -## -language: "en" - -## -## Set a different default language in a virtual host. -## -## host_config: -## "localhost": -## language: "ru" - -###. ======= -###' CAPTCHA - -## -## Full path to a script that generates the image. -## -## captcha_cmd: "/usr/share/ejabberd/captcha.sh" - -## -## Host for the URL and port where ejabberd listens for CAPTCHA requests. -## -## captcha_host: "example.org:5280" - -## -## Limit CAPTCHA calls per minute for JID/IP to avoid DoS. -## -## captcha_limit: 5 - -###. ==== -###' ACME -## -## In order to use the acme certificate acquiring through "Let's Encrypt" -## an http listener has to be configured to listen to port 80 so that -## the authorization challenges posed by "Let's Encrypt" can be solved. -## -## A simple way of doing this would be to add the following in the listening -## section and to configure port forwarding from 80 to 5281 either via NAT -## (for ipv4 only) or using frontends such as haproxy/nginx/sslh/etc. -## - -## port: 5281 -## ip: "::" -## module: ejabberd_http - -acme: - - ## A contact mail that the ACME Certificate Authority can contact in case of - ## an authorization issue, such as a server-initiated certificate revocation. - ## It is not mandatory to provide an email address but it is highly suggested. - contact: "mailto:example-admin@example.com" - - - ## The ACME Certificate Authority URL. - ## This could either be: - ## - https://acme-v01.api.letsencrypt.org - (Default) for the production CA - ## - https://acme-staging.api.letsencrypt.org - for the staging CA - ## - http://localhost:4000 - for a local version of the CA - ca_url: "https://acme-v01.api.letsencrypt.org" - -###. ======= -###' MODULES - -## -## Modules enabled in all ejabberd virtual hosts. -## -modules: - mod_adhoc: {} - mod_admin_extra: {} - mod_announce: # recommends mod_adhoc - access: announce - mod_blocking: {} # requires mod_privacy - mod_caps: {} - mod_carboncopy: {} - mod_client_state: {} - mod_configure: {} # requires mod_adhoc - ## mod_delegation: {} # for xep0356 - mod_disco: {} - ## mod_echo: {} - ## ipstamp module used by XpartaMuPP to insert IP addresses into the gamelist - mod_ipstamp: {} - ## mod_irc: {} - mod_bosh: {} - ## mod_http_fileserver: - ## docroot: "/var/www" - ## accesslog: "/var/log/ejabberd/access.log" - ## mod_http_upload: - ## # docroot: "@HOME@/upload" - ## put_url: "https://@HOST@:5444" - ## thumbnail: false # otherwise needs the identify command from ImageMagick installed - ## mod_http_upload_quota: - ## max_days: 30 - mod_last: {} - ## XEP-0313: Message Archive Management - ## You might want to setup a SQL backend for MAM because the mnesia database is - ## limited to 2GB which might be exceeded on large servers - ## mod_mam: {} # for xep0313, mnesia is limited to 2GB, better use an SQL backend - mod_muc: - ## host: "conference.@HOST@" - access: - - allow - access_admin: muc_admin - access_create: muc_admin - access_persistent: muc_admin - max_users: 5000 - default_room_options: - allow_change_subj: false - logging: true - max_users: 1000 - persistent: true - mod_muc_admin: {} - mod_muc_log: - outdir: "/lobby/logs" - dirtype: plain - file_format: plaintext - timezone: universal - ## mod_multicast: {} - mod_offline: - access_max_user_messages: max_user_offline_messages - mod_ping: - send_pings: true - ## mod_pres_counter: - ## count: 5 - ## interval: 60 - mod_privacy: {} - mod_private: {} - ## mod_proxy65: {} - mod_pubsub: - access_createnode: pubsub_createnode - ## reduces resource comsumption, but XEP incompliant - ignore_pep_from_offline: true - ## XEP compliant, but increases resource comsumption - ## ignore_pep_from_offline: false - last_item_cache: false - plugins: - - "flat" - - "hometree" - - "pep" # pep requires mod_caps - mod_push: {} - mod_push_keepalive: {} - mod_register: - ## - ## Protect In-Band account registrations with CAPTCHA. - ## - ## captcha_protected: true - ## - ## Set the minimum informational entropy for passwords. - ## - ## password_strength: 32 - ## - ## After successful registration, the user receives - ## a message with this subject and body. - ## - ## welcome_message: - ## subject: "Welcome!" - ## body: |- - ## Hi. - ## Welcome to this XMPP server. - ## - ## When a user registers, send a notification to - ## these XMPP accounts. - ## - ## registration_watchers: - ## - "admin1@example.org" - ## - ## Only clients in the server machine can register accounts - ## - ## ip_access: trusted_network - ## - ## Local c2s or remote s2s users cannot register accounts - ## - ## access_from: deny - access: register - mod_roster: - versioning: true - ## mod_shared_roster: {} - mod_stats: {} - mod_time: {} - ## mod_vcard: - ## search: false - ## mod_vcard_xupdate: {} - ## Convert all avatars posted by Android clients from WebP to JPEG - ## mod_avatar: # this module needs compile option --enable-graphics - ## convert: - ## webp: jpeg - mod_version: {} - mod_stream_mgmt: - resend_on_timeout: if_offline - ## Non-SASL Authentication (XEP-0078) is now disabled by default - ## because it's obsoleted and is used mostly by abandoned - ## client software - ## mod_legacy_auth: {} - ## The module for S2S dialback (XEP-0220). Please note that you cannot - ## rely solely on dialback if you want to federate with other servers, - ## because a lot of servers have dialback disabled and instead rely on - ## PKIX authentication. Make sure you have proper certificates installed - ## and check your accessibility at https://check.messaging.one/ - mod_s2s_dialback: {} - mod_http_api: {} - -## -## Enable modules with custom options in a specific virtual host -## -## host_config: -## "localhost": -## modules: -## mod_echo: -## host: "mirror.localhost" - -## -## Enable modules management via ejabberdctl for installation and -## uninstallation of public/private contributed modules -## (enabled by default) -## - -allow_contrib_modules: true - -###. -###' -### Local Variables: -### mode: yaml -### End: -### vim: set filetype=yaml tabstop=8 foldmarker=###',###. foldmethod=marker: - Property changes on: ps/trunk/source/tools/XpartaMuPP/ejabberd_example.yml ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/README.md =================================================================== --- ps/trunk/source/tools/XpartaMuPP/README.md (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/README.md (nonexistent) @@ -1,639 +0,0 @@ -# 0 A.D. / Pyrogenesis Multiplayer Lobby Setup - -This README explains how to setup a custom Pyrogenesis Multiplayer Lobby server that can be used with the Pyrogenesis game. - -## Service description -The Pyrogenesis Multiplayer Lobby consists of three components: - -* **XMPP server: ejabberd**: - The XMPP server provides the platform where users can register accounts, chat in a public room, and can interact with lobby bots. - Currently, ejabberd is the only XMPP server software supported (by the ipstamp module for XpartaMuPP). - -* **Gamelist bot: XpartaMuPP**: - This bot allows players to host and join online multiplayer matches. - It utilizes the ejabberd ipstamp module to inform players of IP addresses of hosting players. - -* **Rating bot: EcheLOn**: - This bot allows players to gain a rating that reflects their skill based on online multiplayer matches. - It is by no means necessary for the operation of a lobby in terms of match-making and chatting. - -## Service choices -Before installing the service, you have to make some decisions: - -#### Choice: Domain Name -Decide on a domain name where the service will be provided. -This document will use `lobby.wildfiregames.com` as an example. -If you intend to use the server only for local testing, you may choose `localhost`. - -#### Choice: Rating service -Decide whether or not you want to employ the rating service. -If you decide to not provide the rating service, you may skip the instructions for the rating bot in this document. - -#### Choice: Pyrogenesis version compatibility -Decide whether you want to support serving multiple Pyrogenesis versions. - -Serving multiple versions of Pyrogenesis allows for seamless version upgrading on the backend and -allows players that don't have the most recent version of Pyrogenesis yet to continue to play until -the new release is available for their platform (applies mostly to linux distributions). - -If you decide to do so, you should use a naming pattern that includes the targetted Pyrogenesis version. -For example to provide a Multiplayer Lobby for Pyrogenesis Alpha 23 "Ken Wood", -name the lobby room `arena23` instead of `arena` and use `xpartamupp23` and `echelon23` as lobby bot names. -Then when a version 24 of Pyrogenesis is employed, you can easily add `arena24`, `xpartamupp24` and `echelon24`. -If you only want to use the service for local testing, you can stick to a single room and a single gamelist and rating bot. - -## 1. Install dependencies - -This section explains how to install the required software on a Debian-based linux distribution. -For other operating systems, use the according package manager or consult the official documentation of the software. - -### 1.1 Install ejabberd - -The version requirement for ejabberd is 17.03 or later (due to the ipstamp module format). - -* Install `ejabberd` using the following command. Alternatively see . - - ``` - $ apt-get install ejabberd - ``` - -* Confirm that the ejabberd version you installed is the one mentioned above or later: - - ``` - $ ejabberdctl status - ``` - -* Configure ejabberd by setting the domain name of your choice and add an `admin` user.: - - ``` - $ dpkg-reconfigure ejabberd - ```` - -You should now be able to connect to this XMPP server using any XMPP client. - -### 1.2 Install python3 and SleekXmpp - -* The lobby bots are programmed in python3 and use SleekXMPP to connect to the lobby. Install these dependencies using: - - ``` - $ apt-get install python3 python3-sleekxmpp - ``` - -* Confirm that the SleekXmpp version is 1.3.1 or later: - - ``` - pip3 show sleekxmpp - ``` - -* If you would like to run the rating bot, you will need to install SQLAlchemy for python3: - - ``` - $ apt-get install python3-sqlalchemy - ``` - -### 1.3 Install ejabberd ipstamp module - -The ejabberd ipstamp module has the purpose of inserting the IP address of the hosting players into the gamelist packet. -That enables players to connect to each others games. - -* Adjust `/etc/ejabberd/ejabberdctl.cfg` and set `CONTRIB_MODULES_PATH` to the directory where you want to store `mod_ipstamp`: - - ``` - CONTRIB_MODULES_PATH=/opt/ejabberd-modules - ``` - -* Ensure the target directory is readable by ejabberd. -* Copy the `mod_ipstamp` directory from `XpartaMuPP/` to `CONTRIB_MODULES_PATH/sources/`. -* Check that the module is available and compatible with your ejabberd: - - ``` - $ ejabberdctl modules_available - $ ejabberdctl module_check mod_ipstamp - ``` - -* Install `mod_ipstamp`: - - ``` - $ ejabberdctl module_install mod_ipstamp - ``` - -## 2. Configure ejabberd mod_ipstamp - -The ejabberd configuration in the remainder of this document is performed by editing `/etc/ejabberd/ejabberd.yml`. -The directory containing this README includes a preconfigured `ejabberd_example.yml` that only needs few setting changes to work with your setup. -For a full documentation of the ejabberd configuration, see . -If something goes wrong with ejabberd, check `/var/log/ejabberd/ejabberd.log` - -* Add `mod_ipstamp` to the modules ejabberd should load: - - ``` - modules: - mod_ipstamp: {} - ``` - -* Reload the ejabberd config. - This should be done every few steps, so that configuration errors can be identified as soon as possible. - - ``` - $ ejabberdctl reload_config - ``` - -## 3. Configure ejabberd connectivity - -The settings in this section ensure that connections can be built where intended, and only where intended. - -### 3.1 Disable IPv6 -* Since the enet library which Pyrogenesis uses for multiplayer mode does not support IPv6, ejabberd must be configured to not use IPv6: - - ``` - listen: - ip: "0.0.0.0" - ``` - -### 3.2 Enable STUN -* ejabberd and Pyrogenesis support the STUN protocol. This allows players to connect to each others games even if the host did not configure -the router and forward the UDP port. Enabling STUN is optional but recommended. - - ``` - listen: - - - port: 3478 - transport: udp - module: ejabberd_stun - ``` - -### 3.3 Enable keep-alive - -* This helps with users becoming disconnected: - - ``` - modules: - mod_ping: - send_pings: true - ``` - -### 3.3 Disable unused services - -* Disable the currently unused server-to-server communication: - - ``` - listen: - ## - - ## port: 5269 - ## ip: "::" - ## module: ejabberd_s2s_in - ``` - -* Protect the administrative webinterface at from external access by disabling or restriction to `localhost`: - - ``` - listen: - - - port: 5280 - ip: "127.0.0.1" - ``` - -* Disable some unused modules: - - ``` - modules: - ## mod_echo: {} - ## mod_irc: {} - ## mod_shared_roster: {} - ## mod_vcard: {} - ## mod_vcard_xupdate: {} - ``` - -### 3.4 Setup TLS encryption - -Depending on whether you use the server for a player audience or only for local testing, -you may have to either obtain and install a certificate with ejabberd or disable TLS encryption. - -#### Choice A: No encryption -* If you intend to use the server solely for local testing, you may disable TLS encryption in the ejabberd config: - - ``` - listen: - starttls_required: false - ``` - -#### Choice B: Self-signed certificate - -If you want to use the server for local testing only, you may use a self-signed certificate to test encryption. -Notice the lobby bots currently reject self-signed certificates. - -* Enable TLS over the default port: - ``` - listen: - starttls: true - ``` - -* Create the key file for certificate: - - ``` - openssl genrsa -out key.pem 2048 - ``` -* Create the certificate file. “common name” should match the domainname. - - ``` - openssl req -new -key key.pem -out request.pem - ``` - -* Sign the certificate: - - ``` - openssl x509 -req -days 900 -in request.pem -signkey key.pem -out certificate.pem - ``` - -* Store it as the ejabberd certificate: - - ``` - $ cat key.pem request.pem > /etc/ejabberd/ejabberd.pem - ``` - -#### Choice C: Let's Encrypt certificate -To secure user authentication and communication with modern encryption and to comply with privacy laws, -ejabberd should be configured to use TLS with a proper, trusted certificate. - -* A free, valid, and trusted TLS certificate may be obtained from some certificate authorites, such as Let's Encrypt: - - - -* Enable TLS over the default port: - ``` - listen: - starttls: true - ``` - -* Setup the contact address if Let's Encrypt found an authentication issue: - - ``` - acme: - contact: "mailto:admin@example.com" - ``` - -* Ensure old, vulnerable SSL/TLS protocols are disabled: - - ``` - define_macro: - 'TLS_OPTIONS': - - "no_sslv2" - - "no_sslv3" - - "no_tlsv1" - ``` - -## 3. Configure ejabberd use policy - -The settings in this section grant or restrict user access rights. - -* Prevent the rooms from being destroyed if the last client leaves it: - - ``` - access_rules: - muc_admin: - - allow: admin - modules: - mod_muc: - access_persistent: muc_admin - default_room_options: - persistent: true - ``` - -* Allow users to create accounts using the game via in-band registration. - ``` - access_rules: - register: - - all: allow - ``` - -### Optional use policies - -* (Optional) It is recommended to restrict usernames to alphanumeric characters (so that playernames are easily typeable for every participant). - The username may be restricted in length (because very long usernames are uncomfortably time-consuming to read and may not fit into the playername fields). - Notice the username regex below is also used by the 0 A.D. client to indicate invalid names to the user. - ``` - acl: - validname: - user_regexp: "^[0-9A-Za-z._-]{1,20}$" - - access_rules: - register: - - allow: validname - - modules: - mod_register: - access: register - ``` - -* (Optional) Prevent users from creating new rooms: - - ``` - modules: - mod_muc: - access_create: muc_admin - ``` - -* (Optional) Increase the maximum number of users from the default 200: - - ``` - mod_muc: - max_users: 5000 - default_room_options: - max_users: 1000 - ``` - -* (Optional) Prevent users from sending too large stanzas. - Notice the bots can send large stanzas as well, so don't restrict it too much. - - ``` - max_stanza_size: 1048576 - ``` - - -* (Optional) Prevent users from changing the room topic: - - ``` - mod_muc: - default_room_options: - allow_change_subj: false - ``` - -* (Optional) Prevent malicious users from registering new accounts quickly if they were banned. - Notice this also prevents players using the same internet router from registering for that time if they want to play together. - - ``` - registration_timeout: 3600 - ``` - -* (Optional) Enable room chatlogging. - Make sure to mention this collection and the purposes in the Terms and Conditions to comply with personal data laws. - Ensure that ejabberd has write access to the given folder. - Notice that `ejabberd.service` by default prevents write access to some directories (PrivateTmp, ProtectHome, ProtectSystem). - - ``` - modules: - mod_muc_log: - outdir: "/lobby/logs" - file_format: plaintext - timezone: universal - mod_muc: - default_room_options: - logging: true - ``` - -* (Optional) Grant specific moderators administrator rights to see the IP address of a user: - See also `https://xmpp.org/extensions/xep-0133.html#get-user-stats`. - - ``` - acl: - admin: - user: - - "username@lobby.wildfiregames.com" - ``` - -* (Optional) Grant specific moderators to : - See also `https://xmpp.org/extensions/xep-0133.html#get-user-stats`. - - ``` - modules: - mod_muc: - access_admin: muc_admin - ``` - -* (Optional) Ban specific IP addresses or subnet masks for persons that create new accounts after having been banned from the room: - - ``` - acl: - blocked: - ip: - - "12.34.56.78" - - "12.34.56.0/8" - - "12.34.0.0/16" - ... - access_rules: - c2s: - - deny: blocked - - allow - register: - - deny: blocked - - allow - ``` - -## 4. Setup lobby bots - -### 4.1 Register lobby bot accounts - -* Check list of registered users: - - ``` - $ ejabberdctl registered_users lobby.wildfiregames.com - ``` - -* Register the accounts of the lobby bots. - The rating account is only needed if you decided to enable the rating service. - - ``` - $ ejabberdctl register echelon23 lobby.wildfiregames.com secure_password - $ ejabberdctl register xpartamupp23 lobby.wildfiregames.com secure_password - ``` - -### 4.2 Authorize lobby bots to see real JIDs - -* The bots need to be able to see real JIDs of users. - So either the room must be configured as non-anonymous, i.e. real JIDs are visible to all users of the room, - or the bots need to receive muc administrator rights. - -#### Choice A: Non-anonymous room -* (Recommended) This method has the advantage that bots do not gain administrative access that they don't use. - The only possible downside is that room users may not hide their username behind arbitrary nicknames anymore. - - ``` - modules: - mod_muc: - default_room_options: - anonymous: false - -#### Choice B: Non-anonymous room -* If you for any reason wish to configure the room as semi-anonymous (only muc administrators can see real JIDs), - then the bots need to be authorized as muc administrators: - - ``` - access_rules: - muc_admin: - - allow: bots - - modules: - mod_muc: - access_admin: muc_admin - ``` - -### 4.3 Authorize lobby bots with ejabberd - -* The bots need an ACL to be able to get the IPs of users hosting a match (which is what `mod_ipstamp` does). - - ``` - acl: - ## Don't use a regex, to prevent others from obtaining permissions after registering such an account. - bots: - - user: "xpartamupp23@lobby.wildfiregames.com" - - user: "echelon23@lobby.wildfiregames.com" - ``` - -* Add an access rule for `ipbots` and a rule allowing bots to create PubSub nodes: - - ``` - access_rules: - ## Expected by the ipstamp module for XpartaMuPP - ipbots: - - allow: bots - - pubsub_createnode: - - allow: bots - ``` - -* Due to the amount of traffic the bot may process, give the group containing bots either unlimited - or a very high traffic shaper: - - ``` - shaper_rules: - c2s_shaper: - - none: admin, bots - - normal - ``` - -* Finally reload ejabberd's configuration: - - ``` - $ ejabberdctl reload_config - ``` - -### 4.4 Running XpartaMuPP - XMPP Multiplayer Game Manager - -* Execute the following command to run the gamelist bot: - - ``` - $ python3 XpartaMuPP.py --domain lobby.wildfiregames.com --login xpartamupp23 --password XXXXXX --nickname GamelistBot --room arena --elo echelon23 - ``` - -If you want to run XpartaMuPP without a rating bot, the `--elo` argument should be omitted. -Pass `--disable-tls` if you did not setup valid TLS encryption on the server. -Run `python3 XpartaMuPP.py --help` for the full list of options - -* If the connection and authentication succeeded, you should see the following messages in the console: - - ``` - INFO JID set to: xpartamupp23@lobby.wildfiregames.com/CC - INFO XpartaMuPP started - ``` - -### 4.5 Running EcheLOn - XMPP Multiplayer Rating Manager - -This bot can be thought of as a module of XpartaMuPP in that IQs stanzas sent to XpartaMuPP are -forwarded onto EcheLOn if its corresponding EcheLOn is online and ignored otherwise. -EcheLOn handles all aspects of operation related to ELO, the chess rating system invented by Arpad Elo. -Players gain a rating after a rated 1v1 match. -The score difference after a completed match is relative to the rating difference of the players. - -* (Optional) Some constants of the algorithm may be edited by experienced administrators at the head of `ELO.py`: - - ``` - # Difference between two ratings such that it is - # regarded as a "sure win" for the higher player. - # No points are gained or lost for such a game. - elo_sure_win_difference = 600.0 - - # Lower ratings "move faster" and change more - # dramatically than higher ones. Anything rating above - # this value moves at the same rate as this value. - elo_k_factor_constant_rating = 2200.0 - ``` - -* To initialize the `lobby_rankings.sqlite3` database, execute the following command: - - ``` - $ python3 LobbyRanking.py - ``` - -* Execute the following command to run the rating bot: - - ``` - $ python3 EcheLOn.py --domain lobby.wildfiregames.com --login echelon23 --password XXXXXX --nickname RatingBot --room arena23 - ``` - -Run `python3 EcheLOn.py --help` for the full list of options - -## 5. Configure Pyrogenesis for the new Multiplayer Lobby - -The Pyrogenesis client is now going to be configured to become able to connect to the new Multiplayer Lobby. - -The Pyrogenesis documentation of configuration files can be found at . -Available Pyrogenesis configuration settings are specified in `default.cfg`, see . - -### 5.1 Local Configuration - - * Visit to identify the local user's Pyrogenesis configuration path depending on the operating system. - - * Create or open `local.cfg` in the configuration path. - - * Add the following settings that determine the lobby server connection: - - ``` - lobby.room = "arena23" ; Default MUC room to join - lobby.server = "lobby.wildfiregames.com" ; Address of lobby server - lobby.stun.server = "lobby.wildfiregames.com" ; Address of the STUN server. - lobby.require_tls = true ; Whether to reject connecting to the lobby if TLS encryption is unavailable. - lobby.verify_certificate = true ; Whether to reject connecting to the lobby if the TLS certificate is invalid. - lobby.xpartamupp = "xpartamupp23" ; Name of the server-side XMPP-account that manage games - lobby.echelon = "echelon23" ; Name of the server-side XMPP-account that manages ratings - ``` - - If you disabled TLS encryption, set `require_tls` to `false`. - If you employed a self-signed certificate, set `verify_certificate` to `false`. - -### 5.2 Test the Multiplayer Lobby - -You should now be able to join the new multiplayer lobby with the Pyrogenesis client and play multiplayer matches. - -* To confirm that the match hosting works as intended, create two user accounts, host a game with one, join the game with the other account. - -* To confirm that the rating service works as intended, resign a rated 1v1 match with two accounts. - -### 5.3 Terms and Conditions - -Players joining public servers are subject to Terms and Conditions of the service provider and subject to privacy laws such as GDPR. -If you intend to use the server only for local testing, you may skip this step. - -* The following files should be created by the service provider: - - `Terms_of_Service.txt` to explain the service and the contract. - `Terms_of_Use.txt` to explain what the user should and should not do. - `Privacy_Policy.txt` to explain how personal data is handled. - -* To use Wildfire Games Terms as a template, obtain our Terms from a copy of the game or from or from - - -* Replace all occurrences of `Wildfire Games` in the files with the one providing the new server. - -* Update the `Terms_of_Use.txt` depending on which behavior you would like to (not) see on your service. - -* Update the `Privacy_Policy.txt` depending on the user data processing in relation to the usage policies. -Make sure to not violate privacy laws such as GDPR or COPPA while doing so. - -* The retention times of ejabberd logs are relevant to GDPR. -Visit for details. - -* The terms should be published online, so users can save and print them. - Add to your `local.cfg`: - - ``` - lobby.terms_url = "https://lobby.wildfiregames.com/terms/"; Allows the user to save the text and print the terms - ``` - -### 5.4 Distribute the configuration - -To make this a public server, distribute your `local.cfg`, `Terms_of_Service.txt`, `Terms_of_Use.txt`, `Privacy_Policy.txt`. - -It may be advisable to create a mod with a modified `default.cfg` and the new terms documents, -see . - -Congratulations, you are now running a custom Pyrogenesis Multiplayer Lobby! Property changes on: ps/trunk/source/tools/XpartaMuPP/README.md ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/mod_ipstamp.spec =================================================================== --- ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/mod_ipstamp.spec (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/mod_ipstamp.spec (nonexistent) @@ -1,5 +0,0 @@ -author: "Wildfire Games" -category: "log" -summary: "Add senders IP address to game registration stanzas for 0ad" -home: "undefined" -url: "https://play0ad.com" Property changes on: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/mod_ipstamp.spec ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/src/mod_ipstamp.erl =================================================================== --- ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/src/mod_ipstamp.erl (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/src/mod_ipstamp.erl (nonexistent) @@ -1,72 +0,0 @@ -%% Copyright (C) 2018 Wildfire Games. -%% This file is part of 0 A.D. -%% -%% 0 A.D. is free software: you can redistribute it and/or modify -%% it under the terms of the GNU General Public License as published by -%% the Free Software Foundation, either version 2 of the License, or -%% (at your option) any later version. -%% -%% 0 A.D. is distributed in the hope that it will be useful, -%% but WITHOUT ANY WARRANTY; without even the implied warranty of -%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -%% GNU General Public License for more details. -%% -%% You should have received a copy of the GNU General Public License -%% along with 0 A.D. If not, see . - --module(mod_ipstamp). - --behaviour(gen_mod). - --include("ejabberd.hrl"). --include("logger.hrl"). --include("xmpp.hrl"). - --export([start/2, - stop/1, - depends/2, - mod_opt_type/1, - reload/3, - on_filter_packet/1]). - -start(_Host, _Opts) -> - ejabberd_hooks:add(filter_packet, global, ?MODULE, on_filter_packet, 50). - -stop(_Host) -> - ejabberd_hooks:delete(filter_packet, global, ?MODULE, on_filter_packet, 50). - -depends(_Host, _Opts) -> []. - -mod_opt_type(_) -> []. - -reload(_Host, _NewOpts, _OldOpts) -> ok. - --spec on_filter_packet(Input :: iq()) -> iq() | drop. -on_filter_packet(#iq{type = set, to = To, sub_els = [SubEl]} = Input) -> - % We only want to do something for the bots - case acl:match_rule(global, ipbots, To) of - allow -> - NS = xmpp:get_ns(SubEl), - if NS == <<"jabber:iq:gamelist">> -> - SCommand = fxml:get_path_s(SubEl, [{elem, <<"command">>}, cdata]), - if SCommand == <<"register">> -> - % Get the sender's IP. - Ip = xmpp:get_meta(Input, ip), - SIp = inet_parse:ntoa(Ip), - ?INFO_MSG(string:concat("Inserting IP into game registration " - "stanza: ", SIp), []), - Game = fxml:get_subtag(SubEl, <<"game">>), - GameWithIp = fxml:replace_tag_attr(<<"ip">>, SIp, Game), - SubEl2 = fxml:replace_subtag(GameWithIp, SubEl), - xmpp:set_els(Input, [SubEl2]); - true -> - Input - end; - true -> - Input - end; - _ -> Input - end; - -on_filter_packet(Input) -> - Input. Property changes on: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/src/mod_ipstamp.erl ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/COPYING =================================================================== --- ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/COPYING (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/COPYING (nonexistent) @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. Property changes on: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/COPYING ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/README.txt =================================================================== --- ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/README.txt (revision 21925) +++ ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/README.txt (nonexistent) @@ -1,7 +0,0 @@ -mod_ipstamp -=========== - -mod_ipstamp is an ejabberd module for 0ad which adds ip addresses of a -game host to game registration stanzas. - -For it to work the 0ad XMPP bots need to have the ACL "ipbots". Property changes on: ps/trunk/source/tools/XpartaMuPP/mod_ipstamp/README.txt ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/source/tools/LICENSE.txt =================================================================== --- ps/trunk/source/tools/LICENSE.txt (revision 21925) +++ ps/trunk/source/tools/LICENSE.txt (revision 21926) @@ -1,72 +1,72 @@ This directory mostly contains tools that are not required to run 0 A.D., with the exception of Atlas, but they may be useful to some people. Those files authored by Philip Taylor are released under the MIT license. Some files don't yet have licensing details specified - if you care about any in particular, let us know and we can try to clarify it. atlas GPL version 2 (or later) - see license_gpl-2.0.txt autolog MIT cmpgraph MIT dist MIT zlib/libpng (FileAssociation.nsh) entdocs MIT entgraph MIT libjpeg (jpeg.dll) libpng (png.dll) zlib (z.dll) entity MIT fontbuilder2 MIT unspecified (FontLoader.py) IBM CPL (Packer.py) i18n GPL version 2 (or later) BSD (extractors) openlogsfolder MIT profiler2 MIT MIT / GPLv2 (jquery-1.6.4.js) replayprofile MIT MIT / GPLv2 (jquery.flot.navigate.js, jquery.js) selectiontexgen unspecified springimport MIT templatesanalyzer MIT templatessorter MIT webservices MIT / unspecified xmlvalidator MIT - XpartaMuPP + lobbybots GPL version 2 (or later) Index: ps/trunk/source/tools/lobbybots/EcheLOn/ELO.py =================================================================== --- ps/trunk/source/tools/lobbybots/EcheLOn/ELO.py (nonexistent) +++ ps/trunk/source/tools/lobbybots/EcheLOn/ELO.py (revision 21926) @@ -0,0 +1,90 @@ +"""Copyright (C) 2014 Wildfire Games. + * This file is part of 0 A.D. + * + * 0 A.D. is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * 0 A.D. is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with 0 A.D. If not, see . +""" + +############ Constants ############ +# Difference between two ratings such that it is +# regarded as a "sure win" for the higher player. +# No points are gained or lost for such a game. +elo_sure_win_difference = 600.0 + +# Lower ratings "move faster" and change more +# dramatically than higher ones. Anything rating above +# this value moves at the same rate as this value. +elo_k_factor_constant_rating = 2200.0 + +# This preset number of games is the number of games +# where a player is considered "stable". +# Rating volatility is constant after this number. +volatility_constant = 20.0 + +# Fair rating adjustment loses against inflation +# This constant will battle inflation. +# NOTE: This can be adjusted as needed by a +# bot/server administrator +anti_inflation = 0.015 + +############ Functions ############ +def get_rating_adjustment(rating, opponent_rating, games_played, opponent_games_played, result): + """ + Calculates the rating adjustment after a 1v1 game finishes using simplified ELO. + + Arguments: + rating, opponent_rating - Ratings of the players before this game. + games_played, opponent_games_played - Number of games each player has played + before this game. + result - 1 for the first player (rating, games_played) won, 0 for draw, or + -1 for the second player (opponent_rating, opponent_games_played) won. + + Returns: + The integer that should be subtracted from the loser's rating and added + to the winner's rating to get their new ratings. + + TODO: Team games. + """ + player_volatility = (min(games_played, volatility_constant) / volatility_constant + 0.25) / 1.25 + rating_k_factor = 50.0 * (min(rating, elo_k_factor_constant_rating) / elo_k_factor_constant_rating + 1.0) / 2.0 + volatility = rating_k_factor * player_volatility + difference = opponent_rating - rating + if result == 1: + return round(max(0, (difference + result * elo_sure_win_difference) / volatility - anti_inflation)) + elif result == -1: + return round(min(0, (difference + result * elo_sure_win_difference) / volatility - anti_inflation)) + else: + return round(difference / volatility - anti_inflation) + +# Inflation test - A slightly negative is better than a slightly positive +# Lower rated players stop playing more often than higher rated players +# Uncomment to test. +# In this example, two evenly matched players play for 150000 games. +""" +from random import randrange +r1start = 1600 +r2start = 1600 +r1 = r1start +r2 = r2start +for x in range(0, 150000): + res = randrange(3)-1 # How often one wins against the other + if res >= 1: + res = 1 + elif res <= -1: + res = -1 + r1gain = get_rating_adjustment(r1, r2, 20, 20, res) + r2gain = get_rating_adjustment(r2, r1, 20, 20, -1 * res) + r1 += r1gain + r2 += r2gain +print(str(r1) + " " + str(r2) + " : " + str(r1 + r2-r1start - r2start)) +""" Property changes on: ps/trunk/source/tools/lobbybots/EcheLOn/ELO.py ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/source/tools/lobbybots/EcheLOn/EcheLOn.py =================================================================== --- ps/trunk/source/tools/lobbybots/EcheLOn/EcheLOn.py (nonexistent) +++ ps/trunk/source/tools/lobbybots/EcheLOn/EcheLOn.py (revision 21926) @@ -0,0 +1,795 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Copyright (C) 2018 Wildfire Games. + * This file is part of 0 A.D. + * + * 0 A.D. is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * 0 A.D. is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with 0 A.D. If not, see . +""" + +import logging, time, traceback +from optparse import OptionParser + +import sleekxmpp +from sleekxmpp.stanza import Iq +from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin, ET +from sleekxmpp.xmlstream.handler import Callback +from sleekxmpp.xmlstream.matcher import StanzaPath + +from sqlalchemy import func + +from LobbyRanking import session as db, Game, Player, PlayerInfo +from ELO import get_rating_adjustment +# Rating that new players should be inserted into the +# database with, before they've played any games. +leaderboard_default_rating = 1200 + +## Class that contains and manages leaderboard data ## +class LeaderboardList(): + def __init__(self, room): + self.room = room + self.lastRated = "" + + def getProfile(self, JID): + """ + Retrieves the profile for the specified JID + """ + stats = {} + player = db.query(Player).filter(Player.jid.ilike(str(JID))) + + if not player.first(): + return + + queried_player = player.first() + playerID = queried_player.id + if queried_player.rating != -1: + stats['rating'] = str(queried_player.rating) + rank = db.query(Player).filter(Player.rating >= queried_player.rating).count() + stats['rank'] = str(rank) + + if queried_player.highest_rating != -1: + stats['highestRating'] = str(queried_player.highest_rating) + + gamesPlayed = db.query(PlayerInfo).filter_by(player_id=playerID).count() + wins = db.query(Game).filter_by(winner_id=playerID).count() + stats['totalGamesPlayed'] = str(gamesPlayed) + stats['wins'] = str(wins) + stats['losses'] = str(gamesPlayed - wins) + return stats + + def getOrCreatePlayer(self, JID): + """ + Stores a player(JID) in the database if they don't yet exist. + Returns either the newly created instance of + the Player model, or the one that already + exists in the database. + """ + players = db.query(Player).filter(Player.jid.ilike(str(JID))) + if not players.first(): + player = Player(jid=str(JID), rating=-1) + db.add(player) + db.commit() + return player + return players.first() + + def removePlayer(self, JID): + """ + Remove a player(JID) from database. + Returns the player that was removed, or None + if that player didn't exist. + """ + players = db.query(Player).filter(Player.jid.ilike(str(JID))) + player = players.first() + if not player: + return None + players.delete() + return player + + def addGame(self, gamereport): + """ + Adds a game to the database and updates the data + on a player(JID) from game results. + Returns the created Game object, or None if + the creation failed for any reason. + Side effects: + Inserts a new Game instance into the database. + """ + # Discard any games still in progress. + if any(map(lambda state: state == 'active', + dict.values(gamereport['playerStates']))): + return None + + players = map(lambda jid: db.query(Player).filter(Player.jid.ilike(str(jid))).first(), + dict.keys(gamereport['playerStates'])) + + winning_jid = list(dict.keys({jid: state for jid, state in + gamereport['playerStates'].items() + if state == 'won'}))[0] + + def get(stat, jid): + return gamereport[stat][jid] + + singleStats = {'timeElapsed', 'mapName', 'teamsLocked', 'matchID'} + totalScoreStats = {'economyScore', 'militaryScore', 'totalScore'} + resourceStats = {'foodGathered', 'foodUsed', 'woodGathered', 'woodUsed', + 'stoneGathered', 'stoneUsed', 'metalGathered', 'metalUsed', 'vegetarianFoodGathered', + 'treasuresCollected', 'lootCollected', 'tributesSent', 'tributesReceived'} + unitsStats = {'totalUnitsTrained', 'totalUnitsLost', 'enemytotalUnitsKilled', 'infantryUnitsTrained', + 'infantryUnitsLost', 'enemyInfantryUnitsKilled', 'workerUnitsTrained', 'workerUnitsLost', + 'enemyWorkerUnitsKilled', 'femaleCitizenUnitsTrained', 'femaleCitizenUnitsLost', 'enemyFemaleCitizenUnitsKilled', + 'cavalryUnitsTrained', 'cavalryUnitsLost', 'enemyCavalryUnitsKilled', 'championUnitsTrained', + 'championUnitsLost', 'enemyChampionUnitsKilled', 'heroUnitsTrained', 'heroUnitsLost', + 'enemyHeroUnitsKilled', 'shipUnitsTrained', 'shipUnitsLost', 'enemyShipUnitsKilled', 'traderUnitsTrained', + 'traderUnitsLost', 'enemyTraderUnitsKilled'} + buildingsStats = {'totalBuildingsConstructed', 'totalBuildingsLost', 'enemytotalBuildingsDestroyed', + 'civCentreBuildingsConstructed', 'civCentreBuildingsLost', 'enemyCivCentreBuildingsDestroyed', + 'houseBuildingsConstructed', 'houseBuildingsLost', 'enemyHouseBuildingsDestroyed', + 'economicBuildingsConstructed', 'economicBuildingsLost', 'enemyEconomicBuildingsDestroyed', + 'outpostBuildingsConstructed', 'outpostBuildingsLost', 'enemyOutpostBuildingsDestroyed', + 'militaryBuildingsConstructed', 'militaryBuildingsLost', 'enemyMilitaryBuildingsDestroyed', + 'fortressBuildingsConstructed', 'fortressBuildingsLost', 'enemyFortressBuildingsDestroyed', + 'wonderBuildingsConstructed', 'wonderBuildingsLost', 'enemyWonderBuildingsDestroyed'} + marketStats = {'woodBought', 'foodBought', 'stoneBought', 'metalBought', 'tradeIncome'} + miscStats = {'civs', 'teams', 'percentMapExplored'} + + stats = totalScoreStats | resourceStats | unitsStats | buildingsStats | marketStats | miscStats + playerInfos = [] + for player in players: + jid = player.jid + playerinfo = PlayerInfo(player=player) + for reportname in stats: + setattr(playerinfo, reportname, get(reportname, jid.lower())) + playerInfos.append(playerinfo) + + game = Game(map=gamereport['mapName'], duration=int(gamereport['timeElapsed']), teamsLocked=bool(gamereport['teamsLocked']), matchID=gamereport['matchID']) + game.players.extend(players) + game.player_info.extend(playerInfos) + game.winner = db.query(Player).filter(Player.jid.ilike(str(winning_jid))).first() + db.add(game) + db.commit() + return game + + def verifyGame(self, gamereport): + """ + Returns a boolean based on whether the game should be rated. + Here, we can specify the criteria for rated games. + """ + winning_jids = list(dict.keys({jid: state for jid, state in + gamereport['playerStates'].items() + if state == 'won'})) + # We only support 1v1s right now. TODO: Support team games. + if len(winning_jids) * 2 > len(dict.keys(gamereport['playerStates'])): + # More than half the people have won. This is not a balanced team game or duel. + return False + if len(dict.keys(gamereport['playerStates'])) != 2: + return False + return True + + def rateGame(self, game): + """ + Takes a game with 2 players and alters their ratings + based on the result of the game. + Returns self. + Side effects: + Changes the game's players' ratings in the database. + """ + player1 = game.players[0] + player2 = game.players[1] + # TODO: Support draws. Since it's impossible to draw in the game currently, + # the database model, and therefore this code, requires a winner. + # The Elo implementation does not, however. + result = 1 if player1 == game.winner else -1 + # Player's ratings are -1 unless they have played a rated game. + if player1.rating == -1: + player1.rating = leaderboard_default_rating + if player2.rating == -1: + player2.rating = leaderboard_default_rating + + rating_adjustment1 = int(get_rating_adjustment(player1.rating, player2.rating, + len(player1.games), len(player2.games), result)) + rating_adjustment2 = int(get_rating_adjustment(player2.rating, player1.rating, + len(player2.games), len(player1.games), result * -1)) + if result == 1: + resultQualitative = "won" + elif result == 0: + resultQualitative = "drew" + else: + resultQualitative = "lost" + name1 = '@'.join(player1.jid.split('@')[:-1]) + name2 = '@'.join(player2.jid.split('@')[:-1]) + self.lastRated = "A rated game has ended. %s %s against %s. Rating Adjustment: %s (%s -> %s) and %s (%s -> %s)."%(name1, + resultQualitative, name2, name1, player1.rating, player1.rating + rating_adjustment1, + name2, player2.rating, player2.rating + rating_adjustment2) + player1.rating += rating_adjustment1 + player2.rating += rating_adjustment2 + if not player1.highest_rating: + player1.highest_rating = -1 + if not player2.highest_rating: + player2.highest_rating = -1 + if player1.rating > player1.highest_rating: + player1.highest_rating = player1.rating + if player2.rating > player2.highest_rating: + player2.highest_rating = player2.rating + db.commit() + return self + + def getLastRatedMessage(self): + """ + Gets the string of the last rated game. Triggers an update + chat for the bot. + """ + return self.lastRated + + def addAndRateGame(self, gamereport): + """ + Calls addGame and if the game has only two + players, also calls rateGame. + Returns the result of addGame. + """ + game = self.addGame(gamereport) + if game and self.verifyGame(gamereport): + self.rateGame(game) + else: + self.lastRated = "" + return game + + def getBoard(self): + """ + Returns a dictionary of player rankings to + JIDs for sending. + """ + board = {} + players = db.query(Player).filter(Player.rating != -1).order_by(Player.rating.desc()).limit(100).all() + for rank, player in enumerate(players): + board[player.jid] = {'name': '@'.join(player.jid.split('@')[:-1]), 'rating': str(player.rating)} + return board + + def getRatingList(self, nicks): + """ + Returns a rating list of players + currently in the lobby by nick + because the client can't link + JID to nick conveniently. + """ + ratinglist = {} + players = db.query(Player.jid, Player.rating).filter(func.upper(Player.jid).in_([ str(JID).upper() for JID in list(nicks) ])) + for player in players: + rating = str(player.rating) if player.rating != -1 else '' + for JID in list(nicks): + if JID.upper() == player.jid.upper(): + ratinglist[nicks[JID]] = {'name': nicks[JID], 'rating': rating} + break + return ratinglist + +## Class which manages different game reports from clients ## +## and calls leaderboard functions as appropriate. ## +class ReportManager(): + def __init__(self, leaderboard): + self.leaderboard = leaderboard + self.interimReportTracker = [] + self.interimJIDTracker = [] + + def addReport(self, JID, rawGameReport): + """ + Adds a game to the interface between a raw report + and the leaderboard database. + """ + # cleanRawGameReport is a copy of rawGameReport with all reporter specific information removed. + cleanRawGameReport = rawGameReport.copy() + del cleanRawGameReport["playerID"] + + if cleanRawGameReport not in self.interimReportTracker: + # Store the game. + appendIndex = len(self.interimReportTracker) + self.interimReportTracker.append(cleanRawGameReport) + # Initilize the JIDs and store the initial JID. + numPlayers = self.getNumPlayers(rawGameReport) + JIDs = [None] * numPlayers + if numPlayers - int(rawGameReport["playerID"]) > -1: + JIDs[int(rawGameReport["playerID"])-1] = str(JID).lower() + self.interimJIDTracker.append(JIDs) + else: + # We get the index at which the JIDs coresponding to the game are stored. + index = self.interimReportTracker.index(cleanRawGameReport) + # We insert the new report JID into the ascending list of JIDs for the game. + JIDs = self.interimJIDTracker[index] + if len(JIDs) - int(rawGameReport["playerID"]) > -1: + JIDs[int(rawGameReport["playerID"])-1] = str(JID).lower() + self.interimJIDTracker[index] = JIDs + + self.checkFull() + + def expandReport(self, rawGameReport, JIDs): + """ + Takes an raw game report and re-formats it into + Python data structures leaving JIDs empty. + Returns a processed gameReport of type dict. + """ + processedGameReport = {} + for key in rawGameReport: + if rawGameReport[key].find(",") == -1: + processedGameReport[key] = rawGameReport[key] + else: + split = rawGameReport[key].split(",") + # Remove the false split positive. + split.pop() + statToJID = {} + for i, part in enumerate(split): + statToJID[JIDs[i]] = part + processedGameReport[key] = statToJID + return processedGameReport + + def checkFull(self): + """ + Searches internal database to check if enough + reports have been submitted to add a game to + the leaderboard. If so, the report will be + interpolated and addAndRateGame will be + called with the result. + """ + i = 0 + length = len(self.interimReportTracker) + while(i < length): + numPlayers = self.getNumPlayers(self.interimReportTracker[i]) + numReports = 0 + for JID in self.interimJIDTracker[i]: + if JID != None: + numReports += 1 + if numReports == numPlayers: + try: + self.leaderboard.addAndRateGame(self.expandReport(self.interimReportTracker[i], self.interimJIDTracker[i])) + except: + traceback.print_exc() + del self.interimJIDTracker[i] + del self.interimReportTracker[i] + length -= 1 + else: + i += 1 + self.leaderboard.lastRated = "" + + def getNumPlayers(self, rawGameReport): + """ + Computes the number of players in a raw gameReport. + Returns int, the number of players. + """ + # Find a key in the report which holds values for multiple players. + for key in rawGameReport: + if rawGameReport[key].find(",") != -1: + # Count the number of values, minus one for the false split positive. + return len(rawGameReport[key].split(","))-1 + # Return -1 in case of failure. + return -1 + +## Class for custom player stanza extension ## +class PlayerXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:player' + interfaces = set(('game', 'online')) + sub_interfaces = interfaces + plugin_attrib = 'player' + + def addPlayerOnline(self, player): + playerXml = ET.fromstring("%s" % player) + self.xml.append(playerXml) + +## Class for custom boardlist and ratinglist stanza extension ## +class BoardListXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:boardlist' + interfaces = set(('board', 'command', 'recipient')) + sub_interfaces = interfaces + plugin_attrib = 'boardlist' + def addCommand(self, command): + commandXml = ET.fromstring("%s" % command) + self.xml.append(commandXml) + def addRecipient(self, recipient): + recipientXml = ET.fromstring("%s" % recipient) + self.xml.append(recipientXml) + def addItem(self, name, rating): + itemXml = ET.Element("board", {"name": name, "rating": rating}) + self.xml.append(itemXml) + +## Class for custom gamereport stanza extension ## +class GameReportXmppPlugin(ElementBase): + name = 'report' + namespace = 'jabber:iq:gamereport' + plugin_attrib = 'gamereport' + interfaces = ('game', 'sender') + sub_interfaces = interfaces + def addSender(self, sender): + senderXml = ET.fromstring("%s" % sender) + self.xml.append(senderXml) + def getGame(self): + """ + Required to parse incoming stanzas with this + extension. + """ + game = self.xml.find('{%s}game' % self.namespace) + data = {} + for key, item in game.items(): + data[key] = item + return data + +## Class for custom profile ## +class ProfileXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:profile' + interfaces = set(('profile', 'command', 'recipient')) + sub_interfaces = interfaces + plugin_attrib = 'profile' + def addCommand(self, command): + commandXml = ET.fromstring("%s" % command) + self.xml.append(commandXml) + def addRecipient(self, recipient): + recipientXml = ET.fromstring("%s" % recipient) + self.xml.append(recipientXml) + def addItem(self, player, rating, highestRating, rank, totalGamesPlayed, wins, losses): + itemXml = ET.Element("profile", {"player": player, "rating": rating, "highestRating": highestRating, + "rank" : rank, "totalGamesPlayed" : totalGamesPlayed, "wins" : wins, + "losses" : losses}) + self.xml.append(itemXml) + +## Main class which handles IQ data and sends new data ## +class EcheLOn(sleekxmpp.ClientXMPP): + """ + A simple list provider + """ + def __init__(self, sjid, password, room, nick): + sleekxmpp.ClientXMPP.__init__(self, sjid, password) + self.sjid = sjid + self.room = room + self.nick = nick + self.ratingListCache = {} + self.ratingCacheReload = True + self.boardListCache = {} + self.boardCacheReload = True + + # Init leaderboard object + self.leaderboard = LeaderboardList(room) + + # gameReport to leaderboard abstraction + self.reportManager = ReportManager(self.leaderboard) + + # Store mapping of nicks and XmppIDs, attached via presence stanza + self.nicks = {} + + self.lastLeft = "" + + register_stanza_plugin(Iq, PlayerXmppPlugin) + register_stanza_plugin(Iq, BoardListXmppPlugin) + register_stanza_plugin(Iq, GameReportXmppPlugin) + register_stanza_plugin(Iq, ProfileXmppPlugin) + + self.register_handler(Callback('Iq Player', + StanzaPath('iq/player'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq Boardlist', + StanzaPath('iq/boardlist'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq GameReport', + StanzaPath('iq/gamereport'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq Profile', + StanzaPath('iq/profile'), + self.iqhandler, + instream=True)) + + self.add_event_handler("session_start", self.start) + self.add_event_handler("muc::%s::got_online" % self.room, self.muc_online) + self.add_event_handler("muc::%s::got_offline" % self.room, self.muc_offline) + + def start(self, event): + """ + Process the session_start event + """ + self.plugin['xep_0045'].joinMUC(self.room, self.nick) + self.send_presence() + self.get_roster() + logging.info("EcheLOn started") + + def muc_online(self, presence): + """ + Process presence stanza from a chat room. + """ + if presence['muc']['nick'] != self.nick: + # If it doesn't already exist, store player JID mapped to their nick. + if str(presence['muc']['jid']) not in self.nicks: + self.nicks[str(presence['muc']['jid'])] = presence['muc']['nick'] + # Check the jid isn't already in the lobby. + logging.debug("Client '%s' connected with a nick of '%s'." %(presence['muc']['jid'], presence['muc']['nick'])) + + def muc_offline(self, presence): + """ + Process presence stanza from a chat room. + """ + # Clean up after a player leaves + if presence['muc']['nick'] != self.nick: + # Remove them from the local player list. + self.lastLeft = str(presence['muc']['jid']) + if str(presence['muc']['jid']) in self.nicks: + del self.nicks[str(presence['muc']['jid'])] + + def iqhandler(self, iq): + """ + Handle the custom stanzas + This method should be very robust because we could receive anything + """ + if iq['type'] == 'error': + logging.error('iqhandler error' + iq['error']['condition']) + #self.disconnect() + elif iq['type'] == 'get': + """ + Request lists. + """ + if 'boardlist' in iq.loaded_plugins: + command = iq['boardlist']['command'] + recipient = iq['boardlist']['recipient'] + if command == 'getleaderboard': + try: + self.sendBoardList(iq['from'], recipient) + except: + traceback.print_exc() + logging.error("Failed to process leaderboardlist request from %s" % iq['from'].bare) + elif command == 'getratinglist': + try: + self.sendRatingList(iq['from']); + except: + traceback.print_exc() + else: + logging.error("Failed to process boardlist request from %s" % iq['from'].bare) + elif 'profile' in iq.loaded_plugins: + command = iq['profile']['command'] + recipient = iq['profile']['recipient'] + try: + self.sendProfile(iq['from'], command, recipient) + except: + try: + self.sendProfileNotFound(iq['from'], command, recipient) + except: + logging.debug("No record found for %s" % command) + else: + logging.error("Unknown 'get' type stanza request from %s" % iq['from'].bare) + elif iq['type'] == 'result': + """ + Iq successfully received + """ + pass + elif iq['type'] == 'set': + if 'gamereport' in iq.loaded_plugins: + """ + Client is reporting end of game statistics + """ + if iq['gamereport']['sender']: + sender = iq['gamereport']['sender'] + else: + sender = iq['from'] + try: + self.leaderboard.getOrCreatePlayer(iq['gamereport']['sender']) + self.reportManager.addReport(sender, iq['gamereport']['game']) + if self.leaderboard.getLastRatedMessage() != "": + self.ratingCacheReload = True + self.boardCacheReload = True + self.send_message(mto=self.room, mbody=self.leaderboard.getLastRatedMessage(), mtype="groupchat", + mnick=self.nick) + self.sendRatingList(iq['from']) + except: + traceback.print_exc() + logging.error("Failed to update game statistics for %s" % iq['from'].bare) + elif 'player' in iq.loaded_plugins: + player = iq['player']['online'] + #try: + self.leaderboard.getOrCreatePlayer(player) + #except: + #logging.debug("Could not create new user %s" % player) + else: + logging.error("Failed to process stanza type '%s' received from %s" % iq['type'], iq['from'].bare) + + def sendBoardList(self, to, recipient): + """ + Send the whole leaderboard list. + If no target is passed the boardlist is broadcasted + to all clients. + """ + ## See if we can squeak by with the cached version. + # Leaderboard cache is reloaded upon a new rated game being rated. + if self.boardCacheReload: + self.boardListCache = self.leaderboard.getBoard() + self.boardCacheReload = False + + stz = BoardListXmppPlugin() + iq = self.Iq() + iq['type'] = 'result' + for i in self.boardListCache: + stz.addItem(self.boardListCache[i]['name'], self.boardListCache[i]['rating']) + stz.addCommand('boardlist') + stz.addRecipient(recipient) + iq.setPayload(stz) + ## Check recipient exists + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send boardlist to" % str(to)) + return + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send leaderboard list") + + def sendRatingList(self, to): + """ + Send the rating list. + """ + ## Attempt to use the cache. + # Cache is invalidated when a new game is rated or a uncached player + # comes online. + if self.ratingCacheReload: + self.ratingListCache = self.leaderboard.getRatingList(self.nicks) + self.ratingCacheReload = False + else: + for JID in list(self.nicks): + if JID not in self.ratingListCache: + self.ratingListCache = self.leaderboard.getRatingList(self.nicks) + self.ratingCacheReload = False + break + + stz = BoardListXmppPlugin() + iq = self.Iq() + iq['type'] = 'result' + for i in self.ratingListCache: + stz.addItem(self.ratingListCache[i]['name'], self.ratingListCache[i]['rating']) + stz.addCommand('ratinglist') + iq.setPayload(stz) + ## Check recipient exists + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send ratinglist to" % str(to)) + return + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send rating list") + + def sendProfile(self, to, player, recipient): + """ + Send the player profile to a specified target. + """ + if to == "": + logging.error("Failed to send profile") + return + + online = False; + ## Pull stats and add it to the stanza + for JID in list(self.nicks): + if self.nicks[JID] == player: + stats = self.leaderboard.getProfile(JID) + online = True + break + + if online == False: + stats = self.leaderboard.getProfile(player + "@" + str(recipient).split('@')[1]) + stz = ProfileXmppPlugin() + iq = self.Iq() + iq['type'] = 'result' + + stz.addItem(player, stats['rating'], stats['highestRating'], stats['rank'], stats['totalGamesPlayed'], stats['wins'], stats['losses']) + stz.addCommand(player) + stz.addRecipient(recipient) + iq.setPayload(stz) + ## Check recipient exists + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send profile to" % str(to)) + return + + ## Set additional IQ attributes + iq['to'] = to + + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + traceback.print_exc() + logging.error("Failed to send profile") + + def sendProfileNotFound(self, to, player, recipient): + """ + Send a profile not-found error to a specified target. + """ + stz = ProfileXmppPlugin() + iq = self.Iq() + iq['type'] = 'result' + + filler = str(0) + stz.addItem(player, str(-2), filler, filler, filler, filler, filler) + stz.addCommand(player) + stz.addRecipient(recipient) + iq.setPayload(stz) + ## Check recipient exists + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send profile to" % str(to)) + return + + ## Set additional IQ attributes + iq['to'] = to + + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + traceback.print_exc() + logging.error("Failed to send profile") + +## Main Program ## +if __name__ == '__main__': + # Setup the command line arguments. + optp = OptionParser() + + # Output verbosity options. + optp.add_option('-q', '--quiet', help='set logging to ERROR', + action='store_const', dest='loglevel', + const=logging.ERROR, default=logging.INFO) + optp.add_option('-d', '--debug', help='set logging to DEBUG', + action='store_const', dest='loglevel', + const=logging.DEBUG, default=logging.INFO) + optp.add_option('-v', '--verbose', help='set logging to COMM', + action='store_const', dest='loglevel', + const=5, default=logging.INFO) + + # EcheLOn configuration options + optp.add_option('-m', '--domain', help='set EcheLOn domain', + action='store', dest='xdomain', + default="lobby.wildfiregames.com") + optp.add_option('-l', '--login', help='set EcheLOn login', + action='store', dest='xlogin', + default="EcheLOn") + optp.add_option('-p', '--password', help='set EcheLOn password', + action='store', dest='xpassword', + default="XXXXXX") + optp.add_option('-n', '--nickname', help='set EcheLOn nickname', + action='store', dest='xnickname', + default="Ratings") + optp.add_option('-r', '--room', help='set muc room to join', + action='store', dest='xroom', + default="arena") + + # ejabberd server options + optp.add_option('-s', '--server', help='address of the ejabberd server', + action='store', dest='xserver', + default="localhost") + optp.add_option('-t', '--disable-tls', help='Pass this argument to connect without TLS encryption', + action='store_true', dest='xdisabletls', + default=False) + + opts, args = optp.parse_args() + + # Setup logging. + logging.basicConfig(level=opts.loglevel, + format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') + + # EcheLOn + xmpp = EcheLOn(opts.xlogin+'@'+opts.xdomain+'/CC', opts.xpassword, opts.xroom+'@conference.'+opts.xdomain, opts.xnickname) + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0004') # Data Forms + xmpp.register_plugin('xep_0045') # Multi-User Chat # used + xmpp.register_plugin('xep_0060') # PubSub + xmpp.register_plugin('xep_0199') # XMPP Ping + + if xmpp.connect((opts.xserver, 5222), True, not opts.xdisabletls): + xmpp.process(threaded=False) + else: + logging.error("Unable to connect") Property changes on: ps/trunk/source/tools/lobbybots/EcheLOn/EcheLOn.py ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/source/tools/lobbybots/EcheLOn/LobbyRanking.py =================================================================== --- ps/trunk/source/tools/lobbybots/EcheLOn/LobbyRanking.py (nonexistent) +++ ps/trunk/source/tools/lobbybots/EcheLOn/LobbyRanking.py (revision 21926) @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Copyright (C) 2013 Wildfire Games. + * This file is part of 0 A.D. + * + * 0 A.D. is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * 0 A.D. is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with 0 A.D. If not, see . +""" + +import sqlalchemy +from sqlalchemy import Column, ForeignKey, Integer, String, Boolean +from sqlalchemy.orm import relationship, sessionmaker +from sqlalchemy.ext.declarative import declarative_base + +engine = sqlalchemy.create_engine('sqlite:///lobby_rankings.sqlite3') +Session = sessionmaker(bind=engine) +session = Session() +Base = declarative_base() + +class Player(Base): + __tablename__ = 'players' + + id = Column(Integer, primary_key=True) + jid = Column(String(255)) + rating = Column(Integer) + highest_rating = Column(Integer) + games = relationship('Game', secondary='players_info') + # These two relations really only exist to satisfy the linkage + # between PlayerInfo and Player and Game and player. + games_info = relationship('PlayerInfo', backref='player') + games_won = relationship('Game', backref='winner') + +class PlayerInfo(Base): + __tablename__ = 'players_info' + + id = Column(Integer, primary_key=True) + player_id = Column(Integer, ForeignKey('players.id')) + game_id = Column(Integer, ForeignKey('games.id')) + civs = Column(String(20)) + teams = Column(Integer) + economyScore = Column(Integer) + militaryScore = Column(Integer) + totalScore = Column(Integer) + foodGathered = Column(Integer) + foodUsed = Column(Integer) + woodGathered = Column(Integer) + woodUsed = Column(Integer) + stoneGathered = Column(Integer) + stoneUsed = Column(Integer) + metalGathered = Column(Integer) + metalUsed = Column(Integer) + vegetarianFoodGathered = Column(Integer) + treasuresCollected = Column(Integer) + lootCollected = Column(Integer) + tributesSent = Column(Integer) + tributesReceived = Column(Integer) + totalUnitsTrained = Column(Integer) + totalUnitsLost = Column(Integer) + enemytotalUnitsKilled = Column(Integer) + infantryUnitsTrained = Column(Integer) + infantryUnitsLost = Column(Integer) + enemyInfantryUnitsKilled = Column(Integer) + workerUnitsTrained = Column(Integer) + workerUnitsLost = Column(Integer) + enemyWorkerUnitsKilled = Column(Integer) + femaleCitizenUnitsTrained = Column(Integer) + femaleCitizenUnitsLost = Column(Integer) + enemyFemaleCitizenUnitsKilled = Column(Integer) + cavalryUnitsTrained = Column(Integer) + cavalryUnitsLost = Column(Integer) + enemyCavalryUnitsKilled = Column(Integer) + championUnitsTrained = Column(Integer) + championUnitsLost = Column(Integer) + enemyChampionUnitsKilled = Column(Integer) + heroUnitsTrained = Column(Integer) + heroUnitsLost = Column(Integer) + enemyHeroUnitsKilled = Column(Integer) + shipUnitsTrained = Column(Integer) + shipUnitsLost = Column(Integer) + enemyShipUnitsKilled = Column(Integer) + traderUnitsTrained = Column(Integer) + traderUnitsLost = Column(Integer) + enemyTraderUnitsKilled = Column(Integer) + totalBuildingsConstructed = Column(Integer) + totalBuildingsLost = Column(Integer) + enemytotalBuildingsDestroyed = Column(Integer) + civCentreBuildingsConstructed = Column(Integer) + civCentreBuildingsLost = Column(Integer) + enemyCivCentreBuildingsDestroyed = Column(Integer) + houseBuildingsConstructed = Column(Integer) + houseBuildingsLost = Column(Integer) + enemyHouseBuildingsDestroyed = Column(Integer) + economicBuildingsConstructed = Column(Integer) + economicBuildingsLost = Column(Integer) + enemyEconomicBuildingsDestroyed = Column(Integer) + outpostBuildingsConstructed = Column(Integer) + outpostBuildingsLost = Column(Integer) + enemyOutpostBuildingsDestroyed = Column(Integer) + militaryBuildingsConstructed = Column(Integer) + militaryBuildingsLost = Column(Integer) + enemyMilitaryBuildingsDestroyed = Column(Integer) + fortressBuildingsConstructed = Column(Integer) + fortressBuildingsLost = Column(Integer) + enemyFortressBuildingsDestroyed = Column(Integer) + wonderBuildingsConstructed = Column(Integer) + wonderBuildingsLost = Column(Integer) + enemyWonderBuildingsDestroyed = Column(Integer) + woodBought = Column(Integer) + foodBought = Column(Integer) + stoneBought = Column(Integer) + metalBought = Column(Integer) + tradeIncome = Column(Integer) + percentMapExplored = Column(Integer) + +class Game(Base): + __tablename__ = 'games' + + id = Column(Integer, primary_key=True) + map = Column(String(80)) + duration = Column(Integer) + teamsLocked = Column(Boolean) + matchID = Column(String(20)) + winner_id = Column(Integer, ForeignKey('players.id')) + player_info = relationship('PlayerInfo', backref='game') + players = relationship('Player', secondary='players_info') + + +if __name__ == '__main__': + Base.metadata.create_all(engine) + Property changes on: ps/trunk/source/tools/lobbybots/EcheLOn/LobbyRanking.py ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/source/tools/lobbybots/README.md =================================================================== --- ps/trunk/source/tools/lobbybots/README.md (nonexistent) +++ ps/trunk/source/tools/lobbybots/README.md (revision 21926) @@ -0,0 +1,639 @@ +# 0 A.D. / Pyrogenesis Multiplayer Lobby Setup + +This README explains how to setup a custom Pyrogenesis Multiplayer Lobby server that can be used with the Pyrogenesis game. + +## Service description +The Pyrogenesis Multiplayer Lobby consists of three components: + +* **XMPP server: ejabberd**: + The XMPP server provides the platform where users can register accounts, chat in a public room, and can interact with lobby bots. + Currently, ejabberd is the only XMPP server software supported (by the ipstamp module for XpartaMuPP). + +* **Gamelist bot: XpartaMuPP**: + This bot allows players to host and join online multiplayer matches. + It utilizes the ejabberd ipstamp module to inform players of IP addresses of hosting players. + +* **Rating bot: EcheLOn**: + This bot allows players to gain a rating that reflects their skill based on online multiplayer matches. + It is by no means necessary for the operation of a lobby in terms of match-making and chatting. + +## Service choices +Before installing the service, you have to make some decisions: + +#### Choice: Domain Name +Decide on a domain name where the service will be provided. +This document will use `lobby.wildfiregames.com` as an example. +If you intend to use the server only for local testing, you may choose `localhost`. + +#### Choice: Rating service +Decide whether or not you want to employ the rating service. +If you decide to not provide the rating service, you may skip the instructions for the rating bot in this document. + +#### Choice: Pyrogenesis version compatibility +Decide whether you want to support serving multiple Pyrogenesis versions. + +Serving multiple versions of Pyrogenesis allows for seamless version upgrading on the backend and +allows players that don't have the most recent version of Pyrogenesis yet to continue to play until +the new release is available for their platform (applies mostly to linux distributions). + +If you decide to do so, you should use a naming pattern that includes the targetted Pyrogenesis version. +For example to provide a Multiplayer Lobby for Pyrogenesis Alpha 23 "Ken Wood", +name the lobby room `arena23` instead of `arena` and use `xpartamupp23` and `echelon23` as lobby bot names. +Then when a version 24 of Pyrogenesis is employed, you can easily add `arena24`, `xpartamupp24` and `echelon24`. +If you only want to use the service for local testing, you can stick to a single room and a single gamelist and rating bot. + +## 1. Install dependencies + +This section explains how to install the required software on a Debian-based linux distribution. +For other operating systems, use the according package manager or consult the official documentation of the software. + +### 1.1 Install ejabberd + +The version requirement for ejabberd is 17.03 or later (due to the ipstamp module format). + +* Install `ejabberd` using the following command. Alternatively see . + + ``` + $ apt-get install ejabberd + ``` + +* Confirm that the ejabberd version you installed is the one mentioned above or later: + + ``` + $ ejabberdctl status + ``` + +* Configure ejabberd by setting the domain name of your choice and add an `admin` user.: + + ``` + $ dpkg-reconfigure ejabberd + ```` + +You should now be able to connect to this XMPP server using any XMPP client. + +### 1.2 Install python3 and SleekXmpp + +* The lobby bots are programmed in python3 and use SleekXMPP to connect to the lobby. Install these dependencies using: + + ``` + $ apt-get install python3 python3-sleekxmpp + ``` + +* Confirm that the SleekXmpp version is 1.3.1 or later: + + ``` + pip3 show sleekxmpp + ``` + +* If you would like to run the rating bot, you will need to install SQLAlchemy for python3: + + ``` + $ apt-get install python3-sqlalchemy + ``` + +### 1.3 Install ejabberd ipstamp module + +The ejabberd ipstamp module has the purpose of inserting the IP address of the hosting players into the gamelist packet. +That enables players to connect to each others games. + +* Adjust `/etc/ejabberd/ejabberdctl.cfg` and set `CONTRIB_MODULES_PATH` to the directory where you want to store `mod_ipstamp`: + + ``` + CONTRIB_MODULES_PATH=/opt/ejabberd-modules + ``` + +* Ensure the target directory is readable by ejabberd. +* Copy the `mod_ipstamp` directory from `XpartaMuPP/` to `CONTRIB_MODULES_PATH/sources/`. +* Check that the module is available and compatible with your ejabberd: + + ``` + $ ejabberdctl modules_available + $ ejabberdctl module_check mod_ipstamp + ``` + +* Install `mod_ipstamp`: + + ``` + $ ejabberdctl module_install mod_ipstamp + ``` + +## 2. Configure ejabberd mod_ipstamp + +The ejabberd configuration in the remainder of this document is performed by editing `/etc/ejabberd/ejabberd.yml`. +The directory containing this README includes a preconfigured `ejabberd_example.yml` that only needs few setting changes to work with your setup. +For a full documentation of the ejabberd configuration, see . +If something goes wrong with ejabberd, check `/var/log/ejabberd/ejabberd.log` + +* Add `mod_ipstamp` to the modules ejabberd should load: + + ``` + modules: + mod_ipstamp: {} + ``` + +* Reload the ejabberd config. + This should be done every few steps, so that configuration errors can be identified as soon as possible. + + ``` + $ ejabberdctl reload_config + ``` + +## 3. Configure ejabberd connectivity + +The settings in this section ensure that connections can be built where intended, and only where intended. + +### 3.1 Disable IPv6 +* Since the enet library which Pyrogenesis uses for multiplayer mode does not support IPv6, ejabberd must be configured to not use IPv6: + + ``` + listen: + ip: "0.0.0.0" + ``` + +### 3.2 Enable STUN +* ejabberd and Pyrogenesis support the STUN protocol. This allows players to connect to each others games even if the host did not configure +the router and forward the UDP port. Enabling STUN is optional but recommended. + + ``` + listen: + - + port: 3478 + transport: udp + module: ejabberd_stun + ``` + +### 3.3 Enable keep-alive + +* This helps with users becoming disconnected: + + ``` + modules: + mod_ping: + send_pings: true + ``` + +### 3.3 Disable unused services + +* Disable the currently unused server-to-server communication: + + ``` + listen: + ## - + ## port: 5269 + ## ip: "::" + ## module: ejabberd_s2s_in + ``` + +* Protect the administrative webinterface at from external access by disabling or restriction to `localhost`: + + ``` + listen: + - + port: 5280 + ip: "127.0.0.1" + ``` + +* Disable some unused modules: + + ``` + modules: + ## mod_echo: {} + ## mod_irc: {} + ## mod_shared_roster: {} + ## mod_vcard: {} + ## mod_vcard_xupdate: {} + ``` + +### 3.4 Setup TLS encryption + +Depending on whether you use the server for a player audience or only for local testing, +you may have to either obtain and install a certificate with ejabberd or disable TLS encryption. + +#### Choice A: No encryption +* If you intend to use the server solely for local testing, you may disable TLS encryption in the ejabberd config: + + ``` + listen: + starttls_required: false + ``` + +#### Choice B: Self-signed certificate + +If you want to use the server for local testing only, you may use a self-signed certificate to test encryption. +Notice the lobby bots currently reject self-signed certificates. + +* Enable TLS over the default port: + ``` + listen: + starttls: true + ``` + +* Create the key file for certificate: + + ``` + openssl genrsa -out key.pem 2048 + ``` +* Create the certificate file. “common name” should match the domainname. + + ``` + openssl req -new -key key.pem -out request.pem + ``` + +* Sign the certificate: + + ``` + openssl x509 -req -days 900 -in request.pem -signkey key.pem -out certificate.pem + ``` + +* Store it as the ejabberd certificate: + + ``` + $ cat key.pem request.pem > /etc/ejabberd/ejabberd.pem + ``` + +#### Choice C: Let's Encrypt certificate +To secure user authentication and communication with modern encryption and to comply with privacy laws, +ejabberd should be configured to use TLS with a proper, trusted certificate. + +* A free, valid, and trusted TLS certificate may be obtained from some certificate authorites, such as Let's Encrypt: + + + +* Enable TLS over the default port: + ``` + listen: + starttls: true + ``` + +* Setup the contact address if Let's Encrypt found an authentication issue: + + ``` + acme: + contact: "mailto:admin@example.com" + ``` + +* Ensure old, vulnerable SSL/TLS protocols are disabled: + + ``` + define_macro: + 'TLS_OPTIONS': + - "no_sslv2" + - "no_sslv3" + - "no_tlsv1" + ``` + +## 3. Configure ejabberd use policy + +The settings in this section grant or restrict user access rights. + +* Prevent the rooms from being destroyed if the last client leaves it: + + ``` + access_rules: + muc_admin: + - allow: admin + modules: + mod_muc: + access_persistent: muc_admin + default_room_options: + persistent: true + ``` + +* Allow users to create accounts using the game via in-band registration. + ``` + access_rules: + register: + - all: allow + ``` + +### Optional use policies + +* (Optional) It is recommended to restrict usernames to alphanumeric characters (so that playernames are easily typeable for every participant). + The username may be restricted in length (because very long usernames are uncomfortably time-consuming to read and may not fit into the playername fields). + Notice the username regex below is also used by the 0 A.D. client to indicate invalid names to the user. + ``` + acl: + validname: + user_regexp: "^[0-9A-Za-z._-]{1,20}$" + + access_rules: + register: + - allow: validname + + modules: + mod_register: + access: register + ``` + +* (Optional) Prevent users from creating new rooms: + + ``` + modules: + mod_muc: + access_create: muc_admin + ``` + +* (Optional) Increase the maximum number of users from the default 200: + + ``` + mod_muc: + max_users: 5000 + default_room_options: + max_users: 1000 + ``` + +* (Optional) Prevent users from sending too large stanzas. + Notice the bots can send large stanzas as well, so don't restrict it too much. + + ``` + max_stanza_size: 1048576 + ``` + + +* (Optional) Prevent users from changing the room topic: + + ``` + mod_muc: + default_room_options: + allow_change_subj: false + ``` + +* (Optional) Prevent malicious users from registering new accounts quickly if they were banned. + Notice this also prevents players using the same internet router from registering for that time if they want to play together. + + ``` + registration_timeout: 3600 + ``` + +* (Optional) Enable room chatlogging. + Make sure to mention this collection and the purposes in the Terms and Conditions to comply with personal data laws. + Ensure that ejabberd has write access to the given folder. + Notice that `ejabberd.service` by default prevents write access to some directories (PrivateTmp, ProtectHome, ProtectSystem). + + ``` + modules: + mod_muc_log: + outdir: "/lobby/logs" + file_format: plaintext + timezone: universal + mod_muc: + default_room_options: + logging: true + ``` + +* (Optional) Grant specific moderators administrator rights to see the IP address of a user: + See also `https://xmpp.org/extensions/xep-0133.html#get-user-stats`. + + ``` + acl: + admin: + user: + - "username@lobby.wildfiregames.com" + ``` + +* (Optional) Grant specific moderators to : + See also `https://xmpp.org/extensions/xep-0133.html#get-user-stats`. + + ``` + modules: + mod_muc: + access_admin: muc_admin + ``` + +* (Optional) Ban specific IP addresses or subnet masks for persons that create new accounts after having been banned from the room: + + ``` + acl: + blocked: + ip: + - "12.34.56.78" + - "12.34.56.0/8" + - "12.34.0.0/16" + ... + access_rules: + c2s: + - deny: blocked + - allow + register: + - deny: blocked + - allow + ``` + +## 4. Setup lobby bots + +### 4.1 Register lobby bot accounts + +* Check list of registered users: + + ``` + $ ejabberdctl registered_users lobby.wildfiregames.com + ``` + +* Register the accounts of the lobby bots. + The rating account is only needed if you decided to enable the rating service. + + ``` + $ ejabberdctl register echelon23 lobby.wildfiregames.com secure_password + $ ejabberdctl register xpartamupp23 lobby.wildfiregames.com secure_password + ``` + +### 4.2 Authorize lobby bots to see real JIDs + +* The bots need to be able to see real JIDs of users. + So either the room must be configured as non-anonymous, i.e. real JIDs are visible to all users of the room, + or the bots need to receive muc administrator rights. + +#### Choice A: Non-anonymous room +* (Recommended) This method has the advantage that bots do not gain administrative access that they don't use. + The only possible downside is that room users may not hide their username behind arbitrary nicknames anymore. + + ``` + modules: + mod_muc: + default_room_options: + anonymous: false + +#### Choice B: Non-anonymous room +* If you for any reason wish to configure the room as semi-anonymous (only muc administrators can see real JIDs), + then the bots need to be authorized as muc administrators: + + ``` + access_rules: + muc_admin: + - allow: bots + + modules: + mod_muc: + access_admin: muc_admin + ``` + +### 4.3 Authorize lobby bots with ejabberd + +* The bots need an ACL to be able to get the IPs of users hosting a match (which is what `mod_ipstamp` does). + + ``` + acl: + ## Don't use a regex, to prevent others from obtaining permissions after registering such an account. + bots: + - user: "xpartamupp23@lobby.wildfiregames.com" + - user: "echelon23@lobby.wildfiregames.com" + ``` + +* Add an access rule for `ipbots` and a rule allowing bots to create PubSub nodes: + + ``` + access_rules: + ## Expected by the ipstamp module for XpartaMuPP + ipbots: + - allow: bots + + pubsub_createnode: + - allow: bots + ``` + +* Due to the amount of traffic the bot may process, give the group containing bots either unlimited + or a very high traffic shaper: + + ``` + shaper_rules: + c2s_shaper: + - none: admin, bots + - normal + ``` + +* Finally reload ejabberd's configuration: + + ``` + $ ejabberdctl reload_config + ``` + +### 4.4 Running XpartaMuPP - XMPP Multiplayer Game Manager + +* Execute the following command to run the gamelist bot: + + ``` + $ python3 XpartaMuPP.py --domain lobby.wildfiregames.com --login xpartamupp23 --password XXXXXX --nickname GamelistBot --room arena --elo echelon23 + ``` + +If you want to run XpartaMuPP without a rating bot, the `--elo` argument should be omitted. +Pass `--disable-tls` if you did not setup valid TLS encryption on the server. +Run `python3 XpartaMuPP.py --help` for the full list of options + +* If the connection and authentication succeeded, you should see the following messages in the console: + + ``` + INFO JID set to: xpartamupp23@lobby.wildfiregames.com/CC + INFO XpartaMuPP started + ``` + +### 4.5 Running EcheLOn - XMPP Multiplayer Rating Manager + +This bot can be thought of as a module of XpartaMuPP in that IQs stanzas sent to XpartaMuPP are +forwarded onto EcheLOn if its corresponding EcheLOn is online and ignored otherwise. +EcheLOn handles all aspects of operation related to ELO, the chess rating system invented by Arpad Elo. +Players gain a rating after a rated 1v1 match. +The score difference after a completed match is relative to the rating difference of the players. + +* (Optional) Some constants of the algorithm may be edited by experienced administrators at the head of `ELO.py`: + + ``` + # Difference between two ratings such that it is + # regarded as a "sure win" for the higher player. + # No points are gained or lost for such a game. + elo_sure_win_difference = 600.0 + + # Lower ratings "move faster" and change more + # dramatically than higher ones. Anything rating above + # this value moves at the same rate as this value. + elo_k_factor_constant_rating = 2200.0 + ``` + +* To initialize the `lobby_rankings.sqlite3` database, execute the following command: + + ``` + $ python3 LobbyRanking.py + ``` + +* Execute the following command to run the rating bot: + + ``` + $ python3 EcheLOn.py --domain lobby.wildfiregames.com --login echelon23 --password XXXXXX --nickname RatingBot --room arena23 + ``` + +Run `python3 EcheLOn.py --help` for the full list of options + +## 5. Configure Pyrogenesis for the new Multiplayer Lobby + +The Pyrogenesis client is now going to be configured to become able to connect to the new Multiplayer Lobby. + +The Pyrogenesis documentation of configuration files can be found at . +Available Pyrogenesis configuration settings are specified in `default.cfg`, see . + +### 5.1 Local Configuration + + * Visit to identify the local user's Pyrogenesis configuration path depending on the operating system. + + * Create or open `local.cfg` in the configuration path. + + * Add the following settings that determine the lobby server connection: + + ``` + lobby.room = "arena23" ; Default MUC room to join + lobby.server = "lobby.wildfiregames.com" ; Address of lobby server + lobby.stun.server = "lobby.wildfiregames.com" ; Address of the STUN server. + lobby.require_tls = true ; Whether to reject connecting to the lobby if TLS encryption is unavailable. + lobby.verify_certificate = true ; Whether to reject connecting to the lobby if the TLS certificate is invalid. + lobby.xpartamupp = "xpartamupp23" ; Name of the server-side XMPP-account that manage games + lobby.echelon = "echelon23" ; Name of the server-side XMPP-account that manages ratings + ``` + + If you disabled TLS encryption, set `require_tls` to `false`. + If you employed a self-signed certificate, set `verify_certificate` to `false`. + +### 5.2 Test the Multiplayer Lobby + +You should now be able to join the new multiplayer lobby with the Pyrogenesis client and play multiplayer matches. + +* To confirm that the match hosting works as intended, create two user accounts, host a game with one, join the game with the other account. + +* To confirm that the rating service works as intended, resign a rated 1v1 match with two accounts. + +### 5.3 Terms and Conditions + +Players joining public servers are subject to Terms and Conditions of the service provider and subject to privacy laws such as GDPR. +If you intend to use the server only for local testing, you may skip this step. + +* The following files should be created by the service provider: + + `Terms_of_Service.txt` to explain the service and the contract. + `Terms_of_Use.txt` to explain what the user should and should not do. + `Privacy_Policy.txt` to explain how personal data is handled. + +* To use Wildfire Games Terms as a template, obtain our Terms from a copy of the game or from or from + + +* Replace all occurrences of `Wildfire Games` in the files with the one providing the new server. + +* Update the `Terms_of_Use.txt` depending on which behavior you would like to (not) see on your service. + +* Update the `Privacy_Policy.txt` depending on the user data processing in relation to the usage policies. +Make sure to not violate privacy laws such as GDPR or COPPA while doing so. + +* The retention times of ejabberd logs are relevant to GDPR. +Visit for details. + +* The terms should be published online, so users can save and print them. + Add to your `local.cfg`: + + ``` + lobby.terms_url = "https://lobby.wildfiregames.com/terms/"; Allows the user to save the text and print the terms + ``` + +### 5.4 Distribute the configuration + +To make this a public server, distribute your `local.cfg`, `Terms_of_Service.txt`, `Terms_of_Use.txt`, `Privacy_Policy.txt`. + +It may be advisable to create a mod with a modified `default.cfg` and the new terms documents, +see . + +Congratulations, you are now running a custom Pyrogenesis Multiplayer Lobby! Property changes on: ps/trunk/source/tools/lobbybots/README.md ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/source/tools/lobbybots/XpartaMuPP/XpartaMuPP.py =================================================================== --- ps/trunk/source/tools/lobbybots/XpartaMuPP/XpartaMuPP.py (nonexistent) +++ ps/trunk/source/tools/lobbybots/XpartaMuPP/XpartaMuPP.py (revision 21926) @@ -0,0 +1,663 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Copyright (C) 2018 Wildfire Games. + * This file is part of 0 A.D. + * + * 0 A.D. is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * 0 A.D. is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with 0 A.D. If not, see . +""" + +import logging, time, traceback +from optparse import OptionParser + +import sleekxmpp +from sleekxmpp.stanza import Iq +from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin, ET +from sleekxmpp.xmlstream.handler import Callback +from sleekxmpp.xmlstream.matcher import StanzaPath + +## Class to tracks all games in the lobby ## +class GameList(): + def __init__(self): + self.gameList = {} + def addGame(self, JID, data): + """ + Add a game + """ + data['players-init'] = data['players'] + data['nbp-init'] = data['nbp'] + data['state'] = 'init' + self.gameList[str(JID)] = data + def removeGame(self, JID): + """ + Remove a game attached to a JID + """ + del self.gameList[str(JID)] + def getAllGames(self): + """ + Returns all games + """ + return self.gameList + def changeGameState(self, JID, data): + """ + Switch game state between running and waiting + """ + JID = str(JID) + if JID in self.gameList: + if self.gameList[JID]['nbp-init'] > data['nbp']: + logging.debug("change game (%s) state from %s to %s", JID, self.gameList[JID]['state'], 'waiting') + self.gameList[JID]['state'] = 'waiting' + else: + logging.debug("change game (%s) state from %s to %s", JID, self.gameList[JID]['state'], 'running') + self.gameList[JID]['state'] = 'running' + self.gameList[JID]['nbp'] = data['nbp'] + self.gameList[JID]['players'] = data['players'] + if 'startTime' not in self.gameList[JID]: + self.gameList[JID]['startTime'] = str(round(time.time())) + +## Class for custom player stanza extension ## +class PlayerXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:player' + interfaces = set(('online')) + sub_interfaces = interfaces + plugin_attrib = 'player' + + def addPlayerOnline(self, player): + playerXml = ET.fromstring("%s" % player) + self.xml.append(playerXml) + +## Class for custom gamelist stanza extension ## +class GameListXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:gamelist' + interfaces = set(('game', 'command')) + sub_interfaces = interfaces + plugin_attrib = 'gamelist' + + def addGame(self, data): + itemXml = ET.Element("game", data) + self.xml.append(itemXml) + + def getGame(self): + """ + Required to parse incoming stanzas with this + extension. + """ + game = self.xml.find('{%s}game' % self.namespace) + data = {} + for key, item in game.items(): + data[key] = item + return data + +## Class for custom boardlist and ratinglist stanza extension ## +class BoardListXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:boardlist' + interfaces = set(('board', 'command', 'recipient')) + sub_interfaces = interfaces + plugin_attrib = 'boardlist' + def addCommand(self, command): + commandXml = ET.fromstring("%s" % command) + self.xml.append(commandXml) + def addRecipient(self, recipient): + recipientXml = ET.fromstring("%s" % recipient) + self.xml.append(recipientXml) + def addItem(self, name, rating): + itemXml = ET.Element("board", {"name": name, "rating": rating}) + self.xml.append(itemXml) + +## Class for custom gamereport stanza extension ## +class GameReportXmppPlugin(ElementBase): + name = 'report' + namespace = 'jabber:iq:gamereport' + plugin_attrib = 'gamereport' + interfaces = ('game', 'sender') + sub_interfaces = interfaces + def addSender(self, sender): + senderXml = ET.fromstring("%s" % sender) + self.xml.append(senderXml) + def addGame(self, gr): + game = ET.fromstring(str(gr)).find('{%s}game' % self.namespace) + self.xml.append(game) + def getGame(self): + """ + Required to parse incoming stanzas with this + extension. + """ + game = self.xml.find('{%s}game' % self.namespace) + data = {} + for key, item in game.items(): + data[key] = item + return data + +## Class for custom profile ## +class ProfileXmppPlugin(ElementBase): + name = 'query' + namespace = 'jabber:iq:profile' + interfaces = set(('profile', 'command', 'recipient')) + sub_interfaces = interfaces + plugin_attrib = 'profile' + def addCommand(self, command): + commandXml = ET.fromstring("%s" % command) + self.xml.append(commandXml) + def addRecipient(self, recipient): + recipientXml = ET.fromstring("%s" % recipient) + self.xml.append(recipientXml) + def addItem(self, player, rating, highestRating, rank, totalGamesPlayed, wins, losses): + itemXml = ET.Element("profile", {"player": player, "rating": rating, "highestRating": highestRating, + "rank" : rank, "totalGamesPlayed" : totalGamesPlayed, "wins" : wins, + "losses" : losses}) + self.xml.append(itemXml) + +## Main class which handles IQ data and sends new data ## +class XpartaMuPP(sleekxmpp.ClientXMPP): + """ + A simple list provider + """ + def __init__(self, sjid, password, room, nick, ratingsbot): + sleekxmpp.ClientXMPP.__init__(self, sjid, password) + self.sjid = sjid + self.room = room + self.nick = nick + self.ratingsBotWarned = False + + self.ratingsBot = ratingsbot + # Game collection + self.gameList = GameList() + + # Store mapping of nicks and XmppIDs, attached via presence stanza + self.nicks = {} + self.presences = {} # Obselete when XEP-0060 is implemented. + + self.lastLeft = "" + + register_stanza_plugin(Iq, PlayerXmppPlugin) + register_stanza_plugin(Iq, GameListXmppPlugin) + register_stanza_plugin(Iq, BoardListXmppPlugin) + register_stanza_plugin(Iq, GameReportXmppPlugin) + register_stanza_plugin(Iq, ProfileXmppPlugin) + + self.register_handler(Callback('Iq Player', + StanzaPath('iq/player'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq Gamelist', + StanzaPath('iq/gamelist'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq Boardlist', + StanzaPath('iq/boardlist'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq GameReport', + StanzaPath('iq/gamereport'), + self.iqhandler, + instream=True)) + self.register_handler(Callback('Iq Profile', + StanzaPath('iq/profile'), + self.iqhandler, + instream=True)) + + self.add_event_handler("session_start", self.start) + self.add_event_handler("muc::%s::got_online" % self.room, self.muc_online) + self.add_event_handler("muc::%s::got_offline" % self.room, self.muc_offline) + self.add_event_handler("groupchat_message", self.muc_message) + self.add_event_handler("changed_status", self.presence_change) + + def start(self, event): + """ + Process the session_start event + """ + self.plugin['xep_0045'].joinMUC(self.room, self.nick) + self.send_presence() + self.get_roster() + logging.info("XpartaMuPP started") + + def muc_online(self, presence): + """ + Process presence stanza from a chat room. + """ + if self.ratingsBot in self.nicks: + self.relayRatingListRequest(self.ratingsBot) + self.relayPlayerOnline(presence['muc']['jid']) + if presence['muc']['nick'] != self.nick: + # If it doesn't already exist, store player JID mapped to their nick. + if str(presence['muc']['jid']) not in self.nicks: + self.nicks[str(presence['muc']['jid'])] = presence['muc']['nick'] + self.presences[str(presence['muc']['jid'])] = "available" + # Check the jid isn't already in the lobby. + # Send Gamelist to new player. + self.sendGameList(presence['muc']['jid']) + logging.debug("Client '%s' connected with a nick of '%s'." %(presence['muc']['jid'], presence['muc']['nick'])) + + def muc_offline(self, presence): + """ + Process presence stanza from a chat room. + """ + # Clean up after a player leaves + if presence['muc']['nick'] != self.nick: + # Delete any games they were hosting. + for JID in self.gameList.getAllGames(): + if JID == str(presence['muc']['jid']): + self.gameList.removeGame(JID) + self.sendGameList() + break + # Remove them from the local player list. + self.lastLeft = str(presence['muc']['jid']) + if str(presence['muc']['jid']) in self.nicks: + del self.nicks[str(presence['muc']['jid'])] + del self.presences[str(presence['muc']['jid'])] + if presence['muc']['nick'] == self.ratingsBot: + self.ratingsBotWarned = False + + def muc_message(self, msg): + """ + Process new messages from the chatroom. + """ + if msg['mucnick'] != self.nick and self.nick.lower() in msg['body'].lower(): + self.send_message(mto=msg['from'].bare, + mbody="I am the administrative bot in this lobby and cannot participate in any games.", + mtype='groupchat') + + def presence_change(self, presence): + """ + Processes presence change + """ + prefix = "%s/" % self.room + nick = str(presence['from']).replace(prefix, "") + for JID in self.nicks: + if self.nicks[JID] == nick: + if self.presences[JID] == 'dnd' and (str(presence['type']) == "available" or str(presence['type']) == "away"): + self.sendGameList(JID) + self.relayBoardListRequest(JID) + self.presences[JID] = str(presence['type']) + break + + + def iqhandler(self, iq): + """ + Handle the custom stanzas + This method should be very robust because we could receive anything + """ + if iq['type'] == 'error': + logging.error('iqhandler error' + iq['error']['condition']) + #self.disconnect() + elif iq['type'] == 'get': + """ + Request lists. + """ + # Send lists/register on leaderboard; depreciated once muc_online + # can send lists/register automatically on joining the room. + if 'boardlist' in iq.loaded_plugins: + command = iq['boardlist']['command'] + try: + self.relayBoardListRequest(iq['from']) + except: + traceback.print_exc() + logging.error("Failed to process leaderboardlist request from %s" % iq['from'].bare) + elif 'profile' in iq.loaded_plugins: + command = iq['profile']['command'] + try: + self.relayProfileRequest(iq['from'], command) + except: + pass + else: + logging.error("Unknown 'get' type stanza request from %s" % iq['from'].bare) + elif iq['type'] == 'result': + """ + Iq successfully received + """ + if 'boardlist' in iq.loaded_plugins: + recipient = iq['boardlist']['recipient'] + self.relayBoardList(iq['boardlist'], recipient) + elif 'profile' in iq.loaded_plugins: + recipient = iq['profile']['recipient'] + player = iq['profile']['command'] + self.relayProfile(iq['profile'], player, recipient) + else: + pass + elif iq['type'] == 'set': + if 'gamelist' in iq.loaded_plugins: + """ + Register-update / unregister a game + """ + command = iq['gamelist']['command'] + if command == 'register': + # Add game + try: + if iq['from'] in self.nicks: + self.gameList.addGame(iq['from'], iq['gamelist']['game']) + self.sendGameList() + except: + traceback.print_exc() + logging.error("Failed to process game registration data") + elif command == 'unregister': + # Remove game + try: + self.gameList.removeGame(iq['from']) + self.sendGameList() + except: + traceback.print_exc() + logging.error("Failed to process game unregistration data") + + elif command == 'changestate': + # Change game status (waiting/running) + try: + self.gameList.changeGameState(iq['from'], iq['gamelist']['game']) + self.sendGameList() + except: + traceback.print_exc() + logging.error("Failed to process changestate data. Trying to add game") + try: + if iq['from'] in self.nicks: + self.gameList.addGame(iq['from'], iq['gamelist']['game']) + self.sendGameList() + except: + pass + else: + logging.error("Failed to process command '%s' received from %s" % command, iq['from'].bare) + elif 'gamereport' in iq.loaded_plugins: + """ + Client is reporting end of game statistics + """ + try: + self.relayGameReport(iq['gamereport'], iq['from']) + except: + traceback.print_exc() + logging.error("Failed to update game statistics for %s" % iq['from'].bare) + else: + logging.error("Failed to process stanza type '%s' received from %s" % iq['type'], iq['from'].bare) + + def sendGameList(self, to = ""): + """ + Send a massive stanza with the whole game list. + If no target is passed the gamelist is broadcasted + to all clients. + """ + games = self.gameList.getAllGames() + + stz = GameListXmppPlugin() + + ## Pull games and add each to the stanza + for JIDs in games: + g = games[JIDs] + stz.addGame(g) + + ## Set additional IQ attributes + iq = self.Iq() + iq['type'] = 'result' + iq.setPayload(stz) + if to == "": + for JID in list(self.presences): + if self.presences[JID] != "available" and self.presences[JID] != "away": + continue + iq['to'] = JID + + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send game list") + else: + ## Check recipient exists + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send gamelist to." % str(to)) + return + iq['to'] = to + + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send game list") + + def relayBoardListRequest(self, recipient): + """ + Send a boardListRequest to EcheLOn. + """ + to = self.ratingsBot + if to not in self.nicks: + self.warnRatingsBotOffline() + return + stz = BoardListXmppPlugin() + iq = self.Iq() + iq['type'] = 'get' + stz.addCommand('getleaderboard') + stz.addRecipient(recipient) + iq.setPayload(stz) + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send leaderboard list request") + + def relayRatingListRequest(self, recipient): + """ + Send a ratingListRequest to EcheLOn. + """ + to = self.ratingsBot + if to not in self.nicks: + self.warnRatingsBotOffline() + return + stz = BoardListXmppPlugin() + iq = self.Iq() + iq['type'] = 'get' + stz.addCommand('getratinglist') + iq.setPayload(stz) + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send rating list request") + + def relayProfileRequest(self, recipient, player): + """ + Send a profileRequest to EcheLOn. + """ + to = self.ratingsBot + if to not in self.nicks: + self.warnRatingsBotOffline() + return + stz = ProfileXmppPlugin() + iq = self.Iq() + iq['type'] = 'get' + stz.addCommand(player) + stz.addRecipient(recipient) + iq.setPayload(stz) + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send profile request") + + def relayPlayerOnline(self, jid): + """ + Tells EcheLOn that someone comes online. + """ + ## Check recipient exists + to = self.ratingsBot + if to not in self.nicks: + return + stz = PlayerXmppPlugin() + iq = self.Iq() + iq['type'] = 'set' + stz.addPlayerOnline(jid) + iq.setPayload(stz) + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send player muc online") + + def relayGameReport(self, data, sender): + """ + Relay a game report to EcheLOn. + """ + to = self.ratingsBot + if to not in self.nicks: + self.warnRatingsBotOffline() + return + stz = GameReportXmppPlugin() + stz.addGame(data) + stz.addSender(sender) + iq = self.Iq() + iq['type'] = 'set' + iq.setPayload(stz) + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send game report request") + + def relayBoardList(self, boardList, to = ""): + """ + Send the whole leaderboard list. + If no target is passed the boardlist is broadcasted + to all clients. + """ + iq = self.Iq() + iq['type'] = 'result' + iq.setPayload(boardList) + ## Check recipient exists + if to == "": + # Rating List + for JID in list(self.presences): + if self.presences[JID] != "available" and self.presences[JID] != "away": + continue + ## Set additional IQ attributes + iq['to'] = JID + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send rating list") + else: + # Leaderboard or targeted rating list + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send boardlist to" % str(to)) + return + ## Set additional IQ attributes + iq['to'] = to + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + logging.error("Failed to send leaderboard list") + + def relayProfile(self, data, player, to): + """ + Send the player profile to a specified target. + """ + if to == "": + logging.error("Failed to send profile, target unspecified") + return + + iq = self.Iq() + iq['type'] = 'result' + iq.setPayload(data) + ## Check recipient exists + if str(to) not in self.nicks: + logging.error("No player with the XmPP ID '%s' known to send profile to" % str(to)) + return + + ## Set additional IQ attributes + iq['to'] = to + + ## Try sending the stanza + try: + iq.send(block=False, now=True) + except: + traceback.print_exc() + logging.error("Failed to send profile") + + def warnRatingsBotOffline(self): + """ + Warns that the ratings bot is offline. + """ + if not self.ratingsBotWarned: + logging.warn("Ratings bot '%s' is offline" % str(self.ratingsBot)) + self.ratingsBotWarned = True + +## Main Program ## +if __name__ == '__main__': + # Setup the command line arguments. + optp = OptionParser() + + # Output verbosity options. + optp.add_option('-q', '--quiet', help='set logging to ERROR', + action='store_const', dest='loglevel', + const=logging.ERROR, default=logging.INFO) + optp.add_option('-d', '--debug', help='set logging to DEBUG', + action='store_const', dest='loglevel', + const=logging.DEBUG, default=logging.INFO) + optp.add_option('-v', '--verbose', help='set logging to COMM', + action='store_const', dest='loglevel', + const=5, default=logging.INFO) + + # XpartaMuPP configuration options + optp.add_option('-m', '--domain', help='set xpartamupp domain', + action='store', dest='xdomain', + default="lobby.wildfiregames.com") + optp.add_option('-l', '--login', help='set xpartamupp login', + action='store', dest='xlogin', + default="xpartamupp") + optp.add_option('-p', '--password', help='set xpartamupp password', + action='store', dest='xpassword', + default="XXXXXX") + optp.add_option('-n', '--nickname', help='set xpartamupp nickname', + action='store', dest='xnickname', + default="WFGbot") + optp.add_option('-r', '--room', help='set muc room to join', + action='store', dest='xroom', + default="arena") + optp.add_option('-e', '--elo', help='set rating bot username', + action='store', dest='xratingsbot', + default="disabled") + + # ejabberd server options + optp.add_option('-s', '--server', help='address of the ejabberd server', + action='store', dest='xserver', + default="localhost") + optp.add_option('-t', '--disable-tls', help='Pass this argument to connect without TLS encryption', + action='store_true', dest='xdisabletls', + default=False) + + opts, args = optp.parse_args() + + # Setup logging. + logging.basicConfig(level=opts.loglevel, + format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') + + # XpartaMuPP + xmpp = XpartaMuPP(opts.xlogin+'@'+opts.xdomain+'/CC', opts.xpassword, opts.xroom+'@conference.'+opts.xdomain, opts.xnickname, opts.xratingsbot+'@'+opts.xdomain+'/CC') + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0004') # Data Forms + xmpp.register_plugin('xep_0045') # Multi-User Chat # used + xmpp.register_plugin('xep_0060') # PubSub + xmpp.register_plugin('xep_0199') # XMPP Ping + + if xmpp.connect((opts.xserver, 5222), True, not opts.xdisabletls): + xmpp.process(threaded=False) + else: + logging.error("Unable to connect") Property changes on: ps/trunk/source/tools/lobbybots/XpartaMuPP/XpartaMuPP.py ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Index: ps/trunk/source/tools/lobbybots/ejabberd_example.yml =================================================================== --- ps/trunk/source/tools/lobbybots/ejabberd_example.yml (nonexistent) +++ ps/trunk/source/tools/lobbybots/ejabberd_example.yml (revision 21926) @@ -0,0 +1,855 @@ +### +###' ejabberd configuration file +### +### + +### The parameters used in this configuration file are explained in more detail +### in the ejabberd Installation and Operation Guide. +### Please consult the Guide in case of doubts, it is included with +### your copy of ejabberd, and is also available online at +### http://www.process-one.net/en/ejabberd/docs/ + +### The configuration file is written in YAML. +### Refer to http://en.wikipedia.org/wiki/YAML for the brief description. +### However, ejabberd treats different literals as different types: +### +### - unquoted or single-quoted strings. They are called "atoms". +### Example: dog, 'Jupiter', '3.14159', YELLOW +### +### - numeric literals. Example: 3, -45.0, .0 +### +### - quoted or folded strings. +### Examples of quoted string: "Lizzard", "orange". +### Example of folded string: +### > Art thou not Romeo, +### and a Montague? +--- +###. ======= +###' LOGGING + +## +## loglevel: Verbosity of log files generated by ejabberd. +## 0: No ejabberd log at all (not recommended) +## 1: Critical +## 2: Error +## 3: Warning +## 4: Info +## 5: Debug +## +loglevel: 4 + +## +## rotation: Disable ejabberd's internal log rotation, as the Debian package +## uses logrotate(8). +log_rotate_size: 0 +log_rotate_date: "" + +## +## overload protection: If you want to limit the number of messages per second +## allowed from error_logger, which is a good idea if you want to avoid a flood +## of messages when system is overloaded, you can set a limit. +## 100 is ejabberd's default. +log_rate_limit: 100 + +## +## watchdog_admins: Only useful for developers: if an ejabberd process +## consumes a lot of memory, send live notifications to these XMPP +## accounts. +## +## watchdog_admins: +## - "bob@example.com" + +###. =============== +###' NODE PARAMETERS + +## +## net_ticktime: Specifies net_kernel tick time in seconds. This options must have +## identical value on all nodes, and in most cases shouldn't be changed at all from +## default value. +## +## net_ticktime: 60 + +###. ================ +###' SERVED HOSTNAMES + +## +## hosts: Domains served by ejabberd. +## You can define one or several, for example: +## hosts: +## - "example.net" +## - "example.com" +## - "example.org" +## +hosts: + - "localhost" + +## +## route_subdomains: Delegate subdomains to other XMPP servers. +## For example, if this ejabberd serves example.org and you want +## to allow communication with an XMPP server called im.example.org. +## +## route_subdomains: s2s + +###. ============ +###' Certificates + +## List all available PEM files containing certificates for your domains, +## chains of certificates or certificate keys. Full chains will be built +## automatically by ejabberd. +## +certfiles: + - "/etc/ejabberd/ejabberd.pem" + +## If your system provides only a single CA file (CentOS/FreeBSD): +## ca_file: "/etc/ssl/certs/ca-bundle.pem" + +###. ================= +###' TLS configuration + +## Note that the following configuration is the default +## configuration of the TLS driver, so you don't need to +## uncomment it. +## +define_macro: + 'TLS_CIPHERS': "HIGH:!aNULL:!eNULL:!3DES:@STRENGTH" + 'TLS_OPTIONS': + - "no_sslv2" + - "no_sslv3" + - "no_tlsv1" + - "cipher_server_preference" + - "no_compression" + ## 'DH_FILE': "/path/to/dhparams.pem" # generated with: openssl dhparam -out dhparams.pem 2048 + +## c2s_dhfile: 'DH_FILE' +## s2s_dhfile: 'DH_FILE' +c2s_ciphers: 'TLS_CIPHERS' +s2s_ciphers: 'TLS_CIPHERS' +c2s_protocol_options: 'TLS_OPTIONS' +s2s_protocol_options: 'TLS_OPTIONS' + +###. =============== +###' LISTENING PORTS + +## +## listen: The ports ejabberd will listen on, which service each is handled +## by and what options to start it with. +## +listen: + - + port: 5222 + ip: "0.0.0.0" + module: ejabberd_c2s + starttls: true + starttls_required: false + protocol_options: 'TLS_OPTIONS' + max_stanza_size: 1048576 + shaper: c2s_shaper + access: c2s + + ## port: 5269 + ## ip: "::" + ## module: ejabberd_s2s_in + + - + port: 5280 + ip: "127.0.0.1" + module: ejabberd_http + request_handlers: + "/ws": ejabberd_http_ws + "/bosh": mod_bosh + "/api": mod_http_api + ## "/pub/archive": mod_http_fileserver + web_admin: true + ## register: true + ## captcha: true + tls: true + protocol_options: 'TLS_OPTIONS' + + ## + ## ejabberd_service: Interact with external components (transports, ...) + ## + ## - + ## port: 8888 + ## ip: "::" + ## module: ejabberd_service + ## access: all + ## shaper_rule: fast + ## ip: "127.0.0.1" + ## privilege_access: + ## roster: "both" + ## message: "outgoing" + ## presence: "roster" + ## delegations: + ## "urn:xmpp:mam:1": + ## filtering: ["node"] + ## "http://jabber.org/protocol/pubsub": + ## filtering: [] + ## hosts: + ## "icq.example.org": + ## password: "secret" + ## "sms.example.org": + ## password: "secret" + + ## + ## ejabberd_stun: Handles STUN Binding requests + ## + - + port: 3478 + transport: udp + module: ejabberd_stun + + ## + ## To handle XML-RPC requests that provide admin credentials: + ## + ## - + ## port: 4560 + ## ip: "::" + ## module: ejabberd_xmlrpc + ## maxsessions: 10 + ## timeout: 5000 + ## access_commands: + ## admin: + ## commands: all + ## options: [] + + ## + ## To enable secure http upload + ## + ## - + ## port: 5444 + ## ip: "::" + ## module: ejabberd_http + ## request_handlers: + ## "": mod_http_upload + ## tls: true + ## protocol_options: 'TLS_OPTIONS' + ## dhfile: 'DH_FILE' + ## ciphers: 'TLS_CIPHERS' + +## Disabling digest-md5 SASL authentication. digest-md5 requires plain-text +## password storage (see auth_password_format option). +disable_sasl_mechanisms: "digest-md5" + +###. ================== +###' S2S GLOBAL OPTIONS + +## +## s2s_use_starttls: Enable STARTTLS for S2S connections. +## Allowed values are: false, optional or required +## You must specify 'certfiles' option +## +s2s_use_starttls: required + +## +## S2S whitelist or blacklist +## +## Default s2s policy for undefined hosts. +## +## s2s_access: s2s + +## +## Outgoing S2S options +## +## Preferred address families (which to try first) and connect timeout +## in seconds. +## +## outgoing_s2s_families: +## - ipv4 +## - ipv6 +## outgoing_s2s_timeout: 190 + +###. ============== +###' AUTHENTICATION + +## +## auth_method: Method used to authenticate the users. +## The default method is the internal. +## If you want to use a different method, +## comment this line and enable the correct ones. +## +auth_method: internal + +## +## Store the plain passwords or hashed for SCRAM: +## auth_password_format: plain +auth_password_format: scram +## +## Define the FQDN if ejabberd doesn't detect it: +## fqdn: "server3.example.com" + +## +## Authentication using external script +## Make sure the script is executable by ejabberd. +## +## auth_method: external +## extauth_program: "/path/to/authentication/script" + +## +## Authentication using SQL +## Remember to setup a database in the next section. +## +## auth_method: sql + +## +## Authentication using PAM +## +## auth_method: pam +## pam_service: "pamservicename" + +## +## Authentication using LDAP +## +## auth_method: ldap +## +## List of LDAP servers: +## ldap_servers: +## - "lw" +## +## Encryption of connection to LDAP servers: +## ldap_encrypt: none +## ldap_encrypt: tls +## +## Port to connect to on LDAP servers: +## ldap_port: 389 +## ldap_port: 636 +## +## LDAP manager: +## ldap_rootdn: "dc=example,dc=com" +## +## Password of LDAP manager: +## ldap_password: "******" +## +## Search base of LDAP directory: +## ldap_base: "dc=example,dc=com" +## +## LDAP attribute that holds user ID: +## ldap_uids: +## - "mail": "%u@mail.example.org" +## +## LDAP filter: +## ldap_filter: "(objectClass=shadowAccount)" + +## +## Anonymous login support: +## auth_method: anonymous +## anonymous_protocol: sasl_anon | login_anon | both +## allow_multiple_connections: true | false +## +## host_config: +## "public.example.org": +## auth_method: anonymous +## allow_multiple_connections: false +## anonymous_protocol: sasl_anon +## +## To use both anonymous and internal authentication: +## +## host_config: +## "public.example.org": +## auth_method: +## - internal +## - anonymous + +###. ============== +###' DATABASE SETUP + +## ejabberd by default uses the internal Mnesia database, +## so you do not necessarily need this section. +## This section provides configuration examples in case +## you want to use other database backends. +## Please consult the ejabberd Guide for details on database creation. + +## +## MySQL server: +## +## sql_type: mysql +## sql_server: "server" +## sql_database: "database" +## sql_username: "username" +## sql_password: "password" +## +## If you want to specify the port: +## sql_port: 1234 + +## +## PostgreSQL server: +## +## sql_type: pgsql +## sql_server: "server" +## sql_database: "database" +## sql_username: "username" +## sql_password: "password" +## +## If you want to specify the port: +## sql_port: 1234 +## +## If you use PostgreSQL, have a large database, and need a +## faster but inexact replacement for "select count(*) from users" +## +## pgsql_users_number_estimate: true + +## +## SQLite: +## +## sql_type: sqlite +## sql_database: "/path/to/database.db" + +## +## ODBC compatible or MSSQL server: +## +## sql_type: odbc +## sql_server: "DSN=ejabberd;UID=ejabberd;PWD=ejabberd" + +## +## Number of connections to open to the database for each virtual host +## +## sql_pool_size: 10 + +## +## Interval to make a dummy SQL request to keep the connections to the +## database alive. Specify in seconds: for example 28800 means 8 hours +## +## sql_keepalive_interval: undefined + +###. =============== +###' TRAFFIC SHAPERS + +shaper: + ## + ## The "normal" shaper limits traffic speed to 1000 B/s + ## + normal: 1000 + + ## + ## The "fast" shaper limits traffic speed to 50000 B/s + ## + fast: 50000 + +## +## This option specifies the maximum number of elements in the queue +## of the FSM. Refer to the documentation for details. +## +max_fsm_queue: 10000 + +###. ==================== +###' ACCESS CONTROL LISTS +acl: + ## + ## The 'admin' ACL grants administrative privileges to XMPP accounts. + ## You can put here as many accounts as you want. + ## + admin: + user: + - "admin@localhost" + + ## Don't use a regex, to prevent others from obtaining permissions after registering such an account. + bots: + - user: "echelon23@localhost" + - user: "wfgbot23@localhost" + + # Keep playernames short and easily typeable for everyone + validname: + user_regexp: "^[0-9A-Za-z._-]{1,20}$" + + ## + ## Blocked users + ## + ## blocked: + ## user: + ## - "baduser@example.org" + ## - "test" + + ## Local users: don't modify this. + ## + local: + user_regexp: "" + + ## + ## More examples of ACLs + ## + ## jabberorg: + ## server: + ## - "jabber.org" + ## aleksey: + ## user: + ## - "aleksey@jabber.ru" + ## test: + ## user_regexp: "^test" + ## user_glob: "test*" + + ## + ## Loopback network + ## + loopback: + ip: + - "127.0.0.0/8" + - "::1/128" + - "::FFFF:127.0.0.1/128" + + ## + ## Bad XMPP servers + ## + ## bad_servers: + ## server: + ## - "xmpp.zombie.org" + ## - "xmpp.spam.com" + +## +## Define specific ACLs in a virtual host. +## +## host_config: +## "localhost": +## acl: +## admin: +## user: +## - "bob-local@localhost" + +###. ============ +###' SHAPER RULES + +shaper_rules: + ## Maximum number of simultaneous sessions allowed for a single user: + max_user_sessions: 10 + ## Maximum number of offline messages that users can have: + max_user_offline_messages: + - 5000: admin + - 100 + ## For C2S connections, all users except admins use the "normal" shaper + c2s_shaper: + - none: admin + - none: bots + - normal + ## All S2S connections use the "fast" shaper + s2s_shaper: fast + +###. ============ +###' ACCESS RULES +access_rules: + ## This rule allows access only for local users: + local: + - allow: local + ## Only non-blocked users can use c2s connections: + c2s: + - deny: blocked + - allow + ## Only admins can send announcement messages: + announce: + - allow: admin + ## Only admins can use the configuration interface: + configure: + - allow: admin + ## Expected by the ipstamp module for XpartaMuPP + ipbots: + - allow: bots + muc_admin: + - allow: admin + ## Bots must be able to create nodes for games, ratings and boards lists + pubsub_createnode: + - allow: admin + - allow: bots + ## In-band registration allows registration of any possible username. + ## To disable in-band registration, replace 'allow' with 'deny'. + register: + - deny: blocked + - allow: validname + ## Only allow to register from localhost + trusted_network: + - allow: loopback + ## Do not establish S2S connections with bad servers + ## If you enable this you also have to uncomment "s2s_access: s2s" + ## s2s: + ## - deny: + ## - ip: "XXX.XXX.XXX.XXX/32" + ## - deny: + ## - ip: "XXX.XXX.XXX.XXX/32" + ## - allow + +## =============== +## API PERMISSIONS +## =============== +## +## This section allows you to define who and using what method +## can execute commands offered by ejabberd. +## +## By default "console commands" section allow executing all commands +## issued using ejabberdctl command, and "admin access" section allows +## users in admin acl that connect from 127.0.0.1 to execute all +## commands except start and stop with any available access method +## (ejabberdctl, http-api, xmlrpc depending what is enabled on server). +## +## If you remove "console commands" there will be one added by +## default allowing executing all commands, but if you just change +## permissions in it, version from config file will be used instead +## of default one. +## +api_permissions: + "console commands": + from: + - ejabberd_ctl + who: all + what: "*" + "admin access": + who: + - access: + - allow: + - acl: loopback + - acl: admin + - oauth: + - scope: "ejabberd:admin" + - access: + - allow: + - acl: loopback + - acl: admin + what: + - "*" + - "!stop" + - "!start" + "public commands": + who: + - ip: "127.0.0.1/8" + what: + - "status" + - "connected_users_number" + +## By default the frequency of account registrations from the same IP +## is limited to 1 account every 10 minutes. To disable, specify: infinity +registration_timeout: 3600 + +## +## Define specific Access Rules in a virtual host. +## +## host_config: +## "localhost": +## access: +## c2s: +## - allow: admin +## - deny +## register: +## - deny + +###. ================ +###' DEFAULT LANGUAGE + +## +## language: Default language used for server messages. +## +language: "en" + +## +## Set a different default language in a virtual host. +## +## host_config: +## "localhost": +## language: "ru" + +###. ======= +###' CAPTCHA + +## +## Full path to a script that generates the image. +## +## captcha_cmd: "/usr/share/ejabberd/captcha.sh" + +## +## Host for the URL and port where ejabberd listens for CAPTCHA requests. +## +## captcha_host: "example.org:5280" + +## +## Limit CAPTCHA calls per minute for JID/IP to avoid DoS. +## +## captcha_limit: 5 + +###. ==== +###' ACME +## +## In order to use the acme certificate acquiring through "Let's Encrypt" +## an http listener has to be configured to listen to port 80 so that +## the authorization challenges posed by "Let's Encrypt" can be solved. +## +## A simple way of doing this would be to add the following in the listening +## section and to configure port forwarding from 80 to 5281 either via NAT +## (for ipv4 only) or using frontends such as haproxy/nginx/sslh/etc. +## - +## port: 5281 +## ip: "::" +## module: ejabberd_http + +acme: + + ## A contact mail that the ACME Certificate Authority can contact in case of + ## an authorization issue, such as a server-initiated certificate revocation. + ## It is not mandatory to provide an email address but it is highly suggested. + contact: "mailto:example-admin@example.com" + + + ## The ACME Certificate Authority URL. + ## This could either be: + ## - https://acme-v01.api.letsencrypt.org - (Default) for the production CA + ## - https://acme-staging.api.letsencrypt.org - for the staging CA + ## - http://localhost:4000 - for a local version of the CA + ca_url: "https://acme-v01.api.letsencrypt.org" + +###. ======= +###' MODULES + +## +## Modules enabled in all ejabberd virtual hosts. +## +modules: + mod_adhoc: {} + mod_admin_extra: {} + mod_announce: # recommends mod_adhoc + access: announce + mod_blocking: {} # requires mod_privacy + mod_caps: {} + mod_carboncopy: {} + mod_client_state: {} + mod_configure: {} # requires mod_adhoc + ## mod_delegation: {} # for xep0356 + mod_disco: {} + ## mod_echo: {} + ## ipstamp module used by XpartaMuPP to insert IP addresses into the gamelist + mod_ipstamp: {} + ## mod_irc: {} + mod_bosh: {} + ## mod_http_fileserver: + ## docroot: "/var/www" + ## accesslog: "/var/log/ejabberd/access.log" + ## mod_http_upload: + ## # docroot: "@HOME@/upload" + ## put_url: "https://@HOST@:5444" + ## thumbnail: false # otherwise needs the identify command from ImageMagick installed + ## mod_http_upload_quota: + ## max_days: 30 + mod_last: {} + ## XEP-0313: Message Archive Management + ## You might want to setup a SQL backend for MAM because the mnesia database is + ## limited to 2GB which might be exceeded on large servers + ## mod_mam: {} # for xep0313, mnesia is limited to 2GB, better use an SQL backend + mod_muc: + ## host: "conference.@HOST@" + access: + - allow + access_admin: muc_admin + access_create: muc_admin + access_persistent: muc_admin + max_users: 5000 + default_room_options: + allow_change_subj: false + logging: true + max_users: 1000 + persistent: true + mod_muc_admin: {} + mod_muc_log: + outdir: "/lobby/logs" + dirtype: plain + file_format: plaintext + timezone: universal + ## mod_multicast: {} + mod_offline: + access_max_user_messages: max_user_offline_messages + mod_ping: + send_pings: true + ## mod_pres_counter: + ## count: 5 + ## interval: 60 + mod_privacy: {} + mod_private: {} + ## mod_proxy65: {} + mod_pubsub: + access_createnode: pubsub_createnode + ## reduces resource comsumption, but XEP incompliant + ignore_pep_from_offline: true + ## XEP compliant, but increases resource comsumption + ## ignore_pep_from_offline: false + last_item_cache: false + plugins: + - "flat" + - "hometree" + - "pep" # pep requires mod_caps + mod_push: {} + mod_push_keepalive: {} + mod_register: + ## + ## Protect In-Band account registrations with CAPTCHA. + ## + ## captcha_protected: true + ## + ## Set the minimum informational entropy for passwords. + ## + ## password_strength: 32 + ## + ## After successful registration, the user receives + ## a message with this subject and body. + ## + ## welcome_message: + ## subject: "Welcome!" + ## body: |- + ## Hi. + ## Welcome to this XMPP server. + ## + ## When a user registers, send a notification to + ## these XMPP accounts. + ## + ## registration_watchers: + ## - "admin1@example.org" + ## + ## Only clients in the server machine can register accounts + ## + ## ip_access: trusted_network + ## + ## Local c2s or remote s2s users cannot register accounts + ## + ## access_from: deny + access: register + mod_roster: + versioning: true + ## mod_shared_roster: {} + mod_stats: {} + mod_time: {} + ## mod_vcard: + ## search: false + ## mod_vcard_xupdate: {} + ## Convert all avatars posted by Android clients from WebP to JPEG + ## mod_avatar: # this module needs compile option --enable-graphics + ## convert: + ## webp: jpeg + mod_version: {} + mod_stream_mgmt: + resend_on_timeout: if_offline + ## Non-SASL Authentication (XEP-0078) is now disabled by default + ## because it's obsoleted and is used mostly by abandoned + ## client software + ## mod_legacy_auth: {} + ## The module for S2S dialback (XEP-0220). Please note that you cannot + ## rely solely on dialback if you want to federate with other servers, + ## because a lot of servers have dialback disabled and instead rely on + ## PKIX authentication. Make sure you have proper certificates installed + ## and check your accessibility at https://check.messaging.one/ + mod_s2s_dialback: {} + mod_http_api: {} + +## +## Enable modules with custom options in a specific virtual host +## +## host_config: +## "localhost": +## modules: +## mod_echo: +## host: "mirror.localhost" + +## +## Enable modules management via ejabberdctl for installation and +## uninstallation of public/private contributed modules +## (enabled by default) +## + +allow_contrib_modules: true + +###. +###' +### Local Variables: +### mode: yaml +### End: +### vim: set filetype=yaml tabstop=8 foldmarker=###',###. foldmethod=marker: + Property changes on: ps/trunk/source/tools/lobbybots/ejabberd_example.yml ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property