Files
FileCodeBox/main.py
T

179 lines
6.3 KiB
Python
Raw Permalink Normal View History

2022-12-09 19:06:47 +08:00
import datetime
import uuid
import random
2022-12-11 18:55:02 +08:00
import asyncio
2022-12-11 21:07:39 +08:00
from pathlib import Path
2022-12-11 18:55:02 +08:00
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException
2022-12-11 14:40:14 +08:00
from starlette.responses import HTMLResponse, FileResponse
2022-12-09 19:06:47 +08:00
from starlette.staticfiles import StaticFiles
2022-12-11 17:41:54 +08:00
from sqlalchemy import or_, select, update, delete
2022-12-11 14:04:25 +08:00
from sqlalchemy.ext.asyncio.session import AsyncSession
2022-12-09 19:06:47 +08:00
2022-12-11 21:07:39 +08:00
import settings
2022-12-11 18:55:02 +08:00
from database import get_session, Codes, init_models, engine
2022-12-12 11:18:55 +08:00
from storage import STORAGE_ENGINE
from depends import admin_required, IPRateLimit
2022-12-11 14:04:25 +08:00
2022-12-11 21:07:39 +08:00
app = FastAPI(debug=settings.DEBUG)
DATA_ROOT = Path(settings.DATA_ROOT)
if not DATA_ROOT.exists():
DATA_ROOT.mkdir(parents=True)
STATIC_URL = settings.STATIC_URL
app.mount(STATIC_URL, StaticFiles(directory=DATA_ROOT), name="static")
2022-12-12 11:18:55 +08:00
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
2022-12-11 18:14:41 +08:00
@app.on_event('startup')
async def startup():
await init_models()
2022-12-11 18:55:02 +08:00
asyncio.create_task(delete_expire_files())
index_html = open('templates/index.html', 'r', encoding='utf-8').read() \
2022-12-11 21:07:39 +08:00
.replace('{{title}}', settings.TITLE) \
.replace('{{description}}', settings.DESCRIPTION) \
.replace('{{keywords}}', settings.KEYWORDS)
admin_html = open('templates/admin.html', 'r', encoding='utf-8').read() \
2022-12-11 21:07:39 +08:00
.replace('{{title}}', settings.TITLE) \
.replace('{{description}}', settings.DESCRIPTION) \
.replace('{{keywords}}', settings.KEYWORDS)
ip_limit = IPRateLimit()
2022-12-09 19:06:47 +08:00
2022-12-11 18:55:02 +08:00
async def delete_expire_files():
while True:
async with AsyncSession(engine, expire_on_commit=False) as s:
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
exps = (await s.execute(query)).scalars().all()
2022-12-12 11:18:55 +08:00
files = [{'type': old.type, 'text': old.text} for old in exps]
await storage.delete_files(files)
2022-12-11 18:55:02 +08:00
exps_ids = [exp.id for exp in exps]
query = delete(Codes).where(Codes.id.in_(exps_ids))
await s.execute(query)
await s.commit()
await asyncio.sleep(random.randint(60, 300))
2022-12-11 14:04:25 +08:00
async def get_code(s: AsyncSession):
2022-12-09 19:06:47 +08:00
code = random.randint(10000, 99999)
2022-12-11 14:04:25 +08:00
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
2022-12-09 19:06:47 +08:00
code = random.randint(10000, 99999)
return str(code)
2022-12-11 21:07:39 +08:00
@app.get(f'/{settings.ADMIN_ADDRESS}')
async def admin():
return HTMLResponse(admin_html)
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)])
async def admin_post(s: AsyncSession = Depends(get_session)):
query = select(Codes)
codes = (await s.execute(query)).scalars().all()
2022-12-13 10:48:09 +08:00
return {'detail': '查询成功', 'data': codes}
@app.delete(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)])
async def admin_delete(code: str, s: AsyncSession = Depends(get_session)):
query = select(Codes).where(Codes.code == code)
file = (await s.execute(query)).scalars().first()
await storage.delete_file({'type': file.type, 'text': file.text})
await s.delete(file)
await s.commit()
2022-12-13 10:48:09 +08:00
return {'detail': '删除成功'}
2022-12-09 19:06:47 +08:00
@app.get('/')
async def index():
2022-12-09 20:31:54 +08:00
return HTMLResponse(index_html)
2022-12-09 19:06:47 +08:00
2022-12-11 14:52:28 +08:00
@app.get('/select')
2022-12-11 17:41:54 +08:00
async def get_file(code: str, s: AsyncSession = Depends(get_session)):
query = select(Codes).where(Codes.code == code)
info = (await s.execute(query)).scalars().first()
if not info:
raise HTTPException(status_code=404, detail="口令不存在")
if info.type == 'text':
2022-12-13 10:48:09 +08:00
return {'detail': '查询成功', 'data': info.text}
2022-12-11 14:40:14 +08:00
else:
filepath = await storage.get_filepath(info.text)
return FileResponse(filepath, filename=info.name)
2022-12-11 14:40:14 +08:00
2022-12-09 19:06:47 +08:00
@app.post('/')
async def index(code: str, ip: str = Depends(ip_limit), s: AsyncSession = Depends(get_session)):
2022-12-11 14:04:25 +08:00
query = select(Codes).where(Codes.code == code)
info = (await s.execute(query)).scalars().first()
if not info:
2022-12-13 10:48:09 +08:00
error_count = settings.ERROR_COUNT - ip_limit.add_ip(ip)
raise HTTPException(status_code=404, detail=f"取件码错误,错误{error_count}次将被禁止10分钟")
2022-12-11 00:02:12 +08:00
if info.exp_time < datetime.datetime.now() or info.count == 0:
2022-12-12 11:18:55 +08:00
await storage.delete_file({'type': info.type, 'text': info.text})
2022-12-11 14:04:25 +08:00
await s.delete(info)
await s.commit()
raise HTTPException(status_code=404, detail="取件码已过期,请联系寄件人")
2022-12-13 10:48:09 +08:00
await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
2022-12-11 14:04:25 +08:00
await s.commit()
2022-12-11 14:40:14 +08:00
if info.type != 'text':
2022-12-11 14:52:28 +08:00
info.text = f'/select?code={code}'
2022-12-10 23:47:36 +08:00
return {
2022-12-13 10:48:09 +08:00
'detail': '取件成功,请点击"取"查看',
2022-12-10 23:47:36 +08:00
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
}
2022-12-09 19:06:47 +08:00
@app.post('/share')
async def share(text: str = Form(default=None), style: str = Form(default='2'), value: int = Form(default=1),
2022-12-11 14:04:25 +08:00
file: UploadFile = File(default=None), s: AsyncSession = Depends(get_session)):
code = await get_code(s)
if style == '2':
if value > 7:
raise HTTPException(status_code=400, detail="最大有效天数为7天")
exp_time = datetime.datetime.now() + datetime.timedelta(days=value)
exp_count = -1
elif style == '1':
if value < 1:
raise HTTPException(status_code=400, detail="最小有效次数为1次")
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = value
2022-12-09 19:06:47 +08:00
else:
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = -1
key = uuid.uuid4().hex
if file:
2022-12-12 11:18:55 +08:00
file_bytes = await file.read()
size = len(file_bytes)
2022-12-11 21:07:39 +08:00
if size > settings.FILE_SIZE_LIMIT:
raise HTTPException(status_code=400, detail="文件过大")
2022-12-12 11:18:55 +08:00
_text, _type, name = await storage.save_file(file, file_bytes, key), file.content_type, file.filename
else:
size, _text, _type, name = len(text), text, 'text', '文本分享'
2022-12-11 14:04:25 +08:00
info = Codes(
code=code,
text=_text,
size=size,
type=_type,
name=name,
count=exp_count,
exp_time=exp_time,
key=key
)
2022-12-11 14:04:25 +08:00
s.add(info)
await s.commit()
return {
2022-12-13 10:48:09 +08:00
'detail': '分享成功,请点击文件箱查看取件码',
'data': {'code': code, 'key': key, 'name': name, 'text': _text}
}
2022-12-10 21:43:12 +08:00
if __name__ == '__main__':
import uvicorn
2022-12-12 15:15:17 +08:00
uvicorn.run('main:app', host='0.0.0.0', port=settings.PORT, debug=settings.DEBUG)