def webapp_post_message(): """Try to queue a message for a user. Returns the message's position in the queue. Raises ChillOut if the user has posted too many messages recently. """ user_id = request.values['userId'] message = request.values['message'] prev = pymongo.db.posts.find_one({'poster_id': user_id}, sort=[('submitted', DESCENDING)]) if (prev is not None and prev['submitted'] + USER_POST_THROTTLE > tznow()): resp = jsonify(response="error - too many attempts") resp.status_code = 400 return resp post = { 'message': message, 'poster_id': user_id, 'submitted': tznow(), 'extender_ids': [user_id], } pymongo.db.posts.insert(post) return jsonify(status='cool')
def seed(): """seed some stuff""" # qr code # sms code # initial message app.pymongo.db.posts.insert({ 'message': 'The first post', 'submitted': tznow() - timedelta(minutes=60), 'showtime': tznow() - timedelta(minutes=50), })
def episode_menu(): et_tz = pytz.timezone('US/Eastern') date_et = common.get_date() if vars.params.get('custom_date', False) else utils.tznow(et_tz).date() # Avoid possible caching by using query string epg_url = 'https://nlnbamdnyc-a.akamaihd.net/fs/nba/feeds/epg/%d/%d_%d.js?t=%d' % ( date_et.year, date_et.month, date_et.day, time.time()) response = utils.fetch(epg_url) g_epg = json.loads(response[response.find('['):]) for epg_item in g_epg: entry = epg_item['entry'] start_et_hours, start_et_minutes = map(int, entry['start'].split(':')) duration_hours, duration_minutes = map(int, entry['duration'].split(':')) dt_et = et_tz.localize(datetime.datetime(date_et.year, date_et.month, date_et.day, start_et_hours, start_et_minutes)) dt_utc = dt_et.astimezone(pytz.utc) start_timestamp = int((dt_utc - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000 # in milliseconds duration = (duration_hours * 60 + duration_minutes) * 60 * 1000 # in milliseconds params = { 'start_timestamp': start_timestamp, 'duration': duration, } utils.log(params, xbmc.LOGDEBUG) name = '%s %s: %s' % ( entry['start'], dt_et.tzname(), entry['showTitle'] if entry['showTitle'] else entry['title']) common.addListItem(name, '', 'nba_tv_play_episode', iconimage=entry['image'], customparams=params)
def check_in_with_sms_code(phone_number, code): """Check in (and possibly create) a user, verified by the active code. Returns the user's data, or raises InvalidCodeException if the code is wrong or expired. """ if not check_sms_code(code): raise InvalidCodeException("You There has been an error") user = pymongo.db.users.find_one({'phone_number': phone_number}) if user is None: # so racey user = { 'phone_number': phone_number, 'created': tznow(), } user['last_checkin'] = tznow() pymongo.db.users.save(user) return user
def update_showing(): next_ = pymongo.db.posts.find_one({'showtime': {'$exists': False}}, sort=[('submitted', ASCENDING)]) if next_ is not None: print('changing...') pymongo.db.posts.update({'_id': next_['_id']}, {'$set': {'showtime': tznow()}}) else: print('nothing in the queue') socket_push(key='new_message', val=get_current_post()['message'])
def create_account_with_qr_code(code): """Creates a new user with a QR code.""" if not check_qr_code(code): raise InvalidCodeException('You There has been an error -- wrong qr code yooy') now = tznow() user = { 'qr_code': code, 'created': now, 'last_checkin': now, } pymongo.db.users.insert(user) return user
def post_message(user, message): """Try to queue a message for a user. Returns the message's position in the queue. Raises ChillOut if the user has posted too many messages recently. """ user_id = user['_id'] prev = pymongo.db.posts.find_one({'poster_id': user_id}, sort=[('submitted', DESCENDING)]) if (prev is not None and prev['submitted'] + USER_POST_THROTTLE > tznow()): raise ChillOut('Whoa. Chill out, hey. So many messages.') post = { 'message': message, 'poster_id': user_id, 'submitted': tznow(), 'extender_ids': [user_id], } pymongo.db.posts.insert(post) return get_queue().count()
def check_in_with_qr_code(user_id, code): """Check in an existing user with a QR code.""" try: user_oid = ObjectId(user_id) except InvalidId: raise NoSuchUserException('nope nuttin') user = pymongo.db.users.find_one({'_id': ObjectId(user_id)}) ## ERRROROING if user is None: raise NoSuchUserException('no user exists with id {}'.format(user_id)) if not check_qr_code(code): raise InvalidCodeException('You There has been an error -- wrong qr code yoyo') user['last_checkin'] = tznow() pymongo.db.users.save(user)
def check_sms_code(test_code): """Checks whether the SMS code is currently valid.""" codes = pymongo.db.smscodes.find(sort=[('created', DESCENDING)]) current = next(codes) if test_code == current['code']: return True else: previous = next(codes) if (test_code == previous['code'] and tznow() - current['created'] < SMS_CODE_GRACE): return True else: return False
def get_sms_code(): """Fetches the most up-to-date SMS code for the billboard. This may trigger a new code if one is due. """ codes = pymongo.db.smscodes.find(sort=[('created', DESCENDING)]) try: current = next(codes) except StopIteration: # empty database current = create_sms_code() if current['created'] + SMS_CODE_RESET < tznow(): # yo, WARNING: off to the races! current = create_sms_code() return current
def create_sms_code(): """Create a new code. More races woo!""" while True: code = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz1234567890') for _ in range(6)) existing_with_code = pymongo.db.smscodes.find_one({'code': code}) if existing_with_code is None: break new_sms = { 'code': code, 'created': tznow() } pymongo.db.smscodes.insert(new_sms) socket_push(key='new_sms', val=new_sms['code']) return new_sms
def refresh_qr_code(): """Create a new one""" while True: code = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz1234567890') for _ in range(9)) existing_with_code = pymongo.db.qrcodes.find_one({'code': code}) if existing_with_code is None: break new_qr = { 'code': code, 'created': tznow() } pymongo.db.qrcodes.insert(new_qr) socket_push(key='new_qr', val=new_qr['code']) return new_qr
def is_checked_in(user): """Test whether a user is checked in or not.""" if user is None: return False a_ok = user['last_checkin'] + USER_CHECKIN_EXPIRE > tznow() return a_ok