remote.py 43 KB

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