rules.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : rules.py.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Date : 2022/8/25
  6. import json
  7. import os
  8. from time import time
  9. import js2py
  10. from utils.log import logger
  11. # from utils.web import get_interval,UA
  12. from utils.ua import UA,get_interval
  13. from flask import render_template_string
  14. def getRuleLists():
  15. base_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在目录
  16. # print(base_path)
  17. file_name = os.listdir(base_path)
  18. file_name = list(filter(lambda x:str(x).endswith('.js') and str(x).find('模板') < 0,file_name))
  19. # print(file_name)
  20. rule_list = [file.replace('.js','') for file in file_name]
  21. # print(rule_list)
  22. return rule_list
  23. def getCacheCount():
  24. base_path = 'cache/' # 当前缓存js所在目录
  25. os.makedirs(base_path, exist_ok=True)
  26. file_name = os.listdir(base_path)
  27. file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
  28. return len(file_name)
  29. def getRules(path='cache',js_mode=0):
  30. t1 = time()
  31. base_path = path+'/' # 当前文件所在目录
  32. # print(base_path)
  33. os.makedirs(base_path,exist_ok=True)
  34. file_name = os.listdir(base_path)
  35. file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
  36. # print(file_name)
  37. rule_list = [file.replace('.js', '') for file in file_name]
  38. js_path = [f'{path}/{rule}.js' for rule in rule_list]
  39. with open('js/模板.js', encoding='utf-8') as f:
  40. before = f.read().split('export')[0]
  41. rule_codes = []
  42. # for js in js_path:
  43. # with open(js,encoding='utf-8') as f:
  44. # code = f.read()
  45. # rule_codes.append(js2py.eval_js(before+code))
  46. ctx = js2py.EvalJs()
  47. codes = []
  48. for i in range(len(js_path)):
  49. js = js_path[i]
  50. with open(js,encoding='utf-8') as f:
  51. code = f.read()
  52. new_code = 'var muban = JSON.parse(JSON.stringify(mubanDict));\n'+code.replace('rule',f'rule{i}',1)
  53. # new_code = ''+code.replace('rule',f'rule{i}',1)
  54. codes.append(new_code)
  55. newCodes = before + '\n'+ '\n'.join(codes)
  56. # print(newCodes)
  57. try:
  58. ctx.execute(newCodes)
  59. for i in range(len(js_path)):
  60. rule_codes.append(ctx.eval(f'rule{i}'))
  61. # print(rule_codes)
  62. # print(type(rule_codes[0]),rule_codes[0])
  63. # print(rule_codes[0].title)
  64. # print(rule_codes[0].searchable)
  65. # print(rule_codes[0].quickSearch)
  66. new_rule_list = []
  67. for i in range(len(rule_list)):
  68. if js_mode == 1 and rule_list[i] == 'drpy':
  69. continue
  70. sable = rule_codes[i].searchable or 0
  71. tmpObj = {
  72. 'name':rule_list[i],
  73. # 'searchable':1 if (js_mode==1 and sable==2) else sable, # 对js模式1开放软件聚搜(还是算了,服务器遭不住)
  74. 'searchable':sable,
  75. 'quickSearch':rule_codes[i].quickSearch or 0,
  76. 'filterable':rule_codes[i].filterable or 0,
  77. }
  78. if rule_codes[i].multi:
  79. tmpObj['multi'] = 1
  80. new_rule_list.append(tmpObj)
  81. # print(new_rule_list)
  82. rules = {'list': new_rule_list, 'count': len(rule_list)}
  83. except Exception as e:
  84. logger.info(f'装载js内置源列表失败,置空内置源')
  85. rules = []
  86. logger.info(f'自动配置装载耗时:{get_interval(t1)}毫秒')
  87. return rules
  88. def jxTxt2Json(text:str,host:str):
  89. try:
  90. data = render_template_string(text,host=host).strip().split('\n')
  91. except Exception as e:
  92. logger.info(f'jxTxt2Json发生错误:{e}')
  93. data = []
  94. jxs = []
  95. for i in data:
  96. i = i.strip()
  97. dt = i.split(',')
  98. if not i.startswith('#') and len(i) > 10:
  99. try:
  100. jxs.append({
  101. 'name':dt[0],
  102. 'url':dt[1],
  103. 'type':dt[2] if len(dt) > 2 and dt[2] else 0,
  104. 'ua':dt[3] if len(dt) > 3 and dt[3] else UA,
  105. })
  106. except Exception as e:
  107. logger.info(f'解析行有错误:{e}')
  108. return jxs
  109. def getJxs(path='js',host=None):
  110. custom_jx = 'base/解析.conf'
  111. if not os.path.exists(custom_jx):
  112. with open(custom_jx,'w+',encoding='utf-8') as f1:
  113. msg = """# 这是用户自定义解析列表,不会被系统升级覆盖
  114. # 0123,对应,普通解析,json解析,并发多json解析,聚合解析,参数3不填默认0
  115. # flags是线路名称标识,会自动拦截并走以下的解析
  116. # 名称,链接,类型,ua (ua不填默认 Mozilla/5.0) 可以手动填 Dart/2.14 (dart:io)
  117. 虾米,https://dm.xmflv.com:4433/?url=
  118. """
  119. f1.write(msg)
  120. base_path = 'jiexi' # 自建解析目录
  121. os.makedirs(base_path, exist_ok=True)
  122. file_name = os.listdir(base_path)
  123. file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
  124. # print(file_name)
  125. jx_list = [file.replace('.js', '') for file in file_name]
  126. # print(file_name)
  127. # print(jx_list)
  128. jx_str = '\n'.join([jx+',{{host}}'+f'/parse/api/{jx}.js?url=,1' for jx in jx_list])
  129. # print(jx_str)
  130. with open(f'{path}/解析.conf',encoding='utf-8') as f:
  131. text = f.read()
  132. text = jx_str + '\n' + text
  133. jxs = jxTxt2Json(text,host)
  134. with open(custom_jx,encoding='utf-8') as f2:
  135. text = f2.read()
  136. jxs2 = jxTxt2Json(text,host)
  137. jxs.extend(jxs2)
  138. print(f'共计{len(jxs)}条解析')
  139. return jxs
  140. def getPys(path='txt/py'):
  141. t1 = time()
  142. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  143. py_path = os.path.join(base_path, path)
  144. os.makedirs(py_path, exist_ok=True)
  145. file_name = os.listdir(py_path)
  146. file_name = list(filter(lambda x: str(x).endswith('.py'), file_name))
  147. # print(file_name)
  148. rule_list = [file.replace('.py', '') for file in file_name]
  149. py_path = [f'{path}/{rule}.py' for rule in rule_list]
  150. new_rule_list = []
  151. for i in range(len(rule_list)):
  152. new_rule_list.append({
  153. 'name': rule_list[i],
  154. 'searchable': 1,
  155. 'quickSearch': 1,
  156. 'filterable': 0,
  157. })
  158. logger.info(f'自动加载Pyramid耗时:{get_interval(t1)}毫秒')
  159. return new_rule_list
  160. def gen_cache(path='txt/js/tg'):
  161. t1 = time()
  162. base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
  163. py_path = os.path.join(base_path, path)
  164. os.makedirs(py_path, exist_ok=True)
  165. file_name = os.listdir(py_path)
  166. file_name = list(filter(lambda x: str(x).endswith('.js'), file_name))
  167. # print(file_name)
  168. rule_list = [file.replace('.js', '') for file in file_name]
  169. js_path = [f'{path}/{rule}.js' for rule in rule_list]
  170. new_rule_list = []
  171. for i in range(len(rule_list)):
  172. # print(js_path[i])
  173. rname = rule_list[i]
  174. new_rule_list.append(
  175. {
  176. "key": f"dr_{rname}",
  177. "name": f"{rname}(道长)",
  178. "type": 1,
  179. # "api": "{{host}}"+f"/vod?rule={rname}&ext="+"{{host}}/"+js_path[i],
  180. "api": "{{host}}"+f"/vod?rule={rname}&ext="+js_path[i],
  181. "searchable": 2,
  182. "quickSearch": 0,
  183. "filterable": 0
  184. })
  185. logger.info(f'自动加载{len(new_rule_list)}个缓存JS耗时:{get_interval(t1)}毫秒')
  186. new_rules_texts = [json.dumps(new_rule,ensure_ascii=False) for new_rule in new_rule_list]
  187. # new_rules_text = json.dumps(new_rule_list,ensure_ascii=False)
  188. new_rules_text = ',\n'.join(new_rules_texts)+','
  189. return new_rules_text
  190. if __name__ == '__main__':
  191. print(getRuleLists())
  192. # print(gen_cache())
  193. # print(gen_cache('txt/js/18'))
  194. custom_file = gen_cache() + '\n'+gen_cache('txt/js/18')
  195. print(custom_file)
  196. with open('custom.conf','w+',encoding='utf-8') as f:
  197. f.write(custom_file)