local.py 31 KB

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