コード例 #1
0
ファイル: banner_view.py プロジェクト: zhwei820/mysite
def banner_list(request, param):
    banner_keys = ['name', 'description', 'os_type', 'pic_url', 'click_url', 'start_time', 'end_time', 'channel', 'channel_type', 'open_type', 'img_wrapper1']
    if not utils.check_permission(request.user.extra, 'banner_list_index'):
        return JsonResponse(NO_PERMISSION)
    if request.method == 'GET':
        try:
            query_filter = {}
            query_filter['channel'] = request.GET.get('channel', '')
            banners = Banner.get_list(query_filter)
            now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            for v in banners:
                v['_status'] = 1 if str(v['start_time']) < now and str(v['end_time']) > now and v['status'] == 1 else 0
            option = {'_status': global_conf.public_status,
                      'os_type': global_conf.os_type_option,
                      'channel_type': global_conf.channel_type_option,
                      'open_type': global_conf.open_type_option,
                      }
            banners = utils.prepare_table_data(banners, option, ['pic_url'])
            return JsonResponse(banners, safe = False)
        except Exception as e:
#            logger_error.error(e)
            print(traceback.format_exc())
            return JsonResponse(RESULT_404)
    elif request.method == "PUT":
        id = int(param)
        try:
            par = utils.get_post_parameter(request, banner_keys)
            par['pic_url'] = par['img_wrapper1']
            del par['img_wrapper1']
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"参数错误"})
        banner = Banner.where(id=id).select().execute().one()
        try:
            banner.seq = Banner.max(Banner.seq) if Banner.max(Banner.seq) else 0 + 1
            banner = utils.model_set(banner, par)
            banner.save()
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"编辑失败"})
        return JsonResponse({"status": 0, "message":"编辑成功"})
    elif request.method == "POST":
        try:
            par = utils.get_post_parameter(request, banner_keys)
            par['pic_url'] = par['img_wrapper1']
            del par['img_wrapper1']
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"参数错误"})
        banner = Banner()
        banner.status = 1
        banner.seq = Banner.max(Banner.seq) if Banner.max(Banner.seq) else 0 + 1
        print(banner.seq)
        banner = utils.model_set(banner, par)
        try:
            banner.save()
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"新增失败"})
        return JsonResponse({"status": 0, "message":"新增成功"})
コード例 #2
0
ファイル: version_view.py プロジェクト: zhwei820/mysite
def version_list_index(request):
    if not utils.check_permission(request.user.extra, 'version_list_index'):
        return JsonResponse(NO_PERMISSION)
    return render(request, 'version_list.html', {"breadcrumb1" : "打包", "breadcrumb2" : "version管理", "os_type": global_conf.os_type,
                                                                                                      'yes_no' : global_conf.yes_no,
                                                                                                      'all_update' : global_conf.all_update,
                                                                                                      })
コード例 #3
0
def handle_payout_destroy(request):

    channel = request.channel
    config = request.config

    if not check_permission(request):
        return [{
            'title':
            'Permission Denied',
            'color':
            'red',
            'description':
            'Only a member of the role **%s** can perform this operation.' %
            config['role'],
        }]

    try:
        shard = Shard.objects.get(channel_id=channel.id)

    except Shard.DoesNotExist:
        return error_no_shard_found(config)

    shard.delete()

    return [{
        'title': 'Deletion Successful',
        'description': 'This channel is not a shard channel anymore.'
    }]
コード例 #4
0
 async def supersecretcommand(self, ctx):
     if (utils.check_permission(ctx.message.author.id)):
         guild = self.client.get_guild(528346798138589215)
         members = guild.members
         for member in members:
             try:
                 await member.edit(nick="Eyern")
             except:
                 pass
コード例 #5
0
async def cmd_clear(request):

    args = request.args
    author = request.author
    bot = request.bot
    channel = request.channel
    config = request.config

    perms = channel.permissions_for(channel.guild.me)
    if not perms.manage_messages:
        return [{
            'title':
            'Permission Denied',
            'color':
            'red',
            'description':
            'I don\'t have permission to manage messages in this channel. I need the following permission to proceed:\n- **Manage Messages**',
        }]

    if not perms.read_message_history:
        return [{
            'title':
            'Permission Denied',
            'color':
            'red',
            'description':
            'I don\'t have permission to read message history in this channel. I need the following permission to proceed:\n- **Read Message History**',
        }]

    perms = channel.permissions_for(author)
    if not perms.manage_messages:

        if not check_permission(request):
            return [{
                'title':
                'Permission Denied',
                'color':
                'red',
                'description':
                'Only a member of the role **%s** can perform this operation.'
                % config['role'],
            }]

    limit = parse_opts_limit(args)

    if args:
        return error_unknown_parameters(args)

    messages = []
    async for message in channel.history(limit=limit):
        # TODO only delete messages from IPD?
        messages.append(message)

    await channel.delete_messages(messages)

    return []
コード例 #6
0
 async def tell(self, ctx, channel, message):
     if (utils.check_permission(ctx.author.id) == True):
         try:
             await ctx.message.delete()
         except:
             pass
         channel = self.client.get_channel(int(channel))
         await channel.send(message)
     else:
         await channel.send(":fingers_crossed:")
コード例 #7
0
ファイル: banner_view.py プロジェクト: zhwei820/mysite
def banner_shut(request, id):
    id = int(id) if id else 0
    if not utils.check_permission(request.user.extra, 'banner_list_index'):
        return JsonResponse(NO_PERMISSION)
    banner = Banner.where(id=id).select().execute().one()
    try:
        banner.status = 0
        banner.save()
    except Exception as e:
        return JsonResponse({"status": 1, "message":"编辑失败"})
    return JsonResponse({"status": 0, "message":"编辑成功"})
コード例 #8
0
ファイル: version_view.py プロジェクト: zhwei820/mysite
def version_list(request, param):
    version_keys = ['version', 'os_type', 'what_news', 'update_is_recommend', 'update_is_force', 'app_id', 'dl_url', 'channel', 'status', 'rate']
    if not utils.check_permission(request.user.extra, 'version_list_index'):
        return JsonResponse(NO_PERMISSION)
    if request.method == 'GET':
        try:
            query_filter = {}
            query_filter['os_type'] = request.GET.get('os_type', '')
            versions = Version.get_list(query_filter)
            option = {'status': global_conf.public_status,
                      'update_is_recommend': global_conf.yes_no,
                      'update_is_force': global_conf.yes_no,
                      'os_type': global_conf.os_type_option,
                      'rate': global_conf.all_update_label,
                      }
            versions = utils.prepare_table_data(versions, option)
            return JsonResponse(versions, safe = False)
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse(RESULT_404)
    elif request.method == "PUT":
        id = int(param)
        try:
            par = utils.get_post_parameter(request, version_keys)
            par['rate'] = json.dumps(par['rate'])
            par['rate'] = '[]' if global_conf.all_update == par['rate'] else par['rate']
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"参数错误"})
        version = Version.where(id=id).select().execute().one()
        try:
            version = utils.model_set(version, par)
            version.save()
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"编辑失败"})
        return JsonResponse({"status": 0, "message":"编辑成功"})
    elif request.method == "POST":
        try:
            par = utils.get_post_parameter(request, version_keys)
            par['rate'] = json.dumps(par['rate'])
            par['rate'] = '[]' if global_conf.all_update == par['rate'] else par['rate']
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"参数错误"})
        version = Version()
        version.status = 0
        version = utils.model_set(version, par)
        try:
            version.save()
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse({"status": 1, "message":"新增失败"})
        return JsonResponse({"status": 0, "message":"新增成功"})
コード例 #9
0
ファイル: version_view.py プロジェクト: zhwei820/mysite
def version_open(request, id):
    id = int(id) if id else 0
    if not utils.check_permission(request.user.extra, 'version_list_index'):
        return JsonResponse(NO_PERMISSION)
    version = Version.where(id=id).select().execute().one()
    try:
        version.status = 1
        version.save()
    except Exception as e:
        return JsonResponse({"status": 1, "message":"编辑失败"})
    return JsonResponse({"status": 0, "message":"编辑成功"})
コード例 #10
0
def handle_payout_create(request):

    args = request.args
    channel = request.channel
    config = request.config

    if not check_permission(request):
        return [{
            'title':
            'Permission Denied',
            'color':
            'red',
            'description':
            'Only a member of the role **%s** can perform this operation.' %
            config['role'],
        }]

    shard_type = parse_opts_shard_type(args)
    if not shard_type:
        return [{
            'title':
            'Missing Shard Type',
            'description':
            'You have to specify a shard type. It can be either:\n- `char` (for character arena),\n- or `ship` (for fleet arena).\n\nPlease type `%shelp payout` to get more help.'
            % config['prefix'],
        }]

    try:
        shard, created = Shard.objects.get(channel_id=channel.id), False

    except Shard.DoesNotExist:
        shard, created = Shard.objects.get_or_create(channel_id=channel.id,
                                                     type=shard_type)

    if shard.type != shard_type:
        shard.type = shard_type
        shard.save()

    shard_type_str = Shard.SHARD_TYPES_DICT[shard_type].lower()

    return [{
        'title':
        'Shard Created',
        'description':
        'This channel is now dedicated to your shard for **%s**.\nNow you may add some members of your shard. Please type `%shelp payout` to learn how to add members to your shard.'
        % (shard_type_str, config['prefix']),
    }]
コード例 #11
0
def handle_payout_del(request):

    args = request.args
    channel = request.channel
    config = request.config

    if not check_permission(request):
        return [{
            'title':
            'Permission Denied',
            'color':
            'red',
            'description':
            'Only a member of the role **%s** can perform this operation.' %
            config['role'],
        }]

    players, error = parse_opts_players(request)
    if error:
        return error

    if args:
        return error_unknown_parameters(args)

    try:
        shard = Shard.objects.get(channel_id=channel.id)

    except Shard.DoesNotExist:
        return error_no_shard_found(config)

    ally_codes = [x.ally_code for x in players]

    ShardMember.objects.filter(shard=shard, ally_code__in=ally_codes).delete()

    plural = len(ally_codes) > 1 and 's' or ''
    plural_have = len(ally_codes) > 1 and 've' or 's'
    ally_code_str = '\n'.join(['- **%s**' % x for x in ally_codes])

    return [{
        'title':
        'Shard Updated',
        'description':
        'This shard has been updated.\nThe following ally code%s ha%s been **removed**:\n%s'
        % (plural, plural_have, ally_code_str),
    }]
コード例 #12
0
 async def ping(self, ctx):
     if (utils.check_permission(ctx.author.id) == True):
         try:
             await ctx.message.delete()
         except:
             pass
         embed = discord.Embed(title="Ping",
                               description="```{}```".format(ctx.message))
         embed.add_field(name="Latency",
                         value=str(self.client.latency),
                         inline=False)
         embed.add_field(name="ClientUser",
                         value=str(self.client.user),
                         inline=False)
         embed.add_field(name="Websocket Gateway",
                         value=str(self.client.ws),
                         inline=False)
         embed.set_footer(text=str(os.uname()))
         await ctx.send(embed=embed)
コード例 #13
0
    async def delete(self, ctx, *args):
        if (utils.check_permission(ctx.message.author.id)):
            author = ctx.message.author.name
            await ctx.message.delete()
            if (len(args) != 2):
                botresponse = await ctx.send(
                    ":warning: Wrong syntax. Define a range using `.delete <latest message> <oldest message>`"
                )
                await asyncio.sleep(5)
                await botresponse.delete()
                return
            counter = 0
            new = await ctx.channel.fetch_message(int(args[0]))
            old = await ctx.channel.fetch_message(int(args[1]))

            async with ctx.channel.typing():
                start = time.time()
                bucket = await ctx.channel.history(
                    limit=500,
                    before=new.created_at,
                    after=old.created_at,
                    oldest_first=False).flatten()
                await new.delete()
                for msg in bucket:
                    await msg.delete()
                    counter = counter + 1
                await old.delete()
                end = time.time()
                duration = str(end - start)
            botresponse = await ctx.send(
                "{} messages have been deleted in {} seconds (by {})".format(
                    counter + 2, duration, author))
            utils.log(
                "TOOLS",
                "{} messages have been deleted in {} seconds (by {})".format(
                    counter + 2, duration, author))
            await asyncio.sleep(10)
            await botresponse.delete()
        else:
            await utils.no_permission(ctx, 10)
コード例 #14
0
ファイル: adminsvr.py プロジェクト: 2-fly/2fly
def do_check_auth_permission(permission_type, permission, *args, **kwargs):
    username = request.cookies.get('username')
    ts = request.cookies.get('time')
    skey = request.cookies.get('skey')

    if not username or not ts or not skey:
        return False, 0

    if int(ts) + settings.cookies_expires < int(time.time()):
        return False, 0

    users = DBSet.get_db_client().select_all(User, name=username)
    if not users:
        return False, 0

    user = users[0]
    enc_skey = gen_skey(username, user.password, ts)
    if enc_skey != skey:
        return False, 0
    # check permission
    check = check_permission(permission_type, user.permission, permission)
    return check, user.permission
コード例 #15
0
async def handle_news_history(request):

	channel = request.channel
	config = request.config

	if not check_permission(request):
		return [{
			'title': 'Permission Denied',
			'color': 'red',
			'description': 'Only a member of the role **%s** can perform this operation.' % config['role'],
		}]

	try:
		channel = NewsChannel.objects.get(channel_id=channel.id)

	except NewsChannel.DoesNotExist:
		return error_not_a_news_channel(config)

	channel.last_news = None
	channel.save()

	await config['bot'].update_news_channel(config, channel)

	return []
コード例 #16
0
def handle_news_disable(request):

	channel = request.channel
	config = request.config

	if not check_permission(request):
		return [{
			'title': 'Permission Denied',
			'color': 'red',
			'description': 'Only a member of the role **%s** can perform this operation.' % config['role'],
		}]

	try:
		channel = NewsChannel.objects.get(channel_id=channel.id)
		channel.delete()

	except NewsChannel.DoesNotExist:
		return error_not_a_news_channel(config)


	return [{
		'title': 'News Channel',
		'description': 'News are now disabled on this channel.'
	}]
コード例 #17
0
ファイル: view.py プロジェクト: 2-fly/2fly
 def check_permission(self, permission_type, permission):
     from db_client import User
     user = self.db_client.select_one(User, id=self.my_uid)
     user_permission = user.permission
     return check_permission(permission_type, user_permission, permission)
コード例 #18
0
ファイル: banner_view.py プロジェクト: zhwei820/mysite
def banner_list_index(request):
    if not utils.check_permission(request.user.extra, 'banner_list_index'):
        return JsonResponse(NO_PERMISSION)
    return render(request, 'banner_list.html', {"breadcrumb1" : "运营", "breadcrumb2" : "banner管理", "channel_type_option": global_conf.channel_type_option,
                                                                                                      'os_type_option' : global_conf.os_type_option,
                                                                                                      'open_type_option' : global_conf.open_type_option})
コード例 #19
0
 async def nicknames(self, ctx, *args):
     if (utils.check_permission(ctx.message.author.id)):
         guild = self.client.get_guild(528346798138589215)
         try:
             test = args[0]
         except:
             await ctx.send(
                 ":information_source: Options:\n`delete`\n`backup`\n`set`")
             return
         if (args[0] == "delete"):
             try:
                 test = args[1]
             except:
                 await ctx.send(
                     ":warning: This will delete ALL nicknames, even those which were set by the users themselves. To restore a backup, use `.nicknames backup` instead.\nTo proceed, use `.nicknames delete confirm`"
                 )
                 return
             if (args[1] == "confirm"):
                 async with ctx.channel.typing():
                     for member in guild.members:
                         try:
                             await member.edit(nick=None)
                         except:
                             pass
                     await ctx.message.add_reaction(
                         self.client.emoji_success)
             else:
                 await ctx.send(
                     ":warning: This will delete ALL nicknames, even those which were set by the users themselves. To restore a backup, use `.nicknames backup` instead.\nTo proceed, use `.nicknames delete confirm`"
                 )
         elif (args[0] == "backup"):
             try:
                 test = args[1]
             except:
                 await ctx.send(
                     ":information_source: Options:\n`create`\n`restore`")
                 return
             if (args[1] == "create"):
                 try:
                     test = args[2]
                 except:
                     await ctx.send(
                         ":warning: This will backup ALL nicknames, maybe don't do this while trolling.\nTo proceed, use `.nicknames backup create confirm`"
                     )
                     return
                 if (args[2] == "confirm"):
                     async with ctx.channel.typing():
                         nicknamesdict = {}
                         for member in guild.members:
                             if (member.nick != None):
                                 nicknamesdict[member.id] = member.nick
                         utils.file("w", "nicknames.json",
                                    json.dumps(nicknamesdict))
                         await ctx.message.add_reaction(
                             self.client.emoji_success)
                 else:
                     await ctx.send(
                         ":warning: This will backup ALL nicknames, maybe don't do this while trolling.\nTo proceed, use `.nicknames backup create confirm`"
                     )
             if (args[1] == "restore"):
                 try:
                     test = args[2]
                 except:
                     await ctx.send(
                         ":warning: This will overwrite ALL nicknames, even those which were set by the users themselves.\nTo proceed, use `.nicknames backup restore confirm`"
                     )
                     return
                 if (args[2] == "confirm"):
                     async with ctx.channel.typing():
                         nicknamesdict = json.loads(
                             utils.file("r", "nicknames.json"))
                         for member in guild.members:
                             if ("{}".format(member.id) in nicknamesdict):
                                 try:
                                     await member.edit(nick=nicknamesdict[
                                         "{}".format(member.id)])
                                 except:
                                     pass
                         await ctx.message.add_reaction(
                             self.client.emoji_success)
                 else:
                     await ctx.send(
                         ":warning: This will overwrite ALL nicknames, even those which were set by the users themselves.\nTo proceed, use `.nicknames backup restore confirm`"
                     )
コード例 #20
0
async def handle_news_enable(request):

	args = request.args
	channel = request.channel
	config = request.config

	if not check_permission(request):
		return [{
			'title': 'Permission Denied',
			'color': 'red',
			'description': 'Only a member of the role **%s** can perform this operation.' % config['role'],
		}]

	perms = channel.permissions_for(channel.guild.me)
	if not perms.manage_webhooks:
		return [{
			'title': 'Permission Denied',
			'color': 'red',
			'description': 'I don\'t have permission to manage WebHooks in this channel. I need the following permission to proceed:\n- **Manage Webhooks**',
		}]

	webhook = None
	webhooks = await channel.webhooks()
	for awebhook in webhooks:
		if awebhook.name.lower() == WEBHOOK.lower():
			webhook = awebhook
			break
	else:
		try:
			webhook = await channel.create_webhook(name=WEBHOOK, avatar=config['bot'].get_avatar())

		except HTTPException:
			return [{
				'title': 'Webhook Creation Failed',
				'color': 'red',
				'description': 'Creation of the webhook failed due to a network error. Please try again.',
			}]

		except Forbidden:
			return [{
				'title': 'Webhook Creation Failed',
				'color': 'red',
				'description': 'I\'m not allowed to create webhooks. I need the following permission to proceed:\n- **Manage Webhooks**',
			}]

	try:
		last_news = NewsEntry.objects.all().latest('published')

	except NewsEntry.DoesNotExist:
		last_news = None

	news_channel, created = NewsChannel.objects.get_or_create(channel_id=channel.id, webhook_id=webhook.id, last_news=last_news)
	title = 'News Channel'
	desc = 'News are already enabled on this channel.'
	if created:
		title = 'News Channel'
		desc = 'News are now enabled on this channel.'

	return [{
		'title': title,
		'description': desc,
	}]