Ejemplo n.º 1
0
    def create_stream_chunk(self, status):

        if self.current_stream_chunk is not None:
            # There's already a stream chunk started!
            session = DBManager.create_session(expire_on_commit=False)
            self.current_stream_chunk.chunk_end = datetime.datetime.now()
            session.add(self.current_stream_chunk)
            session.commit()
            session.close()
            self.current_stream_chunk = None

        session = DBManager.create_session(expire_on_commit=False)
        stream_chunk = session.query(StreamChunk).filter_by(broadcast_id=status['broadcast_id']).one_or_none()
        if stream_chunk is None:
            log.info('Creating stream chunk, from create_stream_chunk')
            stream_chunk = StreamChunk(self.current_stream, status['broadcast_id'], status['created_at'])
            self.current_stream_chunk = stream_chunk
            session.add(stream_chunk)
            session.commit()
        else:
            log.info('We already have a stream chunk!')
            self.current_stream_chunk = stream_chunk
        session.expunge_all()
        session.close()

        self.current_stream.stream_chunks.append(stream_chunk)
Ejemplo n.º 2
0
def highlight_list_date(date):
    # Make sure we were passed a valid date
    try:
        parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d')
    except ValueError:
        # Invalid date
        return redirect('/highlights/', 303)
    session = DBManager.create_session()
    dates_with_highlights = []
    highlights = session.query(StreamChunkHighlight).filter(
        cast(StreamChunkHighlight.created_at, Date) == parsed_date).order_by(
            StreamChunkHighlight.created_at.desc()).all()
    for highlight in session.query(StreamChunkHighlight):
        dates_with_highlights.append(
            datetime.datetime(year=highlight.created_at.year,
                              month=highlight.created_at.month,
                              day=highlight.created_at.day))

    try:
        return render_template(
            'highlights_date.html',
            highlights=highlights,
            date=parsed_date,
            dates_with_highlights=set(dates_with_highlights))
    finally:
        session.close()
Ejemplo n.º 3
0
 def get_current_song(stream_id):
     with DBManager.create_session_scope() as session:
         cur_song = session.query(PleblistSong).filter(PleblistSong.stream_id == stream_id, PleblistSong.date_played.is_(None)).order_by(PleblistSong.date_added.asc()).first()
         if cur_song is None:
             return None
         session.expunge(cur_song)
         return cur_song
Ejemplo n.º 4
0
def pleblist_next():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method'}), 405)
    if 'song_id' not in request.form:
        return make_response(jsonify({'error': 'Missing data song_id'}), 400)
    if 'password' not in request.form:
        return make_response(jsonify({'error': 'Missing data password'}), 400)
    salted_password = generate_password_hash(config['web']['pleblist_password'], config['web']['pleblist_password_salt'])
    try:
        user_password = base64.b64decode(request.form['password'])
    except binascii.Error:
        return make_response(jsonify({'error': 'Invalid data password'}), 400)
    if not user_password == salted_password:
        return make_response(jsonify({'error': 'Invalid password'}), 401)

    with DBManager.create_session_scope() as session:
        try:
            current_song = session.query(PleblistSong).filter(PleblistSong.id == int(request.form['song_id'])).order_by(PleblistSong.date_added.asc()).first()
        except ValueError:
            return make_response(jsonify({'error': 'Invalid data song_id'}), 400)

        if current_song is None:
            return make_response(jsonify({'error': 'No song active in the pleblist'}), 404)

        current_song.date_played = datetime.datetime.now()
        session.commit()

        # TODO: Add more data.
        # Was this song forcefully skipped? Or did it end naturally.

        return jsonify({'message': 'Success!'})
Ejemplo n.º 5
0
    def create_highlight(self, **options):
        """
        Returns an error message (string) if something went wrong, otherwise returns True
        """
        if self.online is False or self.current_stream_chunk is None:
            return 'The stream is not online'

        if self.current_stream_chunk.video_url is None:
            return 'No video URL fetched for this chunk yet, try in 5 minutes'

        try:
            highlight = StreamChunkHighlight(self.current_stream_chunk, **options)

            session = DBManager.create_session(expire_on_commit=False)
            session.add(highlight)
            session.add(self.current_stream_chunk)
            session.commit()
            session.close()

            x = inspect(self.current_stream_chunk)
            log.info('{0.transient} - {0.pending} - {0.persistent} - {0.detached}'.format(x))
            x = inspect(highlight)
            log.info('{0.transient} - {0.pending} - {0.persistent} - {0.detached}'.format(x))
            x = inspect(self.current_stream)
            log.info('{0.transient} - {0.pending} - {0.persistent} - {0.detached}'.format(x))

            log.info(self.current_stream.id)
            log.info(highlight.id)
            log.info(self.current_stream_chunk.id)
        except:
            log.exception('uncaught exception in create_highlight')
            return 'Unknown reason, ask pajlada'

        return True
Ejemplo n.º 6
0
def decks_warrior():
    session = DBManager.create_session()
    decks = session.query(Deck).filter_by(deck_class='warrior').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
    session.close()
    return render_template('decks/by_class.html',
            decks=decks,
            deck_class='Warrior')
Ejemplo n.º 7
0
    def remove_command(self, command):
        self.remove_command_aliases(command)

        with DBManager.create_session_scope() as db_session:
            self.db_session.expunge(command.data)
            db_session.delete(command.data)
            db_session.delete(command)
Ejemplo n.º 8
0
    def __init__(self, bot):
        self.bot = bot

        self.current_stream_chunk = None  # should this even exist?

        self.num_offlines = 0
        self.first_offline = None

        self.bot.execute_every(self.STATUS_CHECK_INTERVAL, self.refresh_stream_status)
        self.bot.execute_every(self.VIDEO_URL_CHECK_INTERVAL, self.refresh_video_url)

        """
        This will load the latest stream so we can post an accurate
        "time since last online" figure.
        """
        session = DBManager.create_session(expire_on_commit=False)
        self.current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()
        self.last_stream = session.query(Stream).filter_by(ended=True).order_by(Stream.stream_end.desc()).first()
        # if self.current_stream and len(self.current_stream.stream_chunks) > 0:
        if self.current_stream:
            # sorted_chunks = sorted(self.current_stream.stream_chunks, key=lambda x: x.chunk_start, reverse=True)
            # self.current_stream_chunk = sorted_chunks[0]
            self.current_stream_chunk = session.query(StreamChunk).filter_by(stream_id=self.current_stream.id).order_by(StreamChunk.chunk_start.desc()).first()
            log.info('Set current stream chunk here to {0}'.format(self.current_stream_chunk))
        session.expunge_all()
        session.close()
Ejemplo n.º 9
0
def get_user(username):
    session = DBManager.create_session()
    user = session.query(User).filter_by(username=username).one_or_none()
    if user is None:
        return make_response(jsonify({'error': 'Not found'}), 404)

    rank = session.query(func.Count(
        User.id)).filter(User.points > user.points).one()
    rank = rank[0] + 1
    session.close()
    if user:
        accessible_data = {
            'id': user.id,
            'username': user.username,
            'username_raw': user.username_raw,
            'points': user.points,
            'rank': rank,
            'level': user.level,
            'last_seen': user.last_seen,
            'last_active': user.last_active,
            'subscriber': user.subscriber,
            'num_lines': user.num_lines,
            'minutes_in_chat_online': user.minutes_in_chat_online,
            'minutes_in_chat_offline': user.minutes_in_chat_offline,
            'banned': user.banned,
            'ignored': user.ignored,
        }
        return jsonify(accessible_data)

    return make_response(jsonify({'error': 'Not found'}), 404)
Ejemplo n.º 10
0
    def create_command(self, alias_str, **options):
        """
        TODO: Does this part of the code work as expected?
        Right now if the second alias is already used, it could result in us
        creating a command with an alias that's already in use.
        """
        aliases = alias_str.lower().replace('!', '').split('|')
        main_alias = aliases[0]
        if main_alias in self.data:
            # Command with this alias already exists, return its instance!
            return self.data[main_alias], False

        command = Command(command=alias_str, **options)
        command.data = CommandData(command.id)
        self.add_command_aliases(command)
        with DBManager.create_session_scope(
                expire_on_commit=False) as db_session:
            db_session.add(command)
            db_session.add(command.data)
            db_session.commit()
            db_session.expunge(command)
            db_session.expunge(command.data)
        self.db_session.add(command.data)
        self.commit()
        return command, True
Ejemplo n.º 11
0
def get_user(username):
    session = DBManager.create_session()
    user = session.query(User).filter_by(username=username).one_or_none()
    if user is None:
        return make_response(jsonify({'error': 'Not found'}), 404)

    rank = session.query(func.Count(User.id)).filter(User.points > user.points).one()
    rank = rank[0] + 1
    session.close()
    if user:
        accessible_data = {
                'id': user.id,
                'username': user.username,
                'username_raw': user.username_raw,
                'points': user.points,
                'rank': rank,
                'level': user.level,
                'last_seen': user.last_seen,
                'last_active': user.last_active,
                'subscriber': user.subscriber,
                'num_lines': user.num_lines,
                'minutes_in_chat_online': user.minutes_in_chat_online,
                'minutes_in_chat_offline': user.minutes_in_chat_offline,
                'banned': user.banned,
                'ignored': user.ignored,
                }
        return jsonify(accessible_data)

    return make_response(jsonify({'error': 'Not found'}), 404)
Ejemplo n.º 12
0
def stats_duels():
    session = DBManager.create_session()

    data = {
        'top_5_winners':
        session.query(UserDuelStats).order_by(
            UserDuelStats.duels_won.desc())[:5],
        'top_5_points_won':
        session.query(UserDuelStats).order_by(UserDuelStats.profit.desc())[:5],
        'top_5_points_lost':
        session.query(UserDuelStats).order_by(UserDuelStats.profit.asc())[:5],
        'top_5_losers':
        session.query(UserDuelStats).order_by(
            UserDuelStats.duels_lost.desc())[:5],
        'top_5_winrate':
        session.query(UserDuelStats).filter(
            UserDuelStats.duels_won >= 5).order_by(
                UserDuelStats.winrate.desc())[:5],
        'bottom_5_winrate':
        session.query(UserDuelStats).filter(
            UserDuelStats.duels_lost >= 5).order_by(
                UserDuelStats.winrate.asc())[:5],
    }

    try:
        return render_template('stats_duels.html', **data)
    finally:
        session.close()
Ejemplo n.º 13
0
def command_checkalias(**options):
    if 'alias' not in request.form:
        return make_response(jsonify({'error': 'Missing `alias` parameter.'}),
                             400)

    request_alias = request.form['alias'].lower()

    command_manager = CommandManager(None)

    internal_commands = command_manager.get_internal_commands()
    db_command_aliases = []

    with DBManager.create_session_scope() as db_session:
        for command in db_session.query(Command):
            db_command_aliases.extend(command.command.split('|'))

    for alias in internal_commands:
        db_command_aliases.append(alias)

    db_command_aliases = set(db_command_aliases)

    if request_alias in db_command_aliases:
        return make_response(jsonify({'error': 'Alias already in use'}))
    else:
        return make_response(jsonify({'success': 'good job'}))
Ejemplo n.º 14
0
    def refresh_video_url(self):
        if self.online is False:
            return

        if self.current_stream_chunk is None or self.current_stream is None:
            return

        if self.current_stream_chunk.video_url is not None:
            return

        log.info('Attempting to fetch video url for broadcast {0}'.format(self.current_stream_chunk.broadcast_id))
        video_url, video_preview_image_url = self.fetch_video_url(self.current_stream_chunk)
        if video_url is not None:
            log.info('Successfully fetched a video url: {0}'.format(video_url))
            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                self.current_stream_chunk.video_url = video_url
                self.current_stream_chunk.video_preview_image_url = video_preview_image_url

                db_session.add(self.current_stream_chunk)

                db_session.commit()

                db_session.expunge_all()
            log.info('successfully commited it and shit')
        else:
            log.info('Not video for broadcast found')
Ejemplo n.º 15
0
    def create_stream(self, status):
        log.info('Attempting to create a stream!')
        with DBManager.create_session_scope(expire_on_commit=False) as db_session:
            stream_chunk = db_session.query(StreamChunk).filter_by(broadcast_id=status['broadcast_id']).one_or_none()
            if stream_chunk is not None:
                stream = stream_chunk.stream
            else:
                log.info('checking if there is an active stream already')
                stream = db_session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()

                if stream is None:
                    log.info('No active stream, create new!')
                    stream = Stream(status['created_at'],
                            title=status['title'])
                    db_session.add(stream)
                    db_session.commit()
                    log.info('added stream!')
                stream_chunk = StreamChunk(stream, status['broadcast_id'], status['created_at'])
                db_session.add(stream_chunk)
                db_session.commit()
                stream.stream_chunks.append(stream_chunk)
                log.info('Created stream chunk')

            self.current_stream = stream
            self.current_stream_chunk = stream_chunk
            db_session.expunge_all()

            log.info('added shit to current_stream etc')
Ejemplo n.º 16
0
    def __init__(self, bot):
        self.bot = bot
        self.db_session = DBManager.create_session()

        self.twitter_client = None
        self.twitter_stream = None
        self.listener = None

        if 'twitter' in bot.config:
            self.use_twitter_stream = 'streaming' in bot.config[
                'twitter'] and bot.config['twitter']['streaming'] == '1'

            try:
                self.twitter_auth = tweepy.OAuthHandler(
                    bot.config['twitter']['consumer_key'],
                    bot.config['twitter']['consumer_secret'])
                self.twitter_auth.set_access_token(
                    bot.config['twitter']['access_token'],
                    bot.config['twitter']['access_token_secret'])

                self.twitter_client = tweepy.API(self.twitter_auth)

                if self.use_twitter_stream:
                    self.connect_to_twitter_stream()
                    bot.execute_every(60 * 5, self.check_twitter_connection)
            except:
                log.exception('Twitter authentication failed.')
                self.twitter_client = None
Ejemplo n.º 17
0
def pleblist_add():
    if not request.method == 'POST':
        return make_response(jsonify({'error': 'Invalid request method'}), 405)
    if 'youtube_id' not in request.form:
        return make_response(jsonify({'error': 'Missing data youtube_id'}), 400)
    if 'password' not in request.form:
        return make_response(jsonify({'error': 'Missing data password'}), 400)
    salted_password = generate_password_hash(config['web']['pleblist_password'], config['web']['pleblist_password_salt'])
    try:
        user_password = base64.b64decode(request.form['password'])
    except binascii.Error:
        return make_response(jsonify({'error': 'Invalid data password'}), 400)
    if not user_password == salted_password:
        return make_response(jsonify({'error': 'Invalid password'}), 401)

    with DBManager.create_session_scope() as session:
        youtube_id = request.form['youtube_id']
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        song_requested = PleblistSong(current_stream.id, youtube_id)
        session.add(song_requested)
        song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
        if song_info is None and song_requested.song_info is None:
            PleblistManager.init(config['youtube']['developer_key'])
            song_info = PleblistManager.create_pleblist_song_info(song_requested.youtube_id)
            if song_info is not False:
                session.add(song_info)
                session.commit()

        return jsonify({'success': True})
Ejemplo n.º 18
0
    def __init__(self, bot):
        self.db_session = DBManager.create_session()
        self.messages = []
        self.bot = bot
        self.minute = 0
        self.iterator = 0

        self.bot.execute_every(60, self.tick)
Ejemplo n.º 19
0
def points():
    session = DBManager.create_session()
    top_30_users = []
    for user in session.query(User).order_by(User.points.desc())[:30]:
        top_30_users.append(user)
    session.close()
    return render_template('points.html',
            top_30_users=top_30_users)
Ejemplo n.º 20
0
def decks_warrior():
    session = DBManager.create_session()
    decks = session.query(Deck).filter_by(deck_class='warrior').order_by(
        Deck.last_used.desc(), Deck.first_used.desc()).all()
    session.close()
    return render_template('decks/by_class.html',
                           decks=decks,
                           deck_class='Warrior')
Ejemplo n.º 21
0
    def __init__(self, bot):
        self.db_session = DBManager.create_session()
        self.messages = []
        self.bot = bot
        self.minute = 0
        self.iterator = 0

        self.bot.execute_every(60, self.tick)
Ejemplo n.º 22
0
    def remove_highlight(self, id):
        """
        Returns True if a highlight was removed, otherwise return False
        """

        with DBManager.create_session_scope() as db_session:
            num_rows = db_session.query(StreamChunkHighlight).filter(StreamChunkHighlight.id == id).delete()

        return (num_rows == 1)
Ejemplo n.º 23
0
def pleblist_blacklist():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        # TODO: implement this

        return make_response(jsonify({'error': 'NOT IMPLEMENTED'}), 400)
Ejemplo n.º 24
0
    def __init__(self, bot):
        UserDict.__init__(self)
        self.bot = bot
        self.streamer = bot.streamer
        self.db_session = DBManager.create_session()
        self.custom_data = []
        self.bttv_emote_manager = BTTVEmoteManager(self)

        self.bot.execute_every(60 * 60 * 2, self.bot.action_queue.add, (self.bttv_emote_manager.update_emotes, ))
Ejemplo n.º 25
0
def decks():
    session = DBManager.create_session()
    top_decks = []
    for deck in session.query(Deck).order_by(Deck.last_used.desc(), Deck.first_used.desc())[:25]:
        top_decks.append(deck)
    session.close()
    return render_template('decks/all.html',
            top_decks=top_decks,
            deck_class=None)
Ejemplo n.º 26
0
def decks():
    session = DBManager.create_session()
    top_decks = []
    for deck in session.query(Deck).order_by(Deck.last_used.desc(),
                                             Deck.first_used.desc())[:25]:
        top_decks.append(deck)
    session.close()
    return render_template('decks/all.html',
                           top_decks=top_decks,
                           deck_class=None)
Ejemplo n.º 27
0
def pleblist_blacklist():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(
            Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        # TODO: implement this

        return make_response(jsonify({'error': 'NOT IMPLEMENTED'}), 400)
Ejemplo n.º 28
0
def highlights():
    session = DBManager.create_session()
    streams = session.query(Stream).order_by(Stream.stream_start.desc()).all()
    for stream in streams:
        stream.stream_chunks = sorted(stream.stream_chunks, key=lambda x: x.chunk_start, reverse=True)
        for stream_chunk in stream.stream_chunks:
            stream_chunk.highlights = sorted(stream_chunk.highlights, key=lambda x: x.created_at, reverse=True)
    session.close()
    return render_template('highlights.html',
            streams=streams)
Ejemplo n.º 29
0
def pleblist_list_by_stream(stream_id):
    with DBManager.create_session_scope() as session:
        songs = session.query(PleblistSong).filter_by(stream_id=stream_id).all()

        payload = {
                '_total': len(songs),
                'songs': [song.jsonify() for song in songs],
                }

        return jsonify(payload)
Ejemplo n.º 30
0
 def __init__(self, bot):
     UserDict.__init__(self)
     self.db_session = DBManager.create_session()
     self.internal_commands = None
     self.bot = bot
     if bot:
         self.bot.socket_manager.add_handler('command.update',
                                             self.on_command_update)
         self.bot.socket_manager.add_handler('command.remove',
                                             self.on_command_remove)
Ejemplo n.º 31
0
    def __init__(self, bot):
        UserDict.__init__(self)
        self.bot = bot
        self.streamer = bot.streamer
        self.db_session = DBManager.create_session()
        self.custom_data = []
        self.bttv_emote_manager = BTTVEmoteManager(self)

        self.bot.execute_every(60 * 60 * 2, self.bot.action_queue.add,
                               (self.bttv_emote_manager.update_emotes, ))
Ejemplo n.º 32
0
def pleblist_list_by_stream(stream_id):
    with DBManager.create_session_scope() as session:
        songs = session.query(PleblistSong).filter_by(
            stream_id=stream_id).all()

        payload = {
            '_total': len(songs),
            'songs': [song.jsonify() for song in songs],
        }

        return jsonify(payload)
Ejemplo n.º 33
0
    def remove_highlight(self, id):
        """
        Returns True if a highlight was removed, otherwise return False
        """

        session = DBManager.create_session()
        num_rows = session.query(StreamChunkHighlight).filter(StreamChunkHighlight.id == id).delete()
        session.commit()
        session.close()

        return (num_rows == 1)
Ejemplo n.º 34
0
def pleblist_history_redirect():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()
        if current_stream is not None:
            return redirect('/pleblist/history/{}/'.format(current_stream.id), 303)

        last_stream = session.query(Stream).filter_by(ended=True).order_by(Stream.stream_start.desc()).first()
        if last_stream is not None:
            return redirect('/pleblist/history/{}/'.format(last_stream.id), 303)

        return render_template('pleblist_history_no_stream.html'), 404
Ejemplo n.º 35
0
def commands_edit(command_id, **options):
    with DBManager.create_session_scope() as db_session:
        command = db_session.query(Command).filter_by(
            id=command_id).one_or_none()

        if command is None:
            return render_template('admin/command_404.html'), 404

        return render_template('admin/edit_command.html',
                               command=command,
                               user=options.get('user', None))
Ejemplo n.º 36
0
    def update_highlight(self, id, **options):
        """
        Returns True if a highlight was modified, otherwise return False
        """

        if 'offset' in options:
            options['highlight_offset'] = options.pop('offset')

        with DBManager.create_session_scope() as db_session:
            num_rows = db_session.query(StreamChunkHighlight).filter(StreamChunkHighlight.id == id).update(options)

        return (num_rows == 1)
Ejemplo n.º 37
0
    def create_stream_chunk(self, status):
        if self.current_stream_chunk is not None:
            # There's already a stream chunk started!
            self.current_stream_chunk.chunk_end = datetime.datetime.now()
            DBManager.session_add_expunge(self.current_stream_chunk)

        with DBManager.create_session_scope(expire_on_commit=False) as db_session:
            stream_chunk = db_session.query(StreamChunk).filter_by(broadcast_id=status['broadcast_id']).one_or_none()
            if stream_chunk is None:
                log.info('Creating stream chunk, from create_stream_chunk')
                stream_chunk = StreamChunk(self.current_stream, status['broadcast_id'], status['created_at'])
                self.current_stream_chunk = stream_chunk
                db_session.add(stream_chunk)
                db_session.commit()
            else:
                log.info('We already have a stream chunk!')
                self.current_stream_chunk = stream_chunk
            db_session.expunge_all()
            db_session.close()

        self.current_stream.stream_chunks.append(stream_chunk)
Ejemplo n.º 38
0
def pleblist_history_stream(stream_id):
    with DBManager.create_session_scope() as session:
        stream = session.query(Stream).filter_by(id=stream_id).one_or_none()
        if stream is None:
            return render_template('pleblist_history_404.html'), 404

        songs = session.query(PleblistSong).filter(PleblistSong.stream_id == stream.id).order_by(PleblistSong.date_added.asc(), PleblistSong.date_played.asc()).all()
        total_length_left = sum([song.song_info.duration if song.date_played is None and song.song_info is not None else 0 for song in songs])

        return render_template('pleblist_history.html',
                stream=stream,
                songs=songs,
                total_length_left=total_length_left)
Ejemplo n.º 39
0
def pleblist_list():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        songs = session.query(PleblistSong).filter(PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None)).all()
        payload = {
                '_total': len(songs),
                'songs': [song.jsonify() for song in songs],
                }

        return jsonify(payload)
Ejemplo n.º 40
0
    def __init__(self, reactor, bot, target, message_limit, time_interval, num_of_conns=30):
        self.db_session = DBManager.create_session()
        self.reactor = reactor
        self.bot = bot
        self.message_limit = message_limit
        self.time_interval = time_interval
        self.num_of_conns = num_of_conns
        self.whisper_thread = None

        self.connlist = []
        self.whispers = Queue()

        self.maintenance_lock = False
Ejemplo n.º 41
0
def stats():
    top_5_commands = sorted(bot_commands_list, key=lambda c: c.num_uses, reverse=True)[:5]

    if 'linefarming' in modules:
        session = DBManager.create_session()
        top_5_line_farmers = session.query(User).order_by(User.num_lines.desc())[:5]
        session.close()
    else:
        top_5_line_farmers = []

    return render_template('stats.html',
            top_5_commands=top_5_commands,
            top_5_line_farmers=top_5_line_farmers)
Ejemplo n.º 42
0
def points():
    custom_content = custom_web_content.get('points', '')
    try:
        custom_content = Markup(markdown.markdown(custom_content))
    except:
        log.exception('Unhandled exception in def index')
    session = DBManager.create_session()
    top_30_users = []
    for user in session.query(User).order_by(User.points.desc())[:30]:
        top_30_users.append(user)
    session.close()
    return render_template('points.html',
                           top_30_users=top_30_users,
                           custom_content=custom_content)
Ejemplo n.º 43
0
    def update_highlight(self, id, **options):
        """
        Returns True if a highlight was modified, otherwise return False
        """

        if 'offset' in options:
            options['highlight_offset'] = options.pop('offset')

        session = DBManager.create_session()
        num_rows = session.query(StreamChunkHighlight).filter(StreamChunkHighlight.id == id).update(options)
        session.commit()
        session.close()

        return (num_rows == 1)
Ejemplo n.º 44
0
def highlight_id(date, highlight_id, highlight_title=None):
    session = DBManager.create_session()
    highlight = session.query(StreamChunkHighlight).filter_by(id=highlight_id).first()
    if highlight is None:
        session.close()
        return render_template('highlight_404.html'), 404
    else:
        stream_chunk = highlight.stream_chunk
        stream = stream_chunk.stream
        session.close()
    return render_template('highlight.html',
            highlight=highlight,
            stream_chunk=stream_chunk,
            stream=stream)
Ejemplo n.º 45
0
    def __init__(self, bot, run_later):
        self.db_session = DBManager.create_session()

        self.blacklisted_links = []
        self.whitelisted_links = []

        if 'safebrowsingapi' in bot.config['main']:
            self.safeBrowsingAPI = SafeBrowsingAPI(bot.config['main']['safebrowsingapi'], bot.nickname, bot.version)
        else:
            self.safeBrowsingAPI = None

        self.regex = re.compile(LinkChecker.regex_str, re.IGNORECASE)
        self.run_later = run_later
        self.cache = LinkCheckerCache()  # cache[url] = True means url is safe, False means the link is bad
Ejemplo n.º 46
0
def highlight_id(date, highlight_id, highlight_title=None):
    session = DBManager.create_session()
    highlight = session.query(StreamChunkHighlight).filter_by(
        id=highlight_id).first()
    if highlight is None:
        session.close()
        return render_template('highlight_404.html'), 404
    else:
        stream_chunk = highlight.stream_chunk
        stream = stream_chunk.stream
        session.close()
    return render_template('highlight.html',
                           highlight=highlight,
                           stream_chunk=stream_chunk,
                           stream=stream)
Ejemplo n.º 47
0
def pleblist_history_redirect():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(
            Stream.stream_start.desc()).first()
        if current_stream is not None:
            return redirect('/pleblist/history/{}/'.format(current_stream.id),
                            303)

        last_stream = session.query(Stream).filter_by(ended=True).order_by(
            Stream.stream_start.desc()).first()
        if last_stream is not None:
            return redirect('/pleblist/history/{}/'.format(last_stream.id),
                            303)

        return render_template('pleblist_history_no_stream.html'), 404
Ejemplo n.º 48
0
def highlights():
    session = DBManager.create_session()
    dates_with_highlights = []
    highlights = session.query(StreamChunkHighlight).order_by(StreamChunkHighlight.created_at.desc()).all()
    for highlight in highlights:
        dates_with_highlights.append(datetime.datetime(
            year=highlight.created_at.year,
            month=highlight.created_at.month,
            day=highlight.created_at.day))
    try:
        return render_template('highlights.html',
                highlights=highlights[:5],
                dates_with_highlights=set(dates_with_highlights))
    finally:
        session.close()
Ejemplo n.º 49
0
 def __init__(self, overrides={}):
     UserDict.__init__(self)
     self.db_session = DBManager.create_session()
     self.default_settings = {
             'broadcaster': 'test_broadcaster',
             'ban_ascii': True,
             'ban_msg_length': True,
             'motd_interval_offline': 60,
             'motd_interval_online': 5,
             'max_msg_length': 350,
             'lines_offline': True,
             'parse_pyramids': False,
             'check_links': True,
             }
     self.default_settings.update(overrides)
Ejemplo n.º 50
0
 def __init__(self, overrides={}):
     UserDict.__init__(self)
     self.db_session = DBManager.create_session()
     self.default_settings = {
         'broadcaster': 'test_broadcaster',
         'ban_ascii': True,
         'ban_msg_length': True,
         'motd_interval_offline': 60,
         'motd_interval_online': 5,
         'max_msg_length': 350,
         'lines_offline': True,
         'parse_pyramids': False,
         'parse_emote_combo': False,
         'check_links': True,
     }
     self.default_settings.update(overrides)
Ejemplo n.º 51
0
 def __init__(self, overrides={}):
     UserDict.__init__(self)
     self.db_session = DBManager.create_session()
     self.default_settings = {
         "broadcaster": "test_broadcaster",
         "ban_ascii": True,
         "ban_msg_length": True,
         "motd_interval_offline": 60,
         "motd_interval_online": 5,
         "max_msg_length": 350,
         "lines_offline": True,
         "parse_pyramids": False,
         "parse_emote_combo": False,
         "check_links": True,
     }
     self.default_settings.update(overrides)
Ejemplo n.º 52
0
        def decorated_function(*args, **kwargs):
            if 'user' not in session:
                abort(403)
            with DBManager.create_session_scope() as db_session:
                user = db_session.query(User).filter_by(
                    username=session['user']['username']).one_or_none()
                if user is None:
                    abort(403)

                if user.level < level:
                    abort(403)

                db_session.expunge(user)
                kwargs['user'] = user

            return f(*args, **kwargs)
Ejemplo n.º 53
0
def highlight_list_date(date):
    # Make sure we were passed a valid date
    try:
        parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d')
    except ValueError:
        # Invalid date
        return redirect('/highlights/', 303)
    session = DBManager.create_session()
    highlights = session.query(StreamChunkHighlight).filter(cast(StreamChunkHighlight.created_at, Date) == parsed_date).order_by(StreamChunkHighlight.created_at.desc()).all()

    try:
        return render_template('highlights_date.html',
                highlights=highlights,
                date=parsed_date)
    finally:
        session.close()
Ejemplo n.º 54
0
def stats_duels():
    session = DBManager.create_session()

    data = {
            'top_5_winners': session.query(UserDuelStats).order_by(UserDuelStats.duels_won.desc())[:5],
            'top_5_points_won': session.query(UserDuelStats).order_by(UserDuelStats.profit.desc())[:5],
            'top_5_points_lost': session.query(UserDuelStats).order_by(UserDuelStats.profit.asc())[:5],
            'top_5_losers': session.query(UserDuelStats).order_by(UserDuelStats.duels_lost.desc())[:5],
            'top_5_winrate': session.query(UserDuelStats).filter(UserDuelStats.duels_won >= 5).order_by(UserDuelStats.winrate.desc())[:5],
            'bottom_5_winrate': session.query(UserDuelStats).filter(UserDuelStats.duels_won >= 5).order_by(UserDuelStats.winrate.asc())[:5],
            }

    try:
        return render_template('stats_duels.html', **data)
    finally:
        session.close()
Ejemplo n.º 55
0
def pleblist_list():
    with DBManager.create_session_scope() as session:
        current_stream = session.query(Stream).filter_by(ended=False).order_by(
            Stream.stream_start).first()
        if current_stream is None:
            return make_response(jsonify({'error': 'Stream offline'}), 400)

        songs = session.query(PleblistSong).filter(
            PleblistSong.stream_id == current_stream.id,
            PleblistSong.date_played.is_(None)).all()
        payload = {
            '_total': len(songs),
            'songs': [song.jsonify() for song in songs],
        }

        return jsonify(payload)
Ejemplo n.º 56
0
    def go_offline(self):
        with DBManager.create_session_scope(expire_on_commit=False) as db_session:
            self.current_stream.ended = True
            self.current_stream.stream_end = self.first_offline
            self.current_stream_chunk.chunk_end = self.first_offline

            db_session.add(self.current_stream)
            db_session.add(self.current_stream_chunk)

            db_session.commit()

            db_session.expunge_all()

        self.last_stream = self.current_stream
        self.current_stream = None
        self.current_stream_chunk = None
Ejemplo n.º 57
0
    def __init__(self, bot, run_later):
        self.db_session = DBManager.create_session()

        self.blacklisted_links = []
        self.whitelisted_links = []

        if 'safebrowsingapi' in bot.config['main']:
            self.safeBrowsingAPI = SafeBrowsingAPI(
                bot.config['main']['safebrowsingapi'], bot.nickname,
                bot.version)
        else:
            self.safeBrowsingAPI = None

        self.regex = re.compile(LinkChecker.regex_str, re.IGNORECASE)
        self.run_later = run_later
        self.cache = LinkCheckerCache(
        )  # cache[url] = True means url is safe, False means the link is bad
Ejemplo n.º 58
0
def user_profile(username):
    session = DBManager.create_session()
    user = session.query(User).filter_by(username=username).one_or_none()
    if user is None:
        return render_template('no_user.html'), 404

    rank = session.query(func.Count(User.id)).filter(User.points > user.points).one()
    rank = rank[0] + 1
    session.close()

    user.rank = rank

    if user:
        return render_template('user.html',
                user=user)
    else:
        return render_template('no_user.html'), 404
Ejemplo n.º 59
0
def user_profile(username):
    session = DBManager.create_session()
    user = session.query(User).filter_by(username=username).one_or_none()
    if user is None:
        return render_template('no_user.html'), 404

    rank = session.query(func.Count(User.id)).filter(User.points > user.points).one()
    rank = rank[0] + 1
    user.rank = rank

    user_duel_stats = session.query(UserDuelStats).filter_by(user_id=user.id).one_or_none()

    try:
        return render_template('user.html',
                user=user,
                user_duel_stats=user_duel_stats)
    finally:
        session.close()