This commit is contained in:
felinae98 2022-08-07 23:12:18 +08:00
parent b8af6d0024
commit ea928bf3fc
No known key found for this signature in database
GPG Key ID: 00C8B010587FF610
12 changed files with 149 additions and 27 deletions

View File

@ -2,12 +2,14 @@ import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import authReducer from '../features/auth/authSlice';
import globalConfReducer from '../features/globalConf/globalConfSlice';
import { subscribeApi } from '../features/subsribeConfigManager/subscribeConfigSlice';
import { weightApi } from '../features/weightConfig/weightConfigSlice';
export const store = configureStore({
reducer: {
auth: authReducer,
globalConf: globalConfReducer,
[subscribeApi.reducerPath]: subscribeApi.reducer,
[weightApi.reducerPath]: weightApi.reducer,
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(subscribeApi.middleware),
});

View File

@ -1,18 +1,13 @@
import React from 'react';
import { useGetSubsQuery, useDeleteSubMutation } from './subscribeConfigSlice';
import { useGetSubsQuery } from './subscribeConfigSlice';
export default function SubscribeManager() {
const { data: subs } = useGetSubsQuery();
const [patchSub] = useDeleteSubMutation();
const createNewSub = () => {
patchSub({ target: '2773976700', platformName: 'weibo', groupNumber: 868610060 }).unwrap();
};
return (
<>
<div>{ subs && JSON.stringify(subs) }</div>
<div>1</div>
<button onClick={() => createNewSub()} type="button">new</button>
</>
);
}

View File

@ -0,0 +1,9 @@
import React from 'react';
import { useGetWeightQuery } from './weightConfigSlice';
export default function WeightManager() {
const { data: weight } = useGetWeightQuery();
return (
<div>{weight && JSON.stringify(weight)}</div>
);
}

View File

@ -0,0 +1,18 @@
import { createApi } from '@reduxjs/toolkit/query/react';
import baseQueryWithAuth from '../auth/authQuery';
export const weightApi = createApi({
reducerPath: 'weight',
baseQuery: baseQueryWithAuth,
tagTypes: ['Weight'],
endpoints: (builder) => ({
getWeight: builder.query<any, void>({
query: () => '/weight',
providesTags: ['Weight'],
}),
}),
});
export const {
useGetWeightQuery,
} = weightApi;

View File

@ -1,11 +1,12 @@
import React from 'react';
import SubscribeManager from '../features/subsribeConfigManager/SubscribeManager';
// import SubscribeManager from '../features/subsribeConfigManager/SubscribeManager';
import WeightManager from '../features/weightConfig/WeightManager';
export default function Home() {
return (
<>
<div>hoem</div>
<SubscribeManager />
<WeightManager />
</>
);
}

View File

@ -52,3 +52,9 @@ export interface SubmitParam {
groupNumber: number;
sub: SubscribeConfig;
}
export interface TimeWeightConfig {
start_time: string;
end_time: string;
weight: number;
}

View File

@ -14,6 +14,7 @@ from nonebot.rule import to_me
from nonebot.typing import T_State
from ..plugin_config import plugin_config
from ..types import WeightConfig
from .api import (
add_group_sub,
auth,
@ -21,8 +22,10 @@ from .api import (
get_global_conf,
get_subs_info,
get_target_name,
get_weight_config,
test,
update_group_sub,
update_weigth_config,
)
from .jwt import load_jwt
from .token_manager import token_manager as tm
@ -32,6 +35,7 @@ GLOBAL_CONF_URL = f"{URL_BASE}api/global_conf"
AUTH_URL = f"{URL_BASE}api/auth"
SUBSCRIBE_URL = f"{URL_BASE}api/subs"
GET_TARGET_NAME_URL = f"{URL_BASE}api/target_name"
WEIGHT_URL = f"{URL_BASE}api/weight"
TEST_URL = f"{URL_BASE}test"
STATIC_PATH = (Path(__file__).parent / "dist").resolve()
@ -74,6 +78,10 @@ def register_router_fastapi(driver: Driver, socketio):
return
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
async def check_is_superuser(token_obj: dict = Depends(get_jwt_obj)):
if token_obj.get("type") != "admin":
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
@dataclass
class AddSubscribeReq:
platformName: str
@ -124,6 +132,14 @@ def register_router_fastapi(driver: Driver, socketio):
async def _del_group_subs(groupNumber: int, target: str, platformName: str):
return await del_group_sub(groupNumber, platformName, target)
@app.get(WEIGHT_URL, dependencies=[Depends(check_is_superuser)])
async def _get_weight_config():
return await get_weight_config()
@app.patch(WEIGHT_URL, dependencies=[Depends(check_is_superuser)])
async def _update_weight_config(platformName: str, target: str, req: WeightConfig):
return await update_weigth_config(platformName, target, req)
app.mount(URL_BASE, SinglePageApplication(directory=static_path), name="bison")

View File

@ -1,9 +1,15 @@
import nonebot
from nonebot.adapters.onebot.v11.bot import Bot
from ..config import NoSuchSubscribeException, NoSuchUserException, config
from ..config import (
NoSuchSubscribeException,
NoSuchTargetException,
NoSuchUserException,
config,
)
from ..platform import check_sub_target, platform_manager
from ..types import Target as T_Target
from ..types import WeightConfig
from .jwt import pack_jwt
from .token_manager import token_manager
@ -47,6 +53,7 @@ async def auth(token: str):
if str(qq) in nonebot.get_driver().config.superusers:
jwt_obj = {
"id": qq,
"type": "admin",
"groups": list(
map(
lambda info: {
@ -65,7 +72,7 @@ async def auth(token: str):
}
return {"status": 200, **ret_obj}
if admin_groups := await get_admin_groups(int(qq)):
jwt_obj = {"id": str(qq), "groups": admin_groups}
jwt_obj = {"id": str(qq), "type": "user", "groups": admin_groups}
ret_obj = {
"type": "user",
"name": nickname,
@ -147,3 +154,19 @@ async def update_group_sub(
except (NoSuchUserException, NoSuchSubscribeException):
return {"status": 400, "msg": "更新错误"}
return {"status": 200, "msg": ""}
async def get_weight_config():
return await config.get_all_weight_config()
async def update_weigth_config(
platform_name: str, target: str, weight_config: WeightConfig
):
try:
await config.update_time_weight_config(
T_Target(target), platform_name, weight_config
)
except NoSuchTargetException:
return {"status": 400, "msg": "该订阅不存在"}
return {"status": 200, "msg": ""}

View File

@ -1,3 +1,3 @@
from .config_legacy import NoSuchSubscribeException, NoSuchUserException
from .db import DATA
from .db_config import config
from .utils import NoSuchSubscribeException, NoSuchTargetException, NoSuchUserException

View File

@ -1,3 +1,4 @@
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime, time
from typing import Any, Awaitable, Callable, Optional
@ -8,11 +9,13 @@ from sqlalchemy.orm import selectinload
from sqlalchemy.sql.expression import delete, select
from sqlalchemy.sql.functions import func
from ..types import Category, Tag
from ..types import Category, PlatformWeightConfigResp, Tag
from ..types import Target as T_Target
from ..types import TimeWeightConfig
from ..types import User as T_User
from ..types import UserSubInfo
from ..types import UserSubInfo, WeightConfig
from .db_model import ScheduleTimeWeight, Subscribe, Target, User
from .utils import NoSuchTargetException
def _get_time():
@ -21,20 +24,6 @@ def _get_time():
return cur_time
@dataclass
class TimeWeightConfig:
start_time: time
end_time: time
weight: int
@dataclass
class WeightConfig:
default: int
time_config: list[TimeWeightConfig]
class DBConfig:
def __init__(self):
self.add_target_hook: Optional[Callable[[str, T_Target], Awaitable]] = None
@ -202,6 +191,8 @@ class DBConfig:
Target.platform_name == platform_name, Target.target == target
)
)
if not targetObj:
raise NoSuchTargetException()
target_id = targetObj.id
targetObj.default_schedule_weight = conf.default
delete(ScheduleTimeWeight).where(ScheduleTimeWeight.target_id == target_id)
@ -262,5 +253,40 @@ class DBConfig:
)
)
async def get_all_weight_config(
self,
) -> dict[str, dict[str, PlatformWeightConfigResp]]:
res: dict[str, dict[str, PlatformWeightConfigResp]] = defaultdict(dict)
async with AsyncSession(get_engine()) as sess:
query = select(Target)
targets: list[Target] = (await sess.scalars(query)).all()
query = select(ScheduleTimeWeight).options(
selectinload(ScheduleTimeWeight.target)
)
time_weights: list[ScheduleTimeWeight] = (await sess.scalars(query)).all()
for target in targets:
platform_name = target.platform_name
if platform_name not in res.keys():
res[platform_name][target.target] = PlatformWeightConfigResp(
target=T_Target(target.target),
target_name=target.target_name,
weight=WeightConfig(
default=target.default_schedule_weight, time_config=[]
),
)
for time_weight_config in time_weights:
platform_name = time_weight_config.target.platform_name
target = time_weight_config.target.target
res[platform_name][target].weight.time_config.append(
TimeWeightConfig(
start_time=time_weight_config.start_time,
end_time=time_weight_config.end_time,
weight=time_weight_config.weight,
)
)
return res
config = DBConfig()

View File

@ -4,3 +4,7 @@ class NoSuchUserException(Exception):
class NoSuchSubscribeException(Exception):
pass
class NoSuchTargetException(Exception):
pass

View File

@ -1,4 +1,5 @@
from dataclasses import dataclass
from datetime import time
from typing import Any, Callable, Literal, NamedTuple, NewType
RawPost = NewType("RawPost", Any)
@ -24,3 +25,24 @@ class UserSubInfo(NamedTuple):
user: User
categories: list[Category]
tags: list[Tag]
@dataclass
class TimeWeightConfig:
start_time: time
end_time: time
weight: int
@dataclass
class WeightConfig:
default: int
time_config: list[TimeWeightConfig]
@dataclass
class PlatformWeightConfigResp:
target: Target
target_name: str
weight: WeightConfig