def broadcastMusic(self, nextMusic = False): if self.broadcasting and not nextMusic: return 0 if self.currentMusic is not None: self.currentMusic.shared = False self.shareQueue.remove(self.currentMusic) if len(self.shareQueue) < 1: # try once self.currentMusic = None self.broadcasting = False GeneralEvent('music:broadcast', self, None) self.redis.server.set('music:broadcasting', None) return 0 # No more queue self.broadcasting = True self.currentMusic = self.shareQueue[0] self.redis.server.hmset('music:sharing', {self.currentMusic.id : int(0)}) t = ceil(self.currentMusic.length / 1000) self.redis.server.set('music:broadcasting', int(self.currentMusic)) GeneralEvent('music:broadcast', self, self.currentMusic) self.logger.info('Broadcasting "%s" by %s, %i seconds until next music!', self.currentMusic.name, self.currentMusic.pengNick, t) self.broadcastDefer = reactor.callLater(t, self.broadcastMusic, True) self.refresh()
def handleKickPlayer(client, _id): if not client['moderator']: client.engine.log('warn', '%s tried to kick %s. %s is not a moderator.', client['nickname'], _id) return GeneralEvent('ban-player', client, 0, 'Hacking or Manipulating server. Unauthorized kick {}, while not a moderator.'.format(_id), 1, 3) _kickable = GetPenguin(client.engine, _id) if _kickable['moderator']: return client.send('e', 800) GeneralEvent('kick-player', _kickable, '{} kicked {} on {}'.format(client['nickname'], _kickable['nickname'], client.engine))
def handleMutePlayer(client, _id): if not client['moderator']: client.engine.log('warn', '%s tried to (un)mute %s. %s is not a moderator.', client['nickname'], _id) return GeneralEvent( 'ban-player', client, 0, 'Hacking or Manipulating server. Unauthorized (un)muting {}, while not a moderator.' .format(_id), 1, 3) _mutable = GetPenguin(client.engine, _id) GeneralEvent( 'mute-player', _mutable, '{} (un)muted {} on {}'.format(client['nickname'], _mutable['nickname'], client.engine))
def connectionLost(self, reason): super(Penguin, self).connectionLost(reason) if self.id in self.users: del self.users[self.id] self.penguin.connectionLost = True # decentralize and make disconnection more flexible if self.engine.type == WORLD_SERVER and self.penguin.id != None: # sending self just to make sure it doesn't throw weak-reference error if self['RefreshHandler'] is not None: self['RefreshHandler'].RefreshManagerLoop.stop( ) if self['RefreshHandler'].RefreshManagerLoop.running else 0 yield self.engine.redis.server.srem( "users:{}".format(self.engine.id), self['swid']) yield GeneralEvent('onClientDisconnect', self.ref) if self['RefreshHandler'] is not None: del self.penguin.RefreshHandler yield self.engine.redis.server.delete("online:{}".format(self['id'])) yield self.engine.disconnect(self) self.cleanConnectionLost.callback(True)
def initialize(self): self.penguin.nickname = Nickname(self.dbpenguin.nickname, self.ref) self.penguin.swid = self.dbpenguin.swid #TODO: figure out why the hell EPF even exists. self.penguin.epf = EPFAgent(self.dbpenguin.agent, str(self.dbpenguin.epf), self.ref) self.penguin.RefreshHandler = Refresh(self.ref) self.penguin.moderator = int(self.dbpenguin.moderator) self.penguin.stealth_mode = self['moderator'] == 2 self.penguin.mascot_mode = self['moderator'] == 3 self.penguin.x = self.penguin.y = self.penguin.frame = 0 self.penguin.age = Age(self.dbpenguin.create, self.ref) self.penguin.muted = False self.penguin.cache = Cache(self.ref) self.penguin.ninjaHandler = NinjaHandler(self.ref) self.penguin.currencyHandler = CurrencyHandler(self.ref) self.engine.musicHandler.init(self.ref) GeneralEvent('onBuildClient', self.ref)
def __init__(self, protocol, _type, _id, name="World Server 1", _max=300, server_protocol = AS3_PROTOCOL): self.protocol = protocol self.server_protocol = server_protocol self.type = _type self.id = _id self.logger = logging.getLogger(TIMELINE_LOGGER) self.name = name self.users = deque() # Thread safe self.dbDetails = dict() self.maximum = _max - 1 self._listening = False self._portListener = None self.proxyReference = weakref.proxy(self) self.redis = Redis(self) self.log("info", "Timeline Factory Started!") self.log("info", "Running:", self.name) self.log("info", "Maximum users:", self.maximum) if self.type == WORLD_SERVER: self.initializeWorld() self.redis.redisConnectionDefer.addCallback(lambda *x: GeneralEvent('onEngine', self))
def __call__(self, client, message): if not message.startswith('!') or client['muted']: return msg_packets = message[1:].split(' ') command = msg_packets[0].lower() params = msg_packets[1:] __commands__ = [str(k).lower() for k in self.__commands__] if command in __commands__: client.penguin.muted = True client.penguin.muted_for_command = True if client['muted_for_command'] is None \ else client['muted_for_command'] GeneralEvent('command={}'.format(command), client, params) GeneralEvent('command[{}]={}'.format(client.Protocol, command), client, params)
def onRemove(self, client): try: super(TableGame, self).onRemove(client) except: pass GeneralEvent('Table-Left-{}-{}'.format(client['id'], self.table), client, self) GeneralEvent('Table-Left-{}'.format(client['id']), client, self) GeneralEvent('Table-Left-{}'.format(self.table), client, self) client.penguin.playing = client.penguin.waddling = False client.penguin.game = None self.room.append(self) client.penguin.room = self.room # must client.engine.redis.server.hmset("online:{}".format(client.penguin.id), {'place' : self.room.ext_id}) self.updateTable()
def disconnect(self, client): GeneralEvent('onClientRemove', client.ref) if client in self.users: self.users.remove(client) yield self.redis.server.hmset("server:{}".format(self.id), {'population':len(self.users)}) returnValue(True) returnValue(False)
def checkForMascotPresence(self): mascots = set(m['nickname'] for m in self if m['mascot_mode']) penguins = [p for p in self if not p['mascot_mode']] [ GeneralEvent("mascot-joined-room", self, mascot, penguins) for mascot in mascots ] self.roomHandler.engine.log("info", "Mascot presence found in room: ", self.name)
def handleSendMessage(client, _id, message): if not client['id'] == _id: return message = message.strip(' ').replace('|', '\\|') GeneralEvent.call('before-message', client, message) if client['muted']: GeneralEvent.call('after-message-muted', client, message) return if client['stealth_mode'] or client['mascot_mode']: return toxic = Toxicity(message) if toxic > 60: # wow toxic... if toxic > 90: # he's a racist, ban him GeneralEvent('ban-player', client, 0, 'Rude. Toxicity [{}] message: {}'.format( toxic, message), type=3, ban_type=610) elif toxic > 80: # Kick'em GeneralEvent( 'kick-player', client, 'Rude. Toxicity [{}] message: {}'.format(toxic, message)) else: GeneralEvent( 'mute-player', client, 'Rude. Toxicity [{}] message: {}'.format(toxic, message)) return client['room'].send('sm', _id, message) GeneralEvent.call('after-message', client, message)
def connectionLost(self, reason): del self.PacketHandler.penguin super(Penguin, self).connectionLost(reason) # decentralize and make disconnection more flexible if self.engine.type == WORLD_SERVER and self.penguin.id != None: self.engine.roomHandler.removeFromAnyRoom(self.selfRefer) yield GeneralEvent('onClientDisconnect', self.selfRefer) yield self.engine.disconnect(self) self.cleanConnectionLost.callback(True)
def _refresh(self, forced=False): if self.DEBUG: self.logger.info( 'Penguin ASync-Refresh-ing : Penguin - {}, Forced - {}'.format( self.penguin['nickname'], forced)) if self.penguin['connectionLost']: returnValue(0) if self.firstTimeCall: yield self._setupCache() self.firstTimeCall = False returnValue(1) # coins update self.penguin.penguin.coins = (yield Registry.getConfig(). \ execute("SELECT SUM(transaction) FROM coins where penguin_id = %s" % self.penguin['id']))[0][0] if self.penguin['coins'] is None: yield Coin(penguin_id=self.penguin['id'], transaction=100, comment="Player went bankrupt. " "Giving them +100").save() self.penguin.penguin.coins = 100 self.penguin.penguin.coins = int(self.penguin['coins']) self.penguin.send('gtc', self.penguin['coins']) for item in self.REFRESH_ITEMS: if not hasattr(self.penguin.dbpenguin, item): continue relation = getattr(self.penguin.dbpenguin, item) items_o = set(self.cache[item]) items_ = yield relation.get() items_updated = set(items_) items_added = items_updated - items_o items_removed = items_o - items_updated reactor.callFromThread(self.cacheHandlers[item], items_added, items_removed, items_o) reactor.callFromThread(self.cacheHandlers['igloos']) GeneralEvent( 'Refresh-Cache', self) # Refresh cache data for things other than those in here if forced: reactor.callFromThread( self.RefreshManagerLoop.stop ) if self.RefreshManagerLoop.running else None reactor.callFromThread(self.RefreshManagerLoop.start, self.REFRESH_INTERVAL, False) if \ not self.penguin['connectionLost'] else None
def handleGameOver(client, data): score = int(data[2][0]) coins = round(score / 10.0) client.penguin.playing = False current_game = client['room'] if coins > 10000: client.engine.log('warn', "Potential coins manipulation,", current_game, ':', score) return if not isinstance(current_game, Game) or isinstance( current_game, Multiplayer): try: current_game.gameOver(client=client) except: client.engine.log('warn', "Game exploitation,", current_game.name, ':', score) return stamps = map(int, client['recentStamps']) g_stamps = map( int, client.engine.stampCrumbs.getStampsByGroup(current_game.stamp_id)) e_stamps = list( set(map(lambda x: int(x.stamp), client['data'].stamps)).intersection(g_stamps)) stamps = list(set(stamps).intersection(g_stamps)) earned = len(e_stamps) total = len(g_stamps) if total == earned and total != 0: coins *= 2 client.send('zo', client['coins'] + coins, '|'.join(map(str, stamps)), earned, total, total) client['coins'] += coins Coin(penguin_id=client['id'], transaction=coins, comment="Coins earned by playing game. Game: {}".format( current_game.name)).save() GeneralEvent("Game-Over", client, score, current_game) client['room'].remove(client) for room in client['prevRooms'][::-1]: if isinstance(room, Place): room.append(client) return
def onAdd(self, client): super(Place, self).onAdd(client) client.send('jr', self.ext_id, *((self, ) if len(str(self)) > 0 else [])) self.send('ap', client) if not client['stealth_mode'] else client.send( 'ap', client) if client['mascot_mode']: GeneralEvent("mascot:{}-joined-room".format(client['nickname']), self) self.checkForMascotPresence()
def connectionLost(self, reason): super(Penguin, self).connectionLost(reason) # decentralize and make disconnection more flexible if self.engine.type == WORLD_SERVER and self.penguin.id != None: #self.engine.roomHandler.removeFromAnyRoom(self.selfRefer) # needs some fix b4 further usage on-disconnect self.engine.roomHandler.removeFromAnyRoom(self.selfRefer, self) # experimental # sending self just to make sure it doesn't throw weak-reference error yield self.engine.redis.server.delete("online:{}".format( self['id'])) yield GeneralEvent('onClientDisconnect', self.selfRefer) yield self.engine.disconnect(self) self.cleanConnectionLost.callback(True)
def initialize(self): self.penguin.nickname = Nickname(self.dbpenguin.nickname, self.selfRefer) self.penguin.swid = self.dbpenguin.swid self.penguin.inventory = Inventory(self.selfRefer) self.penguin.inventory.parseFromString(self.dbpenguin.inventory) self.penguin.member = Membership(self.dbpenguin.membership, self.selfRefer) self.penguin.moderator = int(self.dbpenguin.moderator) self.penguin.stealth_mode = self['moderator'] == 2 self.penguin.mascot_mode = self['moderator'] == 3 self.penguin.x = self.penguin.y = self.penguin.frame = self.penguin.avatar = 0 self.penguin.coins = Coins(self.dbpenguin.coins, self.selfRefer) self.penguin.age = Age(self.dbpenguin.create, self.selfRefer) self.penguin.cache = Cache(self.selfRefer) self.penguin.muted = False self.penguin.epf = EPFAgent(self.dbpenguin.agent, str(self.dbpenguin.epf), self.selfRefer) clothing = [Color, Head, Face, Neck, Body, Hand, Feet, Pin, Photo] for cloth in clothing: name = cloth.__name__.lower() self.penguin[name] = cloth(0, 0, name + " item", False, False, False) self.penguin.mail = MailHandler(self.selfRefer) self.penguin.iglooHandler = PenguinIglooHandler(self.selfRefer) self.penguin.puffleHandler = PuffleHandler(self.selfRefer) self.penguin.stampHandler = StampHandler(self.selfRefer) self.penguin.ninjaHandler = NinjaHandler(self.selfRefer) self.penguin.currencyHandler = CurrencyHandler(self.selfRefer) self.penguin.friendsHandler = FriendsHandler(self.selfRefer) self.engine.musicHandler.init(self.selfRefer) self.loadClothing() GeneralEvent('onBuildClient', self.selfRefer)
def __init__(self, protocol, _type, _id, name="World Server 1", _max=300): self.protocol = protocol self.type = _type self.id = _id self.logger = logging.getLogger(TIMELINE_LOGGER) self.name = name self.users = deque() # Thread safe self.dbDetails = dict() self.maximum = _max - 1 self.redis = Redis(self) self.log("info", "Timeline Factory Started!") self.log("info", "Running:", self.name) self.log("info", "Maximum users:", self.maximum) if self.type == WORLD_SERVER: self.initializeWorld() GeneralEvent('onEngine', self)
def initialize(self): self.penguin.nickname = Nickname(self.dbpenguin.nickname, self.selfRefer) self.penguin.swid = self.dbpenguin.swid self.penguin.RefreshHandler = Refresh(self) self.penguin.moderator = int(self.dbpenguin.moderator) self.penguin.stealth_mode = self['moderator'] == 2 self.penguin.mascot_mode = self['moderator'] == 3 self.penguin.x = self.penguin.y = self.penguin.frame = 0 self.penguin.age = Age(self.dbpenguin.create, self.selfRefer) self.penguin.muted = False self.penguin.cache = Cache(self.selfRefer) self.penguin.ninjaHandler = NinjaHandler(self.selfRefer) self.penguin.currencyHandler = CurrencyHandler(self.selfRefer) self.engine.musicHandler.init(self.selfRefer) GeneralEvent('onBuildClient', self.selfRefer)
def handleSendEmote(client, emote): GeneralEvent('Handle-Emote', client, emote) if emote not in EMOTES \ else client['room'].send('se', client['id'], emote)
def _setupCache(self): self.penguin.penguin.recentStamps = [] database_penguin = self.penguin.dbpenguin self.cache.avatar = yield database_penguin.avatar.get() if self.cache.avatar is None: self.cache.avatar = yield Avatar( penguin_id=self.penguin['id']).save() yield self.cache.avatar.refresh() self.cache.inventories = yield database_penguin.inventories.get() self.cache.assets = yield database_penguin.assets.get() self.cache.friends = yield database_penguin.friends.get() self.cache.requests = [] friends_data = [] for friend in self.cache.friends: friendObj = (yield Penguin.find(where=['swid = ?', friend.friend], limit=1)) if friendObj is None: continue friend.friend_id = friendObj.id friend.onlinePresence = {'online_status': False} data = [ int(friendObj.id), friendObj.nickname, friendObj.swid, friend.bff ] friends_data.append('|'.join(map(str, data))) self.penguin.send('fl', (yield database_penguin.requests.count()), *friends_data) self.cache.ignores = yield database_penguin.ignores.get() self.cache.careItems = yield database_penguin.careItems.get() self.cache.stamps = yield database_penguin.stamps.get() self.cache.mails = yield database_penguin.mails.get() self.cache.bans = yield database_penguin.bans.get() self.cache.puffles = yield database_penguin.puffles.get() self.cache.stampCovers = yield database_penguin.stampCovers.get() self.cache.igloos = deque() igloos = yield database_penguin.igloos.get(limit=6) for igloo in igloos: iglooCache = PenguinObject() iglooCache.igloo = igloo iglooCache.iglooFurnitures = yield igloo.iglooFurnitures.get( limit=99) iglooCache.iglooLikes = yield igloo.iglooLikes.get() self.cache.igloos.append(iglooCache) self.cache.memberships = yield database_penguin.memberships.get() self.cacheHandlers.inventories = self.handleInventory self.cacheHandlers.assets = self.handleAssets self.cacheHandlers.friends = self.handleFriends self.cacheHandlers.requests = self.handleRequests self.cacheHandlers.ignores = self.handleIgnores self.cacheHandlers.careItems = self.handleCareItems self.cacheHandlers.stamps = self.handleStamps self.cacheHandlers.mails = self.handleMails self.cacheHandlers.bans = self.handleBans self.cacheHandlers.puffles = self.handlePuffles self.cacheHandlers.stampCovers = self.handleStampCovers self.cacheHandlers.igloos = self.handleIgloos self.penguin.penguin.coins = (yield Registry.getConfig().\ execute("SELECT COALESCE(SUM(transaction), 0) FROM coins where penguin_id = %s" % self.penguin['id']))[0][0] self.penguin.penguin.igloo = yield self.initPenguinIglooRoom( self.penguin['id']) if self.penguin['igloo']._id not in self.getIgloos(): igloo = yield database_penguin.igloos.get( where=['id = ?', self.penguin['igloo']._id], limit=1) iglooCache = PenguinObject() iglooCache.igloo = igloo iglooCache.iglooFurnitures = yield igloo.iglooFurnitures.get( limit=99) iglooCache.iglooLikes = yield igloo.iglooLikes.get() self.cache.igloos.append(iglooCache) self.penguin.penguin.currentIgloo = self.getIgloos()[ self.penguin.dbpenguin.igloo].igloo self.setupCJMats() membership = yield database_penguin.memberships.get( orderby='expires desc', limit=1) if membership is None: #no membership records, give a free 7 day trial trialExpiry = time.time() + 7 * 24 * 60 * 60 membership = yield \ Membership(penguin_id=self.penguin['id'], expires=Registry.getDBAPIClass("TimestampFromTicks")(trialExpiry), comments='Redeemed 7-day auto free trial membership. - Timeline Server').save() self.penguin.penguin.member = MembershipHandler( membership, self.penguin) self.cache.avatar = yield database_penguin.avatar.get() if self.cache.avatar is None: self.cache.avatar = yield Avatar( penguin_id=self.penguin['id']).save() GeneralEvent('Setup-Cache', self) self.CacheInitializedDefer.callback(True)
roomObj.stamp_id = stamp self.rooms.append(roomObj) except Exception, e: self.log('error', 'Error parsing JSON. E:', e) sys.exit() for r in self.details: self.log('info', 'Loaded', self.details[r], '{}(s)'.format(r.__name__)) self.ROOM_CONFIG = type('RoomConfig', (object, ), { 'ROOM_HANDLER': self })() # user editable, flexible attribute. Used by each game as desired GeneralEvent('Room-handler', self) def log(self, l, *a): self.engine.log(l, '[RoomHandler] ', *a) def getRoomByExtId(self, _id): for room in self.rooms: if room.ext_id == _id: return room return None def getRoomById(self, _id): for room in self.rooms: if int(room) == _id: return room