Skip to content

Commit

Permalink
💄 auto fix by pre-commit hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
pre-commit-ci[bot] committed Dec 11, 2024
1 parent 1744e05 commit 6e18f02
Show file tree
Hide file tree
Showing 106 changed files with 2,381 additions and 927 deletions.
4 changes: 2 additions & 2 deletions extra_plugins/auto_agree.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from nonebot import on_request
from nonebot.log import logger
from nonebot.adapters.onebot.v11 import Bot
from nonebot.adapters.onebot.v11.event import GroupRequestEvent, FriendRequestEvent
from nonebot.adapters.onebot.v11.event import FriendRequestEvent, GroupRequestEvent
from nonebot.log import logger

friend_req = on_request(priority=5)

Expand Down
20 changes: 16 additions & 4 deletions nonebot_bison/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,19 @@

import nonebot_plugin_saa

from . import admin_page, bootstrap, config, platform, post, scheduler, send, sub_manager, theme, types, utils
from . import (
admin_page,
bootstrap,
config,
platform,
post,
scheduler,
send,
sub_manager,
theme,
types,
utils,
)
from .plugin_config import PlugConfig, plugin_config

__help__version__ = "0.8.2"
Expand Down Expand Up @@ -36,12 +48,12 @@
"admin_page",
"bootstrap",
"config",
"sub_manager",
"platform",
"post",
"scheduler",
"send",
"platform",
"sub_manager",
"theme",
"types",
"utils",
"theme",
]
26 changes: 19 additions & 7 deletions nonebot_bison/admin_page/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,19 @@


def init_fastapi(driver: "Driver"):
import socketio
from fastapi.applications import FastAPI
from fastapi.staticfiles import StaticFiles
import socketio

sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
socket_app = socketio.ASGIApp(sio, socketio_path="socket")

class SinglePageApplication(StaticFiles):
def __init__(self, directory: os.PathLike, index="index.html"):
self.index = index
super().__init__(directory=directory, packages=None, html=True, check_dir=True)
super().__init__(
directory=directory, packages=None, html=True, check_dir=True
)

def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]:
full_path, stat_res = super().lookup_path(path)
Expand All @@ -47,7 +49,9 @@ def register_router_fastapi(driver: "Driver", socketio):
description="nonebot-bison webui and api",
)
nonebot_app.include_router(api_router)
nonebot_app.mount("/", SinglePageApplication(directory=static_path), name="bison-frontend")
nonebot_app.mount(
"/", SinglePageApplication(directory=static_path), name="bison-frontend"
)

app = driver.server_app
app.mount("/bison", nonebot_app, "nonebot-bison")
Expand All @@ -57,12 +61,18 @@ def register_router_fastapi(driver: "Driver", socketio):
port = driver.config.port
if host in ["0.0.0.0", "127.0.0.1"]:
host = "localhost"
logger.opt(colors=True).info(f"Nonebot Bison frontend will be running at: <b><u>http://{host}:{port}/bison</u></b>")
logger.opt(colors=True).info("该页面不能被直接访问,请私聊bot <b><u>后台管理</u></b> 以获取可访问地址")
logger.opt(colors=True).info(
f"Nonebot Bison frontend will be running at: <b><u>http://{host}:{port}/bison</u></b>"
)
logger.opt(colors=True).info(
"该页面不能被直接访问,请私聊bot <b><u>后台管理</u></b> 以获取可访问地址"
)


def register_get_token_handler():
get_token = on_command("后台管理", rule=to_me(), priority=5, aliases={"管理后台"}, block=True)
get_token = on_command(
"后台管理", rule=to_me(), priority=5, aliases={"管理后台"}, block=True
)

@get_token.handle()
async def send_token(bot: "Bot", event: PrivateMessageEvent, state: T_State):
Expand Down Expand Up @@ -92,4 +102,6 @@ def get_fastapi_driver() -> "Driver | None":
else:
logger.warning("your driver is not fastapi, webui feature will be disabled")
else:
logger.warning("Frontend file not found, please compile it or use docker or pypi version")
logger.warning(
"Frontend file not found, please compile it or use docker or pypi version"
)
63 changes: 48 additions & 15 deletions nonebot_bison/admin_page/api.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
from typing import cast

import nonebot
from fastapi import status
from fastapi.exceptions import HTTPException
from fastapi.param_functions import Depends
from fastapi.routing import APIRouter
from fastapi.security.oauth2 import OAuth2PasswordBearer
import nonebot
from nonebot_plugin_saa import TargetQQGroup
from nonebot_plugin_saa.auto_select_bot import get_bot

from nonebot_bison.apis import check_sub_target
from nonebot_bison.config import NoSuchSubscribeException, NoSuchTargetException, NoSuchUserException, config
from nonebot_bison.config import (
NoSuchSubscribeException,
NoSuchTargetException,
NoSuchUserException,
config,
)
from nonebot_bison.config.db_config import SubscribeDupException
from nonebot_bison.platform import platform_manager
from nonebot_bison.scheduler import scheduler_dict
from nonebot_bison.types import Target as T_Target
from nonebot_bison.types import WeightConfig
from nonebot_bison.utils.get_bot import get_groups
from nonebot_bison.utils.site import CookieClientManager, is_cookie_client_manager, site_manager
from nonebot_bison.utils.site import (
CookieClientManager,
is_cookie_client_manager,
site_manager,
)

from .jwt import load_jwt, pack_jwt
from .token_manager import token_manager
Expand Down Expand Up @@ -48,7 +57,9 @@ async def get_jwt_obj(token: str = Depends(oath_scheme)):
return obj


async def check_group_permission(groupNumber: int, token_obj: dict = Depends(get_jwt_obj)):
async def check_group_permission(
groupNumber: int, token_obj: dict = Depends(get_jwt_obj)
):
groups = token_obj["groups"]
for group in groups:
if int(groupNumber) == group["id"]:
Expand All @@ -75,7 +86,9 @@ async def get_global_conf() -> GlobalConf:
)
site_res = {}
for site_name, site in site_manager.items():
site_res[site_name] = SiteConfig(name=site_name, enable_cookie=is_cookie_client_manager(site.client_mgr))
site_res[site_name] = SiteConfig(
name=site_name, enable_cookie=is_cookie_client_manager(site.client_mgr)
)
return GlobalConf(platformConf=platform_res, siteConf=site_res)


Expand Down Expand Up @@ -176,7 +189,9 @@ async def add_group_sub(groupNumber: int, req: AddSubscribeReq) -> StatusResp:
@router.delete("/subs", dependencies=[Depends(check_group_permission)])
async def del_group_sub(groupNumber: int, platformName: str, target: str):
try:
await config.del_subscribe(TargetQQGroup(group_id=groupNumber), target, platformName)
await config.del_subscribe(
TargetQQGroup(group_id=groupNumber), target, platformName
)
except (NoSuchUserException, NoSuchSubscribeException):
raise HTTPException(status.HTTP_400_BAD_REQUEST, "no such user or subscribe")
return StatusResp(ok=True, msg="")
Expand Down Expand Up @@ -204,16 +219,22 @@ async def get_weight_config():


@router.put("/weight", dependencies=[Depends(check_is_superuser)])
async def update_weigth_config(platformName: str, target: str, weight_config: WeightConfig):
async def update_weigth_config(
platformName: str, target: str, weight_config: WeightConfig
):
try:
await config.update_time_weight_config(T_Target(target), platformName, weight_config)
await config.update_time_weight_config(
T_Target(target), platformName, weight_config
)
except NoSuchTargetException:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "no such subscribe")
return StatusResp(ok=True, msg="")


@router.get("/cookie", dependencies=[Depends(check_is_superuser)])
async def get_cookie(site_name: str | None = None, target: str | None = None) -> list[Cookie]:
async def get_cookie(
site_name: str | None = None, target: str | None = None
) -> list[Cookie]:
cookies_in_db = await config.get_cookie(site_name, is_anonymous=False)
return [
Cookie(
Expand All @@ -234,7 +255,9 @@ async def get_cookie(site_name: str | None = None, target: str | None = None) ->

@router.post("/cookie", dependencies=[Depends(check_is_superuser)])
async def add_cookie(site_name: str, content: str) -> StatusResp:
client_mgr = cast(CookieClientManager, scheduler_dict[site_manager[site_name]].client_mgr)
client_mgr = cast(
CookieClientManager, scheduler_dict[site_manager[site_name]].client_mgr
)
await client_mgr.add_user_cookie(content)
return StatusResp(ok=True, msg="")

Expand All @@ -247,14 +270,18 @@ async def delete_cookie_by_id(cookie_id: int) -> StatusResp:

@router.get("/cookie_target", dependencies=[Depends(check_is_superuser)])
async def get_cookie_target(
site_name: str | None = None, target: str | None = None, cookie_id: int | None = None
site_name: str | None = None,
target: str | None = None,
cookie_id: int | None = None,
) -> list[CookieTarget]:
cookie_targets = await config.get_cookie_target()
# TODO: filter in SQL
return [
CookieTarget(
target=Target(
platform_name=x.target.platform_name, target_name=x.target.target_name, target=x.target.target
platform_name=x.target.platform_name,
target_name=x.target.target_name,
target=x.target.target,
),
cookie_id=x.cookie.id,
)
Expand All @@ -266,20 +293,26 @@ async def get_cookie_target(


@router.post("/cookie_target", dependencies=[Depends(check_is_superuser)])
async def add_cookie_target(platform_name: str, target: T_Target, cookie_id: int) -> StatusResp:
async def add_cookie_target(
platform_name: str, target: T_Target, cookie_id: int
) -> StatusResp:
await config.add_cookie_target(target, platform_name, cookie_id)
return StatusResp(ok=True, msg="")


@router.delete("/cookie_target", dependencies=[Depends(check_is_superuser)])
async def del_cookie_target(platform_name: str, target: T_Target, cookie_id: int) -> StatusResp:
async def del_cookie_target(
platform_name: str, target: T_Target, cookie_id: int
) -> StatusResp:
await config.delete_cookie_target(target, platform_name, cookie_id)
return StatusResp(ok=True, msg="")


@router.post("/cookie/validate", dependencies=[Depends(check_is_superuser)])
async def get_cookie_valid(site_name: str, content: str) -> StatusResp:
client_mgr = cast(CookieClientManager, scheduler_dict[site_manager[site_name]].client_mgr)
client_mgr = cast(
CookieClientManager, scheduler_dict[site_manager[site_name]].client_mgr
)
if await client_mgr.validate_cookie(content):
return StatusResp(ok=True, msg="")
else:
Expand Down
6 changes: 4 additions & 2 deletions nonebot_bison/admin_page/token_manager.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from datetime import timedelta
import random
import string
from datetime import timedelta

from expiringdictx import ExpiringDict


class TokenManager:
def __init__(self):
self.token_manager = ExpiringDict[str, tuple](capacity=100, default_age=timedelta(minutes=10))
self.token_manager = ExpiringDict[str, tuple](
capacity=100, default_age=timedelta(minutes=10)
)

def get_user(self, token: str) -> tuple | None:
res = self.token_manager.get(token)
Expand Down
4 changes: 3 additions & 1 deletion nonebot_bison/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ def _has_table(conn, table_name):
if await conn.run_sync(_has_table, "nonebot_bison_alembic_version"):
await conn.execute(text("drop table nonebot_bison_alembic_version"))

await conn.execute(text("alter table alembic_version rename to nonebot_bison_alembic_version"))
await conn.execute(
text("alter table alembic_version rename to nonebot_bison_alembic_version")
)


@post_db_init
Expand Down
2 changes: 1 addition & 1 deletion nonebot_bison/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from nonebot.compat import PYDANTIC_V2
from pydantic import BaseModel

__all__ = ("model_validator", "model_rebuild")
__all__ = ("model_rebuild", "model_validator")


if PYDANTIC_V2:
Expand Down
46 changes: 31 additions & 15 deletions nonebot_bison/config/config_legacy.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from collections import defaultdict
from datetime import datetime
import json
import os
from collections import defaultdict
from datetime import datetime
from os import path
from pathlib import Path
from typing import Literal, TypedDict
Expand Down Expand Up @@ -93,7 +93,9 @@ def _do_init(self):
else:
self.available = False

def add_subscribe(self, user, user_type, target, target_name, target_type, cats, tags):
def add_subscribe(
self, user, user_type, target, target_name, target_type, cats, tags
):
user_query = Query()
query = (user_query.user == user) & (user_query.user_type == user_type)
if user_data := self.user_target.get(query):
Expand Down Expand Up @@ -131,7 +133,9 @@ def add_subscribe(self, user, user_type, target, target_name, target_type, cats,

def list_subscribe(self, user, user_type) -> list[SubscribeContent]:
query = Query()
if user_sub := self.user_target.get((query.user == user) & (query.user_type == user_type)):
if user_sub := self.user_target.get(
(query.user == user) & (query.user_type == user_type)
):
assert not isinstance(user_sub, list)
return user_sub["subs"]
return []
Expand All @@ -154,7 +158,9 @@ def del_subscribe(self, user, user_type, target, target_type):
return
raise NoSuchSubscribeException()

def update_subscribe(self, user, user_type, target, target_name, target_type, cats, tags):
def update_subscribe(
self, user, user_type, target, target_name, target_type, cats, tags
):
user_query = Query()
query = (user_query.user == user) & (user_query.user_type == user_type)
if user_data := self.user_target.get(query):
Expand All @@ -180,8 +186,14 @@ def update_subscribe(self, user, user_type, target, target_name, target_type, ca

def update_send_cache(self):
res = {target_type: defaultdict(list) for target_type in supported_target_type}
cat_res = {target_type: defaultdict(lambda: defaultdict(list)) for target_type in supported_target_type}
tag_res = {target_type: defaultdict(lambda: defaultdict(list)) for target_type in supported_target_type}
cat_res = {
target_type: defaultdict(lambda: defaultdict(list))
for target_type in supported_target_type
}
tag_res = {
target_type: defaultdict(lambda: defaultdict(list))
for target_type in supported_target_type
}
# res = {target_type: defaultdict(lambda: defaultdict(list)) for target_type in supported_target_type}
to_del = []
for user in self.user_target.all():
Expand All @@ -196,18 +208,22 @@ def update_send_cache(self):
}
)
continue
res[sub["target_type"]][sub["target"]].append(User(user["user"], user["user_type"]))
cat_res[sub["target_type"]][sub["target"]]["{}-{}".format(user["user_type"], user["user"])] = sub[
"cats"
]
tag_res[sub["target_type"]][sub["target"]]["{}-{}".format(user["user_type"], user["user"])] = sub[
"tags"
]
res[sub["target_type"]][sub["target"]].append(
User(user["user"], user["user_type"])
)
cat_res[sub["target_type"]][sub["target"]][
"{}-{}".format(user["user_type"], user["user"])
] = sub["cats"]
tag_res[sub["target_type"]][sub["target"]][
"{}-{}".format(user["user_type"], user["user"])
] = sub["tags"]
self.target_user_cache = res
self.target_user_cat_cache = cat_res
self.target_user_tag_cache = tag_res
for target_type in self.target_user_cache:
self.target_list[target_type] = list(self.target_user_cache[target_type].keys())
self.target_list[target_type] = list(
self.target_user_cache[target_type].keys()
)

logger.info(f"Deleting {to_del}")
for d in to_del:
Expand Down
Loading

0 comments on commit 6e18f02

Please sign in to comment.