Repository navigation
Expand file tree
/
Copy pathsync.py
More file actions
1720 lines (1510 loc) · 59.7 KB
/
Copy pathsync.py
File metadata and controls
1720 lines (1510 loc) · 59.7 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
from __future__ import annotations
import argparse
import json
import logging
import math
import os
import re
import sys
import time
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from datetime import date, datetime, timezone
from typing import Any
from urllib.parse import quote
import pandas as pd
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
LOG = logging.getLogger("steam_to_notion")
NOTION_VERSION = "2022-06-28"
STEAM_LOGO_URL = (
"https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg"
)
class SyncError(RuntimeError):
pass
@dataclass(frozen=True)
class Account:
steam_id: str
profile_id: str
account_name: str
@dataclass(frozen=True)
class FieldDef:
notion_name: str
record_key: str
notion_type: str
auto_create: bool = True
@dataclass
class Config:
steam_api_key: str
notion_api_key: str
notion_database_id: str
accounts: list[Account]
include_played_free_games: bool = True
enable_item_update: bool = True
enable_filter: bool = False
fetch_web_library: bool = False
fetch_store_metadata: bool = True
schema: str = "cn"
insert_fields: set[str] | None = None
update_fields: set[str] | None = None
sync_main_games_only: bool = True
skip_playtime_web: bool = True
use_account_field: bool = False
top_tags: int = 5
verify_cover_urls: bool = False
store_failure_limit: int = 3
refresh_store_metadata: bool = False
abandoned_days: int = 180
http_timeout: int = 15
http_retries: int = 2
request_delay: float = 0.4
export_csv_path: str | None = None
export_xlsx_path: str | None = None
dry_run: bool = False
mark_uploaded: bool = True
set_page_cover: bool = True
set_page_icon: bool = True
@classmethod
def from_env(cls, args: argparse.Namespace) -> "Config":
steam_api_key = env_any("STEAM_API_KEY", required=True)
notion_api_key = env_any("NOTION_API_KEY", default="")
notion_database_id = env_any("NOTION_DATABASE_ID", default="")
accounts = parse_accounts()
use_account_default = len(accounts) > 1
use_account_field = env_bool("USE_ACCOUNT_FIELD", use_account_default)
cfg = cls(
steam_api_key=steam_api_key,
notion_api_key=notion_api_key,
notion_database_id=notion_database_id,
accounts=accounts,
include_played_free_games=env_bool(
"INCLUDE_PLAYED_FREE_GAMES",
env_bool("include_played_free_games", True),
),
enable_item_update=env_bool(
"ENABLE_ITEM_UPDATE", env_bool("enable_item_update", True)
),
enable_filter=env_bool("ENABLE_FILTER", env_bool("enable_filter", False)),
fetch_web_library=env_bool(
"FETCH_WEB_LIBRARY", env_bool("FETCH_STEAM_WEB_LIBRARY", False)
),
fetch_store_metadata=env_bool("FETCH_STORE_METADATA", True),
schema=env_any("NOTION_SCHEMA", "FIELD_PRESET", default="cn").lower(),
insert_fields=env_field_set("INSERT_FIELDS"),
update_fields=env_field_set("UPDATE_FIELDS"),
sync_main_games_only=env_bool("SYNC_MAIN_GAMES_ONLY", True),
skip_playtime_web=env_bool("SKIP_PLAYTIME_WEB", True),
use_account_field=use_account_field,
top_tags=max(0, env_int("TOP_TAGS", 5)),
verify_cover_urls=env_bool("VERIFY_COVER_URLS", False),
store_failure_limit=max(1, env_int("STORE_FAILURE_LIMIT", 3)),
refresh_store_metadata=env_bool("REFRESH_STORE_METADATA", False),
abandoned_days=max(31, env_int("ABANDONED_DAYS", 180)),
http_timeout=max(5, env_int("HTTP_TIMEOUT", 15)),
http_retries=max(1, env_int("HTTP_RETRIES", 2)),
request_delay=max(0.0, env_float("REQUEST_DELAY", 0.4)),
export_csv_path=args.export_csv or env_any("EXPORT_CSV_PATH", default=""),
export_xlsx_path=args.export_xlsx or env_any("EXPORT_XLSX_PATH", default=""),
dry_run=args.dry_run or env_bool("DRY_RUN", False),
mark_uploaded=env_bool("MARK_UPLOADED", True),
set_page_cover=env_bool("SET_PAGE_COVER", True),
set_page_icon=env_bool("SET_PAGE_ICON", True),
)
if args.schema:
cfg.schema = args.schema
if cfg.schema == "english":
cfg.schema = "legacy"
if cfg.schema not in {"cn", "legacy"}:
raise SyncError("NOTION_SCHEMA 仅支持 cn 或 legacy")
if not cfg.dry_run and (not cfg.notion_api_key or not cfg.notion_database_id):
raise SyncError("同步到 Notion 需要设置 NOTION_API_KEY 和 NOTION_DATABASE_ID")
return cfg
@dataclass
class NotionSyncContext:
db_props: dict[str, str]
title_prop: str
field_defs: list[FieldDef]
existing_pages: dict[str, str]
key_property: str | None
store_metadata_cache: dict[str, dict[str, Any]]
FIELD_DEFS_CN: list[FieldDef] = [
FieldDef("游戏名称", "游戏名称", "title"),
FieldDef("游戏封面", "封面", "files"),
FieldDef("游戏ID", "游戏ID", "number"),
FieldDef("商店链接", "商店链接", "url"),
FieldDef("游玩时间", "游玩时间", "rich_text"),
FieldDef("总时长/h", "总时长小时", "number"),
FieldDef("完成度", "完成度", "number"),
FieldDef("成就总数", "成就总数", "number"),
FieldDef("已解锁成就", "已解锁成就", "number"),
FieldDef("首个成就解锁于", "首个成就时间", "date"),
FieldDef("最后游玩日期", "最后游玩", "date"),
FieldDef("游玩状态", "游玩状态", "status"),
FieldDef("开发商", "开发商", "rich_text"),
FieldDef("发行商", "发行商", "rich_text"),
FieldDef("发售日期", "发售日期", "date"),
FieldDef("商店标签", "商店标签", "multi_select"),
FieldDef("内容类型", "内容类型", "select"),
FieldDef("数据源", "数据源", "select"),
FieldDef("抓取来源", "抓取来源", "select"),
FieldDef("所属账户", "所属账户", "select"),
FieldDef("游戏简介", "游戏简介", "rich_text"),
FieldDef("评分", "评分", "number"),
]
FIELD_DEFS_LEGACY: list[FieldDef] = [
FieldDef("name", "游戏名称", "title"),
FieldDef("appid", "游戏ID", "number"),
FieldDef("playtime", "总时长小时", "number"),
FieldDef("last play", "最后游玩", "date"),
FieldDef("store url", "商店链接", "url"),
FieldDef("completion", "完成度", "number"),
FieldDef("total achievements", "成就总数", "number"),
FieldDef("achieved achievements", "已解锁成就", "number"),
FieldDef("info", "游戏简介", "rich_text"),
FieldDef("tags", "商店标签", "multi_select"),
FieldDef("type", "内容类型", "select"),
FieldDef("source", "抓取来源", "select"),
FieldDef("data source", "数据源", "select"),
FieldDef("account", "所属账户", "select"),
]
WEB_PLAYTIME_FIELDS = {
"游玩时间",
"最后游玩日期",
"总时长/h",
"playtime",
"last play",
}
SELECT_OPTIONS: dict[str, list[dict[str, str]]] = {
"内容类型": [
{"name": "游戏本体", "color": "green"},
{"name": "DLC", "color": "blue"},
{"name": "试玩版", "color": "yellow"},
{"name": "原声音轨", "color": "purple"},
{"name": "其它", "color": "gray"},
],
"数据源": [{"name": "Steam", "color": "blue"}],
"抓取来源": [
{"name": "API", "color": "green"},
{"name": "网页", "color": "orange"},
{"name": "两者都有", "color": "blue"},
{"name": "未知", "color": "gray"},
],
}
STATUS_OPTIONS = [
{"name": "未开始", "color": "gray", "group": "To-do"},
{"name": "游玩中", "color": "blue", "group": "In progress"},
{"name": "暂搁置", "color": "yellow", "group": "In progress"},
{"name": "已弃坑", "color": "red", "group": "Complete"},
{"name": "已通关", "color": "green", "group": "Complete"},
{"name": "全成就", "color": "purple", "group": "Complete"},
]
def env_any(*names: str, default: str | None = None, required: bool = False) -> str:
for name in names:
value = os.environ.get(name)
if value is not None and value.strip() != "":
return value.strip()
if required:
joined = " / ".join(names)
raise SyncError(f"缺少环境变量:{joined}")
return default or ""
def env_bool(name: str, default: bool) -> bool:
value = os.environ.get(name)
if value is None or value.strip() == "":
return default
return value.strip().lower() in {"1", "true", "yes", "y", "on"}
def env_int(name: str, default: int) -> int:
value = os.environ.get(name)
if value is None or value.strip() == "":
return default
try:
return int(value)
except ValueError:
return default
def env_float(name: str, default: float) -> float:
value = os.environ.get(name)
if value is None or value.strip() == "":
return default
try:
return float(value)
except ValueError:
return default
def env_field_set(name: str) -> set[str] | None:
value = env_any(name, default="")
if not value:
return None
fields = [item.strip() for item in re.split(r"[,,;;|]", value) if item.strip()]
return set(fields) or None
def redact_secrets(text: str) -> str:
return re.sub(
r"([?&](?:key|access_token|auth|token|secret)=)[^&\s)]+",
r"\1***",
text,
flags=re.IGNORECASE,
)
def normalize_steam_identity(value: str) -> str:
text = value.strip().rstrip("/")
match = re.search(r"steamcommunity\.com/(?:profiles|id)/([^/?#]+)", text)
if match:
return match.group(1)
return text
def parse_accounts() -> list[Account]:
raw_accounts = env_any("STEAM_ACCOUNTS", default="")
accounts: list[Account] = []
if raw_accounts:
try:
parsed = json.loads(raw_accounts)
except json.JSONDecodeError as exc:
raise SyncError("STEAM_ACCOUNTS 必须是 JSON 数组") from exc
if not isinstance(parsed, list):
raise SyncError("STEAM_ACCOUNTS 必须是 JSON 数组")
for idx, item in enumerate(parsed, start=1):
if not isinstance(item, dict):
raise SyncError(f"STEAM_ACCOUNTS 第 {idx} 项必须是对象")
steam_id = normalize_steam_identity(
str(item.get("steam_id") or item.get("STEAM_USER_ID") or "")
)
profile_id = normalize_steam_identity(str(
item.get("profile_id") or item.get("profile") or steam_id
))
account_name = str(
item.get("account")
or item.get("account_name")
or item.get("name")
or profile_id
).strip()
if not steam_id:
raise SyncError(f"STEAM_ACCOUNTS 第 {idx} 项缺少 steam_id")
accounts.append(Account(steam_id, profile_id or steam_id, account_name))
else:
steam_id = normalize_steam_identity(env_any("STEAM_USER_ID", required=True))
profile_id = normalize_steam_identity(env_any("STEAM_PROFILE_ID", default=steam_id))
account_name = env_any("STEAM_ACCOUNT_NAME", default=profile_id)
accounts.append(Account(steam_id, profile_id, account_name))
return accounts
def is_blank(value: Any) -> bool:
if value is None:
return True
if isinstance(value, float) and math.isnan(value):
return True
if isinstance(value, str) and value.strip() == "":
return True
return False
def text_or_none(value: Any) -> str | None:
if is_blank(value):
return None
return str(value).strip()
def number_or_none(value: Any) -> float | None:
if is_blank(value):
return None
try:
if isinstance(value, str):
value = value.replace(",", "")
number = float(value)
except (TypeError, ValueError):
return None
if math.isnan(number):
return None
return number
def int_key(value: Any) -> str | None:
number = number_or_none(value)
if number is None:
return None
return str(int(number))
def chunks(text: str, size: int = 2000) -> list[str]:
return [text[i : i + size] for i in range(0, len(text), size)] or [""]
def parse_date(value: Any) -> str | None:
if isinstance(value, date) and not isinstance(value, datetime):
return value.isoformat()
if isinstance(value, datetime):
return value.date().isoformat()
if is_blank(value):
return None
text = str(value).strip()
text = re.sub(r"\s+", " ", text)
if text in {"此版本无成就", "未知", "无"}:
return None
chinese_match = re.search(r"(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日", text)
if chinese_match:
year, month, day = map(int, chinese_match.groups())
return date(year, month, day).isoformat()
for fmt in (
"%Y-%m-%d",
"%Y/%m/%d",
"%Y.%m.%d",
"%Y-%m-%d %H:%M:%S",
"%b %d, %Y",
"%d %b, %Y",
"%B %d, %Y",
"%d %B, %Y",
"%m/%d/%Y",
):
try:
return datetime.strptime(text, fmt).date().isoformat()
except ValueError:
continue
return None
def timestamp_to_date(value: Any) -> str | None:
number = number_or_none(value)
if number is None or number <= 0:
return None
return datetime.fromtimestamp(number, tz=timezone.utc).date().isoformat()
def is_steam_id64(value: str | None) -> bool:
return bool(value and re.fullmatch(r"\d{17}", value.strip()))
def steam_profile_path(profile_id: str) -> str:
profile = profile_id.strip()
if is_steam_id64(profile):
return f"profiles/{profile}"
return f"id/{quote(profile)}"
def format_playtime(minutes: Any) -> str:
mins = number_or_none(minutes)
if mins is None or mins <= 0:
return "0"
if mins < 60:
return f"{int(round(mins))} 分钟"
return f"{round(mins / 60, 2)} 小时"
class HttpClient:
def __init__(self, timeout: int = 25, retries: int = 3) -> None:
self.timeout = timeout
self.retries = retries
self.session = requests.Session()
self.session.headers.update(
{
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/115.0.0.0 Safari/537.36"
)
}
)
def request(self, method: str, url: str, **kwargs: Any) -> requests.Response:
kwargs.setdefault("timeout", self.timeout)
for attempt in range(1, self.retries + 1):
response: requests.Response | None = None
try:
response = self.session.request(method, url, **kwargs)
if response.status_code in {429, 500, 502, 503, 504}:
retry_after = response.headers.get("Retry-After")
delay = float(retry_after) if retry_after else min(2 * attempt, 10)
LOG.warning(
"请求 %s %s 返回 %s,%.1f 秒后重试",
method.upper(),
url,
response.status_code,
delay,
)
time.sleep(delay)
continue
if not response.ok:
detail = redact_secrets(response.text[:500])
raise SyncError(
f"请求失败:{method.upper()} {url} -> "
f"HTTP {response.status_code}: {detail}"
)
return response
except requests.RequestException as exc:
if attempt >= self.retries:
detail = (
response.text[:500] if response is not None else str(exc)
)
raise SyncError(
f"请求失败:{method.upper()} {url} -> "
f"{redact_secrets(detail)}"
) from None
time.sleep(min(2 * attempt, 10))
raise SyncError(f"请求失败:{method.upper()} {url}")
class SteamClient:
def __init__(
self,
http: HttpClient,
config: Config,
store_metadata_cache: dict[str, dict[str, Any]] | None = None,
) -> None:
self.http = http
self.config = config
self.store_metadata_cache = store_metadata_cache or {}
self._steam_id64_cache: dict[str, str] = {}
self._store_network_failures = 0
self._store_metadata_disabled = False
self._store_cache_hits = 0
self._store_cache_misses = 0
self._store_fetches = 0
def resolve_steam_id64(self, account: Account) -> str:
raw_id = account.steam_id.strip()
if is_steam_id64(raw_id):
return raw_id
if raw_id in self._steam_id64_cache:
return self._steam_id64_cache[raw_id]
candidates = unique_keys([raw_id, account.profile_id.strip()])
for candidate in candidates:
if is_steam_id64(candidate):
self._steam_id64_cache[raw_id] = candidate
return candidate
try:
response = self.http.request(
"GET",
"https://api.steampowered.com/ISteamUser/ResolveVanityURL/v1/",
params={
"key": self.config.steam_api_key,
"vanityurl": candidate,
},
)
except SyncError as exc:
LOG.warning("解析 Steam 自定义 ID 失败(%s):%s", candidate, exc)
continue
payload = response.json().get("response", {})
if payload.get("success") == 1 and payload.get("steamid"):
steam_id64 = str(payload["steamid"])
self._steam_id64_cache[raw_id] = steam_id64
LOG.info("已将 Steam 自定义 ID %s 解析为 SteamID64", candidate)
return steam_id64
raise SyncError(
"无法把 STEAM_USER_ID 解析为 17 位 SteamID64。"
"请填 SteamID64,或确认自定义短链接名是否正确。"
)
def get_owned_games(self, account: Account) -> pd.DataFrame:
steam_id64 = self.resolve_steam_id64(account)
params = {
"key": self.config.steam_api_key,
"steamid": steam_id64,
"include_appinfo": 1,
}
if self.config.include_played_free_games:
params["include_played_free_games"] = 1
response = self.http.request(
"GET",
"https://api.steampowered.com/IPlayerService/GetOwnedGames/v1/",
params=params,
)
games = response.json().get("response", {}).get("games", [])
df = pd.DataFrame(games)
if df.empty:
return pd.DataFrame(
columns=[
"appid",
"name",
"playtime_forever",
"rtime_last_played",
"img_icon_url",
]
)
keep = [
"appid",
"name",
"playtime_forever",
"rtime_last_played",
"img_icon_url",
]
for column in keep:
if column not in df.columns:
df[column] = None
return df[keep]
def get_all_games_web(self, account: Account) -> pd.DataFrame:
if not self.config.fetch_web_library:
return pd.DataFrame(columns=["appid", "name_web", "hours_total_web"])
path = steam_profile_path(account.profile_id)
url = f"https://steamcommunity.com/{path}/games?xml=1"
try:
response = self.http.request("GET", url, timeout=min(self.http.timeout, 10))
root = ET.fromstring(response.content)
except Exception as exc:
LOG.warning(
"无法抓取 Steam XML 游戏库(%s),已仅使用 Steam API 数据:%s",
account.account_name,
exc,
)
return pd.DataFrame(columns=["appid", "name_web", "hours_total_web"])
rows: list[dict[str, Any]] = []
for game_node in root.findall(".//game"):
appid = game_node.findtext("appID")
if not appid:
continue
hours_text = game_node.findtext("hoursOnRecord")
hours = number_or_none(hours_text)
rows.append(
{
"appid": int(appid),
"name_web": game_node.findtext("name"),
"hours_total_web": hours,
}
)
return pd.DataFrame(rows, columns=["appid", "name_web", "hours_total_web"])
def merge_games(self, api_games: pd.DataFrame, web_games: pd.DataFrame) -> pd.DataFrame:
api = api_games.copy()
web = web_games.copy()
api["from_api"] = True
web["from_web"] = True
merged = pd.merge(api, web, how="outer", on="appid")
if merged.empty:
return merged
merged["from_api"] = merged["from_api"].eq(True)
merged["from_web"] = merged["from_web"].eq(True)
merged["name"] = merged["name"].combine_first(merged["name_web"])
missing_api_minutes = merged["playtime_forever"].isna() & merged[
"hours_total_web"
].notna()
merged.loc[missing_api_minutes, "playtime_forever"] = (
merged.loc[missing_api_minutes, "hours_total_web"].astype(float) * 60
).round()
def source(row: pd.Series) -> str:
if row["from_api"] and row["from_web"]:
return "两者都有"
if row["from_api"]:
return "API"
if row["from_web"]:
return "网页"
return "未知"
merged["抓取来源"] = merged.apply(source, axis=1)
merged = merged.drop_duplicates(subset=["appid"], keep="first")
return merged.sort_values("name", na_position="last").reset_index(drop=True)
def get_achievements(self, account: Account, appid: int) -> dict[str, Any]:
steam_id64 = self.resolve_steam_id64(account)
params = {
"key": self.config.steam_api_key,
"steamid": steam_id64,
"appid": appid,
}
try:
response = self.http.request(
"GET",
"https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v1/",
params=params,
)
data = response.json().get("playerstats", {})
except SyncError:
return {"total": 0, "achieved": 0, "first_unlock": None}
achievements = data.get("achievements") or []
if not isinstance(achievements, list):
return {"total": 0, "achieved": 0, "first_unlock": None}
unlocked = [
item
for item in achievements
if item.get("achieved") in {1, True} and number_or_none(item.get("unlocktime"))
]
first_unlock = None
if unlocked:
first_unlock_time = min(int(item["unlocktime"]) for item in unlocked)
first_unlock = timestamp_to_date(first_unlock_time)
return {"total": len(achievements), "achieved": len(unlocked), "first_unlock": first_unlock}
def get_store_info(
self, appid: int, account: Account, api_name: str | None = None
) -> dict[str, Any]:
cached = self.lookup_store_metadata(appid, account, api_name)
if cached and not self.config.refresh_store_metadata:
missing_fields = missing_store_metadata_fields(cached)
if not missing_fields or not self.config.fetch_store_metadata:
self._store_cache_hits += 1
return cached
LOG.debug(
"AppID %s Notion 元数据缺失:%s",
appid,
", ".join(missing_fields),
)
self._store_cache_misses += 1
elif self.store_metadata_cache and not cached:
self._store_cache_misses += 1
if not self.config.fetch_store_metadata or self._store_metadata_disabled:
return cached or self.empty_store_info()
data, region, network_failed = self.fetch_appdetails(appid, "cn", "zh-cn")
if data is None:
data, region, us_network_failed = self.fetch_appdetails(appid, "us", "en")
network_failed = network_failed or us_network_failed
if data is None:
if network_failed:
self._store_network_failures += 1
if self._store_network_failures >= self.config.store_failure_limit:
self._store_metadata_disabled = True
LOG.warning(
"Steam 商店接口连续失败 %s 次,后续本次运行将跳过商店元数据",
self._store_network_failures,
)
return cached or self.empty_store_info(region=region or "未知")
html_info = self.fetch_store_html_info(appid)
content_type = {
"game": "游戏本体",
"dlc": "DLC",
"music": "原声音轨",
"demo": "试玩版",
}.get(str(data.get("type", "")).lower(), "其它")
tags = html_info.get("tags") or [
str(genre.get("description", "")).strip()
for genre in data.get("genres") or []
if str(genre.get("description", "")).strip()
]
cover_url = (
data.get("header_image")
or data.get("capsule_image")
or data.get("capsule_imagev5")
or self.get_cover_url(appid)
)
self._store_fetches += 1
return {
"store_name": data.get("name"),
"cn_title": html_info.get("cn_title") or data.get("name"),
"description": html_info.get("description")
or data.get("short_description")
or "",
"developers": ", ".join(data.get("developers") or []),
"publishers": ", ".join(data.get("publishers") or []),
"release_date": parse_date((data.get("release_date") or {}).get("date")),
"tags": tags,
"content_type": content_type,
"region": region,
"cover_url": cover_url,
}
def lookup_store_metadata(
self, appid: int, account: Account, api_name: str | None
) -> dict[str, Any] | None:
if not self.store_metadata_cache:
return None
for key in metadata_lookup_keys(
appid=appid,
title=api_name,
account_name=account.account_name,
use_account_field=self.config.use_account_field,
):
cached = self.store_metadata_cache.get(key)
if cached:
return cached
return None
def empty_store_info(self, region: str = "未知") -> dict[str, Any]:
return {
"store_name": None,
"cn_title": None,
"description": "",
"developers": "",
"publishers": "",
"release_date": None,
"tags": [],
"content_type": "游戏本体",
"region": region,
}
def fetch_appdetails(
self, appid: int, country: str, language: str
) -> tuple[dict[str, Any] | None, str, bool]:
try:
response = self.http.request(
"GET",
"https://store.steampowered.com/api/appdetails",
params={"appids": appid, "cc": country, "l": language},
timeout=min(self.http.timeout, 10),
)
payload = response.json().get(str(appid), {})
except SyncError as exc:
LOG.warning("AppID %s 商店 API 请求失败:%s", appid, exc)
return None, country.upper(), True
if payload.get("success") and payload.get("data"):
return payload["data"], country.upper(), False
return None, country.upper(), False
def fetch_store_html_info(self, appid: int) -> dict[str, Any]:
url = f"https://store.steampowered.com/app/{appid}/?l=schinese"
headers = {
"Cookie": (
"birthtime=568022401; lastagecheckage=1-January-1990; "
"wants_mature_content=1"
)
}
try:
response = self.http.request(
"GET",
url,
headers=headers,
timeout=min(self.http.timeout, 10),
)
except SyncError:
return {"cn_title": None, "description": "", "tags": []}
soup = BeautifulSoup(response.text, "html.parser")
title_node = soup.select_one(".apphub_AppName")
description_node = soup.select_one(".game_description_snippet")
tag_nodes = soup.select(".glance_tags.popular_tags a.app_tag") or soup.select(
"a.app_tag"
)
tags = [
tag.get_text(strip=True)
for tag in tag_nodes[: self.config.top_tags]
if tag.get_text(strip=True)
]
return {
"cn_title": title_node.get_text(strip=True) if title_node else None,
"description": (
description_node.get_text(strip=True) if description_node else ""
),
"tags": tags,
}
def get_cover_url(self, appid: int) -> str:
base = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}"
candidates = [
f"{base}/capsule_616x353.jpg",
f"{base}/header.jpg",
]
if not self.config.verify_cover_urls:
return candidates[0]
for url in candidates:
try:
response = self.http.session.head(url, timeout=5, allow_redirects=True)
if response.status_code == 200:
return url
except requests.RequestException:
continue
return candidates[-1]
def build_dataframe(self) -> pd.DataFrame:
records: list[dict[str, Any]] = []
for account in self.config.accounts:
LOG.info("开始抓取账号 %s", account.account_name)
api_games = self.get_owned_games(account)
web_games = self.get_all_games_web(account)
games = self.merge_games(api_games, web_games)
LOG.info(
"账号 %s 合并后共 %s 个游戏", account.account_name, len(games)
)
for index, game in games.iterrows():
appid = int(game["appid"])
name = text_or_none(game.get("name")) or f"App {appid}"
LOG.info("[%s/%s] 处理 %s", index + 1, len(games), name)
records.append(self.build_record(account, game))
if self.config.request_delay:
time.sleep(self.config.request_delay)
if self.store_metadata_cache:
LOG.info(
"商店元数据缓存:命中 %s,缺失/不完整 %s,实际抓取 %s",
self._store_cache_hits,
self._store_cache_misses,
self._store_fetches,
)
return pd.DataFrame(records)
def build_record(self, account: Account, game: pd.Series) -> dict[str, Any]:
appid = int(game["appid"])
api_name = text_or_none(game.get("name"))
store = self.get_store_info(appid, account, api_name)
achievements = self.get_achievements(account, appid)
minutes = number_or_none(game.get("playtime_forever"))
hours = round(minutes / 60, 2) if minutes is not None else None
title = store.get("cn_title") or store.get("store_name") or api_name or f"App {appid}"
total_achievements = achievements["total"]
achieved_achievements = achievements["achieved"]
completion = (
round(achieved_achievements / total_achievements, 4)
if total_achievements
else None
)
content_type = store.get("content_type") or "其它"
record = {
"游戏名称": title,
"游戏ID": appid,
"商店链接": f"https://store.steampowered.com/app/{appid}",
"游玩时间": format_playtime(minutes),
"总时长小时": hours,
"最后游玩": timestamp_to_date(game.get("rtime_last_played")),
"成就总数": total_achievements,
"已解锁成就": achieved_achievements,
"完成度": completion,
"首个成就时间": achievements["first_unlock"],
"开发商": store.get("developers"),
"发行商": store.get("publishers"),
"发售日期": store.get("release_date"),
"商店标签": store.get("tags") or [],
"数据源": "Steam",
"抓取来源": game.get("抓取来源"),
"内容类型": content_type,
"封面": store.get("cover_url") or self.get_cover_url(appid),
"所属账户": account.account_name,
"游戏简介": store.get("description") or "",
}
record["游玩状态"] = get_game_status(
record,
abandoned_days=self.config.abandoned_days,
)
return record
class NotionClient:
def __init__(self, http: HttpClient, config: Config) -> None:
self.http = http
self.config = config
@property
def headers(self) -> dict[str, str]:
return {
"Authorization": f"Bearer {self.config.notion_api_key}",
"Content-Type": "application/json",
"Notion-Version": NOTION_VERSION,
}
def retrieve_database(self) -> dict[str, Any]:
url = f"https://api.notion.com/v1/databases/{self.config.notion_database_id}"
return self.http.request("GET", url, headers=self.headers).json()
def update_database_schema(self, properties: dict[str, Any]) -> dict[str, Any]:
url = f"https://api.notion.com/v1/databases/{self.config.notion_database_id}"
return self.http.request(
"PATCH",
url,
headers=self.headers,
json={"properties": properties},
).json()
def ensure_database_schema(
self,
db_props: dict[str, str],
title_prop: str,
field_defs: list[FieldDef],
) -> dict[str, str]:
missing_schemas: dict[str, Any] = {}
for field in field_defs:
if not field.auto_create:
continue
if field.notion_type == "title":
continue
if field.notion_name in db_props:
continue
schema = notion_property_schema(field.notion_name, field.notion_type)
if schema:
missing_schemas[field.notion_name] = schema
if (
self.config.mark_uploaded
and "已上传" not in db_props
and self.config.schema == "cn"
):
missing_schemas["已上传"] = {"checkbox": {}}
if not missing_schemas:
return db_props
LOG.info("Notion 缺少字段,自动创建:%s", ", ".join(missing_schemas))
new_props = dict(db_props)
for name, schema in missing_schemas.items():
try:
database = self.update_database_schema({name: schema})
except SyncError:
if name == "游玩状态" and "status" in schema:
LOG.warning("创建 status 字段失败,改用 select 字段:%s", name)
database = self.update_database_schema(
{name: status_as_select_schema()}
)
else:
raise
new_props = {
prop_name: meta.get("type", "")
for prop_name, meta in database.get("properties", {}).items()
}
if title_prop not in new_props:
new_props[title_prop] = "title"
return new_props