Skip to content

Commit

Permalink
🚑 重新迁移
Browse files Browse the repository at this point in the history
  • Loading branch information
KomoriDev committed Aug 1, 2024
1 parent f5583bd commit 07fc34c
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 22 deletions.
26 changes: 14 additions & 12 deletions nonebot_plugin_wakatime/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
from nonebot.rule import Rule
from nonebot.log import logger
from httpx import ConnectTimeout
from nonebot.internal.adapter import Event
from nonebot.plugin import PluginMetadata, inherit_supported_adapters

require("nonebot_plugin_orm")
require("nonebot_plugin_user")
require("nonebot_plugin_alconna")
require("nonebot_plugin_htmlrender")
from nonebot_plugin_orm import async_scoped_session
Expand Down Expand Up @@ -73,7 +73,7 @@ def _rule() -> bool:


@wakatime.assign("$main")
async def _(event: Event, target: Match[At | int]):
async def _(user_session: UserSession, target: Match[At | int]):
if target.available:
if isinstance(target.result, At):
target_name = "他"
Expand All @@ -84,7 +84,7 @@ async def _(event: Event, target: Match[At | int]):
target_id = (await get_user(user_session.platform, target_platform_id)).id
else:
target_name = "你"
target_id = event.get_user_id()
target_id = user_session.user_id

try:
user_info_task = API.get_user_info(target_id)
Expand Down Expand Up @@ -114,10 +114,13 @@ async def _(event: Event, target: Match[At | int]):

@wakatime.assign("bind")
async def _(
code: Match[str], event: Event, msg_target: MsgTarget, session: async_scoped_session
code: Match[str],
user_session: UserSession,
msg_target: MsgTarget,
session: async_scoped_session,
):

if await session.get(User, event.get_user_id()):
if await session.get(User, user_session.user_id):
await UniMessage("已绑定过 wakatime 账号").finish(at_sender=True)

if not msg_target.private:
Expand All @@ -140,30 +143,29 @@ async def _(
if resp.status_code == 200:
parsed_data = parse_qs(resp.text)
user = User(
user_id=event.get_user_id(),
platform=msg_target.adapter,
id=user_session.user_id,
access_token=parsed_data["access_token"][0],
)
session.add(user)
await session.commit()
await UniMessage("绑定成功").finish(at_sender=True)

logger.error(f"用户 {event.get_user_id()} 绑定失败。状态码:{resp.status_code}")
logger.error(f"用户 {user_session.user_id} 绑定失败。状态码:{resp.status_code}")
await UniMessage("绑定失败").finish(at_sender=True)


@wakatime.assign("revoke")
async def _(event: Event, session: async_scoped_session):
if not (user := await session.get(User, event.get_user_id())):
async def _(user_session: UserSession, session: async_scoped_session):
if not (user := await session.get(User, user_session.user_id)):
await UniMessage.text(
"还没有绑定 Wakatime 账号!请私聊我并使用 /wakatime bind 命令进行绑定"
).finish(at_sender=True)

resp = await API.revoke_user_token(event.get_user_id())
resp = await API.revoke_user_token(user_session.user_id)
if resp.status_code == 200:
await session.delete(user)
await session.commit()
await UniMessage("已解绑").finish(at_sender=True)

logger.error(f"用户 {event.get_user_id()} 解绑失败。状态码:{resp.status_code}")
logger.error(f"用户 {user_session.user_id} 解绑失败。状态码:{resp.status_code}")
await UniMessage("解绑失败").finish(at_sender=True)
14 changes: 7 additions & 7 deletions nonebot_plugin_wakatime/apis/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@

class API:

_access_token_cache: dict[str, str] = {}
_access_token_cache: dict[int, str] = {}

@classmethod
async def get_access_token(cls, user_id: str) -> str:
async def get_access_token(cls, user_id: int) -> str:
"""Get the access token from database"""
if user_id in cls._access_token_cache:
return cls._access_token_cache[user_id]

session = get_session()
async with session.begin():
stmt = select(User).where(User.user_id == user_id)
stmt = select(User).where(User.id == user_id)
user = (await session.execute(stmt)).scalar()

if not user:
Expand Down Expand Up @@ -58,7 +58,7 @@ async def bind_user(cls, code: str) -> Response:
return response

@classmethod
async def revoke_user_token(cls, user_id: str) -> Response:
async def revoke_user_token(cls, user_id: int) -> Response:
"""Invalidate a secret access token"""
access_token = await cls.get_access_token(user_id)
async with httpx.AsyncClient() as client:
Expand All @@ -74,7 +74,7 @@ async def revoke_user_token(cls, user_id: str) -> Response:
return response

@classmethod
async def get_user_info(cls, user_id: str) -> Users:
async def get_user_info(cls, user_id: int) -> Users:
"""Get user's information"""
access_token = await cls.get_access_token(user_id)
async with httpx.AsyncClient() as client:
Expand All @@ -86,7 +86,7 @@ async def get_user_info(cls, user_id: str) -> Users:

@classmethod
async def get_user_stats(
cls, user_id: str, scope: TimeScope = "last_7_days"
cls, user_id: int, scope: TimeScope = "last_7_days"
) -> Stats:
"""Get user's coding activity.
Expand All @@ -103,7 +103,7 @@ async def get_user_stats(
return Stats(**(response.json()["data"]))

@classmethod
async def get_all_time_since_today(cls, user_id: str) -> str:
async def get_all_time_since_today(cls, user_id: int) -> str:
"""Get the total time logged since account created."""
assess_token = await cls.get_access_token(user_id)
async with httpx.AsyncClient() as client:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""adapt user plugin
迁移 ID: 263d60026863
父迁移:
创建时间: 2024-08-01 22:42:18.427022
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "263d60026863"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade(name: str = "") -> None:
if name:
return
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("wakatime", schema=None) as batch_op:
batch_op.add_column(sa.Column("id", sa.Integer(), nullable=False))
batch_op.drop_column("platform")
batch_op.drop_column("user_id")

# ### end Alembic commands ###


def downgrade(name: str = "") -> None:
if name:
return
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("wakatime", schema=None) as batch_op:
batch_op.add_column(sa.Column("user_id", sa.VARCHAR(), nullable=False))
batch_op.add_column(sa.Column("platform", sa.VARCHAR(), nullable=False))
batch_op.drop_column("id")

# ### end Alembic commands ###
Empty file.
4 changes: 1 addition & 3 deletions nonebot_plugin_wakatime/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ class User(Model):

__tablename__ = "wakatime"

user_id: Mapped[str] = mapped_column(primary_key=True)
id: Mapped[int] = mapped_column(primary_key=True)
"""User ID"""
platform: Mapped[str]
"""User Account Platform"""
access_token: Mapped[str]
"""Wakatime Access Token"""

0 comments on commit 07fc34c

Please sign in to comment.