remote.py 42 KB

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