app.py 16.6 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
# import settings
H
hjdhnx 已提交
13 14
import warnings
warnings.filterwarnings('ignore')
H
hjdhnx 已提交
15 16

import os
H
hjdhnx 已提交
17
from flask import Flask, jsonify, abort,request,redirect,make_response,render_template,send_from_directory,url_for
H
hjdhnx 已提交
18
from werkzeug.utils import secure_filename
19
from js.rules import getRuleLists
H
hjdhnx 已提交
20
from utils import error,parser
H
hjdhnx 已提交
21
from utils.web import *
H
hjdhnx 已提交
22 23
import sys
import codecs
H
hjdhnx 已提交
24
from classes.cms import CMS,logger
H
hjdhnx 已提交
25
import json
H
hjdhnx 已提交
26
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
H
hjdhnx 已提交
27
app = Flask(__name__,static_folder='static',static_url_path='/static')
H
hjdhnx 已提交
28

H
hjdhnx 已提交
29 30
# app.config["JSON_AS_ASCII"] = False # jsonify返回的中文正常显示
app.config.from_object(config) # 单独的配置文件里写了,这里就不用弄json中文显示了
H
hjdhnx 已提交
31 32 33
# new_conf = get_conf(settings)
# print(new_conf)
print('自定义播放解析地址:',app.config.get('PLAY_URL'))
34
print('当前操作系统',sys.platform)
H
hjdhnx 已提交
35
app.logger.name="drLogger"
H
hjdhnx 已提交
36
db = SQLAlchemy(app)
37
migrate = Migrate(app, db)
38
rule_list = getRuleLists()
H
hjdhnx 已提交
39
logger.info(rule_list)
40
logger.info(f'局域网: {getHost(1, 5705)}/index\n本地: {getHost(0, 5705)}/index')
H
hjdhnx 已提交
41

H
hjdhnx 已提交
42
from models import *
H
hjdhnx 已提交
43 44
from gevent.pywsgi import WSGIServer
# from geventwebsocket.handler import WebSocketHandler
H
hjdhnx 已提交
45 46

RuleClass = rule_classes.init(db)
H
hjdhnx 已提交
47
PlayParse = play_parse.init(db)
H
hjdhnx 已提交
48

49 50 51
def is_linux():
    return not 'win' in sys.platform

52
def getParmas(key=None,value=''):
H
hjdhnx 已提交
53 54 55 56 57
    """
    获取链接参数
    :param key:
    :return:
    """
H
hjdhnx 已提交
58
    content_type = request.headers.get('Content-Type')
H
hjdhnx 已提交
59 60
    args = {}
    if request.method == 'POST':
H
hjdhnx 已提交
61 62 63 64 65 66 67 68
        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 已提交
69 70 71
    elif request.method == 'GET':
        args = request.args
    if key:
72
        return args.get(key,value)
H
hjdhnx 已提交
73 74 75
    else:
        return args

H
hjdhnx 已提交
76 77 78 79 80 81
@app.route('/')
def forbidden():  # put application's code here
    abort(403)

@app.route('/index')
def index():  # put application's code here
H
hjdhnx 已提交
82
    # logger.info("进入了首页")
83 84 85 86
    sup_port = app.config.get('SUP_PORT',9001)
    manager0 = ':'.join(getHost(0).split(':')[0:2]) + f':{sup_port}'
    manager1 = ':'.join(getHost(1).split(':')[0:2]) + f':{sup_port}'
    manager2 = ':'.join(getHost(2).split(':')[0:2]) + f':{sup_port}'
H
1  
hjdhnx 已提交
87
    # print(manager1)
88 89
    # print(manager2)
    return render_template('index.html',getHost=getHost,manager0=manager0,manager1=manager1,manager2=manager2,is_linux=is_linux())
H
hjdhnx 已提交
90

H
hjdhnx 已提交
91 92 93 94 95 96 97 98 99 100 101
@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 已提交
102
    return render_template('admin.html',rules=getRules('js'))
H
hjdhnx 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

@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 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
@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'))

    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 已提交
141 142 143 144 145 146 147 148 149
@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 已提交
150 151 152 153 154 155 156 157 158 159 160 161
        try:
            f = request.files['file']
            # print(request.files)
            filename = secure_filename(f.filename)
            savePath = f'js/{filename}'
            if os.path.exists(savePath):
                return jsonify(error.failed(f'上传失败,文件已存在,请先查看删除再试'))
            # print(savePath)
            f.save(savePath)
            return jsonify(error.success('文件上传成功'))
        except Exception as e:
            return jsonify(error.failed(f'文件上传失败!{e}'))
H
hjdhnx 已提交
162 163 164 165
    else:
        # return render_template('upload.html')
        return jsonify(error.failed('文件上传失败'))

H
hjdhnx 已提交
166 167
@app.route('/vod')
def vod():
168
    t0 = time()
H
hjdhnx 已提交
169
    rule = getParmas('rule')
H
hjdhnx 已提交
170
    ext = getParmas('ext')
H
hjdhnx 已提交
171
    if not ext.startswith('http') and not rule:
H
hjdhnx 已提交
172
        return jsonify(error.failed('规则字段必填'))
173
    rule_list = getRuleLists()
H
hjdhnx 已提交
174 175
    if not ext.startswith('http') and not rule in rule_list:
        msg = f'服务端本地仅支持以下规则:{",".join(rule_list)}'
H
hjdhnx 已提交
176
        return jsonify(error.failed(msg))
177
    # logger.info(f'检验耗时:{get_interval(t0)}毫秒')
H
hjdhnx 已提交
178
    t1 = time()
H
hjdhnx 已提交
179
    js_path = f'js/{rule}.js' if not ext.startswith('http') else ext
180 181
    with open('js/模板.js', encoding='utf-8') as f:
        before = f.read()
182 183
    # logger.info(f'js读取耗时:{get_interval(t1)}毫秒')
    logger.info(f'参数检验js读取共计耗时:{get_interval(t0)}毫秒')
H
hjdhnx 已提交
184 185
    t2 = time()
    ctx, js_code = parser.runJs(js_path,before=before)
H
hjdhnx 已提交
186 187
    if not js_code:
        return jsonify(error.failed('爬虫规则加载失败'))
H
hjdhnx 已提交
188

H
hjdhnx 已提交
189
    # rule = ctx.eval('rule')
H
hjdhnx 已提交
190 191
    ruleDict = ctx.rule.to_dict()
    ruleDict['id'] = rule  # 把路由请求的id装到字典里,后面播放嗅探才能用
192
    # print(ruleDict)
H
hjdhnx 已提交
193 194
    # print(rule)
    # print(type(rule))
195
    # print(ruleDict)
H
hjdhnx 已提交
196
    logger.info(f'js装载耗时:{get_interval(t2)}毫秒')
H
hjdhnx 已提交
197
    # print(ruleDict)
198
    # print(rule)
H
hjdhnx 已提交
199
    cms = CMS(ruleDict,db,RuleClass,PlayParse,app.config)
H
hjdhnx 已提交
200 201 202 203 204 205 206
    wd = getParmas('wd')
    ac = getParmas('ac')
    quick = getParmas('quick')
    play = getParmas('play')
    flag = getParmas('flag')
    filter = getParmas('filter')
    t = getParmas('t')
207 208
    pg = getParmas('pg','1')
    pg = int(pg)
H
hjdhnx 已提交
209 210
    ids = getParmas('ids')
    q = getParmas('q')
H
hjdhnx 已提交
211 212 213
    play_url = getParmas('play_url')

    if play_url:  # 播放
H
hjdhnx 已提交
214 215
        jxs = getJxs()
        play_url = cms.playContent(play_url,jxs)
H
hjdhnx 已提交
216
        return redirect(play_url)
H
hjdhnx 已提交
217

H
hjdhnx 已提交
218 219 220 221 222
    if ac and t: # 一级
        data = cms.categoryContent(t,pg)
        # print(data)
        return jsonify(data)
    if ac and ids: # 二级
223 224 225 226
        id_list = ids.split(',')
        # print(len(id_list))
        # print(id_list)
        data = cms.detailContent(pg,id_list)
H
hjdhnx 已提交
227 228 229 230 231 232 233 234
        # print(data)
        return jsonify(data)
    if wd: # 搜索
        data = cms.searchContent(wd)
        # print(data)
        return jsonify(data)

    # return jsonify({'rule':rule,'js_code':js_code})
235
    home_data = cms.homeContent(pg)
H
hjdhnx 已提交
236
    return jsonify(home_data)
H
hjdhnx 已提交
237

H
hjdhnx 已提交
238 239 240 241 242
@app.route('/clear')
def clear():
    rule = getParmas('rule')
    if not rule:
        return jsonify(error.failed('规则字段必填'))
H
hjdhnx 已提交
243
    cache_path = os.path.abspath(f'cache/{rule}.js')
H
hjdhnx 已提交
244
    if not os.path.exists(cache_path):
H
hjdhnx 已提交
245
        return jsonify(error.failed('服务端没有此规则的缓存文件!'+cache_path))
H
hjdhnx 已提交
246 247 248
    os.remove(cache_path)
    return jsonify(error.success('成功删除文件:'+cache_path))

H
hjdhnx 已提交
249
def getRules(path='cache'):
250
    t1 = time()
H
hjdhnx 已提交
251 252 253
    base_path = path+'/'  # 当前文件所在目录
    # print(base_path)
    os.makedirs(base_path,exist_ok=True)
H
hjdhnx 已提交
254
    file_name = os.listdir(base_path)
255
    file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
H
hjdhnx 已提交
256 257
    # print(file_name)
    rule_list = [file.replace('.js', '') for file in file_name]
258 259 260 261
    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 已提交
262 263 264 265 266 267 268 269 270
    # 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]
271
        with open(js,encoding='utf-8') as f:
H
hjdhnx 已提交
272 273 274 275 276 277 278
            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}'))
279 280 281 282 283 284 285 286 287 288 289

    # 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,
290 291
            'quickSearch':rule_codes[i].quickSearch or 0,
            'filterable':rule_codes[i].filterable or 0,
292 293 294 295
        })
    # print(new_rule_list)
    rules = {'list': new_rule_list, 'count': len(rule_list)}
    logger.info(f'自动配置装载耗时:{get_interval(t1)}毫秒')
H
hjdhnx 已提交
296 297
    return rules

H
hjdhnx 已提交
298 299 300 301 302 303 304 305 306 307 308
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 已提交
309 310 311 312 313 314 315 316 317
def getJxs(path='js'):
    with open(f'{path}/解析.txt',encoding='utf-8') as f:
        data = f.read().strip()
    jxs = [{'name':dt.split(',')[0],'url':dt.split(',')[1]} for dt in data.split('\n')]
    # print(jxs)
    print(f'共计{len(jxs)}条解析')
    return jxs


H
hjdhnx 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
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 已提交
339 340 341 342 343 344 345

@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 已提交
346 347 348 349
@app.route('/cls/<cls>')
def getClassInfoApi(cls):
    info = getClassInfo(cls)
    return jsonify({'msg':info})
H
hjdhnx 已提交
350

351 352 353 354 355 356 357 358 359 360 361
@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 已提交
362 363
@app.route('/rules')
def rules():
364
    return render_template('rules.html',rules=getRules(),classes=getClasses())
H
hjdhnx 已提交
365 366 367

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

H
hjdhnx 已提交
370 371
@app.route('/pics')
def random_pics():
H
hjdhnx 已提交
372 373
    id = getParmas('id')
    # print(f'id:{id}')
H
hjdhnx 已提交
374 375
    pics = getPics()
    if len(pics) > 0:
H
hjdhnx 已提交
376 377 378 379
        if id and f'images/{id}.jpg' in pics:
            pic = f'images/{id}.jpg'
        else:
            pic = random.choice(pics)
H
hjdhnx 已提交
380 381 382 383 384 385 386
        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 已提交
387 388
@app.route('/config/<int:mode>')
def config_render(mode):
H
hjdhnx 已提交
389
    # print(dict(app.config))
390 391 392
    if mode == 1:
        jyw_ip = getHost(mode)
        logger.info(jyw_ip)
393
    html = render_template('config.txt',rules=getRules('js'),host=getHost(mode),mode=mode,jxs=getJxs(),base64Encode=base64Encode,config=dict(app.config))
H
hjdhnx 已提交
394 395 396 397
    response = make_response(html)
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

H
hjdhnx 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410
@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 已提交
411 412 413
@app.route('/configs')
def config_gen():
    # 生成文件
414
    os.makedirs('txt',exist_ok=True)
H
hjdhnx 已提交
415
    jxs=getJxs()
416 417 418
    set_local = render_template('config.txt',rules=getRules('js'),base64Encode=base64Encode,mode=0,host=getHost(0),jxs=jxs)
    set_area = render_template('config.txt',rules=getRules('js'),base64Encode=base64Encode,mode=1,host=getHost(1),jxs=jxs)
    set_online = render_template('config.txt',rules=getRules('js'),base64Encode=base64Encode,mode=1,host=getHost(2),jxs=jxs)
419
    with open('txt/pycms0.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
420 421
        set_dict = json.loads(set_local)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
422
    with open('txt/pycms1.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
423 424 425
        set_dict = json.loads(set_area)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))

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

H
hjdhnx 已提交
433 434 435 436
@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 已提交
437
        return jsonify(error.failed(f'非法猥亵,未指定文件名。必须包含js|txt|json|py'))
H
hjdhnx 已提交
438 439 440 441
    try:
        return parser.toJs(name)
    except Exception as e:
        return jsonify(error.failed(f'非法猥亵\n{e}'))
H
hjdhnx 已提交
442

H
hjdhnx 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
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 已提交
471

H
hjdhnx 已提交
472
if __name__ == '__main__':
H
hjdhnx 已提交
473 474
    # app.run(host="0.0.0.0", port=5705)
    # app.run(debug=True, host='0.0.0.0', port=5705)
H
hjdhnx 已提交
475 476 477 478
    # server = WSGIServer(('0.0.0.0', 5705), app, handler_class=WebSocketHandler,log=app.logger)
    server = WSGIServer(('0.0.0.0', 5705), app,log=logger)
    # server = WSGIServer(('0.0.0.0', 5705), app, handler_class=WebSocketHandler,log=None)
    server.serve_forever()
H
hjdhnx 已提交
479
    # WSGIServer(('0.0.0.0', 5705), app,log=None).serve_forever()