update.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. import ujson
  17. headers = {
  18. 'Referer': 'https://gitcode.net/',
  19. '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',
  20. }
  21. def getHotSuggest1(url='http://4g.v.sogou.com/hotsugg',size=0):
  22. jsp = jsoup(url)
  23. pdfh = jsp.pdfh
  24. pdfa = jsp.pdfa
  25. pd = jsp.pd
  26. try:
  27. r = requests.get(url,headers=headers,timeout=2)
  28. html = r.text
  29. data = pdfa(html,'ul.hot-list&&li')
  30. suggs = [{'title':pdfh(dt,'a&&Text'),'url':pd(dt,'a&&href')} for dt in data]
  31. # print(html)
  32. # print(suggs)
  33. return suggs
  34. except:
  35. return []
  36. def getHotSuggest2(url='https://pbaccess.video.qq.com/trpc.videosearch.hot_rank.HotRankServantHttp/HotRankHttp',size=0):
  37. size = int(size) if size else 50
  38. pdata = ujson.dumps({"pageNum":0,"pageSize":size})
  39. try:
  40. r = requests.post(url,headers={'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', 'content-type': 'application/json'},data=pdata,timeout=2)
  41. html = r.json()
  42. # print(html)
  43. data = html['data']['navItemList'][0]['hotRankResult']['rankItemList']
  44. suggs = [{'title':dt['title'],'url':dt['url']} for dt in data]
  45. # print(html)
  46. # print(suggs)
  47. return suggs
  48. except:
  49. return []
  50. def getHotSuggest(s_from,size):
  51. if s_from == 'sougou':
  52. return getHotSuggest1(size=size)
  53. else:
  54. return getHotSuggest2(size=size)
  55. def getLocalVer():
  56. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  57. version_path = os.path.join(base_path, f'js/version.txt')
  58. if not os.path.exists(version_path):
  59. with open(version_path,mode='w+',encoding='utf-8') as f:
  60. version = '1.0.0'
  61. f.write(version)
  62. else:
  63. with open(version_path,encoding='utf-8') as f:
  64. version = f.read()
  65. return version
  66. def getOnlineVer():
  67. ver = '1.0.1'
  68. msg = ''
  69. try:
  70. # r = requests.get('https://gitcode.net/qq_32394351/dr_py/-/raw/master/js/version.txt',timeout=(2,2))
  71. r = requests.get('https://code.gitlink.org.cn/api/v1/repos/hjdhnx/dr_py/raw/master/js/version.txt',timeout=(2,2))
  72. ver = r.text
  73. except Exception as e:
  74. # print(f'{e}')
  75. msg = f'{e}'
  76. logger.info(msg)
  77. return ver,msg
  78. def checkUpdate():
  79. local_ver = getLocalVer()
  80. online_ver,msg = getOnlineVer()
  81. if local_ver != online_ver:
  82. return True
  83. return False
  84. def del_file(filepath):
  85. """
  86. 删除execl目录下的所有文件或文件夹
  87. :param filepath: 路径
  88. :return:
  89. """
  90. del_list = os.listdir(filepath)
  91. for f in del_list:
  92. file_path = os.path.join(filepath, f)
  93. if os.path.isfile(file_path):
  94. os.remove(file_path)
  95. def copytree(src, dst, ignore=None):
  96. if ignore is None:
  97. ignore = []
  98. dirs = os.listdir(src) # 获取目录下的所有文件包括文件夹
  99. logger.info(f'{dirs}')
  100. for dir in dirs: # 遍历文件或文件夹
  101. from_dir = os.path.join(src, dir) # 将要复制的文件夹或文件路径
  102. to_dir = os.path.join(dst, dir) # 将要复制到的文件夹或文件路径
  103. if os.path.isdir(from_dir): # 判断是否为文件夹
  104. if not os.path.exists(to_dir): # 判断目标文件夹是否存在,不存在则创建
  105. os.mkdir(to_dir)
  106. copytree(from_dir, to_dir,ignore) # 迭代 遍历子文件夹并复制文件
  107. elif os.path.isfile(from_dir): # 如果为文件,则直接复制文件
  108. if ignore:
  109. regxp = '|'.join(ignore).replace('\\','/') # 组装正则
  110. to_dir_str = str(to_dir).replace('\\','/')
  111. if not re.search(rf'{regxp}', to_dir_str, re.M):
  112. shutil.copy(from_dir, to_dir) # 复制文件
  113. else:
  114. shutil.copy(from_dir, to_dir) # 复制文件
  115. def force_copy_files(from_path, to_path, exclude_files=None):
  116. # print(f'开始拷贝文件{from_path}=>{to_path}')
  117. if exclude_files is None:
  118. exclude_files = []
  119. logger.info(f'开始拷贝文件{from_path}=>{to_path}')
  120. if not os.path.exists(to_path):
  121. os.makedirs(to_path,exist_ok=True)
  122. try:
  123. if sys.version_info < (3, 8):
  124. copytree(from_path, to_path,exclude_files)
  125. else:
  126. if len(exclude_files) > 0:
  127. shutil.copytree(from_path, to_path, dirs_exist_ok=True,ignore=shutil.ignore_patterns(*exclude_files))
  128. else:
  129. shutil.copytree(from_path, to_path, dirs_exist_ok=True)
  130. except Exception as e:
  131. logger.info(f'拷贝文件{from_path}=>{to_path}发生错误:{e}')
  132. def copy_to_update():
  133. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  134. tmp_path = os.path.join(base_path, f'tmp')
  135. dr_path = os.path.join(tmp_path, f'dr_py')
  136. if not os.path.exists(dr_path):
  137. # print(f'升级失败,找不到目录{dr_path}')
  138. logger.info(f'升级失败,找不到目录{dr_path}')
  139. return False
  140. # 千万不能覆盖super,base
  141. paths = ['js','models','controllers','libs','static','templates','utils','txt','jiexi','py','whl','doc']
  142. exclude_files = ['txt/pycms0.json','txt/pycms1.json','txt/pycms2.json','base/rules.db']
  143. for path in paths:
  144. force_copy_files(os.path.join(dr_path, path),os.path.join(base_path, path),exclude_files)
  145. try:
  146. shutil.copy(os.path.join(dr_path, 'app.py'), os.path.join(base_path, 'app.py')) # 复制文件
  147. except Exception as e:
  148. logger.info(f'更新app.py发生错误:{e}')
  149. logger.info(f'升级程序执行完毕,全部文件已拷贝覆盖')
  150. return True
  151. def download_new_version():
  152. t1 = getTime()
  153. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  154. tmp_path = os.path.join(base_path, f'tmp')
  155. os.makedirs(tmp_path,exist_ok=True)
  156. # url = 'https://gitcode.net/qq_32394351/dr_py/-/archive/master/dr_py-master.zip'
  157. url = 'https://code.gitlink.org.cn/api/v1/repos/hjdhnx/dr_py/archive/master.zip'
  158. # tmp_files = os.listdir(tmp_path)
  159. # for tp in tmp_files:
  160. # print(f'清除缓存文件:{tp}')
  161. # os.remove(os.path.join(tmp_path, tp))
  162. del_file(tmp_path)
  163. msg = ''
  164. try:
  165. # print(f'开始下载:{url}')
  166. logger.info(f'开始下载:{url}')
  167. r = requests.get(url,headers=headers,timeout=(20,20))
  168. rb = r.content
  169. download_path = os.path.join(tmp_path, 'dr_py.zip')
  170. with open(download_path,mode='wb+') as f:
  171. f.write(rb)
  172. # print(f'开始解压文件:{download_path}')
  173. logger.info(f'开始解压文件:{download_path}')
  174. f = zipfile.ZipFile(download_path, 'r') # 压缩文件位置
  175. for file in f.namelist():
  176. f.extract(file, tmp_path) # 解压位置
  177. f.close()
  178. # print('解压完毕,开始升级')
  179. logger.info('解压完毕,开始升级')
  180. ret = copy_to_update()
  181. logger.info(f'升级完毕,结果为:{ret}')
  182. # print(f'升级完毕,结果为:{ret}')
  183. msg = '升级成功'
  184. except Exception as e:
  185. msg = f'升级失败:{e}'
  186. logger.info(f'系统升级共计耗时:{get_interval(t1)}毫秒')
  187. return msg
  188. def download_lives(live_url:str):
  189. t1 = getTime()
  190. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  191. live_path = os.path.join(base_path, f'base/直播.txt')
  192. logger.info(f'尝试同步{live_url}远程内容到{live_path}')
  193. try:
  194. r = requests.get(live_url,headers=headers,timeout=3)
  195. auto_encoding = r.apparent_encoding
  196. if auto_encoding.lower() in ['utf-8','gbk','bg2312','gb18030']:
  197. r.encoding = auto_encoding
  198. # print(r.encoding)
  199. html = r.text
  200. # print(len(html))
  201. if re.search('cctv|.m3u8',html,re.M|re.I) and len(html) > 1000:
  202. logger.info(f'直播源同步成功,耗时{get_interval(t1)}毫秒')
  203. with open(live_path,mode='w+',encoding='utf-8') as f:
  204. f.write(html)
  205. return True
  206. else:
  207. logger.info(f'直播源同步失败,远程文件看起来不是直播源。耗时{get_interval(t1)}毫秒')
  208. return False
  209. except Exception as e:
  210. logger.info(f'直播源同步失败,耗时{get_interval(t1)}毫秒\n{e}')
  211. return False