app.py 22.9 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : app.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/25
H
hjdhnx 已提交
6
import random
7
from utils.encode import base64Encode
8
import js2py
H
hjdhnx 已提交
9
from flask_sqlalchemy import SQLAlchemy
10
from flask_migrate import Migrate
H
hjdhnx 已提交
11
import config
H
hjdhnx 已提交
12 13
import warnings
warnings.filterwarnings('ignore')
H
hjdhnx 已提交
14 15

import os
H
hjdhnx 已提交
16
from flask import Flask, jsonify, abort,request,redirect,make_response,render_template,send_from_directory,url_for
H
hjdhnx 已提交
17
from werkzeug.utils import secure_filename
18
from js.rules import getRuleLists
H
hjdhnx 已提交
19
from utils import error,parser
H
hjdhnx 已提交
20
from utils.web import *
H
hjdhnx 已提交
21
from utils.update import checkUpdate,getOnlineVer,getLocalVer,download_new_version,download_lives
H
hjdhnx 已提交
22 23
import sys
import codecs
H
hjdhnx 已提交
24
from classes.cms import CMS,logger
H
hjdhnx 已提交
25
from models import *
H
hjdhnx 已提交
26
import json
H
hjdhnx 已提交
27
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
H
hjdhnx 已提交
28 29 30 31 32 33 34 35 36 37 38

def create_flask_app(config):
    app = Flask(__name__, static_folder='static', static_url_path='/static')
    # app.config["JSON_AS_ASCII"] = False # jsonify返回的中文正常显示
    app.config.from_object(config)  # 单独的配置文件里写了,这里就不用弄json中文显示了
    # new_conf = get_conf(settings)
    # print(new_conf)
    print('自定义播放解析地址:', app.config.get('PLAY_URL'))
    print('当前操作系统', sys.platform)
    app.logger.name = "drLogger"
    rule_list = getRuleLists()
H
hjdhnx 已提交
39
    wlan_info,_ = get_wlan_info()
H
hjdhnx 已提交
40
    logger.info(rule_list)
H
hjdhnx 已提交
41
    logger.info(f'局域网: {getHost(1, 5705)}/index\n本地: {getHost(0, 5705)}/index\nwlan_info:{wlan_info}')
H
hjdhnx 已提交
42 43 44 45
    return app

app = create_flask_app(config)

H
hjdhnx 已提交
46
db = SQLAlchemy(app)
47
migrate = Migrate(app, db)
H
hjdhnx 已提交
48

H
hjdhnx 已提交
49 50 51
now_python_ver = ".".join([str(i) for i in sys.version_info[:3]])
if sys.version_info < (3,9):
    from gevent.pywsgi import WSGIServer
H
hjdhnx 已提交
52 53
    # from gevent import monkey
    # monkey.patch_socket() # 开启socket异步
H
hjdhnx 已提交
54 55 56 57
    print(f'当前python版本{now_python_ver}为3.9.0及以下,支持gevent')
else:
    print(f'当前python版本{now_python_ver}为3.9.0及以上,不支持gevent')

H
hjdhnx 已提交
58
# from geventwebsocket.handler import WebSocketHandler
H
hjdhnx 已提交
59
RuleClass = rule_classes.init(db)
H
hjdhnx 已提交
60
PlayParse = play_parse.init(db)
H
hjdhnx 已提交
61
lsg = storage.init(db)
H
hjdhnx 已提交
62 63 64 65 66 67 68

def initConfToDb():
    if not lsg.getItem('LIVE_URL'):
        lsg.setItem('LIVE_URL', app.config.get('LIVE_URL'))

initConfToDb()

69 70 71
def is_linux():
    return not 'win' in sys.platform

72
def getParmas(key=None,value=''):
H
hjdhnx 已提交
73 74 75 76 77
    """
    获取链接参数
    :param key:
    :return:
    """
H
hjdhnx 已提交
78
    content_type = request.headers.get('Content-Type')
H
hjdhnx 已提交
79 80
    args = {}
    if request.method == 'POST':
H
hjdhnx 已提交
81 82 83 84 85 86 87 88
        if 'application/x-www-form-urlencoded' in content_type or 'multipart/form-data' in content_type:
            args = request.form
        elif 'application/json' in content_type:
            args = request.json
        elif 'text/plain' in content_type:
            args = request.data
        else:
            args = request.args
H
hjdhnx 已提交
89 90 91
    elif request.method == 'GET':
        args = request.args
    if key:
92
        return args.get(key,value)
H
hjdhnx 已提交
93 94 95
    else:
        return args

H
hjdhnx 已提交
96 97 98 99 100 101
@app.route('/')
def forbidden():  # put application's code here
    abort(403)

@app.route('/index')
def index():  # put application's code here
H
hjdhnx 已提交
102
    # logger.info("进入了首页")
H
hjdhnx 已提交
103 104 105 106 107 108 109 110
    sup_port = app.config.get('SUP_PORT', False)
    manager0 = ':'.join(getHost(0).split(':')[0:2])
    manager1 = ':'.join(getHost(1).split(':')[0:2])
    manager2 = ':'.join(getHost(2).split(':')[0:2]).replace('https','http')
    if sup_port:
        manager0 += f':{sup_port}'
        manager1 += f':{sup_port}'
        manager2 += f':{sup_port}'
H
1  
hjdhnx 已提交
111
    # print(manager1)
112 113
    # print(manager2)
    return render_template('index.html',getHost=getHost,manager0=manager0,manager1=manager1,manager2=manager2,is_linux=is_linux())
H
hjdhnx 已提交
114

H
hjdhnx 已提交
115 116 117 118 119 120 121 122 123 124 125
@app.route('/admin')
def admin_home():  # 管理员界面
    # headers  = request.headers
    # print(headers)
    cookies = request.cookies
    # print(cookies)
    token = cookies.get('token','')
    # print(f'mytoken:{token}')
    if not verfy_token(token):
        return render_template('login.html')
    # return jsonify(error.success('登录成功'))
H
hjdhnx 已提交
126 127
    live_url = lsg.getItem('LIVE_URL')
    return render_template('admin.html',rules=getRules('js'),ver=getLocalVer(),live_url=live_url)
H
hjdhnx 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

@app.route('/api/login',methods=['GET','POST'])
def login_api():
    username = getParmas('username')
    password = getParmas('password')
    autologin = getParmas('autologin')
    if not all([username,password]):
        return jsonify(error.failed('账号密码字段必填'))
    token = md5(f'{username};{password}')
    check = verfy_token(token)
    if check:
        # response = make_response(redirect('/admin'))
        response = make_response(jsonify(error.success('登录成功')))
        response.set_cookie('token', token)
        return response
    else:
        return jsonify(error.failed('登录失败,用户名或密码错误'))

H
hjdhnx 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158
@app.route("/admin/view/<name>",methods=['GET'])
def admin_view_rule(name):
    if not name or not name.split('.')[-1] in ['js','txt','py','json']:
        return jsonify(error.failed(f'非法猥亵,未指定文件名。必须包含js|txt|json|py'))
    try:
        return parser.toJs(name,'js')
    except Exception as e:
        return jsonify(error.failed(f'非法猥亵\n{e}'))

@app.route('/admin/clear/<name>')
def admin_clear_rule(name):
    if not name or not name.split('.')[-1] in ['js','txt','py','json']:
        return jsonify(error.failed(f'非法猥亵,未指定文件名。必须包含js|txt|json|py'))
H
hjdhnx 已提交
159 160 161 162 163 164
    cookies = request.cookies
    # print(cookies)
    token = cookies.get('token', '')
    # print(f'mytoken:{token}')
    if not verfy_token(token):
        return render_template('login.html')
H
hjdhnx 已提交
165 166 167 168 169 170 171

    file_path = os.path.abspath(f'js/{name}')
    if not os.path.exists(file_path):
        return jsonify(error.failed('服务端没有此文件!'+file_path))
    os.remove(file_path)
    return jsonify(error.success('成功删除文件:'+file_path))

H
hjdhnx 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
@app.route('/admin/get_ver')
def admin_get_ver():
    cookies = request.cookies
    # print(cookies)
    token = cookies.get('token', '')
    # print(f'mytoken:{token}')
    if not verfy_token(token):
        # return render_template('login.html')
        return jsonify(error.failed('请登录后再试'))

    return jsonify({'local_ver':getLocalVer(),'online_ver':getOnlineVer()})

@app.route('/admin/update_ver')
def admin_update_ver():
    cookies = request.cookies
    # print(cookies)
    token = cookies.get('token', '')
    # print(f'mytoken:{token}')
    if not verfy_token(token):
        # return render_template('login.html')
        return jsonify(error.failed('请登录后再试'))
    msg = download_new_version()
    return jsonify(error.success(msg))

H
hjdhnx 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
@app.route('/admin/update_lives')
def admin_update_lives():
    url = getParmas('url')
    if not url:
        return jsonify(error.failed('未提供被同步的直播源远程地址!'))
    cookies = request.cookies
    token = cookies.get('token', '')
    if not verfy_token(token):
        return jsonify(error.failed('请登录后再试'))
    live_url = url
    success = download_lives(live_url)
    if success:
        return jsonify(error.success(f'直播源{live_url}同步成功'))
    else:
        return jsonify(error.failed(f'直播源{live_url}同步失败'))

@app.route('/admin/write_live_url')
def admin_write_live_url():
    url = getParmas('url')
    if not url:
        return jsonify(error.failed('未提供修改后的直播源地址!'))
    cookies = request.cookies
    token = cookies.get('token', '')
    if not verfy_token(token):
        return jsonify(error.failed('请登录后再试'))
    id = lsg.setItem('LIVE_URL',url)
    msg = f'已修改的配置记录id为:{id}'
    return jsonify(error.success(msg))


H
hjdhnx 已提交
226 227 228 229 230 231 232 233 234
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    cookies = request.cookies
    # print(cookies)
    token = cookies.get('token', '')
    # print(f'mytoken:{token}')
    if not verfy_token(token):
        return render_template('login.html')
    if request.method == 'POST':
H
hjdhnx 已提交
235
        try:
236
            file = request.files['file']
H
hjdhnx 已提交
237
            # print(f.size)
238
            # print(f)
H
hjdhnx 已提交
239
            # print(request.files)
240
            filename = secure_filename(file.filename)
241 242
            print(f'推荐安全文件命名:{filename}')
            # savePath = f'js/{filename}'
243
            savePath = f'js/{file.filename}'
244
            # print(savePath)
H
hjdhnx 已提交
245 246
            if os.path.exists(savePath):
                return jsonify(error.failed(f'上传失败,文件已存在,请先查看删除再试'))
247 248
            with open('js/模板.js', encoding='utf-8') as f2:
                before = f2.read()
249
            upcode = file.stream.read().decode('utf-8')
250 251 252 253 254 255
            check_to_run = before + upcode
            # print(check_to_run)
            try:
                js2py.eval_js(check_to_run)
            except:
                return jsonify(error.failed('文件上传失败,检测到上传的文件不是drpy框架支持的源代码'))
256 257
            print(savePath)
            # savePath = os.path.join('', savePath)
H
hjdhnx 已提交
258
            # print(savePath)
259 260
            file.seek(0) # 读取后变成空文件,重新赋能
            file.save(savePath)
H
hjdhnx 已提交
261 262 263
            return jsonify(error.success('文件上传成功'))
        except Exception as e:
            return jsonify(error.failed(f'文件上传失败!{e}'))
H
hjdhnx 已提交
264 265 266 267
    else:
        # return render_template('upload.html')
        return jsonify(error.failed('文件上传失败'))

H
hjdhnx 已提交
268 269
@app.route('/vod')
def vod():
270
    t0 = time()
H
hjdhnx 已提交
271
    rule = getParmas('rule')
H
hjdhnx 已提交
272
    ext = getParmas('ext')
H
hjdhnx 已提交
273
    if not ext.startswith('http') and not rule:
H
hjdhnx 已提交
274
        return jsonify(error.failed('规则字段必填'))
275
    rule_list = getRuleLists()
H
hjdhnx 已提交
276 277
    if not ext.startswith('http') and not rule in rule_list:
        msg = f'服务端本地仅支持以下规则:{",".join(rule_list)}'
H
hjdhnx 已提交
278
        return jsonify(error.failed(msg))
279
    # logger.info(f'检验耗时:{get_interval(t0)}毫秒')
H
hjdhnx 已提交
280
    t1 = time()
H
hjdhnx 已提交
281
    js_path = f'js/{rule}.js' if not ext.startswith('http') else ext
282 283
    with open('js/模板.js', encoding='utf-8') as f:
        before = f.read()
284 285
    # logger.info(f'js读取耗时:{get_interval(t1)}毫秒')
    logger.info(f'参数检验js读取共计耗时:{get_interval(t0)}毫秒')
H
hjdhnx 已提交
286 287
    t2 = time()
    ctx, js_code = parser.runJs(js_path,before=before)
H
hjdhnx 已提交
288 289
    if not js_code:
        return jsonify(error.failed('爬虫规则加载失败'))
H
hjdhnx 已提交
290

H
hjdhnx 已提交
291
    # rule = ctx.eval('rule')
292
    # print(type(ctx.rule.lazy()),ctx.rule.lazy().toString())
H
hjdhnx 已提交
293 294
    ruleDict = ctx.rule.to_dict()
    ruleDict['id'] = rule  # 把路由请求的id装到字典里,后面播放嗅探才能用
295
    # print(ruleDict)
H
hjdhnx 已提交
296 297
    # print(rule)
    # print(type(rule))
298
    # print(ruleDict)
H
hjdhnx 已提交
299
    logger.info(f'js装载耗时:{get_interval(t2)}毫秒')
H
hjdhnx 已提交
300
    # print(ruleDict)
301
    # print(rule)
H
hjdhnx 已提交
302
    cms = CMS(ruleDict,db,RuleClass,PlayParse,app.config)
H
hjdhnx 已提交
303 304 305
    wd = getParmas('wd')
    ac = getParmas('ac')
    quick = getParmas('quick')
H
hjdhnx 已提交
306 307
    play = getParmas('play') # 类型为4的时候点击播放会带上来
    flag = getParmas('flag') # 类型为4的时候点击播放会带上来
H
hjdhnx 已提交
308 309
    filter = getParmas('filter')
    t = getParmas('t')
310 311
    pg = getParmas('pg','1')
    pg = int(pg)
H
hjdhnx 已提交
312 313
    ids = getParmas('ids')
    q = getParmas('q')
H
hjdhnx 已提交
314 315
    play_url = getParmas('play_url')

H
hjdhnx 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329
    if play:
        jxs = getJxs()
        play_url = play.split('play_url=')[1]
        play_url = cms.playContent(play_url, jxs,flag)
        if isinstance(play_url, str):
            # return redirect(play_url)
            # return jsonify({'parse': 0, 'playUrl': play_url, 'jx': 0, 'url': play_url})
            # return jsonify({'parse': 0, 'playUrl': play_url, 'jx': 0, 'url': ''})
            return jsonify({'parse': 0, 'playUrl': '', 'jx': 0, 'url': play_url})
        elif isinstance(play_url, dict):
            return jsonify(play_url)
        else:
            return play_url

H
hjdhnx 已提交
330
    if play_url:  # 播放
H
hjdhnx 已提交
331 332
        jxs = getJxs()
        play_url = cms.playContent(play_url,jxs)
H
hjdhnx 已提交
333 334 335 336 337 338
        if isinstance(play_url,str):
            return redirect(play_url)
        elif isinstance(play_url,dict):
            return jsonify(play_url)
        else:
            return play_url
H
hjdhnx 已提交
339

H
hjdhnx 已提交
340 341 342 343 344
    if ac and t: # 一级
        data = cms.categoryContent(t,pg)
        # print(data)
        return jsonify(data)
    if ac and ids: # 二级
345
        id_list = ids.split(',')
H
hjdhnx 已提交
346
        # print('app:377',len(id_list))
347 348
        # print(id_list)
        data = cms.detailContent(pg,id_list)
H
hjdhnx 已提交
349 350 351 352 353 354 355 356
        # print(data)
        return jsonify(data)
    if wd: # 搜索
        data = cms.searchContent(wd)
        # print(data)
        return jsonify(data)

    # return jsonify({'rule':rule,'js_code':js_code})
357
    home_data = cms.homeContent(pg)
H
hjdhnx 已提交
358
    return jsonify(home_data)
H
hjdhnx 已提交
359

H
hjdhnx 已提交
360 361 362 363 364
@app.route('/clear')
def clear():
    rule = getParmas('rule')
    if not rule:
        return jsonify(error.failed('规则字段必填'))
H
hjdhnx 已提交
365
    cache_path = os.path.abspath(f'cache/{rule}.js')
H
hjdhnx 已提交
366
    if not os.path.exists(cache_path):
H
hjdhnx 已提交
367
        return jsonify(error.failed('服务端没有此规则的缓存文件!'+cache_path))
H
hjdhnx 已提交
368 369 370
    os.remove(cache_path)
    return jsonify(error.success('成功删除文件:'+cache_path))

H
hjdhnx 已提交
371
def getRules(path='cache'):
372
    t1 = time()
H
hjdhnx 已提交
373 374 375
    base_path = path+'/'  # 当前文件所在目录
    # print(base_path)
    os.makedirs(base_path,exist_ok=True)
H
hjdhnx 已提交
376
    file_name = os.listdir(base_path)
377
    file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
H
hjdhnx 已提交
378 379
    # print(file_name)
    rule_list = [file.replace('.js', '') for file in file_name]
380 381 382 383
    js_path = [f'{path}/{rule}.js' for rule in rule_list]
    with open('js/模板.js', encoding='utf-8') as f:
        before = f.read()
    rule_codes = []
H
hjdhnx 已提交
384 385 386 387 388 389 390 391 392
    # for js in js_path:
    #     with open(js,encoding='utf-8') as f:
    #         code = f.read()
    #         rule_codes.append(js2py.eval_js(before+code))

    ctx = js2py.EvalJs()
    codes = []
    for i in range(len(js_path)):
        js = js_path[i]
393
        with open(js,encoding='utf-8') as f:
H
hjdhnx 已提交
394 395 396 397 398 399 400
            code = f.read()
            codes.append(code.replace('rule',f'rule{i}',1))
    newCodes = before + '\n'+ '\n'.join(codes)
    # print(newCodes)
    ctx.execute(newCodes)
    for i in range(len(js_path)):
        rule_codes.append(ctx.eval(f'rule{i}'))
401 402 403 404 405 406 407 408 409 410 411

    # print(rule_codes)
    # print(type(rule_codes[0]),rule_codes[0])
    # print(rule_codes[0].title)
    # print(rule_codes[0].searchable)
    # print(rule_codes[0].quickSearch)
    new_rule_list = []
    for i in range(len(rule_list)):
        new_rule_list.append({
            'name':rule_list[i],
            'searchable':rule_codes[i].searchable or 0,
412 413
            'quickSearch':rule_codes[i].quickSearch or 0,
            'filterable':rule_codes[i].filterable or 0,
414 415 416 417
        })
    # print(new_rule_list)
    rules = {'list': new_rule_list, 'count': len(rule_list)}
    logger.info(f'自动配置装载耗时:{get_interval(t1)}毫秒')
H
hjdhnx 已提交
418 419
    return rules

H
hjdhnx 已提交
420 421 422 423 424 425 426 427 428 429 430
def getPics(path='images'):
    base_path = path+'/'  # 当前文件所在目录
    os.makedirs(base_path,exist_ok=True)
    file_name = os.listdir(base_path)
    # file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
    # print(file_name)
    pic_list = [base_path+file for file in file_name]
    # pic_list = file_name
    # print(type(pic_list))
    return pic_list

H
hjdhnx 已提交
431
def getJxs(path='js'):
H
hjdhnx 已提交
432
    with open(f'{path}/解析.conf',encoding='utf-8') as f:
H
hjdhnx 已提交
433
        data = f.read().strip()
H
hjdhnx 已提交
434 435 436 437 438 439 440 441 442
    jxs = []
    for i in data.split('\n'):
        i = i.strip()
        dt = i.split(',')
        if not i.startswith('#'):
            jxs.append({
                'name':dt[0],
                'url':dt[1],
                'type':dt[2] if len(dt) > 2 else 0,
H
hjdhnx 已提交
443
                'ua':dt[3] if len(dt) > 3 else UA,
H
hjdhnx 已提交
444 445 446
            })
    # jxs = [{'name':dt.split(',')[0],'url':dt.split(',')[1]} for dt in data.split('\n')]
    # jxs = list(filter(lambda x:not str(x['name']).strip().startswith('#'),jxs))
H
hjdhnx 已提交
447 448 449 450 451
    # print(jxs)
    print(f'共计{len(jxs)}条解析')
    return jxs


H
hjdhnx 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
def getClasses():
    if not db:
        msg = '未提供数据库连接'
        logger.info(msg)
        return []
    res = db.session.query(RuleClass).all()
    return [rc.name for rc in res]

def getClassInfo(cls):
    if not db:
        msg = f'未提供数据库连接,获取{cls}详情失败'
        logger.info(msg)
        return None
    logger.info(f'开始查询{cls}的分类详情')
    res = db.session.query(RuleClass).filter(RuleClass.name == cls).first()
    if res:
        logger.info(str(res))
        return str(res)
    else:
        return f'数据库不存在{cls}的分类缓存'

H
hjdhnx 已提交
473 474 475 476 477 478 479

@app.route('/favicon.ico')  # 设置icon
def favicon():
    return app.send_static_file('img/favicon.svg')
    # 对于当前文件所在路径,比如这里是static下的favicon.ico
    return send_from_directory(os.path.join(app.root_path, 'static'),  'img/favicon.svg', mimetype='image/vnd.microsoft.icon')

H
hjdhnx 已提交
480 481 482 483
@app.route('/cls/<cls>')
def getClassInfoApi(cls):
    info = getClassInfo(cls)
    return jsonify({'msg':info})
H
hjdhnx 已提交
484

485 486 487 488 489 490 491 492 493 494 495
@app.route('/clearcls/<cls>')
def clearClassApi(cls):
    logger.info(f'开始查询{cls}的分类详情')
    res = db.session.query(RuleClass).filter(RuleClass.name == cls)
    if res:
        res.delete()
        db.session.commit()
        return jsonify(error.success(f'已清除{cls}的分类缓存'))
    else:
        return jsonify(error.failed(f'数据库不存在{cls}的分类缓存'))

H
hjdhnx 已提交
496 497
@app.route('/rules')
def rules():
498
    return render_template('rules.html',rules=getRules(),classes=getClasses())
H
hjdhnx 已提交
499 500 501

@app.route('/raw')
def rules_raw():
H
hjdhnx 已提交
502
    return render_template('raw.html',rules=getRules(),classes=getClasses())
H
hjdhnx 已提交
503

H
hjdhnx 已提交
504 505
@app.route('/pics')
def random_pics():
H
hjdhnx 已提交
506 507
    id = getParmas('id')
    # print(f'id:{id}')
H
hjdhnx 已提交
508 509
    pics = getPics()
    if len(pics) > 0:
H
hjdhnx 已提交
510 511 512 513
        if id and f'images/{id}.jpg' in pics:
            pic = f'images/{id}.jpg'
        else:
            pic = random.choice(pics)
H
hjdhnx 已提交
514 515 516 517 518 519 520
        file = open(pic, "rb").read()
        response = make_response(file)
        response.headers['Content-Type'] = 'image/jpeg'
        return response
    else:
        return redirect(config.WALL_PAPER)

H
hjdhnx 已提交
521 522
def get_live_url(new_conf,mode):
    host = getHost(mode)
H
hjdhnx 已提交
523 524
    # t1 = time()
    live_url = host + '/lives' if new_conf.get('LIVE_MODE',1) == 0 else lsg.getItem('LIVE_URL',getHost(2)+'/lives')
H
hjdhnx 已提交
525
    live_url = base64Encode(live_url)
H
hjdhnx 已提交
526
    # print(f'{get_interval(t1)}毫秒')
H
hjdhnx 已提交
527 528
    return live_url

H
hjdhnx 已提交
529 530
@app.route('/config/<int:mode>')
def config_render(mode):
H
hjdhnx 已提交
531
    # print(dict(app.config))
532 533 534
    if mode == 1:
        jyw_ip = getHost(mode)
        logger.info(jyw_ip)
H
hjdhnx 已提交
535 536 537
    new_conf = dict(app.config)
    host = getHost(mode)
    jxs = getJxs()
H
hjdhnx 已提交
538
    alists = getAlist()
H
hjdhnx 已提交
539 540
    live_url = get_live_url(new_conf,mode)
    # html = render_template('config.txt',rules=getRules('js'),host=host,mode=mode,jxs=jxs,base64Encode=base64Encode,config=new_conf)
H
hjdhnx 已提交
541
    html = render_template('config.txt',rules=getRules('js'),host=host,mode=mode,jxs=jxs,alists=alists,live_url=live_url,config=new_conf)
H
hjdhnx 已提交
542 543 544 545
    response = make_response(html)
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

H
hjdhnx 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558
@app.route('/lives')
def get_lives():
    live_path = 'js/直播.txt'
    if not os.path.exists(live_path):
        with open(live_path,mode='w+',encoding='utf-8') as f:
            f.write('')

    with open(live_path,encoding='utf-8') as f:
        live_text = f.read()
    response = make_response(live_text)
    response.headers['Content-Type'] = 'text/plain; charset=utf-8'
    return response

H
hjdhnx 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
@app.route('/liveslib')
def get_liveslib():
    live_path = 'js/custom_spider.jar'
    if not os.path.exists(live_path):
        with open(live_path,mode='w+',encoding='utf-8') as f:
            f.write('')

    with open(live_path,mode='rb') as f:
        live_text = f.read()
    response = make_response(live_text)
    filename = 'custom_spider.jar'
    response.headers['Content-Type'] = 'application/octet-stream'
    response.headers['Content-Disposition'] = f'attachment;filename="{filename}"'
    return response

H
hjdhnx 已提交
574 575 576
@app.route('/configs')
def config_gen():
    # 生成文件
577
    os.makedirs('txt',exist_ok=True)
H
hjdhnx 已提交
578 579
    new_conf = dict(app.config)
    jxs = getJxs()
H
hjdhnx 已提交
580 581
    alists = getAlist()
    set_local = render_template('config.txt',rules=getRules('js'),alists=alists,live_url=get_live_url(new_conf,0),mode=0,host=getHost(0),jxs=jxs)
H
hjdhnx 已提交
582
    print(set_local)
H
hjdhnx 已提交
583 584
    set_area = render_template('config.txt',rules=getRules('js'),alists=alists,live_url=get_live_url(new_conf,1),mode=1,host=getHost(1),jxs=jxs)
    set_online = render_template('config.txt',rules=getRules('js'),alists=alists,live_url=get_live_url(new_conf,2),mode=1,host=getHost(2),jxs=jxs)
585
    with open('txt/pycms0.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
586 587
        set_dict = json.loads(set_local)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
588
    with open('txt/pycms1.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
589 590 591
        set_dict = json.loads(set_area)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))

592
    with open('txt/pycms2.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
593 594
        set_dict = json.loads(set_online)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
595
    files = [os.path.abspath(rf'txt\pycms{i}.json') for i in range(3)]
H
hjdhnx 已提交
596 597 598
    # print(files)
    return jsonify(error.success('猫配置生成完毕,文件位置在:\n'+'\n'.join(files)))

H
hjdhnx 已提交
599 600 601 602
@app.route("/plugin/<name>",methods=['GET'])
def plugin(name):
    # name=道长影视模板.js
    if not name or not name.split('.')[-1] in ['js','txt','py','json']:
H
hjdhnx 已提交
603
        return jsonify(error.failed(f'非法猥亵,未指定文件名。必须包含js|txt|json|py'))
H
hjdhnx 已提交
604 605 606 607
    try:
        return parser.toJs(name)
    except Exception as e:
        return jsonify(error.failed(f'非法猥亵\n{e}'))
H
hjdhnx 已提交
608

H
hjdhnx 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
def db_test():
    name = '555影视'
    class_name = '电影&连续剧&福利&动漫&综艺'
    class_url = '1&2&124&4&3'
    # data = RuleClass.query.filter(RuleClass.name == '555影视').all()
    res = db.session.query(RuleClass).filter(RuleClass.name == name).first()
    print(res)
    if res:
        res.class_name = class_name
        res.class_url = class_url
        db.session.add(res)
        msg = f'修改成功:{res.id}'
    else:
        res = RuleClass(name=name, class_name=class_name, class_url=class_url)
        db.session.add(res)
        res = db.session.query(RuleClass).filter(RuleClass.name == name).first()
        msg = f'新增成功:{res.id}'

    try:
        db.session.commit()
        return jsonify(error.success(msg))
    except Exception as e:
        return jsonify(error.failed(f'{e}'))

@app.route('/db')
def database():
    return db_test()

H
hjdhnx 已提交
637

H
hjdhnx 已提交
638
if __name__ == '__main__':
H
hjdhnx 已提交
639 640
    # app.run(host="0.0.0.0", port=5705)
    # app.run(debug=True, host='0.0.0.0', port=5705)
H
hjdhnx 已提交
641 642 643 644 645 646 647 648
    http_port = int(app.config.get('HTTP_PORT', 5705))
    http_host = app.config.get('HTTP_HOST', '0.0.0.0')
    if sys.version_info < (3, 9):
        # server = WSGIServer(('0.0.0.0', 5705), app, handler_class=WebSocketHandler,log=app.logger)
        # server = WSGIServer(('0.0.0.0', 5705), app, handler_class=WebSocketHandler,log=None)
        server = WSGIServer((http_host, http_port), app,log=logger)
        server.serve_forever()
    else:
H
hjdhnx 已提交
649
        app.run(debug=False, host=http_host, port=http_port)