style: code format
This commit is contained in:
@@ -12,26 +12,34 @@ class IPRateLimit:
|
||||
def check_ip(self, ip: str) -> bool:
|
||||
if ip in self.ips:
|
||||
ip_info = self.ips[ip]
|
||||
if ip_info['count'] >= self.count:
|
||||
if ip_info['time'] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
if ip_info["count"] >= self.count:
|
||||
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip: str) -> int:
|
||||
ip_info = self.ips.get(ip, {'count': 0, 'time': datetime.now()})
|
||||
ip_info['count'] += 1
|
||||
ip_info['time'] = datetime.now()
|
||||
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
|
||||
ip_info["count"] += 1
|
||||
ip_info["time"] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info['count']
|
||||
return ip_info["count"]
|
||||
|
||||
async def remove_expired_ip(self) -> None:
|
||||
now = datetime.now()
|
||||
expiration = timedelta(minutes=self.minutes)
|
||||
self.ips = {ip: info for ip, info in self.ips.items() if info['time'] + expiration >= now}
|
||||
self.ips = {
|
||||
ip: info
|
||||
for ip, info in self.ips.items()
|
||||
if info["time"] + expiration >= now
|
||||
}
|
||||
|
||||
def __call__(self, request: Request) -> str:
|
||||
ip = request.headers.get('X-Real-IP') or request.headers.get('X-Forwarded-For') or request.client.host
|
||||
ip = (
|
||||
request.headers.get("X-Real-IP")
|
||||
or request.headers.get("X-Forwarded-For")
|
||||
or request.client.host
|
||||
)
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
||||
return ip
|
||||
|
||||
+33
-15
@@ -14,17 +14,31 @@ from core.utils import get_now
|
||||
|
||||
class FileCodes(Model):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
code: Optional[int] = fields.CharField(description='分享码', max_length=255, index=True, unique=True)
|
||||
prefix: Optional[str] = fields.CharField(max_length=255, description='前缀', default='')
|
||||
suffix: Optional[str] = fields.CharField(max_length=255, description='后缀', default='')
|
||||
uuid_file_name: Optional[str] = fields.CharField(max_length=255, description='uuid文件名', null=True)
|
||||
file_path: Optional[str] = fields.CharField(max_length=255, description='文件路径', null=True)
|
||||
size: Optional[int] = fields.IntField(description='文件大小', default=0)
|
||||
text: Optional[str] = fields.TextField(description='文本内容', null=True)
|
||||
expired_at: Optional[datetime] = fields.DatetimeField(null=True, description='过期时间')
|
||||
expired_count: Optional[int] = fields.IntField(description='可用次数', default=0)
|
||||
used_count: Optional[int] = fields.IntField(description='已用次数', default=0)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(auto_now_add=True, description='创建时间')
|
||||
code: Optional[int] = fields.CharField(
|
||||
description="分享码", max_length=255, index=True, unique=True
|
||||
)
|
||||
prefix: Optional[str] = fields.CharField(
|
||||
max_length=255, description="前缀", default=""
|
||||
)
|
||||
suffix: Optional[str] = fields.CharField(
|
||||
max_length=255, description="后缀", default=""
|
||||
)
|
||||
uuid_file_name: Optional[str] = fields.CharField(
|
||||
max_length=255, description="uuid文件名", null=True
|
||||
)
|
||||
file_path: Optional[str] = fields.CharField(
|
||||
max_length=255, description="文件路径", null=True
|
||||
)
|
||||
size: Optional[int] = fields.IntField(description="文件大小", default=0)
|
||||
text: Optional[str] = fields.TextField(description="文本内容", null=True)
|
||||
expired_at: Optional[datetime] = fields.DatetimeField(
|
||||
null=True, description="过期时间"
|
||||
)
|
||||
expired_count: Optional[int] = fields.IntField(description="可用次数", default=0)
|
||||
used_count: Optional[int] = fields.IntField(description="已用次数", default=0)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(
|
||||
auto_now_add=True, description="创建时间"
|
||||
)
|
||||
|
||||
async def is_expired(self):
|
||||
# 按时间
|
||||
@@ -42,9 +56,13 @@ class FileCodes(Model):
|
||||
|
||||
class KeyValue(Model):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
key: Optional[str] = fields.CharField(max_length=255, description='键', index=True, unique=True)
|
||||
value: Optional[str] = fields.JSONField(description='值', null=True)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(auto_now_add=True, description='创建时间')
|
||||
key: Optional[str] = fields.CharField(
|
||||
max_length=255, description="键", index=True, unique=True
|
||||
)
|
||||
value: Optional[str] = fields.JSONField(description="值", null=True)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(
|
||||
auto_now_add=True, description="创建时间"
|
||||
)
|
||||
|
||||
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name='FileCodes')
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes")
|
||||
|
||||
+30
-20
@@ -14,47 +14,57 @@ from core.utils import get_random_num, get_random_string, max_save_times_desc
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
"""获取文件路径和文件名"""
|
||||
today = datetime.datetime.now()
|
||||
storage_path = settings.storage_path.strip('/') # 移除开头和结尾的斜杠
|
||||
storage_path = settings.storage_path.strip("/") # 移除开头和结尾的斜杠
|
||||
file_uuid = uuid.uuid4().hex
|
||||
|
||||
|
||||
# 使用 UUID 作为子目录名
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}"
|
||||
|
||||
|
||||
# 如果设置了存储路径,将其添加到基础路径中
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
|
||||
|
||||
prefix, suffix = os.path.splitext(file.filename)
|
||||
# 保持原始文件名
|
||||
save_path = f"{path}/{file.filename}"
|
||||
return path, suffix, prefix, file.filename, save_path
|
||||
|
||||
|
||||
async def get_expire_info(expire_value: int, expire_style: str) -> Tuple[Optional[datetime.datetime], int, int, str]:
|
||||
async def get_expire_info(
|
||||
expire_value: int, expire_style: str
|
||||
) -> Tuple[Optional[datetime.datetime], int, int, str]:
|
||||
"""获取过期信息"""
|
||||
expired_count, used_count = -1, 0
|
||||
now = datetime.datetime.now()
|
||||
code = None
|
||||
|
||||
max_timedelta = datetime.timedelta(seconds=settings.max_save_seconds) if settings.max_save_seconds > 0 else datetime.timedelta(days=7)
|
||||
detail = await max_save_times_desc(settings.max_save_seconds) if settings.max_save_seconds > 0 else '7天'
|
||||
detail = f'限制最长时间为 {detail[0]},可换用其他方式'
|
||||
max_timedelta = (
|
||||
datetime.timedelta(seconds=settings.max_save_seconds)
|
||||
if settings.max_save_seconds > 0
|
||||
else datetime.timedelta(days=7)
|
||||
)
|
||||
detail = (
|
||||
await max_save_times_desc(settings.max_save_seconds)
|
||||
if settings.max_save_seconds > 0
|
||||
else "7天"
|
||||
)
|
||||
detail = f"限制最长时间为 {detail[0]},可换用其他方式"
|
||||
|
||||
expire_styles = {
|
||||
'day': lambda: now + datetime.timedelta(days=expire_value),
|
||||
'hour': lambda: now + datetime.timedelta(hours=expire_value),
|
||||
'minute': lambda: now + datetime.timedelta(minutes=expire_value),
|
||||
'count': lambda: (now + datetime.timedelta(days=1), expire_value),
|
||||
'forever': lambda: (None, None), # 修改这里
|
||||
"day": lambda: now + datetime.timedelta(days=expire_value),
|
||||
"hour": lambda: now + datetime.timedelta(hours=expire_value),
|
||||
"minute": lambda: now + datetime.timedelta(minutes=expire_value),
|
||||
"count": lambda: (now + datetime.timedelta(days=1), expire_value),
|
||||
"forever": lambda: (None, None), # 修改这里
|
||||
}
|
||||
|
||||
if expire_style in expire_styles:
|
||||
result = expire_styles[expire_style]()
|
||||
if isinstance(result, tuple):
|
||||
expired_at, extra = result
|
||||
if expire_style == 'count':
|
||||
if expire_style == "count":
|
||||
expired_count = extra
|
||||
elif expire_style == 'forever':
|
||||
code = await get_random_code(style='string') # 移动到这里
|
||||
elif expire_style == "forever":
|
||||
code = await get_random_code(style="string") # 移动到这里
|
||||
else:
|
||||
expired_at = result
|
||||
if expired_at and expired_at - now > max_timedelta:
|
||||
@@ -68,15 +78,15 @@ async def get_expire_info(expire_value: int, expire_style: str) -> Tuple[Optiona
|
||||
return expired_at, expired_count, used_count, code
|
||||
|
||||
|
||||
async def get_random_code(style='num') -> str:
|
||||
async def get_random_code(style="num") -> str:
|
||||
"""获取随机字符串"""
|
||||
while True:
|
||||
code = await get_random_num() if style == 'num' else await get_random_string()
|
||||
code = await get_random_num() if style == "num" else await get_random_string()
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
return code
|
||||
|
||||
|
||||
ip_limit = {
|
||||
'error': IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute),
|
||||
'upload': IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute)
|
||||
"error": IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
}
|
||||
|
||||
+52
-40
@@ -8,32 +8,36 @@ from core.settings import settings
|
||||
from core.storage import storages, FileStorageInterface
|
||||
from core.utils import get_select_token
|
||||
|
||||
share_api = APIRouter(prefix='/share', tags=['分享'])
|
||||
share_api = APIRouter(prefix="/share", tags=["分享"])
|
||||
|
||||
|
||||
async def validate_file_size(file: UploadFile, max_size: int):
|
||||
if file.size > max_size:
|
||||
max_size_mb = max_size / (1024 * 1024)
|
||||
raise HTTPException(status_code=403, detail=f'大小超过限制,最大为{max_size_mb:.2f} MB')
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"大小超过限制,最大为{max_size_mb:.2f} MB"
|
||||
)
|
||||
|
||||
|
||||
async def create_file_code(code, **kwargs):
|
||||
return await FileCodes.create(code=code, **kwargs)
|
||||
|
||||
|
||||
@share_api.post('/text/', dependencies=[Depends(admin_required)])
|
||||
@share_api.post("/text/", dependencies=[Depends(admin_required)])
|
||||
async def share_text(
|
||||
text: str = Form(...),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default='day'),
|
||||
ip: str = Depends(ip_limit['upload'])
|
||||
text: str = Form(...),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
text_size = len(text.encode('utf-8'))
|
||||
text_size = len(text.encode("utf-8"))
|
||||
max_txt_size = 222 * 1024
|
||||
if text_size > max_txt_size:
|
||||
raise HTTPException(status_code=403, detail='内容过多,建议采用文件形式')
|
||||
raise HTTPException(status_code=403, detail="内容过多,建议采用文件形式")
|
||||
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(expire_value, expire_style)
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
await create_file_code(
|
||||
code=code,
|
||||
text=text,
|
||||
@@ -41,25 +45,27 @@ async def share_text(
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
size=len(text),
|
||||
prefix='Text'
|
||||
prefix="Text",
|
||||
)
|
||||
ip_limit['upload'].add_ip(ip)
|
||||
return APIResponse(detail={'code': code})
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code})
|
||||
|
||||
|
||||
@share_api.post('/file/', dependencies=[Depends(admin_required)])
|
||||
@share_api.post("/file/", dependencies=[Depends(admin_required)])
|
||||
async def share_file(
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default='day'),
|
||||
file: UploadFile = File(...),
|
||||
ip: str = Depends(ip_limit['upload'])
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
file: UploadFile = File(...),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
await validate_file_size(file, settings.uploadSize)
|
||||
|
||||
if expire_style not in settings.expireStyle:
|
||||
raise HTTPException(status_code=400, detail='过期时间类型错误')
|
||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(expire_value, expire_style)
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
|
||||
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
@@ -76,16 +82,16 @@ async def share_file(
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
)
|
||||
ip_limit['upload'].add_ip(ip)
|
||||
return APIResponse(detail={'code': code, 'name': file.filename})
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": file.filename})
|
||||
|
||||
|
||||
async def get_code_file_by_code(code, check=True):
|
||||
file_code = await FileCodes.filter(code=code).first()
|
||||
if not file_code:
|
||||
return False, '文件不存在'
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
return False, '文件已过期'
|
||||
return False, "文件已过期"
|
||||
return True, file_code
|
||||
|
||||
|
||||
@@ -96,44 +102,50 @@ async def update_file_usage(file_code):
|
||||
await file_code.save()
|
||||
|
||||
|
||||
@share_api.get('/select/')
|
||||
async def get_code_file(code: str, ip: str = Depends(ip_limit['error'])):
|
||||
@share_api.get("/select/")
|
||||
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
if not has:
|
||||
ip_limit['error'].add_ip(ip)
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
await update_file_usage(file_code)
|
||||
return await file_storage.get_file_response(file_code)
|
||||
|
||||
|
||||
@share_api.post('/select/')
|
||||
async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit['error'])):
|
||||
@share_api.post("/select/")
|
||||
async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
has, file_code = await get_code_file_by_code(data.code)
|
||||
if not has:
|
||||
ip_limit['error'].add_ip(ip)
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
await update_file_usage(file_code)
|
||||
return APIResponse(detail={
|
||||
'code': file_code.code,
|
||||
'name': file_code.prefix + file_code.suffix,
|
||||
'size': file_code.size,
|
||||
'text': file_code.text if file_code.text is not None else await file_storage.get_file_url(file_code),
|
||||
})
|
||||
return APIResponse(
|
||||
detail={
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": (
|
||||
file_code.text
|
||||
if file_code.text is not None
|
||||
else await file_storage.get_file_url(file_code)
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@share_api.get('/download')
|
||||
async def download_file(key: str, code: str, ip: str = Depends(ip_limit['error'])):
|
||||
@share_api.get("/download")
|
||||
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
if await get_select_token(code) != key:
|
||||
ip_limit['error'].add_ip(ip)
|
||||
ip_limit["error"].add_ip(ip)
|
||||
|
||||
has, file_code = await get_code_file_by_code(code, False)
|
||||
if not has:
|
||||
return APIResponse(code=404, detail='文件不存在')
|
||||
return APIResponse(code=404, detail="文件不存在")
|
||||
|
||||
return (
|
||||
APIResponse(detail=file_code.text)
|
||||
|
||||
Reference in New Issue
Block a user