def search(field=None, action=None, value=None): '''Plugin search A generalized search system that accepts both single-criteria get requests as well as multi-criteria posts. ''' filters = [] if request.method == 'GET': fields = bleach.clean(request.query.fields or 'slug,plugin_name,description').split(',') start = c.sint(bleach.clean(request.query.start or None)) size = c.sint(bleach.clean(request.query.size or None)) sort = bleach.clean(request.query.sort or 'slug') field = bleach.clean(field) value = bleach.clean(value) filters = [ {'field': field, 'action': action, 'value': value} ] else: req = json.dumps(request.forms.get('search')) fields = req['fields'] if 'fields' in req else ['slug', 'plugin_name', 'description'] start = req['start'] if 'sort' in req else None size = req['size'] if 'size' in req else None sort = req['sort'] if 'sort' in req else 'slug' filters = req['filters'] if 'filters' in req else [] try: data = c.plugin_search(filters, fields, sort) except: raise bottle.HTTPError(400, '{"error": "invalid post"}') else: if start is not None and size is not None: return c.jsonify(data[start:start+size]) return c.jsonify(data)
def search(base=None, field=None, action=None, value=None): '''Plugin search A generalized search system that accepts both single-criteria get requests as well as multi-criteria posts. ''' fields = bleach.clean(request.query.fields or 'name,plugname,description').split(',') fields = v2to3(fields) start = c.sint(bleach.clean(request.query.start or None)) size = c.sint(bleach.clean(request.query.size or None)) sort = bleach.clean(request.query.sort or 'slug') field = bleach.clean(field) value = bleach.clean(value) base = bleach.clean(base) if base == 'version': field = 'versions.%s' % field filters = [ {'field': field, 'action': action, 'value': value} ] try: data = c.plugin_search(filters, fields, sort) except: raise bottle.HTTPError(400, '{"error": "invalid search"}') else: if start is not None and size is not None: return c.jsonify(v3to2(data[start:start+size])) return c.jsonify(v3to2(data))
def valid(msg, schema): try: log.debug('Validating message %s with schema %s', c.jsonify(msg), c.jsonify(schema)) jsonschema.Draft3Validator(schema).validate(msg) except jsonschema.ValidationError as e: log.warning("Message is not valid %s", e.message) return False return True
def category_plugins(name, server=None): '''Category Plugin listing returns the list of plugins that match a specific category. Optionally a specific server binary compatability can be specified. ''' fields = bleach.clean(request.query.fields or 'slug,plugin_name,description').split(',') start = c.sint(bleach.clean(request.query.start or None)) size = c.sint(bleach.clean(request.query.size or None)) sort = bleach.clean(request.query.sort or 'slug') data = c.list_category_plugins(server, name, fields, sort) if size is not None and start is not None: return c.jsonify(data[start:start+size]) return c.jsonify(data)
def plugin_list(server=None): '''Plugin Listing Returns the plugin listing. Can optionally be limited to a specific server binary compatability type. ''' fields = bleach.clean(request.query.fields or 'slug,plugin_name,description').split(',') start = c.sint(bleach.clean(request.query.start or None)) size = c.sint(bleach.clean(request.query.size or None)) sort = bleach.clean(request.query.sort or 'slug') data = c.list_plugins(server, fields, sort) if size is not None and start is not None: return c.jsonify(data[start:start+size]) return c.jsonify(data)
def author_plugins(name, server=None): '''Author Plugin Listing Returns the plugins associated with a specific author. Optionally can also be restricted to a specific server binary compatability. ''' fields = bleach.clean(request.query.fields or 'slug,plugin_name,description').split(',') start = c.sint(bleach.clean(request.query.start or None)) size = c.sint(bleach.clean(request.query.size or None)) sort = bleach.clean(request.query.sort or 'slug') data = c.list_author_plugins(server, name, fields, sort) if size is not None and start is not None: return c.jsonify(data[start:start+size]) return c.jsonify(data)
def plugin_list(): '''Plugin Listing Returns the plugin listing. Can optionally be limited to a specific server binary compatability type. ''' data = c.list_plugins('bukkit', ['slug',], 'slug') return c.jsonify([a['slug'] for a in data])
def export_json(db): u = input('enter file path: ') sdata = common.jsonify(db.get_all()) file = open(u, "w") file.write(sdata) file.close() print('data exported succesfully')
def wakeup_asg(asg): log.debug('Initializing ASG: %s', pprint.saferepr(asg)) tags = {i['Key']: i['Value'] for i in asg['Tags']} if not valid(tags, desired_wakeup_tags_schema): error = "Autoscaling group doesn't contain correct wakeup tags %s ".format( c.jsonify(tags)) log.error(error) raise ValueError(error) initial_capacity = int(tags['InitialCapacity']) desired_capacity = int(tags['DesiredCapacity']) min_size = int(tags['MinSize']) max_size = int(tags['MaxSize']) if (int(asg['MinSize']) != min_size or \ int(asg['MaxSize']) != max_size or \ int(asg['DesiredCapacity']) != desired_capacity) and \ int(asg['MaxSize']) == initial_capacity: log.info( 'Resizing autoscaling group from initial %i to desired %i capacity', initial_capacity, desired_capacity) asg_client.update_auto_scaling_group( AutoScalingGroupName=asg['AutoScalingGroupName'], MinSize=min_size, MaxSize=max_size, DesiredCapacity=desired_capacity)
def get_messages(self): self.user game = str(self.json.get('game', "")) all_messages = self.messages.filter(game = self.user.game) if game else self.messages.filter(game = None) if str(self.json['game']): try: game_id = int(game) if self.user.game is None or game_id != self.user.game.id: raise BadGame() except ValueError: raise BadGame() try: since = float(str(self.json['since'])) except ValueError: raise BadSince() messages = [msg for msg in all_messages if msg.timestamp >= since] return jsonify( result="ok", messages=[{ "time": msg.timestamp, "text": msg.text, "login": msg.user.login} for msg in messages])
def signin(self): user = self.users.filter(login=self._str_param('login'), password=self.users.encode(self._str_param('password'))) if user.count() != 1: raise Incorrect() user = user.items()[0] return jsonify(result="ok", sid=user.authenticate())
def generation_info(): '''Generation Information Returns the generation information as requested. User can optionall request to look X number of versions back. ''' size = c.sint(bleach.clean(request.query.size or None)) return c.jsonify(c.list_geninfo(size))
def join_game(self): user = self._user_by_sid() try: user.join_game(id=int(self.json['game'])) # self.current_games.game(int(self.json['game'])).add_player(user.id, user.login) except ValueError: raise BadGame() return jsonify(result="ok")
def start_testing(self): self.models.flush() self.games.flush() CommonController.WEBSOCKET_MODE_SYNC = True if self.json.get("websocketMode") == "sync" else False print("websocketMode: ", self.json["websocketMode"]) return jsonify(result="ok")
def plugin_details(server, slug, version=None): '''Plugin Details Returns the document for a specific plugin. Optionally can return only a specific version as part of the data as well. ''' fields = bleach.clean(request.query.fields or '').split(',') fields = v2to3(fields) data = c.plugin_details(server, slug, version, fields) return c.jsonify(v3to2([data])[0])
def naughty_list(): plugins = list(c.db.plugins.find({'_use_dbo': {'$exists': True}}, { '_id': 0, 'slug': 1, 'plugin_name': 1, 'authors': 1, })) return c.jsonify(plugins)
def get_maps(self): maps = self.maps.all() return jsonify( maps=[{ "id": map.id, "name": map.name, "map": map.map, "maxPlayers": map.max_players, } for map in maps], result="ok")
def signup(self): try: password = self._str_param('password') if len(password) < self.MIN_PASSWORD_SYMBOLS: raise BadPassword() self.users.new(login=self._str_param('login'), password=self.users.encode(password)) except CommitException: raise UserExists() return jsonify(result="ok")
def upload_map(self): try: self.maps.new( name = str(self.json['name']), map = list(self.json['map']), max_players = int(str(self.json['maxPlayers']))) except CommitException: raise MapExists() except ValueError: raise BadMaxPlayers() return jsonify(result="ok")
def plugin_details(server, slug, version=None): '''Plugin Details Returns the document for a specific plugin. Optionally can return only a specific version as part of the data as well. ''' fields = bleach.clean(request.query.fields or '').split(',') size = c.sint(bleach.clean(request.query.size or None)) data = c.plugin_details(server, slug, version, fields) if size is not None: data['versions'] = data['versions'][:size] return c.jsonify(data)
def get_games(self): games = self.games.filter(status=str(self.json["status"])).all() if self.json.get("status") else self.games.all() return jsonify( games=[{ "name": game.name, "id": game.id, "map": game.map.id, "maxPlayers": game.max_players, "players": [player.login for player in game.players.all()], "status": game.status } for game in games], result="ok")
def search(field=None, action=None, value=None): '''Plugin search A generalized search system that accepts both single-criteria get requests as well as multi-criteria posts. ''' fields = ['slug',] start = c.sint(bleach.clean(request.query.start or None)) size = c.sint(bleach.clean(request.query.size or None)) sort = bleach.clean(request.query.sort or 'slug') field = bleach.clean(field) value = bleach.clean(value) filters = [ {'field': field, 'action': action, 'value': value} ] try: data = c.plugin_search(filters, fields, sort) except: raise bottle.HTTPError(400, '{"error": "invalid search"}') else: if start is not None and size is not None: return c.jsonify([a['slug'] for a in data[start:start+size]]) return c.jsonify([a['slug'] for a in data])
def todays_trends(): today = datetime.date.today().strftime('%Y-%m-%d') stats = list(c.db.stats.find({'counts.%s' % today: {'$exists': True}}, {'_id': 0, 'slug': 1, 'server': 1, 'counts.%s' % today: 1})\ .sort('counts.%s' % today, -1).limit(10)) plugins = c.db.plugins.find({},{'slug': 1, 'versions.version': 1}) pcount = 0 vcount = 0 for plugin in plugins: pcount += 1 for version in plugin['versions']: vcount += 1 return c.jsonify({ 'plugin_count': pcount, 'version_count': vcount, 'top_plugs': stats, })
def get_stats(self): gameid = int(self.json["game"]) try: game = self.games.get(gameid) if game.status == "running": raise BadGame() except: raise BadGame() return jsonify( players=[{ login: player.login, kills: player.kills, deaths: player.deaths } for player in game.player_stats] )
def leave_game(self): user = self._user_by_sid() if user.game: game = self.current_games.game(user.game.id) if game: game.remove_player(user.id) if len(user.game.players.all()) == 1: for player in game.players_.values(): user.game.player_stats.new(login=player.login, kills=player.kills, deaths=player.deaths) self.current_games.remove_game(user.game.id) user.leave_game() return jsonify(result="ok")
def create_game(self): if self.user.game: raise AlreadyInGame() try: map = self.maps.get(id=int(self.json['map'])) except (ValueError, ObjectNotFound): raise BadMap() try: game = self.games.new(map = map, name = str(self.json['name']), max_players = int(str(self.json['maxPlayers']))) self.user.game = game self.user.save() self.current_games.add_game(game.id, map.map, self.json.get('consts')) #.add_player(self.user.id, self.user.login) except CommitException: raise GameExists() except ValueError: raise BadMaxPlayers() return jsonify(result="ok")
def plugin_details(slug, version=None): '''Plugin Details Returns the document for a specific plugin. Optionally can return only a specific version as part of the data as well. ''' data = c.plugin_details('bukkit', slug, version, []) # Moving data to the old format data['name'] = data['slug'] data['bukkitdev_link'] = data['dbo_page'] data['desc'] = data['description'] # Deleting all of the data that didnt exist in the old format. del(data['slug']) del(data['dbo_page']) del(data['description']) del(data['logo']) del(data['logo_full']) del(data['server']) del(data['website']) if '_use_dbo' in data: del(data['_use_dbo']) # Now we will perform the same actions for each version. versions = [] for version in data['versions']: version['dl_link'] = version['download'] version['name'] = version['version'] del(version['commands']) del(version['permissions']) del(version['changelog']) del(version['md5']) del(version['slug']) del(version['download']) if 'dbo_version' in version: del(version['dbo_version']) versions.append(version) data['versions'] = versions return c.jsonify(data)
def handler(event, context): log.info("Incoming event: %s", c.jsonify(event)) if not valid(event, event_schema): raise Exception( 'This lambda expects SNS events however have got unexpected event', event) responses = [] for rec in event['Records']: msg = message(rec) msg_id = rec['Sns']['MessageId'] log.debug("Checking if incoming message is a SNS test notification") if is_wakeup_message(msg): log.info('This is an ASG wakeup message. %s', c.jsonify(msg)) asg_name = msg['AutoScalingGroupName'] asg_obj = describe_asg(asg_name) wakeup_asg(asg_obj) # log.info(c.jsonify(asg_obj)) continue log.debug( "Checking if incoming message is valid ASG lifecycle hook message with metadata" ) if not valid(msg, ags_hook_msg_schema): log.error("Unexpected incoming message. Payllad: %s", c.jsonify(msg)) continue metadata = msg['NotificationMetadata'] r53_zone_id = metadata['HostedZoneId'] # r53_domain = metadata['r53_hosted_zone_domain'] asg_name = msg['AutoScalingGroupName'] instances = asg_running_instances(asg_name) try: resp = asg_client.complete_lifecycle_action( LifecycleHookName=msg['LifecycleHookName'], AutoScalingGroupName=msg['AutoScalingGroupName'], LifecycleActionToken=msg['LifecycleActionToken'], LifecycleActionResult='CONTINUE') responses.append(resp) log.debug("Completed ASG scaling event with: %s", resp) except botocore.exceptions.ClientError as e: log.error("Cannot finish autoscaling group event %s", e.message) log.info("Updating hosted zone %s record set", r53_zone_id) changes = { 'Comment': "Updated by AutoScalingGroupsng group: {}".format(asg_name), 'Changes': [{ 'Action': i['Action'], 'ResourceRecordSet': { 'Name': i['Name'], 'Type': i['Type'], 'TTL': int(i['TTL']), 'ResourceRecords': [{ 'Value': pystache.render(i['Template'], j) } for j in instances] } } for i in metadata['Changes']] } log.info(c.jsonify(changes)) r53_client.change_resource_record_sets(HostedZoneId=r53_zone_id, ChangeBatch=changes) responses.append({ "MessageId": msg_id, "Result": "Dns records {} and {} has been updated" }) return {'Responses': responses}
def msg(self): return jsonify(result="notInGame")
def msg(self): return jsonify(result="gameFull")
def msg(self): return jsonify(result="alreadyInGame")
def msg(self): return jsonify(result="gameExists")
def msg(self): return jsonify(result="badMaxPlayers")
def msg(self): return jsonify(result="badMap")