app.py 9.4 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5 6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : app.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/25

H
hjdhnx 已提交
7 8
from flask_sqlalchemy import SQLAlchemy
import config
H
hjdhnx 已提交
9
# import settings
H
hjdhnx 已提交
10 11
import warnings
warnings.filterwarnings('ignore')
H
hjdhnx 已提交
12 13

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

H
hjdhnx 已提交
25 26
# app.config["JSON_AS_ASCII"] = False # jsonify返回的中文正常显示
app.config.from_object(config) # 单独的配置文件里写了,这里就不用弄json中文显示了
H
hjdhnx 已提交
27 28 29
# new_conf = get_conf(settings)
# print(new_conf)
print('自定义播放解析地址:',app.config.get('PLAY_URL'))
H
hjdhnx 已提交
30
app.logger.name="drLogger"
H
hjdhnx 已提交
31
db = SQLAlchemy(app)
H
hjdhnx 已提交
32

H
hjdhnx 已提交
33
rule_list = getRules()
H
hjdhnx 已提交
34 35
logger.info(rule_list)
logger.info(f'http://{getHost(1, 5705)}/index\nhttp://localhost:5705/index')
H
hjdhnx 已提交
36

H
hjdhnx 已提交
37
from models import *
H
hjdhnx 已提交
38 39
from gevent.pywsgi import WSGIServer
# from geventwebsocket.handler import WebSocketHandler
H
hjdhnx 已提交
40 41

RuleClass = rule_classes.init(db)
H
hjdhnx 已提交
42
PlayParse = play_parse.init(db)
H
hjdhnx 已提交
43

44
def getParmas(key=None,value=''):
H
hjdhnx 已提交
45 46 47 48 49 50 51 52 53 54 55
    """
    获取链接参数
    :param key:
    :return:
    """
    args = {}
    if request.method == 'POST':
        args = request.json
    elif request.method == 'GET':
        args = request.args
    if key:
56
        return args.get(key,value)
H
hjdhnx 已提交
57 58 59
    else:
        return args

H
hjdhnx 已提交
60 61 62 63 64 65
@app.route('/')
def forbidden():  # put application's code here
    abort(403)

@app.route('/index')
def index():  # put application's code here
H
hjdhnx 已提交
66
    # logger.info("进入了首页")
67 68
    manager = getHost(1).split(':')[0] + ':9001'
    return render_template('index.html',getHost=getHost,manager=manager)
H
hjdhnx 已提交
69

H
hjdhnx 已提交
70 71 72
@app.route('/vod')
def vod():
    rule = getParmas('rule')
H
hjdhnx 已提交
73
    ext = getParmas('ext')
H
hjdhnx 已提交
74
    if not ext.startswith('http') and not rule:
H
hjdhnx 已提交
75
        return jsonify(error.failed('规则字段必填'))
H
hjdhnx 已提交
76 77
    if not ext.startswith('http') and not rule in rule_list:
        msg = f'服务端本地仅支持以下规则:{",".join(rule_list)}'
H
hjdhnx 已提交
78 79
        return jsonify(error.failed(msg))

H
hjdhnx 已提交
80
    js_path = f'js/{rule}.js' if not ext.startswith('http') else ext
H
hjdhnx 已提交
81
    ctx,js_code = parser.runJs(js_path)
H
hjdhnx 已提交
82 83
    if not js_code:
        return jsonify(error.failed('爬虫规则加载失败'))
H
hjdhnx 已提交
84

H
hjdhnx 已提交
85
    rule = ctx.eval('rule')
H
hjdhnx 已提交
86
    cms = CMS(rule,db,RuleClass,PlayParse,app.config)
H
hjdhnx 已提交
87 88 89 90 91 92 93
    wd = getParmas('wd')
    ac = getParmas('ac')
    quick = getParmas('quick')
    play = getParmas('play')
    flag = getParmas('flag')
    filter = getParmas('filter')
    t = getParmas('t')
94 95
    pg = getParmas('pg','1')
    pg = int(pg)
H
hjdhnx 已提交
96 97
    ids = getParmas('ids')
    q = getParmas('q')
H
hjdhnx 已提交
98 99 100 101 102
    play_url = getParmas('play_url')

    if play_url:  # 播放
        play_url = cms.playContent(play_url)
        return redirect(play_url)
H
hjdhnx 已提交
103

H
hjdhnx 已提交
104 105 106 107 108
    if ac and t: # 一级
        data = cms.categoryContent(t,pg)
        # print(data)
        return jsonify(data)
    if ac and ids: # 二级
109 110 111 112
        id_list = ids.split(',')
        # print(len(id_list))
        # print(id_list)
        data = cms.detailContent(pg,id_list)
H
hjdhnx 已提交
113 114 115 116 117 118 119 120
        # print(data)
        return jsonify(data)
    if wd: # 搜索
        data = cms.searchContent(wd)
        # print(data)
        return jsonify(data)

    # return jsonify({'rule':rule,'js_code':js_code})
121
    home_data = cms.homeContent(pg)
H
hjdhnx 已提交
122
    return jsonify(home_data)
H
hjdhnx 已提交
123

H
hjdhnx 已提交
124 125 126 127 128
@app.route('/clear')
def clear():
    rule = getParmas('rule')
    if not rule:
        return jsonify(error.failed('规则字段必填'))
H
hjdhnx 已提交
129
    cache_path = os.path.abspath(f'cache/{rule}.js')
H
hjdhnx 已提交
130
    if not os.path.exists(cache_path):
H
hjdhnx 已提交
131
        return jsonify(error.failed('服务端没有此规则的缓存文件!'+cache_path))
H
hjdhnx 已提交
132 133 134
    os.remove(cache_path)
    return jsonify(error.success('成功删除文件:'+cache_path))

H
hjdhnx 已提交
135 136 137 138
def getRules(path='cache'):
    base_path = path+'/'  # 当前文件所在目录
    # print(base_path)
    os.makedirs(base_path,exist_ok=True)
H
hjdhnx 已提交
139 140 141 142
    file_name = os.listdir(base_path)
    file_name = list(filter(lambda x: str(x).endswith('.js'), file_name))
    # print(file_name)
    rule_list = [file.replace('.js', '') for file in file_name]
H
hjdhnx 已提交
143 144 145
    rules = {'list': rule_list, 'count': len(rule_list)}
    return rules

H
hjdhnx 已提交
146 147 148 149 150 151 152 153 154
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 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
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 已提交
176 177 178 179 180 181 182

@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 已提交
183 184 185 186
@app.route('/cls/<cls>')
def getClassInfoApi(cls):
    info = getClassInfo(cls)
    return jsonify({'msg':info})
H
hjdhnx 已提交
187

188 189 190 191 192 193 194 195 196 197 198
@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 已提交
199 200
@app.route('/rules')
def rules():
201
    return render_template('rules.html',rules=getRules(),classes=getClasses())
H
hjdhnx 已提交
202 203 204

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

H
hjdhnx 已提交
207 208
@app.route('/config/<int:mode>')
def config_render(mode):
H
hjdhnx 已提交
209
    # print(dict(app.config))
H
hjdhnx 已提交
210
    html = render_template('config.txt',rules=getRules('js'),host=getHost(mode),mode=mode,jxs=getJxs(),config=dict(app.config))
H
hjdhnx 已提交
211 212 213 214 215 216 217
    response = make_response(html)
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

@app.route('/configs')
def config_gen():
    # 生成文件
218
    os.makedirs('txt',exist_ok=True)
H
hjdhnx 已提交
219 220 221 222
    jxs=getJxs()
    set_local = render_template('config.txt',rules=getRules('js'),mode=0,host=getHost(0),jxs=jxs)
    set_area = render_template('config.txt',rules=getRules('js'),mode=1,host=getHost(1),jxs=jxs)
    set_online = render_template('config.txt',rules=getRules('js'),mode=1,host=getHost(2),jxs=jxs)
223
    with open('txt/pycms0.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
224 225
        set_dict = json.loads(set_local)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
226
    with open('txt/pycms1.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
227 228 229
        set_dict = json.loads(set_area)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))

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

H
hjdhnx 已提交
237 238 239 240 241 242 243 244 245
@app.route("/plugin/<name>",methods=['GET'])
def plugin(name):
    # name=道长影视模板.js
    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)
    except Exception as e:
        return jsonify(error.failed(f'非法猥亵\n{e}'))
H
hjdhnx 已提交
246

H
hjdhnx 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
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 已提交
275

H
hjdhnx 已提交
276
if __name__ == '__main__':
H
hjdhnx 已提交
277 278
    # app.run(host="0.0.0.0", port=5705)
    # app.run(debug=True, host='0.0.0.0', port=5705)
H
hjdhnx 已提交
279 280 281 282
    # 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 已提交
283
    # WSGIServer(('0.0.0.0', 5705), app,log=None).serve_forever()