예제 #1
0
파일: league.py 프로젝트: Liam656/API
    async def get_server(self):
        """ Finds a available server for the currnet league. """

        if not self.obj.config.server["regions"].get(self.region):
            return response(error="No server IDs for that region")

        region_servers = list(self.obj.config.server["regions"][self.region])
        region_servers_remove = region_servers.remove

        query = """SELECT server_id
                   FROM scoreboard_total
                   WHERE server_id IN :server_ids AND status != 0"""
        values = {"server_ids": region_servers}

        # Removing any server ID being used in an active match.
        async for row in self.obj.database.iterate(query=query, values=values):
            region_servers_remove(row["server_id"])

        # Removing any server IDs from our temp blacklist.
        for server_id in self.obj.in_memory_cache.temp_server_blacklist:
            if server_id in region_servers:
                region_servers_remove(server_id)

        if len(region_servers) > 0:
            return response(data=region_servers[0])
        else:
            return response(error="No available servers")
예제 #2
0
파일: league.py 프로젝트: Liam656/API
    async def queue_allowed(self):
        """ Checks if over the active queue limit. """

        query = """SELECT COUNT(score.status) AS active_queues,
                          IFNULL(info.queue_limit, 0) AS queue_limit
                   FROM league_info AS info
                    LEFT JOIN scoreboard_total AS score
                        ON score.league_id = info.league_id
                           AND score.status != 0
                   WHERE info.league_id = :league_id"""
        row = await self.obj.database.fetch_one(query=query,
                                                values={
                                                    "league_id":
                                                    self.league_id,
                                                })

        if row:
            # Ensures users can't create another
            # queue when another queue is being created
            # what would put them over the queue limit.
            if self.obj.in_memory_cache.started_queues.get(self.league_id):
                active_queues = row["active_queues"] \
                     + self.obj.in_memory_cache.started_queues[self.league_id]
            else:
                active_queues = row["active_queues"]

            return response(data=row["queue_limit"] > active_queues)
        else:
            return response(error=True)
예제 #3
0
파일: league.py 프로젝트: Liam656/API
    async def details(self):
        """ Gets basic details of league. """

        row = await self.obj.database.fetch_one(
            query="""SELECT league_name, league_website,
                            websocket_endpoint, queue_limit,
                            league_id, discord_prefix,
                            sm_message_prefix, knife_round,
                            pause, surrender,
                            warmup_commands_only, captain_choice_time
                     FROM league_info WHERE league_id = :league_id""",
            values={
                "league_id": self.league_id,
            })

        if row:
            formatted_row = {**row}

            if formatted_row["pause"] == 0:
                formatted_row["pause"] = False

            formatted_row["surrender"] = formatted_row["surrender"] == 1
            formatted_row["warmup_commands_only"] = \
                formatted_row["warmup_commands_only"] == 1
            formatted_row["knife_round"] = formatted_row["knife_round"] == 1

            return response(data=formatted_row)

        return response(error="No such league")
예제 #4
0
파일: companies.py 프로젝트: oc777/backend
def company_actions():
    """Extracts companies"""
    try:
        users = get_users_with_role(COMPANY)
        return response('Successfully extracted all users', 200, {COMPANIES: users})
    except SystemError:
        return response('Something went wrong while retrieving the data', 500)
예제 #5
0
파일: league.py 프로젝트: Liam656/API
    async def update(self, args: dict):
        """ Updates details of league. """

        if len(args) > 0:
            query = "UPDATE league_info SET "
            values = {"league_id": self.league_id}

            for key, item in args.items():
                if type(item) == bool:
                    if item:
                        item = 1
                    else:
                        item = 0

                values[key] = item

                # Don't worry this isn't
                # injecting any values.
                query += "{}={},".format(key, ":" + key)

            query = query[:-1]
            query += " WHERE league_id = :league_id"

            await self.obj.database.execute(query=query, values=values)

            return response(data=args)

        return response(error="No arguments")
예제 #6
0
def get_representatives(name):
    """Gets list of representatives from specific company"""
    try:
        representatives = get_representatives_for_company(name)
        return response(name, 200, {'representatives': representatives})

    except AttributeError:
        return response('Invalid company', 400)
예제 #7
0
파일: auth.py 프로젝트: oc777/backend
def auth_actions():
    """Authenticates any user"""

    try:
        encoded_data, role = auth_and_return_user(request.form)
        return response('Successfully logged in as ' + role, 200, {TOKEN: encoded_data.decode('utf-8')})

    except AttributeError:
        return response('Wrong credentials', 400)
예제 #8
0
def delete_project(request, project_id: int):
    """
    删除项目
    """
    try:
        p = Project.objects.filter(id=project_id, is_delete=False).update(is_delete=True)
    except Project.DoesNotExist:
        return response(error=Error.PROJECT_ID_NULL)
    return response()
예제 #9
0
파일: admin.py 프로젝트: oc777/backend
def admin_auth():
    """Authenticates an admin"""

    try:
        encoded_data = auth_and_return_admin(request.form)
        return response('Successfully logged in as admin', 200,
                        {TOKEN: encoded_data.decode('utf-8')})

    except AttributeError:
        return response('Wrong credentials', 400)
예제 #10
0
파일: companies.py 프로젝트: oc777/backend
def create_representative(name):
    """Creates representative"""
    try:
        payload = extract(request)
        authorized_role(payload, COMPANY)
        representative = dal_create_representative(request, name)
        return response('Representative was created', 201, {DATA: {REPRESENTATIVE: representative}})

    except Exception as e:
        return response(str(e), 400)
예제 #11
0
파일: companies.py 프로젝트: oc777/backend
def company_creation():
    """Creates company"""
    try:
        payload = extract(request)
        authorized_role(payload, ADMIN)
        company = create_company(request)
        return response('Company was created', 201, {DATA: {COMPANY: company}})

    except Exception as e:
        return response(str(e), 400)
예제 #12
0
파일: categories.py 프로젝트: oc777/backend
def create_sub(category):
    """Create a subcategory"""

    try:
        payload = extract(request)
        authorized_role(payload, ADMIN)
        dal_create_subcategory(category, extract_attribute(request, CATEGORY))
        return response('Subcategory created', 201)
    except Exception as e:
        return response(str(e), 400)
예제 #13
0
def entry():
    '''消息入口
    异步发送接收到的通知消息,返回task_id
    '''
    data = request.get_json()
    validator.allow_unknown = True
    if not validator.validate(data, validator_schemas.message_entry_data):
        return response(validator.errors, RetCode.PARAMS_ERROR)
    task_id = handlers.handle_message(data)
    return response({'task_id': task_id})
예제 #14
0
def get_user(token):
    """Gets current user"""

    try:

        username = check_user_token(token)
        return response('Successfully gather user data', 200, {'data': username})

    except AttributeError:
        return response('Wrong credentials', 400)
예제 #15
0
def get_thread(_id):
    """Gets a single thread"""

    try:
        thread = dal_get_thread(_id)
        return response("Got the tråd", 200, {DATA: thread})
    except NotFound as e:
        return response(str(e), 404)
    except Exception:
        return response('Everything broke', 500)
예제 #16
0
파일: products.py 프로젝트: oc777/backend
def upload_actions(_id):
    try:
        payload = extract(request)
        authorized_role(payload, REPRESENTATIVE)
        username = payload[USERNAME]
        dal_upload_files(request.files, username, _id)
        return response(
            'Successfully uploaded material to the product',
            201,
            {DATA: {PRODUCT: {ID: _id}}})

    except AttributeError:
        return response('Tampered token', 400)
    except WrongCredentials:
        return response('Invalid credentials', 400)
    except AlreadyExists as e:
        return response(str(e), 409)
    except InvalidRole:
        return response('You are not a representative', 400)
    except BadFormData as e:
        return response(str(e), 400)
    except ErrorRequestingFiles:
        return response('Error requesting files', 409)
    except NotAuthorized:
        return response('Beppe is a Teapot', 418)
    except ErrorCreatingFiles as e:
        return response(str(e), 409)
예제 #17
0
파일: products.py 프로젝트: oc777/backend
def rate_material(product_id, material_name):
    """Used to rate material"""

    try:
        payload = extract(request)
        authorized_role(payload, CONSUMER)
        username = payload[USERNAME]
        rating = extract_attribute(request, RATE)

        updated_rating = dal_rate_material(
            rating, username, product_id, material_name)

        return response(updated_rating, 200)

    except WrongCredentials:
        return response('Expected jwt key', 400)
    except NotFound:
        return response('Not found', 400)
    except InvalidRole:
        return response('Have to be consumer to rate', 400)
    except BadFormData:
        return response('Expected rate key', 400)
    except FloatingPointError:
        return response('Expected rate to be int', 400)
    except ValueError:
        return response('Expected star value to be between 1 and 5', 400)
    except NotAuthorized:
        return response('Beppe is a Teapot', 418)
    except Exception:
        return response('Everything broke', 500)
예제 #18
0
def create_reply(_id):
    """Posts reply to thread"""

    try:
        payload = extract(request)
        dal_create_reply(request.form, payload, _id)
        return response('Reply created', 201)
    except BadFormData as e:
        return response(str(e), 404)
    except Exception:
        return response('Everything broke', 500)
예제 #19
0
파일: products.py 프로젝트: oc777/backend
def get_product(_id):
    """Gets a single product"""
    try:

        product = dal_get_product_by_id(_id)
        return response('Found product', 200, {DATA: {PRODUCT: product}})

    except WrongCredentials:
        return response('Not a valid id', 400)
    except NotFound:
        return response('Cannot find product', 400)
예제 #20
0
def get_project(request, project_id: int):
    """
    获取项目详情
    """
    try:
        p = Project.objects.get(id=project_id, is_delete=False)
    except Project.DoesNotExist:
        return response(error=Error.PROJECT_ID_NULL)
    data = {
        "id": p.id, "name": p.name, "describe": p.describe, "status": p.status, "create_time": p.create_time
    }
    return response(data=data)
예제 #21
0
def create_representative(name):
    """Creates representative"""
    try:

        representative_exists = dal_create_representative(request.form, name)

        if representative_exists:
            return response('Username already exists', 409)
        else:
            return response('Representative was created', 201)

    except AttributeError:
        return response('Wrong credentials', 400)
예제 #22
0
파일: companies.py 프로젝트: oc777/backend
def get_product(name):
    """Gets all products for the company"""
    try:

        products = get_products_for_company(name)
        return response(
            'Successfully retreived all the products for company ' + name,
            200,
            {DATA:
             {PRODUCTS: products}
             })
    except Exception as e:
        return response(str(e), 400)
예제 #23
0
def company_creation():
    """Creates company"""
    try:

        company_exists = create_company(request.form)

        if company_exists:
            return response('Username already exists', 409)
        else:
            return response('Company was created', 201)

    except AttributeError:
        return response('Wrong credentials', 400)
예제 #24
0
def update_project(request, item: ProjectUpdate):
    """
    更新项目
    """
    try:
        project = Project.objects.get(id=item.id, is_delete=False)
    except Project.DoesNotExist:
        return response(error=Error.PROJECT_OBJECT_NULL)
    project.name = item.name
    project.describe = item.describe
    project.status = item.status
    project.save()
    return response()
예제 #25
0
파일: companies.py 프로젝트: oc777/backend
def remove_thread_read(name, thread_id):
    """Removes read thread from company"""

    try:
        payload = extract(request)
        authorized_role(payload, REPRESENTATIVE)

        if payload[DATA][OWNER] != name:
            raise BadFormData('Wrong company')

        dal_read_thread(thread_id, name)
        return response('', 204)
    except Exception as e:
        return response(str(e), 400)
예제 #26
0
def get_favourites(username):
    """Gets the replies from the threads a consumer participates in"""
    try:

        threads_data = dal_get_favourites(username)
        if len(threads_data) == 0:
            return response("Data not found", 201)

        return response("Got favourites", 200, {DATA: {THREADS: threads_data}})

    except NotFound as e:
        return response(str(e), 404)
    except Exception:
        return response('Everything broke', 500)
예제 #27
0
def create_categories():
    """Creates a new category"""

    try:

        dal_create_category(request.form)
        return response('Category created', 201)

    except AttributeError:
        return response('Broken JWT', 400)
    except WrongCredentials:
        return response('Invalid credentials', 400)
    except AlreadyExists:
        return response('Category exists', 409)
예제 #28
0
    async def validate(self):
        """ Validates if key exists. """

        query = """SELECT COUNT(*)
                   FROM api_keys
                   WHERE `key` = :key
                          AND league_id = :league_id"""

        count = await self.current_league.obj.database.fetch_val(
            query=query, values=self.values)

        if count == 1:
            return response(data="Valid key")
        else:
            return response(error="No such key")
예제 #29
0
파일: player.py 프로젝트: Liam656/API
    async def reset(self):
        """ Resets statistics for given user. """

        query = """UPDATE statistics SET
                   total_time = 0,
                   elo = 0,
                   kills = 0,
                   deaths = 0,
                   assists = 0,
                   shots = 0,
                   hits = 0,
                   damage = 0,
                   headshots = 0,
                   roundswon = 0,
                   roundslost = 0,
                   wins = 0,
                   ties = 0,
                   losses = 0
                   WHERE user_id = :user_id AND region = :region
                         AND league_id = :league_id"""

        await self.current_league.database.execute(
            query=query,
            values=self.values
        )

        return response(data=True)
예제 #30
0
def message_audience():
    body = request.get_json()
    status, missing_field = validate_body(body, ['message', 'phones'])
    if not status:
        return error_response(f'{missing_field} is missing')
    send_bulk_sms(body['phones'], body['message'])
    return response(True, 'Success', None)