update.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : update.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Date : 2022/9/6
  6. import re
  7. from time import time as getTime
  8. import sys
  9. import requests
  10. import os
  11. import zipfile
  12. import shutil # https://blog.csdn.net/weixin_33130113/article/details/112336581
  13. from utils.log import logger
  14. from utils.web import get_interval
  15. from utils.htmlParser import jsoup
  16. headers = {
  17. 'Referer': 'https://gitcode.net/',
  18. # 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36',
  19. 'X-T5-Auth': 'ZjQxNDIh',
  20. 'User-Agent': 'baiduboxapp',
  21. }
  22. proxies={"https":"http://cloudnproxy.baidu.com:443","http":"http://cloudnproxy.baidu.com:443"}
  23. def getHotSuggest(url='http://4g.v.sogou.com/hotsugg'):
  24. jsp = jsoup(url)
  25. pdfh = jsp.pdfh
  26. pdfa = jsp.pdfa
  27. pd = jsp.pd
  28. try:
  29. r = requests.get(url,headers=headers,timeout=2)
  30. html = r.text
  31. data = pdfa(html,'ul.hot-list&&li')
  32. suggs = [{'title':pdfh(dt,'a&&Text'),'url':pd(dt,'a&&href')} for dt in data]
  33. # print(html)
  34. # print(suggs)
  35. return suggs
  36. except:
  37. return []
  38. def getLocalVer():
  39. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  40. version_path = os.path.join(base_path, f'js/version.txt')
  41. if not os.path.exists(version_path):
  42. with open(version_path,mode='w+',encoding='utf-8') as f:
  43. version = '1.0.0'
  44. f.write(version)
  45. else:
  46. with open(version_path,encoding='utf-8') as f:
  47. version = f.read()
  48. return version
  49. def getOnlineVer():
  50. ver = '1.0.1'
  51. msg = ''
  52. try:
  53. r = requests.get('https://gitcode.net/qq_32394351/dr_py/-/raw/master/js/version.txt',timeout=(2,2),proxies=proxies)
  54. ver = r.text
  55. except Exception as e:
  56. # print(f'{e}')
  57. msg = f'{e}'
  58. logger.info(msg)
  59. return ver,msg
  60. def checkUpdate():
  61. local_ver = getLocalVer()
  62. online_ver,msg = getOnlineVer()
  63. if local_ver != online_ver:
  64. return True
  65. return False
  66. def del_file(filepath):
  67. """
  68. 删除execl目录下的所有文件或文件夹
  69. :param filepath: 路径
  70. :return:
  71. """
  72. del_list = os.listdir(filepath)
  73. for f in del_list:
  74. file_path = os.path.join(filepath, f)
  75. if os.path.isfile(file_path):
  76. os.remove(file_path)
  77. def copytree(src, dst, ignore=None):
  78. if ignore is None:
  79. ignore = []
  80. dirs = os.listdir(src) # 获取目录下的所有文件包括文件夹
  81. logger.info(f'{dirs}')
  82. for dir in dirs: # 遍历文件或文件夹
  83. from_dir = os.path.join(src, dir) # 将要复制的文件夹或文件路径
  84. to_dir = os.path.join(dst, dir) # 将要复制到的文件夹或文件路径
  85. if os.path.isdir(from_dir): # 判断是否为文件夹
  86. if not os.path.exists(to_dir): # 判断目标文件夹是否存在,不存在则创建
  87. os.mkdir(to_dir)
  88. copytree(from_dir, to_dir,ignore) # 迭代 遍历子文件夹并复制文件
  89. elif os.path.isfile(from_dir): # 如果为文件,则直接复制文件
  90. if ignore:
  91. regxp = '|'.join(ignore).replace('\\','/') # 组装正则
  92. to_dir_str = str(to_dir).replace('\\','/')
  93. if not re.search(rf'{regxp}', to_dir_str, re.M):
  94. shutil.copy(from_dir, to_dir) # 复制文件
  95. else:
  96. shutil.copy(from_dir, to_dir) # 复制文件
  97. def force_copy_files(from_path, to_path, exclude_files=None):
  98. # print(f'开始拷贝文件{from_path}=>{to_path}')
  99. if exclude_files is None:
  100. exclude_files = []
  101. logger.info(f'开始拷贝文件{from_path}=>{to_path}')
  102. if not os.path.exists(to_path):
  103. os.makedirs(to_path,exist_ok=True)
  104. try:
  105. if sys.version_info < (3, 8):
  106. copytree(from_path, to_path,exclude_files)
  107. else:
  108. if len(exclude_files) > 0:
  109. shutil.copytree(from_path, to_path, dirs_exist_ok=True,ignore=shutil.ignore_patterns(*exclude_files))
  110. else:
  111. shutil.copytree(from_path, to_path, dirs_exist_ok=True)
  112. except Exception as e:
  113. logger.info(f'拷贝文件{from_path}=>{to_path}发生错误:{e}')
  114. def copy_to_update():
  115. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  116. tmp_path = os.path.join(base_path, f'tmp')
  117. dr_path = os.path.join(tmp_path, f'dr_py-master')
  118. if not os.path.exists(dr_path):
  119. # print(f'升级失败,找不到目录{dr_path}')
  120. logger.info(f'升级失败,找不到目录{dr_path}')
  121. return False
  122. # 千万不能覆盖super,base
  123. paths = ['js','models','controllers','libs','static','templates','utils','txt','jiexi','py','whl']
  124. exclude_files = ['txt/pycms0.json','txt/pycms1.json','txt/pycms2.json','base/rules.db','utils/update.py']
  125. for path in paths:
  126. force_copy_files(os.path.join(dr_path, path),os.path.join(base_path, path),exclude_files)
  127. try:
  128. shutil.copy(os.path.join(dr_path, 'app.py'), os.path.join(base_path, 'app.py')) # 复制文件
  129. except Exception as e:
  130. logger.info(f'更新app.py发生错误:{e}')
  131. logger.info(f'升级程序执行完毕,全部文件已拷贝覆盖')
  132. return True
  133. def download_new_version():
  134. t1 = getTime()
  135. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  136. tmp_path = os.path.join(base_path, f'tmp')
  137. os.makedirs(tmp_path,exist_ok=True)
  138. url = 'https://gitcode.net/qq_32394351/dr_py/-/archive/master/dr_py-master.zip'
  139. # tmp_files = os.listdir(tmp_path)
  140. # for tp in tmp_files:
  141. # print(f'清除缓存文件:{tp}')
  142. # os.remove(os.path.join(tmp_path, tp))
  143. del_file(tmp_path)
  144. msg = ''
  145. try:
  146. # print(f'开始下载:{url}')
  147. logger.info(f'开始下载:{url}')
  148. r = requests.get(url,headers=headers,timeout=(20,20),proxies=proxies)
  149. rb = r.content
  150. download_path = os.path.join(tmp_path, 'dr_py.zip')
  151. with open(download_path,mode='wb+') as f:
  152. f.write(rb)
  153. # print(f'开始解压文件:{download_path}')
  154. logger.info(f'开始解压文件:{download_path}')
  155. f = zipfile.ZipFile(download_path, 'r') # 压缩文件位置
  156. for file in f.namelist():
  157. f.extract(file, tmp_path) # 解压位置
  158. f.close()
  159. # print('解压完毕,开始升级')
  160. logger.info('解压完毕,开始升级')
  161. ret = copy_to_update()
  162. logger.info(f'升级完毕,结果为:{ret}')
  163. # print(f'升级完毕,结果为:{ret}')
  164. msg = '升级成功'
  165. except Exception as e:
  166. msg = f'升级失败:{e}'
  167. logger.info(f'系统升级共计耗时:{get_interval(t1)}毫秒')
  168. return msg
  169. def download_lives(live_url:str):
  170. t1 = getTime()
  171. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  172. live_path = os.path.join(base_path, f'base/直播.txt')
  173. logger.info(f'尝试同步{live_url}远程内容到{live_path}')
  174. try:
  175. r = requests.get(live_url,headers=headers,timeout=3)
  176. auto_encoding = r.apparent_encoding
  177. if auto_encoding.lower() in ['utf-8','gbk','bg2312','gb18030']:
  178. r.encoding = auto_encoding
  179. # print(r.encoding)
  180. html = r.text
  181. # print(len(html))
  182. if re.search('cctv|.m3u8',html,re.M|re.I) and len(html) > 1000:
  183. logger.info(f'直播源同步成功,耗时{get_interval(t1)}毫秒')
  184. with open(live_path,mode='w+',encoding='utf-8') as f:
  185. f.write(html)
  186. return True
  187. else:
  188. logger.info(f'直播源同步失败,远程文件看起来不是直播源。耗时{get_interval(t1)}毫秒')
  189. return False
  190. except Exception as e:
  191. logger.info(f'直播源同步失败,耗时{get_interval(t1)}毫秒\n{e}')
  192. return False