remote.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. # coding=utf-8
  2. """
  3. 远程存储后端(S3 兼容协议)
  4. 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等
  5. 使用 S3 兼容 API (boto3) 访问对象存储
  6. 数据流程:下载当天 SQLite → 合并新数据 → 上传回远程
  7. """
  8. import pytz
  9. import re
  10. import shutil
  11. import sys
  12. import tempfile
  13. import sqlite3
  14. from datetime import datetime, timedelta
  15. from pathlib import Path
  16. from typing import Dict, List, Optional
  17. try:
  18. import boto3
  19. from botocore.config import Config as BotoConfig
  20. from botocore.exceptions import ClientError
  21. HAS_BOTO3 = True
  22. except ImportError:
  23. HAS_BOTO3 = False
  24. boto3 = None
  25. BotoConfig = None
  26. ClientError = Exception
  27. from trendradar.storage.base import StorageBackend, NewsItem, NewsData, RSSItem, RSSData
  28. from trendradar.storage.sqlite_mixin import SQLiteStorageMixin
  29. from trendradar.utils.time import (
  30. get_configured_time,
  31. format_date_folder,
  32. format_time_filename,
  33. )
  34. class RemoteStorageBackend(SQLiteStorageMixin, StorageBackend):
  35. """
  36. 远程云存储后端(S3 兼容协议)
  37. 特点:
  38. - 使用 S3 兼容 API 访问远程存储
  39. - 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等
  40. - 下载 SQLite 到临时目录进行操作
  41. - 支持数据合并和上传
  42. - 支持从远程拉取历史数据到本地
  43. - 运行结束后自动清理临时文件
  44. """
  45. def __init__(
  46. self,
  47. bucket_name: str,
  48. access_key_id: str,
  49. secret_access_key: str,
  50. endpoint_url: str,
  51. region: str = "",
  52. enable_txt: bool = False, # 远程模式默认不生成 TXT
  53. enable_html: bool = True,
  54. temp_dir: Optional[str] = None,
  55. timezone: str = "Asia/Shanghai",
  56. ):
  57. """
  58. 初始化远程存储后端
  59. Args:
  60. bucket_name: 存储桶名称
  61. access_key_id: 访问密钥 ID
  62. secret_access_key: 访问密钥
  63. endpoint_url: 服务端点 URL
  64. region: 区域(可选,部分服务商需要)
  65. enable_txt: 是否启用 TXT 快照(默认关闭)
  66. enable_html: 是否启用 HTML 报告
  67. temp_dir: 临时目录路径(默认使用系统临时目录)
  68. timezone: 时区配置(默认 Asia/Shanghai)
  69. """
  70. if not HAS_BOTO3:
  71. raise ImportError("远程存储后端需要安装 boto3: pip install boto3")
  72. self.bucket_name = bucket_name
  73. self.endpoint_url = endpoint_url
  74. self.region = region
  75. self.enable_txt = enable_txt
  76. self.enable_html = enable_html
  77. self.timezone = timezone
  78. # 创建临时目录
  79. self.temp_dir = Path(temp_dir) if temp_dir else Path(tempfile.mkdtemp(prefix="trendradar_"))
  80. self.temp_dir.mkdir(parents=True, exist_ok=True)
  81. # 初始化 S3 客户端
  82. # 使用 virtual-hosted style addressing(主流)
  83. # 根据服务商选择签名版本:
  84. # - 腾讯云 COS 使用 SigV2 以避免 chunked encoding 问题
  85. # - 其他服务商(AWS S3、Cloudflare R2、阿里云 OSS、MinIO 等)默认使用 SigV4
  86. is_tencent_cos = "myqcloud.com" in endpoint_url.lower()
  87. signature_version = 's3' if is_tencent_cos else 's3v4'
  88. s3_config = BotoConfig(
  89. s3={"addressing_style": "virtual"},
  90. signature_version=signature_version,
  91. )
  92. client_kwargs = {
  93. "endpoint_url": endpoint_url,
  94. "aws_access_key_id": access_key_id,
  95. "aws_secret_access_key": secret_access_key,
  96. "config": s3_config,
  97. }
  98. if region:
  99. client_kwargs["region_name"] = region
  100. self.s3_client = boto3.client("s3", **client_kwargs)
  101. # 跟踪下载的文件(用于清理)
  102. self._downloaded_files: List[Path] = []
  103. self._db_connections: Dict[str, sqlite3.Connection] = {}
  104. print(f"[远程存储] 初始化完成,存储桶: {bucket_name},签名版本: {signature_version}")
  105. @property
  106. def backend_name(self) -> str:
  107. return "remote"
  108. @property
  109. def supports_txt(self) -> bool:
  110. return self.enable_txt
  111. # ========================================
  112. # SQLiteStorageMixin 抽象方法实现
  113. # ========================================
  114. def _get_configured_time(self) -> datetime:
  115. """获取配置时区的当前时间"""
  116. return get_configured_time(self.timezone)
  117. def _format_date_folder(self, date: Optional[str] = None) -> str:
  118. """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)"""
  119. return format_date_folder(date, self.timezone)
  120. def _format_time_filename(self) -> str:
  121. """格式化时间文件名 (格式: HH-MM)"""
  122. return format_time_filename(self.timezone)
  123. def _get_remote_db_key(self, date: Optional[str] = None, db_type: str = "news") -> str:
  124. """
  125. 获取远程存储中 SQLite 文件的对象键
  126. Args:
  127. date: 日期字符串
  128. db_type: 数据库类型 ("news" 或 "rss")
  129. Returns:
  130. 远程对象键,如 "news/2025-12-28.db" 或 "rss/2025-12-28.db"
  131. """
  132. date_folder = self._format_date_folder(date)
  133. return f"{db_type}/{date_folder}.db"
  134. def _get_local_db_path(self, date: Optional[str] = None, db_type: str = "news") -> Path:
  135. """
  136. 获取本地临时 SQLite 文件路径
  137. Args:
  138. date: 日期字符串
  139. db_type: 数据库类型 ("news" 或 "rss")
  140. Returns:
  141. 本地临时文件路径
  142. """
  143. date_folder = self._format_date_folder(date)
  144. db_dir = self.temp_dir / db_type
  145. db_dir.mkdir(parents=True, exist_ok=True)
  146. return db_dir / f"{date_folder}.db"
  147. def _check_object_exists(self, r2_key: str) -> bool:
  148. """
  149. 检查远程存储中对象是否存在
  150. Args:
  151. r2_key: 远程对象键
  152. Returns:
  153. 是否存在
  154. """
  155. try:
  156. self.s3_client.head_object(Bucket=self.bucket_name, Key=r2_key)
  157. return True
  158. except ClientError as e:
  159. error_code = e.response.get("Error", {}).get("Code", "")
  160. # S3 兼容存储可能返回 404, NoSuchKey, 或其他变体
  161. if error_code in ("404", "NoSuchKey", "Not Found"):
  162. return False
  163. # 其他错误(如权限问题)也视为不存在,但打印警告
  164. print(f"[远程存储] 检查对象存在性失败 ({r2_key}): {e}")
  165. return False
  166. except Exception as e:
  167. print(f"[远程存储] 检查对象存在性异常 ({r2_key}): {e}")
  168. return False
  169. def _download_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> Optional[Path]:
  170. """
  171. 从远程存储下载当天的 SQLite 文件到本地临时目录
  172. 使用 get_object + iter_chunks 替代 download_file,
  173. 以正确处理腾讯云 COS 的 chunked transfer encoding。
  174. Args:
  175. date: 日期字符串
  176. db_type: 数据库类型 ("news" 或 "rss")
  177. Returns:
  178. 本地文件路径,如果不存在返回 None
  179. """
  180. r2_key = self._get_remote_db_key(date, db_type)
  181. local_path = self._get_local_db_path(date, db_type)
  182. # 确保目录存在
  183. local_path.parent.mkdir(parents=True, exist_ok=True)
  184. # 先检查文件是否存在
  185. if not self._check_object_exists(r2_key):
  186. print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}")
  187. return None
  188. try:
  189. # 使用 get_object + iter_chunks 替代 download_file
  190. # iter_chunks 会自动处理 chunked transfer encoding
  191. response = self.s3_client.get_object(Bucket=self.bucket_name, Key=r2_key)
  192. with open(local_path, 'wb') as f:
  193. for chunk in response['Body'].iter_chunks(chunk_size=1024*1024):
  194. f.write(chunk)
  195. self._downloaded_files.append(local_path)
  196. print(f"[远程存储] 已下载: {r2_key} -> {local_path}")
  197. return local_path
  198. except ClientError as e:
  199. error_code = e.response.get("Error", {}).get("Code", "")
  200. # S3 兼容存储可能返回不同的错误码
  201. if error_code in ("404", "NoSuchKey", "Not Found"):
  202. print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}")
  203. return None
  204. else:
  205. print(f"[远程存储] 下载失败 (错误码: {error_code}): {e}")
  206. raise
  207. except Exception as e:
  208. print(f"[远程存储] 下载异常: {e}")
  209. raise
  210. def _upload_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> bool:
  211. """
  212. 上传本地 SQLite 文件到远程存储
  213. Args:
  214. date: 日期字符串
  215. db_type: 数据库类型 ("news" 或 "rss")
  216. Returns:
  217. 是否上传成功
  218. """
  219. local_path = self._get_local_db_path(date, db_type)
  220. r2_key = self._get_remote_db_key(date, db_type)
  221. if not local_path.exists():
  222. print(f"[远程存储] 本地文件不存在,无法上传: {local_path}")
  223. return False
  224. try:
  225. # 获取本地文件大小
  226. local_size = local_path.stat().st_size
  227. print(f"[远程存储] 准备上传: {local_path} ({local_size} bytes) -> {r2_key}")
  228. # 读取文件内容为 bytes 后上传
  229. # 避免传入文件对象时 requests 库使用 chunked transfer encoding
  230. # 腾讯云 COS 等 S3 兼容服务可能无法正确处理 chunked encoding
  231. with open(local_path, 'rb') as f:
  232. file_content = f.read()
  233. # 使用 put_object 并明确设置 ContentLength,确保不使用 chunked encoding
  234. self.s3_client.put_object(
  235. Bucket=self.bucket_name,
  236. Key=r2_key,
  237. Body=file_content,
  238. ContentLength=local_size,
  239. ContentType='application/x-sqlite3',
  240. )
  241. print(f"[远程存储] 已上传: {local_path} -> {r2_key}")
  242. # 验证上传成功
  243. if self._check_object_exists(r2_key):
  244. print(f"[远程存储] 上传验证成功: {r2_key}")
  245. return True
  246. else:
  247. print(f"[远程存储] 上传验证失败: 文件未在远程存储中找到")
  248. return False
  249. except Exception as e:
  250. print(f"[远程存储] 上传失败: {e}")
  251. return False
  252. def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection:
  253. """
  254. 获取数据库连接
  255. Args:
  256. date: 日期字符串
  257. db_type: 数据库类型 ("news" 或 "rss")
  258. Returns:
  259. 数据库连接
  260. """
  261. local_path = self._get_local_db_path(date, db_type)
  262. db_path = str(local_path)
  263. if db_path not in self._db_connections:
  264. # 确保目录存在
  265. local_path.parent.mkdir(parents=True, exist_ok=True)
  266. # 如果本地不存在,尝试从远程存储下载
  267. if not local_path.exists():
  268. self._download_sqlite(date, db_type)
  269. conn = sqlite3.connect(db_path)
  270. conn.row_factory = sqlite3.Row
  271. self._init_tables(conn, db_type)
  272. self._db_connections[db_path] = conn
  273. return self._db_connections[db_path]
  274. # ========================================
  275. # StorageBackend 接口实现(委托给 mixin + 上传)
  276. # ========================================
  277. def save_news_data(self, data: NewsData) -> bool:
  278. """
  279. 保存新闻数据到远程存储
  280. 流程:下载现有数据库 → 插入/更新数据 → 上传回远程存储
  281. """
  282. # 查询已有记录数
  283. conn = self._get_connection(data.date)
  284. cursor = conn.cursor()
  285. cursor.execute("SELECT COUNT(*) as count FROM news_items")
  286. row = cursor.fetchone()
  287. existing_count = row[0] if row else 0
  288. if existing_count > 0:
  289. print(f"[远程存储] 已有 {existing_count} 条历史记录,将合并新数据")
  290. # 使用 mixin 的实现保存数据
  291. success, new_count, updated_count, title_changed_count, off_list_count = \
  292. self._save_news_data_impl(data, "[远程存储]")
  293. if not success:
  294. return False
  295. # 查询合并后的总记录数
  296. cursor.execute("SELECT COUNT(*) as count FROM news_items")
  297. row = cursor.fetchone()
  298. final_count = row[0] if row else 0
  299. # 输出详细的存储统计日志
  300. log_parts = [f"[远程存储] 处理完成:新增 {new_count} 条"]
  301. if updated_count > 0:
  302. log_parts.append(f"更新 {updated_count} 条")
  303. if title_changed_count > 0:
  304. log_parts.append(f"标题变更 {title_changed_count} 条")
  305. if off_list_count > 0:
  306. log_parts.append(f"脱榜 {off_list_count} 条")
  307. log_parts.append(f"(去重后总计: {final_count} 条)")
  308. print(",".join(log_parts))
  309. # 上传到远程存储
  310. if self._upload_sqlite(data.date):
  311. print(f"[远程存储] 数据已同步到远程存储")
  312. return True
  313. else:
  314. print(f"[远程存储] 上传远程存储失败")
  315. return False
  316. def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  317. """获取指定日期的所有新闻数据(合并后)"""
  318. return self._get_today_all_data_impl(date)
  319. def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  320. """获取最新一次抓取的数据"""
  321. return self._get_latest_crawl_data_impl(date)
  322. def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]:
  323. """检测新增的标题"""
  324. return self._detect_new_titles_impl(current_data)
  325. def is_first_crawl_today(self, date: Optional[str] = None) -> bool:
  326. """检查是否是当天第一次抓取"""
  327. return self._is_first_crawl_today_impl(date)
  328. def has_pushed_today(self, date: Optional[str] = None) -> bool:
  329. """检查指定日期是否已推送过"""
  330. return self._has_pushed_today_impl(date)
  331. def record_push(self, report_type: str, date: Optional[str] = None) -> bool:
  332. """记录推送"""
  333. success = self._record_push_impl(report_type, date)
  334. if success:
  335. now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S")
  336. print(f"[远程存储] 推送记录已保存: {report_type} at {now_str}")
  337. # 上传到远程存储 确保记录持久化
  338. if self._upload_sqlite(date):
  339. print(f"[远程存储] 推送记录已同步到远程存储")
  340. return True
  341. else:
  342. print(f"[远程存储] 推送记录同步到远程存储失败")
  343. return False
  344. return False
  345. # ========================================
  346. # RSS 数据存储方法
  347. # ========================================
  348. def save_rss_data(self, data: RSSData) -> bool:
  349. """
  350. 保存 RSS 数据到远程存储
  351. 流程:下载现有数据库 → 插入/更新数据 → 上传回远程存储
  352. """
  353. success, new_count, updated_count = self._save_rss_data_impl(data, "[远程存储]")
  354. if not success:
  355. return False
  356. # 输出统计日志
  357. log_parts = [f"[远程存储] RSS 处理完成:新增 {new_count} 条"]
  358. if updated_count > 0:
  359. log_parts.append(f"更新 {updated_count} 条")
  360. print(",".join(log_parts))
  361. # 上传到远程存储
  362. if self._upload_sqlite(data.date, db_type="rss"):
  363. print(f"[远程存储] RSS 数据已同步到远程存储")
  364. return True
  365. else:
  366. print(f"[远程存储] RSS 上传远程存储失败")
  367. return False
  368. def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]:
  369. """获取指定日期的所有 RSS 数据"""
  370. return self._get_rss_data_impl(date)
  371. def detect_new_rss_items(self, current_data: RSSData) -> Dict[str, List[RSSItem]]:
  372. """检测新增的 RSS 条目"""
  373. return self._detect_new_rss_items_impl(current_data)
  374. def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]:
  375. """获取最新一次抓取的 RSS 数据"""
  376. return self._get_latest_rss_data_impl(date)
  377. # ========================================
  378. # 远程特有功能:TXT/HTML 快照(临时目录)
  379. # ========================================
  380. def save_txt_snapshot(self, data: NewsData) -> Optional[str]:
  381. """保存 TXT 快照(远程存储模式下默认不支持)"""
  382. if not self.enable_txt:
  383. return None
  384. # 如果启用,保存到本地临时目录
  385. try:
  386. date_folder = self._format_date_folder(data.date)
  387. txt_dir = self.temp_dir / date_folder / "txt"
  388. txt_dir.mkdir(parents=True, exist_ok=True)
  389. file_path = txt_dir / f"{data.crawl_time}.txt"
  390. with open(file_path, "w", encoding="utf-8") as f:
  391. for source_id, news_list in data.items.items():
  392. source_name = data.id_to_name.get(source_id, source_id)
  393. if source_name and source_name != source_id:
  394. f.write(f"{source_id} | {source_name}\n")
  395. else:
  396. f.write(f"{source_id}\n")
  397. sorted_news = sorted(news_list, key=lambda x: x.rank)
  398. for item in sorted_news:
  399. line = f"{item.rank}. {item.title}"
  400. if item.url:
  401. line += f" [URL:{item.url}]"
  402. if item.mobile_url:
  403. line += f" [MOBILE:{item.mobile_url}]"
  404. f.write(line + "\n")
  405. f.write("\n")
  406. if data.failed_ids:
  407. f.write("==== 以下ID请求失败 ====\n")
  408. for failed_id in data.failed_ids:
  409. f.write(f"{failed_id}\n")
  410. print(f"[远程存储] TXT 快照已保存: {file_path}")
  411. return str(file_path)
  412. except Exception as e:
  413. print(f"[远程存储] 保存 TXT 快照失败: {e}")
  414. return None
  415. def save_html_report(self, html_content: str, filename: str, is_summary: bool = False) -> Optional[str]:
  416. """保存 HTML 报告到临时目录"""
  417. if not self.enable_html:
  418. return None
  419. try:
  420. date_folder = self._format_date_folder()
  421. html_dir = self.temp_dir / date_folder / "html"
  422. html_dir.mkdir(parents=True, exist_ok=True)
  423. file_path = html_dir / filename
  424. with open(file_path, "w", encoding="utf-8") as f:
  425. f.write(html_content)
  426. print(f"[远程存储] HTML 报告已保存: {file_path}")
  427. return str(file_path)
  428. except Exception as e:
  429. print(f"[远程存储] 保存 HTML 报告失败: {e}")
  430. return None
  431. # ========================================
  432. # 远程特有功能:资源清理
  433. # ========================================
  434. def cleanup(self) -> None:
  435. """清理资源(关闭连接和删除临时文件)"""
  436. # 检查 Python 是否正在关闭
  437. if sys.meta_path is None:
  438. return
  439. # 关闭数据库连接
  440. db_connections = getattr(self, "_db_connections", {})
  441. for db_path, conn in list(db_connections.items()):
  442. try:
  443. conn.close()
  444. print(f"[远程存储] 关闭数据库连接: {db_path}")
  445. except Exception as e:
  446. print(f"[远程存储] 关闭连接失败 {db_path}: {e}")
  447. if db_connections:
  448. db_connections.clear()
  449. # 删除临时目录
  450. temp_dir = getattr(self, "temp_dir", None)
  451. if temp_dir:
  452. try:
  453. if temp_dir.exists():
  454. shutil.rmtree(temp_dir)
  455. print(f"[远程存储] 临时目录已清理: {temp_dir}")
  456. except Exception as e:
  457. # 忽略 Python 关闭时的错误
  458. if sys.meta_path is not None:
  459. print(f"[远程存储] 清理临时目录失败: {e}")
  460. downloaded_files = getattr(self, "_downloaded_files", None)
  461. if downloaded_files:
  462. downloaded_files.clear()
  463. def cleanup_old_data(self, retention_days: int) -> int:
  464. """
  465. 清理远程存储上的过期数据
  466. Args:
  467. retention_days: 保留天数(0 表示不清理)
  468. Returns:
  469. 删除的数据库文件数量
  470. """
  471. if retention_days <= 0:
  472. return 0
  473. deleted_count = 0
  474. cutoff_date = self._get_configured_time() - timedelta(days=retention_days)
  475. try:
  476. # 列出远程存储中 news/ 前缀下的所有对象
  477. paginator = self.s3_client.get_paginator('list_objects_v2')
  478. pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/")
  479. # 收集需要删除的对象键
  480. objects_to_delete = []
  481. deleted_dates = set()
  482. for page in pages:
  483. if 'Contents' not in page:
  484. continue
  485. for obj in page['Contents']:
  486. key = obj['Key']
  487. # 解析日期(格式: news/YYYY-MM-DD.db)
  488. folder_date = None
  489. date_str = None
  490. try:
  491. date_match = re.match(r'news/(\d{4})-(\d{2})-(\d{2})\.db$', key)
  492. if date_match:
  493. folder_date = datetime(
  494. int(date_match.group(1)),
  495. int(date_match.group(2)),
  496. int(date_match.group(3)),
  497. tzinfo=pytz.timezone(self.timezone)
  498. )
  499. date_str = f"{date_match.group(1)}-{date_match.group(2)}-{date_match.group(3)}"
  500. except Exception:
  501. continue
  502. if folder_date and folder_date < cutoff_date:
  503. objects_to_delete.append({'Key': key})
  504. deleted_dates.add(date_str)
  505. # 批量删除对象(每次最多 1000 个)
  506. if objects_to_delete:
  507. batch_size = 1000
  508. for i in range(0, len(objects_to_delete), batch_size):
  509. batch = objects_to_delete[i:i + batch_size]
  510. try:
  511. self.s3_client.delete_objects(
  512. Bucket=self.bucket_name,
  513. Delete={'Objects': batch}
  514. )
  515. print(f"[远程存储] 删除 {len(batch)} 个对象")
  516. except Exception as e:
  517. print(f"[远程存储] 批量删除失败: {e}")
  518. deleted_count = len(deleted_dates)
  519. for date_str in sorted(deleted_dates):
  520. print(f"[远程存储] 清理过期数据: news/{date_str}.db")
  521. print(f"[远程存储] 共清理 {deleted_count} 个过期日期数据库文件")
  522. return deleted_count
  523. except Exception as e:
  524. print(f"[远程存储] 清理过期数据失败: {e}")
  525. return deleted_count
  526. def __del__(self):
  527. """析构函数"""
  528. # 检查 Python 是否正在关闭
  529. if sys.meta_path is None:
  530. return
  531. try:
  532. self.cleanup()
  533. except Exception:
  534. # Python 关闭时可能会出错,忽略即可
  535. pass
  536. # ========================================
  537. # 远程特有功能:数据拉取和列表
  538. # ========================================
  539. def pull_recent_days(self, days: int, local_data_dir: str = "output") -> int:
  540. """
  541. 从远程拉取最近 N 天的数据到本地
  542. Args:
  543. days: 拉取天数
  544. local_data_dir: 本地数据目录
  545. Returns:
  546. 成功拉取的数据库文件数量
  547. """
  548. if days <= 0:
  549. return 0
  550. local_dir = Path(local_data_dir)
  551. local_dir.mkdir(parents=True, exist_ok=True)
  552. pulled_count = 0
  553. now = self._get_configured_time()
  554. print(f"[远程存储] 开始拉取最近 {days} 天的数据...")
  555. for i in range(days):
  556. date = now - timedelta(days=i)
  557. date_str = date.strftime("%Y-%m-%d")
  558. # 本地目标路径
  559. local_date_dir = local_dir / date_str
  560. local_db_path = local_date_dir / "news.db"
  561. # 如果本地已存在,跳过
  562. if local_db_path.exists():
  563. print(f"[远程存储] 跳过(本地已存在): {date_str}")
  564. continue
  565. # 远程对象键
  566. remote_key = f"news/{date_str}.db"
  567. # 检查远程是否存在
  568. if not self._check_object_exists(remote_key):
  569. print(f"[远程存储] 跳过(远程不存在): {date_str}")
  570. continue
  571. # 下载(使用 get_object + iter_chunks 处理 chunked encoding)
  572. try:
  573. local_date_dir.mkdir(parents=True, exist_ok=True)
  574. response = self.s3_client.get_object(Bucket=self.bucket_name, Key=remote_key)
  575. with open(local_db_path, 'wb') as f:
  576. for chunk in response['Body'].iter_chunks(chunk_size=1024*1024):
  577. f.write(chunk)
  578. print(f"[远程存储] 已拉取: {remote_key} -> {local_db_path}")
  579. pulled_count += 1
  580. except Exception as e:
  581. print(f"[远程存储] 拉取失败 ({date_str}): {e}")
  582. print(f"[远程存储] 拉取完成,共下载 {pulled_count} 个数据库文件")
  583. return pulled_count
  584. def list_remote_dates(self) -> List[str]:
  585. """
  586. 列出远程存储中所有可用的日期
  587. Returns:
  588. 日期字符串列表(YYYY-MM-DD 格式)
  589. """
  590. dates = []
  591. try:
  592. paginator = self.s3_client.get_paginator('list_objects_v2')
  593. pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/")
  594. for page in pages:
  595. if 'Contents' not in page:
  596. continue
  597. for obj in page['Contents']:
  598. key = obj['Key']
  599. # 解析日期
  600. date_match = re.match(r'news/(\d{4}-\d{2}-\d{2})\.db$', key)
  601. if date_match:
  602. dates.append(date_match.group(1))
  603. return sorted(dates, reverse=True)
  604. except Exception as e:
  605. print(f"[远程存储] 列出远程日期失败: {e}")
  606. return []