Esempio n. 1
0
    def _get_messages(self, args):
        """Gets messages from the database"""

        self.print_ok('Fetching data..')
        conditions = [Message.scan == self.current_scan]

        if args.show_only_labeled:
            conditions.append(Topic.not_empty_label())

        if args.message_regex:
            if args.case_sensitive:
                conditions.append(Message.body.regexp(args.message_regex))
            else:
                conditions.append(
                    fn.lower(Message.body).regexp(args.message_regex))

        if args.topic_regex:
            if args.case_sensitive:
                conditions.append(Topic.name.regexp(args.topic_regex))
            else:
                conditions.append(
                    fn.lower(Topic.name).regexp(args.topic_regex))

        return self._generic_fetch_messages(reduce(iand, conditions),
                                            limit=args.limit)
Esempio n. 2
0
def search_categories(query):
    query = query.lower().strip()
    categories = Category.select().where(
        (fn.lower(Category.name).contains(query)) |
        (fn.lower(Category.extra).contains(query))
    )
    return categories
def messages_with_keys_x_seconds(settings, seconds, keys_key, ranking=False):
    """
    Return the messages count with keys per determinate seconds.

    Positional arguments:
    seconds     --  The number of seconds that the script must look
                    in the past.
    keys_key    --  Name of the key that is on the `twitch.yml` file.
    Keyword arguments:
    ranking     --  If the result should return in form of a ranking, where
                    each key result in a key inside a hash with the value
                    that is the count of occourrences.
    """
    if not keys_key and keys_key not in settings['keys']:
        raise ValueError(
            f'Config file attribute `keys` do not contains `{keys_key}`')

    now = time.time()

    if settings['keys'][keys_key]['meta'].get('no_filter'):
        return Message.select().where(Message.time >= now - seconds).count()
    else:
        if ranking:
            counters = {}
            for key in settings['keys'][keys_key]['list']:
                if settings['keys'][keys_key]['meta']['case'] == 'SENSITIVE':
                    counters[key] = Message.select().where(
                        Message.time >= now - seconds,
                        Message.text.contains(key)
                    ).count()
                elif settings['keys'][keys_key]['meta']['case'] == 'INSENSITIVE':
                    counters[key] = Message.select().where(
                        Message.time >= now - seconds,
                        fn.lower(Message.text).contains(key.lower())
                    ).count()
                else:
                    raise ValueError(
                        'key.meta.case must be "SENSITIVE" or "INSENSITIVE"')

            return counters
        else:
            counter = 0
            for key in settings['keys'][keys_key]['list']:
                if settings['keys'][keys_key]['meta']['case'] == 'SENSITIVE':
                    count = Message.select().where(
                        Message.time >= now - seconds,
                        Message.text.contains(key)
                    ).count()
                    counter += count
                elif settings['keys'][keys_key]['meta']['case'] == 'INSENSITIVE':
                    count = Message.select().where(
                        Message.time >= now - seconds,
                        fn.lower(Message.text).contains(key.lower())
                    ).count()
                    counter += count
                else:
                    raise ValueError(
                        'key.meta.case must be "SENSITIVE" or "INSENSITIVE"')

            return counter
Esempio n. 4
0
def search_bots(query):
    query = query.lower().strip()
    split = query.split(' ')

    # easter egg
    if query in ('awesome bot', 'great bot', 'superb bot', 'best bot',
                 'best bot ever'):
        return [Bot.by_username('@botlistbot')]

    # exact results
    where_query = ((fn.lower(Bot.username).contains(query)
                    | fn.lower(Bot.name) << split | fn.lower(Bot.extra)**query)
                   & (Bot.revision <= Revision.get_instance().nr & Bot.approved
                      == True & Bot.disabled == False))
    results = set(Bot.select().distinct().where(where_query))

    # keyword results
    keyword_results = Bot.select(Bot).join(
        Keyword).where((fn.lower(Keyword.name) << split)
                       & (Bot.revision <= Revision.get_instance().nr)
                       & (Bot.approved == True & Bot.disabled == False))
    results.update(keyword_results)

    # many @usernames
    usernames = re.findall(settings.REGEX_BOT_ONLY, query)
    if usernames:
        try:
            bots = Bot.many_by_usernames(usernames)
            print([b.username for b in bots])
            results.update(bots)
        except Bot.DoesNotExist:
            pass

    return list(results)
Esempio n. 5
0
def handle_command(command, message, team_name, event):
    if command in ['help', 'hjelp']:
        return 'Ikke implementert enda, ping <@U8PL7CR4K>'

    if command in ALLOWED_COMMANDS.keys():
        slack_id = event['user']
        member = Member.get_or_none(Member.slack_id == slack_id)
        if member is None:
            return 'Finner deg ikke i systemet, er du sikker på at du tilhører et team?'

        if command in ['ferie', 'team', 'meld av']:
            return ALLOWED_COMMANDS[command](message, member)

        team = None
        if len(member.teams()) > 1 or team_name:
            if team_name:
                team = Team.get_or_none(fn.lower(Team.name) == team_name.lower())
                if team is None:
                    return 'Finner ikke `{}` i systemet, har du skrevet riktig?'.format(team_name)
                if not team.has_member(member):
                    return 'Du er ikke medlem av `{}`'.format(team_name)
            elif member.team_id:
                team = member.team
            else:
                return 'Du er medlem av flere teams; {}\nSpesifieres med `#team-navn {} {}`'.format(
                    ', '.join([t.name for t in member.teams()]), command, message)
        else:
            team = member.teams()[0]

        return ALLOWED_COMMANDS[command](message, member, team)
    else:
        return None
Esempio n. 6
0
def init_indexer_table_entry(indexer_name):
    try:
        Indexer.get(fn.lower(Indexer.name) == indexer_name.lower())
    except Indexer.DoesNotExist as e:
        logger.info("Unable to find indexer with name %s in database. Will add it" % indexer_name)
        indexer = Indexer().create(name=indexer_name)
        IndexerStatus.create_or_get(indexer=indexer, first_failure=None, latest_failure=None, disabled_until=None)
Esempio n. 7
0
 def validate_credentials(self, email, password):
     user = User.select().where(fn.lower(User.email) == email.lower()).first()
     if not user:
         raise self.UserDoesNotExist
     if not self.password_match(user, password):
         raise self.InvalidPassword
     return user
Esempio n. 8
0
def notify_bot_spam(bot, update, args=None):
    tg_user = update.message.from_user
    user = User.from_telegram_object(tg_user)
    if util.stop_banned(update, user):
        return
    reply_to = util.original_reply_id(update)

    if args:
        text = ' '.join(args)
    else:
        text = update.message.text
        command_no_args = len(
            re.findall(r'^/spam\s*$',
                       text)) > 0 or text.lower().strip() == '/spam@botlistbot'
        if command_no_args:
            update.message.reply_text(util.action_hint(
                "Please use this command with an argument. For example:\n/spam @mybot"
            ),
                                      reply_to_message_id=reply_to)
            return

    # `#spam` is already checked by handler
    try:
        username = re.match(settings.REGEX_BOT_IN_TEXT, text).groups()[0]
        if username == '@' + settings.SELF_BOT_NAME:
            log.info("Ignoring {}".format(text))
            return
    except AttributeError:
        if args:
            update.message.reply_text(util.failure(
                "Sorry, but you didn't send me a bot `@username`."),
                                      quote=True,
                                      parse_mode=ParseMode.MARKDOWN,
                                      reply_to_message_id=reply_to)
        else:
            log.info("Ignoring {}".format(text))
            # no bot username, ignore update
            pass
        return

    try:
        spam_bot = Bot.get(
            fn.lower(Bot.username)**username.lower(), Bot.approved == True)
        try:
            Suggestion.get(action="spam", subject=spam_bot)
        except Suggestion.DoesNotExist:
            suggestion = Suggestion(user=user,
                                    action="spam",
                                    date=datetime.date.today(),
                                    subject=spam_bot)
            suggestion.save()
        update.message.reply_text(util.success(
            "Thank you! We will review your suggestion and mark the bot as spammy."
        ),
                                  reply_to_message_id=reply_to)
    except Bot.DoesNotExist:
        update.message.reply_text(
            util.action_hint("The bot you sent me is not in the @BotList."),
            reply_to_message_id=reply_to)
    return ConversationHandler.END
Esempio n. 9
0
def get_indexer_nzb_link(indexer_name, indexerguid, title, searchid, mode, log_api_access):
    """
    Build a link that leads to the actual NZB of the indexer using the given informations. We log this as indexer API access and NZB download because this is only called
    when the NZB will be actually downloaded later (by us or a downloader) 
    :return: str
    """
    for p in indexers.enabled_indexers:
        if p.name.strip() == indexer_name.strip():
            link = p.get_nzb_link(indexerguid, title)

            # Log to database
            indexer = Indexer.get(fn.lower(Indexer.name) == indexer_name.lower())
            papiaccess = IndexerApiAccess(indexer=p.indexer, type="nzb", url=link, response_successful=None, indexer_search=searchid) if log_api_access else None
            try:
                papiaccess.username = request.authorization.username if request.authorization is not None else None
            except RuntimeError:
                pass
            papiaccess.save()
            pnzbdl = IndexerNzbDownload(indexer=indexer, indexer_search=searchid, api_access=papiaccess, mode=mode, title=title, guid=indexerguid)
            pnzbdl.save()

            return link, papiaccess, pnzbdl

    else:
        logger.error("Did not find indexer with name %s" % indexer_name)
        return None, None, None
Esempio n. 10
0
async def get_dog_by_name(request, dog_name: str):
    """Search by dog's name"""
    try:
        dogs_to_show = Dog.select().where(
            fn.lower(Dog.name) == dog_name.lower())
    except DoesNotExist:
        status = {'error': f'can not find a dog with the name {dog_name}'}
    else:
        status = []
        for dog in dogs_to_show:
            print(
                str(dog.name).lower(), dog_name.lower(),
                str(dog.name).lower() == dog_name.lower())
            status.append({
                'id': dog.id,
                'name': dog.name,
                'color': dog.color,
                'birthday': dog.birthday,
                'breed': dog.breed.name,
                'vaccinated': dog.vaccinated,
            })
        if not status:
            status = {'error': f'can not find a dog with the name {dog_name}'}

    return json(status)
Esempio n. 11
0
def internalapi_enable_indexer(args):
    logger.debug("Enabling indexer %s" % args["name"])
    indexer_status = IndexerStatus().select().join(Indexer).where(fn.lower(Indexer.name) == args["name"].lower())
    indexer_status.disabled_until = 0
    indexer_status.reason = None
    indexer_status.level = 0
    indexer_status.save()
    return jsonify({"indexerStatuses": get_indexer_statuses()})
Esempio n. 12
0
def init_indexer_table_entry(indexer_name):
    try:
        Indexer.get(fn.lower(Indexer.name) == indexer_name.lower())
    except Indexer.DoesNotExist as e:
        logger.info(
            "Unable to find indexer with name %s in database. Will add it" %
            indexer_name)
        Indexer().create(name=indexer_name)
Esempio n. 13
0
def internalapi_enable_indexer(args):
    logger.debug("Enabling indexer %s" % args["name"])
    indexer_status = IndexerStatus().select().join(Indexer).where(fn.lower(Indexer.name) == args["name"].lower()).get()
    indexer_status.disabled_until = 0
    indexer_status.reason = None
    indexer_status.level = 0
    indexer_status.save()
    return jsonify({"indexerStatuses": get_indexer_statuses()})
Esempio n. 14
0
    def find_user(self, case_insensitive=False, **kwargs):
        from peewee import fn as peeweeFn

        try:
            if case_insensitive:
                # While it is of course possible to pass in multiple keys to filter on
                # that isn't the normal use case. If caller asks for case_insensitive
                # AND gives multiple keys - throw an error.
                if len(kwargs) > 1:
                    raise ValueError(
                        "Case insensitive option only supports single key")
                attr, identifier = kwargs.popitem()
                return self.user_model.get(
                    peeweeFn.lower(getattr(self.user_model, attr)) ==
                    peeweeFn.lower(identifier))
            else:
                return self.user_model.filter(**kwargs).get()
        except self.user_model.DoesNotExist:
            return None
Esempio n. 15
0
def check_user_password(username, password):
    username_regexp = re.compile(r'[A-Za-z0-9_-]{3,32}')
    if not re.fullmatch(username_regexp, username):
        raise ValueError("Bad Symbols!")
    with db_request("User") as User:
        row = User.select().where(
            (fn.lower(User.username) == username.lower())
            & (User.password_hash == salted_sha256_string(password))).first()
        if row is None:
            raise ValueError("Bad user credentials")
        return row.id, row.username, row.is_food_service
Esempio n. 16
0
async def fetch_infraction_pages(guild_id, query, amount, fields, requested):
    key = get_key(guild_id, query, fields, amount)
    if query == "":
        infs = Infraction.select().where(
            Infraction.guild_id == guild_id).order_by(
                Infraction.id.desc()).limit(50)
    else:
        infs = Infraction.select().where((Infraction.guild_id == guild_id) & (
            ("[user]" in fields and isinstance(query, int) and Infraction.
             user_id == query) | ("[mod]" in fields and isinstance(query, int)
                                  and Infraction.mod_id == query)
            | ("[reason]" in fields and fn.lower(Infraction.reason).contains(
                str(query).lower())))).order_by(Infraction.id.desc()).limit(
                    int(amount))
    longest_type = 4
    longest_id = len(str(infs[0].id)) if len(infs) > 0 else len(
        Translator.translate('id', guild_id))
    longest_timestamp = max(len(Translator.translate('timestamp', guild_id)),
                            19)
    types = dict()
    for inf in infs:
        t = inf.type.lower()
        longest_type = max(longest_type, len(Translator.translate(t,
                                                                  guild_id)))
        if t not in types:
            types[t] = 1
        else:
            types[t] += 1
    header = ", ".join(
        Translator.translate(f"{k}s", guild_id, count=v)
        for k, v in types.items())
    name = await Utils.username(query) if isinstance(
        query, int) else await Utils.clean(bot.get_guild(guild_id).name)
    title = f"{Emoji.get_chat_emoji('SEARCH')} {Translator.translate('inf_search_header', guild_id, name=name, page_num=100, pages=100)}\n```md\n\n```"
    page_header = get_header(longest_id, 37, longest_type, longest_timestamp,
                             guild_id)
    mcount = 2000 - len(header) - len(page_header) - len(title)
    out = "\n".join(
        f"{Utils.pad(str(inf.id), longest_id)} | <@{Utils.pad(str(inf.user_id), 37)}> | <@{Utils.pad(str(inf.mod_id), 37)}> | {inf.start} | {Utils.pad(Translator.translate(inf.type.lower(), guild_id), longest_type)} | {Utils.trim_message(inf.reason, 1000)}"
        for inf in infs)
    pages = Pages.paginate(out, max_chars=mcount)
    if bot.redis_pool is not None:
        GearbotLogging.debug(f"Pushing placeholders for {key}")
        pipe = bot.redis_pool.pipeline()
        for page in pages:
            pipe.lpush(key, "---NO PAGE YET---")
        await pipe.execute()
    bot.loop.create_task(
        update_pages(guild_id, query, fields, amount, pages, requested,
                     longest_id, longest_type, longest_timestamp, header))
    return len(pages)
Esempio n. 17
0
def register_user(username, password, is_food_provider=False):
    with db_request("User") as User:
        try:
            row = User.select()\
                .where(fn.lower(User.username) == username.lower()).first()
            if row is not None:
                raise IntegrityError()
            User.insert(username=username,
                        password_hash=salted_sha256_string(password),
                        registration_date=datetime.now(),
                        is_food_service=is_food_provider).execute()
        except IntegrityError:
            raise ValueError(
                "User \"{}\" already registered!".format(username))
Esempio n. 18
0
def view_ignores(page):
    """ View user's blocked users. """
    if current_user.can_admin:
        abort(404)
    menu = request.args.get("menu", "user")

    def add_form(ig):
        messages = "hide" if ig["hide_messages"] else "show"
        if ig["method"] is None:
            content = "show"
        elif ig["method"] == UserContentBlockMethod.HIDE:
            content = "hide"
        else:
            content = "blur"
        ig["form"] = EditIgnoreForm(view_messages=messages,
                                    view_content=content)
        return ig

    query = (User.select(
        User.name,
        User.uid.alias("target"),
        UserMessageBlock.id.is_null(False).alias("hide_messages"),
        UserContentBlock.method,
    ).join(
        UserMessageBlock,
        JOIN.LEFT_OUTER,
        on=((UserMessageBlock.uid == current_user.uid)
            & (UserMessageBlock.target == User.uid)),
    ).join(
        UserContentBlock,
        JOIN.LEFT_OUTER,
        on=((UserContentBlock.uid == current_user.uid)
            & (UserContentBlock.target == User.uid)),
    ).where((User.status == UserStatus.OK)
            & (UserContentBlock.id.is_null(False)
               | UserMessageBlock.id.is_null(False))).order_by(
                   fn.lower(User.name)).paginate(page, 25).dicts())
    igns = [add_form(ig) for ig in query]

    return engine.get_template("user/ignores.html").render({
        "igns":
        igns,
        "user":
        User.get(User.uid == current_user.uid),
        "page":
        page,
        "menu":
        menu,
    })
Esempio n. 19
0
def register():
    group_name = request.form['group'].strip()
    player_name = request.form['player'].strip()

    try:
        # Perform case-insensitive search.
        group = Group.get(fn.Lower(Group.name) == group_name.lower())
    except:
        group = Group.create(name=group_name)

    try:
        # Perform case-insensitive search.
        player = Player.get(fn.lower(Player.name) == player_name.lower(), group=group)
    except Player.DoesNotExist:
        player = Player.create(
            group=group, name=player_name, order=group.players.count())

    return str(player.id)
Esempio n. 20
0
def register():
    group_name = request.form['group'].strip()
    player_name = request.form['player'].strip()

    try:
        # Perform case-insensitive search.
        group = Group.get(fn.Lower(Group.name) == group_name.lower())
    except:
        group = Group.create(name=group_name)

    try:
        # Perform case-insensitive search.
        player = Player.get(fn.lower(Player.name) == player_name.lower(),
                            group=group)
    except Player.DoesNotExist:
        player = Player.create(group=group,
                               name=player_name,
                               order=group.players.count())

    return str(player.id)
Esempio n. 21
0
def get_nzb_link(indexer_name, guid, title, searchid):
    """
    Build a link that leads to the actual NZB of the indexer using the given informations. We log this as indexer API access and NZB download because this is only called
    when the NZB will be actually downloaded later (by us or a downloader) 
    :return: str
    """
    for p in indexers.enabled_indexers:
        if p.name == indexer_name:
            link = p.get_nzb_link(guid, title)

            # Log to database
            indexer = Indexer.get(fn.lower(Indexer.name) == indexer_name.lower())
            papiaccess = IndexerApiAccess(indexer=p.indexer, type="nzb", url=link, response_successful=None, indexer_search=indexer)
            papiaccess.save()
            pnzbdl = IndexerNzbDownload(indexer=indexer, indexer_search=searchid, api_access=papiaccess, mode="redirect")
            pnzbdl.save()

            return link

    else:
        logger.error("Did not find indexer with name %s" % indexer_name)
        return None
Esempio n. 22
0
def download_nzb_and_log(indexer_name, provider_guid, title, searchid):
    """
    Gets the NZB link from the indexer using the guid, downloads it and logs the download

    :param indexer_name: name of the indexer
    :param provider_guid: guid to build link
    :param title: the title to build the link
    :param searchid: the id of the IndexerSearch entry so we can link the download to a search
    :return: IndexerNzbDownloadResult
    """
    for p in indexers.enabled_indexers:
        if p.name == indexer_name:

            link = p.get_nzb_link(provider_guid, title)
            indexer = Indexer.get(fn.lower(Indexer.name) == indexer_name.lower())
            psearch = IndexerSearch.get((IndexerSearch.indexer == indexer) & (IndexerSearch.search == searchid))
            papiaccess = IndexerApiAccess(indexer=p.indexer, type="nzb", url=link, indexer_search=psearch)
            papiaccess.save()

            internallink, guid = get_nzb_link_and_guid(indexer_name, provider_guid, searchid, title)
            pnzbdl = IndexerNzbDownload(indexer=indexer, indexer_search=searchid, api_access=papiaccess, mode="serve", title=title, guid=internallink)
            pnzbdl.save()
            try:
                r = p.get(link, timeout=10)
                r.raise_for_status()

                papiaccess.response_successful = True
                papiaccess.response_time = r.elapsed.microseconds / 1000

                return IndexerNzbDownloadResult(content=r.content, headers=r.headers)
            except RequestException as e:
                logger.error("Error while connecting to URL %s: %s" % (link, str(e)))
                papiaccess.error = str(e)
                return None
            finally:
                papiaccess.save()
    else:
        return "Unable to find NZB link"
Esempio n. 23
0
def get_indexer_nzb_link(indexer_name, indexerguid, title, searchid, mode,
                         log_api_access):
    """
    Build a link that leads to the actual NZB of the indexer using the given informations. We log this as indexer API access and NZB download because this is only called
    when the NZB will be actually downloaded later (by us or a downloader) 
    :return: str
    """
    for p in indexers.enabled_indexers:
        if p.name.strip() == indexer_name.strip():
            link = p.get_nzb_link(indexerguid, title)

            # Log to database
            indexer = Indexer.get(
                fn.lower(Indexer.name) == indexer_name.lower())
            papiaccess = IndexerApiAccess(
                indexer=p.indexer,
                type="nzb",
                url=link,
                response_successful=None,
                indexer_search=searchid) if log_api_access else None
            try:
                papiaccess.username = request.authorization.username if request.authorization is not None else None
            except RuntimeError:
                pass
            papiaccess.save()
            pnzbdl = IndexerNzbDownload(indexer=indexer,
                                        indexer_search=searchid,
                                        api_access=papiaccess,
                                        mode=mode,
                                        title=title,
                                        guid=indexerguid)
            pnzbdl.save()

            return link, papiaccess, pnzbdl

    else:
        logger.error("Did not find indexer with name %s" % indexer_name)
        return None, None, None
def match_tvdb(include_notvdb=False):
    matches = []
    errors = []

    # NOTE: if anything has TVDBs set already but also has tvdb_not_matched_yet,
    #       this is going to behave oddly, especially if include_notvdb.
    shows = (Show.select()
                 .where(Show.is_a_tv_show)
                 .where(~Show.hidden).where(Show.deleted_at >> None)
                 .join(ShowTVDB, JOIN.LEFT_OUTER).where(ShowTVDB.show >> None))
    if not include_notvdb:
        shows = shows.where(Show.tvdb_not_matched_yet)
    shows = shows.order_by(fn.lower(Show.name).asc())

    for show in shows:
        resp = get('/search/series', params={'name': show.name})
        if resp.status_code == 404:
            matches.append((show, []))
        elif not resp.ok:
            errors.append((show, resp))
        else:
            matches.append((show, resp.json()['data']))

    return render_template('match_tvdb.html', matches=matches, errors=errors)
Esempio n. 25
0
 def email_taken(self, email):
     return User.select().where(
         fn.lower(User.email) == email.lower()).exists()
Esempio n. 26
0
 def indexer(self):
     return Indexer.get(fn.lower(Indexer.name) == self.settings.name.lower())
Esempio n. 27
0
def init_indexer_table_entry(indexer_name):
    try:
        Indexer.get(fn.lower(Indexer.name) == indexer_name.lower())
    except Indexer.DoesNotExist as e:
        logger.info("Unable to find indexer with name %s in database. Will add it" % indexer_name)
        Indexer().create(name=indexer_name)
Esempio n. 28
0
 def email_taken(self, email):
     return User.select().where(fn.lower(User.email) == email.lower()).exists()
Esempio n. 29
0
def view(user):
    """ WIP: View user's profile, posts, comments, badges, etc """
    try:
        user = User.get(fn.lower(User.name) == user.lower())
    except User.DoesNotExist:
        abort(404)

    if user.status == 10:
        abort(404)

    modsquery = SubMod.select(
        Sub.name,
        SubMod.power_level).join(Sub).where((SubMod.uid == user.uid)
                                            & (SubMod.invite == False))
    owns = [x.sub.name for x in modsquery if x.power_level == 0]
    mods = [x.sub.name for x in modsquery if 1 <= x.power_level <= 2]
    badges = misc.getUserBadges(user.uid)
    pcount = SubPost.select().where(SubPost.uid == user.uid).count()
    ccount = SubPostComment.select().where(
        SubPostComment.uid == user.uid).count()

    habit = Sub.select(Sub.name,
                       fn.Count(SubPost.pid).alias('count')).join(
                           SubPost,
                           JOIN.LEFT_OUTER,
                           on=(SubPost.sid == Sub.sid))
    habit = habit.where(SubPost.uid == user.uid).group_by(Sub.sid).order_by(
        fn.Count(SubPost.pid).desc()).limit(10)

    level, xp = misc.get_user_level(user.uid)

    if xp > 0:
        currlv = (level**2) * 10
        nextlv = ((level + 1)**2) * 10

        required_xp = nextlv - currlv
        progress = ((xp - currlv) / required_xp) * 100
    else:
        progress = 0

    givenScore = misc.getUserGivenScore(user.uid)

    return engine.get_template('user/profile.html').render({
        'user':
        user,
        'level':
        level,
        'progress':
        progress,
        'postCount':
        pcount,
        'commentCount':
        ccount,
        'givenScore':
        givenScore,
        'badges':
        badges,
        'owns':
        owns,
        'mods':
        mods,
        'habits':
        habit,
        'msgform':
        CreateUserMessageForm()
    })
Esempio n. 30
0
def notify_bot_offline(bot, update, args=None):
    tg_user = update.message.from_user
    user = User.from_telegram_object(tg_user)
    if util.stop_banned(update, user):
        return
    reply_to = util.original_reply_id(update)

    if args:
        text = ' '.join(args)
    else:
        text = update.message.text
        command_no_args = len(re.findall(
            r'^/offline\s*$',
            text)) > 0 or text.lower().strip() == '/offline@botlistbot'
        if command_no_args:
            update.message.reply_text(util.action_hint(
                "Please use this command with an argument. For example:\n/offline @mybot"
            ),
                                      reply_to_message_id=reply_to)
            return

    # `#offline` is already checked by handler
    try:
        username = re.match(settings.REGEX_BOT_IN_TEXT, text).groups()[0]
        if username == '@' + settings.SELF_BOT_NAME:
            log.info("Ignoring {}".format(text))
            return
    except AttributeError:
        if args:
            update.message.reply_text(util.failure(
                "Sorry, but you didn't send me a bot `@username`."),
                                      quote=True,
                                      parse_mode=ParseMode.MARKDOWN,
                                      reply_to_message_id=reply_to)
        else:
            log.info("Ignoring {}".format(text))
            # no bot username, ignore update
            pass
        return

    def already_reported():
        update.message.reply_text(mdformat.none_action(
            "Someone already reported this, thanks anyway 😊"),
                                  reply_to_message_id=reply_to)

    try:
        offline_bot = Bot.get(
            fn.lower(Bot.username)**username.lower(), Bot.approved == True)
        if offline_bot.offline:
            return already_reported()
        if offline_bot.official:
            update.message.reply_text(mdformat.none_action(
                "Official bots usually don't go offline for a long time. "
                "Just wait a couple hours and it will be back up ;)"),
                                      reply_to_message_id=reply_to)
            return

        try:
            Suggestion.get(action="offline",
                           subject=offline_bot,
                           executed=False)
            return already_reported()
        except Suggestion.DoesNotExist:
            suggestion = Suggestion(user=user,
                                    action="offline",
                                    value=True,
                                    date=datetime.date.today(),
                                    subject=offline_bot)
            suggestion.save()

        update.message.reply_text(util.success(
            "Thank you! We will review your suggestion and set the bot offline."
        ),
                                  reply_to_message_id=reply_to)
    except Bot.DoesNotExist:
        update.message.reply_text(
            util.action_hint("The bot you sent me is not in the @BotList."),
            reply_to_message_id=reply_to)
    return ConversationHandler.END
Esempio n. 31
0
def view(user):
    """ WIP: View user's profile, posts, comments, badges, etc """
    try:
        user = User.get(fn.lower(User.name) == user.lower())
    except User.DoesNotExist:
        abort(404)

    if user.status == 10:
        abort(404)

    modsquery = (SubMod.select(
        Sub.name, SubMod.power_level).join(Sub).where((SubMod.uid == user.uid)
                                                      & (~SubMod.invite)))
    owns = [x.sub.name for x in modsquery if x.power_level == 0]
    mods = [x.sub.name for x in modsquery if 1 <= x.power_level <= 2]
    invitecodeinfo = misc.getInviteCodeInfo(user.uid)
    badges = badges_module.badges_for_user(user.uid)
    pcount = SubPost.select().where(SubPost.uid == user.uid).count()
    ccount = SubPostComment.select().where(
        SubPostComment.uid == user.uid).count()
    user_is_admin = misc.is_target_user_admin(user.uid)
    habit = Sub.select(Sub.name,
                       fn.Count(SubPost.pid).alias("count")).join(
                           SubPost,
                           JOIN.LEFT_OUTER,
                           on=(SubPost.sid == Sub.sid))
    habit = (habit.where(SubPost.uid == user.uid).group_by(Sub.sid).order_by(
        fn.Count(SubPost.pid).desc()).limit(10))

    level, xp = misc.get_user_level(user.uid)

    if xp > 0:
        currlv = (level**2) * 10
        nextlv = ((level + 1)**2) * 10

        required_xp = nextlv - currlv
        progress = ((xp - currlv) / required_xp) * 100
    else:
        progress = 0

    givenScore = misc.getUserGivenScore(user.uid)

    return engine.get_template("user/profile.html").render({
        "user":
        user,
        "level":
        level,
        "progress":
        progress,
        "postCount":
        pcount,
        "commentCount":
        ccount,
        "givenScore":
        givenScore,
        "invitecodeinfo":
        invitecodeinfo,
        "badges":
        badges,
        "owns":
        owns,
        "mods":
        mods,
        "habits":
        habit,
        "target_user_is_admin":
        user_is_admin,
        "msgform":
        CreateUserMessageForm(),
    })
Esempio n. 32
0
 def indexer(self):
     if self.indexerDb is None:
         self.indexerDb = Indexer.get(
             fn.lower(Indexer.name) == self.settings.name.lower())
     return self.indexerDb
Esempio n. 33
0
 def order(self):
     return fn.lower(Tarefa.prioridade)
Esempio n. 34
0
 def order(self):
     return fn.lower(Alocacao.inicio)
Esempio n. 35
0
def set_tip_list(message, users_to_tip, request_json):
    import modules.db as db
    """
    Loop through the message starting after the tip amount and identify any users that were tagged for a tip.  Add the
    user object to the users_to_tip dict to process the tips.
    """
    logging.info("{}: in set_tip_list.".format(datetime.datetime.utcnow()))

    # Identify the first user to string multi tips.  Once a non-user is mentioned, end the user list

    first_user_flag = False

    logging.info("trying to set tiplist in telegram: {}".format(message))

    if 'reply_to_message' in request_json['message']:
        if len(users_to_tip) == 0:
            try:
                user = db.TelegramChatMember.select().where(
                    (db.TelegramChatMember.chat_id == int(message['chat_id']))
                    & (db.TelegramChatMember.member_id ==
                       int(request_json['message']['reply_to_message']['from']
                           ['id']))).get()
                receiver_id = user.member_id
                receiver_screen_name = user.member_name

                user_dict = {
                    'receiver_id': receiver_id,
                    'receiver_screen_name': receiver_screen_name,
                    'receiver_account': None,
                    'receiver_register': None
                }
                users_to_tip.append(user_dict)
            except db.TelegramChatMember.DoesNotExist:
                logging.info(
                    "User not found in DB: chat ID:{} - member name:{}".format(
                        message['chat_id'], request_json['message']
                        ['reply_to_message']['from']['first_name']))
                missing_user_message = (
                    "Couldn't send tip. In order to tip {}, they need to have sent at least "
                    "one message in the group.".format(
                        request_json['message']['reply_to_message']['from']
                        ['first_name']))
                send_reply(message, missing_user_message)
                users_to_tip.clear()
                return message, users_to_tip
    else:
        for item in message['text'].split():
            if str(item).startswith("@") and str(item).lower() != str(
                    message['sender_screen_name']).lower():
                try:
                    user = db.TelegramChatMember.select().where(
                        (db.TelegramChatMember.chat_id == int(
                            message['chat_id']))
                        & (fn.lower(db.TelegramChatMember.member_name) ==
                           item[1:].lower())).get()
                    receiver_id = user.member_id
                    receiver_screen_name = user.member_name
                    duplicate_user = False

                    for u_index in range(0, len(users_to_tip)):
                        if users_to_tip[u_index]['receiver_id'] == receiver_id:
                            duplicate_user = True

                    if not duplicate_user:
                        if not first_user_flag:
                            first_user_flag = True
                        logging.info(
                            "User tipped via searching the string for mentions"
                        )
                        user_dict = {
                            'receiver_id': receiver_id,
                            'receiver_screen_name': receiver_screen_name,
                            'receiver_account': None,
                            'receiver_register': None
                        }
                        users_to_tip.append(user_dict)
                except db.TelegramChatMember.DoesNotExist:
                    logging.info(
                        "User not found in DB: chat ID:{} - member name:{}".
                        format(message['chat_id'], item[1:]))
                    missing_user_message = (
                        "Couldn't send tip. In order to tip {}, they need to have sent at least "
                        "one message in the group.".format(item))
                    send_reply(message, missing_user_message)
                    users_to_tip.clear()
                    return message, users_to_tip
        try:
            text_mentions = request_json['message']['entities']
            for mention in text_mentions:
                if mention['type'] == 'text_mention':
                    try:
                        user = db.TelegramChatMember.select().where(
                            (db.TelegramChatMember.chat_id == int(
                                message['chat_id']))
                            & (db.TelegramChatMember.member_id == int(
                                mention['user']['id']))).get()
                        receiver_id = user.member_id
                        receiver_screen_name = user.member_name
                        logging.info("telegram user added via mention list.")
                        logging.info("mention: {}".format(mention))

                        user_dict = {
                            'receiver_id': receiver_id,
                            'receiver_screen_name': receiver_screen_name,
                            'receiver_account': None,
                            'receiver_register': None
                        }
                        users_to_tip.append(user_dict)
                    except db.TelegramChatMember.DoesNotExist:
                        logging.info(
                            "User not found in DB: chat ID:{} - member name:{}"
                            .format(message['chat_id'],
                                    mention['user']['first_name']))
                        missing_user_message = (
                            "Couldn't send tip. In order to tip {}, they need to have sent at least "
                            "one message in the group.".format(item))
                        send_reply(message, missing_user_message)
                        users_to_tip.clear()
                        return message, users_to_tip
        except:
            pass

    logging.info("{}: Users_to_tip: {}".format(datetime.datetime.utcnow(),
                                               users_to_tip))
    message['total_tip_amount'] = message['tip_amount']
    if len(users_to_tip) > 0 and message['tip_amount'] != -1:
        message['total_tip_amount'] *= len(users_to_tip)

    return message, users_to_tip
Esempio n. 36
0
def view(user):
    """ WIP: View user's profile, posts, comments, badges, etc """
    try:
        user = User.get(fn.lower(User.name) == user.lower())
    except User.DoesNotExist:
        abort(404)

    if user.status == 10 and not current_user.is_admin():
        return view_deleted_user(user)

    modsquery = (SubMod.select(
        Sub.name, SubMod.power_level).join(Sub).where((SubMod.uid == user.uid)
                                                      & (~SubMod.invite)))
    owns = [x.sub.name for x in modsquery if x.power_level == 0]
    mods = [x.sub.name for x in modsquery if 1 <= x.power_level <= 2]
    invitecodeinfo = misc.getInviteCodeInfo(user.uid)
    badges = badges_module.badges_for_user(user.uid)
    pcount = SubPost.select().where(SubPost.uid == user.uid).count()
    ccount = SubPostComment.select().where(
        SubPostComment.uid == user.uid).count()
    user_is_admin = misc.is_target_user_admin(user.uid)
    habit = Sub.select(Sub.name,
                       fn.Count(SubPost.pid).alias("count")).join(
                           SubPost,
                           JOIN.LEFT_OUTER,
                           on=(SubPost.sid == Sub.sid))
    habit = (habit.where(SubPost.uid == user.uid).group_by(Sub.sid).order_by(
        fn.Count(SubPost.pid).desc()).limit(10))

    level, xp = misc.get_user_level(user.uid)

    if xp > 0:
        currlv = (level**2) * 10
        nextlv = ((level + 1)**2) * 10

        required_xp = nextlv - currlv
        progress = ((xp - currlv) / required_xp) * 100
    else:
        progress = 0

    givenScore = misc.getUserGivenScore(user.uid)

    messages = content = "show"
    if (current_user.uid != user.uid and not user_is_admin
            and not current_user.can_admin):
        blocked = (User.select(
            UserMessageBlock.id.is_null(False).alias("hide_messages"),
            UserContentBlock.method,
        ).join(
            UserMessageBlock,
            JOIN.LEFT_OUTER,
            on=((UserMessageBlock.uid == current_user.uid)
                & (UserMessageBlock.target == user.uid)),
        ).join(
            UserContentBlock,
            JOIN.LEFT_OUTER,
            on=((UserContentBlock.uid == current_user.uid)
                & (UserContentBlock.target == user.uid)),
        ).dicts().get())

        if blocked["hide_messages"]:
            messages = "hide"
        else:
            messages = "show"
        if blocked["method"] is None:
            content = "show"
        elif blocked["method"] == UserContentBlockMethod.BLUR:
            content = "blur"
        else:
            content = "hide"
    ignform = EditIgnoreForm(view_messages=messages, view_content=content)

    return engine.get_template("user/profile.html").render({
        "user":
        user,
        "level":
        level,
        "progress":
        progress,
        "postCount":
        pcount,
        "commentCount":
        ccount,
        "givenScore":
        givenScore,
        "invitecodeinfo":
        invitecodeinfo,
        "badges":
        badges,
        "owns":
        owns,
        "mods":
        mods,
        "habits":
        habit,
        "target_user_is_admin":
        user_is_admin,
        "msgform":
        CreateUserMessageForm(),
        "ignform":
        ignform,
    })
Esempio n. 37
0
 def indexer(self):
     if self.indexerDb is None:
         self.indexerDb = Indexer.get(fn.lower(Indexer.name) == self.settings.name.lower())
     return self.indexerDb
Esempio n. 38
0
 def indexer(self):
     return Indexer.get(fn.lower(Indexer.name) == self.settings.name.lower())