Skip to content

Commit

Permalink
分离repo层
Browse files Browse the repository at this point in the history
  • Loading branch information
ssttkkl committed Nov 26, 2023
1 parent 3ab9ff3 commit 118a94c
Show file tree
Hide file tree
Showing 4 changed files with 242 additions and 160 deletions.
27 changes: 27 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
default_install_hook_types: [pre-commit, prepare-commit-msg]
ci:
autofix_commit_msg: ":rotating_light: auto fix by pre-commit hooks"
autofix_prs: true
autoupdate_branch: master
autoupdate_schedule: monthly
autoupdate_commit_msg: ":arrow_up: auto update by pre-commit hooks"
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.292
hooks:
- id: ruff
args: [--fix]
stages: [commit]

- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
stages: [commit]

- repo: https://github.com/psf/black
rev: 23.9.1
hooks:
- id: black
stages: [commit]

163 changes: 160 additions & 3 deletions nonebot_plugin_nagabus/data/naga.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import json
from enum import IntEnum
from typing import Optional
from datetime import datetime
from datetime import datetime, timezone

from sqlalchemy import ForeignKey
from nonebot import logger
from sqlalchemy import ForeignKey, select, update
from sqlalchemy.orm import Mapped, relationship, mapped_column

from .base import SqlModel
from .utils import UTCDateTime
from ..naga.model import NagaOrderStatus
from .session import get_session
from ..naga.model import NagaReport, NagaGameRule, NagaOrderStatus


class NagaOrderSource(IntEnum):
Expand Down Expand Up @@ -49,3 +52,157 @@ class MajsoulOrderOrm(SqlModel):
passive_deletes=True,
lazy="joined",
)


async def get_orders(t_begin: datetime, t_end: datetime) -> list[NagaOrderOrm]:
sess = get_session()
stmt = select(NagaOrderOrm).where(
NagaOrderOrm.create_time >= t_begin,
NagaOrderOrm.create_time < t_end,
NagaOrderOrm.status == NagaOrderStatus.ok,
)
return list((await sess.execute(stmt)).scalars())


async def get_local_majsoul_order(
majsoul_uuid: str, kyoku: int, honba: int, model_type: str
) -> Optional[NagaOrderOrm]:
sess = get_session()
stmt = select(MajsoulOrderOrm).where(
MajsoulOrderOrm.paipu_uuid == majsoul_uuid,
MajsoulOrderOrm.kyoku == kyoku,
MajsoulOrderOrm.honba == honba,
MajsoulOrderOrm.model_type == model_type,
)

order_orm: Optional[MajsoulOrderOrm] = (
await sess.execute(stmt)
).scalar_one_or_none()
if order_orm is not None:
if (
order_orm.order.status == NagaOrderStatus.ok
or datetime.now(tz=timezone.utc).timestamp()
- order_orm.order.update_time.timestamp()
< 90
):
return order_orm.order
else: # 超过90s仍未分析完成则删除重来
logger.opt(colors=True).info(
f"Delete majsoul paipu <y>{majsoul_uuid} "
f"(kyoku: {kyoku}, honba: {honba})</y> "
f"analyze order: {order_orm.naga_haihu_id}, "
f"because it takes over 90 seconds and still not done"
)
await sess.delete(order_orm.order)
await sess.delete(order_orm)
await sess.commit()
return None


async def new_local_majsoul_order(
haihu_id: str,
customer_id: int,
majsoul_uuid: str,
kyoku: int,
honba: int,
model_type: str,
):
sess = get_session()
order_orm = NagaOrderOrm(
haihu_id=haihu_id,
customer_id=customer_id,
cost_np=10,
source=NagaOrderSource.majsoul,
model_type=model_type,
status=NagaOrderStatus.analyzing,
create_time=datetime.now(tz=timezone.utc),
update_time=datetime.now(tz=timezone.utc),
)

majsoul_order_orm = MajsoulOrderOrm(
naga_haihu_id=haihu_id,
paipu_uuid=majsoul_uuid,
kyoku=kyoku,
honba=honba,
model_type=model_type,
order=order_orm,
)

sess.add(order_orm)
sess.add(majsoul_order_orm)
await sess.commit()


async def update_local_majsoul_order(haihu_id: str, report: NagaReport):
sess = get_session()
stmt = (
update(NagaOrderOrm)
.where(NagaOrderOrm.haihu_id == haihu_id)
.values(
status=NagaOrderStatus.ok,
naga_report=json.dumps(report),
update_time=datetime.now(timezone.utc),
)
)
await sess.execute(stmt)
await sess.commit()


async def get_local_order(haihu_id: str, model_type: str) -> Optional[NagaOrderOrm]:
sess = get_session()
stmt = select(NagaOrderOrm).where(
NagaOrderOrm.haihu_id == haihu_id,
NagaOrderOrm.model_type == model_type,
)

order_orm: Optional[NagaOrderOrm] = (await sess.execute(stmt)).scalar_one_or_none()
if order_orm is not None:
if (
order_orm.status == NagaOrderStatus.ok
or datetime.now(tz=timezone.utc).timestamp()
- order_orm.update_time.timestamp()
< 300
):
return order_orm
else: # 超过90s仍未分析完成则删除重来
logger.opt(colors=True).info(
f"Delete tenhou paipu <y>{haihu_id}</y> analyze order "
f"because it takes over 90 seconds and still not done"
)
await sess.delete(order_orm)
await sess.commit()
return None


async def new_local_order(
haihu_id: str, customer_id: int, rule: NagaGameRule, model_type: str
):
sess = get_session()
order_orm = NagaOrderOrm(
haihu_id=haihu_id,
customer_id=customer_id,
cost_np=50 if rule == NagaGameRule.hanchan else 30,
source=NagaOrderSource.tenhou,
model_type=model_type,
status=NagaOrderStatus.analyzing,
create_time=datetime.now(tz=timezone.utc),
update_time=datetime.now(tz=timezone.utc),
)

sess.add(order_orm)
await sess.commit()


async def update_local_order(haihu_id: str, report: NagaReport):
sess = get_session()
stmt = (
update(NagaOrderOrm)
.where(NagaOrderOrm.haihu_id == haihu_id)
.values(
status=NagaOrderStatus.ok,
naga_report=json.dumps(report),
update_time=datetime.now(timezone.utc),
)
)
await sess.execute(stmt)
await sess.commit()
33 changes: 19 additions & 14 deletions nonebot_plugin_nagabus/matchers/naga_analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
from nonebot import on_command
from nonebot.params import CommandArg
from nonebot.internal.params import Depends
from nonebot.internal.matcher import Matcher
from nonebot_plugin_saa import MessageFactory
from ssttkkl_nonebot_utils.integer import decode_integer
from nonebot_plugin_session import Session, extract_session
from ssttkkl_nonebot_utils.errors.errors import BadRequestError
from ssttkkl_nonebot_utils.nonebot import default_command_start
from ssttkkl_nonebot_utils.interceptor.handle_error import handle_error
from nonebot_plugin_access_control_api.service.contextvars import (
current_rate_limit_token,
)
from ssttkkl_nonebot_utils.interceptor.with_graceful_shutdown import (
with_graceful_shutdown,
)
Expand All @@ -26,18 +28,23 @@
analyze_srv = ac.create_subservice("analyze")


async def analyze_majsoul(
matcher: Matcher, session: Session, uuid: str, kyoku: int, honba: int
):
async def _retire_token():
try:
token = current_rate_limit_token.get()
await token.retire()
except LookupError:
pass


async def analyze_majsoul(session: Session, uuid: str, kyoku: int, honba: int):
try:
report, cost_np = await naga.analyze_majsoul(uuid, kyoku, honba, session)
await MessageFactory(
f"https://naga.dmv.nico/htmls/{report.report_id}.html?tw=0"
).send(reply=True)

if cost_np == 0:
token = matcher.state["ac_token"]
await token.retire()
await _retire_token()
await MessageFactory("由于此前已解析过该局,本次解析消耗0NP").send(reply=True)
else:
await MessageFactory(f"本次解析消耗{cost_np}NP").send(reply=True)
Expand All @@ -54,15 +61,14 @@ async def analyze_majsoul(
raise BadRequestError(f"请输入正确的场次与本场({'、'.join(kyoku_honba)})") from e


async def analyze_tenhou(matcher: Matcher, session: Session, haihu_id: str, seat: int):
async def analyze_tenhou(session: Session, haihu_id: str, seat: int):
report, cost_np = await naga.analyze_tenhou(haihu_id, seat, session)
await MessageFactory(
f"https://naga.dmv.nico/htmls/{report.report_id}.html?tw={seat}"
).send(reply=True)

if cost_np == 0:
token = matcher.state["ac_token"]
await token.retire()
await _retire_token()
await MessageFactory("由于此前已解析过该局,本次解析消耗0NP").send(reply=True)
else:
await MessageFactory(f"本次解析消耗{cost_np}NP").send(reply=True)
Expand All @@ -85,7 +91,7 @@ async def analyze_tenhou(matcher: Matcher, session: Session, haihu_id: str, seat
@analyze_srv.patch_handler(retire_on_throw=True)
@with_handling_reaction()
async def naga_analyze(
matcher: Matcher, cmd_args=CommandArg(), session: Session = Depends(extract_session)
cmd_args=CommandArg(), session: Session = Depends(extract_session)
):
args = cmd_args.extract_plain_text().split(" ")
if "maj-soul" in args[0]:
Expand Down Expand Up @@ -115,9 +121,8 @@ async def naga_analyze(
except ValueError:
pass

await analyze_majsoul(
matcher, session, uuid, kyoku, honba
) # 如果未指定场次本场,则让其发送该局的场次本场信息
# 如果未指定场次本场,则让其发送该局的场次本场信息
await analyze_majsoul(session, uuid, kyoku, honba)
elif "tenhou" in args[0]:
tenhou_url = args[0].strip()

Expand All @@ -129,7 +134,7 @@ async def naga_analyze(
if "tw" in tenhou_query and len(tenhou_query["tw"]) > 0:
seat = int(tenhou_query["tw"][0])

await analyze_tenhou(matcher, session, haihu_id, seat)
await analyze_tenhou(session, haihu_id, seat)
else:
await MessageFactory(
"用法:\n"
Expand Down
Loading

0 comments on commit 118a94c

Please sign in to comment.