admin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : admin.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Date : 2022/9/6
  6. import os
  7. import ujson
  8. from flask import Blueprint,request,render_template,render_template_string,jsonify,make_response,redirect
  9. from controllers.service import storage_service,rules_service,parse_service
  10. from base.R import R
  11. from base.database import db
  12. from utils.log import logger
  13. import shutil
  14. from utils.update import getLocalVer,getOnlineVer,download_new_version,download_lives,copy_to_update
  15. from utils import parser
  16. from utils.env import get_env,update_env
  17. from utils.web import getParmas,verfy_token
  18. from js.rules import getRules,getCacheCount
  19. from utils.parser import runJScode
  20. from werkzeug.utils import secure_filename
  21. from utils.web import md5
  22. admin = Blueprint("admin", __name__)
  23. # @admin.route("/",methods=['get'])
  24. # def index():
  25. # return R.ok(msg='欢迎进入首页',data=None)
  26. # @admin.route("/info",methods=['get'])
  27. # def info_all():
  28. # data = storage_service.query_all()
  29. # return R.ok(data=data)
  30. @admin.route('/')
  31. def admin_index(): # 管理员界面
  32. if not verfy_token():
  33. return render_template('login.html')
  34. lsg = storage_service()
  35. live_url = lsg.getItem('LIVE_URL')
  36. use_py = lsg.getItem('USE_PY')
  37. js0_password = lsg.getItem('JS0_PASSWORD')
  38. # print(f'live_url:', live_url)
  39. rules = getRules('js')
  40. # print(rules)
  41. cache_count = getCacheCount()
  42. # print(cache_count)
  43. return render_template('admin.html',js0_password=js0_password, pystate=use_py,rules=rules,cache_count=cache_count, ver=getLocalVer(), live_url=live_url)
  44. @admin.route('/settings')
  45. def admin_settings(): # 管理员界面
  46. if not verfy_token():
  47. return render_template('login.html')
  48. lsg = storage_service()
  49. # conf_list = 'LIVE_URL|USE_PY|PLAY_URL|PLAY_DISABLE|LAZYPARSE_MODE|WALL_PAPER_ENABLE|WALL_PAPER|UNAME|PWD|LIVE_MODE|LIVE_URL|CATE_EXCLUDE|TAB_EXCLUDE'.split('|')
  50. conf_lists = lsg.getStoreConf()
  51. # print(conf_lists)
  52. return render_template('settings.html', conf_lists=conf_lists,ver=getLocalVer())
  53. @admin.route('/save_conf',methods=['POST'])
  54. def admin_save_conf(): # 管理员界面
  55. if not verfy_token():
  56. # return render_template('login.html')
  57. return R.error('请登录后再试')
  58. key = getParmas('key')
  59. value = getParmas('value')
  60. print(f'key:{key},value:{value}')
  61. lsg = storage_service()
  62. res_id = lsg.setItem(key,value)
  63. return R.success(f'修改成功,记录ID为:{res_id}')
  64. @admin.route('/update_env',methods=['POST'])
  65. def admin_update_env(): # 更新环境变量中的某个值
  66. if not verfy_token():
  67. # return render_template('login.html')
  68. return R.error('请登录后再试')
  69. key = getParmas('key')
  70. value = getParmas('value')
  71. print(f'key:{key},value:{value}')
  72. ENV = update_env(key,value)
  73. return R.success(f'修改成功,最新的完整ENV见data',data=ENV)
  74. @admin.route("/view/<name>",methods=['GET'])
  75. def admin_view_rule(name):
  76. if not name or not name.split('.')[-1] in ['js','txt','py','json']:
  77. return R.error(f'非法猥亵,未指定文件名。必须包含js|txt|json|py')
  78. try:
  79. env = get_env()
  80. # print(env)
  81. if env.get('js_proxy'):
  82. js_proxy = env['js_proxy']
  83. burl = request.base_url
  84. if '=>' in js_proxy:
  85. oldsrc = js_proxy.split('=>')[0]
  86. if oldsrc in burl:
  87. newsrc = js_proxy.split('=>')[1]
  88. # print(f'js1源代理已启用,全局替换{oldsrc}为{newsrc}')
  89. rurl = burl.replace(oldsrc, newsrc)
  90. if burl != rurl:
  91. jscode = parser.getJs(name, 'js')
  92. # rjscode = render_template_string(jscode, env=env)
  93. rjscode = jscode
  94. for k in env:
  95. # print(f'${k}', f'{env[k]}')
  96. if f'${k}' in rjscode:
  97. rjscode = rjscode.replace(f'${k}', f'{env[k]}')
  98. # rjscode = render_template_string(jscode, **env)
  99. if rjscode.strip() == jscode.strip(): # 无需渲染才代理
  100. return redirect(rurl)
  101. else:
  102. logger.info(f'{name}由于存在环境变量无法被依赖代理')
  103. return parser.toJs(name,'js',env)
  104. except Exception as e:
  105. return R.error(f'非法猥亵\n{e}')
  106. @admin.route('/clear/<name>')
  107. def admin_clear_rule(name):
  108. if not name or not name.split('.')[-1] in ['js','txt','py','json']:
  109. return R.error(f'非法猥亵,未指定文件名。必须包含js|txt|json|py')
  110. if not verfy_token():
  111. return render_template('login.html')
  112. file_path = os.path.abspath(f'js/{name}')
  113. print(file_path)
  114. if not os.path.exists(file_path):
  115. return R.error('服务端没有此文件!'+file_path)
  116. os.remove(file_path)
  117. return R.ok('成功删除文件:'+file_path)
  118. @admin.route('/get_ver')
  119. def admin_get_ver():
  120. if not verfy_token():
  121. # return render_template('login.html')
  122. return R.error('请登录后再试')
  123. online_ver,msg = getOnlineVer()
  124. return jsonify({'local_ver':getLocalVer(),'online_ver':online_ver,'msg':msg})
  125. @admin.route('/update_db')
  126. def admin_update_db():
  127. if not verfy_token():
  128. # return render_template('login.html')
  129. return R.error('请登录后再试')
  130. old_dbfile = 'migrations'
  131. if os.path.exists(old_dbfile):
  132. logger.info(f'开始删除历史数据库迁移文件:{old_dbfile}')
  133. shutil.rmtree(old_dbfile)
  134. db.session.execute('drop table if exists alembic_version')
  135. cmd = 'flask db migrate && flask db upgrade'
  136. if not os.path.exists('migrations'):
  137. cmd = 'flask db init && '+cmd
  138. logger.info(f'开始执行cmd:{cmd}')
  139. result = os.system(cmd)
  140. logger.info(f'cmd执行结果:{result}')
  141. return R.success('数据库升级完毕')
  142. @admin.route('/update_ver')
  143. def admin_update_ver():
  144. if not verfy_token():
  145. return R.failed('请登录后再试')
  146. msg = download_new_version()
  147. return R.success(msg)
  148. @admin.route('/rule_state/<int:state>',methods=['POST'])
  149. def admin_rule_state(state=0): # 管理员修改规则状态
  150. if not verfy_token():
  151. return R.error('请登录后再试')
  152. names = getParmas('names')
  153. if not names:
  154. return R.success(f'修改失败,没有传递names参数')
  155. rule_list = names.split(',')
  156. rules = rules_service()
  157. # print(rules.query_all())
  158. # print(rules.getState(rule_list[0]))
  159. # print(rule_list)
  160. success_list = []
  161. for rule in rule_list:
  162. try:
  163. res_id = rules.setState(rule,state)
  164. success_list.append(f'{rule}:{res_id}')
  165. except:
  166. success_list.append(rule)
  167. return R.success(f'修改成功,服务器反馈信息为:{success_list}')
  168. @admin.route('/rule_order/<int:order>',methods=['POST'])
  169. def admin_rule_order(order=0): # 管理员修改规则顺序
  170. if not verfy_token():
  171. return R.error('请登录后再试')
  172. names = getParmas('names')
  173. if not names:
  174. return R.success(f'修改失败,没有传递names参数')
  175. rule_list = names.split(',')
  176. rules = rules_service()
  177. # print(rules.query_all())
  178. # print(rules.getState(rule_list[0]))
  179. # print(rule_list)
  180. success_list = []
  181. rule_list.reverse() # 倒序解决时间多重排序问题
  182. for rule in rule_list:
  183. try:
  184. res_id = rules.setOrder(rule,order)
  185. success_list.append(f'{rule}:{res_id}')
  186. except:
  187. success_list.append(rule)
  188. return R.success(f'修改成功,服务器反馈信息为:{success_list}')
  189. @admin.route('/parse/save_data',methods=['POST'])
  190. def admin_parse_save_data(): # 管理员保存拖拽排序后的解析数据
  191. if not verfy_token():
  192. return R.error('请登录后再试')
  193. data = getParmas('data')
  194. if not data:
  195. return R.success(f'修改失败,没有传递data参数')
  196. parse = parse_service()
  197. success_list = []
  198. data = ujson.loads(data)
  199. new_list = []
  200. new_data = []
  201. for nd in data:
  202. if not nd.get('url') and nd.get('name') != '🌐Ⓤ':
  203. continue
  204. if nd['url'] not in new_list:
  205. new_data.append(nd)
  206. new_list.append(nd['url'])
  207. print(f'去重前:{len(data)},去重后:{len(new_data)}')
  208. for i in range(len(new_data)):
  209. d = new_data[i]
  210. # if not d.get('url') and d.get('name') != '🌐Ⓤ':
  211. # continue
  212. obj = {
  213. 'name':d.get('name', ''),
  214. 'url':d.get('url', ''),
  215. 'state':d.get('state',1),
  216. 'type': d.get('state',0),
  217. 'order':i+1,
  218. 'ext':d.get('ext',''),
  219. 'header':d.get('header',''),
  220. }
  221. # print(obj)
  222. try:
  223. parse.saveData(obj)
  224. success_list.append(f'parse:{d["url"]}')
  225. # print(obj)
  226. # print(200,obj)
  227. except Exception as e:
  228. success_list.append(d["url"])
  229. print(f'{d["url"]}失败:{e}')
  230. # print(len(success_list))
  231. return R.success(f'修改成功,服务器反馈信息为:{success_list}')
  232. @admin.route('/force_update')
  233. def admin_force_update():
  234. if not verfy_token():
  235. return R.failed('请登录后再试')
  236. ret = copy_to_update()
  237. if ret:
  238. msg = '升级成功'
  239. return R.success(msg)
  240. else:
  241. msg = '升级失败。具体原因只能去看实时日志(通过9001端口)'
  242. return R.failed(msg)
  243. @admin.route('/update_lives')
  244. def admin_update_lives():
  245. url = getParmas('url')
  246. if not url:
  247. return R.failed('未提供被同步的直播源远程地址!')
  248. if not verfy_token():
  249. return R.failed('请登录后再试')
  250. live_url = url
  251. success = download_lives(live_url)
  252. if success:
  253. return R.success(f'直播源{live_url}同步成功')
  254. else:
  255. return R.failed(f'直播源{live_url}同步失败')
  256. @admin.route('/write_live_url')
  257. def admin_write_live_url():
  258. url = getParmas('url')
  259. if not url:
  260. return R.failed('未提供修改后的直播源地址!')
  261. if not verfy_token():
  262. return R.failed('请登录后再试')
  263. lsg = storage_service()
  264. id = lsg.setItem('LIVE_URL',url)
  265. msg = f'已修改的配置记录id为:{id}'
  266. return R.success(msg)
  267. @admin.route('/change_use_py')
  268. def admin_change_use_py():
  269. if not verfy_token():
  270. return R.failed('请登录后再试')
  271. lsg = storage_service()
  272. use_py = lsg.getItem('USE_PY')
  273. new_use_py = '' if use_py else '1'
  274. state = '开启' if new_use_py else '关闭'
  275. id = lsg.setItem('USE_PY', new_use_py)
  276. msg = f'已修改的配置记录id为:{id},结果为{state}'
  277. return R.success(msg)
  278. # @admin.route('/get_use_py')
  279. # def admin_get_use_py():
  280. # if not verfy_token():
  281. # return R.failed('请登录后再试')
  282. # lsg = storage_service()
  283. # use_py = lsg.getItem('USE_PY')
  284. # state = 1 if use_py else 0
  285. # return R.success(state)
  286. @admin.route('/upload', methods=['GET', 'POST'])
  287. def upload_file():
  288. if not verfy_token():
  289. return render_template('login.html')
  290. if request.method == 'POST':
  291. try:
  292. file = request.files['file']
  293. filename = secure_filename(file.filename)
  294. print(f'推荐安全文件命名:{filename}')
  295. savePath = f'js/{file.filename}'
  296. if os.path.exists(savePath):
  297. return R.failed(f'上传失败,文件已存在,请先查看删除再试')
  298. with open('js/模板.js', encoding='utf-8') as f2:
  299. before = f2.read().split('export')[0]
  300. upcode = file.stream.read().decode('utf-8')
  301. check_to_run = before + upcode
  302. # print(check_to_run)
  303. try:
  304. loader, _ = runJScode(check_to_run)
  305. rule = loader.eval('rule')
  306. if not rule:
  307. return R.failed('文件上传失败,检测到上传的文件不是drpy框架支持的源代码')
  308. except:
  309. return R.failed('文件上传失败,检测到上传的文件不是drpy框架支持的源代码')
  310. print(savePath)
  311. file.seek(0) # 读取后变成空文件,重新赋能
  312. file.save(savePath)
  313. return R.success('文件上传成功')
  314. except Exception as e:
  315. return R.failed(f'文件上传失败!{e}')
  316. else:
  317. # return render_template('upload.html')
  318. return R.failed('文件上传失败')
  319. @admin.route('/login',methods=['GET','POST'])
  320. def login_api():
  321. username = getParmas('username')
  322. password = getParmas('password')
  323. autologin = getParmas('autologin')
  324. if not all([username,password]):
  325. return R.failed('账号密码字段必填')
  326. token = md5(f'{username};{password}')
  327. check = verfy_token(token=token)
  328. if check:
  329. # response = make_response(redirect('/admin'))
  330. response = make_response(R.success('登录成功'))
  331. response.set_cookie('token', token)
  332. return response
  333. else:
  334. return R.failed('登录失败,用户名或密码错误')
  335. @admin.route('/logtail')
  336. def admin_logtail():
  337. if not verfy_token():
  338. return R.failed('请登录后再试')
  339. return render_template('logtail.html')
  340. @admin.route('/lives')
  341. def admin_lives():
  342. if not verfy_token():
  343. return R.failed('请登录后再试')
  344. # print(dir(request))
  345. # 完整地址: request.base_url url
  346. # 带http的前缀 host_url root_url
  347. # 不带http的前缀 host
  348. # 当前路径 path
  349. host_url = request.host_url
  350. def get_lives():
  351. base_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在目录
  352. # print(base_path)
  353. live_path = os.path.join(base_path, '../txt/lives')
  354. # print(live_path)
  355. files = os.listdir(live_path)
  356. # print(files)
  357. # files = list(filter(lambda x: str(x).endswith('.txt') and str(x).find('模板') < 0, files))
  358. files = list(filter(lambda x: str(x).split('.')[-1] in ['txt','json','m3u'] and str(x).find('模板') < 0, files))
  359. files = [f'{host_url}lives?path=txt/lives/{file}' for file in files]
  360. return files
  361. files = '\n'.join(get_lives())
  362. response = make_response(files)
  363. response.headers['Content-Type'] = 'text/plain; charset=utf-8'
  364. return response