コード例 #1
0
ファイル: channels.py プロジェクト: Nemra1/discord-clone-1
async def create_channel(guild_id):
    """Create a channel in a guild."""
    user_id = await token_check()
    j = await request.get_json()

    await guild_check(user_id, guild_id)
    await guild_perm_check(user_id, guild_id, 'manage_channels')

    channel_type = j.get('type', ChannelType.GUILD_TEXT)
    channel_type = ChannelType(channel_type)

    if channel_type not in (ChannelType.GUILD_TEXT, ChannelType.GUILD_VOICE):
        raise BadRequest('Invalid channel type')

    new_channel_id = get_snowflake()
    await create_guild_channel(guild_id, new_channel_id, channel_type, **j)

    # TODO: do a better method
    # subscribe the currently subscribed users to the new channel
    # by getting all user ids and subscribing each one by one.

    # since GuildDispatcher calls Storage.get_channel_ids,
    # it will subscribe all users to the newly created channel.
    guild_pubsub = app.dispatcher.backends['guild']
    user_ids = guild_pubsub.state[guild_id]
    for uid in user_ids:
        await app.dispatcher.sub('guild', guild_id, uid)

    chan = await app.storage.get_channel(new_channel_id)
    await app.dispatcher.dispatch_guild(guild_id, 'CHANNEL_CREATE', chan)
    return jsonify(chan)
コード例 #2
0
ファイル: emoji.py プロジェクト: Nemra1/discord-clone-1
async def _put_emoji(guild_id):
    user_id = await token_check()

    await guild_check(user_id, guild_id)
    await guild_perm_check(user_id, guild_id, 'manage_emojis')

    j = validate(await request.get_json(), NEW_EMOJI)

    emoji_id = get_snowflake()

    icon = await app.icons.put(
        'emoji',
        emoji_id,
        j['image'],

        # limits to emojis
        bsize=128 * KILOBYTES,
        size=(128, 128))

    if not icon:
        return '', 400

    await app.db.execute(
        """
        INSERT INTO guild_emoji
            (id, guild_id, uploader_id, name, image, animated)
        VALUES
            ($1, $2, $3, $4, $5, $6)
        """, emoji_id, guild_id, user_id, j['name'], icon.icon_hash,
        icon.mime == 'image/gif')

    await _dispatch_emojis(guild_id)

    return jsonify(await app.storage.get_emoji(emoji_id))
コード例 #3
0
async def create_payment(subscription_id, db=None):
    """Create a payment."""
    if not db:
        db = app.db

    sub = await get_subscription(subscription_id, db)

    new_id = get_snowflake()

    amount = AMOUNTS[sub['payment_gateway_plan_id']]

    await db.execute(
        """
        INSERT INTO user_payments (
            id, source_id, subscription_id, user_id,
            amount, amount_refunded, currency,
            description, status, tax, tax_inclusive
        )
        VALUES
            ($1, $2, $3, $4, $5, 0, $6, $7, $8, 0, false)
        """, new_id, int(sub['payment_source_id']), subscription_id,
        int(sub['user_id']), amount, 'usd', 'F**K NITRO',
        PaymentStatus.SUCCESS)

    return new_id
コード例 #4
0
ファイル: auth.py プロジェクト: Nemra1/discord-clone-1
async def create_user(username: str,
                      email: str,
                      password: str,
                      db=None,
                      loop=None):
    """Create a single user."""
    db = db or app.db
    loop = loop or app.loop

    new_id = get_snowflake()

    new_discrim = randint(1, 9999)
    new_discrim = '%04d' % new_discrim

    pwd_hash = await hash_data(password, loop)

    await check_username_usage(username, db)

    try:
        await db.execute(
            """
        INSERT INTO users (id, email, username,
                        discriminator, password_hash)
        VALUES ($1, $2, $3, $4, $5)
        """, new_id, email, username, new_discrim, pwd_hash)
    except UniqueViolationError:
        raise BadRequest('Email already used.')

    return new_id, pwd_hash
コード例 #5
0
async def create_role(guild_id, name: str, **kwargs):
    """Create a role in a guild."""
    new_role_id = get_snowflake()

    # TODO: use @everyone's perm number
    default_perms = dict_get(kwargs, 'default_perms', DEFAULT_EVERYONE_PERMS)

    # update all roles so that we have space for pos 1, but without
    # sending GUILD_ROLE_UPDATE for everyone
    await app.db.execute("""
    UPDATE roles
    SET
        position = position + 1
    WHERE guild_id = $1
      AND NOT (position = 0)
    """, guild_id)

    await app.db.execute(
        """
        INSERT INTO roles (id, guild_id, name, color,
            hoist, position, permissions, managed, mentionable)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
        """,
        new_role_id,
        guild_id,
        name,
        dict_get(kwargs, 'color', 0),
        dict_get(kwargs, 'hoist', False),

        # always set ourselves on position 1
        1,
        int(dict_get(kwargs, 'permissions', default_perms)),
        False,
        dict_get(kwargs, 'mentionable', False)
    )

    role = await app.storage.get_role(new_role_id, guild_id)

    # we need to update the lazy guild handlers for the newly created group
    await _maybe_lg(guild_id, 'new_role', role)

    await app.dispatcher.dispatch_guild(
        guild_id, 'GUILD_ROLE_CREATE', {
            'guild_id': str(guild_id),
            'role': role,
        })

    return role
コード例 #6
0
async def _handle_pin_msg(app, channel_id, pinned_id, author_id):
    """Handle a message pin."""
    new_id = get_snowflake()

    await app.db.execute(
        """
        INSERT INTO messages
            (id, channel_id, guild_id, author_id,
             webhook_id, content, message_type)
        VALUES
            ($1, $2, NULL, $3, NULL, '',
             $4)
        """, new_id, channel_id, author_id,
        MessageType.CHANNEL_PINNED_MESSAGE.value)

    return new_id
コード例 #7
0
async def _create_payment_source():
    user_id = await token_check()
    j = validate(await request.get_json(), PAYMENT_SOURCE)

    new_source_id = get_snowflake()

    await app.db.execute(
        """
        INSERT INTO user_payment_sources (id, user_id, source_type,
            default_, expires_month, expires_year, brand, cc_full,
            billing_address)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
        """, new_source_id, user_id, PaymentSource.CREDIT.value, True, 12,
        6969, 'Visa', '4242424242424242', json.dumps(j['billing_address']))

    return jsonify(await get_payment_source(user_id, new_source_id))
コード例 #8
0
async def create_message(channel_id: int, actual_guild_id: int, author_id: int,
                         data: dict) -> int:
    message_id = get_snowflake()

    async with app.db.acquire() as conn:
        await pg_set_json(conn)

        await conn.execute(
            """
            INSERT INTO messages (id, channel_id, guild_id, author_id,
                content, tts, mention_everyone, nonce, message_type,
                embeds)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
        """, message_id, channel_id, actual_guild_id, author_id,
            data['content'], data['tts'], data['everyone_mention'],
            data['nonce'], MessageType.DEFAULT.value, data.get('embeds', []))

    return message_id
コード例 #9
0
async def _create_subscription():
    user_id = await token_check()
    j = validate(await request.get_json(), CREATE_SUBSCRIPTION)

    source = await get_payment_source(user_id, j['payment_source_id'])
    if not source:
        raise BadRequest('invalid source id')

    plan_id = j['payment_gateway_plan_id']

    # tier 1 is lightro / classic
    # tier 2 is nitro

    period_end = {
        'premium_month_tier_1': '1 month',
        'premium_month_tier_2': '1 month',
        'premium_year_tier_1': '1 year',
        'premium_year_tier_2': '1 year',
    }[plan_id]

    new_id = get_snowflake()

    await app.db.execute(
        f"""
        INSERT INTO user_subscriptions (id, source_id, user_id,
            s_type, payment_gateway, payment_gateway_plan_id,
            status, period_end)
        VALUES ($1, $2, $3, $4, $5, $6, $7,
            now()::timestamp + interval '{period_end}')
        """, new_id, j['payment_source_id'], user_id,
        SubscriptionType.PURCHASE, PaymentGateway.STRIPE, plan_id, 1)

    await create_payment(new_id, app.db)

    # make sure we update the user's premium status
    # and dispatch respective user updates to other people.
    await process_subscription(app, new_id)

    return jsonify(await get_subscription(new_id))