mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-21 22:47:13 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e2d83aeb6 | ||
|
|
fadb2ffeeb | ||
|
|
cc2a02cc65 | ||
|
|
676ef1e924 | ||
|
|
b948263519 | ||
|
|
2d7331269c | ||
|
|
11fb809b62 | ||
|
|
7ea84f0941 | ||
|
|
c9ec40803d | ||
|
|
9ecd2c2770 | ||
|
|
e6fa174c0b | ||
|
|
66d9e432bc | ||
|
|
b300463f54 | ||
|
|
bcf0be3d12 | ||
|
|
d4209bb3f7 | ||
|
|
2ba3057f72 | ||
|
|
bdf508264b |
No files matched your search
+3
-3
@@ -1,7 +1,7 @@
|
||||
media/
|
||||
logs/
|
||||
.idea
|
||||
/static/upload
|
||||
/data
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
@@ -111,7 +111,7 @@ celerybeat.pid
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
data/.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
@@ -150,6 +150,6 @@ for_test.py
|
||||
.html
|
||||
/evaluate/temp.py
|
||||
/evaluation/back.json
|
||||
.env*
|
||||
data/.env
|
||||
.backup/
|
||||
/cloc-1.64.exe
|
||||
+2
-3
@@ -1,11 +1,10 @@
|
||||
import datetime
|
||||
|
||||
from sqlalchemy import Boolean, Column, Integer, String, DateTime
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
|
||||
engine = create_async_engine("sqlite+aiosqlite:///database.db")
|
||||
import settings
|
||||
engine = create_async_engine(settings.DATABASE_URL)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
+16
-5
@@ -13,25 +13,36 @@ async def admin_required(pwd: Union[str, None] = Header(default=None)):
|
||||
|
||||
class IPRateLimit:
|
||||
ips = {}
|
||||
count = 0
|
||||
minutes = 0
|
||||
|
||||
def __init__(self, count, minutes):
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
|
||||
def check_ip(self, ip):
|
||||
# 检查ip是否被禁止
|
||||
if ip in self.ips:
|
||||
if self.ips[ip]['count'] >= settings.ERROR_COUNT:
|
||||
if self.ips[ip]['time'] + timedelta(minutes=settings.ERROR_MINUTE) > datetime.now():
|
||||
if self.ips[ip]['count'] >= self.count:
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
else:
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
|
||||
def add_ip(cls, ip):
|
||||
ip_info = cls.ips.get(ip, {'count': 0, 'time': datetime.now()})
|
||||
ip_info['count'] += 1
|
||||
cls.ips[ip] = ip_info
|
||||
return ip_info['count']
|
||||
|
||||
|
||||
async def remove_expired_ip(self):
|
||||
for ip in list(self.ips.keys()):
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) < datetime.now():
|
||||
self.ips.pop(ip)
|
||||
|
||||
def __call__(self, request: Request):
|
||||
ip = request.client.host
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=400, detail="错误次数过多,请稍后再试")
|
||||
raise HTTPException(status_code=400, detail=f"请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -1,89 +1,75 @@
|
||||
import datetime
|
||||
import uuid
|
||||
import random
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException
|
||||
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
|
||||
from starlette.responses import HTMLResponse, FileResponse
|
||||
from starlette.staticfiles import StaticFiles
|
||||
|
||||
from sqlalchemy import or_, select, update, delete
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
|
||||
import settings
|
||||
from database import get_session, Codes, init_models, engine
|
||||
from storage import STORAGE_ENGINE
|
||||
from depends import admin_required, IPRateLimit
|
||||
from utils import delete_expire_files, storage, get_code, error_ip_limit, upload_ip_limit
|
||||
from database import get_session, Codes, init_models
|
||||
from depends import admin_required
|
||||
|
||||
# 实例化FastAPI
|
||||
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")
|
||||
|
||||
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
|
||||
# 静态文件夹,这个固定就行了,静态资源都放在这里
|
||||
app.mount(settings.STATIC_URL, StaticFiles(directory='./static'), name="static")
|
||||
|
||||
|
||||
@app.on_event('startup')
|
||||
async def startup():
|
||||
# 初始化数据库
|
||||
await init_models()
|
||||
# 启动后台任务,不定时删除过期文件
|
||||
asyncio.create_task(delete_expire_files())
|
||||
|
||||
|
||||
# 首页页面
|
||||
index_html = open('templates/index.html', 'r', encoding='utf-8').read() \
|
||||
.replace('{{title}}', settings.TITLE) \
|
||||
.replace('{{description}}', settings.DESCRIPTION) \
|
||||
.replace('{{keywords}}', settings.KEYWORDS)
|
||||
# 管理页面
|
||||
admin_html = open('templates/admin.html', 'r', encoding='utf-8').read() \
|
||||
.replace('{{title}}', settings.TITLE) \
|
||||
.replace('{{description}}', settings.DESCRIPTION) \
|
||||
.replace('{{keywords}}', settings.KEYWORDS)
|
||||
|
||||
ip_limit = IPRateLimit()
|
||||
|
||||
|
||||
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()
|
||||
files = [{'type': old.type, 'text': old.text} for old in exps]
|
||||
await storage.delete_files(files)
|
||||
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))
|
||||
|
||||
|
||||
async def get_code(s: AsyncSession):
|
||||
code = random.randint(10000, 99999)
|
||||
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
|
||||
code = random.randint(10000, 99999)
|
||||
return str(code)
|
||||
|
||||
|
||||
@app.get(f'/{settings.ADMIN_ADDRESS}')
|
||||
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面', response_class=HTMLResponse)
|
||||
async def admin():
|
||||
return HTMLResponse(admin_html)
|
||||
|
||||
|
||||
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)])
|
||||
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='查询数据库列表')
|
||||
async def admin_post(s: AsyncSession = Depends(get_session)):
|
||||
query = select(Codes)
|
||||
codes = (await s.execute(query)).scalars().all()
|
||||
# 查询数据库列表
|
||||
codes = (await s.execute(select(Codes))).scalars().all()
|
||||
return {'detail': '查询成功', 'data': codes}
|
||||
|
||||
|
||||
@app.delete(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)])
|
||||
@app.delete(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='删除数据库记录')
|
||||
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})
|
||||
# 如果记录存在,并且不是文本
|
||||
if file and file.type != 'text':
|
||||
# 删除文件
|
||||
await storage.delete_file(file.text)
|
||||
# 删除数据库记录
|
||||
await s.delete(file)
|
||||
await s.commit()
|
||||
return {'detail': '删除成功'}
|
||||
@@ -95,27 +81,33 @@ async def index():
|
||||
|
||||
|
||||
@app.get('/select')
|
||||
async def get_file(code: str, s: AsyncSession = Depends(get_session)):
|
||||
async def get_file(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
|
||||
# 查出数据库记录
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
info = (await s.execute(query)).scalars().first()
|
||||
# 如果记录不存在,IP错误次数+1
|
||||
if not info:
|
||||
raise HTTPException(status_code=404, detail="口令不存在")
|
||||
error_ip_limit.add_ip(ip)
|
||||
raise HTTPException(status_code=404, detail="口令不存在,次数过多将被禁止访问")
|
||||
# 如果是文本,直接返回
|
||||
if info.type == 'text':
|
||||
return {'detail': '查询成功', 'data': info.text}
|
||||
# 如果是文件,返回文件
|
||||
else:
|
||||
filepath = await storage.get_filepath(info.text)
|
||||
return FileResponse(filepath, filename=info.name)
|
||||
|
||||
|
||||
@app.post('/')
|
||||
async def index(code: str, ip: str = Depends(ip_limit), s: AsyncSession = Depends(get_session)):
|
||||
async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
info = (await s.execute(query)).scalars().first()
|
||||
if not info:
|
||||
error_count = settings.ERROR_COUNT - ip_limit.add_ip(ip)
|
||||
raise HTTPException(status_code=404, detail=f"取件码错误,错误{error_count}次将被禁止10分钟")
|
||||
error_count = settings.ERROR_COUNT - error_ip_limit.add_ip(ip)
|
||||
raise HTTPException(status_code=404, detail=f"取件码错误,{error_count}次后将被禁止{settings.ERROR_MINUTE}分钟")
|
||||
if info.exp_time < datetime.datetime.now() or info.count == 0:
|
||||
await storage.delete_file({'type': info.type, 'text': info.text})
|
||||
if info.type != "text":
|
||||
await storage.delete_file(info.text)
|
||||
await s.delete(info)
|
||||
await s.commit()
|
||||
raise HTTPException(status_code=404, detail="取件码已过期,请联系寄件人")
|
||||
@@ -130,8 +122,9 @@ async def index(code: str, ip: str = Depends(ip_limit), s: AsyncSession = Depend
|
||||
|
||||
|
||||
@app.post('/share')
|
||||
async def share(text: str = Form(default=None), style: str = Form(default='2'), value: int = Form(default=1),
|
||||
file: UploadFile = File(default=None), s: AsyncSession = Depends(get_session)):
|
||||
async def share(background_tasks: BackgroundTasks, text: str = Form(default=None), style: str = Form(default='2'),
|
||||
value: int = Form(default=1), file: UploadFile = File(default=None), ip: str = Depends(upload_ip_limit),
|
||||
s: AsyncSession = Depends(get_session)):
|
||||
code = await get_code(s)
|
||||
if style == '2':
|
||||
if value > 7:
|
||||
@@ -148,27 +141,19 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
|
||||
exp_count = -1
|
||||
key = uuid.uuid4().hex
|
||||
if file:
|
||||
file_bytes = await file.read()
|
||||
size = len(file_bytes)
|
||||
size = await storage.get_size(file)
|
||||
if size > settings.FILE_SIZE_LIMIT:
|
||||
raise HTTPException(status_code=400, detail="文件过大")
|
||||
_text, _type, name = await storage.save_file(file, file_bytes, key), file.content_type, file.filename
|
||||
_text, _type, name = await storage.get_text(file, key), file.content_type, file.filename
|
||||
background_tasks.add_task(storage.save_file, file, _text)
|
||||
else:
|
||||
size, _text, _type, name = len(text), text, 'text', '文本分享'
|
||||
info = Codes(
|
||||
code=code,
|
||||
text=_text,
|
||||
size=size,
|
||||
type=_type,
|
||||
name=name,
|
||||
count=exp_count,
|
||||
exp_time=exp_time,
|
||||
key=key
|
||||
)
|
||||
info = Codes(code=code, text=_text, size=size, type=_type, name=name, count=exp_count, exp_time=exp_time, key=key)
|
||||
s.add(info)
|
||||
await s.commit()
|
||||
upload_ip_limit.add_ip(ip)
|
||||
return {
|
||||
'detail': '分享成功,请点击文件箱查看取件码',
|
||||
'detail': '分享成功,请点击取件码按钮查看上传列表',
|
||||
'data': {'code': code, 'key': key, 'name': name, 'text': _text}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,7 @@
|
||||
- [x] 分享文件:多种上传方式供你选择
|
||||
- [x] 分享文本:直接复制粘贴直接上传
|
||||
- [x] 防爆破:错误五次拉黑十分钟
|
||||
- [x] 完全匿名:不记录任何信息
|
||||
- [x] 无需注册:无需注册,无需登录
|
||||
- [x] 完全匿名:不记录任何信息,无需注册,无需登录
|
||||
- [x] Sqlite3数据库:无需安装数据库
|
||||
- [x] 可以加get参数code,这样打开就会读取取件码如:http://host?code=12345
|
||||
- [x] 管理面板:简单列表页删除违规文件
|
||||
@@ -119,6 +118,10 @@ KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文
|
||||
2. 然后你自己看着填吧
|
||||
|
||||
### Docker部署
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/.env:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
```
|
||||
### Docker自己构建部署
|
||||
|
||||
```bash
|
||||
mkdir "/opt/FileCodeBox"
|
||||
|
||||
+23
-17
@@ -1,31 +1,37 @@
|
||||
from starlette.config import Config
|
||||
|
||||
config = Config(".env")
|
||||
|
||||
# 配置文件.env
|
||||
# 请将.env移动至data目录,方便docker部署
|
||||
config = Config("data/.env")
|
||||
# 是否开启DEBUG模式
|
||||
DEBUG = config('DEBUG', cast=bool, default=False)
|
||||
|
||||
# 端口
|
||||
PORT = config('PORT', cast=int, default=12345)
|
||||
|
||||
DATABASE_URL = config('DATABASE_URL', cast=str, default="sqlite+aiosqlite:///database.db")
|
||||
|
||||
DATA_ROOT = config('DATA_ROOT', cast=str, default="./static")
|
||||
|
||||
# Sqlite数据库文件
|
||||
DATABASE_URL = config('DATABASE_URL', cast=str, default="sqlite+aiosqlite:///data/database.db")
|
||||
# 数据存储文件夹,文件就不暴露在静态资源里面了
|
||||
DATA_ROOT = './data/' + config('DATA_ROOT', cast=str, default=f"static")
|
||||
# 静态文件夹URL
|
||||
STATIC_URL = config('STATIC_URL', cast=str, default="/static")
|
||||
|
||||
# 错误次数
|
||||
ERROR_COUNT = config('ERROR_COUNT', cast=int, default=5)
|
||||
|
||||
# 错误限制分钟数
|
||||
ERROR_MINUTE = config('ERROR_MINUTE', cast=int, default=10)
|
||||
|
||||
# 上传次数
|
||||
UPLOAD_COUNT = config('UPLOAD_COUNT', cast=int, default=60)
|
||||
# 上传限制分钟数
|
||||
UPLOAD_MINUTE = config('UPLOAD_MINUTE', cast=int, default=1)
|
||||
# 管理地址
|
||||
ADMIN_ADDRESS = config('ADMIN_ADDRESS', cast=str, default="admin")
|
||||
|
||||
# 管理密码
|
||||
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default="admin")
|
||||
|
||||
# 文件大小限制,默认10MB
|
||||
FILE_SIZE_LIMIT = config('FILE_SIZE_LIMIT', cast=int, default=10) * 1024 * 1024
|
||||
|
||||
# 网站标题
|
||||
TITLE = config('TITLE', cast=str, default="文件快递柜")
|
||||
|
||||
# 网站描述
|
||||
DESCRIPTION = config('DESCRIPTION', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
|
||||
|
||||
# 网站关键词
|
||||
KEYWORDS = config('KEYWORDS', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
|
||||
|
||||
# 存储引擎
|
||||
STORAGE_ENGINE = config('STORAGE_ENGINE', cast=str, default="filesystem")
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
+37
-23
@@ -1,7 +1,10 @@
|
||||
import os
|
||||
import asyncio
|
||||
import datetime
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
from fastapi import UploadFile
|
||||
|
||||
import settings
|
||||
|
||||
@@ -11,35 +14,46 @@ class FileSystemStorage:
|
||||
STATIC_URL = settings.STATIC_URL
|
||||
NAME = "filesystem"
|
||||
|
||||
async def get_filepath(self, path):
|
||||
return self.DATA_ROOT / path.lstrip(self.STATIC_URL + '/')
|
||||
async def get_filepath(self, text: str):
|
||||
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
|
||||
|
||||
def _save(self, filepath, file_bytes):
|
||||
with open(filepath, 'wb') as f:
|
||||
f.write(file_bytes)
|
||||
|
||||
async def save_file(self, file, file_bytes, key):
|
||||
now = datetime.datetime.now()
|
||||
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
||||
async def get_text(self, file: UploadFile, key: str):
|
||||
ext = file.filename.split('.')[-1]
|
||||
name = f'{key}.{ext}'
|
||||
now = datetime.now()
|
||||
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
||||
if not path.exists():
|
||||
path.mkdir(parents=True)
|
||||
filepath = path / name
|
||||
await asyncio.to_thread(self._save, filepath, file_bytes)
|
||||
text = f"{self.STATIC_URL}/{filepath.relative_to(self.DATA_ROOT)}"
|
||||
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT)}"
|
||||
return text
|
||||
|
||||
async def delete_file(self, file):
|
||||
# 是文件就删除
|
||||
if file['type'] != 'text':
|
||||
filepath = self.DATA_ROOT / file['text'].lstrip(self.STATIC_URL + '/')
|
||||
await asyncio.to_thread(os.remove, filepath)
|
||||
@staticmethod
|
||||
async def get_size(file: UploadFile):
|
||||
f = file.file
|
||||
f.seek(0, os.SEEK_END)
|
||||
size = f.tell()
|
||||
f.seek(0, os.SEEK_SET)
|
||||
return size
|
||||
|
||||
async def delete_files(self, files):
|
||||
for file in files:
|
||||
if file['type'] != 'text':
|
||||
await self.delete_file(file)
|
||||
@staticmethod
|
||||
def _save(filepath, file: BinaryIO):
|
||||
with open(filepath, 'wb') as f:
|
||||
chunk_size = 256 * 1024
|
||||
chunk = file.read(chunk_size)
|
||||
while chunk:
|
||||
f.write(chunk)
|
||||
chunk = file.read(chunk_size)
|
||||
|
||||
async def save_file(self, file: UploadFile, text: str):
|
||||
filepath = await self.get_filepath(text)
|
||||
await asyncio.to_thread(self._save, filepath, file.file)
|
||||
|
||||
async def delete_file(self, text: str):
|
||||
filepath = await self.get_filepath(text)
|
||||
await asyncio.to_thread(os.remove, filepath)
|
||||
|
||||
async def delete_files(self, texts):
|
||||
tasks = [self.delete_file(text) for text in texts]
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
|
||||
STORAGE_ENGINE = {
|
||||
|
||||
+15
-7
@@ -37,7 +37,7 @@
|
||||
<el-row v-if="pageNum === 0" class="qu" style="width:400px;margin: 6vh auto 0 auto">
|
||||
<el-card style="padding-bottom: 1rem">
|
||||
<el-col :span="24">
|
||||
<el-input autofocus @input="listenInput" clearable v-model:value="code" maxlength="5"
|
||||
<el-input autofocus @change="changeInput" clearable v-model:value="code" maxlength="5"
|
||||
:disabled="inputDisable" placeholder="请输入五位取件码">
|
||||
</el-input>
|
||||
</el-col>
|
||||
@@ -119,7 +119,7 @@
|
||||
</el-input>
|
||||
<div class="el-upload__tip">
|
||||
<el-button @click="pageNum=0">去取件</el-button>
|
||||
<el-button @click="cunDrawer=true">取件码</el-button>
|
||||
<el-button @click="jiDrawer=true">取件码</el-button>
|
||||
<el-button v-if="uploadData.type === '2'" @click="toUploadData">寄出去</el-button>
|
||||
</div>
|
||||
</el-card>
|
||||
@@ -236,6 +236,14 @@
|
||||
}
|
||||
});
|
||||
},
|
||||
watch: {
|
||||
code: function (code) {
|
||||
if (code.length === 5) {
|
||||
this.inout_disable = true;
|
||||
this.getFile();
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
http: function (method, url, data = {}, config = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -274,10 +282,9 @@
|
||||
if (this.code.length < 5) {
|
||||
this.code += value;
|
||||
}
|
||||
if (this.code.length === 5) {
|
||||
this.inout_disable = true;
|
||||
this.getFile();
|
||||
}
|
||||
},
|
||||
changeInput: function (value) {
|
||||
this.code = value;
|
||||
},
|
||||
toUploadData: function () {
|
||||
if (this.uploadData.text === '' && this.uploadData.file === null) {
|
||||
@@ -299,8 +306,9 @@
|
||||
}
|
||||
},
|
||||
successUpload(response, file, fileList) {
|
||||
console.log(response)
|
||||
this.$message({
|
||||
message: response.msg,
|
||||
message: response.detail,
|
||||
type: 'success'
|
||||
});
|
||||
this.files.unshift(response.data);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import datetime
|
||||
import random
|
||||
import asyncio
|
||||
from sqlalchemy import or_, select, delete
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
import settings
|
||||
from database import Codes, engine
|
||||
from depends import IPRateLimit
|
||||
from storage import STORAGE_ENGINE
|
||||
|
||||
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
|
||||
|
||||
# 错误IP限制器
|
||||
error_ip_limit = IPRateLimit(settings.ERROR_COUNT, settings.ERROR_MINUTE)
|
||||
# 上传文件限制器
|
||||
upload_ip_limit = IPRateLimit(settings.UPLOAD_COUNT, settings.UPLOAD_MINUTE)
|
||||
|
||||
|
||||
async def delete_expire_files():
|
||||
while True:
|
||||
async with AsyncSession(engine, expire_on_commit=False) as s:
|
||||
await error_ip_limit.remove_expired_ip()
|
||||
await upload_ip_limit.remove_expired_ip()
|
||||
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
|
||||
exps = (await s.execute(query)).scalars().all()
|
||||
files = []
|
||||
exps_ids = []
|
||||
for exp in exps:
|
||||
if exp.type != "text":
|
||||
files.append(exp.text)
|
||||
exps_ids.append(exp.id)
|
||||
await storage.delete_files(files)
|
||||
query = delete(Codes).where(Codes.id.in_(exps_ids))
|
||||
await s.execute(query)
|
||||
await s.commit()
|
||||
await asyncio.sleep(random.randint(2, 2))
|
||||
|
||||
|
||||
async def get_code(s: AsyncSession):
|
||||
code = random.randint(10000, 99999)
|
||||
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
|
||||
code = random.randint(10000, 99999)
|
||||
return str(code)
|
||||
Reference in new issue
Block a user