Repository navigation
Expand file tree
/
Copy pathmodels.py
More file actions
110 lines (92 loc) · 2.94 KB
/
Copy pathmodels.py
File metadata and controls
110 lines (92 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# -*- coding: utf-8 -*-
"""数据模型:Peer、TorrentInfo 及其序列化字典类型。"""
import time
from dataclasses import dataclass, asdict
from typing import Any, Self, TypedDict
from utils import bytes_to_hex, hex_to_bytes
# ---------------------------------------------------------------------------
# 类型定义
# ---------------------------------------------------------------------------
class PeerDict(TypedDict):
peer_id: str
ip: str
port: int
last_seen: float
uploaded: int
downloaded: int
left: int
class TorrentStatsDict(TypedDict):
complete: int
incomplete: int
peers: int
completed: int
class TorrentStateDict(TypedDict):
info: dict[str, Any]
peers_info: list[PeerDict]
stats: TorrentStatsDict
# ---------------------------------------------------------------------------
# 数据模型
# ---------------------------------------------------------------------------
@dataclass(slots=True, frozen=True)
class Peer:
peer_id: bytes
ip: str
port: int
last_seen: float
uploaded: int = 0
downloaded: int = 0
left: int = 0
# 单调时钟版本的 last_seen(仅运行时使用,不持久化):
# 过期判断用它,避免 NTP 校时跳变导致 peer 被提前/延迟剔除
mono_seen: float = 0.0
def to_dict(self) -> PeerDict:
return {
"peer_id": bytes_to_hex(self.peer_id),
"ip": self.ip,
"port": self.port,
"last_seen": self.last_seen,
"uploaded": self.uploaded,
"downloaded": self.downloaded,
"left": self.left,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
last_seen = float(data.get("last_seen", 0.0))
age = max(0.0, time.time() - last_seen)
return cls(
peer_id=hex_to_bytes(data.get("peer_id", "")),
ip=data.get("ip", "0.0.0.0"),
port=int(data.get("port", 0)),
last_seen=last_seen,
uploaded=int(data.get("uploaded", 0)),
downloaded=int(data.get("downloaded", 0)),
left=int(data.get("left", 0)),
mono_seen=time.monotonic() - age,
)
_TORRENT_INFO_FIELDS: frozenset[str] = frozenset({
"info_hash",
"name",
"size",
"piece_length",
"creation_date",
"comment",
"created_by",
})
@dataclass(slots=True)
class TorrentInfo:
info_hash: bytes
name: str = ""
size: int = 0
piece_length: int = 0
creation_date: float = 0.0
comment: str | None = None
created_by: str | None = None
def to_dict(self) -> dict[str, Any]:
d = asdict(self)
d["info_hash"] = bytes_to_hex(self.info_hash)
return d
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
filtered = {k: v for k, v in data.items() if k in _TORRENT_INFO_FIELDS}
filtered["info_hash"] = hex_to_bytes(data.get("info_hash", ""))
return cls(**filtered)