forked from p9ablo/mega.py
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdata_structures.py
More file actions
470 lines (370 loc) · 13.8 KB
/
data_structures.py
File metadata and controls
470 lines (370 loc) · 13.8 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
"""Mega API information
=====================
- This file contains definitions for some of the properties within the API.
- TypeDict objects are the raw data returned by the http requests to the API itself.
- The dataclasses are the internal representation of thoses objects
"""
from __future__ import annotations
import dataclasses
import time
from enum import IntEnum
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, ClassVar, Final, Self, TypeAlias, TypedDict
if TYPE_CHECKING:
from collections.abc import Mapping
from typing import NotRequired
from typing_extensions import ReadOnly
NodeID: TypeAlias = str
UserID: TypeAlias = str
TimeStamp: TypeAlias = int
SharedKeys: TypeAlias = dict[NodeID, tuple[int, ...]]
class ByteSize(int):
def human_readable(self) -> str:
"""(ex: '150.5MiB')"""
scale = 1024
me = float(self)
for unit in ("B", "KiB", "MiB", "GiB", "TiB", "PiB"):
if abs(me) < scale:
if unit == "B":
return f"{me:0.0f}{unit}"
return f"{me:0.1f}{unit}"
me /= scale
return f"{me:0.1f}EiB"
def __repr__(self) -> str:
return self.human_readable()
class NodeType(IntEnum):
FILE = 0
FOLDER = 1
ROOT_FOLDER = 2
INBOX = 3
TRASH = 4
class StorageStatus(IntEnum):
UNKNOWN = -9
GREEN = 0 # there is storage available
ORANGE = 1 # almost full
RED = 2 # full
# CHANGE = 3, # obsolete
PAYWALL = 4 # storage is full and user didn't remedy despite of warnings
class NodeSerialized(TypedDict):
h: NodeID # ID
p: NodeID # Parent ID
u: NotRequired[UserID] # Owner (user ID), not present in transfer.it nodes
t: ReadOnly[NodeType]
a: str # Serialized attributes
ts: TimeStamp # creation date
k: NotRequired[str] # Serialized node keys
su: NotRequired[str] # Share owner (user ID), only present present in shared (public) files / folder
sk: NotRequired[str] # Share key, only present present in shared (public) files / folder
class ShareKeySerialized(TypedDict):
h: NodeID # ID of node for this key
k: str # key
ha: str # ???
class ShareKeySerialized2(TypedDict):
h: NodeID # ID of node for this key
u: str # Owner (user ID)
r: int
ts: TimeStamp
class GetNodesResponse(TypedDict):
f: list[NodeSerialized]
ok: list[ShareKeySerialized]
s: list[ShareKeySerialized2]
class AttributesSerialized(TypedDict):
n: NotRequired[ReadOnly[str]] # Name
lbl: NotRequired[int] # label
fav: NotRequired[bool] # favorited
class FileInfoSerialized(TypedDict):
s: int # size
at: str # Serialized attributes
fa: str # Media file attributes (thumb, audio or video)
g: NotRequired[str] # direct download URL
_FIELDS_CACHE: dict[type, tuple[str, ...]] = {}
def _fields(cls: type) -> tuple[str, ...]:
if fields := _FIELDS_CACHE.get(cls):
return fields
fields = _FIELDS_CACHE[cls] = tuple(f.name for f in dataclasses.fields(cls))
return fields
class _DictDumper:
__dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]
def dump(self) -> dict[str, Any]:
"""Get a JSONable dict representation of this object"""
return dataclasses.asdict(self)
def _shallow_dump(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in _fields(type(self))}
class _DictParser:
__dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]
@classmethod
def _filter_dict(cls, data: Mapping[str, Any], /) -> dict[str, Any]:
return {k: v for k, v in data.items() if k in _fields(cls)}
@classmethod
def parse(cls, data: Mapping[str, Any], /) -> Self:
return cls(**cls._filter_dict(data))
@dataclasses.dataclass(slots=True, frozen=True)
class FileInfo(_DictDumper):
name: str
size: ByteSize
url: str | None
_at: str
@classmethod
def parse(cls, resp: FileInfoSerialized) -> FileInfo:
return FileInfo(
name="",
size=ByteSize(resp["s"]),
url=resp.get("g"),
_at=resp["at"],
)
@dataclasses.dataclass(slots=True, frozen=True)
class Crypto(_DictDumper):
key: tuple[int, int, int, int]
iv: tuple[int, int]
meta_mac: tuple[int, int]
full_key: tuple[int, int, int, int, int, int, int, int]
share_key: tuple[int, ...] | None
@classmethod
def compose(
cls,
key: tuple[int, ...],
iv: tuple[int, ...],
meta_mac: tuple[int, ...],
node_type: NodeType = NodeType.FILE,
) -> Crypto:
if node_type is NodeType.FILE:
full_key = (
key[0] ^ iv[0],
key[1] ^ iv[1],
key[2] ^ meta_mac[0],
key[3] ^ meta_mac[1],
*iv,
*meta_mac,
)
else:
full_key = *key, *iv, *meta_mac
return Crypto(key, iv, meta_mac, full_key, None) # pyright: ignore[reportArgumentType]
@classmethod
def decompose(
cls,
full_key: tuple[int, ...],
node_type: NodeType = NodeType.FILE,
share_key: tuple[int, ...] | None = None,
) -> Crypto:
iv = full_key[4:6]
meta_mac = full_key[6:8]
key = full_key
if node_type is NodeType.FILE:
key = (
key[0] ^ iv[0],
key[1] ^ iv[1],
key[2] ^ meta_mac[0],
key[3] ^ meta_mac[1],
)
return Crypto(key, iv, meta_mac, full_key, share_key) # pyright: ignore[reportArgumentType]
@classmethod
def from_dump(cls, dump: dict[str, Any]) -> Self:
share_key = dump.pop("share_key")
crypto = {k: tuple(v) for k, v in dump.items()}
return cls(**crypto, share_key=tuple(share_key) if share_key else None)
# We populate attrs and crypto after instance creation
@dataclasses.dataclass(slots=True, frozen=True, order=True)
class Node(_DictDumper):
id: NodeID
parent_id: NodeID
owner: UserID
type: NodeType
attributes: Attributes
created_at: TimeStamp
keys: MappingProxyType[UserID, str] = dataclasses.field(compare=False)
share_owner: UserID | None
share_key: str | None
_a: str
_crypto: Crypto
@property
def is_file(self) -> bool:
return self.type is NodeType.FILE
@property
def is_folder(self) -> bool:
return self.type is NodeType.FOLDER
@classmethod
def parse(cls, node: NodeSerialized) -> Node:
owner = node.get("u", "")
if k := node.get("k"):
if owner:
keys = dict(key_pair.split(":", 1) for key_pair in k.split("/") if ":" in key_pair)
else:
keys = {owner: k}
else:
keys: dict[str, str] = {}
return Node(
id=node["h"],
parent_id=node["p"],
owner=owner,
created_at=node["ts"],
type=NodeType(node["t"]),
keys=MappingProxyType(keys),
share_owner=node.get("su"),
share_key=node.get("sk"),
_a=node["a"],
attributes=None, # pyright: ignore[reportArgumentType]
_crypto=None, # pyright: ignore[reportArgumentType]
)
@classmethod
def from_dump(cls, dump: dict[str, Any], /) -> Self:
dump = dump | dict( # noqa: C408
type=NodeType[str(dump["type"]).upper()],
attributes=Attributes(**dump["attributes"]) if dump["attributes"] else None,
keys=MappingProxyType(dump["keys"]),
_crypto=Crypto.from_dump(dump["_crypto"]) if dump["_crypto"] else None,
)
return cls(**dump)
def dump(self) -> dict[str, Any]:
"""Get a JSONable dict representation of this object"""
me = self._shallow_dump()
me["type"] = self.type.name.lower()
me["attributes"] = self.attributes.dump() if self.attributes else {}
me["keys"] = dict(self.keys)
me["_crypto"] = self._crypto.dump() if self._crypto else None
return me
_LABELS: Final = "", "red", "orange", "yellow", "green", "blue", "purple", "grey"
@dataclasses.dataclass(slots=True, frozen=True)
class Attributes(_DictDumper):
name: str
label: str = ""
favorited: bool = False
@classmethod
def parse(cls, attrs: AttributesSerialized) -> Self:
return cls(
name=attrs.get("n", ""),
label=_LABELS[attrs.get("lbl", 0)],
favorited=bool(attrs.get("fav")),
)
def serialize(self) -> AttributesSerialized:
return { # pyright: ignore[reportReturnType]
key: value
for key, value in [
("n", self.name),
("lbl", _LABELS.index(self.label)),
("fav", self.favorited),
]
if value
}
@dataclasses.dataclass(slots=True, frozen=True)
class AccountBalance(_DictDumper):
amount: float
currency: str
@classmethod
def parse(cls, balance: list[tuple[float, str]] | None) -> Self:
amount, currency = balance[0] if balance else (0.0, "EUR")
return cls(float(amount), str(currency))
class AccountStatsSerialized(TypedDict):
# The NotRequired attributes are only available on PRO accounts
mstrg: int # maximum storage allowance
bt: int # "Base time age", number of seconds since the start of the current quota buckets
tah: list[int] # The free IP-based quota buckets, 6 entries for 6 hours
tar: int # IP transfer reserved
rua: int # Actor reserved quota
ruo: int # Owner reserved quota
cstrg: int # total account storage usage
cstrgn: dict[
NodeID, list[int]
] # NodeId -> [bytes, num_of_files, num_of_folders, versioned_bytes, num_versioned_files]
balance: list[tuple[float, str]]
uslw: (
int # The percentage (x100) indicating the limit at which the user is 'nearly' over. 98% for PRO, 90% for free.
)
usl: int # User storage status
subs: list[str]
plans: list[str]
features: list[str]
caxfer: NotRequired[int] # PRO transfer quota consumed by the user
tuo: int # Transfer usage by the owner on quota which hasn't yet been committed back to the API DB. Supplements caxfer
csxfer: NotRequired[int] # PRO transfer quota served to others
tua: int # Transfer usage served to other users which hasn't yet been committed back to the API DB. Supplements csxfer
mxfer: NotRequired[int] # maximum transfer allowance
srvratio: float # Ratio of PRO transfer quota that is able to be served to others
suntil: NotRequired[TimeStamp] # Expiration time of the currently active plan
@dataclasses.dataclass(slots=True, frozen=True)
class StorageMetrics(_DictDumper):
bytes_used: ByteSize
files: int
folders: int
@classmethod
def parse(cls, metrics: list[int]) -> Self:
bytes_used, files, folders = metrics[0:3]
return cls(ByteSize(bytes_used), files, folders)
@dataclasses.dataclass(slots=True, frozen=True)
class StorageQuota(_DictDumper):
used: ByteSize
max: ByteSize
percent: int
threshold: int
@property
def ratio(self) -> float:
return self.used / self.max
@property
def is_full(self) -> bool:
return self.ratio >= 1
@property
def is_almost_full(self) -> bool:
return self.ratio >= self.threshold
@classmethod
def parse(cls, data: Mapping[str, Any]) -> Self:
max, used, threshold = map(ByteSize, (data["mstrg"], data["cstrg"], data["uslw"]))
return cls(
used=used,
max=max,
percent=int(used / max * 100),
threshold=threshold // 100,
)
@dataclasses.dataclass(slots=True, frozen=True)
class ProTransferQuota:
used: ByteSize
used_by_others: ByteSize
max: ByteSize
srv_ratio: float
@dataclasses.dataclass(slots=True, frozen=True)
class AccountStats(_DictParser, _DictDumper):
storage: StorageQuota
transfer_quota: ProTransferQuota | None
balance: AccountBalance
metrics: Mapping[NodeID, StorageMetrics]
subs: tuple[str, ...]
plans: tuple[str, ...]
features: tuple[str, ...]
storage_status: StorageStatus
plan_expires: int | None
current_quota_start_time: int
_raw: AccountStatsSerialized = dataclasses.field(compare=False)
def serialize(self) -> AccountStatsSerialized:
return self._raw.copy()
@classmethod
def parse(cls, data: AccountStatsSerialized) -> Self: # pyright: ignore[reportIncompatibleMethodOverride]
transfer = None
if max_transfer := data.get("mxfer"):
assert "caxfer" in data
assert "csxfer" in data
transfer = ProTransferQuota(
used=ByteSize(data["caxfer"]),
used_by_others=ByteSize(data["caxfer"]),
max=ByteSize(max_transfer),
srv_ratio=data["srvratio"],
)
return cls(
storage=StorageQuota.parse(data),
balance=AccountBalance.parse(data.get("balance")),
metrics={node_id: StorageMetrics.parse(stats) for node_id, stats in data["cstrgn"].items()},
storage_status=StorageStatus(data["usl"]),
plan_expires=data.get("suntil"),
subs=tuple(data["subs"]),
plans=tuple(data["plans"]),
features=tuple(data["features"]),
transfer_quota=transfer,
current_quota_start_time=int(time.time() - data["bt"]),
_raw=data,
)
class UserResponse(TypedDict):
u: UserID
since: TimeStamp # timestamp of account creation
ipcc: str # IP country code (ex: US)
# These fields are not available when using a temp account (anonymous login)
email: NotRequired[str]
emails: NotRequired[list[str]]
pemails: NotRequired[list[str]]
name: NotRequired[str]