remote.py 42 KB

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