update.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. ver = r.text
  72. except Exception as e:
  73. # print(f'{e}')
  74. msg = f'{e}'
  75. logger.info(msg)
  76. return ver,msg
  77. def checkUpdate():
  78. local_ver = getLocalVer()
  79. online_ver,msg = getOnlineVer()
  80. if local_ver != online_ver:
  81. return True
  82. return False
  83. def del_file(filepath):
  84. """
  85. 删除execl目录下的所有文件或文件夹
  86. :param filepath: 路径
  87. :return:
  88. """
  89. del_list = os.listdir(filepath)
  90. for f in del_list:
  91. file_path = os.path.join(filepath, f)
  92. if os.path.isfile(file_path):
  93. os.remove(file_path)
  94. def copytree(src, dst, ignore=None):
  95. if ignore is None:
  96. ignore = []
  97. dirs = os.listdir(src) # 获取目录下的所有文件包括文件夹
  98. logger.info(f'{dirs}')
  99. for dir in dirs: # 遍历文件或文件夹
  100. from_dir = os.path.join(src, dir) # 将要复制的文件夹或文件路径
  101. to_dir = os.path.join(dst, dir) # 将要复制到的文件夹或文件路径
  102. if os.path.isdir(from_dir): # 判断是否为文件夹
  103. if not os.path.exists(to_dir): # 判断目标文件夹是否存在,不存在则创建
  104. os.mkdir(to_dir)
  105. copytree(from_dir, to_dir,ignore) # 迭代 遍历子文件夹并复制文件
  106. elif os.path.isfile(from_dir): # 如果为文件,则直接复制文件
  107. if ignore:
  108. regxp = '|'.join(ignore).replace('\\','/') # 组装正则
  109. to_dir_str = str(to_dir).replace('\\','/')
  110. if not re.search(rf'{regxp}', to_dir_str, re.M):
  111. shutil.copy(from_dir, to_dir) # 复制文件
  112. else:
  113. shutil.copy(from_dir, to_dir) # 复制文件
  114. def force_copy_files(from_path, to_path, exclude_files=None):
  115. # print(f'开始拷贝文件{from_path}=>{to_path}')
  116. if exclude_files is None:
  117. exclude_files = []
  118. logger.info(f'开始拷贝文件{from_path}=>{to_path}')
  119. if not os.path.exists(to_path):
  120. os.makedirs(to_path,exist_ok=True)
  121. try:
  122. if sys.version_info < (3, 8):
  123. copytree(from_path, to_path,exclude_files)
  124. else:
  125. if len(exclude_files) > 0:
  126. shutil.copytree(from_path, to_path, dirs_exist_ok=True,ignore=shutil.ignore_patterns(*exclude_files))
  127. else:
  128. shutil.copytree(from_path, to_path, dirs_exist_ok=True)
  129. except Exception as e:
  130. logger.info(f'拷贝文件{from_path}=>{to_path}发生错误:{e}')
  131. def copy_to_update():
  132. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  133. tmp_path = os.path.join(base_path, f'tmp')
  134. dr_path = os.path.join(tmp_path, f'dr_py-master')
  135. if not os.path.exists(dr_path):
  136. # print(f'升级失败,找不到目录{dr_path}')
  137. logger.info(f'升级失败,找不到目录{dr_path}')
  138. return False
  139. # 千万不能覆盖super,base
  140. paths = ['js','models','controllers','libs','static','templates','utils','txt','jiexi','py','whl','doc']
  141. exclude_files = ['txt/pycms0.json','txt/pycms1.json','txt/pycms2.json','base/rules.db']
  142. for path in paths:
  143. force_copy_files(os.path.join(dr_path, path),os.path.join(base_path, path),exclude_files)
  144. try:
  145. shutil.copy(os.path.join(dr_path, 'app.py'), os.path.join(base_path, 'app.py')) # 复制文件
  146. except Exception as e:
  147. logger.info(f'更新app.py发生错误:{e}')
  148. logger.info(f'升级程序执行完毕,全部文件已拷贝覆盖')
  149. return True
  150. def download_new_version():
  151. t1 = getTime()
  152. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  153. tmp_path = os.path.join(base_path, f'tmp')
  154. os.makedirs(tmp_path,exist_ok=True)
  155. url = 'https://gitcode.net/qq_32394351/dr_py/-/archive/master/dr_py-master.zip'
  156. # tmp_files = os.listdir(tmp_path)
  157. # for tp in tmp_files:
  158. # print(f'清除缓存文件:{tp}')
  159. # os.remove(os.path.join(tmp_path, tp))
  160. del_file(tmp_path)
  161. msg = ''
  162. try:
  163. # print(f'开始下载:{url}')
  164. logger.info(f'开始下载:{url}')
  165. r = requests.get(url,headers=headers,timeout=(20,20))
  166. rb = r.content
  167. download_path = os.path.join(tmp_path, 'dr_py.zip')
  168. with open(download_path,mode='wb+') as f:
  169. f.write(rb)
  170. # print(f'开始解压文件:{download_path}')
  171. logger.info(f'开始解压文件:{download_path}')
  172. f = zipfile.ZipFile(download_path, 'r') # 压缩文件位置
  173. for file in f.namelist():
  174. f.extract(file, tmp_path) # 解压位置
  175. f.close()
  176. # print('解压完毕,开始升级')
  177. logger.info('解压完毕,开始升级')
  178. ret = copy_to_update()
  179. logger.info(f'升级完毕,结果为:{ret}')
  180. # print(f'升级完毕,结果为:{ret}')
  181. msg = '升级成功'
  182. except Exception as e:
  183. msg = f'升级失败:{e}'
  184. logger.info(f'系统升级共计耗时:{get_interval(t1)}毫秒')
  185. return msg
  186. def download_lives(live_url:str):
  187. t1 = getTime()
  188. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  189. live_path = os.path.join(base_path, f'base/直播.txt')
  190. logger.info(f'尝试同步{live_url}远程内容到{live_path}')
  191. try:
  192. r = requests.get(live_url,headers=headers,timeout=3)
  193. auto_encoding = r.apparent_encoding
  194. if auto_encoding.lower() in ['utf-8','gbk','bg2312','gb18030']:
  195. r.encoding = auto_encoding
  196. # print(r.encoding)
  197. html = r.text
  198. # print(len(html))
  199. if re.search('cctv|.m3u8',html,re.M|re.I) and len(html) > 1000:
  200. logger.info(f'直播源同步成功,耗时{get_interval(t1)}毫秒')
  201. with open(live_path,mode='w+',encoding='utf-8') as f:
  202. f.write(html)
  203. return True
  204. else:
  205. logger.info(f'直播源同步失败,远程文件看起来不是直播源。耗时{get_interval(t1)}毫秒')
  206. return False
  207. except Exception as e:
  208. logger.info(f'直播源同步失败,耗时{get_interval(t1)}毫秒\n{e}')
  209. return False