Repository navigation
Expand file tree
/
Copy pathfastapi_data.py
More file actions
1860 lines (1697 loc) · 77.9 KB
/
Copy pathfastapi_data.py
File metadata and controls
1860 lines (1697 loc) · 77.9 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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
"""Framework-independent persistence used by the FastAPI application."""
from __future__ import annotations
from contextlib import contextmanager
from datetime import datetime, timedelta
import hashlib
import hmac
from io import BytesIO
from logging import getLogger
from pathlib import Path
from threading import RLock, Thread
from time import sleep, time
from typing import Any, Iterator
import pytz
import schedule
from sqlalchemy import JSON, Boolean, Float, Integer, String, Text, create_engine, delete, func, inspect, or_, select, text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, scoped_session, sessionmaker
from sqlalchemy.pool import StaticPool
import utils as u
from models import ConfigModel, _StatusItemModel
l = getLogger(__name__)
LIMIT = 1024
ACTIVITY_HISTORY_RETENTION_SECONDS = 183 * 24 * 60 * 60
class Base(DeclarativeBase):
pass
class _MainData(Base):
__tablename__ = "main"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
status: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
private_mode: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
last_updated: Mapped[float] = mapped_column(Float, default=time, onupdate=time)
class _DeviceStatusData(Base):
__tablename__ = "device_status"
id: Mapped[str] = mapped_column(String(LIMIT), primary_key=True, unique=True, nullable=False)
show_name: Mapped[str] = mapped_column(String(LIMIT), nullable=False)
using: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
status: Mapped[str | None] = mapped_column(Text, nullable=True)
fields: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
last_updated: Mapped[float] = mapped_column(Float, default=time, onupdate=time)
class _AppActivityData(Base):
__tablename__ = "app_activities"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
device_id: Mapped[str] = mapped_column(String(LIMIT), nullable=False, index=True)
device_type: Mapped[str] = mapped_column(String(24), nullable=False, default="desktop", index=True)
app_key: Mapped[str] = mapped_column(String(240), nullable=False, index=True)
app_name: Mapped[str] = mapped_column(String(240), nullable=False, default="")
app_icon_url: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
window_title: Mapped[str] = mapped_column(Text, nullable=False, default="")
started_at: Mapped[float] = mapped_column(Float, nullable=False, default=time, index=True)
ended_at: Mapped[float | None] = mapped_column(Float, nullable=True)
last_seen_at: Mapped[float] = mapped_column(Float, nullable=False, default=time, index=True)
class _AppActivityEventData(Base):
__tablename__ = "app_activity_events"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
device_id: Mapped[str] = mapped_column(String(LIMIT), nullable=False, index=True)
device_type: Mapped[str] = mapped_column(String(24), nullable=False, default="desktop", index=True)
app_key: Mapped[str] = mapped_column(String(240), nullable=False, default="", index=True)
app_name: Mapped[str] = mapped_column(String(240), nullable=False, default="")
app_icon_url: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
event_type: Mapped[str] = mapped_column(String(32), nullable=False, default="app_open")
previous_app_name: Mapped[str] = mapped_column(String(240), nullable=False, default="")
created_at: Mapped[float] = mapped_column(Float, nullable=False, default=time, index=True)
class _MetricsMetaData(Base):
__tablename__ = "metrics_meta"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
today: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
week: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
month: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
year: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
class _MetricsData(Base):
__tablename__ = "metrics"
path: Mapped[str] = mapped_column(String(LIMIT), primary_key=True, unique=True, nullable=False)
daily: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
weekly: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
monthly: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
yearly: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
total: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
class _MusicStateData(Base):
__tablename__ = "music_state"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
device_id: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
title: Mapped[str] = mapped_column(String(300), nullable=False, default="")
artist: Mapped[str] = mapped_column(String(300), nullable=False, default="")
album: Mapped[str] = mapped_column(String(300), nullable=False, default="")
cover_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
audio_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
source_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
duration: Mapped[float] = mapped_column(Float, nullable=False, default=0)
position: Mapped[float] = mapped_column(Float, nullable=False, default=0)
playing: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
lyrics: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
client_updated_at: Mapped[float] = mapped_column(Float, nullable=False, default=0)
updated_at: Mapped[float] = mapped_column(Float, nullable=False, default=time)
class _MusicPlayerMetaData(Base):
__tablename__ = "music_player_meta"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
player_name: Mapped[str] = mapped_column(String(200), nullable=False, default="")
player_icon: Mapped[str] = mapped_column(String(64), nullable=False, default="media-player")
player_icon_url: Mapped[str] = mapped_column(String(1024), nullable=False, default="")
library_path: Mapped[str] = mapped_column(Text, nullable=False, default="")
class _MusicLibraryTrackData(Base):
"""Metadata index for content-addressed files in the private music library."""
__tablename__ = "music_library_tracks"
library_path: Mapped[str] = mapped_column(Text, primary_key=True)
title: Mapped[str] = mapped_column(String(300), nullable=False, default="")
artist: Mapped[str] = mapped_column(String(300), nullable=False, default="")
album: Mapped[str] = mapped_column(String(300), nullable=False, default="")
cover_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
lyrics: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
metadata_scanned_at: Mapped[float] = mapped_column(Float, nullable=False, default=0)
updated_at: Mapped[float] = mapped_column(Float, nullable=False, default=time)
class _MusicSourceData(Base):
__tablename__ = "music_source"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
source_mode: Mapped[str] = mapped_column(
String(32), nullable=False, default="metadata-only"
)
source_id: Mapped[str] = mapped_column(String(128), nullable=False, default="")
status: Mapped[str] = mapped_column(String(300), nullable=False, default="")
class _HealthStateData(Base):
__tablename__ = "health_state"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
heart_rate: Mapped[int | None] = mapped_column(Integer, nullable=True)
resting_heart_rate: Mapped[int | None] = mapped_column(Integer, nullable=True)
heart_rate_min: Mapped[int | None] = mapped_column(Integer, nullable=True)
heart_rate_max: Mapped[int | None] = mapped_column(Integer, nullable=True)
steps: Mapped[int | None] = mapped_column(Integer, nullable=True)
step_goal: Mapped[int | None] = mapped_column(Integer, nullable=True)
source: Mapped[str] = mapped_column(String(120), nullable=False, default="")
measured_at: Mapped[float] = mapped_column(Float, nullable=False, default=time)
updated_at: Mapped[float] = mapped_column(Float, nullable=False, default=time)
class _SiteSettingsData(Base):
__tablename__ = "site_settings"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=0)
visit_display_mode: Mapped[str] = mapped_column(
String(16), nullable=False, default="total"
)
class _RuntimeSettingData(Base):
__tablename__ = "runtime_settings"
key: Mapped[str] = mapped_column(String(64), primary_key=True)
value: Mapped[str] = mapped_column(Text, nullable=False, default="")
class _DeviceProfileData(Base):
__tablename__ = "device_profiles"
id: Mapped[str] = mapped_column(
String(LIMIT), primary_key=True, unique=True, nullable=False
)
display_name: Mapped[str] = mapped_column(String(LIMIT), nullable=False, default="")
icon_key: Mapped[str] = mapped_column(String(32), nullable=False, default="desktop")
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
is_public: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
class _CommentData(Base):
__tablename__ = "comments"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
nickname: Mapped[str] = mapped_column(String(24), nullable=False, default="匿名访客")
content: Mapped[str] = mapped_column(String(160), nullable=False)
color: Mapped[str] = mapped_column(String(16), nullable=False, default="violet")
visitor_hash: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
created_at: Mapped[float] = mapped_column(Float, nullable=False, default=time)
is_favorite: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
is_pinned: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
def _database_url(configured_url: str) -> str:
"""Resolve a relative SQLite URL below the project instance directory."""
if not configured_url.startswith("sqlite:///"):
return configured_url
raw_path = configured_url.removeprefix("sqlite:///")
if raw_path == ":memory:":
return configured_url
path = Path(raw_path)
if not path.is_absolute():
# The default ``../data/alive.db`` resolves to the project's data folder.
base = Path(u.current_dir()) / "instance"
path = (base / path).resolve()
path.parent.mkdir(parents=True, exist_ok=True)
return f"sqlite:///{path.as_posix()}"
class Data:
"""Thread-safe synchronous data access for FastAPI endpoints."""
def __init__(self, config: ConfigModel, start_scheduler: bool = True):
perf = u.perf_counter()
self._c = config
self._write_lock = RLock()
url = _database_url(config.main.database)
engine_kwargs: dict[str, Any] = {"pool_pre_ping": True}
if url.startswith("sqlite:"):
engine_kwargs["connect_args"] = {"check_same_thread": False}
if url == "sqlite:///:memory:":
engine_kwargs["poolclass"] = StaticPool
self.engine = create_engine(url, **engine_kwargs)
self._session_factory = scoped_session(
sessionmaker(bind=self.engine, expire_on_commit=False)
)
self.ensure_schema()
if config.metrics.enabled:
self._metrics_refresh()
if start_scheduler:
self._schedule_loop_th = Thread(target=self._schedule_loop, daemon=True)
self._schedule_loop_th.start()
l.debug("[data] FastAPI data init took %sms", perf())
def ensure_schema(self) -> None:
"""Create missing tables and singleton rows (safe to call on startup)."""
Base.metadata.create_all(self.engine)
self._migrate_schema()
with self.session() as session:
if session.scalar(select(_MainData).limit(1)) is None:
session.add(_MainData(id=0))
if self._c.metrics.enabled and session.scalar(select(_MetricsMetaData).limit(1)) is None:
session.add(_MetricsMetaData(id=0))
if session.scalar(select(_SiteSettingsData).limit(1)) is None:
session.add(_SiteSettingsData(id=0))
self.prune_activity_history()
def _migrate_schema(self) -> None:
"""Apply small idempotent migrations for databases created by older releases."""
if self.engine.dialect.name != "sqlite":
return
with self.engine.begin() as connection:
comments_columns = {column["name"] for column in inspect(self.engine).get_columns("comments")}
missing_comments = {
"is_favorite": "ALTER TABLE comments ADD COLUMN is_favorite BOOLEAN NOT NULL DEFAULT 0",
"is_pinned": "ALTER TABLE comments ADD COLUMN is_pinned BOOLEAN NOT NULL DEFAULT 0",
}
for name, statement in missing_comments.items():
if name not in comments_columns:
connection.execute(text(statement))
music_columns = {column["name"] for column in inspect(self.engine).get_columns("music_player_meta")}
missing_music = {
"player_icon_url": "ALTER TABLE music_player_meta ADD COLUMN player_icon_url VARCHAR(1024) NOT NULL DEFAULT ''",
}
for name, statement in missing_music.items():
if name not in music_columns:
connection.execute(text(statement))
music_state_columns = {column["name"] for column in inspect(self.engine).get_columns("music_state")}
if "client_updated_at" not in music_state_columns:
connection.execute(text("ALTER TABLE music_state ADD COLUMN client_updated_at FLOAT NOT NULL DEFAULT 0"))
library_columns = {column["name"] for column in inspect(self.engine).get_columns("music_library_tracks")}
missing_library = {
"cover_url": "ALTER TABLE music_library_tracks ADD COLUMN cover_url TEXT NOT NULL DEFAULT ''",
"lyrics": "ALTER TABLE music_library_tracks ADD COLUMN lyrics JSON NOT NULL DEFAULT '[]'",
"metadata_scanned_at": "ALTER TABLE music_library_tracks ADD COLUMN metadata_scanned_at FLOAT NOT NULL DEFAULT 0",
}
for name, statement in missing_library.items():
if name not in library_columns:
connection.execute(text(statement))
activity_columns = {column["name"] for column in inspect(self.engine).get_columns("app_activities")}
if "device_type" not in activity_columns:
connection.execute(text("ALTER TABLE app_activities ADD COLUMN device_type VARCHAR(24) NOT NULL DEFAULT 'desktop'"))
if "app_icon_url" not in activity_columns:
connection.execute(text("ALTER TABLE app_activities ADD COLUMN app_icon_url VARCHAR(1024) NOT NULL DEFAULT ''"))
# App activity records intentionally retain only app identity and time.
# Remove titles saved by the first preview implementation.
connection.execute(text("UPDATE app_activities SET window_title = '' WHERE window_title <> ''"))
@contextmanager
def session(self) -> Iterator[Any]:
session = self._session_factory()
try:
yield session
session.commit()
except SQLAlchemyError as exc:
session.rollback()
l.error("SQL call failed: %s", exc)
raise u.APIUnsuccessful(500, "Database Error") from exc
finally:
session.close()
self._session_factory.remove()
def close(self) -> None:
self._session_factory.remove()
self.engine.dispose()
def _schedule_loop(self) -> None:
scheduler = schedule.Scheduler()
if self._c.metrics.enabled:
scheduler.every().day.at("00:00:00", self._c.main.timezone).do(self._metrics_refresh)
if self._c.status.device_timeout > 0:
scheduler.every(5).seconds.do(self._expire_devices)
scheduler.every().day.at("00:05:00", self._c.main.timezone).do(self.prune_activity_history)
scheduler.every(max(self._c.main.cache_age, 1)).seconds.do(self._clean_cache)
while True:
scheduler.run_pending()
sleep(1)
def _main(self, session: Any) -> _MainData:
row = session.scalar(select(_MainData).limit(1))
if row is None:
row = _MainData(id=0)
session.add(row)
session.flush()
return row
@property
def status_id(self) -> int:
with self.session() as session:
return self._main(session).status
@status_id.setter
def status_id(self, value: int) -> None:
with self._write_lock, self.session() as session:
row = self._main(session)
row.status = value
row.last_updated = time()
def get_status(self, status_id: int) -> tuple[bool, _StatusItemModel]:
try:
status = self._c.status.status_list[status_id]
if status_id == 0:
status = status.model_copy(update={"desc": self.online_status_desc})
elif status_id == 1:
status = status.model_copy(update={"desc": self.offline_status_desc})
return True, status
except IndexError:
return False, _StatusItemModel(
id=status_id,
name="Unknown",
desc="未知的标识符,可能是配置问题。",
color="error",
)
@property
def status(self) -> tuple[bool, _StatusItemModel]:
return self.get_status(self.status_id)
@property
def status_dict(self) -> tuple[bool, dict[str, int | str]]:
exists, status = self.status
return exists, status.model_dump()
@property
def private_mode(self) -> bool:
with self.session() as session:
return self._main(session).private_mode
@private_mode.setter
def private_mode(self, value: bool) -> None:
with self._write_lock, self.session() as session:
row = self._main(session)
row.private_mode = value
row.last_updated = time()
@property
def last_updated(self) -> float:
with self.session() as session:
return self._main(session).last_updated
@last_updated.setter
def last_updated(self, value: float) -> None:
with self._write_lock, self.session() as session:
self._main(session).last_updated = value
@staticmethod
def _normalize_reported_device_fields(fields: dict[str, Any]) -> dict[str, Any]:
"""Canonicalize client model and activity categories without breaking legacy reports."""
normalized = dict(fields)
raw_model = str(normalized.get("device_type") or "").strip().casefold()
model_aliases = {
"mobile": "phone",
"computer": "desktop",
"pc": "desktop",
}
model = model_aliases.get(raw_model, raw_model)
supported_models = {"desktop", "laptop", "phone", "tablet", "watch", "server", "game", "other"}
if model in supported_models:
normalized["device_type"] = model
if normalized.get("activity_reporting") is True:
raw_activity_type = str(normalized.get("activity_device_type") or model or "desktop").strip().casefold()
normalized["activity_device_type"] = (
"mobile" if raw_activity_type in {"mobile", "phone", "tablet", "watch"} else "desktop"
)
return normalized
@staticmethod
def _default_device_icon(fields: dict[str, Any]) -> str:
model = str(fields.get("device_type") or "").strip().casefold()
if model in {"mobile", "phone"}:
return "phone"
if model in {"desktop", "laptop", "tablet", "watch", "server", "game", "other"}:
return model
return "desktop"
@staticmethod
def _serialize_device(
device: _DeviceStatusData,
profile: _DeviceProfileData | None = None,
redact_desktop_window_title: bool = False,
) -> dict[str, Any]:
fields = device.fields or {}
status = device.status
device_type = str(fields.get("device_type") or fields.get("activity_device_type") or "").casefold()
platform = str(fields.get("platform") or fields.get("os") or "").casefold()
is_desktop = (
device_type in {"desktop", "laptop", "server"}
or platform.startswith("windows")
or "cpu_cores" in fields
or "processor_count" in fields
)
if redact_desktop_window_title and is_desktop:
app_name = str(
fields.get("activity_app_name")
or fields.get("app_name")
or fields.get("activity_app_id")
or ""
).strip()
status = app_name or ("正在使用应用" if device.using else "未在使用")
result = {
"id": device.id,
"show_name": profile.display_name if profile and profile.display_name else device.show_name,
"using": device.using,
"status": status,
"fields": fields,
"last_updated": device.last_updated,
}
result["profile"] = {
"display_name": profile.display_name if profile else "",
"icon_key": profile.icon_key if profile else Data._default_device_icon(fields),
"sort_order": profile.sort_order if profile else 0,
"public": profile.is_public if profile else True,
}
return result
@property
def _raw_device_list(self) -> dict[str, _DeviceStatusData]:
with self.session() as session:
devices = list(session.scalars(select(_DeviceStatusData)).all())
return {device.id: device for device in devices}
@property
def _raw_device_list_dict(self) -> dict[str, dict[str, Any]]:
devices = self._raw_device_list
if not devices:
return {}
redact_desktop_window_title = self.private_mode
with self.session() as session:
profiles = {
profile.id: profile
for profile in session.scalars(select(_DeviceProfileData)).all()
}
return {
device_id: self._serialize_device(
device,
profiles.get(device_id),
redact_desktop_window_title,
)
for device_id, device in devices.items()
}
@property
def device_list(self) -> dict[str, dict[str, Any]]:
devices = self._raw_device_list_dict
devices = {
device_id: device
for device_id, device in devices.items()
if device["profile"]["public"]
}
if self._c.status.not_using:
for device in devices.values():
if device.get("using") is False:
device["status"] = self._c.status.not_using
if self._c.status.sorted:
devices = dict(sorted(devices.items()))
if self._c.status.using_first:
rank = {True: 0, False: 1, None: 2}
devices = dict(
sorted(
devices.items(),
key=lambda item: (rank.get(item[1].get("using"), 2), item[0] if self._c.status.sorted else ""),
)
)
devices = dict(
sorted(
devices.items(),
key=lambda item: (
item[1]["profile"]["sort_order"],
item[1]["show_name"].casefold(),
item[0],
),
)
)
return devices
@property
def admin_device_list(self) -> dict[str, dict[str, Any]]:
redact_desktop_window_title = self.private_mode
with self.session() as session:
devices = list(session.scalars(select(_DeviceStatusData)).all())
profiles = {
profile.id: profile
for profile in session.scalars(select(_DeviceProfileData)).all()
}
serialized = {
device.id: self._serialize_device(
device,
profiles.get(device.id),
redact_desktop_window_title,
)
for device in devices
}
return dict(
sorted(
serialized.items(),
key=lambda item: (
item[1]["profile"]["sort_order"],
item[1]["show_name"].casefold(),
),
)
)
def device_profile_set(
self,
id: str,
display_name: str,
icon_key: str,
sort_order: int | None,
is_public: bool,
) -> dict[str, Any]:
allowed_icons = {
"desktop",
"laptop",
"phone",
"tablet",
"watch",
"server",
"game",
"other",
"bilibili",
}
if not id:
raise u.APIUnsuccessful(400, "device id cannot be empty")
if len(display_name) > LIMIT:
raise u.APIUnsuccessful(400, "display_name is too long")
if icon_key not in allowed_icons:
raise u.APIUnsuccessful(400, "unsupported icon_key")
if sort_order is not None and not -100000 <= sort_order <= 100000:
raise u.APIUnsuccessful(400, "sort_order is outside the allowed range")
with self._write_lock, self.session() as session:
device = session.get(_DeviceStatusData, id)
if device is None:
raise u.APIUnsuccessful(404, "Device not found")
profile = session.get(_DeviceProfileData, id)
if profile is None:
profile = _DeviceProfileData(id=id)
session.add(profile)
profile.display_name = display_name.strip()
profile.icon_key = icon_key
if sort_order is not None:
profile.sort_order = sort_order
profile.is_public = is_public
now = time()
self._main(session).last_updated = now
session.flush()
return self._serialize_device(device, profile)
def device_reorder(self, id: str, direction: str) -> dict[str, dict[str, Any]]:
if not id:
raise u.APIUnsuccessful(400, "device id cannot be empty")
if direction not in {"up", "down"}:
raise u.APIUnsuccessful(400, "direction must be up or down")
with self._write_lock, self.session() as session:
devices = list(session.scalars(select(_DeviceStatusData)).all())
target = session.get(_DeviceStatusData, id)
if target is None:
raise u.APIUnsuccessful(404, "Device not found")
profiles = {}
for device in devices:
profile = session.get(_DeviceProfileData, device.id)
if profile is None:
profile = _DeviceProfileData(
id=device.id,
display_name="",
icon_key=self._default_device_icon(device.fields or {}),
sort_order=0,
is_public=True,
)
session.add(profile)
profiles[device.id] = profile
ordered = sorted(
devices,
key=lambda device: (
profiles[device.id].sort_order,
(profiles[device.id].display_name or device.show_name).casefold(),
device.id,
),
)
# Normalize legacy duplicate order values before moving. More importantly,
# move a device relative to the next device with the same visibility. A
# hidden device between two public devices must not make the homepage look
# as though a public-device reorder had no effect.
for sort_order, device in enumerate(ordered):
profiles[device.id].sort_order = sort_order
target = next(device for device in ordered if device.id == id)
visibility_group = [
device for device in ordered
if profiles[device.id].is_public == profiles[target.id].is_public
]
index = next(index for index, device in enumerate(visibility_group) if device.id == id)
other_index = index - 1 if direction == "up" else index + 1
if 0 <= other_index < len(visibility_group):
other = visibility_group[other_index]
profiles[target.id].sort_order, profiles[other.id].sort_order = (
profiles[other.id].sort_order,
profiles[target.id].sort_order,
)
self._main(session).last_updated = time()
return self.admin_device_list
def device_get(self, id: str) -> _DeviceStatusData | None:
with self.session() as session:
return session.get(_DeviceStatusData, id)
def device_set(
self,
id: str | None = None,
show_name: str | None = None,
using: bool | None = None,
status: str | None = None,
fields: dict | None = None,
) -> None:
if not id:
raise u.APIUnsuccessful(400, "device id cannot be empty!")
normalized_fields = self._normalize_reported_device_fields(fields or {})
with self._write_lock, self.session() as session:
device = session.get(_DeviceStatusData, id)
if device is None:
if not show_name:
raise u.APIUnsuccessful(400, "device show_name cannot be empty!")
device = _DeviceStatusData(
id=id,
show_name=show_name,
using=using,
status=status,
fields=normalized_fields,
last_updated=time(),
)
session.add(device)
else:
if show_name:
device.show_name = show_name
if using is not None:
device.using = using
if status is not None:
device.status = status
if normalized_fields:
device.fields = u.deep_merge_dict(device.fields or {}, normalized_fields)
device.last_updated = time()
self._record_app_activity(session, id, bool(using), normalized_fields)
self._prune_activity_history_in_session(session)
self._main(session).last_updated = time()
@staticmethod
def _activity_duration(activity: _AppActivityData, now: float, grace: float) -> float:
ended_at = activity.ended_at
if ended_at is None:
ended_at = min(now, activity.last_seen_at + grace)
return max(0.0, ended_at - activity.started_at)
@staticmethod
def _record_activity_event(
session: Any,
device_id: str,
device_type: str,
app_key: str,
app_name: str,
app_icon_url: str,
event_type: str,
previous_app_name: str = "",
) -> None:
session.add(
_AppActivityEventData(
device_id=device_id,
device_type=device_type,
app_key=app_key[:240],
app_name=app_name[:240],
app_icon_url=app_icon_url[:LIMIT],
event_type=event_type[:32],
previous_app_name=previous_app_name[:240],
)
)
def _record_app_activity(self, session: Any, device_id: str, using: bool, fields: dict) -> None:
"""Close/open a foreground-app interval when a capable client reports it."""
if fields.get("activity_reporting") is not True:
return
now = time()
current = session.scalar(
select(_AppActivityData)
.where(_AppActivityData.device_id == device_id, _AppActivityData.ended_at.is_(None))
.order_by(_AppActivityData.started_at.desc())
.limit(1)
)
app_key = str(fields.get("activity_app_id") or "").strip()[:240]
app_name = str(fields.get("activity_app_name") or "").strip()[:240]
app_icon_url = str(fields.get("activity_app_icon_url") or fields.get("app_icon_url") or "").strip()[:LIMIT]
device_type = self._activity_category(
str(fields.get("activity_device_type") or fields.get("device_type") or "desktop").strip().lower()
)
reported_event = str(fields.get("activity_event") or "").strip().lower()[:32]
if not using or not app_key:
if current is not None:
current.ended_at = now
current.last_seen_at = now
self._record_activity_event(
session, device_id, device_type, current.app_key, current.app_name,
current.app_icon_url, reported_event or "inactive",
)
return
if current is not None and current.app_key == app_key:
current.last_seen_at = now
current.device_type = device_type
if app_name:
current.app_name = app_name
if app_icon_url:
current.app_icon_url = app_icon_url
if reported_event:
self._record_activity_event(
session, device_id, device_type, current.app_key, current.app_name,
current.app_icon_url, reported_event,
)
return
if current is not None:
current.ended_at = now
current.last_seen_at = now
self._record_activity_event(
session, device_id, device_type, app_key, app_name or app_key, app_icon_url,
reported_event or "app_switch", current.app_name,
)
else:
self._record_activity_event(
session, device_id, device_type, app_key, app_name or app_key, app_icon_url,
reported_event or "app_open",
)
session.add(
_AppActivityData(
device_id=device_id,
device_type=device_type,
app_key=app_key,
app_name=app_name or app_key,
app_icon_url=app_icon_url,
window_title="",
started_at=now,
last_seen_at=now,
)
)
@staticmethod
def _activity_category(device_type: str) -> str:
return "mobile" if device_type in {"mobile", "phone", "tablet", "watch"} else "desktop"
@staticmethod
def _prune_activity_history_in_session(session: Any, now: float | None = None) -> int:
cutoff = (now if now is not None else time()) - ACTIVITY_HISTORY_RETENTION_SECONDS
removed = session.execute(delete(_AppActivityData).where(_AppActivityData.last_seen_at < cutoff)).rowcount or 0
removed += session.execute(delete(_AppActivityEventData).where(_AppActivityEventData.created_at < cutoff)).rowcount or 0
return int(removed)
def prune_activity_history(self) -> int:
"""Keep application usage and event history to a rolling six months."""
with self._write_lock, self.session() as session:
return self._prune_activity_history_in_session(session)
def activity_snapshot(
self,
timeout: float = 60,
period: str = "daily",
selected_date: str | None = None,
) -> dict[str, Any]:
"""Return period-aware application statistics without mixing mobile and desktop."""
period = period if period in {"daily", "weekly", "monthly"} else "daily"
timezone = pytz.timezone(self._c.main.timezone)
local_now = datetime.now(timezone)
try:
selected = timezone.localize(datetime.strptime(selected_date or "", "%Y-%m-%d"))
except ValueError:
selected = local_now
selected = min(selected, local_now)
if period == "daily":
range_start_local = selected.replace(hour=0, minute=0, second=0, microsecond=0)
range_end_local = range_start_local + timedelta(days=1)
labels = [f"{hour:02d}" for hour in range(24)]
elif period == "weekly":
range_start_local = (selected - timedelta(days=selected.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
range_end_local = range_start_local + timedelta(days=7)
labels = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
else:
range_start_local = selected.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
next_month = (range_start_local.replace(day=28) + timedelta(days=4)).replace(day=1)
range_end_local = next_month
labels = [str(day) for day in range(1, (range_end_local - range_start_local).days + 1)]
range_start = range_start_local.timestamp()
range_end = min(range_end_local.timestamp(), time())
grace = max(15.0, float(timeout) if timeout > 0 else 75.0)
now = time()
with self.session() as session:
rows = session.scalars(
select(_AppActivityData)
.where(_AppActivityData.started_at < range_end, _AppActivityData.last_seen_at >= range_start)
.order_by(_AppActivityData.last_seen_at.desc(), _AppActivityData.id.desc())
).all()
event_rows = session.scalars(
select(_AppActivityEventData)
.where(_AppActivityEventData.created_at >= range_start, _AppActivityEventData.created_at < range_end)
.order_by(_AppActivityEventData.created_at.desc(), _AppActivityEventData.id.desc())
.limit(300)
).all()
count_rows = session.execute(
select(_AppActivityData.device_type, func.count()).group_by(_AppActivityData.device_type)
).all()
categories: dict[str, dict[str, Any]] = {
category: {
"period_seconds": 0, "today_seconds": 0, "recent": [], "top_apps": [],
"total_records": 0, "time_series": [{"label": label, "seconds": 0} for label in labels],
}
for category in ("mobile", "desktop")
}
app_totals: dict[str, dict[str, dict[str, Any]]] = {"mobile": {}, "desktop": {}}
latest_events: dict[str, dict[str, dict[str, Any]]] = {"mobile": {}, "desktop": {}}
for device_type, count in count_rows:
categories[self._activity_category(device_type)]["total_records"] += int(count)
for event in event_rows:
category = self._activity_category(event.device_type)
if not event.app_key:
continue
if event.app_key not in latest_events[category]:
latest_events[category][event.app_key] = {
"event_type": event.event_type,
"app_name": event.app_name or event.app_key,
"previous_app_name": event.previous_app_name,
"timestamp": event.created_at,
}
for row in rows:
category = self._activity_category(row.device_type)
effective_end = row.ended_at if row.ended_at is not None else min(now, row.last_seen_at + grace)
clipped_start, clipped_end = max(range_start, row.started_at), min(range_end, effective_end)
overlap = max(0.0, clipped_end - clipped_start)
if overlap <= 0:
continue
active = row.ended_at is None and row.last_seen_at + grace >= now
record = {
"id": row.id,
"device_id": row.device_id,
"device_type": category,
"app_name": row.app_name or row.app_key,
"app_icon_url": row.app_icon_url or "",
"started_at": row.started_at,
"ended_at": effective_end,
"duration_seconds": round(overlap),
"active": active,
}
categories[category]["period_seconds"] += overlap
item = app_totals[category].setdefault(
row.app_key,
{
"app_key": row.app_key,
"app_name": record["app_name"],
"app_icon_url": record["app_icon_url"],
"duration_seconds": 0.0,
"last_seen_at": effective_end,
"active": active,
},
)
item["duration_seconds"] += overlap
item["last_seen_at"] = max(float(item["last_seen_at"]), effective_end)
item["active"] = bool(item["active"] or active)
if record["app_icon_url"]:
item["app_icon_url"] = record["app_icon_url"]
cursor = clipped_start
while cursor < clipped_end:
cursor_local = datetime.fromtimestamp(cursor, timezone)
if period == "daily":
index = cursor_local.hour
next_bucket = (cursor_local.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)).timestamp()
elif period == "weekly":
index = cursor_local.weekday()
next_bucket = (cursor_local.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)).timestamp()
else:
index = cursor_local.day - 1
next_bucket = (cursor_local.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)).timestamp()
piece_end = min(clipped_end, next_bucket)
categories[category]["time_series"][index]["seconds"] += max(0.0, piece_end - cursor)
cursor = piece_end
for category, data in categories.items():
data["period_seconds"] = round(data["period_seconds"])
data["today_seconds"] = data["period_seconds"]
data["time_series"] = [{**item, "seconds": round(item["seconds"])} for item in data["time_series"]]
apps = list(app_totals[category].values())
data["top_apps"] = [
{**item, "duration_seconds": round(item["duration_seconds"])}
for item in sorted(apps, key=lambda item: item["duration_seconds"], reverse=True)[:12]
]
data["recent"] = [
{
**item,
"duration_seconds": round(item["duration_seconds"]),
"latest_event": latest_events[category].get(item["app_key"]),
}
for item in sorted(apps, key=lambda item: item["last_seen_at"], reverse=True)[:50]
]
return {
"period": period,
"range_start": range_start,
"range_end": range_end,
"date_label": range_start_local.strftime("%Y 年 %m 月 %d 日") if period == "daily" else range_start_local.strftime("%Y 年 %m 月") if period == "monthly" else f"{range_start_local.strftime('%m/%d')} – {(range_start_local + timedelta(days=6)).strftime('%m/%d')}",
"today_seconds": sum(category["period_seconds"] for category in categories.values()),
"total_records": sum(category["total_records"] for category in categories.values()),
"categories": categories,
}
def activity_events(self, category: str, app_key: str, selected_date: str | None = None) -> dict[str, Any]:
"""Return one application's detailed events for the selected local day."""
category = "mobile" if category == "mobile" else "desktop"
app_key = str(app_key or "").strip()[:240]
if not app_key:
return {"date_label": "", "events": []}
timezone = pytz.timezone(self._c.main.timezone)
local_now = datetime.now(timezone)
try:
selected = timezone.localize(datetime.strptime(selected_date or "", "%Y-%m-%d"))
except ValueError:
selected = local_now
selected = min(selected, local_now)
range_start_local = selected.replace(hour=0, minute=0, second=0, microsecond=0)
range_start = range_start_local.timestamp()
range_end = min((range_start_local + timedelta(days=1)).timestamp(), time())
with self.session() as session:
rows = session.scalars(
select(_AppActivityEventData)
.where(
_AppActivityEventData.app_key == app_key,
_AppActivityEventData.created_at >= range_start,