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

H
hjdhnx 已提交
9
from flask import Blueprint,abort,render_template,render_template_string,url_for,redirect,make_response,send_from_directory
H
hjdhnx 已提交
10 11 12
from controllers.service import storage_service
from controllers.classes import getClasses,getClassInfo
from utils.web import getParmas
H
hjdhnx 已提交
13
from utils.files import getPics,custom_merge
H
hjdhnx 已提交
14
from js.rules import getRules,getPys
H
hjdhnx 已提交
15
from base.R import R
H
hjdhnx 已提交
16 17
from utils.system import getHost,is_linux
from utils.cfg import cfg
H
hjdhnx 已提交
18 19 20
from utils import parser
from utils.log import logger
from utils.files import getAlist,get_live_url
H
hjdhnx 已提交
21
from utils.update import getLocalVer,getHotSuggest
H
hjdhnx 已提交
22
from utils.encode import parseText
H
hjdhnx 已提交
23
from utils.files import getCustonDict
H
hjdhnx 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
from js.rules import getJxs
import random

home = Blueprint("home", __name__,static_folder='/static')

@home.route('/')
def forbidden():  # put application's code here
    abort(403)

@home.route('/favicon.ico')  # 设置icon
def favicon():
    # return home.send_static_file('img/favicon.svg')
    return redirect('/static/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')

@home.route('/index')
def index():
H
hjdhnx 已提交
42
    sup_port = cfg.get('SUP_PORT', 9001)
H
hjdhnx 已提交
43 44 45 46 47 48 49
    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
hjdhnx 已提交
50 51
    ver = getLocalVer()
    return render_template('index.html',ver=ver,getHost=getHost,manager0=manager0,manager1=manager1,manager2=manager2,is_linux=is_linux())
H
hjdhnx 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65

@home.route('/rules/clear')
def rules_to_clear():
    return render_template('rules_to_clear.html',rules=getRules(),classes=getClasses())

@home.route('/rules/view')
def rules_to_view():
    return render_template('rules_to_view.html',rules=getRules(),classes=getClasses())

@home.route('/pics')
def random_pics():
    id = getParmas('id')
    # print(f'id:{id}')
    pics = getPics()
H
hjdhnx 已提交
66
    # print(pics)
H
hjdhnx 已提交
67 68 69 70 71
    new_conf = cfg
    lsg = storage_service()
    store_conf_dict = lsg.getStoreConfDict()
    new_conf.update(store_conf_dict)
    if not new_conf.WALL_PAPER and len(pics) > 0:
H
hjdhnx 已提交
72 73 74 75 76 77 78 79 80
        if id and f'images/{id}.jpg' in pics:
            pic = f'images/{id}.jpg'
        else:
            pic = random.choice(pics)
        file = open(pic, "rb").read()
        response = make_response(file)
        response.headers['Content-Type'] = 'image/jpeg'
        return response
    else:
H
hjdhnx 已提交
81
        return redirect(new_conf.WALL_PAPER)
H
hjdhnx 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

@home.route('/clear')
def clear_rule():
    rule = getParmas('rule')
    if not rule:
        return R.failed('规则字段必填')
    cache_path = os.path.abspath(f'cache/{rule}.js')
    if not os.path.exists(cache_path):
        return R.failed('服务端没有此规则的缓存文件!'+cache_path)
    os.remove(cache_path)
    return R.success('成功删除文件:'+cache_path)

@home.route("/plugin/<name>",methods=['GET'])
def plugin(name):
    # name=道长影视模板.js
    if not name or not name.split('.')[-1] in ['js','txt','py','json']:
        return R.failed(f'非法猥亵,未指定文件名。必须包含js|txt|json|py')
    try:
        return parser.toJs(name)
    except Exception as e:
        return R.failed(f'非法猥亵\n{e}')

H
hjdhnx 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
@home.route('/files/<name>')
def get_files(name):
    base_path = 'base/files'
    os.makedirs(base_path,exist_ok=True)
    file_path = os.path.join(base_path, f'{name}')
    if not os.path.exists(file_path):
        return R.failed(f'{file_path}文件不存在')

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

H
hjdhnx 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
@home.route('/txt/<path:filename>')
def custom_static(filename):
    # 自定义静态目录 {{ url_for('custom_static',filename='help.txt')}}
    # print(filename)
    return send_from_directory('txt', filename)

# @home.route('/txt/<name>')
# def get_txt_files(name):
#     base_path = 'txt'
#     os.makedirs(base_path,exist_ok=True)
#     file_path = os.path.join(base_path, f'{name}')
#     if not os.path.exists(file_path):
#         return R.failed(f'{file_path}文件不存在')
#
#     with open(file_path, mode='r',encoding='utf-8') as f:
#         file_byte = f.read()
#     response = make_response(file_byte)
#     response.headers['Content-Type'] = 'text/plain; charset=utf-8'
#     return response
H
hjdhnx 已提交
139

H
hjdhnx 已提交
140

H
hjdhnx 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
@home.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

@home.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 已提交
169 170 171 172 173
@home.route('/hotsugg')
def get_hot_search():
    data = getHotSuggest()
    return R.success('获取成功',data)

H
hjdhnx 已提交
174 175 176
@home.route('/config/<int:mode>')
def config_render(mode):
    # print(dict(app.config))
H
hjdhnx 已提交
177 178 179 180
    if mode == 1:
        jyw_ip = getHost(mode)
        logger.info(jyw_ip)
    new_conf = cfg
H
hjdhnx 已提交
181 182 183
    lsg = storage_service()
    store_conf_dict = lsg.getStoreConfDict()
    new_conf.update(store_conf_dict)
H
hjdhnx 已提交
184
    # print(type(new_conf),new_conf)
H
hjdhnx 已提交
185
    host = getHost(mode)
H
hjdhnx 已提交
186
    customConfig = getCustonDict(host)
H
hjdhnx 已提交
187
    jxs = getJxs()
H
hjdhnx 已提交
188 189 190 191
    lsg = storage_service()
    use_py = lsg.getItem('USE_PY')
    pys = getPys() if use_py else []
    # print(pys)
H
hjdhnx 已提交
192 193 194 195
    alists = getAlist()
    alists_str = json.dumps(alists, ensure_ascii=False)
    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 已提交
196
    html = render_template('config.txt',pys=pys,rules=getRules('js'),host=host,mode=mode,jxs=jxs,alists=alists,alists_str=alists_str,live_url=live_url,config=new_conf)
H
hjdhnx 已提交
197 198 199 200 201
    merged_config = custom_merge(parseText(html),customConfig)
    # print(merged_config)
    # response = make_response(html)
    response = make_response(json.dumps(merged_config,ensure_ascii=False,indent=1))
    # response = make_response(str(merged_config))
H
hjdhnx 已提交
202 203 204 205 206 207 208 209
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

@home.route('/configs')
def config_gen():
    # 生成文件
    os.makedirs('txt',exist_ok=True)
    new_conf = cfg
H
hjdhnx 已提交
210 211 212
    lsg = storage_service()
    store_conf_dict = lsg.getStoreConfDict()
    new_conf.update(store_conf_dict)
H
hjdhnx 已提交
213 214 215 216 217 218 219
    try:
        jxs = getJxs()
        lsg = storage_service()
        use_py = lsg.getItem('USE_PY')
        pys = getPys() if use_py else False
        alists = getAlist()
        alists_str = json.dumps(alists,ensure_ascii=False)
H
hjdhnx 已提交
220 221 222 223 224
        rules = getRules('js')
        set_local = render_template('config.txt',pys=pys,rules=rules,alists=alists,alists_str=alists_str,live_url=get_live_url(new_conf,0),mode=0,host=getHost(0),jxs=jxs)
        # print(set_local)
        set_area = render_template('config.txt',pys=pys,rules=rules,alists=alists,alists_str=alists_str,live_url=get_live_url(new_conf,1),mode=1,host=getHost(1),jxs=jxs)
        set_online = render_template('config.txt',pys=pys,rules=rules,alists=alists,alists_str=alists_str,live_url=get_live_url(new_conf,2),mode=1,host=getHost(2),jxs=jxs)
H
hjdhnx 已提交
225
        with open('txt/pycms0.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
226 227 228
            customConfig = getCustonDict(0)
            set_dict = custom_merge(parseText(set_local), customConfig)
            # set_dict = json.loads(set_local)
H
hjdhnx 已提交
229 230
            f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
        with open('txt/pycms1.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
231 232 233
            customConfig = getCustonDict(1)
            set_dict = custom_merge(parseText(set_area), customConfig)
            # set_dict = json.loads(set_area)
H
hjdhnx 已提交
234 235 236
            f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))

        with open('txt/pycms2.json','w+',encoding='utf-8') as f:
H
hjdhnx 已提交
237 238 239
            customConfig = getCustonDict(2)
            set_dict = custom_merge(parseText(set_online), customConfig)
            # set_dict = json.loads(set_online)
H
hjdhnx 已提交
240 241 242 243 244 245
            f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
        files = [os.path.abspath(rf'txt\pycms{i}.json') for i in range(3)]
        # print(files)
        return R.success('猫配置生成完毕,文件位置在:\n'+'\n'.join(files))
    except Exception as e:
        return R.failed(f'配置文件生成错误:\n{e}')
H
hjdhnx 已提交
246 247 248 249 250

@home.route("/info",methods=['get'])
def info_all():
    data = storage_service.query_all()
    return R.ok(data=data)