Exemplo n.º 1
0
def generate_listener_peak(user):
    role_host = Role.get_role('host')
    user_listener_max = 0

    shows = Show.query.join(UserShow).filter(UserShow.user == user,
                                             UserShow.role == role_host,
                                             UserShow.status == UserShow.STATUS.STREAMED,
                                             Show.end <= now()).yield_per(50)

    for show in shows:
        try:
            stats_total = Statistic.query.filter(Statistic.identifier == 'lst-total').one()
            stats = stats_total.get(start=show.begin, stop=show.end)
        except exc.NoResultFound:
            stats = None

        if stats and stats.count() > 0:
            for stat in stats:
                if stat.value > user_listener_max:
                    user_listener_max = stat.value

    if user_listener_max > 0:
        us = UserStatistic.get_userstatistic(user, 'listenerpeak')
        us.statistic.set(now(), user_listener_max)
        rfk.database.session.flush()
Exemplo n.º 2
0
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)})
Exemplo n.º 3
0
def relay_sparkline(relay):
    relay = Relay.query.get(relay)
    rs = RelayStatistic.get_relaystatistic(relay, RelayStatistic.TYPE.TRAFFIC)
    start = now()-timedelta(hours=6)
    dps = []
    for dp in rs.statistic.get(start=start, stop=now()):
        dps.append((int(dp.timestamp.strftime('%s')), dp.value))
    return jsonify({'datapoints': dps})
Exemplo n.º 4
0
def listeners():

    # check if current_user is logged in and if user is streaming or if user is admin
    if not current_user.is_anonymous():
        is_streaming = UserShow.query.join(User).filter(UserShow.status == UserShow.STATUS.STREAMING, UserShow.user == current_user).first()
        if is_streaming or current_user.has_permission('admin'):
            show_listener_list = True
        else:
            show_listener_list = False
    else:
        show_listener_list = False

    # get current bandwidth of all active relays
    total_bandwidth = 0
    relays = Relay.query.filter(Relay.status == Relay.STATUS.ONLINE).all()
    active_relays = len(relays)
    for relay in relays:
        total_bandwidth += relay.usage
    total_bandwidth *= 128 # convert kbit to byte

    # get all current listeners
    current_listener = Listener.get_current_listeners()

    # generate per country stats
    per_country = {}
    for listener in current_listener:
        country = listener.country
        try:
            per_country[country]['count'] += 1
        except KeyError:
            per_country[country] = {'count': 1}
            per_country[country]['ball'] = country
    per_country = sorted(per_country.iteritems(), key=lambda (k, v): v['count'], reverse=True)

    # get recent listener count to calculate a trend
    try:
        stats_total = Statistic.query.filter(Statistic.identifier == 'lst-total').one()
        stats = stats_total.get(start=now() - datetime.timedelta(minutes=2), stop=now())
    except exc.NoResultFound:
        stats = None

    if stats and stats.count() > 0:
        listener_sum = 0
        for stat in stats:
            listener_sum += stat.value
        average_listeners = listener_sum / stats.count()
    else:
        average_listeners = len(current_listener)

    return render_template('listenergraph.html', TITLE='Listeners', show_listener_list=show_listener_list,
                           listeners=current_listener, per_country=per_country, total_bandwidth=total_bandwidth,
                           active_relays=active_relays, average_listeners=average_listeners)
 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)
Exemplo n.º 6
0
    def check_key(key):

        try:
            apikey = ApiKey.query.filter(ApiKey.key == key).one()
        except (exc.NoResultFound, exc.MultipleResultsFound):
            raise rexc.api.KeyInvalidException()
        if apikey.flag & ApiKey.FLAGS.DISABLED:
            raise rexc.api.KeyDisabledException()
        elif not apikey.flag & ApiKey.FLAGS.FASTQUERY:
            if now() - apikey.access <= timedelta(seconds=1):
                raise rexc.api.FastQueryException(last_access=apikey.access)

        apikey.counter += 1
        apikey.access = now()
        return apikey
Exemplo n.º 7
0
 def set_offline(self):
     """sets this combination of stream and relay to offline"""
     self.status = StreamRelay.STATUS.OFFLINE
     connected_listeners = Listener.query.filter(Listener.stream_relay == self,
                                                 Listener.disconnect == None).all()
     for listener in connected_listeners:
         listener.disconnect = now()
Exemplo n.º 8
0
def login():
    form = login_form(request.form)
    if request.method == 'POST' and form.validate():
        username = form.username.data
        try:
            user = User.get_user(username=username)
            if user and user.check_password(password=form.password.data):
                user.authenticated = True
                remember = form.remember.data
                if login_user(user, remember=remember):
                    user.last_login = now()
                    loc = rfk.helper.get_location(request.remote_addr)
                    if 'country_code' in loc and loc['country_code'] is not None:
                        user.country = loc['country_code']
                    rfk.database.session.commit()
                    flash('Logged in!', 'success')
                    return redirect(request.args.get('next') or url_for('index'))
                else:
                    form.username.errors.append('There was an error while logging you in.')
                    flash('There was an error while logging you in.', 'error')
            else:
                form.username.errors.append('Invalid User or Password.')
                flash('Invalid username or password.')
        except UserNotFoundException:
            form.username.errors.append('Invalid User or Password.')
            flash('Invalid username or password.')
    return render_template('login.html', form=form, TITLE='Login')
Exemplo n.º 9
0
 def end_show(self):
     """ends the Show
        raises exception if the show is planned since it doesn't need to be ended"""
     if self.flags & Show.FLAGS.PLANNED:
         raise Exception
     self.end = now()
     rfk.database.session.flush()
Exemplo n.º 10
0
def login():
    form = login_form(request.form)
    if request.method == 'POST' and form.validate():
        username = form.username.data
        try:
            user = User.get_user(username=username)
            if user and user.check_password(password=form.password.data):
                user.authenticated = True
                remember = form.remember.data
                if login_user(user, remember=remember):
                    if not user.last_login:
                        flash(gettext('<strong>Tip:</strong> It appears that this is your first login, if you need any help please visit our help section by clicking <a href="/help">here</a>.'), 'info')
                    user.last_login = now()
                    loc = rfk.helper.get_location(request.remote_addr)
                    if 'country_code' in loc and loc['country_code'] is not None:
                        user.country = loc['country_code']
                    rfk.database.session.commit()
                    flash(gettext('Login successful. Welcome %s!' % user.username), 'success')
                    return redirect(request.args.get('next') or url_for('index'))
                else:
                    form.username.errors.append(gettext('There was an error while logging you in.'))
                    #flash('There was an error while logging you in.', 'error')
            else:
                form.username.errors.append(gettext('Invalid User or Password.'))
                #flash('Invalid username or password.')
        except UserNotFoundException:
            form.username.errors.append(gettext('Invalid User or Password.'))
            #flash('Invalid username or password.')
    return render_template('login.html', form=form, TITLE='Login')
Exemplo n.º 11
0
def show_edit(show):
    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')
        show = Show.query.get(show)
        if show is None:
            return emit_error(7, 'Whoop, invalid show!')
        if show.get_usershow(current_user) is None:
            return emit_error(8, 'Trying to edit another user\'s show, eh?!')
        begin = to_utc(datetime.fromtimestamp(int(request.form['begin'])))
        begin = begin.replace(second=0)
        if begin < now():
            return jsonify({'success': False, 'error': 'You cannot enter a past date!'})
        end = begin + timedelta(minutes=int(request.form['duration']))
        if Show.query.filter(Show.end > begin, Show.begin < end, Show.show != show.show).count() > 0:
            return emit_error(1, 'Your show collides with other shows')
        show.begin = begin
        show.end = end
        _set_show_info(show, request.form)
        rfk.database.session.commit()
    else:
        return emit_error(0, 'Wait a second, are you trying to trick me again?!')
    return jsonify({'success': True, 'data': None})
Exemplo n.º 12
0
def generate_listenerhours(user):
    role_host = Role.get_role('host')
    total_listener_hours = 0

    for usershow in UserShow.query.filter(UserShow.user == user,
                                          UserShow.role == role_host,
                                          UserShow.status == UserShow.STATUS.STREAMED).yield_per(50):

        for listener in Listener.query.filter(Listener.connect <= usershow.show.end,
                                              usershow.show.begin <= Listener.disconnect).all():
            s = listener.connect
            if s < usershow.show.begin:
                s = usershow.show.begin
            e = listener.disconnect
            if e > usershow.show.end:
                e = usershow.show.end
            listener_time = e - s
            if listener_time.total_seconds() >= 0:
                total_listener_hours += listener_time.total_seconds()/3600
            else:
                print 'something went wrong: negative listenertime isn\'t possible'

    if total_listener_hours > 0 or True:
        us = UserStatistic.get_userstatistic(user, 'listenerhours')
        us.statistic.set(now(), total_listener_hours)
        rfk.database.session.flush()
Exemplo n.º 13
0
def main():
    try:
        rfk.init()
        if rfk.CONFIG.has_option('database', 'url'):
            init_db(rfk.CONFIG.get('database', 'url'))
        else:
            init_db("%s://%s:%s@%s/%s" % (rfk.CONFIG.get('database', 'engine'),
                                          rfk.CONFIG.get('database', 'username'),
                                          rfk.CONFIG.get('database', 'password'),
                                          rfk.CONFIG.get('database', 'host'),
                                          rfk.CONFIG.get('database', 'database')))
        for relay in Relay.query.all():
            try:
                relay.usage = get_stats_direct(relay)
                rs = RelayStatistic.get_relaystatistic(relay, RelayStatistic.TYPE.TRAFFIC)
                if relay.usage is not None:
                    rs.statistic.set(now(), relay.usage)
                relay.status = Relay.STATUS.ONLINE
                rfk.database.session.commit()
            except urllib2.URLError as e:
                rfk.database.session.rollback()
                relay.status = Relay.STATUS.UNKNOWN
                rfk.database.session.commit()
                print "Could not reach server: {}:{} - ".format(relay.address, relay.port, str(e))
            except socket.timeout as e:
                rfk.database.session.rollback()
                relay.status = Relay.STATUS.UNKNOWN
                rfk.database.session.commit()
                print "Could not reach server: {}:{} - ".format(relay.address, relay.port, str(e))
    except Exception as e:
        print e
    finally:
        rfk.database.session.rollback()
        rfk.database.session.remove()
Exemplo n.º 14
0
 def end_track(self, end=None):
     """ends the track and updates length in artist/title DB"""
     if end is None:
         self.end = now()
     else:
         self.end = end
     length = self.end - self.begin
     self.title.update_length(length.total_seconds())
Exemplo n.º 15
0
def update_global_statistics():
    try:
        stat = rfk.database.stats.Statistic.query.filter(rfk.database.stats.Statistic.identifier == 'lst-total').one()
    except sqlalchemy.orm.exc.NoResultFound:
        stat = rfk.database.stats.Statistic(name='Overall Listener', identifier='lst-total')
        rfk.database.session.add(stat)
        rfk.database.session.flush()
    stat.set(now(), rfk.database.streaming.Listener.get_total_listener())
Exemplo n.º 16
0
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)})
Exemplo n.º 17
0
def naturaltime(dt):
    # i18n isnt working because of various fuckups
    # will fix later

    #locale = get_locale()
    #locale_name = '_'.join([locale.language, locale.territory])
    #humanize.i18n.activate(locale_name)

    return humanize.time.naturaltime(now() - dt)
Exemplo n.º 18
0
 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)
Exemplo n.º 19
0
def main():
    for relay in Relay.query.all():
        try:
            relay.usage = get_stats(relay)
            rs = RelayStatistic.get_relaystatistic(relay, RelayStatistic.TYPE.TRAFFIC)
            if relay.usage is not None:
                rs.statistic.set(now(),relay.usage)
            rfk.database.session.commit()
        except urllib2.URLError:
            pass
Exemplo n.º 20
0
def generate_missed_show_ratio(user):
    role_host = Role.get_role('host')
    missed_shows = 0
    total_shows = 0

    for usershow in UserShow.query.join(Show).filter(UserShow.user == user,
                                                     UserShow.role == role_host,
                                                     Show.flags == Show.FLAGS.PLANNED,
                                                     Show.end <= now()).yield_per(50):

        total_shows += 1
        if usershow.status != UserShow.STATUS.STREAMED:
            missed_shows += 1

    if total_shows > 0:
        missed_show_ratio = (float(missed_shows)/float(total_shows))*100

        us = UserStatistic.get_userstatistic(user, 'missedshowratio')
        us.statistic.set(now(), missed_show_ratio)
        rfk.database.session.flush()
Exemplo n.º 21
0
 def is_fulfilled(self):
     """ this function returns True under the folling circumstances:
       somebody streamed or is streaming, or
       this show has not ended yet
     """
     if self.end > now():
         return True
     for user in self.users:
         if user.status > UserShow.STATUS.UNKNOWN:
             return True
     return False
Exemplo n.º 22
0
def listenerdata(start, stop):
    from rfk.site import app

    app.logger.warn(start)
    app.logger.warn(stop)
    stop = parse_datetimestring(stop)
    start = parse_datetimestring(start)
    app.logger.warn(start)
    app.logger.warn(stop)
    ret = {'data': {}, 'shows': []}

    streams = Stream.query.all()
    for stream in streams:
        ret['data'][str(stream.mount)] = []
        #just set an initial stating point from before the starting point
        stats = stream.statistic.get(stop=start, num=1, reverse=True)
        c = 0
        for stat in stats:
            c = stat.value
        if not stats:
            c = 0
        ret['data'][str(stream.mount)].append((to_timestamp(to_user_timezone(start)), int(c)))

    #fill in the actual datapoints
    streams = Stream.query.all()
    for stream in streams:
        stats = stream.statistic.get(start=start, stop=stop)
        for stat in stats:
            ret['data'][str(stream.mount)].append(
                (to_timestamp(to_user_timezone(stat.timestamp)), int(stat.value)))

    streams = Stream.query.all()
    for stream in streams:
        stats = stream.statistic.get(stop=stop, num=1, reverse=True)
        for stat in stats:
            c = stat.value
        if not stats:
            c = 0
        ret['data'][str(stream.mount)].append((to_timestamp(to_user_timezone(stop)), int(c)))

    #get the shows for the graph
    shows = Show.query.filter(between(Show.begin, start, stop) \
                              | between(Show.end, start, stop)).order_by(Show.begin.asc()).all()
    for show in shows:
        sstart = to_timestamp(to_user_timezone(show.begin))
        if show.end:
            send = to_timestamp(to_user_timezone(show.end))
        else:
            send = to_timestamp(to_user_timezone(now()))
        ret['shows'].append({'name': show.name,
                             'b': sstart,
                             'e': send})
    return jsonify(ret)
Exemplo n.º 23
0
 def new_track(show, artist, title, begin=None):
     """adds a new Track to database and ends the current track (if any)"""
     if begin is None:
         current_track = Track.current_track()
         if current_track:
             current_track.end_track()
     title = Title.add_title(artist, title)
     if begin is None:
         begin = now()
     track = Track(title=title, begin=begin, show=show)
     rfk.database.session.add(track)
     rfk.database.session.flush()
Exemplo n.º 24
0
class Donation(Base):
    __tablename__ = 'donations'
    donation = Column(Integer(unsigned=True),
                      primary_key=True,
                      autoincrement=True)
    in_value = Column(String(10))
    out_value = Column(String(10))
    in_currency = Column(String(10))
    out_currency = Column(String(10))
    date = Column(UTCDateTime, default=now())
    method = Column(String(20))
    country = Column(String(3))
Exemplo n.º 25
0
def listenerdata(start, stop):
    from rfk.site import app

    app.logger.warn(start)
    app.logger.warn(stop)
    stop = parse_datetimestring(stop)
    start = parse_datetimestring(start)
    app.logger.warn(start)
    app.logger.warn(stop)
    ret = {'data': {}, 'shows': []}

    streams = Stream.query.all()
    for stream in streams:
        ret['data'][str(stream.mount)] = []
        #just set an initial stating point from before the starting point
        stats = stream.statistic.get(stop=start, num=1, reverse=True)
        for stat in stats:
            c = stat.value
        if not stats:
            c = 0
        ret['data'][str(stream.mount)].append(
            (to_timestamp(to_user_timezone(start)), int(c)))

    #fill in the actual datapoints
    streams = Stream.query.all()
    for stream in streams:
        stats = stream.statistic.get(start=start, stop=stop)
        for stat in stats:
            ret['data'][str(stream.mount)].append(
                (to_timestamp(to_user_timezone(stat.timestamp)),
                 int(stat.value)))

    streams = Stream.query.all()
    for stream in streams:
        stats = stream.statistic.get(stop=stop, num=1, reverse=True)
        for stat in stats:
            c = stat.value
        if not stats:
            c = 0
        ret['data'][str(stream.mount)].append(
            (to_timestamp(to_user_timezone(stop)), int(c)))

    #get the shows for the graph
    shows = Show.query.filter(between(Show.begin, start, stop) \
                              | between(Show.end, start, stop)).order_by(Show.begin.asc()).all()
    for show in shows:
        sstart = to_timestamp(to_user_timezone(show.begin))
        if show.end:
            send = to_timestamp(to_user_timezone(show.end))
        else:
            send = to_timestamp(to_user_timezone(now()))
        ret['shows'].append({'name': show.name, 'b': sstart, 'e': send})
    return jsonify(ret)
Exemplo n.º 26
0
Arquivo: track.py Projeto: keios/PyRfK
 def new_track(show, artist, title, begin=None):
     """adds a new Track to database and ends the current track (if any)"""
     if begin is None:
         current_track = Track.current_track()
         if current_track:
             current_track.end_track()
     title = Title.add_title(artist, title)
     if begin is None:
         begin = now()
     track = Track(title=title, begin=begin, show=show)
     rfk.database.session.add(track)
     rfk.database.session.flush()
Exemplo n.º 27
0
def info(user):
    user = User.get_user(username=user)

    upcoming_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.begin >= now()).order_by(
        Show.begin.asc()).limit(5).all()
    last_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.end <= now()).order_by(
        Show.end.desc()).limit(5).all()
    if user:
        ball = iso_country_to_countryball(user.country)
        return render_template('user/info.html',
                               username=user.username,
                               ball=ball,
                               st=user.get_total_streamtime(),
                               shows={'upcoming': upcoming_shows, 'last': last_shows})
    else:
        abort(404)
Exemplo n.º 28
0
 def create(address, client, useragent, stream_relay):
     """adds a new listener to the database"""
     listener = Listener()
     if rfk.CONFIG.getboolean('icecast', 'log_ip'):
         listener.address = int(netaddr.IPAddress(address))
     listener.client = client
     loc = get_location(address)
     if 'city' in loc and loc['city'] is not None:
         listener.city = loc['city'].decode('latin-1') #FICK DICH MAXMIND
     if 'country_code' in loc and loc['country_code'] is not None:
         listener.country = loc['country_code']
     listener.useragent = useragent
     listener.connect = now()
     listener.stream_relay = stream_relay
     rfk.database.session.add(listener)
     rfk.database.session.flush()
     return listener
Exemplo n.º 29
0
    def create(address, client, useragent, stream_relay):
        """adds a new listener to the database"""
        listener = Listener()
        if rfk.CONFIG.getboolean('icecast', 'log_ip'):
            listener.address = int(netaddr.IPAddress(address))
        listener.client = client

        loc = get_location(address)
        if 'city' in loc and loc['city'] is not None:
            listener.city = loc['city']
        if 'country_code' in loc and loc['country_code'] is not None:
            listener.country = loc['country_code']

        listener.useragent = useragent
        listener.connect = now()
        listener.stream_relay = stream_relay
        rfk.database.session.add(listener)
        rfk.database.session.flush()
        return listener
Exemplo n.º 30
0
 def get_current_loop():
     """
         returns the current loop to be scheduled
         @todo maybe broken ;_;
     """
     n = now()
     #try to find a loop that should be running
     loops = Loop.query.filter(Loop.contains(int(n.hour*100+(n.minute/60.)*100))).order_by(Loop.length.asc()).all()
     for loop in loops:
         if loop.file_exists:
             return loop;
     # we found no loops
     # just try to find the longest one
     loops = Loop.query.order_by(Loop.length.asc()).all()
     for loop in loops:
         if loop.file_exists:
             return loop;
     #okay, now we have a problem, just retun none
     return None
Exemplo n.º 31
0
Arquivo: base.py Projeto: keios/PyRfK
class ApiKey(Base):
    __tablename__ = 'apikeys'
    apikey = Column(Integer(unsigned=True),
                    primary_key=True,
                    autoincrement=True)
    user_id = Column(
        "user", Integer(unsigned=True),
        ForeignKey('users.user', onupdate="CASCADE", ondelete="RESTRICT"))
    user = relationship("User", backref="apikeys")
    key = Column(String(128))
    counter = Column(Integer(unsigned=True), default=0)
    access = Column(UTCDateTime, default=now())
    application = Column(String(128))
    description = Column(String(255))
    flag = Column(Integer(unsigned=True), default=0)
    FLAGS = SET(['DISABLED', 'FASTQUERY', 'KICK', 'BAN', 'AUTH'])

    def gen_key(self):
        c = 0
        while True:
            key = hashlib.sha1(
                "%s%s%d%d" % (self.application, self.description, time.time(),
                              c)).hexdigest()
            if ApiKey.query.filter(ApiKey.key == key).first() == None:
                break
        self.key = key

    @staticmethod
    def check_key(key):

        try:
            apikey = ApiKey.query.filter(ApiKey.key == key).one()
        except (exc.NoResultFound, exc.MultipleResultsFound):
            raise rexc.api.KeyInvalidException()
        if apikey.flag & ApiKey.FLAGS.DISABLED:
            raise rexc.api.KeyDisabledException()
        elif not apikey.flag & ApiKey.FLAGS.FASTQUERY:
            if now() - apikey.access <= timedelta(seconds=1):
                raise rexc.api.FastQueryException(last_access=apikey.access)

        apikey.counter += 1
        apikey.access = now()
        return apikey
Exemplo n.º 32
0
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')
Exemplo n.º 33
0
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')
Exemplo n.º 34
0
Arquivo: base.py Projeto: keios/PyRfK
 def get_current_loop():
     """
         returns the current loop to be scheduled
         @todo maybe broken ;_;
     """
     n = now()
     #try to find a loop that should be running
     loops = Loop.query.filter(
         Loop.contains(int(n.hour * 100 +
                           (n.minute / 60.) * 100))).order_by(
                               Loop.length.asc()).all()
     for loop in loops:
         if loop.file_exists:
             return loop
             # we found no loops
             # just try to find the longest one
     loops = Loop.query.order_by(Loop.length.asc()).all()
     for loop in loops:
         if loop.file_exists:
             return loop
             #okay, now we have a problem, just retun none
     return None
Exemplo n.º 35
0
def login():
    form = login_form(request.form)
    if request.method == 'POST' and form.validate():
        username = form.username.data
        try:
            user = User.get_user(username=username)
            if user and user.check_password(password=form.password.data):
                user.authenticated = True
                remember = form.remember.data
                if login_user(user, remember=remember):
                    if not user.last_login:
                        flash(
                            gettext(
                                '<strong>Tip:</strong> It appears that this is your first login, if you need any help please visit our help section by clicking <a href="/help">here</a>.'
                            ), 'info')
                    user.last_login = now()
                    loc = rfk.helper.get_location(request.remote_addr)
                    if 'country_code' in loc and loc[
                            'country_code'] is not None:
                        user.country = loc['country_code']
                    rfk.database.session.commit()
                    flash(
                        gettext('Login successful. Welcome %s!' %
                                user.username), 'success')
                    return redirect(
                        request.args.get('next') or url_for('index'))
                else:
                    form.username.errors.append(
                        gettext('There was an error while logging you in.'))
                    #flash('There was an error while logging you in.', 'error')
            else:
                form.username.errors.append(
                    gettext('Invalid User or Password.'))
                #flash('Invalid username or password.')
        except UserNotFoundException:
            form.username.errors.append(gettext('Invalid User or Password.'))
            #flash('Invalid username or password.')
    return render_template('login.html', form=form, TITLE=gettext('Login'))
Exemplo n.º 36
0
def show_edit(show):
    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')
        show = Show.query.get(show)
        if show is None:
            return emit_error(7, 'Whoop, invalid show!')
        if show.get_usershow(current_user) is None:
            return emit_error(8, 'Trying to edit another user\'s show, eh?!')
        begin = to_utc(get_timezone().localize(
            datetime.utcfromtimestamp(int(request.form['begin']))))
        begin = begin.replace(second=0)
        if begin < now():
            return jsonify({
                'success': False,
                'error': 'You cannot enter a past date!'
            })
        end = begin + timedelta(minutes=int(request.form['duration']))
        if Show.query.filter(Show.end > begin, Show.begin < end,
                             Show.show != show.show).count() > 0:
            return emit_error(1, 'Your show collides with other shows')
        show.begin = begin
        show.end = end
        _set_show_info(show, request.form)
        rfk.database.session.commit()
    else:
        return emit_error(0,
                          'Wait a second, are you trying to trick me again?!')
    return jsonify({'success': True, 'data': None})
Exemplo n.º 37
0
def main():
    try:
        rfk.init()
        if rfk.CONFIG.has_option('database', 'url'):
            init_db(rfk.CONFIG.get('database', 'url'))
        else:
            init_db("%s://%s:%s@%s/%s" %
                    (rfk.CONFIG.get('database', 'engine'),
                     rfk.CONFIG.get('database', 'username'),
                     rfk.CONFIG.get('database', 'password'),
                     rfk.CONFIG.get('database', 'host'),
                     rfk.CONFIG.get('database', 'database')))
        for relay in Relay.query.all():
            try:
                relay.usage = get_stats_direct(relay)
                rs = RelayStatistic.get_relaystatistic(
                    relay, RelayStatistic.TYPE.TRAFFIC)
                if relay.usage is not None:
                    rs.statistic.set(now(), relay.usage)
                relay.status = Relay.STATUS.ONLINE
                rfk.database.session.commit()
            except urllib2.URLError as e:
                rfk.database.session.rollback()
                relay.status = Relay.STATUS.UNKNOWN
                rfk.database.session.commit()
                print "Could not reach server: {}:{} - ".format(
                    relay.address, relay.port, str(e))
            except socket.timeout as e:
                rfk.database.session.rollback()
                relay.status = Relay.STATUS.UNKNOWN
                rfk.database.session.commit()
                print "Could not reach server: {}:{} - ".format(
                    relay.address, relay.port, str(e))
    except Exception as e:
        print e
    finally:
        rfk.database.session.rollback()
        rfk.database.session.remove()
Exemplo n.º 38
0
def info(user):
    try:
        user = User.get_user(username=user)
    except rfk.exc.base.UserNotFoundException:
        abort(404)

    # checking user rank
    if user.has_permission('admin'):
        rank = 'Admin'
    else:
        rank = 'User'

    # count planned and unplanned shows
    planned_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.flags == Show.FLAGS.PLANNED).count()
    unplanned_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.flags == Show.FLAGS.UNPLANNED).count()
    total_shows = planned_shows + unplanned_shows

    # list upcoming and recent shows
    upcoming_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.begin >= now()).order_by(
        Show.begin.asc()).limit(5).all()
    last_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.end <= now()).order_by(
        Show.end.desc()).limit(5).all()

    stats = {}
    for us in UserStatistic.query.filter(UserStatistic.user == user).all():
        stats[us.code] = us.statistic.current_value().value

    return render_template('user/info.html', TITLE=user.username,
                           user=user,
                           rank=rank,
                           planned_shows=planned_shows,
                           unplanned_shows=unplanned_shows,
                           total_shows=total_shows,
                           st=user.get_total_streamtime(),
                           shows={'upcoming': upcoming_shows, 'last': last_shows},
                           stats=stats)
Exemplo n.º 39
0
def login():
    form = login_form(request.form)
    if request.method == "POST" and form.validate():
        username = form.username.data
        try:
            user = User.get_user(username=username)
            if user and user.check_password(password=form.password.data):
                user.authenticated = True
                remember = form.remember.data
                if login_user(user, remember=remember):
                    user.last_login = now()
                    session.commit()
                    flash("Logged in!")
                    return redirect(request.args.get("next") or url_for("index"))
                else:
                    form.username.errors.append('There was an error while logging you in.')
                    flash("Sorry, but you could not log in.")
            else:
                form.username.errors.append('Invalid User or Password.')
                flash(u"Invalid username or password.")
        except UserNotFoundException:
            form.username.errors.append('Invalid User or Password.')
            flash(u"Invalid username or password.")
    return render_template("login.html", form=form)
Exemplo n.º 40
0
 def current_value(self):
     ret = self.get(stop=now(), num=1, reverse=True)
     if ret:
         return ret[0]
     else:
         return None
Exemplo n.º 41
0
 def update_statistic(self):
     stat = self.get_statistic()
     stat.set(now(), self.get_current_listeners())
Exemplo n.º 42
0
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)})
Exemplo n.º 43
0
 def set_disconnected(self):
     """updates the listener to disconnected state"""
     self.disconnect = now()
Exemplo n.º 44
0
def get_shows():
    clauses = []
    clauses.append(Show.end > now())
    result = Show.query.join(UserShow).join(User).filter(*clauses).order_by(Show.begin.asc()).all()
    return result
Exemplo n.º 45
0
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)
Exemplo n.º 46
0
def upcoming(page):
    shows = Show.query.filter(Show.end > now()).order_by(Show.end.asc()).all()
    return render_template('shows/upcoming.html', TITLE=gettext('Shows'), shows=shows)
Exemplo n.º 47
0
def listeners():

    # check if current_user is logged in and if user is streaming or if user is admin
    if not current_user.is_anonymous():
        is_streaming = UserShow.query.join(User).filter(
            UserShow.status == UserShow.STATUS.STREAMING,
            UserShow.user == current_user).first()
        if is_streaming or current_user.has_permission('admin'):
            show_listener_list = True
        else:
            show_listener_list = False
    else:
        show_listener_list = False

    # get current bandwidth of all active relays
    total_bandwidth = 0
    relays = Relay.query.filter(Relay.status == Relay.STATUS.ONLINE).all()
    active_relays = len(relays)
    for relay in relays:
        total_bandwidth += relay.usage
    total_bandwidth *= 128  # convert kbit to byte

    # get all current listeners
    current_listener = Listener.get_current_listeners()

    # generate per country stats
    per_country = {}
    for listener in current_listener:
        country = listener.country
        try:
            per_country[country]['count'] += 1
        except KeyError:
            per_country[country] = {'count': 1}
            per_country[country]['ball'] = country
    per_country = sorted(per_country.iteritems(),
                         key=lambda (k, v): v['count'],
                         reverse=True)

    # get recent listener count to calculate a trend
    try:
        stats_total = Statistic.query.filter(
            Statistic.identifier == 'lst-total').one()
        stats = stats_total.get(start=now() - datetime.timedelta(minutes=5),
                                stop=now())
    except exc.NoResultFound:
        stats = None

    if stats and stats.count() > 0:
        listener_sum = 0
        for stat in stats:
            listener_sum += stat.value
        average_listeners = listener_sum / stats.count()
    else:
        average_listeners = len(current_listener)

    return render_template('listenergraph.html',
                           TITLE=gettext('Listeners'),
                           show_listener_list=show_listener_list,
                           listeners=current_listener,
                           per_country=per_country,
                           total_bandwidth=total_bandwidth,
                           active_relays=active_relays,
                           average_listeners=average_listeners)