local.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. # coding=utf-8
  2. """
  3. 本地存储后端 - SQLite + TXT/HTML
  4. 使用 SQLite 作为主存储,支持可选的 TXT 快照和 HTML 报告
  5. """
  6. import sqlite3
  7. import shutil
  8. import pytz
  9. import re
  10. from datetime import datetime, timedelta
  11. from pathlib import Path
  12. from typing import Dict, List, Optional
  13. from trendradar.storage.base import StorageBackend, NewsItem, NewsData
  14. from trendradar.utils.time import (
  15. get_configured_time,
  16. format_date_folder,
  17. format_time_filename,
  18. )
  19. from trendradar.utils.url import normalize_url
  20. class LocalStorageBackend(StorageBackend):
  21. """
  22. 本地存储后端
  23. 使用 SQLite 数据库存储新闻数据,支持:
  24. - 按日期组织的 SQLite 数据库文件
  25. - 可选的 TXT 快照(用于调试)
  26. - HTML 报告生成
  27. """
  28. def __init__(
  29. self,
  30. data_dir: str = "output",
  31. enable_txt: bool = True,
  32. enable_html: bool = True,
  33. timezone: str = "Asia/Shanghai",
  34. ):
  35. """
  36. 初始化本地存储后端
  37. Args:
  38. data_dir: 数据目录路径
  39. enable_txt: 是否启用 TXT 快照
  40. enable_html: 是否启用 HTML 报告
  41. timezone: 时区配置(默认 Asia/Shanghai)
  42. """
  43. self.data_dir = Path(data_dir)
  44. self.enable_txt = enable_txt
  45. self.enable_html = enable_html
  46. self.timezone = timezone
  47. self._db_connections: Dict[str, sqlite3.Connection] = {}
  48. @property
  49. def backend_name(self) -> str:
  50. return "local"
  51. @property
  52. def supports_txt(self) -> bool:
  53. return self.enable_txt
  54. def _get_configured_time(self) -> datetime:
  55. """获取配置时区的当前时间"""
  56. return get_configured_time(self.timezone)
  57. def _format_date_folder(self, date: Optional[str] = None) -> str:
  58. """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)"""
  59. return format_date_folder(date, self.timezone)
  60. def _format_time_filename(self) -> str:
  61. """格式化时间文件名 (格式: HH-MM)"""
  62. return format_time_filename(self.timezone)
  63. def _get_db_path(self, date: Optional[str] = None) -> Path:
  64. """获取 SQLite 数据库路径"""
  65. date_folder = self._format_date_folder(date)
  66. db_dir = self.data_dir / date_folder
  67. db_dir.mkdir(parents=True, exist_ok=True)
  68. return db_dir / "news.db"
  69. def _get_connection(self, date: Optional[str] = None) -> sqlite3.Connection:
  70. """获取数据库连接(带缓存)"""
  71. db_path = str(self._get_db_path(date))
  72. if db_path not in self._db_connections:
  73. conn = sqlite3.connect(db_path)
  74. conn.row_factory = sqlite3.Row
  75. self._init_tables(conn)
  76. self._db_connections[db_path] = conn
  77. return self._db_connections[db_path]
  78. def _get_schema_path(self) -> Path:
  79. """获取 schema.sql 文件路径"""
  80. return Path(__file__).parent / "schema.sql"
  81. def _init_tables(self, conn: sqlite3.Connection) -> None:
  82. """从 schema.sql 初始化数据库表结构"""
  83. schema_path = self._get_schema_path()
  84. if schema_path.exists():
  85. with open(schema_path, "r", encoding="utf-8") as f:
  86. schema_sql = f.read()
  87. conn.executescript(schema_sql)
  88. else:
  89. raise FileNotFoundError(f"Schema file not found: {schema_path}")
  90. conn.commit()
  91. def save_news_data(self, data: NewsData) -> bool:
  92. """
  93. 保存新闻数据到 SQLite(以 URL 为唯一标识,支持标题更新检测)
  94. Args:
  95. data: 新闻数据
  96. Returns:
  97. 是否保存成功
  98. """
  99. try:
  100. conn = self._get_connection(data.date)
  101. cursor = conn.cursor()
  102. # 获取配置时区的当前时间
  103. now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S")
  104. # 首先同步平台信息到 platforms 表
  105. for source_id, source_name in data.id_to_name.items():
  106. cursor.execute("""
  107. INSERT INTO platforms (id, name, updated_at)
  108. VALUES (?, ?, ?)
  109. ON CONFLICT(id) DO UPDATE SET
  110. name = excluded.name,
  111. updated_at = excluded.updated_at
  112. """, (source_id, source_name, now_str))
  113. # 统计计数器
  114. new_count = 0
  115. updated_count = 0
  116. title_changed_count = 0
  117. success_sources = []
  118. for source_id, news_list in data.items.items():
  119. success_sources.append(source_id)
  120. for item in news_list:
  121. try:
  122. # 标准化 URL(去除动态参数,如微博的 band_rank)
  123. normalized_url = normalize_url(item.url, source_id) if item.url else ""
  124. # 检查是否已存在(通过标准化 URL + platform_id)
  125. if normalized_url:
  126. cursor.execute("""
  127. SELECT id, title FROM news_items
  128. WHERE url = ? AND platform_id = ?
  129. """, (normalized_url, source_id))
  130. existing = cursor.fetchone()
  131. if existing:
  132. # 已存在,更新记录
  133. existing_id, existing_title = existing
  134. # 检查标题是否变化
  135. if existing_title != item.title:
  136. # 记录标题变更
  137. cursor.execute("""
  138. INSERT INTO title_changes
  139. (news_item_id, old_title, new_title, changed_at)
  140. VALUES (?, ?, ?, ?)
  141. """, (existing_id, existing_title, item.title, now_str))
  142. title_changed_count += 1
  143. # 记录排名历史
  144. cursor.execute("""
  145. INSERT INTO rank_history
  146. (news_item_id, rank, crawl_time, created_at)
  147. VALUES (?, ?, ?, ?)
  148. """, (existing_id, item.rank, data.crawl_time, now_str))
  149. # 更新现有记录
  150. cursor.execute("""
  151. UPDATE news_items SET
  152. title = ?,
  153. rank = ?,
  154. mobile_url = ?,
  155. last_crawl_time = ?,
  156. crawl_count = crawl_count + 1,
  157. updated_at = ?
  158. WHERE id = ?
  159. """, (item.title, item.rank, item.mobile_url,
  160. data.crawl_time, now_str, existing_id))
  161. updated_count += 1
  162. else:
  163. # 不存在,插入新记录(存储标准化后的 URL)
  164. cursor.execute("""
  165. INSERT INTO news_items
  166. (title, platform_id, rank, url, mobile_url,
  167. first_crawl_time, last_crawl_time, crawl_count,
  168. created_at, updated_at)
  169. VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
  170. """, (item.title, source_id, item.rank, normalized_url,
  171. item.mobile_url, data.crawl_time, data.crawl_time,
  172. now_str, now_str))
  173. new_id = cursor.lastrowid
  174. # 记录初始排名
  175. cursor.execute("""
  176. INSERT INTO rank_history
  177. (news_item_id, rank, crawl_time, created_at)
  178. VALUES (?, ?, ?, ?)
  179. """, (new_id, item.rank, data.crawl_time, now_str))
  180. new_count += 1
  181. else:
  182. # URL 为空的情况,直接插入(不做去重)
  183. cursor.execute("""
  184. INSERT INTO news_items
  185. (title, platform_id, rank, url, mobile_url,
  186. first_crawl_time, last_crawl_time, crawl_count,
  187. created_at, updated_at)
  188. VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
  189. """, (item.title, source_id, item.rank, "",
  190. item.mobile_url, data.crawl_time, data.crawl_time,
  191. now_str, now_str))
  192. new_id = cursor.lastrowid
  193. # 记录初始排名
  194. cursor.execute("""
  195. INSERT INTO rank_history
  196. (news_item_id, rank, crawl_time, created_at)
  197. VALUES (?, ?, ?, ?)
  198. """, (new_id, item.rank, data.crawl_time, now_str))
  199. new_count += 1
  200. except sqlite3.Error as e:
  201. print(f"保存新闻条目失败 [{item.title[:30]}...]: {e}")
  202. total_items = new_count + updated_count
  203. # 记录抓取信息
  204. cursor.execute("""
  205. INSERT OR REPLACE INTO crawl_records
  206. (crawl_time, total_items, created_at)
  207. VALUES (?, ?, ?)
  208. """, (data.crawl_time, total_items, now_str))
  209. # 获取刚插入的 crawl_record 的 ID
  210. cursor.execute("""
  211. SELECT id FROM crawl_records WHERE crawl_time = ?
  212. """, (data.crawl_time,))
  213. record_row = cursor.fetchone()
  214. if record_row:
  215. crawl_record_id = record_row[0]
  216. # 记录成功的来源
  217. for source_id in success_sources:
  218. cursor.execute("""
  219. INSERT OR REPLACE INTO crawl_source_status
  220. (crawl_record_id, platform_id, status)
  221. VALUES (?, ?, 'success')
  222. """, (crawl_record_id, source_id))
  223. # 记录失败的来源
  224. for failed_id in data.failed_ids:
  225. # 确保失败的平台也在 platforms 表中
  226. cursor.execute("""
  227. INSERT OR IGNORE INTO platforms (id, name, updated_at)
  228. VALUES (?, ?, ?)
  229. """, (failed_id, failed_id, now_str))
  230. cursor.execute("""
  231. INSERT OR REPLACE INTO crawl_source_status
  232. (crawl_record_id, platform_id, status)
  233. VALUES (?, ?, 'failed')
  234. """, (crawl_record_id, failed_id))
  235. conn.commit()
  236. # 输出详细的存储统计日志
  237. log_parts = [f"[本地存储] 处理完成:新增 {new_count} 条"]
  238. if updated_count > 0:
  239. log_parts.append(f"更新 {updated_count} 条")
  240. if title_changed_count > 0:
  241. log_parts.append(f"标题变更 {title_changed_count} 条")
  242. print(",".join(log_parts))
  243. return True
  244. except Exception as e:
  245. print(f"[本地存储] 保存失败: {e}")
  246. return False
  247. def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  248. """
  249. 获取指定日期的所有新闻数据(合并后)
  250. Args:
  251. date: 日期字符串,默认为今天
  252. Returns:
  253. 合并后的新闻数据
  254. """
  255. try:
  256. db_path = self._get_db_path(date)
  257. if not db_path.exists():
  258. return None
  259. conn = self._get_connection(date)
  260. cursor = conn.cursor()
  261. # 获取所有新闻数据(包含 id 用于查询排名历史)
  262. cursor.execute("""
  263. SELECT n.id, n.title, n.platform_id, p.name as platform_name,
  264. n.rank, n.url, n.mobile_url,
  265. n.first_crawl_time, n.last_crawl_time, n.crawl_count
  266. FROM news_items n
  267. LEFT JOIN platforms p ON n.platform_id = p.id
  268. ORDER BY n.platform_id, n.last_crawl_time
  269. """)
  270. rows = cursor.fetchall()
  271. if not rows:
  272. return None
  273. # 收集所有 news_item_id
  274. news_ids = [row[0] for row in rows]
  275. # 批量查询排名历史
  276. rank_history_map: Dict[int, List[int]] = {}
  277. if news_ids:
  278. placeholders = ",".join("?" * len(news_ids))
  279. cursor.execute(f"""
  280. SELECT news_item_id, rank FROM rank_history
  281. WHERE news_item_id IN ({placeholders})
  282. ORDER BY news_item_id, crawl_time
  283. """, news_ids)
  284. for rh_row in cursor.fetchall():
  285. news_id, rank = rh_row[0], rh_row[1]
  286. if news_id not in rank_history_map:
  287. rank_history_map[news_id] = []
  288. if rank not in rank_history_map[news_id]:
  289. rank_history_map[news_id].append(rank)
  290. # 按 platform_id 分组
  291. items: Dict[str, List[NewsItem]] = {}
  292. id_to_name: Dict[str, str] = {}
  293. crawl_date = self._format_date_folder(date)
  294. for row in rows:
  295. news_id = row[0]
  296. platform_id = row[2]
  297. title = row[1]
  298. platform_name = row[3] or platform_id
  299. id_to_name[platform_id] = platform_name
  300. if platform_id not in items:
  301. items[platform_id] = []
  302. # 获取排名历史,如果没有则使用当前排名
  303. ranks = rank_history_map.get(news_id, [row[4]])
  304. items[platform_id].append(NewsItem(
  305. title=title,
  306. source_id=platform_id,
  307. source_name=platform_name,
  308. rank=row[4],
  309. url=row[5] or "",
  310. mobile_url=row[6] or "",
  311. crawl_time=row[8], # last_crawl_time
  312. ranks=ranks,
  313. first_time=row[7], # first_crawl_time
  314. last_time=row[8], # last_crawl_time
  315. count=row[9], # crawl_count
  316. ))
  317. final_items = items
  318. # 获取失败的来源
  319. cursor.execute("""
  320. SELECT DISTINCT css.platform_id
  321. FROM crawl_source_status css
  322. JOIN crawl_records cr ON css.crawl_record_id = cr.id
  323. WHERE css.status = 'failed'
  324. """)
  325. failed_ids = [row[0] for row in cursor.fetchall()]
  326. # 获取最新的抓取时间
  327. cursor.execute("""
  328. SELECT crawl_time FROM crawl_records
  329. ORDER BY crawl_time DESC
  330. LIMIT 1
  331. """)
  332. time_row = cursor.fetchone()
  333. crawl_time = time_row[0] if time_row else self._format_time_filename()
  334. return NewsData(
  335. date=crawl_date,
  336. crawl_time=crawl_time,
  337. items=final_items,
  338. id_to_name=id_to_name,
  339. failed_ids=failed_ids,
  340. )
  341. except Exception as e:
  342. print(f"[本地存储] 读取数据失败: {e}")
  343. return None
  344. def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]:
  345. """
  346. 获取最新一次抓取的数据
  347. Args:
  348. date: 日期字符串,默认为今天
  349. Returns:
  350. 最新抓取的新闻数据
  351. """
  352. try:
  353. db_path = self._get_db_path(date)
  354. if not db_path.exists():
  355. return None
  356. conn = self._get_connection(date)
  357. cursor = conn.cursor()
  358. # 获取最新的抓取时间
  359. cursor.execute("""
  360. SELECT crawl_time FROM crawl_records
  361. ORDER BY crawl_time DESC
  362. LIMIT 1
  363. """)
  364. time_row = cursor.fetchone()
  365. if not time_row:
  366. return None
  367. latest_time = time_row[0]
  368. # 获取该时间的新闻数据(包含 id 用于查询排名历史)
  369. cursor.execute("""
  370. SELECT n.id, n.title, n.platform_id, p.name as platform_name,
  371. n.rank, n.url, n.mobile_url,
  372. n.first_crawl_time, n.last_crawl_time, n.crawl_count
  373. FROM news_items n
  374. LEFT JOIN platforms p ON n.platform_id = p.id
  375. WHERE n.last_crawl_time = ?
  376. """, (latest_time,))
  377. rows = cursor.fetchall()
  378. if not rows:
  379. return None
  380. # 收集所有 news_item_id
  381. news_ids = [row[0] for row in rows]
  382. # 批量查询排名历史
  383. rank_history_map: Dict[int, List[int]] = {}
  384. if news_ids:
  385. placeholders = ",".join("?" * len(news_ids))
  386. cursor.execute(f"""
  387. SELECT news_item_id, rank FROM rank_history
  388. WHERE news_item_id IN ({placeholders})
  389. ORDER BY news_item_id, crawl_time
  390. """, news_ids)
  391. for rh_row in cursor.fetchall():
  392. news_id, rank = rh_row[0], rh_row[1]
  393. if news_id not in rank_history_map:
  394. rank_history_map[news_id] = []
  395. if rank not in rank_history_map[news_id]:
  396. rank_history_map[news_id].append(rank)
  397. items: Dict[str, List[NewsItem]] = {}
  398. id_to_name: Dict[str, str] = {}
  399. crawl_date = self._format_date_folder(date)
  400. for row in rows:
  401. news_id = row[0]
  402. platform_id = row[2]
  403. platform_name = row[3] or platform_id
  404. id_to_name[platform_id] = platform_name
  405. if platform_id not in items:
  406. items[platform_id] = []
  407. # 获取排名历史,如果没有则使用当前排名
  408. ranks = rank_history_map.get(news_id, [row[4]])
  409. items[platform_id].append(NewsItem(
  410. title=row[1],
  411. source_id=platform_id,
  412. source_name=platform_name,
  413. rank=row[4],
  414. url=row[5] or "",
  415. mobile_url=row[6] or "",
  416. crawl_time=row[8], # last_crawl_time
  417. ranks=ranks,
  418. first_time=row[7], # first_crawl_time
  419. last_time=row[8], # last_crawl_time
  420. count=row[9], # crawl_count
  421. ))
  422. # 获取失败的来源(针对最新一次抓取)
  423. cursor.execute("""
  424. SELECT css.platform_id
  425. FROM crawl_source_status css
  426. JOIN crawl_records cr ON css.crawl_record_id = cr.id
  427. WHERE cr.crawl_time = ? AND css.status = 'failed'
  428. """, (latest_time,))
  429. failed_ids = [row[0] for row in cursor.fetchall()]
  430. return NewsData(
  431. date=crawl_date,
  432. crawl_time=latest_time,
  433. items=items,
  434. id_to_name=id_to_name,
  435. failed_ids=failed_ids,
  436. )
  437. except Exception as e:
  438. print(f"[本地存储] 获取最新数据失败: {e}")
  439. return None
  440. def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]:
  441. """
  442. 检测新增的标题
  443. 该方法比较当前抓取数据与历史数据,找出新增的标题。
  444. 关键逻辑:只有在历史批次中从未出现过的标题才算新增。
  445. Args:
  446. current_data: 当前抓取的数据
  447. Returns:
  448. 新增的标题数据 {source_id: {title: NewsItem}}
  449. """
  450. try:
  451. # 获取历史数据
  452. historical_data = self.get_today_all_data(current_data.date)
  453. if not historical_data:
  454. # 没有历史数据,所有都是新的
  455. new_titles = {}
  456. for source_id, news_list in current_data.items.items():
  457. new_titles[source_id] = {item.title: item for item in news_list}
  458. return new_titles
  459. # 获取当前批次时间
  460. current_time = current_data.crawl_time
  461. # 收集历史标题(first_time < current_time 的标题)
  462. # 这样可以正确处理同一标题因 URL 变化而产生多条记录的情况
  463. historical_titles: Dict[str, set] = {}
  464. for source_id, news_list in historical_data.items.items():
  465. historical_titles[source_id] = set()
  466. for item in news_list:
  467. first_time = getattr(item, 'first_time', item.crawl_time)
  468. if first_time < current_time:
  469. historical_titles[source_id].add(item.title)
  470. # 检查是否有历史数据
  471. has_historical_data = any(len(titles) > 0 for titles in historical_titles.values())
  472. if not has_historical_data:
  473. # 第一次抓取,没有"新增"概念
  474. return {}
  475. # 检测新增
  476. new_titles = {}
  477. for source_id, news_list in current_data.items.items():
  478. hist_set = historical_titles.get(source_id, set())
  479. for item in news_list:
  480. if item.title not in hist_set:
  481. if source_id not in new_titles:
  482. new_titles[source_id] = {}
  483. new_titles[source_id][item.title] = item
  484. return new_titles
  485. except Exception as e:
  486. print(f"[本地存储] 检测新标题失败: {e}")
  487. return {}
  488. def save_txt_snapshot(self, data: NewsData) -> Optional[str]:
  489. """
  490. 保存 TXT 快照
  491. Args:
  492. data: 新闻数据
  493. Returns:
  494. 保存的文件路径
  495. """
  496. if not self.enable_txt:
  497. return None
  498. try:
  499. date_folder = self._format_date_folder(data.date)
  500. txt_dir = self.data_dir / date_folder / "txt"
  501. txt_dir.mkdir(parents=True, exist_ok=True)
  502. file_path = txt_dir / f"{data.crawl_time}.txt"
  503. with open(file_path, "w", encoding="utf-8") as f:
  504. for source_id, news_list in data.items.items():
  505. source_name = data.id_to_name.get(source_id, source_id)
  506. # 写入来源标题
  507. if source_name and source_name != source_id:
  508. f.write(f"{source_id} | {source_name}\n")
  509. else:
  510. f.write(f"{source_id}\n")
  511. # 按排名排序
  512. sorted_news = sorted(news_list, key=lambda x: x.rank)
  513. for item in sorted_news:
  514. line = f"{item.rank}. {item.title}"
  515. if item.url:
  516. line += f" [URL:{item.url}]"
  517. if item.mobile_url:
  518. line += f" [MOBILE:{item.mobile_url}]"
  519. f.write(line + "\n")
  520. f.write("\n")
  521. # 写入失败的来源
  522. if data.failed_ids:
  523. f.write("==== 以下ID请求失败 ====\n")
  524. for failed_id in data.failed_ids:
  525. f.write(f"{failed_id}\n")
  526. print(f"[本地存储] TXT 快照已保存: {file_path}")
  527. return str(file_path)
  528. except Exception as e:
  529. print(f"[本地存储] 保存 TXT 快照失败: {e}")
  530. return None
  531. def save_html_report(self, html_content: str, filename: str, is_summary: bool = False) -> Optional[str]:
  532. """
  533. 保存 HTML 报告
  534. Args:
  535. html_content: HTML 内容
  536. filename: 文件名
  537. is_summary: 是否为汇总报告
  538. Returns:
  539. 保存的文件路径
  540. """
  541. if not self.enable_html:
  542. return None
  543. try:
  544. date_folder = self._format_date_folder()
  545. html_dir = self.data_dir / date_folder / "html"
  546. html_dir.mkdir(parents=True, exist_ok=True)
  547. file_path = html_dir / filename
  548. with open(file_path, "w", encoding="utf-8") as f:
  549. f.write(html_content)
  550. print(f"[本地存储] HTML 报告已保存: {file_path}")
  551. return str(file_path)
  552. except Exception as e:
  553. print(f"[本地存储] 保存 HTML 报告失败: {e}")
  554. return None
  555. def is_first_crawl_today(self, date: Optional[str] = None) -> bool:
  556. """
  557. 检查是否是当天第一次抓取
  558. Args:
  559. date: 日期字符串,默认为今天
  560. Returns:
  561. 是否是第一次抓取
  562. """
  563. try:
  564. db_path = self._get_db_path(date)
  565. if not db_path.exists():
  566. return True
  567. conn = self._get_connection(date)
  568. cursor = conn.cursor()
  569. cursor.execute("""
  570. SELECT COUNT(*) as count FROM crawl_records
  571. """)
  572. row = cursor.fetchone()
  573. count = row[0] if row else 0
  574. # 如果只有一条或没有记录,视为第一次抓取
  575. return count <= 1
  576. except Exception as e:
  577. print(f"[本地存储] 检查首次抓取失败: {e}")
  578. return True
  579. def get_crawl_times(self, date: Optional[str] = None) -> List[str]:
  580. """
  581. 获取指定日期的所有抓取时间列表
  582. Args:
  583. date: 日期字符串,默认为今天
  584. Returns:
  585. 抓取时间列表(按时间排序)
  586. """
  587. try:
  588. db_path = self._get_db_path(date)
  589. if not db_path.exists():
  590. return []
  591. conn = self._get_connection(date)
  592. cursor = conn.cursor()
  593. cursor.execute("""
  594. SELECT crawl_time FROM crawl_records
  595. ORDER BY crawl_time
  596. """)
  597. rows = cursor.fetchall()
  598. return [row[0] for row in rows]
  599. except Exception as e:
  600. print(f"[本地存储] 获取抓取时间列表失败: {e}")
  601. return []
  602. def cleanup(self) -> None:
  603. """清理资源(关闭数据库连接)"""
  604. for db_path, conn in self._db_connections.items():
  605. try:
  606. conn.close()
  607. print(f"[本地存储] 关闭数据库连接: {db_path}")
  608. except Exception as e:
  609. print(f"[本地存储] 关闭连接失败 {db_path}: {e}")
  610. self._db_connections.clear()
  611. def cleanup_old_data(self, retention_days: int) -> int:
  612. """
  613. 清理过期数据
  614. Args:
  615. retention_days: 保留天数(0 表示不清理)
  616. Returns:
  617. 删除的日期目录数量
  618. """
  619. if retention_days <= 0:
  620. return 0
  621. deleted_count = 0
  622. cutoff_date = self._get_configured_time() - timedelta(days=retention_days)
  623. try:
  624. if not self.data_dir.exists():
  625. return 0
  626. for date_folder in self.data_dir.iterdir():
  627. if not date_folder.is_dir() or date_folder.name.startswith('.'):
  628. continue
  629. # 解析日期文件夹名(支持两种格式)
  630. folder_date = None
  631. try:
  632. # ISO 格式: YYYY-MM-DD
  633. date_match = re.match(r'(\d{4})-(\d{2})-(\d{2})', date_folder.name)
  634. if date_match:
  635. folder_date = datetime(
  636. int(date_match.group(1)),
  637. int(date_match.group(2)),
  638. int(date_match.group(3)),
  639. tzinfo=pytz.timezone("Asia/Shanghai")
  640. )
  641. else:
  642. # 旧中文格式: YYYY年MM月DD日
  643. date_match = re.match(r'(\d{4})年(\d{2})月(\d{2})日', date_folder.name)
  644. if date_match:
  645. folder_date = datetime(
  646. int(date_match.group(1)),
  647. int(date_match.group(2)),
  648. int(date_match.group(3)),
  649. tzinfo=pytz.timezone("Asia/Shanghai")
  650. )
  651. except Exception:
  652. continue
  653. if folder_date and folder_date < cutoff_date:
  654. # 先关闭该日期的数据库连接
  655. db_path = str(self._get_db_path(date_folder.name))
  656. if db_path in self._db_connections:
  657. try:
  658. self._db_connections[db_path].close()
  659. del self._db_connections[db_path]
  660. except Exception:
  661. pass
  662. # 删除整个日期目录
  663. try:
  664. shutil.rmtree(date_folder)
  665. deleted_count += 1
  666. print(f"[本地存储] 清理过期数据: {date_folder.name}")
  667. except Exception as e:
  668. print(f"[本地存储] 删除目录失败 {date_folder.name}: {e}")
  669. if deleted_count > 0:
  670. print(f"[本地存储] 共清理 {deleted_count} 个过期日期目录")
  671. return deleted_count
  672. except Exception as e:
  673. print(f"[本地存储] 清理过期数据失败: {e}")
  674. return deleted_count
  675. def has_pushed_today(self, date: Optional[str] = None) -> bool:
  676. """
  677. 检查指定日期是否已推送过
  678. Args:
  679. date: 日期字符串(YYYY-MM-DD),默认为今天
  680. Returns:
  681. 是否已推送
  682. """
  683. try:
  684. conn = self._get_connection(date)
  685. cursor = conn.cursor()
  686. target_date = self._format_date_folder(date)
  687. cursor.execute("""
  688. SELECT pushed FROM push_records WHERE date = ?
  689. """, (target_date,))
  690. row = cursor.fetchone()
  691. if row:
  692. return bool(row[0])
  693. return False
  694. except Exception as e:
  695. print(f"[本地存储] 检查推送记录失败: {e}")
  696. return False
  697. def record_push(self, report_type: str, date: Optional[str] = None) -> bool:
  698. """
  699. 记录推送
  700. Args:
  701. report_type: 报告类型
  702. date: 日期字符串(YYYY-MM-DD),默认为今天
  703. Returns:
  704. 是否记录成功
  705. """
  706. try:
  707. conn = self._get_connection(date)
  708. cursor = conn.cursor()
  709. target_date = self._format_date_folder(date)
  710. now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S")
  711. cursor.execute("""
  712. INSERT INTO push_records (date, pushed, push_time, report_type, created_at)
  713. VALUES (?, 1, ?, ?, ?)
  714. ON CONFLICT(date) DO UPDATE SET
  715. pushed = 1,
  716. push_time = excluded.push_time,
  717. report_type = excluded.report_type
  718. """, (target_date, now_str, report_type, now_str))
  719. conn.commit()
  720. print(f"[本地存储] 推送记录已保存: {report_type} at {now_str}")
  721. return True
  722. except Exception as e:
  723. print(f"[本地存储] 记录推送失败: {e}")
  724. return False
  725. def __del__(self):
  726. """析构函数,确保关闭连接"""
  727. self.cleanup()