def register(): """Register a new establishment.""" if request.method == 'POST': form = RegisterEstablishment(request.form) recaptcha = { 'secret': RECAPTCHA_SECRET, 'response': request.form.get('g-recaptcha-response'), 'remoteip': request.remote_addr } if form.validate() and verify_recaptcha(**recaptcha): session = db_session() session.add(Establishment(**form.data)) session.commit() session.close() return 'OK' else: return render_template('register.html', product_name=PRODUCT_NAME, page_name='Register', form=form) else: return render_template('register.html', PRODUCT_NAME=PRODUCT_NAME, page_name='Register', form=RegisterEstablishment())
def banned(establishment_id, video_id): """See if video was already requested.""" session = db_session() result = session.query(exists().where(and_(Request.video_id == video_id, Request.establishment_id == establishment_id, Request.state == 4))).scalar() session.close() return result
def establishment_registered(form, field): """Validates if the establishment has already been registered.""" form = form name = field.data session = db_session() result = session.query(exists().where(Establishment.name == name)).scalar() session.close() if result: raise ValidationError( 'Establishment {name} is already registered!'.format(name=name))
def new_requester_id(): session = db_session() id = session.query(func.max(Requester.id)).scalar() if not id: id = 0 id += 1 session.add(Requester(id=id)) session.commit() session.close() return id
def get_currently_playing(establishment_id): """See if video was already requested.""" session = db_session() result = session.query(Request).\ filter(Request.establishment_id == establishment_id, Request.state == 1).first() session.close() if result: result.youtube = youtube_list([result.video_id])[0] return result else: return None
def get_establishment(establishment_id=None, name=None): """Get establishment info""" session = db_session() if establishment_id: result = session.query(Establishment).filter( Establishment.id == establishment_id).first() return (object_as_dict(result)) if name: result = session.query(Establishment).filter( Establishment.name == name).first() return (object_as_dict(result))
def ban(establishment_id, video_id): """Ban the request.""" title = youtube_list([video_id])[0]['title'] session = db_session() session.query(Request).filter(Request.establishment_id == establishment_id, Request.video_id == video_id)\ .update({'state': 4}, synchronize_session=False) session.commit() session.close() message = u'Banned {title}!'.format(title=title) flash(message, 'success') return redirect(url_for('request_music'))
def calculate_yei_points(base_points=500, max_points=2500): """See if video was already requested.""" now = datetime.utcnow() session = db_session() db_result = session.query(AdditionalRequestInformation).\ order_by(AdditionalRequestInformation.requested_time.desc()).\ first() session.close() requested_time = datetime.strptime(db_result.requested_time, '%Y-%m-%d %H:%M:%S') yei_points = int( round(base_points + ((now - requested_time).total_seconds() * .5))) if yei_points > max_points: return max_points else: return yei_points
def additional_request_information(establishment_id, video_id): """Add additional request information.""" if request.method == 'POST': form = SetAdditionalRequestInformation(request.form) if form.validate(): with open("/tmp/yei", "a") as yei_file: points = calculate_yei_points() yei_file.write('{points},{form_data}\n'.format(points=points, form_data=str( form.data))) # flash('{points} YEI points will be given to {performer}!'.format(points=points, performer=str(form.performer.data)), 'success') session = db_session() record = Request(establishment_id=establishment_id, requester_id=request.cookies['requester_id'], video_id=video_id, state=0) session.add(record) session.flush() request_id = record.id session.add( AdditionalRequestInformation(request_id=request_id, **form.data)) current_request_made_by_human = session.query(Request).filter( Request.establishment_id == establishment_id, Request.state == 1, Request.requester_id != 0).count() if not current_request_made_by_human: session.query(Request).filter(Request.establishment_id == establishment_id, Request.state == 1)\ .update({'state': 3}, synchronize_session=False) session.commit() session.close() return redirect(url_for('request_music')) else: return render_template('additional_request_information.html', product_name=PRODUCT_NAME, page_name='Additional Request Information', form=form) else: return render_template('additional_request_information.html', PRODUCT_NAME=PRODUCT_NAME, page_name='Additional Request Information', form=SetAdditionalRequestInformation())
def get_requests(establishment_id): """See if video was already requested.""" session = db_session() db_results = session.query(Request).\ filter(Request.establishment_id == establishment_id, Request.state == 0) session.close() youtube_results = youtube_list([_.video_id for _ in db_results]) results = [] for db_result in db_results: for youtube_result in youtube_results: if db_result.video_id == youtube_result['videoId']: db_result.youtube = youtube_result results.append(db_result) return results
def get_all_requests(establishment_id): """See if video was already requested.""" session = db_session() results = session.query(select([Request.video_id, func.max(Request.state)]).\ where(Request.establishment_id == establishment_id).\ group_by(Request.video_id)).all() session.close() video_ids_state = [{_[0]: _[1]} for _ in results] video_data = [] for chunk in chunks( list(set().union(*(d.keys() for d in video_ids_state))), 50): video_data += youtube_list(chunk) for video in video_data: video_id = video['videoId'] state = [s[video_id] for s in video_ids_state if video_id in s][0] video['state'] = state return video_data
def submit_request(establishment_id, mode, video_id): """Submits the request.""" if 'requester_id' in request.cookies: if 'establishment_id' not in request.cookies or request.cookies[ 'establishment_id'] == '0': response = make_response(redirect(url_for('set_establishment'))) response.set_cookie('video_id', video_id) return response request_valid, message = validate_request( request.cookies['requester_id'], establishment_id, video_id) if request_valid: if mode in ['karaoke']: flash(message, 'success') return redirect( url_for('additional_request_information', establishment_id=establishment_id, video_id=video_id)) else: session = db_session() session.add( Request(establishment_id=establishment_id, requester_id=request.cookies['requester_id'], video_id=video_id, state=0)) session.commit() session.close() flash(message, 'success') else: flash(message, 'error') else: flash('No cookies set. Please ensure cookies are enabled!', 'error') return redirect(url_for('request_music'))
def request_amount(requester_id): print(requester_id) session = db_session() amount = session.query(Request).filter(Request.requester_id == requester_id, Request.state == 0).count() return amount
def get(self, establishment_id, action, video_id=None): """GET call to API""" session = db_session() value = True additional_request_information = {} youtube = {} establishment = get_establishment(establishment_id) establishment.pop('password', None) if action == 'playing': session.query(Request).filter_by(establishment_id=establishment_id, state=1).update({'state': 2}) session.commit() session.query(Request).filter_by(establishment_id=establishment_id, video_id=video_id, state=0).update({'state': 1}) elif action == 'next': row = session.query(Request)\ .filter_by(establishment_id=establishment_id, state=0)\ .order_by(Request.requested_time)\ .first() if row: request = { c.name: getattr(row, c.name) for c in row.__table__.columns } if row.additional_request_information: additional_request_information = { c.name: getattr(row.additional_request_information, c.name) for c in row.additional_request_information.__table__.columns } video_id = request['video_id'] else: playlist_video_ids = youtube_playlistitems( 'PLBSQz25Ioz5Wo8KKaOLtpj224vD27_97P') played_video_ids = session.query(Request.video_id).\ filter_by(establishment_id=establishment_id, state=2) played_video_ids = [_[0] for _ in played_video_ids] played_video_ids = sample(played_video_ids, int(len(playlist_video_ids) * .3)) video_ids = playlist_video_ids + played_video_ids valid = False while not valid: video_id = choice(video_ids) valid, message = validate_request(0, establishment_id, video_id) if not valid: results = youtube_search( video_id, establishment['autoplay_safesearch'], related_to=True) if results: video_id = choice(results)['videoId'] valid, message = validate_request( 0, establishment_id, video_id) session = db_session() session.add( Request(establishment_id=establishment_id, requester_id=0, video_id=video_id, state=0)) session.commit() elif action == 'skip': state = session.query(Request.state)\ .filter_by(establishment_id=establishment_id, video_id=video_id)\ .order_by(Request.requested_time.desc())\ .limit(1)\ .scalar() if state not in [3, 4]: value = False else: value = True elif action == 'requests': requests = get_requests(establishment_id) if len(requests) > 0: request = { c.name: getattr(requests[0], c.name) for c in requests[0].__table__.columns } if requests[0].additional_request_information: additional_request_information = { c.name: getattr(requests[0].additional_request_information, c.name) for c in requests[0].additional_request_information. __table__.columns } youtube = requests[0].youtube else: value = False elif action == 'yei': value = calculate_yei_points() session.commit() session.close() response = self.merge_two_dicts(establishment, additional_request_information) response = self.merge_two_dicts(response, youtube) response = self.merge_two_dicts(response, { 'action': action, 'value': value, 'video_id': video_id, 'status': 'OK' }) return response