1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import werkzeug
user_agent = werkzeug.UserAgent('swag/2.25.1 (iPhone; iOS 11.4.1; Scale/2.00; com.live.swag.enterprise; zh-tw)') user_preferences = ['gender:female', 'gender:male'] user_tags = ['beta', 'vip'] user_platforms = [user_agent.platform]
def stages(): now = utils.utcnow()
yield {'$match': { '$and': [ {'nbf': {'$lte': now}}, {'exp': {'$gt': now}}, {'requirements': {'$elemMatch': { 'preferences': {'$not': {'$elemMatch': {'$nin': user_preferences}}}, 'tags': {'$not': {'$elemMatch': {'$nin': user_tags}}}, 'platforms': {'$not': {'$elemMatch': {'$nin': user_platforms}}}, '$or': [ {'$and': [ {'version_major_min': {'$lte': user_agent.version.major}}, {'version_minor_min': {'$lte': user_agent.version.minor}}, ]}, {'$and': [ {'version_minor_min': {'$exists': False}}, {'version_minor_min': {'$exists': False}}, ]}, ], }}}, ], }} yield {'$project': { 'name': True, 'nbf': True, 'exp': True, 'positions': {'$objectToArray': '$positions'}, }} yield {'$unwind': '$positions'} yield {'$sort': { 'exp': 1, }} yield {'$project': { '_id': False, 'name': True, 'position': '$positions.k', 'url': {'$arrayElemAt': ['$positions.v.urls', 0]}, 'startedAt': {'$floor': {'$divide': [{'$subtract': ['$nbf', constants.UNIX_EPOCH]}, 1000]}}, 'endedAt': {'$floor': {'$divide': [{'$subtract': ['$exp', constants.UNIX_EPOCH]}, 1000]}}, }} yield {'$group': { '_id': '$position', 'items': {'$push': '$$ROOT'}, }}
try: docs = Promotion.objects.aggregate(*stages()) except StopIteration: docs = [] else: docs = list(docs)
|