Esempio n. 1
0
from settings import Config
from generator import gen_test
from comparator import compare
from printer import print_test

config = Config('config.txt')


def stresstest_with_checker():
    # TO DO
    pass


def stresstest_with_comparator():
    test_n = 1
    while True:
        print(f"TEST #{test_n}")
        test_n += 1
        gen_test(config, test_n)
        res = compare(config)
        if res == 1:
            print('FAIL')
        elif res == 2:
            print('Something went wrong.')
        else:
            print('SUCCES')
        if res != 0:
            print_test(config)


def stresstest_with_interactor():
Esempio n. 2
0
    def __init__(self, engine, path="./pages/sso"):
        self.engine = engine
        self.db = PostgreSQL(**Config().get("Database"))

        self.parent = SingleWebPage(name="/sso",
                                    url_prefix="/sso",
                                    description="SSO (OAuth2소셜로그인)",
                                    template_folder=path)
        self.mobile_platform = ['android', 'iphone', 'blackberry']

        def render_template(template_name, **kwargs):
            return render_template_string(
                open(
                    f"{realpath(self.parent.bp.template_folder)}/{template_name}",
                    "r",
                    encoding="UTF-8").read(),
                google_analystics=open(
                    f"{realpath(self.parent.bp.template_folder)}/../global/gtag.html",
                    "r",
                    encoding="UTF-8").read(),
                **kwargs)

        def send_raw(folder, fname):
            return send_from_directory(
                f"{realpath(self.parent.bp.template_folder)}",
                f"{folder}/{fname}")

        @self.parent.bp.route('/twitch/')
        @cross_origin(
            ["http://enakbot.return0927.xyz", "http://sso.return0927.xyz"])
        def twitch(*args, **kwargs):
            token = request.args.get("access_token")
            if token:
                resp = get("https://api.twitch.tv/kraken/user",
                           headers={
                               "Accept":
                               "application/vnd.twitchtv.v5+json",
                               "Client-ID":
                               Config().get("Cresentials")['twitch-cid'],
                               "Authorization":
                               f"OAuth {token}"
                           }).json()

                _name = resp['display_name']
                _uid = resp['name']
                _tid = resp['_id']
                _email = resp.get('email')

                _first_join, _uuid = self.db.add_user("twitch",
                                                      email=_email,
                                                      name=_name,
                                                      uid=_uid,
                                                      tid=_tid,
                                                      now=session.get("uuid"))
                session['uuid'] = _uuid

                if not isinstance(session.get('li_platform'), dict):
                    session['li_platform'] = {}
                session['li_platform']['twitch'] = {"name": _name}

                return render_template("ok.html")
            else:
                return render_template("index.html")

        @self.parent.bp.route("/discord/")
        @cross_origin(
            ["http://enakbot.return0927.xyz", "http://sso.return0927.xyz"])
        def discord(*args, **kwargs):
            if "sso.return0927.xyz" in request.url:
                return render_template("index.html")

            token = request.args.get("access_token")
            if token:
                resp = get("https://discordapp.com/api/users/@me",
                           headers={
                               "Authorization": f"Bearer {token}"
                           }).json()
                _email = resp['email']
                _name = resp['username']
                _id = resp['id']

                _first_join, _uuid = self.db.add_user("discord",
                                                      email=_email,
                                                      name=_name,
                                                      uid=_id,
                                                      now=session.get("uuid"))
                session['uuid'] = _uuid

                if not isinstance(session.get('li_platform'), dict):
                    session['li_platform'] = {}
                session['li_platform']['discord'] = {"name": _name}

                return render_template("ok.html")
            else:
                return "."

        @self.parent.bp.route(
            "/<any(css, img, js, media):folder>/<path:filename>")
        def statics(folder, filename):
            return send_raw(folder, filename)
Esempio n. 3
0

def setup_app(conf):
    app = web.Application(client_max_size=conf.MAX_BODY_SIZE,
                          logger=log.access_logger,
                          middlewares=[])
    app["conf"] = conf

    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)
    app.on_shutdown.append(on_shutdown)

    app.router.add_routes(routes)  # setup views and routes

    loop = asyncio.get_event_loop()

    executor = ThreadPoolExecutor(max_workers=10)
    app["executor"] = executor

    loop.set_default_executor(executor)

    return app


if __name__ == "__main__":
    argv = sys.argv[1:]
    uvloop.install()
    conf = Config()
    app = setup_app(conf)
    web.run_app(app, host=conf.app_host, port=conf.app_port)
Esempio n. 4
0
async def worker_setup(request):
    # get data from request
    data = request.json
    # If not data -> return "expected json"
    if not data:
        return json({"status": 403, "message": "expected json"})
    # get security token from the data
    token = data.get("security_token", "")
    # Verify security token (of the server)
    if token != tokens['server']:
        return json({"status": 403, "message": "token unauthorized"})
    # Pull url from request
    url = data.get("url", "")
    # Generate new token and pull url
    if not url:
        return json({"status": 403, "message": "url invalid"})
    # check if session is already saved, then this means the frontend was restarted and we can ignore this
    # TODO: Support a changed key where the instance can say that it didnt restart,
    # TODO: rather changed the other variables. Potentially its own endpoint
    check = False
    # if its in the cache we take it from there
    for session_name in tokens:
        # for reasons we save the server token in this cache as well so we have to ignore it in here
        if session_name == "server":
            continue
        if tokens[session_name].url == url:
            check = session_name
            break
    # it was not in the cache, maybe its in the database
    if not check:
        all_sessions = await database.all_frontend_sessions()
        for session in all_sessions:
            # url is the unique identifier here
            if session["url"] == url:
                tokens[session["name"]] = Config(session["token"], session["url"])
                check = session["name"]
    # check is set to the new name which is way better then giving it its own variable
    if check:
        return json({"status": 200, "name": check, "token": tokens[check].token})
    # continue setting up the new session
    # Pull broadcast channel from the request
    broadcast_entity = data.get("broadcast")
    # For "No entity" value must be None
    if broadcast_entity == "":
        return json({"status": 403, "message": "broadcast entity is invalid"})
    # Pull psychological room from the request
    psychological_room = data.get("psychological_room")
    # For "No entity" value must be None
    if psychological_room == "":
        return json({"status": 403, "message": "psychological room is invalid"})
    # Pull doctor room from the request
    doctor_room = data.get("doctor_room")
    # For "No entity" value must be None
    if doctor_room == "":
        return json({"status": 403, "message": "doctor room is invalid"})

    # Generate new token and name for the instance
    # @Important: 40 bytes token is > 50 characters long
    new_token = secrets.token_urlsafe(40)
    # @Important: Conveniently cut to length of 40
    new_token = new_token[:40]
    # @Important: Token hex returns n * 2 amount of symbols
    name = secrets.token_hex(10)
    # [DEBUG]: assert len(name) == 20

    config_obj = Config(new_token, url)
    tokens[name] = config_obj
    # Return useful data back to the caller
    await database.create_session({
        "name": name,
        "token": new_token,
        "url": url,
        "broadcast": broadcast_entity,
        "psychological_room": psychological_room,
        "doctor_room": doctor_room
    })
    return json({"status": 200, "name": name, "token": new_token})
from settings import Config
config = Config()

CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'US/Central'
CELERY_REDIS_MAX_CONNECTIONS = 2

if config["HEROKU_DB"]:
    import os
    url = os.environ.get('BROKER_URL')
else:
    url = 'redis://localhost:6379/0'

BROKER_URL = url
CELERY_RESULT_BACKEND = url
Esempio n. 6
0
    def __init__(self, engine, path="./pages/rank"):
        self.engine = engine

        self.db = PostgreSQL(**Config().get("AppDatabase"))
        self.web_db = PostgreSQL(**Config().get("Database"))

        self.parent = SingleWebPage(name="/ranks",
                                    url_prefix="/ranks",
                                    description="Rank (랭킹)",
                                    template_folder=path)
        self.mobile_platform = ['android', 'iphone', 'blackberry']

        def render_template(template_name, **kwargs):
            return render_template_string(
                open(
                    f"{realpath(self.parent.bp.template_folder)}/{template_name}",
                    "r",
                    encoding="UTF-8").read(),
                google_analystics=open(
                    f"{realpath(self.parent.bp.template_folder)}/../global/gtag.html",
                    "r",
                    encoding="UTF-8").read(),
                **kwargs)

        def send_raw(folder, fname):
            return send_from_directory(
                f"{realpath(self.parent.bp.template_folder)}",
                f"{folder}/{fname}")

        @self.parent.bp.route("/")
        def root(*args, **kwargs):
            return """<script>location.href='/';</script>"""

        @self.parent.bp.route('/<path:channel>')
        def ranks(channel, **kwargs):
            channels = [
                *{
                    *[
                        x[0] for x in self.db.execute(
                            "SELECT channel FROM points;").fetchall()
                    ]
                }
            ]
            if not channel in channels:
                return """<script>alert('올바르지 않은 채널명입니다.');location.href='/';</script>"""

            sel = request.args.get("view", "")
            if sel == "my":
                _logged_in_platforms = session.get("li_platform")
                if not (_logged_in_platforms
                        and "twitch" in _logged_in_platforms):
                    return redirect(f"/login/?redirect={request.url}")

                # return repr(session['uuid'])
                tid = self.web_db.execute(
                    f"SELECT twitch FROM users WHERE uuid='{session['uuid']}';"
                ).fetchall()[0][0]
                uid = self.web_db.execute(
                    f"SELECT uid FROM twitch WHERE tid='{tid}';").fetchall(
                    )[0][0]
                data = self.db.execute(
                    f"SELECT channel, point FROM points WHERE \"user\"='{uid}' ORDER BY channel DESC;"
                ).fetchall()

                _out = []
                for c, p in data:
                    _channel_data = self.db.execute(
                        f"SELECT \"user\", point, RANK() OVER(ORDER BY point DESC) FROM points WHERE channel='{c}' ORDER BY point DESC;"
                    ).fetchall()
                    _out.append(
                        [c, p, [u for u, _, _ in _channel_data].index(uid)])

                return render_template(
                    "my.html",
                    debugstring=f"?{time()}" if self.is_debugging() else "",
                    session=session,
                    user=_logged_in_platforms['twitch']['name'],
                    channel=channel,
                    data=_out)

            elif sel == "":
                data = self.db.execute(
                    f"SELECT \"user\", point, RANK() OVER(ORDER BY point DESC) FROM points WHERE channel='{channel}' ORDER BY point DESC;"
                ).fetchall()

                if session.get("li_platform") and "twitch" in session.get(
                        "li_platform"):
                    tid = self.web_db.execute(
                        f"SELECT twitch FROM users WHERE uuid='{session['uuid']}';"
                    ).fetchall()[0][0]
                    uid = self.web_db.execute(
                        f"SELECT uid FROM twitch WHERE tid='{tid}';").fetchall(
                        )[0][0]

                    data = [[u[:2] + ("*" * (len(u) - 2)), v, r, u == uid]
                            for u, v, r in data]
                    data.sort(key=lambda x: x[3])
                    me = data[-1]
                    data = [me] + data[:-1]
                else:
                    data = [[u[:2] + ("*" * (len(u) - 2)), v, r, False]
                            for u, v, r in data]
                p = [p for u, p, r, me in data]
                top_5 = sum(p[:5]) / sum(p) * 100
                top_10 = sum(p[:10]) / sum(p) * 100

                return render_template(
                    "index.html",
                    debugstring=f"?{time()}" if self.is_debugging() else "",
                    session=session,
                    channel=channel,
                    data=data[:100],
                    perc_10=top_10,
                    perc_5=top_5,
                    sel=sel)

            else:
                return """<script>alert('없는 페이지입니다.');history.go(-1);</script>"""

        @self.parent.bp.route(
            "/<any(css, img, js, media):folder>/<path:filename>")
        def statics(folder, filename):
            return send_raw(folder, filename)
Esempio n. 7
0
    def __init__(self, engine, path="./pages/root"):
        self.engine = engine

        self.parent = Blueprint("API",
                                __name__,
                                url_prefix="/api",
                                template_folder=path)

        ConfigDatabase = Config().get("Database")
        self.ApiDatabase = DBConnector(ConfigDatabase)

        @self.parent.route("/data/<ColumnTargets>")
        def API_GetColumnData(ColumnTargets):
            cols = ColumnTargets.split(",")

            Returns = {}
            for column in cols:
                err, DBData = self.ApiDatabase.fetch_column("APIInfo", column)

                if err:
                    return jsonify({
                        "error":
                        "An error was occured while processing your request."
                    })

                Returns[column] = [
                    [
                        t.timestamp() * 1e3,
                        #int(t.timestamp() // 1e5 * 1e9),  # Drop under seconds
                        v
                    ] for t, v in DBData
                ]

            return jsonify(Returns)

        @self.parent.route("/data/<date>/<ColumnTargets>")
        def API_GetOldColumnData(date, ColumnTargets):
            if not date.isnumeric():
                return jsonify(
                    {"error": "Date must be integer typed (YYYYMMDD)"})

            cols = ColumnTargets.split(",")

            Returns = {}
            for column in cols:
                err, DBData = self.ApiDatabase.fetch_column(
                    "Backup-" + date, column)

                if err:
                    return jsonify({
                        "error":
                        "An error was occured while processing your request."
                    })

                Returns[column] = [
                    [
                        t.timestamp() * 1e3,
                        #int(t.timestamp() // 1e5 * 1e9),  # Drop under seconds
                        v
                    ] for t, v in DBData
                ]

            return jsonify(Returns)
Esempio n. 8
0
import json
import os

from settings import Config

invoice_settings = Config('INVOICE')


def load_commodity_data(file_name):
    if not file_name:
        return
    commodity = {}
    with open(file_name)as file:
        for line in file.readlines()[3:]:
            line = line.replace('\n', '')
            line = line.replace('否', '0').replace('是', '1')
            a = line.split(',')
            a[-6] += ('0' * (19 - len(a[-6])))

            commodity[a[1]] = [a[4], a[-1], a[-6], eval(a[-5])]
    if a[-1] != invoice_settings.get('version_code'):
        invoice_settings.set('version_code', a[-1])
    dump_json_to_file('./src/tax.json', commodity)


def dump_json_to_file(file_name, data):
    with open(file_name, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)


def fix_wins_file_bug(content):
Esempio n. 9
0
class Administration:
    def __init__(self, bot):
        self.bot = bot
        self.session = {}

        conf = Config("config.ini")

        trans_conf = conf.get("Translation")
        i18n.set("locale", trans_conf['default_locale'])
        i18n.set("file_type", "json")
        i18n.load_path.append(trans_conf['path'])

    DB = PostgreSQL(**Config("config.ini").get("Database"))

    def __unload(self):
        self.DB.close()

    async def on_ready(self):
        print(" [ADm] Successfully loaded.")

    @command('종료', pass_context=True)
    async def ad_shutdown(self, ctx):
        Y = t('emojis.t')
        N = t('emojis.f')

        async def callback():
            await self.bot.close()
            exit(1)

        await interact.interact_with_reaction(self.bot,
                                              ctx.message.author,
                                              t('admin.shutdown_really'),
                                              callback,
                                              emojis=[Y, N])

    @group('관리', invoke_without_command=True)
    @checks.is_crescendo()
    async def administration(self, *_):
        pass

    @administration.group('유저', invoke_without_command=True)
    @checks.is_crescendo()
    async def ad_user(self, *_):
        pass

    @ad_user.command("조회", pass_context=True)
    @checks.is_crescendo()
    async def ad_view(self, ctx, *args):
        if not args:
            user = ctx.message.author.id
        else:
            user, *remains = args

        user = users.parse_mention(user)

        user, uuid = users.get_uuid(self.DB, user)

        if uuid is None:
            await ctx.bot.reply(t("admin.no_uuid_found"))
            return

        point = users.get_point(self.DB, uuid)

        _fake_ctx = Context(prefix="\0",
                            message=Message(reactions=[], author={"id": user}))
        valid = checks.is_valid(self.DB, False)(_fake_ctx)
        await ctx.bot.reply(t("admin.view_point") \
            .format(
                _target=user,
                _dsid=user,
                _uuid=uuid,
                _active=valid,
                _point=point
            )
        )

    @ad_user.command("가입", pass_context=True)
    @checks.is_crescendo()
    async def ad_member(self, ctx, *args):
        bot = ctx.bot
        if not args:
            return

        user, *_ = args

        user = users.parse_mention(user)
        if not len(user) == 18:
            await bot.reply(t('admin.invalid_discord_id'))
            return

        _, uuid = users.get_uuid(self.DB, user)

        if uuid:
            await bot.reply(t("admin.remote_register_already"))
            return

        _, data = self.DB.rnf(
            f"INSERT INTO uuid (point) VALUES (0) RETURNING uuid;")
        uuid = data[0][0]
        _, data = self.DB.rnf(
            f"INSERT INTO discord (uuid, discord_id) VALUES ('{uuid}', '{user}') RETURNING uuid;"
        )

        if data:
            await bot.reply(
                t('admin.remote_register_success').format(_discord=user,
                                                          _uuid=uuid))
        else:
            await bot.reply(t('admin.remote_register_failed'))

    @ad_user.command("탈퇴", pass_context=True)
    @checks.is_crescendo()
    async def ad_unregister(self, ctx, *args):
        bot = ctx.bot

        if not args:
            await bot.reply(t("admin.remote_unregister_require_specification"))
            return

        user, *args = args
        user = users.parse_mention(user)
        _, uuid = users.get_uuid(self.DB, user)

        if not uuid:
            await bot.reply(t('admin.remote_unregister_not_user'))
            return

        Y = t("emojis.t")
        N = t("emojis.f")

        if not len(user) == 18:
            await bot.reply(t('admin.invalid_discord_id'))
            return

        await self.ad_view.callback(self, ctx, user)

        async def callback():
            self.DB.run(f"DELETE FROM attendance WHERE uuid='{uuid}';")
            self.DB.run(f"DELETE FROM discord WHERE uuid='{uuid}';")
            self.DB.run(f"DELETE FROM uuid WHERE uuid='{uuid}';")

            await bot.reply(t('admin.remote_unregister_success'))

        await interact.interact_with_reaction(
            ctx.bot,
            ctx.message.author,
            t("admin.remote_unregister_really"),
            callback,
            emojis=[Y, N])

    @administration.error
    @ad_user.error
    @ad_view.error
    async def perm_error(self, error, ctx):
        if isinstance(error, CheckFailure):
            await ctx.bot.reply(t("messages.less_permission"))

        ctx.bot.send_message(
            ctx.bot.get_channel("459291184146153482"),
            t("error_remote_report").format(_server=ctx.message.server,
                                            _channel=ctx.message.channel.id,
                                            _error=repr(error)))