fix winter usage across codebase

This commit is contained in:
Luna 2021-06-25 15:32:29 -03:00
parent bd1d756d22
commit 1a2e7446c7
17 changed files with 45 additions and 50 deletions

View File

@ -24,7 +24,7 @@ import itsdangerous
import bcrypt
from quart import Blueprint, jsonify, request, current_app as app
from logbook import Logger
from winter import get_snowflake
from litecord.auth import token_check
from litecord.common.users import create_user
@ -187,7 +187,7 @@ async def _logout():
@bp.route("/fingerprint", methods=["POST"])
async def _fingerprint():
"""No idea what this route is about."""
fingerprint_id = get_snowflake()
fingerprint_id = app.winter_factory.snowflake()
fingerprint = f"{fingerprint_id}.{secrets.token_urlsafe(32)}"
return jsonify({"fingerprint": fingerprint})

View File

@ -27,7 +27,7 @@ from litecord.blueprints.auth import token_check
from litecord.blueprints.checks import channel_check, channel_perm_check
from litecord.errors import MessageNotFound, Forbidden
from litecord.enums import MessageType, ChannelType, GUILD_CHANS
from winter import get_snowflake
from litecord.schemas import validate, MESSAGE_CREATE
from litecord.utils import pg_set_json, query_tuple_from_args, extract_limit
from litecord.permissions import get_permissions
@ -150,7 +150,7 @@ async def _dm_pre_dispatch(channel_id, peer_id):
async def create_message(
channel_id: int, actual_guild_id: Optional[int], author_id: int, data: dict
) -> int:
message_id = get_snowflake()
message_id = app.winter_factory.snowflake()
async with app.db.acquire() as conn:
await pg_set_json(conn)

View File

@ -21,7 +21,6 @@ from quart import Blueprint, current_app as app, jsonify
from litecord.auth import token_check
from litecord.blueprints.checks import channel_check, channel_perm_check
from winter import snowflake_datetime
from litecord.types import timestamp_
from litecord.system_messages import send_sys_message
@ -95,16 +94,16 @@ async def add_pin(channel_id, message_id):
row = await app.db.fetchrow(
"""
SELECT message_id
FROM channel_pins
WHERE channel_id = $1
ORDER BY message_id ASC
LIMIT 1
""",
SELECT message_id
FROM channel_pins
WHERE channel_id = $1
ORDER BY message_id ASC
LIMIT 1
""",
channel_id,
)
timestamp = snowflake_datetime(row["message_id"])
timestamp = app.winter_factory.to_datetime(row["message_id"])
await app.dispatcher.channel.dispatch(
channel_id,
@ -151,7 +150,7 @@ async def delete_pin(channel_id, message_id):
channel_id,
)
timestamp = snowflake_datetime(row["message_id"])
timestamp = app.winter_factory.to_datetime(row["message_id"])
await app.dispatcher.channel.dispatch(
channel_id,

View File

@ -24,7 +24,6 @@ from dataclasses import dataclass
from quart import Blueprint, request, current_app as app, jsonify
from logbook import Logger
from winter import snowflake_datetime
from litecord.auth import token_check
from litecord.enums import ChannelType, GUILD_CHANS, MessageType, MessageFlags
@ -851,7 +850,7 @@ async def bulk_delete(channel_id: int):
# we must error. a cuter behavior would be returning the message ids
# that were deleted, ignoring the 2 week+ old ones.
for message_id in message_ids:
message_dt = snowflake_datetime(message_id)
message_dt = app.winter_factory.to_datetime(message_id)
delta = datetime.datetime.utcnow() - message_dt
if delta.days > 14:

View File

@ -24,7 +24,7 @@ from litecord.blueprints.auth import token_check
from litecord.blueprints.checks import channel_check
from litecord.enums import ChannelType, MessageType
from litecord.errors import BadRequest, Forbidden
from winter import get_snowflake
from litecord.system_messages import send_sys_message
from litecord.pubsub.channel import gdm_recipient_view
from litecord.pubsub.user import dispatch_user
@ -60,7 +60,7 @@ async def gdm_create(user_id, peer_id) -> int:
Returns the new GDM id.
"""
channel_id = get_snowflake()
channel_id = app.winter_factory.snowflake()
await app.db.execute(
"""

View File

@ -26,7 +26,7 @@ from logbook import Logger
from ..schemas import validate, CREATE_DM, CREATE_GROUP_DM
from ..enums import ChannelType
from winter import get_snowflake
from .auth import token_check
@ -70,7 +70,7 @@ async def create_dm(user_id, recipient_id):
# if no dm was found, create a new one
dm_id = get_snowflake()
dm_id = app.winter_factory.snowflake()
await app.db.execute(
"""
INSERT INTO channels (id, channel_type)

View File

@ -20,7 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
from quart import Blueprint, request, current_app as app, jsonify
from litecord.blueprints.auth import token_check
from winter import get_snowflake
from litecord.errors import BadRequest
from litecord.enums import ChannelType
from litecord.blueprints.guild.roles import gen_pairs
@ -56,7 +56,7 @@ async def create_channel(guild_id):
if channel_type not in (ChannelType.GUILD_TEXT, ChannelType.GUILD_VOICE):
raise BadRequest("Invalid channel type")
new_channel_id = get_snowflake()
new_channel_id = app.winter_factory.snowflake()
await create_guild_channel(guild_id, new_channel_id, channel_type, **j)
chan = await app.storage.get_channel(new_channel_id)

View File

@ -22,7 +22,7 @@ from quart import Blueprint, jsonify, current_app as app, request
from litecord.auth import token_check
from litecord.blueprints.checks import guild_check, guild_perm_check
from litecord.schemas import validate, NEW_EMOJI, PATCH_EMOJI
from winter import get_snowflake
from litecord.types import KILOBYTES
from litecord.images import parse_data_uri
from litecord.errors import BadRequest
@ -94,7 +94,7 @@ async def _put_emoji(guild_id):
mime, _ = parse_data_uri(j["image"])
await _guild_emoji_size_check(guild_id, mime)
emoji_id = get_snowflake()
emoji_id = app.winter_factory.snowflake()
icon = await app.icons.put(
"emoji",

View File

@ -29,7 +29,7 @@ from litecord.common.guilds import (
)
from ..auth import token_check
from winter import get_snowflake
from ..enums import ChannelType
from ..schemas import (
validate,
@ -79,7 +79,7 @@ async def guild_create_roles_prep(guild_id: int, roles: list):
async def guild_create_channels_prep(guild_id: int, channels: list):
"""Create channels pre-guild create"""
for channel_raw in channels:
channel_id = get_snowflake()
channel_id = app.winter_factory.snowflake()
ctype = ChannelType(channel_raw["type"])
await create_guild_channel(guild_id, channel_id, ctype)
@ -120,7 +120,7 @@ async def create_guild():
user_id = await token_check()
j = validate(await request.get_json(), GUILD_CREATE)
guild_id = get_snowflake()
guild_id = app.winter_factory.snowflake()
if "icon" in j:
image = await put_guild_icon(guild_id, j["icon"])
@ -177,7 +177,7 @@ async def create_guild():
)
# create a single #general channel.
general_id = get_snowflake()
general_id = app.winter_factory.snowflake()
await create_guild_channel(
guild_id, general_id, ChannelType.GUILD_TEXT, name="general"

View File

@ -26,7 +26,6 @@ from logbook import Logger
from litecord.auth import token_check
from litecord.schemas import validate
from winter import snowflake_datetime, get_snowflake
from litecord.errors import BadRequest
from litecord.types import timestamp_, HOURS
from litecord.enums import UserFlags, PremiumType
@ -240,7 +239,7 @@ async def get_payment(payment_id: int):
drow.pop("subscription_id")
drow.pop("user_id")
drow["created_at"] = snowflake_datetime(int(drow["id"]))
drow["created_at"] = app.winter_factory.to_datetime(int(drow["id"]))
drow["payment_source"] = await get_payment_source(row["user_id"], row["source_id"])
@ -253,7 +252,7 @@ async def create_payment(subscription_id):
"""Create a payment."""
sub = await get_subscription(subscription_id)
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
amount = AMOUNTS[sub["payment_gateway_plan_id"]]
@ -302,7 +301,7 @@ async def process_subscription(subscription_id: int):
subscription_id,
)
first_payment_ts = snowflake_datetime(first_payment_id)
first_payment_ts = app.winter_factory.to_datetime(first_payment_id)
premium_since = await app.db.fetchval(
"""
@ -394,7 +393,7 @@ async def _create_payment_source():
j = validate(await request.get_json(), PAYMENT_SOURCE)
new_source_id = get_snowflake()
new_source_id = app.winter_factory.snowflake()
await app.db.execute(
"""
@ -438,7 +437,7 @@ async def _create_subscription():
"premium_year_tier_2": "1 year",
}[plan_id]
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
await app.db.execute(
f"""

View File

@ -34,7 +34,6 @@ from litecord.blueprints.user.billing import (
process_subscription,
)
from winter import snowflake_datetime
from litecord.types import MINUTES
log = Logger(__name__)
@ -71,7 +70,7 @@ async def _process_user_payments(user_id: int):
# calculate the difference between this payment
# and now.
now = datetime.datetime.now()
payment_tstamp = snowflake_datetime(int(payment_data["id"]))
payment_tstamp = app.winter_factory.to_datetime(int(payment_data["id"]))
delta = now - payment_tstamp

View File

@ -39,7 +39,7 @@ from litecord.schemas import (
WEBHOOK_MESSAGE_CREATE,
)
from litecord.enums import ChannelType
from winter import get_snowflake
from litecord.utils import async_map
from litecord.errors import WebhookNotFound, Unauthorized, ChannelNotFound, BadRequest
@ -174,7 +174,7 @@ async def create_webhook(channel_id: int):
guild_id = await app.storage.guild_from_channel(channel_id)
webhook_id = get_snowflake()
webhook_id = app.winter_factory.snowflake()
# I'd say generating a full fledged token with itsdangerous is
# relatively wasteful since webhooks don't even have a password_hash,
@ -352,7 +352,7 @@ async def del_webhook_tokened(webhook_id, webhook_token):
async def create_message_webhook(guild_id, channel_id, webhook_id, data):
"""Create a message, but for webhooks only."""
message_id = get_snowflake()
message_id = app.winter_factory.snowflake()
async with app.db.acquire() as conn:
await pg_set_json(conn)

View File

@ -21,7 +21,6 @@ from typing import List
from logbook import Logger
from quart import current_app as app
from ..snowflake import get_snowflake
from ..permissions import get_role_perms, get_permissions
from ..utils import dict_get, maybe_lazy_guild_dispatch
from ..enums import ChannelType
@ -70,7 +69,7 @@ async def remove_member_multi(guild_id: int, members: list):
async def create_role(guild_id, name: str, **kwargs):
"""Create a role in a guild."""
new_role_id = get_snowflake()
new_role_id = app.winter_factory.snowflake()
everyone_perms = await get_role_perms(guild_id, guild_id)
default_perms = dict_get(kwargs, "default_perms", everyone_perms.binary)

View File

@ -5,7 +5,6 @@ from PIL import Image
from quart import request, current_app as app
from litecord.errors import BadRequest
from ..snowflake import get_snowflake
log = logging.getLogger(__name__)
@ -69,7 +68,7 @@ async def msg_add_attachment(message_id: int, channel_id: int, attachment_file)
quart FileStorage instance of the file.
"""
attachment_id = get_snowflake()
attachment_id = app.winter_factory.snowflake()
filename = attachment_file.filename
# understand file info

View File

@ -25,7 +25,6 @@ from asyncpg import UniqueViolationError
from logbook import Logger
from ..presence import BasePresence
from ..snowflake import get_snowflake
from ..errors import BadRequest
from ..auth import hash_data
from ..utils import rand_hex
@ -149,7 +148,7 @@ async def create_user(username: str, email: str, password: str) -> Tuple[int, st
Generates a distriminator and other information. You can fetch the user
data back with :meth:`Storage.get_user`.
"""
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
new_discrim = await roll_discrim(username)
if new_discrim is None:

View File

@ -20,7 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
from logbook import Logger
from quart import current_app as app
from winter import get_snowflake
from litecord.enums import MessageType
log = Logger(__name__)
@ -28,7 +28,7 @@ log = Logger(__name__)
async def _handle_pin_msg(channel_id, _pinned_id, author_id):
"""Handle a message pin."""
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
await app.db.execute(
"""
@ -48,7 +48,7 @@ async def _handle_pin_msg(channel_id, _pinned_id, author_id):
# TODO: decrease repetition between add and remove handlers
async def _handle_recp_add(channel_id, author_id, peer_id):
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
await app.db.execute(
"""
@ -68,7 +68,7 @@ async def _handle_recp_add(channel_id, author_id, peer_id):
async def _handle_recp_rmv(channel_id, author_id, peer_id):
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
await app.db.execute(
"""
@ -88,7 +88,7 @@ async def _handle_recp_rmv(channel_id, author_id, peer_id):
async def _handle_gdm_name_edit(channel_id, author_id):
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
gdm_name = await app.db.fetchval(
"""
@ -120,7 +120,7 @@ async def _handle_gdm_name_edit(channel_id, author_id):
async def _handle_gdm_icon_edit(channel_id, author_id):
new_id = get_snowflake()
new_id = app.winter_factory.snowflake()
await app.db.execute(
"""

2
run.py
View File

@ -28,6 +28,7 @@ from quart import Quart, jsonify, request
from logbook import StreamHandler, Logger
from logbook.compat import redirect_logging
from aiohttp import ClientSession
from winter import SnowflakeFactory
# import the config set by instance owner
import config
@ -257,6 +258,7 @@ async def init_app_db(app_):
def init_app_managers(app_: Quart, *, init_voice=True):
"""Initialize singleton classes."""
app_.winter_factory = SnowflakeFactory()
app_.loop = asyncio.get_event_loop()
app_.ratelimiter = RatelimitManager(app_.config.get("_testing"))
app_.state_manager = StateManager()