monitorStray.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import os
  2. import sys
  3. import threading
  4. import time
  5. from typing import List
  6. import schedule
  7. from PIL import Image
  8. from pystray import Icon, MenuItem
  9. from browser import Browser
  10. from spider import Douyin
  11. class API(Douyin):
  12. def download(self):
  13. """
  14. 采集完成后,统一下载已采集的结果
  15. """
  16. if os.path.exists(self.aria2_conf):
  17. command = f"aria2c -c --console-log-level warn -d {self.down_path} -i {self.aria2_conf}"
  18. # os.system(command) # system有输出,阻塞
  19. os.popen(command) # popen无输出,不阻塞
  20. def get_path(relative_path):
  21. try:
  22. # PyInstaller
  23. base_path = sys._MEIPASS
  24. except Exception:
  25. base_path = os.path.abspath(".")
  26. return os.path.join(base_path, relative_path)
  27. def start() -> None:
  28. print('任务开始')
  29. edge = Browser()
  30. with open('url.txt', 'r', encoding='utf-8') as f:
  31. lines: List[str] = f.readlines()
  32. for url in lines:
  33. a = API(edge.context, url)
  34. a.run()
  35. if a.results:
  36. if download:
  37. icon.notify(f"发现{len(a.results)}条新内容,开始下载", "发现新内容")
  38. a.download()
  39. else:
  40. icon.notify(f"发现{len(a.results)}条新内容", "发现新内容")
  41. else:
  42. # icon.notify("未发现新内容")
  43. pass
  44. edge.stop()
  45. print('任务结束')
  46. def click_download(icon: Icon, item: MenuItem):
  47. global download
  48. download = not item.checked
  49. def click_start(icon: Icon, item: MenuItem):
  50. global running
  51. running = not item.checked
  52. set_schedule(icon)
  53. def click_exit(icon: Icon, item: MenuItem):
  54. global state
  55. state = False
  56. schedule.clear()
  57. icon.stop()
  58. def set_schedule(icon: Icon):
  59. if running:
  60. schedule.every(10).minutes.do(start)
  61. schedule.run_all()
  62. if icon.HAS_NOTIFICATION:
  63. icon.title = '监控中'
  64. icon.notify(f'{int(schedule.idle_seconds())}秒后执行下一次任务', '抖音监控')
  65. else:
  66. schedule.clear()
  67. if icon.HAS_NOTIFICATION:
  68. icon.title = '未启动'
  69. icon.notify("停止监控", '抖音监控')
  70. def on_start():
  71. set_schedule(icon)
  72. while state:
  73. schedule.run_pending()
  74. time.sleep(1)
  75. state = True
  76. running = True
  77. download = False
  78. menu = (
  79. MenuItem(text='开始', action=click_start, checked=lambda item: running, default=True),
  80. MenuItem(text='下载', action=click_download, checked=lambda item: download, default=False),
  81. MenuItem(text='退出', action=click_exit),
  82. )
  83. image: Image = Image.open(get_path("ico.ico"))
  84. icon: Icon = Icon("监控", image, "监控中" if running else "未启动", menu)
  85. # 使用icon.run(setup=on_start)时无法创建图标,只能单独跑一个线程
  86. threading.Thread(target=on_start, daemon=True).start()
  87. icon.run()