def test_transition_planned_unplanned(self): self.test_init_show_planned() show = Show.get_active_show() show.end = show.end - timedelta(minutes=15) rfk.database.session.commit() liquidsoaphandler.init_show(self.user) self.assertNotEqual(show, Show.get_active_show()) self.assertEqual(Show.get_active_show().flags & Show.FLAGS.UNPLANNED, Show.FLAGS.UNPLANNED)
def test_init_show_planned(self): begin = now()-timedelta(minutes=10) end = now()+timedelta(minutes=10) show = Show(begin=begin, end=end, name='titel', description='description', flags=Show.FLAGS.PLANNED) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(self.user) rfk.database.session.commit() self.test_do_connect_valid_user() self.assertEqual(show, show.get_active_show()) self.assertEqual(Show.get_active_show().flags & Show.FLAGS.PLANNED, Show.FLAGS.PLANNED)
def doAuth(username, password): """authenticates the user this function will also disconnect the current user if the user to be authenticated has a show registered. if that happened this function will print false to the user since we need a graceperiod to actually disconnect the other user. Keyword arguments: username password """ if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: if kick(): logger.info('kicking user') sys.stdout.write('false') return logger.info('accepted auth for %s' % (username,)) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('rejected auth for %s (invalid password)' % (username,)) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('rejected auth for %s (invalid user)' % (username,)) sys.stdout.write('false') rfk.database.session.commit()
def disco(): show = Show.get_active_show() ret = {} if show: user = show.get_active_user() ret['countryball'] = iso_country_to_countryball(user.country) ret['logo'] = show.get_logo(), else: ret['countryball'] = False ret['logo'] = False track = Track.current_track() if track: ret['track'] = { 'title': track.title.name, 'artist': track.title.artist.name, } #get listenerinfo for disco listeners = Listener.get_current_listeners() ret['listener'] = {} for listener in listeners: ret['listener'][listener.listener] = { 'listener': listener.listener, 'county': listener.country, 'countryball': iso_country_to_countryball(listener.country) } return ret
def doAuth(username, password): """authenticates the user this function will also disconnect the current user if the user to be authenticated has a show registered. if that happened this function will print false to the user since we need a graceperiod to actually disconnect the other user. Keyword arguments: username password """ if username == 'source': username, password = password.split(username_delimiter) try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: if kick(): logger.info('kicking user') sys.stdout.write('false') return logger.info('accepted auth for %s' %(username,)) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('rejected auth for %s (invalid password)' %(username,)) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('rejected auth for %s (invalid user)' %(username,)) sys.stdout.write('false') rfk.database.session.commit()
def now_playing(): try: ret = {} #gather showinfos show = Show.get_active_show() if show: user = show.get_active_user() if show.end: end = to_timestamp(to_user_timezone(show.end)) else: end = None ret['show'] = {'id': show.show, 'name': show.name, 'begin': to_timestamp(to_user_timezone(show.begin)), 'now': to_timestamp(to_user_timezone(now())), 'end': end, 'logo': show.get_logo(), 'type': Show.FLAGS.name(show.flags), 'user': {'countryball': iso_country_to_countryball(user.country)} } if show.series: ret['series'] = {'name': show.series.name} link_users = [] for ushow in show.users: link_users.append(make_user_link(ushow.user)) ret['users'] = {'links': natural_join(link_users)} #gather trackinfos track = Track.current_track() if track: ret['track'] = {'title': track.title.name, 'artist': track.title.artist.name, } #gather nextshow infos if show and show.end: filter_begin = show.end else: filter_begin = now() if request.args.get('full') == 'true': nextshow = Show.query.filter(Show.begin >= filter_begin).order_by(Show.begin.asc()).first(); if nextshow: ret['nextshow'] = {'name': nextshow.name, 'begin': to_timestamp(to_user_timezone(nextshow.begin)), 'logo': nextshow.get_logo()} if nextshow.series: ret['nextshow']['series'] = nextshow.series.name #get listenerinfo for disco listeners = Listener.get_current_listeners() ret['listener'] = {} for listener in listeners: ret['listener'][listener.listener] = {'listener': listener.listener, 'county': listener.country, 'countryball': iso_country_to_countryball(listener.country)} return jsonify({'success': True, 'data': ret}) except Exception as e: raise e return jsonify({'success': False, 'data': unicode(e)})
def test_transition_unplanned_planned(self): self.test_init_show_unplanned() show = Show.get_active_show() show.begin = show.begin - timedelta(minutes=5) rfk.database.session.commit() begin = now()-timedelta(minutes=3) end = now()+timedelta(minutes=10) show = Show(begin=begin, end=end, name='titel2', description='description2', flags=Show.FLAGS.PLANNED) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(self.other_user) rfk.database.session.commit() self.test_do_metadata() self.assertEqual(Show.get_active_show(), show)
def now_playing(): try: ret = {} #gather showinfos show = Show.get_active_show() if show: user = show.get_active_user() if show.end: end = int(to_user_timezone(show.end).strftime("%s")) * 1000 else: end = None ret['show'] = { 'id': show.show, 'name': show.name, 'begin': int(to_user_timezone(show.begin).strftime("%s")) * 1000, 'now': int(to_user_timezone(now()).strftime("%s")) * 1000, 'end': end, 'logo': show.get_logo(), 'type': Show.FLAGS.name(show.flags), 'user': { 'countryball': iso_country_to_countryball(user.country) } } if show.series: ret['series'] = {'name': show.series.name} link_users = [] for ushow in show.users: link_users.append(make_user_link(ushow.user)) ret['users'] = {'links': natural_join(link_users)} #gather nextshow infos if show and show.end: filter_begin = show.end else: filter_begin = now() if request.args.get('full') == 'true': nextshow = Show.query.filter(Show.begin >= filter_begin).order_by( Show.begin.asc()).first() if nextshow: ret['nextshow'] = { 'name': nextshow.name, 'begin': int(to_user_timezone(nextshow.begin).strftime("%s")) * 1000, 'logo': nextshow.get_logo() } if nextshow.series: ret['nextshow']['series'] = nextshow.series.name return jsonify({'success': True, 'data': ret}) except Exception as e: raise e return jsonify({'success': False, 'data': unicode(e)})
def show_add(): try: if 'begin' in request.form and \ 'description' in request.form and \ 'duration' in request.form and \ 'title' in request.form: if int(request.form['duration']) < 30: return emit_error(6, 'Duration too short') if int(request.form['duration']) > 1440: return emit_error(5, 'Duration too long') if len(request.form['title']) < 3: return emit_error(4, 'Title too short') if len(request.form['description']) == 0: return emit_error(3, 'Description is empty') begin = to_utc(get_timezone().localize( datetime.utcfromtimestamp(int(request.form['begin'])))) begin = begin.replace(second=0) end = begin + timedelta(minutes=int(request.form['duration'])) if begin < now(): return emit_error(2, 'You cannot enter a past date!') if Show.query.filter(Show.end > begin, Show.begin < end).count() > 0: return emit_error(1, 'Your show collides with other shows') show = Show(begin=begin, end=end, name=request.form['title'], description=request.form['description'], flags=Show.FLAGS.PLANNED) rfk.database.session.add(show) show.add_user(current_user) _set_show_info(show, request.form) rfk.database.session.commit() return jsonify({'success': True, 'data': None}) else: return emit_error( 0, 'Wait a second, are you trying to trick me again?!') except Exception as e: from rfk.site import app app.logger.error(e) return emit_error(0, 'something went horribly wrong')
def copy_shows(): local = pytz.timezone('Europe/Berlin') shows = oldsession.query(Show).yield_per(50) for oldshow in shows: if oldshow.streamer != None: user = User.get_user(username=oldshow.streamer.username) if oldshow.type == 'UNPLANNED': flag = NShow.FLAGS.UNPLANNED elif oldshow.type == 'PLANNED': flag = NShow.FLAGS.PLANNED show = NShow(name=oldshow.name[:50], description=oldshow.description, flags=flag, begin=local.normalize(local.localize(oldshow.begin).astimezone(pytz.utc)), end=local.normalize(local.localize(oldshow.end).astimezone(pytz.utc))) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(user) rfk.database.session.flush() rfk.database.session.commit()
def show_add(): try: if 'begin' in request.form and \ 'description' in request.form and \ 'duration' in request.form and \ 'title' in request.form: if int(request.form['duration']) < 30: return emit_error(6, 'Duration too short') if int(request.form['duration']) > 1440: return emit_error(5, 'Duration too long') if len(request.form['title']) < 3: return emit_error(4, 'Title too short') if len(request.form['description']) == 0: return emit_error(3, 'Description is empty') begin = to_utc(datetime.fromtimestamp(int(request.form['begin']))) begin = begin.replace(second=0) end = begin + timedelta(minutes=int(request.form['duration'])) if begin < now(): return emit_error(2, 'You cannot enter a past date!') if Show.query.filter(Show.end > begin, Show.begin < end).count() > 0: return emit_error(1, 'Your show collides with other shows') show = Show(begin=begin, end=end, name=request.form['title'], description=request.form['description'], flags=Show.FLAGS.PLANNED) rfk.database.session.add(show) show.add_user(current_user) _set_show_info(show, request.form) rfk.database.session.commit() return jsonify({'success': True, 'data': None}) else: return emit_error(0, 'Wait a second, are you trying to trick me again?!') except Exception as e: from rfk.site import app app.logger.error(e) return emit_error(0, 'something went horribly wrong')
def copy_shows(): local = pytz.timezone('Europe/Berlin') shows = oldsession.query(Show).yield_per(50) for oldshow in shows: if oldshow.streamer != None: user = User.get_user(username=oldshow.streamer.username) if oldshow.type == 'UNPLANNED': flag = NShow.FLAGS.UNPLANNED elif oldshow.type == 'PLANNED': flag = NShow.FLAGS.PLANNED show = NShow(name=oldshow.name[:50], description=oldshow.description, flags=flag, begin=local.normalize( local.localize(oldshow.begin).astimezone( pytz.utc)), end=local.normalize( local.localize(oldshow.end).astimezone(pytz.utc))) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(user) rfk.database.session.flush() rfk.database.session.commit()
def now_playing(): try: ret = {} #gather showinfos show = Show.get_active_show() if show: user = show.get_active_user() if show.end: end = int(to_user_timezone(show.end).strftime("%s")) * 1000 else: end = None ret['show'] = {'id': show.show, 'name': show.name, 'begin': int(to_user_timezone(show.begin).strftime("%s")) * 1000, 'now': int(to_user_timezone(now()).strftime("%s")) * 1000, 'end': end, 'logo': show.get_logo(), 'type': Show.FLAGS.name(show.flags), 'user': {'countryball': iso_country_to_countryball(user.country)} } if show.series: ret['series'] = {'name': show.series.name} link_users = [] for ushow in show.users: link_users.append(make_user_link(ushow.user)) ret['users'] = {'links': natural_join(link_users)} #gather nextshow infos if show and show.end: filter_begin = show.end else: filter_begin = now() if request.args.get('full') == 'true': nextshow = Show.query.filter(Show.begin >= filter_begin).order_by(Show.begin.asc()).first(); if nextshow: ret['nextshow'] = {'name': nextshow.name, 'begin': int(to_user_timezone(nextshow.begin).strftime("%s")) * 1000, 'logo': nextshow.get_logo()} if nextshow.series: ret['nextshow']['series'] = nextshow.series.name return jsonify({'success': True, 'data': ret}) except Exception as e: raise e return jsonify({'success': False, 'data': unicode(e)})
def liquidsoap_auth(): """Authenticates a user This function will also disconnect the current user if the user to be authenticated has a show registered. If that happens this function will print false to the user since we need a grace period to actually disconnect the other user. Which means that the user has to reconnect! Keyword arguments: - username - password """ data = request.get_json() username, password = data['username'], data['password'] if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: logger.info('liquidsoap_auth: cleaning harbor because of planned show') if kick(): logger.info('liquidsoap_auth: harbor is now clean, reconnect pl0x') session.commit() return 'false' else: logger.info('liquidsoap_auth: harbor was empty, go ahead') logger.info('liquidsoap_auth: accepted auth for %s' % username) session.commit() return 'true' except rexc.base.InvalidPasswordException: logger.info('liquidsoap_auth: rejected auth for %s (invalid password)' % username) session.commit() return 'false' except rexc.base.UserNotFoundException: logger.info('liquidsoap_auth: rejected auth for %s (invalid user)' % username) session.commit() return 'false'
def doAuth(username, password): """Authenticates a user This function will also disconnect the current user if the user to be authenticated has a show registered. If that happens this function will print false to the user since we need a grace period to actually disconnect the other user. (Which means that the user has to reconnect.) Keyword arguments: - username - password """ if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: logger.info('doAuth: cleaning harbor because of planned show') if kick(): sys.stdout.write('false') logger.info('doAuth: harbor is now clean, reconnect pl0x') rfk.database.session.commit() return else: logger.info('doAuth: harbor was empty, go ahead') logger.info('doAuth: accepted auth for %s' % username) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('doAuth: rejected auth for %s (invalid password)' % username) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('doAuth: rejected auth for %s (invalid user)' % username) sys.stdout.write('false') rfk.database.session.commit()
def doAuth(username, password): """Authenticates a user This function will also disconnect the current user if the user to be authenticated has a show registered. If that happens this function will print false to the user since we need a grace period to actually disconnect the other user. (Which means that the user has to reconnect.) Keyword arguments: - username - password """ if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: logger.info('cleaning harbor') if kick(): sys.stdout.write('false') logger.info('harbor is now clean, reconnect pl0x') rfk.database.session.commit() return else: logger.info('harbor was empty, go ahead') logger.info('accepted auth for %s' % (username)) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('rejected auth for %s (invalid password)' % (username)) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('rejected auth for %s (invalid user)' % (username)) sys.stdout.write('false') rfk.database.session.commit()
def test_init_show_planned(self): begin = now() - timedelta(minutes=10) end = now() + timedelta(minutes=10) show = Show(begin=begin, end=end, name='titel', description='description', flags=Show.FLAGS.PLANNED) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(self.user) rfk.database.session.commit() self.test_do_connect_valid_user() self.assertEqual(show, show.get_active_show()) self.assertEqual(Show.get_active_show().flags & Show.FLAGS.PLANNED, Show.FLAGS.PLANNED)
def disco(): show = Show.get_active_show() ret = {} if show: user = show.get_active_user() ret['countryball'] = iso_country_to_countryball(user.country) ret['logo'] = show.get_logo(), else: ret['countryball'] = False ret['logo'] = False track = Track.current_track() if track: ret['track'] = {'title': track.title.name, 'artist': track.title.artist.name, } #get listenerinfo for disco listeners = Listener.get_current_listeners() ret['listener'] = {} for listener in listeners: ret['listener'][listener.listener] = {'listener': listener.listener, 'county': listener.country, 'countryball': iso_country_to_countryball(listener.country)} return ret
def test_transition_unplanned_planned(self): self.test_init_show_unplanned() show = Show.get_active_show() show.begin = show.begin - timedelta(minutes=5) rfk.database.session.commit() begin = now() - timedelta(minutes=3) end = now() + timedelta(minutes=10) show = Show(begin=begin, end=end, name='titel2', description='description2', flags=Show.FLAGS.PLANNED) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(self.other_user) rfk.database.session.commit() self.test_do_metadata() self.assertEqual(Show.get_active_show(), show)
def init_show(user): """Initializes a show it either takes a planned show or an unplanned show if it's still running if non of them is found a new unplanned show is added and initialized if a new show was initialized the old one will be ended and the streamer status will be resetted """ show = Show.get_current_show(user) if show is None: show = Show() if user.get_setting(code='use_icy'): show.add_tags( Tag.parse_tags(user.get_setting(code='icy_show_genre') or '')) show.description = user.get_setting( code='icy_show_description') or '' show.name = user.get_setting(code='icy_show_name') or '' else: show.add_tags( Tag.parse_tags(user.get_setting(code='show_def_tags') or '')) show.description = user.get_setting(code='show_def_desc') or '' show.name = user.get_setting(code='show_def_name') or '' show.logo = user.get_setting(code='show_def_logo') or None show.flags = Show.FLAGS.UNPLANNED show.add_user(user) elif show.flags == Show.FLAGS.UNPLANNED: # just check if there is a planned show to transition to s = Show.get_current_show(user, only_planned=True) if s is not None: show = s us = show.get_usershow(user) us.status = UserShow.STATUS.STREAMING rfk.database.session.commit() unfinished_shows = UserShow.query.filter( UserShow.status == UserShow.STATUS.STREAMING, UserShow.show != show).all() for us in unfinished_shows: if us.show.flags & Show.FLAGS.UNPLANNED: us.show.end_show() if us.status == UserShow.STATUS.STREAMING: us.status = UserShow.STATUS.STREAMED rfk.database.session.commit() return show
def api_legacy(): '''lazy people...''' apikey = request.args.get("apikey") if apikey != '86c6c5162aa6845906cff55320ea8608991358c3': return '' #ltid=0&w=track%2Clistener%2Cdj%2Cshow%2Cnextshows, ret = {} listeners = Listener.query.filter(Listener.disconnect == None).all() tmp = {} for listener in listeners: if listener.stream_relay.stream.code in tmp: tmp[listener.stream_relay.stream.code]['c'] += 1 else: tmp[listener.stream_relay.stream.code] = { 'c': 1, 'name': listener.stream_relay.stream.code, 'description': listener.stream_relay.stream.name } ret['listener'] = tmp.values() currtrack = Track.current_track() ltid = request.args.get("apikey") if currtrack and ltid != currtrack.track: ret['trackid'] = currtrack.track ret['title'] = currtrack.title.name ret['artist'] = currtrack.title.artist.name show = Show.get_active_show() if show: user = show.get_active_user() ret['dj'] = user.username ret['djid'] = user.user ret['status'] = 'STREAMING' ret['showbegin'] = int(to_user_timezone(show.begin).strftime("%s")) if show.end: ret['showend'] = int(to_user_timezone(show.end).strftime("%s")) else: ret['showend'] = None ret['showtype'] = 'PLANNED' ret['showname'] = show.name ret['showdescription'] = show.description ret['showid'] = show.show ret['showthread'] = None ret['showdj'] = user.username ret['showdjid'] = user.user ret['shows'] = [] if show and show.end: filter_begin = show.end else: filter_begin = now() nextshow = Show.query.filter(Show.begin >= filter_begin).order_by( Show.begin.asc()).first() if nextshow: arr = {} arr['showbegin'] = int(to_user_timezone(nextshow.begin).strftime("%s")) if nextshow.end: arr['showend'] = int(to_user_timezone(nextshow.end).strftime("%s")) else: arr['showend'] = None arr['showtype'] = 'PLANNED' arr['showname'] = nextshow.name arr['showdescription'] = nextshow.description arr['showid'] = nextshow.show arr['showdj'] = nextshow.users[0].user.username arr['showdjid'] = nextshow.users[0].user.user arr['showthread'] = None ret['shows'].append(arr) return jsonify(ret)
def api_legacy(): '''lazy people...''' apikey = request.args.get("apikey") if apikey != '86c6c5162aa6845906cff55320ea8608991358c3': return '' #ltid=0&w=track%2Clistener%2Cdj%2Cshow%2Cnextshows, ret = {} listeners = Listener.query.filter(Listener.disconnect == None).all() tmp = {} for listener in listeners: if listener.stream_relay.stream.code in tmp: tmp[listener.stream_relay.stream.code]['c'] += 1 else: tmp[listener.stream_relay.stream.code] = {'c': 1, 'name': listener.stream_relay.stream.code, 'description': listener.stream_relay.stream.name} ret['listener'] = tmp.values() currtrack = Track.current_track() ltid = request.args.get("apikey") if currtrack and ltid != currtrack.track: ret['trackid'] = currtrack.track ret['title'] = currtrack.title.name ret['artist'] = currtrack.title.artist.name show = Show.get_active_show() if show: user = show.get_active_user() ret['dj'] = user.username ret['djid'] = user.user ret['status'] = 'STREAMING' ret['showbegin'] = int(to_user_timezone(show.begin).strftime("%s")) if show.end: ret['showend'] = int(to_user_timezone(show.end).strftime("%s")) else: ret['showend'] = None ret['showtype'] = 'PLANNED'; ret['showname'] = show.name ret['showdescription'] = show.description ret['showid'] = show.show ret['showthread'] = None; ret['showdj'] = user.username ret['showdjid'] = user.user ret['shows'] = [] if show and show.end: filter_begin = show.end else: filter_begin = now() nextshow = Show.query.filter(Show.begin >= filter_begin).order_by(Show.begin.asc()).first() if nextshow: arr = {} arr['showbegin'] = int(to_user_timezone(nextshow.begin).strftime("%s")) if nextshow.end: arr['showend'] = int(to_user_timezone(nextshow.end).strftime("%s")) else: arr['showend'] = None arr['showtype'] = 'PLANNED'; arr['showname'] = nextshow.name; arr['showdescription'] = nextshow.description; arr['showid'] = nextshow.show; arr['showdj'] = nextshow.users[0].user.username; arr['showdjid'] = nextshow.users[0].user.user; arr['showthread'] = None; ret['shows'].append(arr) return jsonify(ret)
def init_show(user): """Initializes a show it either takes a planned show or an unplanned show if it's still running if non of them is found a new unplanned show is added and initialized if a new show was initialized the old one will be ended and the streamer status will be resetted """ show = Show.get_current_show(user) if show is None: show = Show() if user.get_setting(code='use_icy'): show.add_tags(Tag.parse_tags(user.get_setting(code='icy_show_genre') or '')) show.description = user.get_setting(code='icy_show_description') or '' show.name = user.get_setting(code='icy_show_name') or '' else: show.add_tags(Tag.parse_tags(user.get_setting(code='show_def_tags') or '')) show.description = user.get_setting(code='show_def_desc') or '' show.name = user.get_setting(code='show_def_name') or '' show.logo = user.get_setting(code='show_def_logo') or None show.flags = Show.FLAGS.UNPLANNED show.add_user(user) elif show.flags == Show.FLAGS.UNPLANNED: # just check if there is a planned show to transition to s = Show.get_current_show(user, only_planned=True) if s is not None: show = s us = show.get_usershow(user) us.status = UserShow.STATUS.STREAMING rfk.database.session.commit() unfinished_shows = UserShow.query.filter(UserShow.status == UserShow.STATUS.STREAMING, UserShow.show != show).all() for us in unfinished_shows: if us.show.flags & Show.FLAGS.UNPLANNED: us.show.end_show() if us.status == UserShow.STATUS.STREAMING: us.status = UserShow.STATUS.STREAMED rfk.database.session.commit() return show
def test_init_show_unplanned(self): self.test_do_connect_valid_user() self.test_do_metadata() self.assertEqual(Show.get_active_show().flags & Show.FLAGS.UNPLANNED, Show.FLAGS.UNPLANNED)
def test_disconnect(self): liquidsoaphandler.doDisconnect(1) self.assertEqual(Show.get_active_show(), None) self.assertEqual(Track.current_track(), None)