def remove(self, item): item = map_item(item) bots = mongo.db.bots class_id = item.get('class_id') instance_id = item.get('instance_id') amount = int(item['amount']) if amount <= 0: return query = { 'class_id': class_id, 'instance_id': instance_id, } bots.update( { '_id': self.bot['_id'], 'inventory': {'$elemMatch': query}, }, {'$inc': {'inventory.$.amount': -amount}}, ) query['amount'] = {'$lte': 0} bots.update( {'_id': self.bot['_id']}, {'$pull': {'inventory': query}}, )
def user_inventory(_id): if request.method == 'GET': inventory = (mongo.db.users.find_one( {'_id': _id}, {'_id': 0, 'inventory': 1} ) or {}).get('inventory', {}) return fill_items(inventory) elif request.json: inventory = request.json.get('inventory', {}) if inventory: items = [] for app, ctx, item, desc in flatten_inventory(inventory): item.update({ 'app_id': app, 'context_id': ctx, }) items.append(map_item(item)) mongo.db.users.update( {'_id': _id}, {'$set': { 'inventory': items, 'times.inventory': time.time(), }}, ) insert_items(inventory, foreign=True) return {}
def add(self, item, sync=False): item = map_item(item) bots = mongo.db.bots app_id = item.get('app_id') context_id = item.get('context_id') class_id = item.get('class_id') instance_id = item.get('instance_id') amount = int(item['amount']) new = { 'app_id': app_id, 'context_id': context_id, 'class_id': class_id, 'instance_id': instance_id, 'amount': 0, } query = { 'class_id': class_id, 'instance_id': instance_id, } bots.update( { '_id': self.bot['_id'], 'inventory': {'$not': {'$elemMatch': query}}, }, {'$push': {'inventory': new}}, ) if sync: mod = '$set' else: mod = '$inc' old = bots.find_and_modify( { '_id': self.bot['_id'], 'inventory': {'$elemMatch': query}, }, {mod: {'inventory.$.amount': amount}}, fields={'inventory': 1}, ) if sync: # boo, can't properly filter the results of the find_and_modify # so we'll do it here if old: old_amount = 0 key = (class_id, instance_id) for i in old['inventory']: if (i['class_id'], i['instance_id']) == key: old_amount = int(i['amount']) break item['amount'] -= old_amount return item