DushuoServer 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dushuoserver/__init__.py +8 -0
- dushuoserver/__main__.py +6 -0
- dushuoserver/app.py +69 -0
- dushuoserver/config.py +121 -0
- dushuoserver/database.py +211 -0
- dushuoserver/license_show.py +76 -0
- dushuoserver/logger.py +34 -0
- dushuoserver/main.py +252 -0
- dushuoserver/runtime.py +82 -0
- dushuoserver/schemas.py +37 -0
- dushuoserver/service/routers_activity.py +41 -0
- dushuoserver/service/routers_config.py +56 -0
- dushuoserver/service/routers_health.py +11 -0
- dushuoserver/service/routers_messages.py +74 -0
- dushuoserver/service/routers_pairing.py +97 -0
- dushuoserver/service/routers_status.py +25 -0
- dushuoserver/services.py +259 -0
- dushuoserver-0.1.0.dist-info/METADATA +123 -0
- dushuoserver-0.1.0.dist-info/RECORD +22 -0
- dushuoserver-0.1.0.dist-info/WHEEL +4 -0
- dushuoserver-0.1.0.dist-info/entry_points.txt +5 -0
- dushuoserver-0.1.0.dist-info/licenses/LICENSE +201 -0
dushuoserver/main.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""度朔服务端命令行启动入口。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Dict
|
|
8
|
+
|
|
9
|
+
import uvicorn
|
|
10
|
+
|
|
11
|
+
from .config import ServerConfig, config
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
15
|
+
"""构建服务端命令行参数解析器。"""
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="dushuoserver",
|
|
18
|
+
description="度朔服务端:通过监控数字活动进行生死判断。",
|
|
19
|
+
argument_default=argparse.SUPPRESS,
|
|
20
|
+
add_help=False,
|
|
21
|
+
suggest_on_error=True,
|
|
22
|
+
color=True,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"-h",
|
|
27
|
+
"--help",
|
|
28
|
+
action="help",
|
|
29
|
+
help="显示帮助信息并退出",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"-v",
|
|
33
|
+
"--version",
|
|
34
|
+
action="version",
|
|
35
|
+
version="%(prog)s 0.1.0",
|
|
36
|
+
help="显示版本信息并退出",
|
|
37
|
+
)
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"-l",
|
|
40
|
+
"--licence",
|
|
41
|
+
"--license",
|
|
42
|
+
action="store_true",
|
|
43
|
+
default=False,
|
|
44
|
+
help="显示软件授权信息并打印至日志文件后退出",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
starter_argumets = parser.add_argument_group(
|
|
48
|
+
"启动参数",
|
|
49
|
+
"在服务端启动时须配置的参数,无法在客户端修改。",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
starter_argumets.add_argument(
|
|
53
|
+
"-c",
|
|
54
|
+
"--config",
|
|
55
|
+
"--default-config",
|
|
56
|
+
dest="config_path",
|
|
57
|
+
type=Path,
|
|
58
|
+
default=None,
|
|
59
|
+
help="配置文件路径,若配置文件中有与命令行参数冲突的参数,将使用命令行参数覆盖。",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
starter_argumets.add_argument(
|
|
63
|
+
"-a",
|
|
64
|
+
"--addr",
|
|
65
|
+
"--address",
|
|
66
|
+
"--host-address",
|
|
67
|
+
dest="host",
|
|
68
|
+
type=str,
|
|
69
|
+
default=None,
|
|
70
|
+
help="监听地址",
|
|
71
|
+
)
|
|
72
|
+
starter_argumets.add_argument(
|
|
73
|
+
"-p",
|
|
74
|
+
"--port",
|
|
75
|
+
"--host-port",
|
|
76
|
+
dest="port",
|
|
77
|
+
type=int,
|
|
78
|
+
default=None,
|
|
79
|
+
help="监听端口",
|
|
80
|
+
)
|
|
81
|
+
starter_argumets.add_argument(
|
|
82
|
+
"--log-level",
|
|
83
|
+
default=None,
|
|
84
|
+
choices=["critical", "error", "warning", "info", "debug", "trace"],
|
|
85
|
+
help="日志级别",
|
|
86
|
+
)
|
|
87
|
+
starter_argumets.add_argument(
|
|
88
|
+
"-d",
|
|
89
|
+
"--database",
|
|
90
|
+
"--db-path",
|
|
91
|
+
dest="database_path",
|
|
92
|
+
type=Path,
|
|
93
|
+
default=None,
|
|
94
|
+
help="SQLite 数据库文件路径",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
starter_argumets.add_argument(
|
|
98
|
+
"--workers",
|
|
99
|
+
type=int,
|
|
100
|
+
default=None,
|
|
101
|
+
help="Uvicorn 工作进程数",
|
|
102
|
+
)
|
|
103
|
+
starter_argumets.add_argument(
|
|
104
|
+
"--hot-reload",
|
|
105
|
+
dest="hot_reload",
|
|
106
|
+
action="store_true",
|
|
107
|
+
default=None,
|
|
108
|
+
help="开启 Uvicorn 开发模式热重载",
|
|
109
|
+
)
|
|
110
|
+
starter_argumets.add_argument(
|
|
111
|
+
"--no-access-log",
|
|
112
|
+
action="store_true",
|
|
113
|
+
default=None,
|
|
114
|
+
help="关闭 Uvicorn 访问日志",
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# 可运行时修改的配置项,可通过命令行覆盖默认配置文件。
|
|
118
|
+
|
|
119
|
+
runtime_argumets = parser.add_argument_group(
|
|
120
|
+
"运行时参数",
|
|
121
|
+
"可运行时修改的配置项,可通过客户端修改,不应在配置文件中出现。",
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
runtime_argumets.add_argument(
|
|
125
|
+
"--live-activity-duration",
|
|
126
|
+
"--activity-cache-duration",
|
|
127
|
+
dest="seconds",
|
|
128
|
+
type=int,
|
|
129
|
+
default=None,
|
|
130
|
+
help="数字活动缓存时间(秒)",
|
|
131
|
+
)
|
|
132
|
+
runtime_argumets.add_argument(
|
|
133
|
+
"--countdown-seconds",
|
|
134
|
+
"--death-countdown",
|
|
135
|
+
dest="countdown",
|
|
136
|
+
type=int,
|
|
137
|
+
default=None,
|
|
138
|
+
help="倒计时延续时间(秒)",
|
|
139
|
+
)
|
|
140
|
+
runtime_argumets.add_argument(
|
|
141
|
+
"--execution-task",
|
|
142
|
+
dest="command",
|
|
143
|
+
type=str,
|
|
144
|
+
default=None,
|
|
145
|
+
help="最终任务执行命令",
|
|
146
|
+
)
|
|
147
|
+
runtime_argumets.add_argument(
|
|
148
|
+
"--message-cache-duration",
|
|
149
|
+
type=int,
|
|
150
|
+
default=None,
|
|
151
|
+
help="短报文消息缓存时间(秒)",
|
|
152
|
+
)
|
|
153
|
+
runtime_argumets.add_argument(
|
|
154
|
+
"--pairing-window-time",
|
|
155
|
+
type=int,
|
|
156
|
+
default=None,
|
|
157
|
+
help="配对链接的有效窗口时长(秒)",
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
return parser
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def apply_config(new_config: ServerConfig) -> None:
|
|
164
|
+
"""将新的配置逐项写回共享的配置实例。
|
|
165
|
+
|
|
166
|
+
其余模块均以 `from .config import config` 持有同一个实例,重新绑定本模块
|
|
167
|
+
的名字不会影响它们,因此这里必须就地更新。
|
|
168
|
+
"""
|
|
169
|
+
for name in type(config).model_fields:
|
|
170
|
+
setattr(config, name, getattr(new_config, name))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def main(argv: list[str] | None = None) -> None:
|
|
174
|
+
"""解析命令行参数并启动服务"""
|
|
175
|
+
|
|
176
|
+
args = build_parser().parse_args(argv)
|
|
177
|
+
|
|
178
|
+
if args.licence:
|
|
179
|
+
from .license_show import main as license_show
|
|
180
|
+
|
|
181
|
+
license_show()
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
# 数据库 > 命令行传参 > 配置文件 > 默认参数
|
|
185
|
+
|
|
186
|
+
if args.config_path is not None:
|
|
187
|
+
apply_config(config.load_config(args.config_path))
|
|
188
|
+
|
|
189
|
+
overrides = config.model_dump(mode="python")
|
|
190
|
+
|
|
191
|
+
if args.host is not None:
|
|
192
|
+
overrides["host_address"] = args.host
|
|
193
|
+
if args.port is not None:
|
|
194
|
+
overrides["host_port"] = args.port
|
|
195
|
+
|
|
196
|
+
true_log_level = None
|
|
197
|
+
if args.log_level is not None:
|
|
198
|
+
overrides["log_level"] = true_log_level = args.log_level
|
|
199
|
+
if "TRACE" in true_log_level.upper():
|
|
200
|
+
true_log_level = "TRACE"
|
|
201
|
+
|
|
202
|
+
if args.database_path is not None:
|
|
203
|
+
overrides["db_path"] = args.database_path
|
|
204
|
+
if args.hot_reload is not None:
|
|
205
|
+
overrides["uvicron"]["hot_reload"] = args.hot_reload
|
|
206
|
+
if args.workers is not None:
|
|
207
|
+
if overrides["uvicron"]["hot_reload"]:
|
|
208
|
+
overrides["uvicron"]["workers"] = 1
|
|
209
|
+
else:
|
|
210
|
+
overrides["uvicron"]["workers"] = args.workers
|
|
211
|
+
if args.no_access_log is not None:
|
|
212
|
+
overrides["uvicron"]["access_log"] = not args.no_access_log
|
|
213
|
+
if args.seconds is not None:
|
|
214
|
+
overrides["runtime"]["activity_cache_duration"] = args.seconds
|
|
215
|
+
if args.countdown is not None:
|
|
216
|
+
overrides["runtime"]["death_countdown"] = args.countdown
|
|
217
|
+
if args.command is not None:
|
|
218
|
+
overrides["runtime"]["execution_task"] = args.command
|
|
219
|
+
if args.message_cache_duration is not None:
|
|
220
|
+
overrides["runtime"]["message_cache_duration"] = args.message_cache_duration
|
|
221
|
+
if args.pairing_window_time is not None:
|
|
222
|
+
overrides["runtime"]["pairing_window_time"] = args.pairing_window_time
|
|
223
|
+
|
|
224
|
+
apply_config(ServerConfig.model_validate(overrides))
|
|
225
|
+
true_log_level = true_log_level or config.log_level
|
|
226
|
+
|
|
227
|
+
from .logger import logger
|
|
228
|
+
|
|
229
|
+
logger.set_print_level = config.log_level
|
|
230
|
+
|
|
231
|
+
from .license_show import main as license_show
|
|
232
|
+
license_show()
|
|
233
|
+
|
|
234
|
+
logger.debug(
|
|
235
|
+
"获得完整参数为:```\n{}\n```,即将启动服务".format(config.dump_as_toml())
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
uvicorn.run(
|
|
239
|
+
"dushuoserver.app:app",
|
|
240
|
+
host=config.host_address,
|
|
241
|
+
port=config.host_port,
|
|
242
|
+
reload=config.uvicron.hot_reload,
|
|
243
|
+
workers=config.uvicron.workers,
|
|
244
|
+
log_level=true_log_level,
|
|
245
|
+
access_log=config.uvicron.access_log,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
logger.info("程序终止")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
if __name__ == "__main__":
|
|
252
|
+
main()
|
dushuoserver/runtime.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""度朔服务端运行时状态与倒计时。"""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import secrets
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Callable, Coroutine, Optional
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .logger import logger
|
|
10
|
+
from .config import config
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# 服务运行时状态
|
|
14
|
+
@dataclass(init=False, frozen=False, repr=False, eq=False, order=False)
|
|
15
|
+
class State:
|
|
16
|
+
"""运行时状态。"""
|
|
17
|
+
|
|
18
|
+
started_at: float
|
|
19
|
+
deadline: int
|
|
20
|
+
triggered: bool
|
|
21
|
+
last_activity_at: Optional[float]
|
|
22
|
+
|
|
23
|
+
def __init__(self, triggered: bool = False) -> None:
|
|
24
|
+
self.triggered = triggered
|
|
25
|
+
self.last_activity_at = None
|
|
26
|
+
self.__pairing_key: Optional[str] = None
|
|
27
|
+
self.__pairing_key_expire_at: int = -1
|
|
28
|
+
|
|
29
|
+
super().__init__()
|
|
30
|
+
|
|
31
|
+
def __post_init__(self) -> None:
|
|
32
|
+
self.started_at = time.time()
|
|
33
|
+
self.update_deadline()
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def safe_integer_time(after: float) -> int:
|
|
37
|
+
"""返回一个整数时间戳。"""
|
|
38
|
+
return int(time.time() + 0.5 + after)
|
|
39
|
+
|
|
40
|
+
def generate_pairing_key(self):
|
|
41
|
+
"""生成配对密钥。"""
|
|
42
|
+
self.__pairing_key = secrets.token_urlsafe(32)
|
|
43
|
+
self.__pairing_key_expire_at = self.safe_integer_time(
|
|
44
|
+
config.runtime.pairing_window_time
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def pairing_key(self) -> Optional[str]:
|
|
49
|
+
"""配对密钥。"""
|
|
50
|
+
if self.__pairing_key_expire_at < time.time():
|
|
51
|
+
self.__pairing_key = None
|
|
52
|
+
return self.__pairing_key
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def pairing_key_expires_at(self) -> int:
|
|
56
|
+
"""配对密钥的过期时间戳;尚未生成过密钥时为 -1。"""
|
|
57
|
+
return self.__pairing_key_expire_at
|
|
58
|
+
|
|
59
|
+
def update_deadline(self):
|
|
60
|
+
"""更新倒计时。"""
|
|
61
|
+
self.deadline = self.safe_integer_time(config.runtime.death_countdown)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
state: State = State(triggered=False)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def countdown_loop(execute_final_task: Callable[[], None]):
|
|
68
|
+
"""
|
|
69
|
+
后台倒计时循环。
|
|
70
|
+
|
|
71
|
+
当倒计时结束且尚未触发最终任务时,执行最终任务。
|
|
72
|
+
"""
|
|
73
|
+
while True:
|
|
74
|
+
await asyncio.sleep(1)
|
|
75
|
+
|
|
76
|
+
if state.triggered:
|
|
77
|
+
continue
|
|
78
|
+
|
|
79
|
+
if time.time() >= state.deadline:
|
|
80
|
+
state.triggered = True
|
|
81
|
+
logger.info("死亡判定倒计时结束,开始执行最终任务")
|
|
82
|
+
await asyncio.to_thread(execute_final_task)
|
dushuoserver/schemas.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""度朔服务端请求模型。"""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PairRequest(BaseModel):
|
|
9
|
+
"""客户端配对请求模型。"""
|
|
10
|
+
|
|
11
|
+
pairing_code: str = Field(..., min_length=1, description="配对码")
|
|
12
|
+
client_id: str = Field(..., min_length=1, description="客户端标识")
|
|
13
|
+
public_key: str = Field(..., description="客户端公钥(PEM 文本)")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ActivityRequest(BaseModel):
|
|
17
|
+
"""客户端上报数字活动的请求模型。"""
|
|
18
|
+
|
|
19
|
+
activity: str = Field("", description="数字活动描述")
|
|
20
|
+
timestamp: Optional[float] = Field(None, description="客户端上报时间戳")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ConfigUpdateRequest(BaseModel):
|
|
24
|
+
"""客户端修改运行时配置的请求模型。"""
|
|
25
|
+
|
|
26
|
+
activity_cache_duration: Optional[int] = None
|
|
27
|
+
death_countdown: Optional[int] = None
|
|
28
|
+
execution_task: Optional[str] = None
|
|
29
|
+
message_cache_duration: Optional[int] = None
|
|
30
|
+
pairing_window_time: Optional[int] = None
|
|
31
|
+
signature_time_tolerance: Optional[int] = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class MessageRequest(BaseModel):
|
|
35
|
+
"""客户端发送短报文的请求模型。"""
|
|
36
|
+
|
|
37
|
+
content: str = Field(..., min_length=1, description="消息内容")
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""活动上报路由。"""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends
|
|
6
|
+
|
|
7
|
+
from ..logger import logger
|
|
8
|
+
from ..config import config
|
|
9
|
+
from ..database import cleanup_activities, insert_activity
|
|
10
|
+
from ..runtime import state
|
|
11
|
+
from ..schemas import ActivityRequest
|
|
12
|
+
from ..services import require_signature
|
|
13
|
+
|
|
14
|
+
router = APIRouter(tags=["activity"])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@router.post("/api/activity")
|
|
18
|
+
def report_activity(
|
|
19
|
+
body: ActivityRequest, client_id: str = Depends(require_signature)
|
|
20
|
+
) -> dict:
|
|
21
|
+
"""接收数字活动并重置倒计时。"""
|
|
22
|
+
cleanup_activities(config.runtime.activity_cache_duration)
|
|
23
|
+
|
|
24
|
+
now = body.timestamp or time.time()
|
|
25
|
+
insert_activity(client_id, body.activity, now)
|
|
26
|
+
|
|
27
|
+
state.last_activity_at = now
|
|
28
|
+
|
|
29
|
+
if not state.triggered:
|
|
30
|
+
state.update_deadline()
|
|
31
|
+
logger.info(
|
|
32
|
+
"收到客户端`{}`在`{}`时的活动`{}`,倒计时已重置".format(
|
|
33
|
+
client_id, body.timestamp, body.activity
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
"accepted": True,
|
|
39
|
+
"countdown_reset": not state.triggered,
|
|
40
|
+
"deadline": state.deadline,
|
|
41
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""配置管理路由。"""
|
|
2
|
+
|
|
3
|
+
from fastapi import APIRouter, Depends, HTTPException
|
|
4
|
+
|
|
5
|
+
from ..logger import logger
|
|
6
|
+
from ..config import config
|
|
7
|
+
from ..database import set_config_value
|
|
8
|
+
from ..runtime import state
|
|
9
|
+
from ..schemas import ConfigUpdateRequest
|
|
10
|
+
from ..services import require_signature
|
|
11
|
+
|
|
12
|
+
router = APIRouter(tags=["config"])
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def positive_integer_keys() -> set[str]:
|
|
16
|
+
"""取值为整数的运行时配置项,其值必须为正整数。
|
|
17
|
+
|
|
18
|
+
须在运行时求值:配置项在数据库初始化后才被记为已设置的字段。
|
|
19
|
+
"""
|
|
20
|
+
return {
|
|
21
|
+
key
|
|
22
|
+
for key in config.runtime.model_fields_set
|
|
23
|
+
if isinstance(getattr(config.runtime, key), int)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@router.get("/api/config")
|
|
28
|
+
def read_config(client_id: str = Depends(require_signature)) -> dict:
|
|
29
|
+
"""读取当前配置。"""
|
|
30
|
+
return config.model_dump(mode="json")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@router.put("/api/config")
|
|
34
|
+
def update_config(
|
|
35
|
+
body: ConfigUpdateRequest, client_id: str = Depends(require_signature)
|
|
36
|
+
) -> dict:
|
|
37
|
+
"""修改允许客户端修改的运行时配置项。"""
|
|
38
|
+
updates = body.model_dump(exclude_none=True)
|
|
39
|
+
positive_keys = positive_integer_keys()
|
|
40
|
+
|
|
41
|
+
for key, value in updates.items():
|
|
42
|
+
if key in positive_keys and value <= 0:
|
|
43
|
+
raise HTTPException(
|
|
44
|
+
status_code=400, detail="配置项`{}`必须为正整数".format(key)
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
set_config_value(key, value)
|
|
49
|
+
except (TypeError, ValueError) as exc:
|
|
50
|
+
raise HTTPException(status_code=400, detail=str(exc))
|
|
51
|
+
|
|
52
|
+
if "death_countdown" in updates and not state.triggered:
|
|
53
|
+
state.update_deadline()
|
|
54
|
+
|
|
55
|
+
logger.info("配置更新请求已处理:{}".format(sorted(updates)))
|
|
56
|
+
return config.model_dump(mode="json")
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""短报文路由。"""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends, HTTPException, Response
|
|
6
|
+
|
|
7
|
+
from ..config import config
|
|
8
|
+
from ..logger import logger
|
|
9
|
+
from ..database import (
|
|
10
|
+
cleanup_messages,
|
|
11
|
+
delete_message,
|
|
12
|
+
get_latest_message,
|
|
13
|
+
has_fetched_message,
|
|
14
|
+
insert_message,
|
|
15
|
+
mark_message_fetched,
|
|
16
|
+
)
|
|
17
|
+
from ..schemas import MessageRequest
|
|
18
|
+
from ..services import require_signature
|
|
19
|
+
|
|
20
|
+
router = APIRouter(tags=["messages"])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@router.get("/api/message")
|
|
24
|
+
def fetch_message(client_id: str = Depends(require_signature)) -> dict:
|
|
25
|
+
"""获取当前短报文,并记录本客户端已读取。"""
|
|
26
|
+
cleanup_messages(config.runtime.message_cache_duration)
|
|
27
|
+
|
|
28
|
+
msg = get_latest_message()
|
|
29
|
+
if msg is None:
|
|
30
|
+
raise HTTPException(status_code=404, detail="当前没有短报文")
|
|
31
|
+
|
|
32
|
+
already_fetched = has_fetched_message(client_id, msg["id"])
|
|
33
|
+
|
|
34
|
+
if not already_fetched:
|
|
35
|
+
mark_message_fetched(client_id, msg["id"], time.time())
|
|
36
|
+
|
|
37
|
+
logger.debug("客户端`{}`获取了短报文".format(client_id))
|
|
38
|
+
return {
|
|
39
|
+
"message": msg["content"],
|
|
40
|
+
"created_at": msg["created_at"],
|
|
41
|
+
"already_fetched": already_fetched,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@router.post("/api/message", status_code=201)
|
|
46
|
+
def send_message(
|
|
47
|
+
body: MessageRequest, client_id: str = Depends(require_signature)
|
|
48
|
+
) -> dict:
|
|
49
|
+
"""发送一条新的短报文;当前已存在短报文时须先删除。"""
|
|
50
|
+
cleanup_messages(config.runtime.message_cache_duration)
|
|
51
|
+
|
|
52
|
+
if get_latest_message() is not None:
|
|
53
|
+
raise HTTPException(status_code=409, detail="当前已有短报文,请先删除后再发送")
|
|
54
|
+
|
|
55
|
+
created_at = time.time()
|
|
56
|
+
insert_message(body.content, created_at)
|
|
57
|
+
|
|
58
|
+
logger.debug("客户端`{}`发送了新的短报文".format(client_id))
|
|
59
|
+
return {"message": body.content, "created_at": created_at}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@router.delete("/api/message", status_code=204)
|
|
63
|
+
def remove_message(client_id: str = Depends(require_signature)) -> Response:
|
|
64
|
+
"""删除当前短报文。"""
|
|
65
|
+
cleanup_messages(config.runtime.message_cache_duration)
|
|
66
|
+
|
|
67
|
+
msg = get_latest_message()
|
|
68
|
+
if msg is None:
|
|
69
|
+
raise HTTPException(status_code=404, detail="当前没有短报文")
|
|
70
|
+
|
|
71
|
+
delete_message(msg["id"])
|
|
72
|
+
|
|
73
|
+
logger.debug("客户端`{}`删除了短报文".format(client_id))
|
|
74
|
+
return Response(status_code=204)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""配对路由。"""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends, HTTPException, Response
|
|
6
|
+
from fastapi.responses import HTMLResponse
|
|
7
|
+
|
|
8
|
+
from ..runtime import state
|
|
9
|
+
from ..schemas import PairRequest
|
|
10
|
+
from ..services import (
|
|
11
|
+
pairing_payload,
|
|
12
|
+
pairing_qr_html,
|
|
13
|
+
register_client,
|
|
14
|
+
reopen_pairing_window,
|
|
15
|
+
require_signature,
|
|
16
|
+
verify_pairing_code,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
router = APIRouter(tags=["pairing"])
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@router.get("/", response_class=HTMLResponse)
|
|
23
|
+
def pairing_page() -> str:
|
|
24
|
+
"""返回配对页面。仅在配对窗口内可用。"""
|
|
25
|
+
if state.pairing_key is None:
|
|
26
|
+
raise HTTPException(status_code=410, detail="配对窗口已关闭")
|
|
27
|
+
|
|
28
|
+
payload = pairing_payload()
|
|
29
|
+
qr_html = pairing_qr_html()
|
|
30
|
+
|
|
31
|
+
return """
|
|
32
|
+
<html>
|
|
33
|
+
<head><meta charset="utf-8"><title>度朔配对</title></head>
|
|
34
|
+
<body>
|
|
35
|
+
<h1>度朔服务端配对</h1>
|
|
36
|
+
{qr_html}
|
|
37
|
+
<p>服务端地址:{host}</p>
|
|
38
|
+
<p>配对码:{pairing_code}</p>
|
|
39
|
+
<p>桌面端配置码:{config_code}</p>
|
|
40
|
+
</body>
|
|
41
|
+
</html>
|
|
42
|
+
""".format(
|
|
43
|
+
qr_html=qr_html,
|
|
44
|
+
host=payload["host"],
|
|
45
|
+
pairing_code=payload["pairing_code"],
|
|
46
|
+
config_code=payload["config_code"],
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@router.get("/api/pairing")
|
|
51
|
+
def pairing_info() -> dict:
|
|
52
|
+
"""返回配对信息与窗口剩余时间。仅在配对窗口内可用。"""
|
|
53
|
+
if state.pairing_key is None:
|
|
54
|
+
raise HTTPException(status_code=410, detail="配对窗口已关闭")
|
|
55
|
+
|
|
56
|
+
payload = pairing_payload()
|
|
57
|
+
return {
|
|
58
|
+
**payload,
|
|
59
|
+
"window_remaining_seconds": max(
|
|
60
|
+
0, int(state.pairing_key_expires_at - time.time())
|
|
61
|
+
),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@router.post("/api/pair", status_code=201)
|
|
66
|
+
def pair(response: Response, body: PairRequest) -> dict:
|
|
67
|
+
"""处理客户端配对请求,登记客户端公钥。
|
|
68
|
+
|
|
69
|
+
全新的客户端返回 201;更换公钥或公钥已登记时返回 200,
|
|
70
|
+
处置结果由响应中的 `action` 标示。
|
|
71
|
+
"""
|
|
72
|
+
verify_pairing_code(body.pairing_code)
|
|
73
|
+
|
|
74
|
+
action = register_client(body.client_id, body.public_key)
|
|
75
|
+
if action != "created":
|
|
76
|
+
response.status_code = 200
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
"paired": True,
|
|
80
|
+
"action": action,
|
|
81
|
+
"client_id": body.client_id,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@router.post("/api/pairing/reopen")
|
|
86
|
+
def reopen_pairing(client_id: str = Depends(require_signature)) -> dict:
|
|
87
|
+
"""由已配对的客户端重新开放配对窗口。"""
|
|
88
|
+
reopen_pairing_window()
|
|
89
|
+
|
|
90
|
+
payload = pairing_payload()
|
|
91
|
+
return {
|
|
92
|
+
"reopened_by": client_id,
|
|
93
|
+
**payload,
|
|
94
|
+
"window_remaining_seconds": max(
|
|
95
|
+
0, int(state.pairing_key_expires_at - time.time())
|
|
96
|
+
),
|
|
97
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""状态查询路由。"""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends
|
|
6
|
+
|
|
7
|
+
from ..runtime import state
|
|
8
|
+
from ..services import require_signature
|
|
9
|
+
|
|
10
|
+
router = APIRouter(tags=["status"])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@router.get("/api/status")
|
|
14
|
+
def status(client_id: str = Depends(require_signature)) -> dict:
|
|
15
|
+
"""返回服务端当前状态。"""
|
|
16
|
+
now = time.time()
|
|
17
|
+
|
|
18
|
+
return {
|
|
19
|
+
"status": "dead" if state.triggered else "alive",
|
|
20
|
+
"countdown_remaining_seconds": max(0, state.deadline - now),
|
|
21
|
+
"last_activity_at": state.last_activity_at,
|
|
22
|
+
"pairing_window_open": state.pairing_key is not None,
|
|
23
|
+
"pairing_window_remaining_seconds": max(0, state.pairing_key_expires_at - now),
|
|
24
|
+
"client_id": client_id,
|
|
25
|
+
}
|