Esempio n. 1
0
    def add_banphrase(self, **options):
        """Method for creating and editing banphrases.
        Usage: !add banphrase BANPHRASE [options]
        Multiple options available:
        --length LENGTH
        --perma/--no-perma
        --notify/--no-notify
        """

        message = options['message']
        bot = options['bot']
        source = options['source']

        if message:
            options, phrase = bot.banphrase_manager.parse_banphrase_arguments(message)

            if options is False:
                bot.whisper(source.username, 'Invalid banphrase')
                return False

            options['added_by'] = source.id
            options['edited_by'] = source.id

            banphrase, new_banphrase = bot.banphrase_manager.create_banphrase(phrase, **options)

            if new_banphrase is True:
                bot.whisper(source.username, 'Added your banphrase (ID: {banphrase.id})'.format(banphrase=banphrase))
                return True

            banphrase.set(**options)
            banphrase.data.set(edited_by=options['edited_by'])
            DBManager.session_add_expunge(banphrase)
            bot.banphrase_manager.commit()
            bot.whisper(source.username, 'Updated your banphrase (ID: {banphrase.id}) with ({what})'.format(banphrase=banphrase, what=', '.join([key for key in options if key != 'added_by'])))
Esempio n. 2
0
    def on_banphrase_update(self, data, conn):
        try:
            banphrase_id = int(data["banphrase_id"])
        except (KeyError, ValueError):
            log.warn("No banphrase ID found in on_banphrase_update")
            return False

        updated_banphrase = find(lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
        if updated_banphrase:
            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                db_session.add(updated_banphrase)
                db_session.refresh(updated_banphrase)
                db_session.expunge(updated_banphrase)
        else:
            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                updated_banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
                db_session.expunge_all()
                if updated_banphrase is not None:
                    self.db_session.add(updated_banphrase.data)

        if updated_banphrase:
            if updated_banphrase not in self.banphrases:
                self.banphrases.append(updated_banphrase)
            if updated_banphrase.enabled is True and updated_banphrase not in self.enabled_banphrases:
                self.enabled_banphrases.append(updated_banphrase)

        for banphrase in self.enabled_banphrases:
            if banphrase.enabled is False:
                self.enabled_banphrases.remove(banphrase)
Esempio n. 3
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)
Esempio n. 4
0
    def add_banphrase(bot, source, message, event, args):
        """Dispatch method for creating and editing banphrases.
        Usage: !add banphrase BANPHRASE [options]
        Multiple options available:
        --length LENGTH
        --perma/--no-perma
        --notify/--no-notify
        """

        if message:
            options, phrase = bot.banphrase_manager.parse_banphrase_arguments(message)

            if options is False:
                bot.whisper(source.username, 'Invalid banphrase')
                return False

            options['added_by'] = source.id

            banphrase, new_banphrase = bot.banphrase_manager.create_banphrase(phrase, **options)

            if new_banphrase is True:
                bot.whisper(source.username, 'Added your banphrase (ID: {banphrase.id})'.format(banphrase=banphrase))
                return True

            banphrase.set(**options)
            DBManager.session_add_expunge(banphrase)
            bot.whisper(source.username, 'Updated your banphrase (ID: {banphrase.id}) with ({what})'.format(banphrase=banphrase, what=', '.join([key for key in options])))
Esempio n. 5
0
    def on_banphrase_update(self, data, conn):
        try:
            banphrase_id = int(data['banphrase_id'])
        except (KeyError, ValueError):
            log.warn('No banphrase ID found in on_banphrase_update')
            return False

        updated_banphrase = find(
            lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
        if updated_banphrase:
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                db_session.add(updated_banphrase)
                db_session.refresh(updated_banphrase)
                db_session.expunge(updated_banphrase)
        else:
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                updated_banphrase = db_session.query(Banphrase).filter_by(
                    id=banphrase_id).one_or_none()
                db_session.expunge_all()
                if updated_banphrase is not None:
                    self.db_session.add(updated_banphrase.data)

        if updated_banphrase:
            if updated_banphrase not in self.banphrases:
                self.banphrases.append(updated_banphrase)
            if updated_banphrase.enabled is True and updated_banphrase not in self.enabled_banphrases:
                self.enabled_banphrases.append(updated_banphrase)

        for banphrase in self.enabled_banphrases:
            if banphrase.enabled is False:
                self.enabled_banphrases.remove(banphrase)
Esempio n. 6
0
def modules_edit(module_id, **options):
    module_manager = ModuleManager(None).load(do_reload=False)
    current_module = find(lambda m: m.ID == module_id,
                          module_manager.all_modules)

    if current_module is None:
        return render_template('admin/module_404.html'), 404

    if request.method == 'POST':
        form_values = {key: value for key, value in request.form.items()}
        res = current_module.parse_settings(**form_values)
        if res is False:
            return render_template('admin/module_404.html'), 404

        with DBManager.create_session_scope() as db_session:
            db_module = db_session.query(Module).filter_by(
                id=module_id).one_or_none()
            if db_module is None:
                return render_template('admin/module_404.html'), 404

            db_module.settings = json.dumps(res)
            db_session.commit()

            current_module.db_module = db_module

            settings = None
            try:
                settings = json.loads(db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            SocketClientManager.send('module.update',
                                     {'module_id': db_module.id})

            return render_template('admin/configure_module.html',
                                   module=current_module)
        pass
    else:
        with DBManager.create_session_scope() as db_session:
            db_module = db_session.query(Module).filter_by(
                id=module_id).one_or_none()
            if db_module is None:
                return render_template('admin/module_404.html'), 404

            current_module.db_module = db_module

            settings = None
            try:
                settings = json.loads(db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            return render_template('admin/configure_module.html',
                                   module=current_module)
Esempio n. 7
0
def modules_edit(module_id, **options):
    module_manager = ModuleManager(None).load(do_reload=False)
    current_module = find(lambda m: m.ID == module_id, module_manager.all_modules)

    if current_module is None:
        return render_template('admin/module_404.html'), 404

    if request.method == 'POST':
        form_values = {key: value for key, value in request.form.items()}
        res = current_module.parse_settings(**form_values)
        if res is False:
            return render_template('admin/module_404.html'), 404

        with DBManager.create_session_scope() as db_session:
            db_module = db_session.query(Module).filter_by(id=module_id).one_or_none()
            if db_module is None:
                return render_template('admin/module_404.html'), 404

            db_module.settings = json.dumps(res)
            db_session.commit()

            current_module.db_module = db_module

            settings = None
            try:
                settings = json.loads(db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            SocketClientManager.send('module.update', {'module_id': db_module.id})

            return render_template('admin/configure_module.html',
                    module=current_module)
        pass
    else:
        with DBManager.create_session_scope() as db_session:
            db_module = db_session.query(Module).filter_by(id=module_id).one_or_none()
            if db_module is None:
                return render_template('admin/module_404.html'), 404

            current_module.db_module = db_module

            settings = None
            try:
                settings = json.loads(db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            return render_template('admin/configure_module.html',
                    module=current_module)
Esempio n. 8
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

        log.info('Attempting to fetch video url for broadcast {0}'.format(
            self.current_stream_chunk.broadcast_id))
        stream_chunk = self.current_stream_chunk if self.current_stream_chunk.video_url is None else None
        video_url, video_preview_image_url, video_recorded_at = self.fetch_video_url(
            stream_chunk)
        if video_url is not None:
            log.info('Successfully fetched a video url: {0}'.format(video_url))
            if self.current_stream_chunk is None or self.current_stream_chunk.video_url is None:
                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 video url data.')
            elif self.current_stream_chunk.video_url != video_url:
                # End current stream chunk
                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 = StreamChunk(
                        self.current_stream,
                        self.current_stream_chunk.broadcast_id,
                        video_recorded_at)
                    self.current_stream_chunk = stream_chunk
                    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 video url data in a new chunk.')
        else:
            log.info('Not video for broadcast found')
Esempio n. 9
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')
Esempio n. 10
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(), PleblistSong.id.asc()).first()
         if cur_song is None:
             return None
         session.expunge(cur_song)
         return cur_song
Esempio n. 11
0
def command_remove(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 make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        db_session.delete(command.data)
        db_session.delete(command)

    payload = {
            'event': 'command.remove',
            'data': {
                'command_id': command_id
                }
            }
    payload_bytes = json.dumps(payload).encode('utf-8')
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.connect(config['sock']['sock_file'])
            client.sendall(payload_bytes)
            return make_response(jsonify({'success': 'good job'}))
    except:
        log.exception('???')
        return make_response(jsonify({'error': 'Could not push update'}))
Esempio n. 12
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!'})
Esempio n. 13
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('Successfully 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('Successfully created a stream')
Esempio n. 14
0
def generic_toggle(route_key, row_id, **options):
    valid_routes = {
            'timer': Timer,
            'banphrase': Banphrase,
            'module': Module,
            }

    if route_key not in valid_routes:
        return make_response(jsonify({'error': 'Invalid route.'}), 400)
    if 'new_state' not in request.form:
        return make_response(jsonify({'error': 'Missing `new_state` parameter.'}), 400)
    try:
        new_state = int(request.form['new_state'])
    except (ValueError, KeyError):
        return make_response(jsonify({'error': 'Invalid `new_state` parameter.'}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            row.enabled = True if new_state == 1 else False
            db_session.commit()
            SocketClientManager.send('{}.update'.format(route_key), {'{}_id'.format(route_key): row.id})
            return make_response(jsonify({'success': 'successful toggle', 'new_state': new_state}))
        else:
            return make_response(jsonify({'error': 'invalid {} id'.format(route_key)}))
Esempio n. 15
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)
Esempio n. 16
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!'})
Esempio n. 17
0
    def enable(self, bot):
        self.bot = bot
        if bot:
            bot.add_handler('on_message', self.on_message, priority=100)
            bot.add_handler('on_commit', self.on_commit)
            self.run_later = bot.execute_delayed

            if 'safebrowsingapi' in bot.config['main']:
                # XXX: This should be loaded as a setting instead.
                # There needs to be a setting for settings to have them as "passwords"
                # so they're not displayed openly
                self.safeBrowsingAPI = SafeBrowsingAPI(bot.config['main']['safebrowsingapi'], bot.nickname, bot.version)
            else:
                self.safeBrowsingAPI = None

        if self.db_session is not None:
            self.db_session.commit()
            self.db_session.close()
            self.db_session = None
        self.db_session = DBManager.create_session()
        self.blacklisted_links = []
        for link in self.db_session.query(BlacklistedLink):
            self.blacklisted_links.append(link)

        self.whitelisted_links = []
        for link in self.db_session.query(WhitelistedLink):
            self.whitelisted_links.append(link)
Esempio n. 18
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')
Esempio n. 19
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('Successfully 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('Successfully created a stream')
Esempio n. 20
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
Esempio n. 21
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.
        """
        with DBManager.create_session_scope(
                expire_on_commit=False) as db_session:
            self.current_stream = db_session.query(Stream).filter_by(
                ended=False).order_by(Stream.stream_start.desc()).first()
            self.last_stream = db_session.query(Stream).filter_by(
                ended=True).order_by(Stream.stream_end.desc()).first()
            if self.current_stream:
                self.current_stream_chunk = db_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))
            db_session.expunge_all()
Esempio n. 22
0
def command_remove(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 make_response(jsonify({'error': 'Invalid command ID'}), 404)
        if command.level > options['user'].level:
            abort(403)
        db_session.delete(command.data)
        db_session.delete(command)

    payload = {
            'event': 'command.remove',
            'data': {
                'command_id': command_id
                }
            }
    payload_bytes = json.dumps(payload).encode('utf-8')
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.connect(config['sock']['sock_file'])
            client.sendall(payload_bytes)
            return make_response(jsonify({'success': 'good job'}))
    except:
        log.exception('???')
        return make_response(jsonify({'error': 'Could not push update'}))
Esempio n. 23
0
def generic_toggle(route_key, row_id, **options):
    valid_routes = {
            'timer': Timer,
            'banphrase': Banphrase,
            'module': Module,
            }

    if route_key not in valid_routes:
        return make_response(jsonify({'error': 'Invalid route.'}), 400)
    if 'new_state' not in request.form:
        return make_response(jsonify({'error': 'Missing `new_state` parameter.'}), 400)
    try:
        new_state = int(request.form['new_state'])
    except (ValueError, KeyError):
        return make_response(jsonify({'error': 'Invalid `new_state` parameter.'}), 400)

    route_value = valid_routes[route_key]

    with DBManager.create_session_scope() as db_session:
        row = db_session.query(route_value).filter_by(id=row_id).one_or_none()
        if row:
            row.enabled = True if new_state == 1 else False
            db_session.commit()
            SocketClientManager.send('{}.update'.format(route_key), {'{}_id'.format(route_key): row.id})
            return make_response(jsonify({'success': 'successful toggle', 'new_state': new_state}))
        else:
            return make_response(jsonify({'error': 'invalid {} id'.format(route_key)}))
Esempio n. 24
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)
Esempio n. 25
0
    def authorized():
        try:
            resp = twitch.authorized_response()
        except OAuthException:
            log.exception('An exception was caught while authorizing')
            next_url = get_next_url(request, 'state')
            return redirect(next_url)

        print(resp)
        if resp is None:
            log.warn('Access denied: reason={}, error={}'.format(request.args['error'], request.args['error_description']))
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        elif type(resp) is OAuthException:
            log.warn(resp.message)
            log.warn(resp.data)
            log.warn(resp.type)
            next_url = get_next_url(request, 'state')
            return redirect(next_url)
        session['twitch_token'] = (resp['access_token'], )
        me = twitch.get('user')
        level = 100
        with DBManager.create_session_scope() as db_session:
            db_user = db_session.query(User).filter_by(username=me.data['name'].lower()).one_or_none()
            if db_user:
                level = db_user.level
        session['user'] = {
                'username': me.data['name'],
                'username_raw': me.data['display_name'],
                'level': level,
                }
        next_url = get_next_url(request, 'state')
        return redirect(next_url)
Esempio n. 26
0
    def enable(self, bot):
        self.bot = bot
        if bot:
            bot.add_handler('on_message', self.on_message, priority=100)
            bot.add_handler('on_commit', self.on_commit)
            self.run_later = bot.execute_delayed

            if 'safebrowsingapi' in bot.config['main']:
                # XXX: This should be loaded as a setting instead.
                # There needs to be a setting for settings to have them as "passwords"
                # so they're not displayed openly
                self.safeBrowsingAPI = SafeBrowsingAPI(
                    bot.config['main']['safebrowsingapi'], bot.nickname,
                    bot.version)
            else:
                self.safeBrowsingAPI = None

        if self.db_session is not None:
            self.db_session.commit()
            self.db_session.close()
            self.db_session = None
        self.db_session = DBManager.create_session()
        self.blacklisted_links = []
        for link in self.db_session.query(BlacklistedLink):
            self.blacklisted_links.append(link)

        self.whitelisted_links = []
        for link in self.db_session.query(WhitelistedLink):
            self.whitelisted_links.append(link)
Esempio n. 27
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)
Esempio n. 28
0
def commands(**options):
    from pajbot.models.command import CommandManager
    from pajbot.models.module import ModuleManager
    bot_commands = CommandManager(
        socket_manager=None,
        module_manager=ModuleManager(None).load(),
        bot=None).load(enabled=None)

    bot_commands_list = bot_commands.parse_for_web()
    custom_commands = []
    point_commands = []
    moderator_commands = []

    for command in bot_commands_list:
        if command.id is None:
            continue
        if command.level > 100 or command.mod_only:
            moderator_commands.append(command)
        elif command.cost > 0:
            point_commands.append(command)
        else:
            custom_commands.append(command)

    with DBManager.create_session_scope() as db_session:
        moderator_users = db_session.query(User).filter(User.level > 100).order_by(User.id.desc()).all()
        return render_template(
            'admin/commands.html',
            moderator_users=moderator_users,
            custom_commands=sorted(custom_commands, key=lambda f: f.command),
            point_commands=sorted(point_commands, key=lambda a: (a.cost, a.command)),
            moderator_commands=sorted(moderator_commands, key=lambda c: (c.level if c.mod_only is False else 500, c.command)),
            created=session.pop('command_created_id', None),
            edited=session.pop('command_edited_id', None))
Esempio 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)
Esempio n. 30
0
def pleblist_validate():
    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)

    with DBManager.create_session_scope() as session:
        youtube_id = request.form["youtube_id"]
        print(youtube_id)
        song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
        if song_info is not None:
            return jsonify({"message": "success", "song_info": song_info.jsonify()})

        PleblistManager.init(config["youtube"]["developer_key"])
        song_info = PleblistManager.create_pleblist_song_info(youtube_id)
        if not song_info and len(youtube_id) > 11:
            youtube_id = youtube_id[:11]
            song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first()
            if song_info is not None:
                return jsonify({"message": "success", "new_youtube_id": youtube_id, "song_info": song_info.jsonify()})
            else:
                song_info = PleblistManager.create_pleblist_song_info(youtube_id)

        if song_info:
            print(song_info)
            session.add(song_info)
            session.commit()
            return jsonify({"message": "success", "new_youtube_id": youtube_id, "song_info": song_info.jsonify()})

        return jsonify({"message": "invalid youtube id", "song_info": None})
Esempio n. 31
0
def timers_edit(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()

        if timer is None:
            return render_template('admin/timer_404.html'), 404

        return render_template('admin/create_timer.html', timer=timer)
Esempio n. 32
0
def timer_remove(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
        if timer is None:
            return make_response(jsonify({"error": "Invalid timer ID"}))
        db_session.delete(timer)
        SocketClientManager.send("timer.remove", {"timer_id": timer.id})
        return make_response(jsonify({"success": "good job"}))
Esempio n. 33
0
def timer_remove(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
        if timer is None:
            return make_response(jsonify({'error': 'Invalid timer ID'}))
        db_session.delete(timer)
        SocketClientManager.send('timer.remove', {'timer_id': timer.id})
        return make_response(jsonify({'success': 'good job'}))
Esempio n. 34
0
def timer_remove(timer_id, **options):
    with DBManager.create_session_scope() as db_session:
        timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()
        if timer is None:
            return make_response(jsonify({'error': 'Invalid timer ID'}))
        db_session.delete(timer)
        SocketClientManager.send('timer.remove', {'timer_id': timer.id})
        return make_response(jsonify({'success': 'good job'}))
Esempio n. 35
0
    def modules_edit(module_id, **options):
        module_manager = ModuleManager(None).load(do_reload=False)
        current_module = find(lambda m: m.ID == module_id, module_manager.all_modules)

        if current_module is None:
            return render_template('admin/module_404.html'), 404

        sub_modules = []
        for module in module_manager.all_modules:
            module.db_module = None

        with DBManager.create_session_scope() as db_session:
            for db_module in db_session.query(Module):
                module = find(lambda m: m.ID == db_module.id, module_manager.all_modules)
                if module:
                    module.db_module = db_module
                    if module.PARENT_MODULE == current_module.__class__:
                        sub_modules.append(module)

            if current_module.db_module is None:
                return render_template('admin/module_404.html'), 404

            if request.method == 'POST':
                form_values = {key: value for key, value in request.form.items()}
                res = current_module.parse_settings(**form_values)
                if res is False:
                    return render_template('admin/module_404.html'), 404

                current_module.db_module.settings = json.dumps(res)
                db_session.commit()

                settings = None
                try:
                    settings = json.loads(current_module.db_module.settings)
                except (TypeError, ValueError):
                    pass
                current_module.load(settings=settings)

                payload = {
                        'id': current_module.db_module.id,
                        }

                SocketClientManager.send('module.update', payload)

                return render_template('admin/configure_module.html',
                        module=current_module,
                        sub_modules=sub_modules)
            else:
                settings = None
                try:
                    settings = json.loads(current_module.db_module.settings)
                except (TypeError, ValueError):
                    pass
                current_module.load(settings=settings)

                return render_template('admin/configure_module.html',
                        module=current_module,
                        sub_modules=sub_modules)
Esempio n. 36
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)
Esempio n. 37
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)
Esempio n. 38
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)

        self.rebuild()
Esempio n. 39
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)

        self.rebuild()
Esempio n. 40
0
def banphrase_remove(banphrase_id, **options):
    with DBManager.create_session_scope() as db_session:
        banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
        if banphrase is None:
            return make_response(jsonify({"error": "Invalid banphrase ID"}))
        db_session.delete(banphrase)
        db_session.delete(banphrase.data)
        SocketClientManager.send("banphrase.remove", {"banphrase_id": banphrase.id})
        return make_response(jsonify({"success": "good job"}))
Esempio n. 41
0
def modules_edit(module_id, **options):
    module_manager = ModuleManager(None).load(do_reload=False)
    current_module = find(lambda m: m.ID == module_id,
                          module_manager.all_modules)

    if current_module is None:
        return render_template('admin/module_404.html'), 404

    sub_modules = []
    for module in module_manager.all_modules:
        module.db_module = None

    with DBManager.create_session_scope() as db_session:
        for db_module in db_session.query(Module):
            module = find(lambda m: m.ID == db_module.id,
                          module_manager.all_modules)
            if module:
                module.db_module = db_module
                if module.PARENT_MODULE == current_module.__class__:
                    sub_modules.append(module)

        if current_module.db_module is None:
            return render_template('admin/module_404.html'), 404

        if request.method == 'POST':
            form_values = {key: value for key, value in request.form.items()}
            res = current_module.parse_settings(**form_values)
            if res is False:
                return render_template('admin/module_404.html'), 404

            current_module.db_module.settings = json.dumps(res)
            db_session.commit()

            settings = None
            try:
                settings = json.loads(current_module.db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            SocketClientManager.send(
                'module.update', {'module_id': current_module.db_module.id})

            return render_template('admin/configure_module.html',
                                   module=current_module,
                                   sub_modules=sub_modules)
        else:
            settings = None
            try:
                settings = json.loads(current_module.db_module.settings)
            except (TypeError, ValueError):
                pass
            current_module.load(settings=settings)

            return render_template('admin/configure_module.html',
                                   module=current_module,
                                   sub_modules=sub_modules)
Esempio n. 42
0
def banphrases_edit(banphrase_id, **options):
    with DBManager.create_session_scope() as db_session:
        banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()

        if banphrase is None:
            return render_template('admin/banphrase_404.html'), 404

        return render_template('admin/create_banphrase.html',
                banphrase=banphrase)
Esempio n. 43
0
    def __init__(self, bot):
        self.bot = bot
        self.banphrases = []
        self.enabled_banphrases = []
        self.db_session = DBManager.create_session(expire_on_commit=False)

        if self.bot:
            self.bot.socket_manager.add_handler("banphrase.update", self.on_banphrase_update)
            self.bot.socket_manager.add_handler("banphrase.remove", self.on_banphrase_remove)
Esempio n. 44
0
def banphrase_remove(banphrase_id, **options):
    with DBManager.create_session_scope() as db_session:
        banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
        if banphrase is None:
            return make_response(jsonify({'error': 'Invalid banphrase ID'}))
        db_session.delete(banphrase)
        db_session.delete(banphrase.data)
        SocketClientManager.send('banphrase.remove', {'banphrase_id': banphrase.id})
        return make_response(jsonify({'success': 'good job'}))
Esempio n. 45
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)
Esempio n. 46
0
    def timers_create(**options):
        session.pop('timer_created_id', None)
        session.pop('timer_edited_id', None)
        if request.method == 'POST':
            id = None
            try:
                if 'id' in request.form:
                    id = int(request.form['id'])
                name = request.form['name'].strip()
                interval_online = int(request.form['interval_online'])
                interval_offline = int(request.form['interval_offline'])
                message_type = request.form['message_type']
                message = request.form['message'].strip()
            except (KeyError, ValueError):
                abort(403)

            if interval_online < 0 or interval_offline < 0:
                abort(403)

            if message_type not in ['say', 'me']:
                abort(403)

            if len(message) == 0:
                abort(403)

            options = {
                    'name': name,
                    'interval_online': interval_online,
                    'interval_offline': interval_offline,
                    }

            action = {
                    'type': message_type,
                    'message': message
                    }
            options['action'] = action

            if id is None:
                timer = Timer(**options)

            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                if id is not None:
                    timer = db_session.query(Timer).filter_by(id=id).one_or_none()
                    if timer is None:
                        return redirect('/admin/timers/', 303)
                    timer.set(**options)
                else:
                    db_session.add(timer)

            SocketClientManager.send('timer.update', {'timer_id': timer.id})
            if id is None:
                session['timer_created_id'] = timer.id
            else:
                session['timer_edited_id'] = timer.id
            return redirect('/admin/timers/', 303)
        else:
            return render_template('admin/create_timer.html')
Esempio n. 47
0
def banphrase_remove(banphrase_id, **options):
    with DBManager.create_session_scope() as db_session:
        banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
        if banphrase is None:
            return make_response(jsonify({'error': 'Invalid banphrase ID'}))
        db_session.delete(banphrase)
        db_session.delete(banphrase.data)
        SocketClientManager.send('banphrase.remove', {'banphrase_id': banphrase.id})
        return make_response(jsonify({'success': 'good job'}))
Esempio n. 48
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)
Esempio n. 49
0
    def timers_edit(timer_id, **options):
        with DBManager.create_session_scope() as db_session:
            timer = db_session.query(Timer).filter_by(id=timer_id).one_or_none()

            if timer is None:
                return render_template('admin/timer_404.html'), 404

            return render_template('admin/create_timer.html',
                    timer=timer)
Esempio n. 50
0
    def banphrases_edit(banphrase_id, **options):
        with DBManager.create_session_scope() as db_session:
            banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()

            if banphrase is None:
                return render_template('admin/banphrase_404.html'), 404

            return render_template('admin/create_banphrase.html',
                    banphrase=banphrase)
Esempio n. 51
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)
Esempio n. 52
0
def timers_create(**options):
    session.pop('timer_created_id', None)
    session.pop('timer_edited_id', None)
    if request.method == 'POST':
        id = None
        try:
            if 'id' in request.form:
                id = int(request.form['id'])
            name = request.form['name'].strip()
            interval_online = int(request.form['interval_online'])
            interval_offline = int(request.form['interval_offline'])
            message_type = request.form['message_type']
            message = request.form['message'].strip()
        except (KeyError, ValueError):
            abort(403)

        if interval_online < 0 or interval_offline < 0:
            abort(403)

        if message_type not in ['say', 'me']:
            abort(403)

        if len(message) == 0:
            abort(403)

        options = {
                'name': name,
                'interval_online': interval_online,
                'interval_offline': interval_offline,
                }

        action = {
                'type': message_type,
                'message': message
                }
        options['action'] = action

        if id is None:
            timer = Timer(**options)

        with DBManager.create_session_scope(expire_on_commit=False) as db_session:
            if id is not None:
                timer = db_session.query(Timer).filter_by(id=id).one_or_none()
                if timer is None:
                    return redirect('/admin/timers/', 303)
                timer.set(**options)
            else:
                db_session.add(timer)

        SocketClientManager.send('timer.update', {'timer_id': timer.id})
        if id is None:
            session['timer_created_id'] = timer.id
        else:
            session['timer_edited_id'] = timer.id
        return redirect('/admin/timers/', 303)
    else:
        return render_template('admin/create_timer.html')
Esempio n. 53
0
def moderators(**options):
    with DBManager.create_session_scope() as db_session:
        moderator_users = db_session.query(User).filter(User.level > 100).order_by(User.level.desc()).all()
        userlists = collections.OrderedDict()
        userlists['Admins'] = list(filter(lambda user: user.level >= 2000, moderator_users))
        userlists['Super Moderators/Broadcaster'] = list(filter(lambda user: user.level >= 1000 and user.level < 2000, moderator_users))
        userlists['Moderators'] = list(filter(lambda user: user.level >= 500 and user.level < 1000, moderator_users))
        userlists['Notables/Helpers'] = list(filter(lambda user: user.level >= 101 and user.level < 500, moderator_users))
        return render_template('admin/moderators.html',
                userlists=userlists)
Esempio n. 54
0
def predictions(**options):
    with DBManager.create_session_scope() as db_session:
        predictions = db_session.query(PredictionRun).order_by(PredictionRun.started.desc()).all()

        for prediction in predictions:
            prediction.num_entries = db_session.query(PredictionRunEntry).filter_by(prediction_run_id=prediction.id).count()
            pass

        return render_template('admin/predictions.html',
                predictions=predictions)
Esempio n. 55
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)
Esempio n. 56
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)
Esempio n. 57
0
 def get_highlight_thumbnails(no_clue_what_this_does):
     from pajbot.web.models.thumbnail import StreamThumbnailWriter
     with DBManager.create_session_scope() as db_session:
         highlights = db_session.query(StreamChunkHighlight).filter_by(thumbnail=None).all()
         if len(highlights) > 0:
             log.info('Writing {} thumbnails...'.format(len(highlights)))
             StreamThumbnailWriter(config['main']['streamer'], [h.id for h in highlights])
             log.info('Done!')
             for highlight in highlights:
                 highlight.thumbnail = True
Esempio n. 58
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(),
                 PleblistSong.id.asc()).first()
         if cur_song is None:
             return None
         session.expunge(cur_song)
         return cur_song
Esempio n. 59
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))