Exemplo n.º 1
0
    async def show_polls(self, ctx, *, title=None):
        async def query_getter(user):
            query = Poll.join('users', 'polls.creator_id', '=', 'users.id') \
                .where('users.guild_id', user.guild.id)

            if title:
                query = query.where('polls.title', 'like', f'%{title}%')

            if not ut.is_admin(user):
                query = query.where('users.id', user.id)

            return query

        if title:
            desc = f"Showing results for '{title}' "
            if ut.is_admin(ctx.author):
                desc += " in all polls"
            else:
                desc += " in your polls"
        else:
            desc = ("Showing all polls" if ut.is_admin(ctx.author) else
                    "Showing all of your polls")

        result = await self.display_poll_search(query_getter,
                                                ctx.author,
                                                ctx.channel,
                                                desc=desc)

        if result:
            await ctx.message.delete()
Exemplo n.º 2
0
    def delete(self, transaction_id):
        '''
        Endpoint for deleting a transaction

        Deletes the given Transaction and updates the associated User record's
        balance
        '''
        parser = reqparse.RequestParser()
        parser.add_argument('Credits-Token',
                            location='headers',
                            required=True,
                            type=netid_from_token,
                            dest='admin_netid')
        args = parser.parse_args()

        # Require an admin session token to delete transactions
        if not is_admin(args.admin_netid):
            return send_error("Must be admin to delete transaction", 403)

        transaction = Transaction.query.filter_by(id=transaction_id).first()
        if transaction:
            transaction.user.balance -= transaction.amount
            db.session.add(transaction.user)
            db.session.delete(transaction)
            db.session.commit()
            return send_success("Deleted transaction: %s" % transaction_id)
        else:
            return send_error("Unknown transaction")
Exemplo n.º 3
0
 async def del_poll(self, message):
     args = message.content.split()[1:]
     poll_id = await self.get_poll_index(message, args)
     if poll_id is not None:
         poll = self.polls[poll_id]
         if poll.dead:
             await self.send_message(message.channel,
                                     "I have already deleted that poll.")
             return False
         if not (poll.author == message.author or is_admin(message.author)):
             await self.send_message(message.channel,
                                     "That's not your poll :exclamation:")
             return False
         await self.edit_message(
             poll.poll_message, poll.poll_message.content +
             "\n[This poll's results were deleted and you can no longer vote officially in it.]"
         )
         del self.polls_by_msgid[poll.poll_message.id]
         poll.kill()
         await self.send_message(message.channel,
                                 "I took care of that poll. :bread:")
         while self.polls and self.polls[-1].dead:
             self.polls.pop()
         self.polls_changed = True
         return True
Exemplo n.º 4
0
    def recover_from_dmd(self, path, tmp_path, when=None):
        '''Perform a dar_manager recovery'''
        if isinstance(path, list):
            path = " ".join(path)

        args = {'dar_manager': self.cf.dar_manager_bin, 'dmd_file': self.dmd,
                'path': path, 'tmp_path': tmp_path}
        tpl = "%(dar_manager)s -B %(dmd_file)s "

        tpl += ' -e "-Q -w -R %(tmp_path)s '
        if self.cf.encryption:
            command_file = mk_dar_crypt_file(self.cf.encryption)
            self.logger.debug('Creating encryption command file %s' %
                              command_file)
            tpl += '-B %s ' % command_file

        if not is_admin():
            tpl += ' --comparison-field=ignore-owner '

        #Close the -e quote.
        tpl += ' " '

        if when:
            tpl += "-w %(when)s "
            args['when'] = when

        tpl += "-Q -r %(path)s "

        self.logger.debug(tpl)
        rval = self.run_command(tpl, args)
        if self.cf.encryption and os.path.exists(command_file):
            self.logger.debug('Deleting encryption command file %s' %
                              command_file)
            os.unlink(command_file)
        return rval
Exemplo n.º 5
0
def customcmd(cog, server_id):
    is_admin = utils.is_admin(server_id)
    owner = utils.session["user"]["id"]
    customcmd_content = db.hgetall("{}:Customcmd:content".format(server_id))
    customcmd_brief = db.hgetall("{}:Customcmd:brief".format(server_id))
    customcmd_owner = db.hgetall("{}:Customcmd:owner".format(server_id))
    current_use = db.hget("{}:Customcmd:owner_use".format(server_id),owner) or 0
    use = max_use(server_id)
    content = {}
    brief = {}

    if customcmd_content:
        customcmd_content = dict([x,str(y.encode()).replace("\\\\","\\")] for x,y in customcmd_content.items()) #a way to fix escape term. terrible yeh

    if is_admin: #if someone is admin, they can view all
        log.info("It is admin person")
        member = db.hgetall("Info:Name")
        content = customcmd_content
        brief = customcmd_brief
        owner = {}
        for name,_id in customcmd_owner.items():
            owner[name] = member.get(_id,"UNKNOWN") #getting member name WHILE checking left member
    else:
        log.info("Not admin person")
        for cmd in customcmd_content:#running check each commands to filter out to owner only
            if customcmd_owner[cmd] == owner:
                content[cmd] = customcmd_content[cmd]
                brief[cmd] = customcmd_brief[cmd]
        owner = "none"
    return render_template("customcmd.html", data_customcmd=content,data_brief = brief,
                           server_id=server_id,max_use = use,current =  current_use,cmd_owner = owner, cog = "customcmd")
Exemplo n.º 6
0
 def GET(self, targetuid, key):
     uid = check_headers()
     if utils.is_admin(uid):
         utils.delete_user_attribute(targetuid, key)
         return result_ok()
     else:
         return result_nok()
Exemplo n.º 7
0
def config():
    if not is_admin():
        return redirect(url_for("bp_main.home"))

    pcfg = {"title": "Application Config"}

    _config = Config.query.one()
    if not _config:
        flash("Config not found", "error")
        return redirect(url_for("bp_main.home"))

    form = ConfigForm(request.form, obj=_config)

    if form.validate_on_submit():
        _config.clublog_api_key = form.clublog_api_key.data
        _config.eqsl_download_url = form.eqsl_download_url.data
        _config.eqsl_rcvd_mark = form.eqsl_rcvd_mark.data
        _config.eqsl_upload_url = form.eqsl_upload_url.data
        _config.lotw_download_url = form.lotw_download_url.data
        _config.lotw_upload_url = form.lotw_upload_url.data
        _config.lotw_login_url = form.lotw_login_url.data
        _config.lotw_rcvd_mark = form.lotw_rcvd_mark.data

        db.session.commit()
        flash("Configuration updated", "info")
        return redirect(url_for("bp_admin.config"))

    return render_template("admin/config.jinja2", pcfg=pcfg, form=form)
Exemplo n.º 8
0
 def wrapper(update, context):
     if not is_admin(update.effective_message.reply_to_message.from_user.id,
                     update.effective_chat.id, context.bot):
         return func(update, context)
     update.effective_message.reply_text(
         strings.get(strings.cannot_perform_on_admin,
                     update.effective_chat))
Exemplo n.º 9
0
def customcmd(cog, server_id):
    is_admin = utils.is_admin(server_id)
    owner = utils.session["user"]["id"]
    customcmd_content = db.hgetall("{}:Customcmd:content".format(server_id))
    customcmd_brief = db.hgetall("{}:Customcmd:brief".format(server_id))
    customcmd_owner = db.hgetall("{}:Customcmd:owner".format(server_id))
    current_use = db.hget("{}:Customcmd:owner_use".format(server_id),owner) or 0
    use = max_use(server_id)
    content = {}
    brief = {}

    if customcmd_content:
        customcmd_content = dict([x,str(y.encode()).replace("\\\\","\\")] for x,y in customcmd_content.items()) #a way to fix escape term. terrible yeh

    if is_admin or utils.is_owner(): #if someone is admin, they can view all
        log.info("It is admin person")
        member = db.hgetall("Info:Name")
        content = customcmd_content
        brief = customcmd_brief
        owner = {}
        for name,_id in customcmd_owner.items():
            owner[name] = member.get(_id,"UNKNOWN") #getting member name WHILE checking left member
    else:
        log.info("Not admin person")
        for cmd in customcmd_content:#running check each commands to filter out to owner only
            if customcmd_owner[cmd] == owner:
                content[cmd] = customcmd_content[cmd]
                brief[cmd] = customcmd_brief[cmd]
        owner = "none"
    return render_template("customcmd.html", data_customcmd=content,data_brief = brief,
                           server_id=server_id,max_use = use,current =  current_use,cmd_owner = owner, cog = "customcmd")
Exemplo n.º 10
0
 def predicate(ctx):
     if not ctx.guild:
         return True
     if utils.is_admin(ctx):
         return True
     else:
         raise NoUserPermissionError
Exemplo n.º 11
0
def list_log():
    if not is_admin(request):
        abort(403)
    logdir = request.form.get("logdir")
    if logdir:
        logdir = admin_list_log(logdir)
        return str(logdir)
    return ''
Exemplo n.º 12
0
def view_log():
    if not is_admin(request):
        abort(403)
    logfile = request.form.get("logfile")
    if logfile:
        logcontent = admin_view_log(logfile)
        return logcontent
    return ''
Exemplo n.º 13
0
 async def check_for_duplicate_by_name(ctx, template):
     dup = sql.template_get_by_name(ctx.guild.id, template.name)
     if dup:
         if template.owner_id != ctx.author.id and not utils.is_admin(ctx):
             await ctx.send(ctx.s("template.err.name_exists"))
             return False
         print(dup.x)
         q = ctx.s("template.name_exists_ask_replace") \
             .format(dup.name, canvases.pretty_print[dup.canvas], dup.x, dup.y)
         return await utils.yes_no(ctx, q)
Exemplo n.º 14
0
	def post(self):
		self.response.headers['Content-Type'] = 'application/json'

		try:
			int(self.request.get('user_id'))
		except:
			self.response.write(json.dumps({"status": "NOT OK", "message": "Valid user_id must be supplied."}))
			return

		room_exists = True

		roomlist_name = self.request.get('roomlist_name',utils.DEFAULT_ROOMLIST_NAME)
		room_id = self.request.get('room_id')
		if not room_id:
			room_exists = False
		else:
			try:
				room = models.Room.get_by_id(int(room_id),parent=utils.roomlist_key(roomlist_name))
				if room == None:
					room_exists = False
			except:
				room_exists = False

		if room_exists:
			if not utils.is_admin(room,self.request.get('user_id')):
				self.response.write(json.dumps({"status": "NOT OK", "message": "You must be an admin to reorder songs."}))
				return

		if not room_exists:
			self.response.write(json.dumps({"status": "NOT OK", "message": "The requested room was not found."}))
		else:
			if room.mode != 0:
				self.response.write(json.dumps({"status": "NOT OK", "message": "You can only reorder songs in First Come First Serve mode."}))
			else:
				allowed = utils.checkPassword(self.request.get('password', ''), room.password)
				if not allowed:
					self.response.write(json.dumps({"status": "NOT OK", "message": "The correct password was not provided."}))
				else:
					#TODO: Error checking
					song_exists = True
					try:
						song_id = int(self.request.get('song_id'))
					except:
						song_exists = False
					if not song_exists or room.queue.count(song_id) == 0:
						self.response.write(json.dumps({"status": "NOT OK", "message": "The requested song is not in the Room's queue."}))
					else:
						try:
							new_pos = int(self.request.get('new_pos'))
						except: # originally a else, getting a syntax error
							new_pos = 0
						room.queue.remove(song_id)
						room.queue.insert(new_pos,song_id)
						room.put()
						self.response.write(json.dumps({"status":"OK"}))
Exemplo n.º 15
0
 async def template_remove(self, ctx, name):
     t = sql.template_get_by_name(ctx.guild.id, name)
     if not t:
         raise TemplateNotFoundError
     log.info("(T:{})".format(t.name, t.gid))
     if t.owner_id != ctx.author.id and not utils.is_template_admin(
             ctx) and not utils.is_admin(ctx):
         await ctx.send(ctx.s("template.err.not_owner"))
         return
     sql.template_delete(t.gid, t.name)
     await ctx.send(ctx.s("template.remove").format(name))
Exemplo n.º 16
0
 async def template_remove(self, ctx, name):
     t = ctx.session.query(TemplateDb).filter_by(guild_id=ctx.guild.id,
                                                 name=name).first()
     if not t:
         raise TemplateNotFoundError(ctx, ctx.guild.id, name)
     if t.owner != ctx.author.id and not utils.is_template_admin(
             ctx) and not utils.is_admin(ctx):
         await ctx.send(ctx.s("template.err.not_owner"))
         return
     ctx.session.delete(t)
     await ctx.send(ctx.s("template.remove").format(name))
Exemplo n.º 17
0
        async def query_getter(user):
            query = Poll.join('users', 'polls.creator_id', '=', 'users.id') \
                .where('users.guild_id', user.guild.id)

            if title:
                query = query.where('polls.title', 'like', f'%{title}%')

            if not ut.is_admin(user):
                query = query.where('users.id', user.id)

            return query
Exemplo n.º 18
0
def logs_delete(log_id):
    if not is_admin():
        _datas = {"status": "error", "id": log_id}
    else:
        log = Logging.query.filter(Logging.id == log_id).first()
        if not log:
            _datas = {"status": "error", "id": log_id}
        else:
            db.session.delete(log)
            db.session.commit()
            _datas = {"status": "deleted", "id": log_id}
    return Response(json.dumps(_datas), mimetype="application/json;charset=utf-8")
Exemplo n.º 19
0
    async def snapshot_remove(self, ctx, base_template, snapshot_template):
        if not utils.is_template_admin(ctx) and not utils.is_admin(ctx):
            return await ctx.send(ctx.s("template.err.not_owner"))

        snap = ctx.session.query(Snapshot).filter(
            Snapshot.base_template.has(name=base_template),
            Snapshot.target_template.has(name=snapshot_template)).first()

        if not snap:
            return await ctx.send("That snapshot does not exist.")

        ctx.session.delete(snap)
        await ctx.send("Snapshot removed!")
Exemplo n.º 20
0
    async def template_snapshot_remove(self, ctx, base_template,
                                       snapshot_template):
        if not utils.is_template_admin(ctx) and not utils.is_admin(ctx):
            await ctx.send(ctx.s("template.err.not_owner"))
            return

        s = sql.snapshot_get_by_names(ctx.guild.id, base_template,
                                      snapshot_template)
        if s is None:
            await ctx.send("That snapshot does not exist.")
            return

        sql.snapshot_delete(ctx.guild.id, base_template, snapshot_template)
        await ctx.send("Snapshot removed!")
Exemplo n.º 21
0
def get_logs_handler(update, context):
    chat = utils.get_chat(context, update)
    chat_id = chat.effective_chat.id
    bot = utils.get_bot(context, update)
    logger.info(f'get_logs_handler -> {chat_id}')
    if utils.is_admin(chat_id):
        try:
            f = open('deliver_bot.log', 'rb')
            bot.send_document(
                chat_id=chat_id,
                document=f
            )
        except Exception as ex:
            logger.warning(f'{ex}')
Exemplo n.º 22
0
    async def user_end_poll(self, poll, message, user: discord.User):
        # Only the creator of the poll can end the poll
        if poll.creator_id != user.id and not ut.is_admin(user):
            return

        result, reason = await ut.get_confirmation(
            message.channel, user, self.bot,
            "Are you sure you want to end the poll now?")

        # Brings forward the end date for the poll to current time
        #
        # The poll will end the poll on its next iteration
        if result:
            poll.end_date = ut.get_utc_time()
            poll.save()
Exemplo n.º 23
0
def get_db_handler(update, context):
    chat = utils.get_chat(context, update)
    chat_id = chat.effective_chat.id
    bot = utils.get_bot(context, update)
    logger.info(f'get_db_handler -> {chat_id}')
    if utils.is_admin(chat_id):
        try:
            f_path = os.path.join(os.path.dirname(__file__), 'admin/db.sqlite')
            f = open(f_path, 'rb')
            bot.send_document(
                chat_id=chat_id,
                document=f
            )
        except Exception:
            pass
Exemplo n.º 24
0
 async def reread_votes(self, message):
     args = message.content.split()[1:]
     poll_id = await self.get_poll_index(message, args)
     if poll_id is not None:
         poll = self.polls[poll_id]
         if not (poll.author == message.author or is_admin(message.author)):
             await self.send_message(message.channel,
                                     "That's not your poll :exclamation:")
             return False
         for v in poll.votes:
             v.clear()
         for reaction in poll.poll_message.reactions:
             user_list = await self.get_reaction_users(reaction, limit=100)
             for user in user_list:
                 await handle_reaction_addition(self, reaction, user)
         await self.send_message(message.channel, "Done rereading :)")
         return True
Exemplo n.º 25
0
    async def user_delete_poll(self, poll, message, user: discord.User):
        # Only the creator of the poll or admins can delete it
        if poll.creator_id != user.id and not ut.is_admin(user):
            return

        # Awaits confirmation of the deletion
        result, reason = await ut.get_confirmation(
            message.channel, user, self.bot,
            "Are you sure you want to delete the poll? "
            "The poll will be deleted from the conversation.\n"
            "You can use the `summonpoll` command to bring the poll back")

        if result:
            # The message containing the poll is deleted
            await message.delete()

        return result
Exemplo n.º 26
0
def get_report_handler(update, context):
    chat = utils.get_chat(context, update)
    chat_id = chat.effective_chat.id
    bot = utils.get_bot(context, update)
    logger.info(f'get_report_handler -> {chat_id}')

    db.export_orders_to_file()

    if utils.is_admin(chat_id):
        try:
            f = open('orders.csv', 'rb')
            bot.send_document(
                chat_id=chat_id,
                document=f
            )
        except Exception as ex:
            logger.warning(f'{ex}')
            pass
Exemplo n.º 27
0
    async def snapshot_add(self, ctx, base_template, snapshot_template):
        if not utils.is_template_admin(ctx) and not utils.is_admin(ctx):
            await ctx.send(ctx.s("template.err.not_owner"))
            return

        base = ctx.session.query(TemplateDb).filter_by(
            guild_id=ctx.guild.id, name=base_template).first()
        target = ctx.session.query(TemplateDb).filter_by(
            guild_id=ctx.guild.id, name=snapshot_template).first()

        if base is None:
            return await ctx.send("The base template does not exist.")
        if target is None:
            return await ctx.send("The snapshot template does not exist.")

        snap = Snapshot(base_template=base, target_template=target)
        ctx.session.add(snap)
        await ctx.send("Snapshot added!")
Exemplo n.º 28
0
    async def template_snapshot_add(self, ctx, base_template,
                                    snapshot_template):
        if not utils.is_template_admin(ctx) and not utils.is_admin(ctx):
            await ctx.send(ctx.s("template.err.not_owner"))
            return

        base = sql.template_get_by_name(ctx.guild.id, base_template)
        target = sql.template_get_by_name(ctx.guild.id, snapshot_template)

        if base == None:
            await ctx.send("The base template does not exist.")
            return
        if target == None:
            await ctx.send("The snapshot template does not exist.")
            return

        sql.snapshot_add(ctx.guild.id, base_template, snapshot_template)
        await ctx.send("Snapshot added!")
Exemplo n.º 29
0
def reply_all_handler(update, context):
    if utils.is_admin(update.message.chat_id):
        logger.info(f'reply_all_handler -> text: {update.message.text}')
        users = db.get_all_users()
        for user in users:
            try:
                logger.info(f'reply_all_handler -> {user}')
                context.bot.send_message(
                    chat_id=user.user_id,
                    text=update.message.text_markdown.replace(
                        f'/replyall', ''),
                    parse_mode=ParseMode.MARKDOWN,
                    disable_web_page_preview=True
                )
            except Exception as ex:
                logger.warning(f'{ex}')
                logger.warning(f'reply_all_handler -> {ex}')
                pass
Exemplo n.º 30
0
    async def on_message(self, message):
        """
        don't touch this! keep it abstract
        """

        # we don't want interaction in any other channels
        if message.channel.id != self.secret_channel.id:
            return

        # quick content reference
        content = message.content

        # we also want to skip anything that doesn't start with the prefix
        if not content.startswith("!"):
            return

        # strip prefix
        content = content[1:]

        # get base command
        base_command = content.split(" ")

        # the function to call
        cmd_funct = None

        # parse base commands (not mapped)
        if content == 'commands':
            await self.commands(message)
        elif content == 'rules':
            await self.rules(message)
        elif content == 'devme':
            await self.devme(message)
        elif base_command[0] in commands_map:
            # user commands
            cmd_funct = self._get_command_function(commands_map, base_command)
        elif base_command[0] in dev_commands_map and utils.is_dev(message.author):
            # dev commands
            cmd_funct = self._get_command_function(dev_commands_map, base_command)
        elif base_command[0] in admin_commands_map and utils.is_admin(message.author):
            # admin commands
            cmd_funct = self._get_command_function(admin_commands_map, base_command)

        if cmd_funct is not None:
            await cmd_funct(message)
Exemplo n.º 31
0
    async def summon_poll(self, ctx, poll_id: int):
        """
        Allows a user to bring forward a poll in the conversation,
        for the benefit of longer-duration polls
        """

        poll = Poll.find(poll_id)
        if not poll:
            await ctx.send(f"Poll with ID {poll_id} could not found.")
            return

        if ctx.author.id != poll.creator_id and not ut.is_admin(ctx.author):
            await ctx.send("You don't have permission to summon that poll!")
            return

        old_channel = self.bot.get_channel(poll.channel_id)

        try:
            old_message = await old_channel.fetch_message(poll.message_id)
            await old_message.delete()
        except discord.errors.NotFound:
            pass

        embed = await self.create_poll_embed(poll.title, poll.end_date,
                                             poll.ended)
        new_message = await ctx.send(embed=embed)

        if not poll.ended:
            await new_message.add_reaction(ADD_CHOICE_EMOJI)

        await new_message.add_reaction(DELETE_POLL_EMOJI)

        if not poll.ended:
            await new_message.add_reaction(END_POLL_EMOJI)
            for choice in poll.choices:
                await new_message.add_reaction(choice.reaction)

        await ctx.message.delete()

        poll.message_id = new_message.id
        poll.channel_id = ctx.channel.id
        poll.save()

        await self.update_response_counts(poll)
Exemplo n.º 32
0
async def new_account(ctx, user: discord.Member = None):
    """
    Create an account for a new account
    """
    if user is None:
        user_id = ctx.author.id
    elif utils.is_admin(ctx):
        user_id = user.id
    else:
        res = "Erreur : vous ne pouvez pas créer un compte pour une autre personne."
        log_info(res)
        await ctx.send(res)
        return

    if bank.new_account(user_id):
        res = "<@{}> a maintenant un compte en banque.".format(user_id)
    else:
        res = "Erreur : <@{}> a déjà un compte en banque.".format(user_id)

    log_info(res)
    await ctx.send(res)
Exemplo n.º 33
0
 async def stop_poll(self, message):
     args = message.content.split()[1:]
     poll_id = await self.get_poll_index(message, args)
     if poll_id is not None:
         poll = self.polls[poll_id]
         if not poll.active:
             await self.send_message(
                 message.channel, "I have already deactivated that poll.")
             return False
         if not (poll.author == message.author or is_admin(message.author)):
             await self.send_message(message.channel,
                                     "That's not your poll :exclamation:")
             return False
         await self.edit_message(
             poll.poll_message,
             poll.poll_message.content + "\n[This poll has ended.]")
         poll.deactivate()
         await self.send_message(message.channel,
                                 "I deactivated that poll. :bulb:")
         self.polls_changed = True
         return True
Exemplo n.º 34
0
def config():
    if not is_admin():
        return redirect(url_for("bp_main.home"))

    pcfg = {"title": gettext("Application Config")}

    _config = Config.query.one()
    if not _config:
        flash(gettext("Config not found"), "error")
        return redirect(url_for("bp_main.home"))

    form = ConfigForm(request.form, obj=_config)

    if form.validate_on_submit():
        _config.app_name = form.app_name.data
        _config.app_description = form.app_description.data

        db.session.commit()
        flash(gettext("Configuration updated"), "info")
        return redirect(url_for("bp_admin.config"))

    return render_template("admin/config.jinja2", pcfg=pcfg, form=form)
Exemplo n.º 35
0
        q = self.sess.query(Catalog)

        if not catalog:
            last = q.filter(and_(Catalog.clean,
                                 Catalog.job == self.Job,
                                 Catalog.type == self.Full
                                 )).order_by(Catalog.date.desc()).first()
            childs = getchilds(last)
        else:
            try:
                last = q.filter_by(id=catalog).one()
                childs = getancestors(last)
            except NoResultFound, e:
                raise RecoverError("% s is not a valid jobid." % catalog)

        if not is_admin():
            tpl += "-O ignore-owner "

        if self.cf.encryption:
            command_file = mk_dar_crypt_file(self.cf.encryption)
            self.logger.debug('Creating encryption command file %s' %
                              command_file)
            tpl += '-B %s ' % command_file

        args = {'dar_bin': self.cf.dar_bin, 'recover_path': rpath}

        #If catalog was given, we need to sort the list.
        all_archives = sorted([last] + childs, key=lambda x: x.date)
        self.logger.debug("Restoring from: %s" % all_archives)
        _err = False
        for arch in all_archives:
Exemplo n.º 36
0
def levels(server_id):
    is_admin = utils.is_admin(server_id)
    css_theme  = "css/custom/{}.css".format(server_id) if os.path.isfile("static/css/custom/{}.css".format(server_id)) else None
    print(css_theme)
    is_private=False
    if db.get("{}:Level:Private".format(server_id)) == "on":
        is_private=True
    #Check if server and plugins are in
    server_check = db.hget("Info:Server",server_id)
    if server_check is None:
        return redirect(url_for('index'))
    plugin_check = db.hget("{}:Config:Cogs".format(server_id),"level")
    if plugin_check is None:
        return redirect(url_for('index'))

    log.info("Pass all requirement check")

    server = {
        'id':server_id,
        'name':server_check,
        'icon':db.hget("Info:Server_Icon",server_id)}

    #Players' level
    name_list = db.hgetall("Info:Name")
    avatar_list = db.hgetall("Info:Icon")
    total_member = len(db.smembers("{}:Level:Player".format(server_id)))
    player_data = db.sort("{}:Level:Player".format(server_id), by="{}:Level:Player:*->Total_XP".format(server_id), get=[
                                                                                                          "{}:Level:Player:*->ID".format(server_id),
                                                                                                          "{}:Level:Player:*->Total_XP".format(server_id),], start=0, num=total_member, desc=True)
    data = []
    total_exp = 0
    for x in range(0,len(player_data),2):

            if name_list.get(player_data[x]) is None:
                db.srem("{}:Level:Player".format(server_id),player_data[x])
            if player_data[x] is None: continue
            # print(player_data[x],player_data[x+1]) #for future references
            total_exp += int(player_data[x+1])
            level, remain,next_xp= next_Level(int(player_data[x+1]))
            name = name_list.get(player_data[x],"None#1234").split("#")
            temp = {
                "Name":name[0],
                "ID":player_data[x],
                "Level":level,
                "XP": remain,
                "Next_XP":next_xp,
                "Total_XP":player_data[x+1],
                "Discriminator":name[1],
                "Avatar":avatar_list.get(player_data[x]),
                "XP_Percent":100*(float(remain)/float(next_xp))
            }
            data.append(temp)
    log.info("Done gather player infos")
    #Role rewards
    get_role = utils.resource_get("/guilds/{}".format(server_id))
    guild_roles = get_role['roles']
    role_level = db.hgetall("{}:Level:role_reward".format(server_id)) or {}
    reward_roles = [
        {"name":x['name'],
         "id":x['id'],
         "color":hex(x["color"]).split("0x")[1],
         "level":role_level.get(x["id"],0)} for x in guild_roles if role_level.get(x["id"],"0") != "0" and x["id"] != str(server_id)]
    reward_roles.sort(key=lambda x: x['name'])
    print(reward_roles)
    #Those are for Website
    stats = {"total_member":total_member,"total_exp":total_exp}

    if request.args.get('json'):
        log.info("Requesting Json")
        return jsonify({"server:":server,"reward_roles":reward_roles,"players":data})

    return render_template('level/levels.html', players=data, stats = stats, reward_roles = reward_roles,server=server, title="{} leaderboard".format(server['name']),is_admin=is_admin,is_private=is_private,css_theme = css_theme)
Exemplo n.º 37
0
	def GET(self):
		if utils.is_admin():
			raise web.seeother('/')

		return render.admin.login(None)
Exemplo n.º 38
0
 def GET(self):
     uid = check_headers()
     if utils.is_admin(uid):
         return utils.get_users_with_notifications()
     else:
         return result_nok()