home.py 9.0 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
H
hjdhnx 已提交
22
from utils.encode import parseText
H
hjdhnx 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
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 已提交
41
    sup_port = cfg.get('SUP_PORT', 9001)
H
hjdhnx 已提交
42 43 44 45 46 47 48
    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 已提交
49 50
    ver = getLocalVer()
    return render_template('index.html',ver=ver,getHost=getHost,manager0=manager0,manager1=manager1,manager2=manager2,is_linux=is_linux())
H
hjdhnx 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64

@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 已提交
65
    # print(pics)
H
hjdhnx 已提交
66 67 68 69 70
    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 已提交
71 72 73 74 75 76 77 78 79
        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 已提交
80
        return redirect(new_conf.WALL_PAPER)
H
hjdhnx 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

@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 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
@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 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
@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 已提交
138

H
hjdhnx 已提交
139

H
hjdhnx 已提交
140 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 169 170
@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

@home.route('/config/<int:mode>')
def config_render(mode):
    # print(dict(app.config))
H
hjdhnx 已提交
171 172 173 174 175
    customFile = 'base/custom.conf'
    if not os.path.exists(customFile):
        with open(customFile,'w+',encoding='utf-8') as f:
            f.write('{}')
    customConfig = False
H
hjdhnx 已提交
176 177 178 179
    if mode == 1:
        jyw_ip = getHost(mode)
        logger.info(jyw_ip)
    new_conf = cfg
H
hjdhnx 已提交
180 181 182
    lsg = storage_service()
    store_conf_dict = lsg.getStoreConfDict()
    new_conf.update(store_conf_dict)
H
hjdhnx 已提交
183
    # print(type(new_conf),new_conf)
H
hjdhnx 已提交
184
    host = getHost(mode)
H
hjdhnx 已提交
185 186 187 188 189 190
    try:
        with open(customFile,'r',encoding='utf-8') as f:
            text = f.read()
            customConfig = parseText(render_template_string(text,host=host))
    except Exception as e:
        logger.info(f'用户自定义配置加载失败:{e}')
H
hjdhnx 已提交
191
    jxs = getJxs()
H
hjdhnx 已提交
192 193 194 195
    lsg = storage_service()
    use_py = lsg.getItem('USE_PY')
    pys = getPys() if use_py else []
    # print(pys)
H
hjdhnx 已提交
196 197 198 199
    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 已提交
200
    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 已提交
201 202 203 204 205
    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 已提交
206 207 208 209 210 211 212 213
    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 已提交
214 215 216
    lsg = storage_service()
    store_conf_dict = lsg.getStoreConfDict()
    new_conf.update(store_conf_dict)
H
hjdhnx 已提交
217
    jxs = getJxs()
H
hjdhnx 已提交
218 219 220
    lsg = storage_service()
    use_py = lsg.getItem('USE_PY')
    pys = getPys() if use_py else False
H
hjdhnx 已提交
221 222
    alists = getAlist()
    alists_str = json.dumps(alists,ensure_ascii=False)
H
hjdhnx 已提交
223
    set_local = render_template('config.txt',pys=pys,rules=getRules('js'),alists=alists,alists_str=alists_str,live_url=get_live_url(new_conf,0),mode=0,host=getHost(0),jxs=jxs)
H
hjdhnx 已提交
224
    print(set_local)
H
hjdhnx 已提交
225 226
    set_area = render_template('config.txt',pys=pys,rules=getRules('js'),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=getRules('js'),alists=alists,alists_str=alists_str,live_url=get_live_url(new_conf,2),mode=1,host=getHost(2),jxs=jxs)
H
hjdhnx 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    with open('txt/pycms0.json','w+',encoding='utf-8') as f:
        set_dict = json.loads(set_local)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))
    with open('txt/pycms1.json','w+',encoding='utf-8') as f:
        set_dict = json.loads(set_area)
        f.write(json.dumps(set_dict,ensure_ascii=False,indent=4))

    with open('txt/pycms2.json','w+',encoding='utf-8') as f:
        set_dict = json.loads(set_online)
        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))

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