remote.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. # coding=utf-8
  2. """
  3. 远程存储后端(S3 兼容协议)
  4. 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等
  5. 使用 S3 兼容 API (boto3) 访问对象存储
  6. 数据流程:下载当天 SQLite → 合并新数据 → 上传回远程
  7. """
  8. import atexit
  9. import os
  10. import pytz
  11. import re
  12. import shutil
  13. import sys
  14. import tempfile
  15. import sqlite3
  16. from datetime import datetime, timedelta
  17. from pathlib import Path
  18. from typing import Dict, List, Optional, Any
  19. try:
  20. import boto3
  21. from botocore.config import Config as BotoConfig
  22. from botocore.exceptions import ClientError
  23. HAS_BOTO3 = True
  24. except ImportError:
  25. HAS_BOTO3 = False
  26. boto3 = None
  27. BotoConfig = None
  28. ClientError = Exception
  29. from trendradar.storage.base import StorageBackend, NewsItem, NewsData
  30. from trendradar.utils.time import (
  31. get_configured_time,
  32. format_date_folder,
  33. format_time_filename,
  34. )
  35. class RemoteStorageBackend(StorageBackend):
  36. """
  37. 远程云存储后端(S3 兼容协议)
  38. 特点:
  39. - 使用 S3 兼容 API 访问远程存储
  40. - 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等
  41. - 下载 SQLite 到临时目录进行操作
  42. - 支持数据合并和上传
  43. - 支持从远程拉取历史数据到本地
  44. - 运行结束后自动清理临时文件
  45. """
  46. def __init__(
  47. self,
  48. bucket_name: str,
  49. access_key_id: str,
  50. secret_access_key: str,
  51. endpoint_url: str,
  52. region: str = "",
  53. enable_txt: bool = False, # 远程模式默认不生成 TXT
  54. enable_html: bool = True,
  55. temp_dir: Optional[str] = None,
  56. timezone: str = "Asia/Shanghai",
  57. ):
  58. """
  59. 初始化远程存储后端
  60. Args:
  61. bucket_name: 存储桶名称
  62. access_key_id: 访问密钥 ID
  63. secret_access_key: 访问密钥
  64. endpoint_url: 服务端点 URL
  65. region: 区域(可选,部分服务商需要)
  66. enable_txt: 是否启用 TXT 快照(默认关闭)
  67. enable_html: 是否启用 HTML 报告
  68. temp_dir: 临时目录路径(默认使用系统临时目录)
  69. timezone: 时区配置(默认 Asia/Shanghai)
  70. """
  71. if not HAS_BOTO3:
  72. raise ImportError("远程存储后端需要安装 boto3: pip install boto3")
  73. self.bucket_name = bucket_name
  74. self.endpoint_url = endpoint_url
  75. self.region = region
  76. self.enable_txt = enable_txt
  77. self.enable_html = enable_html
  78. self.timezone = timezone
  79. # 创建临时目录
  80. self.temp_dir = Path(temp_dir) if temp_dir else Path(tempfile.mkdtemp(prefix="trendradar_"))
  81. self.temp_dir.mkdir(parents=True, exist_ok=True)
  82. # 初始化 S3 客户端
  83. # 使用 virtual-hosted style addressing(主流)
  84. s3_config = BotoConfig(s3={"addressing_style": "virtual"})
  85. client_kwargs = {
  86. "endpoint_url": endpoint_url,
  87. "aws_access_key_id": access_key_id,
  88. "aws_secret_access_key": secret_access_key,
  89. "config": s3_config,
  90. }
  91. if region:
  92. client_kwargs["region_name"] = region
  93. self.s3_client = boto3.client("s3", **client_kwargs)
  94. # 跟踪下载的文件(用于清理)
  95. self._downloaded_files: List[Path] = []
  96. self._db_connections: Dict[str, sqlite3.Connection] = {}
  97. print(f"[远程存储] 初始化完成,存储桶: {bucket_name}")
  98. @property
  99. def backend_name(self) -> str:
  100. return "remote"
  101. @property
  102. def supports_txt(self) -> bool:
  103. return self.enable_txt
  104. def _get_configured_time(self) -> datetime:
  105. """获取配置时区的当前时间"""
  106. return get_configured_time(self.timezone)
  107. def _format_date_folder(self, date: Optional[str] = None) -> str:
  108. """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)"""
  109. return format_date_folder(date, self.timezone)
  110. def _format_time_filename(self) -> str:
  111. """格式化时间文件名 (格式: HH-MM)"""
  112. return format_time_filename(self.timezone)
  113. def _get_remote_db_key(self, date: Optional[str] = None) -> str:
  114. """获取 R2 中 SQLite 文件的对象键"""
  115. date_folder = self._format_date_folder(date)
  116. return f"news/{date_folder}.db"
  117. def _get_local_db_path(self, date: Optional[str] = None) -> Path:
  118. """获取本地临时 SQLite 文件路径"""
  119. date_folder = self._format_date_folder(date)
  120. return self.temp_dir / date_folder / "news.db"
  121. def _check_object_exists(self, r2_key: str) -> bool:
  122. """
  123. 检查 R2 中对象是否存在
  124. Args:
  125. r2_key: R2 对象键
  126. Returns:
  127. 是否存在
  128. """
  129. try:
  130. self.s3_client.head_object(Bucket=self.bucket_name, Key=r2_key)
  131. return True
  132. except ClientError as e:
  133. error_code = e.response.get("Error", {}).get("Code", "")
  134. # R2/S3 可能返回 404, NoSuchKey, 或其他变体
  135. if error_code in ("404", "NoSuchKey", "Not Found"):
  136. return False
  137. # 其他错误(如权限问题)也视为不存在,但打印警告
  138. print(f"[远程存储] 检查对象存在性失败 ({r2_key}): {e}")
  139. return False
  140. except Exception as e:
  141. print(f"[远程存储] 检查对象存在性异常 ({r2_key}): {e}")
  142. return False
  143. def _download_sqlite(self, date: Optional[str] = None) -> Optional[Path]:
  144. """
  145. 从 R2 下载当天的 SQLite 文件到本地临时目录
  146. Args:
  147. date: 日期字符串
  148. Returns:
  149. 本地文件路径,如果不存在返回 None
  150. """
  151. r2_key = self._get_remote_db_key(date)
  152. local_path = self._get_local_db_path(date)
  153. # 确保目录存在
  154. local_path.parent.mkdir(parents=True, exist_ok=True)
  155. # 先检查文件是否存在
  156. if not self._check_object_exists(r2_key):
  157. print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}")
  158. return None
  159. try:
  160. self.s3_client.download_file(self.bucket_name, r2_key, str(local_path))
  161. self._downloaded_files.append(local_path)
  162. print(f"[远程存储] 已下载: {r2_key} -> {local_path}")
  163. return local_path
  164. except ClientError as e:
  165. error_code = e.response.get("Error", {}).get("Code", "")
  166. # R2/S3 可能返回不同的错误码
  167. if error_code in ("404", "NoSuchKey", "Not Found"):
  168. print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}")
  169. return None
  170. else:
  171. print(f"[远程存储] 下载失败 (错误码: {error_code}): {e}")
  172. raise
  173. except Exception as e:
  174. print(f"[远程存储] 下载异常: {e}")
  175. raise
  176. def _upload_sqlite(self, date: Optional[str] = None) -> bool:
  177. """
  178. 上传本地 SQLite 文件到 R2
  179. Args:
  180. date: 日期字符串
  181. Returns:
  182. 是否上传成功
  183. """
  184. local_path = self._get_local_db_path(date)
  185. r2_key = self._get_remote_db_key(date)
  186. if not local_path.exists():
  187. print(f"[远程存储] 本地文件不存在,无法上传: {local_path}")
  188. return False
  189. try:
  190. # 获取本地文件大小
  191. local_size = local_path.stat().st_size
  192. print(f"[远程存储] 准备上传: {local_path} ({local_size} bytes) -> {r2_key}")
  193. self.s3_client.upload_file(str(local_path), self.bucket_name, r2_key)
  194. print(f"[远程存储] 已上传: {local_path} -> {r2_key}")
  195. # 验证上传成功
  196. if self._check_object_exists(r2_key):
  197. print(f"[远程存储] 上传验证成功: {r2_key}")
  198. return True
  199. else:
  200. print(f"[远程存储] 上传验证失败: 文件未在 R2 中找到")
  201. return False
  202. except Exception as e:
  203. print(f"[远程存储] 上传失败: {e}")
  204. return False
  205. def _get_connection(self, date: Optional[str] = None) -> sqlite3.Connection:
  206. """获取数据库连接"""
  207. local_path = self._get_local_db_path(date)
  208. db_path = str(local_path)
  209. if db_path not in self._db_connections:
  210. # 确保目录存在
  211. local_path.parent.mkdir(parents=True, exist_ok=True)
  212. # 如果本地不存在,尝试从 R2 下载
  213. if not local_path.exists():
  214. self._download_sqlite(date)
  215. conn = sqlite3.connect(db_path)
  216. conn.row_factory = sqlite3.Row
  217. self._init_tables(conn)
  218. self._db_connections[db_path] = conn
  219. return self._db_connections[db_path]
  220. def _get_schema_path(self) -> Path:
  221. """获取 schema.sql 文件路径"""
  222. return Path(__file__).parent / "schema.sql"
  223. def _init_tables(self, conn: sqlite3.Connection) -> None:
  224. """从 schema.sql 初始化数据库表结构"""
  225. schema_path = self._get_schema_path()
  226. if schema_path.exists():
  227. with open(schema_path, "r", encoding="utf-8") as f:
  228. schema_sql = f.read()
  229. conn.executescript(schema_sql)
  230. else:
  231. raise FileNotFoundError(f"Schema file not found: {schema_path}")
  232. conn.commit()
  233. def save_news_data(self, data: NewsData) -> bool:
  234. """
  235. 保存新闻数据到 R2(以 URL 为唯一标识,支持标题更新检测)
  236. 流程:下载现有数据库 → 插入/更新数据 → 上传回 R2
  237. Args:
  238. data: 新闻数据
  239. Returns:
  240. 是否保存成功
  241. """
  242. try:
  243. conn = self._get_connection(data.date)
  244. cursor = conn.cursor()
  245. # 查询已有记录数
  246. cursor.execute("SELECT COUNT(*) as count FROM news_items")
  247. row = cursor.fetchone()
  248. existing_count = row[0] if row else 0
  249. if existing_count > 0:
  250. print(f"[远程存储] 已有 {existing_count} 条历史记录,将合并新数据")
  251. # 获取配置时区的当前时间
  252. now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S")
  253. # 首先同步平台信息到 platforms 表
  254. for source_id, source_name in data.id_to_name.items():
  255. cursor.execute("""
  256. INSERT INTO platforms (id, name, updated_at)
  257. VALUES (?, ?, ?)
  258. ON CONFLICT(id) DO UPDATE SET
  259. name = excluded.name,
  260. updated_at = excluded.updated_at
  261. """, (source_id, source_name, now_str))
  262. # 统计计数器
  263. new_count = 0
  264. updated_count = 0
  265. title_changed_count = 0
  266. success_sources = []
  267. for source_id, news_list in data.items.items():
  268. success_sources.append(source_id)
  269. for item in news_list:
  270. try:
  271. # 检查是否已存在(通过 URL + platform_id)
  272. if item.url:
  273. cursor.execute("""
  274. SELECT id, title FROM news_items
  275. WHERE url = ? AND platform_id = ?
  276. """, (item.url, source_id))
  277. existing = cursor.fetchone()
  278. if existing:
  279. # 已存在,更新记录
  280. existing_id, existing_title = existing
  281. # 检查标题是否变化
  282. if existing_title != item.title:
  283. # 记录标题变更
  284. cursor.execute("""
  285. INSERT INTO title_changes
  286. (news_item_id, old_title, new_title, changed_at)
  287. VALUES (?, ?, ?, ?)
  288. """, (existing_id, existing_title, item.title, now_str))
  289. title_changed_count += 1
  290. # 记录排名历史
  291. cursor.execute("""
  292. INSERT INTO rank_history
  293. (news_item_id, rank, crawl_time, created_at)
  294. VALUES (?, ?, ?, ?)
  295. """, (existing_id, item.rank, data.crawl_time, now_str))
  296. # 更新现有记录
  297. cursor.execute("""
  298. UPDATE news_items SET
  299. title = ?,
  300. rank = ?,
  301. mobile_url = ?,
  302. last_crawl_time = ?,
  303. crawl_count = crawl_count + 1,
  304. updated_at = ?
  305. WHERE id = ?
  306. """, (item.title, item.rank, item.mobile_url,
  307. data.crawl_time, now_str, existing_id))
  308. updated_count += 1
  309. else:
  310. # 不存在,插入新记录
  311. cursor.execute("""
  312. INSERT INTO news_items
  313. (title, platform_id, rank, url, mobile_url,
  314. first_crawl_time, last_crawl_time, crawl_count,
  315. created_at, updated_at)
  316. VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
  317. """, (item.title, source_id, item.rank, item.url,
  318. item.mobile_url, data.crawl_time, data.crawl_time,
  319. now_str, now_str))
  320. new_id = cursor.lastrowid
  321. # 记录初始排名
  322. cursor.execute("""
  323. INSERT INTO rank_history
  324. (news_item_id, rank, crawl_time, created_at)
  325. VALUES (?, ?, ?, ?)
  326. """, (new_id, item.rank, data.crawl_time, now_str))
  327. new_count += 1
  328. else:
  329. # URL 为空的情况,直接插入(不做去重)
  330. cursor.execute("""
  331. INSERT INTO news_items
  332. (title, platform_id, rank, url, mobile_url,
  333. first_crawl_time, last_crawl_time, crawl_count,
  334. created_at, updated_at)
  335. VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
  336. """, (item.title, source_id, item.rank, item.url,
  337. item.mobile_url, data.crawl_time, data.crawl_time,
  338. now_str, now_str))
  339. new_id = cursor.lastrowid
  340. # 记录初始排名
  341. cursor.execute("""
  342. INSERT INTO rank_history
  343. (news_item_id, rank, crawl_time, created_at)
  344. VALUES (?, ?, ?, ?)
  345. """, (new_id, item.rank, data.crawl_time, now_str))
  346. new_count += 1
  347. except sqlite3.Error as e:
  348. print(f"[远程存储] 保存新闻条目失败 [{item.title[:30]}...]: {e}")
  349. total_items = new_count + updated_count
  350. # 记录抓取信息
  351. cursor.execute("""
  352. INSERT OR REPLACE INTO crawl_records
  353. (crawl_time, total_items, created_at)
  354. VALUES (?, ?, ?)
  355. """, (data.crawl_time, total_items, now_str))
  356. # 获取刚插入的 crawl_record 的 ID
  357. cursor.execute("""
  358. SELECT id FROM crawl_records WHERE crawl_time = ?
  359. """, (data.crawl_time,))
  360. record_row = cursor.fetchone()
  361. if record_row:
  362. crawl_record_id = record_row[0]
  363. # 记录成功的来源
  364. for source_id in success_sources:
  365. cursor.execute("""
  366. INSERT OR REPLACE INTO crawl_source_status
  367. (crawl_record_id, platform_id, status)
  368. VALUES (?, ?, 'success')
  369. """, (crawl_record_id, source_id))
  370. # 记录失败的来源
  371. for failed_id in data.failed_ids:
  372. # 确保失败的平台也在 platforms 表中
  373. cursor.execute("""
  374. INSERT OR IGNORE INTO platforms (id, name, updated_at)
  375. VALUES (?, ?, ?)
  376. """, (failed_id, failed_id, now_str))
  377. cursor.execute("""
  378. INSERT OR REPLACE INTO crawl_source_status
  379. (crawl_record_id, platform_id, status)
  380. VALUES (?, ?, 'failed')
  381. """, (crawl_record_id, failed_id))
  382. conn.commit()
  383. # 查询合并后的总记录数
  384. cursor.execute("SELECT COUNT(*) as count FROM news_items")
  385. row = cursor.fetchone()
  386. final_count = row[0] if row else 0
  387. # 输出详细的存储统计日志
  388. log_parts = [f"[远程存储] 处理完成:新增 {new_count} 条"]
  389. if updated_count > 0:
  390. log_parts.append(f"更新 {updated_count} 条")
  391. if title_changed_count > 0:
  392. log_parts.append(f"标题变更 {title_changed_count} 条")
  393. log_parts.append(f"(去重后总计: {final_count} 条)")
  394. print(",".join(log_parts))
  395. # 上传到 R2
  396. if self._upload_sqlite(data.date):
  397. print(f"[远程存储] 数据已同步到 R2")
  398. return True
  399. else:
  400. print(f"[远程存储] 上传 R2 失败")
  401. return False
  402. except Exception as e:
  403. print(f"[远程存储] 保存失败: {e}")
  404. return False
  405. def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  406. """获取指定日期的所有新闻数据(合并后)"""
  407. try:
  408. conn = self._get_connection(date)
  409. cursor = conn.cursor()
  410. # 获取所有新闻数据(包含 id 用于查询排名历史)
  411. cursor.execute("""
  412. SELECT n.id, n.title, n.platform_id, p.name as platform_name,
  413. n.rank, n.url, n.mobile_url,
  414. n.first_crawl_time, n.last_crawl_time, n.crawl_count
  415. FROM news_items n
  416. LEFT JOIN platforms p ON n.platform_id = p.id
  417. ORDER BY n.platform_id, n.last_crawl_time
  418. """)
  419. rows = cursor.fetchall()
  420. if not rows:
  421. return None
  422. # 收集所有 news_item_id
  423. news_ids = [row[0] for row in rows]
  424. # 批量查询排名历史
  425. rank_history_map: Dict[int, List[int]] = {}
  426. if news_ids:
  427. placeholders = ",".join("?" * len(news_ids))
  428. cursor.execute(f"""
  429. SELECT news_item_id, rank FROM rank_history
  430. WHERE news_item_id IN ({placeholders})
  431. ORDER BY news_item_id, crawl_time
  432. """, news_ids)
  433. for rh_row in cursor.fetchall():
  434. news_id, rank = rh_row[0], rh_row[1]
  435. if news_id not in rank_history_map:
  436. rank_history_map[news_id] = []
  437. if rank not in rank_history_map[news_id]:
  438. rank_history_map[news_id].append(rank)
  439. # 按 platform_id 分组
  440. items: Dict[str, List[NewsItem]] = {}
  441. id_to_name: Dict[str, str] = {}
  442. crawl_date = self._format_date_folder(date)
  443. for row in rows:
  444. news_id = row[0]
  445. platform_id = row[2]
  446. title = row[1]
  447. platform_name = row[3] or platform_id
  448. id_to_name[platform_id] = platform_name
  449. if platform_id not in items:
  450. items[platform_id] = []
  451. # 获取排名历史,如果没有则使用当前排名
  452. ranks = rank_history_map.get(news_id, [row[4]])
  453. items[platform_id].append(NewsItem(
  454. title=title,
  455. source_id=platform_id,
  456. source_name=platform_name,
  457. rank=row[4],
  458. url=row[5] or "",
  459. mobile_url=row[6] or "",
  460. crawl_time=row[8], # last_crawl_time
  461. ranks=ranks,
  462. first_time=row[7], # first_crawl_time
  463. last_time=row[8], # last_crawl_time
  464. count=row[9], # crawl_count
  465. ))
  466. final_items = items
  467. # 获取失败的来源
  468. cursor.execute("""
  469. SELECT DISTINCT css.platform_id
  470. FROM crawl_source_status css
  471. JOIN crawl_records cr ON css.crawl_record_id = cr.id
  472. WHERE css.status = 'failed'
  473. """)
  474. failed_ids = [row[0] for row in cursor.fetchall()]
  475. # 获取最新的抓取时间
  476. cursor.execute("""
  477. SELECT crawl_time FROM crawl_records
  478. ORDER BY crawl_time DESC
  479. LIMIT 1
  480. """)
  481. time_row = cursor.fetchone()
  482. crawl_time = time_row[0] if time_row else self._format_time_filename()
  483. return NewsData(
  484. date=crawl_date,
  485. crawl_time=crawl_time,
  486. items=final_items,
  487. id_to_name=id_to_name,
  488. failed_ids=failed_ids,
  489. )
  490. except Exception as e:
  491. print(f"[远程存储] 读取数据失败: {e}")
  492. return None
  493. def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  494. """获取最新一次抓取的数据"""
  495. try:
  496. conn = self._get_connection(date)
  497. cursor = conn.cursor()
  498. # 获取最新的抓取时间
  499. cursor.execute("""
  500. SELECT crawl_time FROM crawl_records
  501. ORDER BY crawl_time DESC
  502. LIMIT 1
  503. """)
  504. time_row = cursor.fetchone()
  505. if not time_row:
  506. return None
  507. latest_time = time_row[0]
  508. # 获取该时间的新闻数据,通过 JOIN 获取平台名称
  509. cursor.execute("""
  510. SELECT n.title, n.platform_id, p.name as platform_name,
  511. n.rank, n.url, n.mobile_url,
  512. n.first_crawl_time, n.last_crawl_time, n.crawl_count
  513. FROM news_items n
  514. LEFT JOIN platforms p ON n.platform_id = p.id
  515. WHERE n.last_crawl_time = ?
  516. """, (latest_time,))
  517. rows = cursor.fetchall()
  518. if not rows:
  519. return None
  520. items: Dict[str, List[NewsItem]] = {}
  521. id_to_name: Dict[str, str] = {}
  522. crawl_date = self._format_date_folder(date)
  523. for row in rows:
  524. platform_id = row[1]
  525. platform_name = row[2] or platform_id
  526. id_to_name[platform_id] = platform_name
  527. if platform_id not in items:
  528. items[platform_id] = []
  529. items[platform_id].append(NewsItem(
  530. title=row[0],
  531. source_id=platform_id,
  532. source_name=platform_name,
  533. rank=row[3],
  534. url=row[4] or "",
  535. mobile_url=row[5] or "",
  536. crawl_time=row[7], # last_crawl_time
  537. ranks=[row[3]],
  538. first_time=row[6], # first_crawl_time
  539. last_time=row[7], # last_crawl_time
  540. count=row[8], # crawl_count
  541. ))
  542. # 获取失败的来源(针对最新一次抓取)
  543. cursor.execute("""
  544. SELECT css.platform_id
  545. FROM crawl_source_status css
  546. JOIN crawl_records cr ON css.crawl_record_id = cr.id
  547. WHERE cr.crawl_time = ? AND css.status = 'failed'
  548. """, (latest_time,))
  549. failed_ids = [row[0] for row in cursor.fetchall()]
  550. return NewsData(
  551. date=crawl_date,
  552. crawl_time=latest_time,
  553. items=items,
  554. id_to_name=id_to_name,
  555. failed_ids=failed_ids,
  556. )
  557. except Exception as e:
  558. print(f"[远程存储] 获取最新数据失败: {e}")
  559. return None
  560. def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]:
  561. """检测新增的标题"""
  562. try:
  563. historical_data = self.get_today_all_data(current_data.date)
  564. if not historical_data:
  565. new_titles = {}
  566. for source_id, news_list in current_data.items.items():
  567. new_titles[source_id] = {item.title: item for item in news_list}
  568. return new_titles
  569. historical_titles: Dict[str, set] = {}
  570. for source_id, news_list in historical_data.items.items():
  571. historical_titles[source_id] = {item.title for item in news_list}
  572. new_titles = {}
  573. for source_id, news_list in current_data.items.items():
  574. hist_set = historical_titles.get(source_id, set())
  575. for item in news_list:
  576. if item.title not in hist_set:
  577. if source_id not in new_titles:
  578. new_titles[source_id] = {}
  579. new_titles[source_id][item.title] = item
  580. return new_titles
  581. except Exception as e:
  582. print(f"[远程存储] 检测新标题失败: {e}")
  583. return {}
  584. def save_txt_snapshot(self, data: NewsData) -> Optional[str]:
  585. """保存 TXT 快照(R2 模式下默认不支持)"""
  586. if not self.enable_txt:
  587. return None
  588. # 如果启用,保存到本地临时目录
  589. try:
  590. date_folder = self._format_date_folder(data.date)
  591. txt_dir = self.temp_dir / date_folder / "txt"
  592. txt_dir.mkdir(parents=True, exist_ok=True)
  593. file_path = txt_dir / f"{data.crawl_time}.txt"
  594. with open(file_path, "w", encoding="utf-8") as f:
  595. for source_id, news_list in data.items.items():
  596. source_name = data.id_to_name.get(source_id, source_id)
  597. if source_name and source_name != source_id:
  598. f.write(f"{source_id} | {source_name}\n")
  599. else:
  600. f.write(f"{source_id}\n")
  601. sorted_news = sorted(news_list, key=lambda x: x.rank)
  602. for item in sorted_news:
  603. line = f"{item.rank}. {item.title}"
  604. if item.url:
  605. line += f" [URL:{item.url}]"
  606. if item.mobile_url:
  607. line += f" [MOBILE:{item.mobile_url}]"
  608. f.write(line + "\n")
  609. f.write("\n")
  610. if data.failed_ids:
  611. f.write("==== 以下ID请求失败 ====\n")
  612. for failed_id in data.failed_ids:
  613. f.write(f"{failed_id}\n")
  614. print(f"[远程存储] TXT 快照已保存: {file_path}")
  615. return str(file_path)
  616. except Exception as e:
  617. print(f"[远程存储] 保存 TXT 快照失败: {e}")
  618. return None
  619. def save_html_report(self, html_content: str, filename: str, is_summary: bool = False) -> Optional[str]:
  620. """保存 HTML 报告到临时目录"""
  621. if not self.enable_html:
  622. return None
  623. try:
  624. date_folder = self._format_date_folder()
  625. html_dir = self.temp_dir / date_folder / "html"
  626. html_dir.mkdir(parents=True, exist_ok=True)
  627. file_path = html_dir / filename
  628. with open(file_path, "w", encoding="utf-8") as f:
  629. f.write(html_content)
  630. print(f"[远程存储] HTML 报告已保存: {file_path}")
  631. return str(file_path)
  632. except Exception as e:
  633. print(f"[远程存储] 保存 HTML 报告失败: {e}")
  634. return None
  635. def is_first_crawl_today(self, date: Optional[str] = None) -> bool:
  636. """检查是否是当天第一次抓取"""
  637. try:
  638. conn = self._get_connection(date)
  639. cursor = conn.cursor()
  640. cursor.execute("""
  641. SELECT COUNT(*) as count FROM crawl_records
  642. """)
  643. row = cursor.fetchone()
  644. count = row[0] if row else 0
  645. return count <= 1
  646. except Exception as e:
  647. print(f"[远程存储] 检查首次抓取失败: {e}")
  648. return True
  649. def cleanup(self) -> None:
  650. """清理资源(关闭连接和删除临时文件)"""
  651. # 检查 Python 是否正在关闭
  652. if sys.meta_path is None:
  653. return
  654. # 关闭数据库连接
  655. db_connections = getattr(self, "_db_connections", {})
  656. for db_path, conn in list(db_connections.items()):
  657. try:
  658. conn.close()
  659. print(f"[远程存储] 关闭数据库连接: {db_path}")
  660. except Exception as e:
  661. print(f"[远程存储] 关闭连接失败 {db_path}: {e}")
  662. if db_connections:
  663. db_connections.clear()
  664. # 删除临时目录
  665. temp_dir = getattr(self, "temp_dir", None)
  666. if temp_dir:
  667. try:
  668. if temp_dir.exists():
  669. shutil.rmtree(temp_dir)
  670. print(f"[远程存储] 临时目录已清理: {temp_dir}")
  671. except Exception as e:
  672. # 忽略 Python 关闭时的错误
  673. if sys.meta_path is not None:
  674. print(f"[远程存储] 清理临时目录失败: {e}")
  675. downloaded_files = getattr(self, "_downloaded_files", None)
  676. if downloaded_files:
  677. downloaded_files.clear()
  678. def cleanup_old_data(self, retention_days: int) -> int:
  679. """
  680. 清理 R2 上的过期数据
  681. Args:
  682. retention_days: 保留天数(0 表示不清理)
  683. Returns:
  684. 删除的数据库文件数量
  685. """
  686. if retention_days <= 0:
  687. return 0
  688. deleted_count = 0
  689. cutoff_date = self._get_configured_time() - timedelta(days=retention_days)
  690. try:
  691. # 列出 R2 中 news/ 前缀下的所有对象
  692. paginator = self.s3_client.get_paginator('list_objects_v2')
  693. pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/")
  694. # 收集需要删除的对象键
  695. objects_to_delete = []
  696. deleted_dates = set()
  697. for page in pages:
  698. if 'Contents' not in page:
  699. continue
  700. for obj in page['Contents']:
  701. key = obj['Key']
  702. # 解析日期(格式: news/YYYY-MM-DD.db 或 news/YYYY年MM月DD日.db)
  703. folder_date = None
  704. try:
  705. # ISO 格式: news/YYYY-MM-DD.db
  706. date_match = re.match(r'news/(\d{4})-(\d{2})-(\d{2})\.db$', key)
  707. if date_match:
  708. folder_date = datetime(
  709. int(date_match.group(1)),
  710. int(date_match.group(2)),
  711. int(date_match.group(3)),
  712. tzinfo=pytz.timezone("Asia/Shanghai")
  713. )
  714. date_str = f"{date_match.group(1)}-{date_match.group(2)}-{date_match.group(3)}"
  715. else:
  716. # 旧中文格式: news/YYYY年MM月DD日.db
  717. date_match = re.match(r'news/(\d{4})年(\d{2})月(\d{2})日\.db$', key)
  718. if date_match:
  719. folder_date = datetime(
  720. int(date_match.group(1)),
  721. int(date_match.group(2)),
  722. int(date_match.group(3)),
  723. tzinfo=pytz.timezone("Asia/Shanghai")
  724. )
  725. date_str = f"{date_match.group(1)}年{date_match.group(2)}月{date_match.group(3)}日"
  726. except Exception:
  727. continue
  728. if folder_date and folder_date < cutoff_date:
  729. objects_to_delete.append({'Key': key})
  730. deleted_dates.add(date_str)
  731. # 批量删除对象(每次最多 1000 个)
  732. if objects_to_delete:
  733. batch_size = 1000
  734. for i in range(0, len(objects_to_delete), batch_size):
  735. batch = objects_to_delete[i:i + batch_size]
  736. try:
  737. self.s3_client.delete_objects(
  738. Bucket=self.bucket_name,
  739. Delete={'Objects': batch}
  740. )
  741. print(f"[远程存储] 删除 {len(batch)} 个对象")
  742. except Exception as e:
  743. print(f"[远程存储] 批量删除失败: {e}")
  744. deleted_count = len(deleted_dates)
  745. for date_str in sorted(deleted_dates):
  746. print(f"[远程存储] 清理过期数据: news/{date_str}.db")
  747. print(f"[远程存储] 共清理 {deleted_count} 个过期日期数据库文件")
  748. return deleted_count
  749. except Exception as e:
  750. print(f"[远程存储] 清理过期数据失败: {e}")
  751. return deleted_count
  752. def has_pushed_today(self, date: Optional[str] = None) -> bool:
  753. """
  754. 检查指定日期是否已推送过
  755. Args:
  756. date: 日期字符串(YYYY-MM-DD),默认为今天
  757. Returns:
  758. 是否已推送
  759. """
  760. try:
  761. conn = self._get_connection(date)
  762. cursor = conn.cursor()
  763. target_date = self._format_date_folder(date)
  764. cursor.execute("""
  765. SELECT pushed FROM push_records WHERE date = ?
  766. """, (target_date,))
  767. row = cursor.fetchone()
  768. if row:
  769. return bool(row[0])
  770. return False
  771. except Exception as e:
  772. print(f"[远程存储] 检查推送记录失败: {e}")
  773. return False
  774. def record_push(self, report_type: str, date: Optional[str] = None) -> bool:
  775. """
  776. 记录推送
  777. Args:
  778. report_type: 报告类型
  779. date: 日期字符串(YYYY-MM-DD),默认为今天
  780. Returns:
  781. 是否记录成功
  782. """
  783. try:
  784. conn = self._get_connection(date)
  785. cursor = conn.cursor()
  786. target_date = self._format_date_folder(date)
  787. now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S")
  788. cursor.execute("""
  789. INSERT INTO push_records (date, pushed, push_time, report_type, created_at)
  790. VALUES (?, 1, ?, ?, ?)
  791. ON CONFLICT(date) DO UPDATE SET
  792. pushed = 1,
  793. push_time = excluded.push_time,
  794. report_type = excluded.report_type
  795. """, (target_date, now_str, report_type, now_str))
  796. conn.commit()
  797. print(f"[远程存储] 推送记录已保存: {report_type} at {now_str}")
  798. # 上传到 R2 确保记录持久化
  799. if self._upload_sqlite(date):
  800. print(f"[远程存储] 推送记录已同步到 R2")
  801. return True
  802. else:
  803. print(f"[远程存储] 推送记录同步到 R2 失败")
  804. return False
  805. except Exception as e:
  806. print(f"[远程存储] 记录推送失败: {e}")
  807. return False
  808. def __del__(self):
  809. """析构函数"""
  810. # 检查 Python 是否正在关闭
  811. if sys.meta_path is None:
  812. return
  813. try:
  814. self.cleanup()
  815. except Exception:
  816. # Python 关闭时可能会出错,忽略即可
  817. pass
  818. def pull_recent_days(self, days: int, local_data_dir: str = "output") -> int:
  819. """
  820. 从远程拉取最近 N 天的数据到本地
  821. Args:
  822. days: 拉取天数
  823. local_data_dir: 本地数据目录
  824. Returns:
  825. 成功拉取的数据库文件数量
  826. """
  827. if days <= 0:
  828. return 0
  829. local_dir = Path(local_data_dir)
  830. local_dir.mkdir(parents=True, exist_ok=True)
  831. pulled_count = 0
  832. now = self._get_configured_time()
  833. print(f"[远程存储] 开始拉取最近 {days} 天的数据...")
  834. for i in range(days):
  835. date = now - timedelta(days=i)
  836. date_str = date.strftime("%Y-%m-%d")
  837. # 本地目标路径
  838. local_date_dir = local_dir / date_str
  839. local_db_path = local_date_dir / "news.db"
  840. # 如果本地已存在,跳过
  841. if local_db_path.exists():
  842. print(f"[远程存储] 跳过(本地已存在): {date_str}")
  843. continue
  844. # 远程对象键
  845. remote_key = f"news/{date_str}.db"
  846. # 检查远程是否存在
  847. if not self._check_object_exists(remote_key):
  848. print(f"[远程存储] 跳过(远程不存在): {date_str}")
  849. continue
  850. # 下载
  851. try:
  852. local_date_dir.mkdir(parents=True, exist_ok=True)
  853. self.s3_client.download_file(
  854. self.bucket_name,
  855. remote_key,
  856. str(local_db_path)
  857. )
  858. print(f"[远程存储] 已拉取: {remote_key} -> {local_db_path}")
  859. pulled_count += 1
  860. except Exception as e:
  861. print(f"[远程存储] 拉取失败 ({date_str}): {e}")
  862. print(f"[远程存储] 拉取完成,共下载 {pulled_count} 个数据库文件")
  863. return pulled_count
  864. def list_remote_dates(self) -> List[str]:
  865. """
  866. 列出远程存储中所有可用的日期
  867. Returns:
  868. 日期字符串列表(YYYY-MM-DD 格式)
  869. """
  870. dates = []
  871. try:
  872. paginator = self.s3_client.get_paginator('list_objects_v2')
  873. pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/")
  874. for page in pages:
  875. if 'Contents' not in page:
  876. continue
  877. for obj in page['Contents']:
  878. key = obj['Key']
  879. # 解析日期
  880. date_match = re.match(r'news/(\d{4}-\d{2}-\d{2})\.db$', key)
  881. if date_match:
  882. dates.append(date_match.group(1))
  883. return sorted(dates, reverse=True)
  884. except Exception as e:
  885. print(f"[远程存储] 列出远程日期失败: {e}")
  886. return []