153 lines
11 KiB
Python
153 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Loopback-only Fuc theme preview. Synthetic data; never imports Laravel or forwards requests."""
|
|
import argparse
|
|
from http.cookies import SimpleCookie
|
|
import json
|
|
import mimetypes
|
|
import time
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse, parse_qs
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
ASSETS = ROOT / 'theme/Fuc/assets'
|
|
NOW = int(time.time())
|
|
PLANS = [dict(id=i, name=name, transfer_enable=gb, speed_limit=speed, device_limit=devices,
|
|
display_device_limit=devices, sell=True, capacity_limit=None, content='',
|
|
month_price=price, quarter_price=price*3, year_price=price*10,
|
|
half_year_price=None, two_year_price=None, three_year_price=None,
|
|
onetime_price=None, reset_price=None)
|
|
for i, name, gb, speed, devices, price in [
|
|
(1,'轻量订阅',100,100,3,1200),(2,'标准订阅',300,300,5,2400),
|
|
(3,'高级订阅',600,500,8,4200),(4,'旗舰订阅',1000,1000,10,6800)]]
|
|
USER = dict(email='[email protected]',balance=2800,commission_balance=1200,
|
|
created_at=NOW-86400*180,remind_expire=True,remind_traffic=False)
|
|
SUB = dict(plan=PLANS[1],plan_id=2,device_limit=5,speed_limit=300,expired_at=NOW+86400*27,
|
|
u=1024**3*3.18,d=1024**3*43.24,transfer_enable=1024**3*300,reset_day=27,
|
|
subscribe_url='https://subscription.example.test/client/subscribe?token=preview-only')
|
|
ORDERS = [dict(id=1,trade_no='PREVIEW202610210001',plan_id=2,plan=PLANS[1],period='month_price',
|
|
total_amount=2400,created_at=NOW-86400*3,status=3)]
|
|
TICKETS = [dict(id=1,subject='客户端订阅使用咨询',status=0,level=1,created_at=NOW-86400,
|
|
message=[dict(is_me=True,message='请问在哪里复制订阅链接?',created_at=NOW-86400),
|
|
dict(is_me=False,message='您好,在用户中心选择对应客户端,然后点击“复制订阅链接”即可。',created_at=NOW-86000)])]
|
|
CODES = [dict(code='FUCDEMO1')]
|
|
DOCS = {'客户端教程':[dict(id=1,title='Windows · Clash Verge 使用指南',body='<h3>添加订阅</h3><p>在用户中心选择 Windows,复制订阅链接后,在客户端添加远程配置。</p>'),dict(id=2,title='iOS · Shadowrocket 使用指南',body='<h3>导入订阅</h3><p>打开已安装的客户端,在用户中心选择 iOS 后使用导入按钮。</p>')], '常见问题':[dict(id=3,title='订阅更新与流量说明',body='<p>如果更新订阅失败,请检查套餐有效期与剩余流量。</p>')]}
|
|
HTML = '''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Fuc · 本地预览</title></head><body><div id="app"></div><script>window.fucSettings={title:'福云',description:'访问国际互联网,解锁奈飞、ChatGPT,加速 GitHub。',preview:true};</script><script type="module" src="/theme/Fuc/assets/app.mjs"></script></body></html>'''
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def log_message(self, *args):
|
|
pass # No request bodies or authentication headers in logs.
|
|
def send(self, content, status=200, kind='application/json; charset=utf-8', headers=None):
|
|
body = content.encode() if isinstance(content,str) else content
|
|
self.send_response(status)
|
|
self.send_header('Content-Type',kind)
|
|
self.send_header('Cache-Control','no-store')
|
|
self.send_header('X-Content-Type-Options','nosniff')
|
|
for name,value in (headers or {}).items():
|
|
for item in (value if isinstance(value,list) else [value]): self.send_header(name,item)
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
def data(self, content):
|
|
self.send(json.dumps(dict(data=content),ensure_ascii=False))
|
|
def do_GET(self):
|
|
parsed = urlparse(self.path)
|
|
path = parsed.path
|
|
query = {k:v[0] for k,v in parse_qs(parsed.query).items()}
|
|
if path == '/':
|
|
fixture=query.get('fixture','normal')
|
|
cookies=[]
|
|
if 'fixture' in query:cookies.append(f'fuc_fixture={fixture if fixture in ["empty","error"] else "normal"}; Path=/; SameSite=Strict')
|
|
if 'delay' in query:
|
|
try: delay=max(0,min(3000,int(query['delay'])))
|
|
except ValueError: delay=0
|
|
cookies.append(f'fuc_delay={delay}; Path=/; SameSite=Strict')
|
|
return self.send(HTML,kind='text/html; charset=utf-8',headers={'Set-Cookie':cookies})
|
|
if path.startswith('/reference/'):
|
|
directory=ROOT/'codex/output/fuc-theme/reference/pages'
|
|
asset=(directory/path.removeprefix('/reference/')).resolve()
|
|
if not asset.is_relative_to(directory) or not asset.is_file(): return self.send('Not found',404,'text/plain')
|
|
return self.send(asset.read_bytes(),kind='text/html; charset=utf-8')
|
|
if path.startswith('/theme/Fuc/assets/'):
|
|
asset = (ASSETS / path.removeprefix('/theme/Fuc/assets/')).resolve()
|
|
if not asset.is_relative_to(ASSETS) or not asset.is_file(): return self.send('Not found',404,'text/plain')
|
|
kind = 'text/javascript' if asset.suffix == '.mjs' else mimetypes.guess_type(asset.name)[0] or 'text/plain'
|
|
return self.send(asset.read_bytes(),kind=kind)
|
|
if path.startswith('/api/v1/'):
|
|
return self.api(path.removeprefix('/api/v1/'),query)
|
|
self.send('Not found',404,'text/plain')
|
|
def do_POST(self):
|
|
size = int(self.headers.get('Content-Length','0'))
|
|
if size > 20000: return self.send('{}',413)
|
|
try: data = json.loads(self.rfile.read(size) or b'{}')
|
|
except ValueError: return self.send('{}',400)
|
|
self.api(urlparse(self.path).path.removeprefix('/api/v1/'), data)
|
|
def api(self,path,data):
|
|
if path.startswith('user/'):
|
|
cookie=SimpleCookie(self.headers.get('Cookie',''))
|
|
try: delay=max(0,min(3000,int(cookie['fuc_delay'].value))) if 'fuc_delay' in cookie else 0
|
|
except ValueError: delay=0
|
|
if delay:time.sleep(delay/1000)
|
|
|
|
if path == 'guest/plan/fetch': return self.data(PLANS)
|
|
if path == 'guest/comm/config': return self.data(dict(is_captcha=0,is_email_verify=1,is_invite_force=0))
|
|
if path.startswith('passport/'):
|
|
if path == 'passport/comm/sendEmailVerify': return self.data(True)
|
|
if path == 'passport/auth/forget': return self.data(True)
|
|
return self.data(dict(auth_data='Bearer local-preview-only'))
|
|
if not self.headers.get('Authorization'):
|
|
return self.send(json.dumps(dict(message='请先登录')),401)
|
|
fixture=self.headers.get('Cookie','')
|
|
if 'fuc_fixture=error' in fixture: return self.send(json.dumps(dict(message='本地演示错误状态')),503)
|
|
if 'fuc_fixture=empty' in fixture:
|
|
if path in ['user/notice/fetch','user/plan/fetch','user/order/fetch','user/server/fetch','user/ticket/fetch','user/invite/details']: return self.data([])
|
|
if path == 'user/knowledge/fetch': return self.data({})
|
|
if path == 'user/invite/fetch': return self.data(dict(codes=[],stat=[0,0,0,0,0]))
|
|
if path == 'user/info': return self.data(USER)
|
|
if path == 'user/getSubscribe': return self.data(SUB)
|
|
if path == 'user/notice/fetch': return self.data([dict(title='欢迎使用福云',content='<p>感谢您的支持。您可以在用户中心查看订阅与用量,选择对应客户端一键导入订阅。</p><p>如有使用问题,请查看使用文档或提交工单,我们会尽快为您处理。</p>',created_at=NOW-86400*2)])
|
|
if path == 'user/plan/fetch': return self.data(PLANS)
|
|
if path == 'user/order/fetch': return self.data(ORDERS)
|
|
if path == 'user/order/save':
|
|
plan = next(p for p in PLANS if p['id']==int(data['plan_id']))
|
|
no = f'PREVIEW{time.time_ns()}'
|
|
ORDERS.insert(0,dict(id=len(ORDERS)+1,trade_no=no,plan=plan,plan_id=plan['id'],period=data['period'],total_amount=plan[data['period']],status=0,created_at=int(time.time())))
|
|
return self.data(no)
|
|
if path == 'user/order/detail': return self.data(next((o for o in ORDERS if o['trade_no']==data['trade_no']),{}))
|
|
if path == 'user/order/getPaymentMethod': return self.data([dict(id=1,name='演示支付(不扣款)')])
|
|
if path in ['user/order/cancel','user/order/checkout']:
|
|
order = next(o for o in ORDERS if o['trade_no']==data['trade_no'])
|
|
order['status'] = 2 if path.endswith('cancel') else 3
|
|
if path.endswith('checkout'): return self.send(json.dumps(dict(type=-1,data=True)))
|
|
return self.data(True)
|
|
if path == 'user/invite/fetch': return self.data(dict(codes=CODES,stat=[8,5600,600,10,1200]))
|
|
if path == 'user/invite/details': return self.data([dict(id=1,trade_no='PREVIEWINVITE1',user_id=101,order_amount=2400,get_amount=240,created_at=NOW-86400)])
|
|
if path == 'user/resetSecurity': return self.data(SUB['subscribe_url'])
|
|
if path == 'user/transfer':
|
|
amount=int(data['transfer_amount'])
|
|
if amount <= 0 or amount > USER['commission_balance']: return self.send(json.dumps(dict(message='余额不足')),422)
|
|
USER['commission_balance']-=amount; USER['balance']+=amount; return self.data(True)
|
|
if path == 'user/ticket/withdraw': return self.data(True)
|
|
if path == 'user/invite/save': CODES.append(dict(code=f'DEMO{len(CODES)+1:04}')); return self.data(True)
|
|
if path == 'user/server/fetch': return self.data([dict(id=i,name=f'{country} {i:02}',type='vless',rate=1,is_online=i!=3) for i,country in enumerate(['日本','新加坡','香港','美国'],1)])
|
|
if path == 'user/ticket/fetch':
|
|
return self.data(next((t for t in TICKETS if t['id']==int(data['id'])),{}) if 'id' in data else TICKETS)
|
|
if path == 'user/ticket/save':
|
|
TICKETS.insert(0,dict(id=len(TICKETS)+1,subject=data['subject'],level=int(data['level']),status=0,created_at=NOW,message=[dict(is_me=True,message=data['message'],created_at=NOW)]))
|
|
return self.data(True)
|
|
if path in ['user/ticket/reply','user/ticket/close']:
|
|
ticket = next(t for t in TICKETS if t['id']==int(data['id']))
|
|
if path.endswith('reply'): ticket['message'].append(dict(is_me=True,message=data['message'],created_at=NOW))
|
|
else: ticket['status']=1
|
|
return self.data(True)
|
|
if path == 'user/knowledge/fetch':
|
|
docs = [d for group in DOCS.values() for d in group]
|
|
return self.data(next((d for d in docs if d['id']==int(data['id'])),{}) if 'id' in data else DOCS)
|
|
if path == 'user/update': USER.update(data); return self.data(True)
|
|
if path == 'user/changePassword': return self.data(True)
|
|
self.send(json.dumps(dict(message='此演示接口不存在')),404)
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--port',type=int,default=8594)
|
|
args = parser.parse_args()
|
|
print(f'Fuc synthetic preview: http://127.0.0.1:{args.port}/',flush=True)
|
|
ThreadingHTTPServer(('127.0.0.1',args.port),Handler).serve_forever()
|