Skip to content

Commit

Permalink
some code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
RuslanUC committed May 8, 2024
1 parent bc256c6 commit 42376be
Show file tree
Hide file tree
Showing 20 changed files with 38 additions and 25 deletions.
4 changes: 1 addition & 3 deletions yepcord/cdn/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""

import sys

from quart import Quart, Blueprint
from quart_schema import validate_querystring, QuartSchema
from tortoise.contrib.quart import register_tortoise
Expand Down Expand Up @@ -165,7 +163,7 @@ async def get_sticker(query_args: CdnImageSizeQuery, sticker_id: int, format_: s
break
else:
sticker = await getStorage().getSticker(sticker_id, query_args.size, format_,
sticker.format in (StickerFormat.APNG, StickerFormat.GIF))
sticker.format in (StickerFormat.APNG, StickerFormat.GIF))
if not sticker:
return b'', 404
return sticker, 200, {"Content-Type": f"image/{format_}"}
Expand Down
1 change: 1 addition & 0 deletions yepcord/remote_auth/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ async def handle_nonce_proof(self, data: dict) -> None:
return await self.ws.close(1001)
await self.send("pending_remote_init", fingerprint=self.fingerprint)

# noinspection PyUnusedLocal
async def handle_heartbeat(self, data: dict) -> None:
self.last_heartbeat = time()
await self.send("heartbeat_ack")
Expand Down
2 changes: 1 addition & 1 deletion yepcord/rest_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import sys

from json import dumps as jdumps

from quart import Quart, request, Response
Expand Down
1 change: 1 addition & 0 deletions yepcord/rest_api/models/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ def validate_title(cls, value: str):
raise EmbedErr(makeEmbedError(27, f"title", {"length": "256"}))
return value

# noinspection PyUnusedLocal
@field_validator("type")
def validate_type(cls, value: Optional[str]):
return "rich"
Expand Down
4 changes: 2 additions & 2 deletions yepcord/rest_api/models/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ class AppAuthorizeGetQs(BaseModel):
client_id: Optional[int] = None
scope: Optional[str] = None

def __init__(self, *args, **kwargs):
def __init__(self, **kwargs):
if "client_id" not in kwargs or not kwargs.get("client_id", "").strip():
raise InvalidDataErr(400, Errors.make(50035, {"client_id": {
"code": "BASE_TYPE_REQUIRED", "message": "This field is required"
}}))
super().__init__(*args, **kwargs)
super().__init__(**kwargs)


class AppAuthorizePostQs(BaseModel):
Expand Down
1 change: 1 addition & 0 deletions yepcord/rest_api/routes/guilds.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ async def delete_role(user: User = DepUser, guild: Guild = DepGuild, member: Gui
return "", 204


# noinspection PyUnusedLocal
@guilds.get("/<int:guild>/roles/<int:role>/connections/configuration", allow_bots=True)
async def get_connections_configuration(role: int, member: GuildMember = DepGuildMember):
await member.checkPermission(GuildPermissions.MANAGE_ROLES)
Expand Down
5 changes: 5 additions & 0 deletions yepcord/rest_api/routes/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ async def api_outboundpromotions():
return []


# noinspection PyUnusedLocal
@other.get("/api/v9/users/@me/applications/<aid>/entitlements")
async def api_users_me_applications_id_entitlements(aid):
return []
Expand Down Expand Up @@ -187,6 +188,7 @@ async def api_users_me_settingsproto_3():
return {"settings": ""}


# noinspection PyUnusedLocal
@other.route("/api/v9/users/@me/settings-proto/<int:t>", methods=["GET", "PATCH"])
async def api_users_me_settingsproto_type(t):
raise InvalidDataErr(400, Errors.make(50035, {"type": {
Expand All @@ -196,16 +198,19 @@ async def api_users_me_settingsproto_type(t):
}}))


# noinspection PyUnusedLocal
@other.get("/api/v9/applications/<int:app_id>/skus")
async def application_skus(app_id: int):
return []


# noinspection PyUnusedLocal
@other.get("/api/v9/applications/<int:app_id>/subscription-group-listings")
async def application_sub_group_list(app_id: int):
return {"items": []}


# noinspection PyUnusedLocal
@other.get("/api/v9/applications/<int:app_id>/listings")
async def application_listings(app_id: int):
return []
Expand Down
1 change: 1 addition & 0 deletions yepcord/rest_api/routes/teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
teams = YBlueprint('teams', __name__)


# noinspection PyUnusedLocal
@teams.get("/", strict_slashes=False)
async def get_teams(user: User = DepUser):
return []
2 changes: 1 addition & 1 deletion yepcord/rest_api/routes/users_me.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ async def get_backup_codes(data: MfaCodesVerification, user: User = DepUser):
}}))
reg = data.regenerate
await getCore().verifyUserMfaNonce(user, nonce, reg)
if await getCore().mfaNonceToCode(user, nonce) != key:
if await getCore().mfaNonceToCode(nonce) != key:
raise InvalidDataErr(400, Errors.make(60011))
if reg:
codes = ["".join([choice('abcdefghijklmnopqrstuvwxyz0123456789') for _ in range(8)]) for _ in range(10)]
Expand Down
2 changes: 1 addition & 1 deletion yepcord/rest_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import yepcord.yepcord.models as models
from ..yepcord.classes.captcha import Captcha
from ..yepcord.config import Config
from ..yepcord.ctx import Ctx, getCore, getCDNStorage
from ..yepcord.ctx import getCore, getCDNStorage
from ..yepcord.enums import MessageType
from ..yepcord.errors import Errors, InvalidDataErr
from ..yepcord.models import Session, User, Channel, Attachment, Authorization, Bot, Webhook, Message
Expand Down
2 changes: 1 addition & 1 deletion yepcord/rest_api/y_blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from fast_depends import inject
from flask.sansio.scaffold import T_route, setupmethod
from quart import Blueprint, g
from quart_schema import validate_request, DataSource, validate_querystring
from quart_schema import validate_request, validate_querystring

validate_funcs = {"body": validate_request, "qs": validate_querystring}

Expand Down
1 change: 1 addition & 0 deletions yepcord/yepcord/classes/gifs.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ class GifSuggestion(_J):
time: int


# noinspection PyTestUnpassedFixture
class Gifs(Singleton):
def __init__(self, key: str = None, keep_searches: int = 100):
self._key = key
Expand Down
15 changes: 9 additions & 6 deletions yepcord/yepcord/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,9 @@ async def getChannelMessagesCount(self, channel: Channel) -> int:

async def getPrivateChannels(self, user: User, with_hidden: bool = False) -> list[Channel]:
channels = await Channel.filter(recipients__id=user.id).select_related("owner").all()
channels = [channel for channel in channels if not await self.isDmChannelHidden(user, channel)]
channels = [
channel for channel in channels if not with_hidden and not await self.isDmChannelHidden(user, channel)
]
return [await self.setLastMessageIdForChannel(channel) for channel in channels]

async def getChannelMessages(self, channel: Channel, limit: int, before: int = 0, after: int = 0) -> list[Message]:
Expand Down Expand Up @@ -430,15 +432,15 @@ async def changeUserEmail(self, user: User, email: str) -> None:
await user.update(email=email, verified=False)

async def sendMfaChallengeEmail(self, user: User, nonce: str) -> None:
code = await self.mfaNonceToCode(user, nonce)
code = await self.mfaNonceToCode(nonce)
await EmailMsg(user.email,
f"Your one-time verification key is {code}",
f"It looks like you're trying to view your account's backup codes.\n"
f"This verification key expires in 10 minutes. This key is extremely sensitive, treat it like a "
f"password and do not share it with anyone.\n"
f"Enter it in the app to unlock your backup codes:\n{code}").send()

async def mfaNonceToCode(self, user: User, nonce: str) -> Optional[str]:
async def mfaNonceToCode(self, nonce: str) -> Optional[str]:
if not (payload := JWT.decode(nonce, self.key)):
return
token = JWT.encode({"code": payload["code"]}, self.key)
Expand Down Expand Up @@ -694,8 +696,9 @@ async def getGuildBan(self, guild: Guild, user_id: int) -> Optional[GuildMember]
async def getGuildBans(self, guild: Guild) -> list[GuildBan]:
return await GuildBan.filter(guild=guild).select_related("user", "guild").all()

async def bulkDeleteGuildMessagesFromBanned(self, guild: Guild, user_id: int, after_id: int) -> dict[
Channel, list[int]]:
async def bulkDeleteGuildMessagesFromBanned(
self, guild: Guild, user_id: int, after_id: int
) -> dict[Channel, list[int]]:
messages = await (Message.filter(guild=guild, author__id=user_id, id__gt=after_id).select_related("channel")
.limit(500).all())
result = {}
Expand Down Expand Up @@ -775,7 +778,7 @@ async def getGuildMembersGw(self, guild: Guild, query: str, limit: int, user_ids
# noinspection PyUnresolvedReferences
return await GuildMember.filter(
Q(guild=guild) &
(Q(nick__startswith=query) | Q(user__userdatas__username__istartswith=query)) #&
(Q(nick__startswith=query) | Q(user__userdatas__username__istartswith=query)) #&
#((GuildMember.user.id in user_ids) if user_ids else (GuildMember.user.id not in [0]))
).select_related("user").limit(limit).all()

Expand Down
2 changes: 1 addition & 1 deletion yepcord/yepcord/gateway_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async def dispatchSub(self, user_ids: list[int], guild_id: int = None, role_id:
"role_id": role_id,
})

async def dispatchUnsub(self, user_ids: list[int], guild_id: int = None, role_id: int = None, delete = False) -> None:
async def dispatchUnsub(self, user_ids: list[int], guild_id: int = None, role_id: int = None, delete=False) -> None:
await self.dispatchSys("unsub", {
"user_ids": user_ids,
"guild_id": guild_id,
Expand Down
2 changes: 1 addition & 1 deletion yepcord/yepcord/models/audit_log_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ async def role_delete(user: models.User, role: models.Role) -> AuditLogEntry:
@staticmethod
async def bot_add(user: models.User, guild: models.Guild, bot: models.User) -> AuditLogEntry:
return await AuditLogEntry.create(id=Snowflake.makeId(), guild=guild, user=user, target_id=bot.id,
action_type=AuditLogEntryType.BOT_ADD)
action_type=AuditLogEntryType.BOT_ADD)

@staticmethod
async def integration_create(user: models.User, guild: models.Guild, bot: models.User) -> AuditLogEntry:
Expand Down
2 changes: 1 addition & 1 deletion yepcord/yepcord/models/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ async def ds_json(self, user_id: int=None, with_ids: bool=True) -> dict:
}
elif self.type == ChannelType.GUILD_PUBLIC_THREAD:
message_count = await getCore().getChannelMessagesCount(self)
data = base_data | {
data: dict = base_data | {
"guild_id": str(self.guild.id),
"parent_id": str(self.parent.id) if self.parent else None,
"owner_id": str(self.owner.id),
Expand Down
4 changes: 2 additions & 2 deletions yepcord/yepcord/models/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ async def ds_json(self, user_id: int = None, search: bool = False) -> dict:
mdata = await member.data
data["mentions"].append(mdata.ds_json)
if self.type in (MessageType.RECIPIENT_ADD, MessageType.RECIPIENT_REMOVE):
if (userid := self.extra_data.get("user")) and (udata := await models.UserData.get_or_none(id=userid)
.select_related("user")):
if (userid := self.extra_data.get("user")) \
and (udata := await models.UserData.get_or_none(id=userid).select_related("user")):
data["mentions"].append(udata.ds_json)
if self.message_reference:
data["message_reference"] = {
Expand Down
1 change: 0 additions & 1 deletion yepcord/yepcord/models/userdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
from datetime import date, timedelta
from typing import Optional

from quart import g
from tortoise import fields
from tortoise.validators import MinValueValidator, MaxValueValidator

Expand Down
1 change: 1 addition & 0 deletions yepcord/yepcord/mq_broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ async def close(self) -> None:


class WsBroker:
# noinspection PyUnusedLocal
def __init__(self, url: str = "ws://127.0.0.1:5055", **kwargs):
self._connection: Optional[WebSocketClientProtocol] = None
self._url = url
Expand Down
10 changes: 6 additions & 4 deletions yepcord/yepcord/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,9 @@ async def _getResizeImage(self, paths: list[str], size: tuple[int, int], anim: b
await self._write(paths[0], data)
return data

async def _getImage(self, type: str, id: int, hash: str, size: int, fmt: str, def_size: int, size_f) -> Optional[
bytes]:
async def _getImage(
self, type: str, id: int, hash: str, size: int, fmt: str, def_size: int, size_f
) -> Optional[bytes]:
anim = hash.startswith("a_")
def_fmt = "gif" if anim else "png"
paths = [f"{hash}_{size}.{fmt}", f"{hash}_{def_size}.{fmt}", f"{hash}_{def_size}.{def_fmt}"]
Expand Down Expand Up @@ -341,8 +342,9 @@ async def _write(self, path: str, data: bytes) -> int:
def _getClient(self) -> FClient:
return FClient.context(self.host, user=self.user, password=self.password, port=self.port)

async def _getImage(self, type: str, id: int, hash: str, size: int, fmt: str, def_size: int, size_f) -> Optional[
bytes]:
async def _getImage(
self, type: str, id: int, hash: str, size: int, fmt: str, def_size: int, size_f
) -> Optional[bytes]:
async with self._getClient() as ftp:
self.session.set(ftp)
return await super()._getImage(type, id, hash, size, fmt, def_size, size_f)
Expand Down

0 comments on commit 42376be

Please sign in to comment.