Compare commits

..
82 Commits
Author SHA1 Message Date
vastsa f80d50981c fix:error 2022-12-19 22:34:19 +08:00
vastsa dfb7367100 fix:error 2022-12-19 22:33:51 +08:00
vastsa d764cb48e3 fix:admin error 2022-12-19 22:28:59 +08:00
lan f01d39c1c9 update:background-color 2022-12-19 22:00:04 +08:00
lan 59805273bf add:管理页面页码+Banner配置 2022-12-19 18:50:36 +08:00
lan a58102a61b add:管理页面页码+Banner配置 2022-12-19 18:16:47 +08:00
lan b40c77e49f add:管理页面页码+Banner配置 2022-12-19 18:14:18 +08:00
lan c686822c43 add:管理页面页码+Banner配置 2022-12-19 18:07:51 +08:00
lan 4ed95f8b64 add:管理页面页码+Banner配置 2022-12-19 18:05:56 +08:00
lan d47da11916 add:管理页面页码+Banner配置 2022-12-19 18:05:38 +08:00
lan 8a93dd5e38 add:管理页面页码+Banner配置 2022-12-19 18:01:50 +08:00
lan 1c938948fd add:上传页面新增banner 2022-12-19 15:21:24 +08:00
lan 141008639a add:点击复制取件码,文本 2022-12-19 14:32:48 +08:00
lan dd3267cf1f add:点击复制取件码 2022-12-19 13:59:44 +08:00
lan 3d6f5ba9f4 update:index.html 2022-12-17 14:02:27 +08:00
vastsa 422ae8adff Merge pull request #15 from BrackRat/master
修改文本,按钮和部分布局方便用户理解存取逻辑
2022-12-17 13:44:16 +08:00
“BrackRat” cb340b6b22 修改文本,按钮和部分布局方便用户理解逻辑 2022-12-17 12:40:31 +08:00
lan b3533e897a update:code 2022-12-16 12:21:47 +08:00
lan 0bc73796e7 update:code 2022-12-16 12:20:58 +08:00
lan 594c105190 update:code 2022-12-16 12:19:00 +08:00
lan 6caca3cb7b Merge remote-tracking branch 'origin/master' 2022-12-16 11:51:20 +08:00
lan 2d9348c293 update:静态资源 2022-12-16 11:51:13 +08:00
vastsa ec6939f824 Update readme.md
私有化提示
2022-12-16 11:38:58 +08:00
lan 6d83e94c2f update:update readme 2022-12-16 09:23:56 +08:00
lan 3c0376b63c Merge remote-tracking branch 'origin/master' 2022-12-16 02:22:27 +08:00
lan f021673961 update:rename asserts and update docker file 2022-12-16 02:21:49 +08:00
vastsa de190e6345 Update readme.md
update
2022-12-16 01:56:38 +08:00
lan f9daa3cab3 update:去除取件判断过期删除 2022-12-15 17:14:39 +08:00
lan 965384500a add:前端判断文件大小
add:自定义删除过期文件间隔,修复因间隔过短导致还没下载文件就没了
2022-12-15 16:59:25 +08:00
lan eb9a656ee1 add:前端判断文件大小
add:自定义删除过期文件间隔,修复因间隔过短导致还没下载文件就没了
2022-12-15 16:49:23 +08:00
lan 5543811c20 add:前端判断文件大小
add:自定义删除过期文件间隔,修复因间隔过短导致还没下载文件就没了
2022-12-15 16:34:18 +08:00
lan 1f14997e4a update:readme 2022-12-14 17:22:35 +08:00
lan 5297146a63 add:demo 2022-12-14 13:21:00 +08:00
lan d77dcb3f92 fix:admin list text 2022-12-14 12:31:48 +08:00
lan 133e85fa49 fix:更新获取IP的方式 2022-12-14 12:28:09 +08:00
lan a432f8d80f fix:暂时移除alembic,需要默认创建数据库 2022-12-14 11:22:24 +08:00
lan 2a102bfb1f fix:暂时移除alembic,需要默认创建数据库 2022-12-14 11:16:30 +08:00
lan 1994ba5917 update:关闭docs,redoc 2022-12-14 10:21:11 +08:00
lan 68175f9583 update:限制管理员上传,最长天数配置 2022-12-14 09:55:04 +08:00
lan 0caabe3ee8 update:docker version 2022-12-14 09:36:50 +08:00
lan 5c350cbfc6 update:docker version 2022-12-14 09:35:18 +08:00
lan 0a200da28b update:docker version 2022-12-14 01:32:46 +08:00
lan 7f2c1c9e7c update:english readme and future plan 2022-12-14 01:16:45 +08:00
lan 12d28ec691 add:开关上传功能,关闭则仅允许管理员上传 2022-12-14 01:13:48 +08:00
lan 65ad220bb4 update:readme 2022-12-14 00:16:12 +08:00
lan 585bf0948c update:readme 2022-12-14 00:02:30 +08:00
lan a258bb4ea3 update:readme 2022-12-13 23:10:38 +08:00
lan d8985db3e1 fix: no database file 2022-12-13 22:19:37 +08:00
vastsa a17a7e1d58 Merge pull request #12 from veoco/master
新增 alembic 管理数据库架构
2022-12-13 22:13:39 +08:00
vastsa 63d60022d2 Merge branch 'master' into master 2022-12-13 22:13:27 +08:00
lan 1e2d83aeb6 update:修改文件结构,存储文件不再暴露,自定义数据都放在/data文件夹,方便docker 2022-12-13 22:07:14 +08:00
lan fadb2ffeeb update:修改文件结构,存储文件不再暴露,自定义数据都放在/data文件夹,方便docker 2022-12-13 22:06:29 +08:00
lan cc2a02cc65 update:docker script 2022-12-13 21:37:09 +08:00
lan 676ef1e924 update:docker script 2022-12-13 21:20:09 +08:00
lan b948263519 fix:upload failure 2022-12-13 21:16:41 +08:00
veoco 8ffddd5870 新增 alembic 管理数据库架构 2022-12-13 21:03:15 +08:00
lan 2d7331269c update:新增限制时间内上传次数,移除IP黑名单列表过期IP,防止炸内存 2022-12-13 19:16:29 +08:00
lan 11fb809b62 fix:keyboard double input 2022-12-13 18:51:14 +08:00
lan 7ea84f0941 update:adjust file structure 2022-12-13 17:55:25 +08:00
lan c9ec40803d update:adjust file structure 2022-12-13 17:50:22 +08:00
vastsa 9ecd2c2770 Merge pull request #11 from veoco/master
调整文件的大小计算和写入方法
2022-12-13 17:05:31 +08:00
lan e6fa174c0b update:docker image 2022-12-13 15:12:52 +08:00
veoco 66d9e432bc 调整文件删除方式 2022-12-13 14:18:02 +08:00
lan b300463f54 fix:打不开取件框 2022-12-13 14:13:40 +08:00
veoco bcf0be3d12 调整文件大小计算和写入方法 2022-12-13 12:45:28 +08:00
lan d4209bb3f7 lan 2022-12-13 11:29:33 +08:00
lan 2ba3057f72 test 2022-12-13 11:28:55 +08:00
lan-air bdf508264b logo 2022-12-13 11:25:42 +08:00
lan-air 4218caeaf7 完善手机版上传文本 2022-12-13 10:50:48 +08:00
lan-air 24ad5e08ca 重构index.html 2022-12-13 10:48:09 +08:00
vastsa 31f67fae3f Merge pull request #10 from veoco/master
重写用户登录和 IP 检查并重定义状态码
2022-12-13 08:01:40 +08:00
lan-air 27fc665239 update version 2022-12-13 07:52:20 +08:00
lan-air 541d49d636 update version 2022-12-13 07:46:46 +08:00
veoco 68881c6df0 重写用户登录和 IP 检查并重定义状态码 2022-12-12 22:30:03 +08:00
lan-air fb80d26b70 add setting port 2022-12-12 15:15:17 +08:00
vastsa 9cf0d9418d Merge pull request #7 from veoco/master
新增存储引擎统一文件读写
2022-12-12 11:47:49 +08:00
veoco 4e069486bf 新增存储引擎统一文件读写 2022-12-12 11:18:55 +08:00
lan-air 8935da813b .gitattributes 2022-12-12 11:11:45 +08:00
lan-air 387a3babfd readme.md 2022-12-12 01:02:50 +08:00
lan-air 42dedfae1e 完善文档,以及docker新增文件夹映射 2022-12-11 23:06:28 +08:00
lan-air cfd2989bc0 完善文档,以及docker新增文件夹映射 2022-12-11 22:47:33 +08:00
lan-air 31b61a2f7a 完善文档,以及docker新增文件夹映射 2022-12-11 22:47:08 +08:00
34 changed files with 1051 additions and 412 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
*.js linguist-language=python
*.css linguist-language=python
*.html linguist-language=python
+3 -3
View File
@@ -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
+3 -5
View File
@@ -1,13 +1,11 @@
FROM python:3.9.5
FROM python:3.9.5-slim-buster
LABEL author="Lan"
LABEL email="vast@tom.com"
LABEL version="1.4.2"
LABEL version="1.5.8"
COPY . /app
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' >/etc/timezone
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 12345
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "12345"]
CMD ["python","main.py"]
+10 -3
View File
@@ -1,11 +1,11 @@
import datetime
from sqlalchemy import Boolean, Column, Integer, String, DateTime
from sqlalchemy import Boolean, Column, Integer, String, DateTime, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio.session import AsyncSession
import settings
engine = create_async_engine("sqlite+aiosqlite:///database.db")
engine = create_async_engine(settings.DATABASE_URL)
Base = declarative_base()
@@ -20,6 +20,13 @@ async def get_session():
yield s
class Values(Base):
__tablename__ = 'values'
id = Column(Integer, primary_key=True, index=True)
key = Column(String, unique=True)
value = Column(JSON)
class Codes(Base):
__tablename__ = "codes"
id = Column(Integer, primary_key=True, index=True)
+52
View File
@@ -0,0 +1,52 @@
from typing import Union
from datetime import datetime, timedelta
from fastapi import Header, HTTPException, Request
import settings
async def admin_required(pwd: Union[str, None] = Header(default=None), request: Request = None):
if 'share' in request.url.path:
if pwd != settings.ADMIN_PASSWORD and not settings.ENABLE_UPLOAD:
raise HTTPException(status_code=403, detail='本站上传功能已关闭,仅管理员可用')
else:
if not pwd or pwd != settings.ADMIN_PASSWORD:
raise HTTPException(status_code=401, detail="密码错误,请重新登录")
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'] >= 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(self, ip):
ip_info = self.ips.get(ip, {'count': 0, 'time': datetime.now()})
ip_info['count'] += 1
self.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.headers.get('X-Real-IP', request.headers.get('X-Forwarded-For', request.client.host))
if not self.check_ip(ip):
raise HTTPException(status_code=400, detail=f"请求次数过多,请稍后再试")
return ip
+33
View File
@@ -0,0 +1,33 @@
## 更新记录
### 2022年12月13日
- [x] 完善手机版上传文本
- [x] 优化Index.html首页
- [x] 填补了由于上面修改带来的坑
- [x] 更新了
### 2022年12月12日
- [x] 重写用户登录和 IP 检查并重定义状态码
- [x] 新增存储引擎统一文件读写
- [x] 设置PORT
### 2022年12月11日
1. 修复取件不显示码的问题
2. 修复文件次数为1时,文件被删除的问题
3. 使用 aiosqlite 驱动异步化数据库操作
4. 增加定时清理过期文件
5. 优化部署方式,Docker映射,后续更新直接覆盖代码重启
6. 优化配置文件,增加配置项
7. 发布V1.4.5稳定版
### 2022年12月10日
1. 管理面板已新增,一如既往的极简,只有删除
2. 二维码图片(调用的网络接口,如果离线环境将无法使用,一切为了极简)
3. 取件码有效期,取件码使用次数
4. 优化代码逻辑
5. 限制上传文件大小
6. 完善配置参数
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 54 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 66 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 57 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 121 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 69 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 60 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+115 -129
View File
@@ -1,114 +1,104 @@
import datetime
import os
import uuid
import threading
import random
import asyncio
from pathlib import Path
from fastapi import FastAPI, Depends, UploadFile, Form, File
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
from starlette.requests import Request
from starlette.responses import HTMLResponse, FileResponse
from starlette.staticfiles import StaticFiles
from sqlalchemy import or_, select, update, delete
from sqlalchemy import select, update, func
from sqlalchemy.ext.asyncio.session import AsyncSession
import settings
from database import get_session, Codes, init_models, engine
from utils import delete_expire_files, storage, get_code, error_ip_limit, upload_ip_limit
from database import get_session, Codes, init_models, Values
from depends import admin_required
app = FastAPI(debug=settings.DEBUG)
# 实例化FastAPI
app = FastAPI(debug=settings.DEBUG, docs_url=None, redoc_url=None)
# 数据存储文件夹
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")
# 静态文件夹,这个固定就行了,静态资源都放在这里
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)
.replace('{{keywords}}', settings.KEYWORDS) \
.replace("'{{fileSizeLimit}}'", str(settings.FILE_SIZE_LIMIT))
# 管理页面
admin_html = open('templates/admin.html', 'r', encoding='utf-8').read() \
.replace('{{title}}', settings.TITLE) \
.replace('{{description}}', settings.DESCRIPTION) \
.replace('{{keywords}}', settings.KEYWORDS)
error_ip_count = {}
def delete_file(files):
for file in files:
if file['type'] != 'text':
os.remove(DATA_ROOT / file['text'].lstrip(STATIC_URL + '/'))
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()
await asyncio.to_thread(delete_file, [{'type': old.type, 'text': old.text} for old in exps])
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)
def get_file_name(key, ext, file, file_bytes):
now = datetime.datetime.now()
path = DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
name = f'{key}.{ext}'
if not path.exists():
path.mkdir(parents=True)
filepath = path / name
with open(filepath, 'wb') as f:
f.write(file_bytes)
return f"{STATIC_URL}/{filepath.relative_to(DATA_ROOT)}", file.content_type, file.filename
@app.get(f'/{settings.ADMIN_ADDRESS}')
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面')
async def admin():
return HTMLResponse(admin_html)
@app.post(f'/{settings.ADMIN_ADDRESS}')
async def admin_post(request: Request, s: AsyncSession = Depends(get_session)):
if request.headers.get('pwd') == settings.ADMIN_PASSWORD:
query = select(Codes)
codes = (await s.execute(query)).scalars().all()
return {'code': 200, 'msg': '查询成功', 'data': codes}
else:
return {'code': 404, 'msg': '密码错误'}
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='查询数据库列表')
async def admin_post(page: int = Form(default=1), size: int = Form(default=10), s: AsyncSession = Depends(get_session)):
codes = (await s.execute(select(Codes).offset((page - 1) * size).limit(size))).scalars().all()
total = (await s.execute(select(func.count(Codes.id)))).scalar()
return {'detail': '查询成功', 'data': codes, 'paginate': {
'page': page,
'size': size,
'total': total
}}
@app.delete(f'/{settings.ADMIN_ADDRESS}')
async def admin_delete(request: Request, code: str, s: AsyncSession = Depends(get_session)):
if request.headers.get('pwd') == settings.ADMIN_PASSWORD:
query = select(Codes).where(Codes.code == code)
file = (await s.execute(query)).scalars().first()
await asyncio.to_thread(delete_file, [{'type': file.type, 'text': file.text}])
await s.delete(file)
await s.commit()
return {'code': 200, 'msg': '删除成功'}
@app.patch(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='修改数据库数据')
async def admin_patch(request: Request, s: AsyncSession = Depends(get_session)):
# 从数据库获取系统配置
# 如果不存在config这个key,就创建一个
config = (await s.execute(select(Values).filter(Values.key == 'config'))).scalar_one_or_none()
if not config:
s.add(Values(key='config', value=await request.json()))
else:
return {'code': 404, 'msg': '密码错误'}
await s.execute(update(Values).where(Values.key == 'config').values(value=await request.json()))
await s.commit()
return {'detail': '修改成功'}
@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()
# 如果记录存在,并且不是文本
if file and file.type != 'text':
# 删除文件
await storage.delete_file(file.text)
# 删除数据库记录
await s.delete(file)
await s.commit()
return {'detail': '删除成功'}
@app.get('/config', description='获取系统配置', dependencies=[Depends(admin_required)])
async def config(s: AsyncSession = Depends(get_session)):
# 从数据库获取系统配置
data = (await s.execute(select(Values).filter(Values.key == 'config'))).scalar_one_or_none()
return {'detail': '获取成功', 'data': data.value}
@app.get('/')
@@ -116,76 +106,81 @@ async def index():
return HTMLResponse(index_html)
def check_ip(ip):
# 检查ip是否被禁止
if ip in error_ip_count:
if error_ip_count[ip]['count'] >= settings.ERROR_COUNT:
if error_ip_count[ip]['time'] + datetime.timedelta(minutes=settings.ERROR_MINUTE) > datetime.datetime.now():
return False
else:
error_ip_count.pop(ip)
return True
def ip_error(ip):
ip_info = error_ip_count.get(ip, {'count': 0, 'time': datetime.datetime.now()})
ip_info['count'] += 1
error_ip_count[ip] = ip_info
return ip_info['count']
@app.get('/banner')
async def banner(s: AsyncSession = Depends(get_session)):
# 数据库查询config
config = (await s.execute(select(Values).filter(Values.key == 'config'))).scalar_one_or_none()
# 如果存在config,就返回config的value
if config and config.value.get('banners'):
return {
'detail': '查询成功',
'data': config.value['banners']
}
# 如果不存在config,就返回默认的banner
return {
'detail': 'banner',
'data': [{
'text': 'FileCodeBox',
'url': 'https://github.com/vastsa/FileCodeBox',
'src': '/static/banners/img_1.png'
}, {
'text': 'FileCodeBox',
'url': 'https://www.lanol.cn',
'src': '/static/banners/img_2.png'
}]
}
@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()
if info:
if info.type == 'text':
return {'code': code, 'msg': '查询成功', 'data': info.text}
else:
return FileResponse(DATA_ROOT / info.text.lstrip(STATIC_URL + '/'), filename=info.name)
# 如果记录不存在,IP错误次数+1
if not info:
error_ip_limit.add_ip(ip)
raise HTTPException(status_code=404, detail="口令不存在,次数过多将被禁止访问")
# 如果是文本,直接返回
if info.type == 'text':
return {'detail': '查询成功', 'data': info.text}
# 如果是文件,返回文件
else:
return {'code': 404, 'msg': '口令不存在'}
filepath = await storage.get_filepath(info.text)
return FileResponse(filepath, filename=info.name)
@app.post('/')
async def index(request: Request, code: str, s: AsyncSession = Depends(get_session)):
ip = request.client.host
if not check_ip(ip):
return {'code': 404, 'msg': '错误次数过多,请稍后再试'}
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:
return {'code': 404, 'msg': f'取件码错误,错误{settings.ERROR_COUNT - ip_error(ip)}次将被禁止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:
threading.Thread(target=delete_file, args=([{'type': info.type, 'text': info.text}],)).start()
await s.delete(info)
await s.commit()
return {'code': 404, 'msg': '取件码已过期,请联系寄件人'}
count = info.count - 1
query = update(Codes).where(Codes.id == info.id).values(count=count)
await s.execute(query)
raise HTTPException(status_code=404, detail="取件码已失效,请联系寄件人")
await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
await s.commit()
if info.type != 'text':
info.text = f'/select?code={code}'
return {
'code': 200,
'msg': '取件成功,请点击"取"查看',
'detail': f'取件成功,文件将在{settings.DELETE_EXPIRE_FILES_INTERVAL}分钟后删除',
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
}
@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)):
@app.post('/share', dependencies=[Depends(admin_required)], description='分享文件')
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:
return {'code': 404, 'msg': '最大有效天数为7天'}
if value > settings.MAX_DAYS:
raise HTTPException(status_code=400, detail=f"最大有效天数为{settings.MAX_DAYS}天")
exp_time = datetime.datetime.now() + datetime.timedelta(days=value)
exp_count = -1
elif style == '1':
if value < 1:
return {'code': 404, 'msg': '最小有效次数为1次'}
raise HTTPException(status_code=400, detail="最小有效次数为1次")
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = value
else:
@@ -193,28 +188,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 = file.file.read()
size = len(file_bytes)
size = await storage.get_size(file)
if size > settings.FILE_SIZE_LIMIT:
return {'code': 404, 'msg': '文件过大'}
_text, _type, name = get_file_name(key, file.filename.split('.')[-1], file, file_bytes)
raise HTTPException(status_code=400, detail="文件过大")
_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 {
'code': 200,
'msg': '分享成功,请点击文件箱查看取件码',
'detail': '分享成功,请点击取件码按钮查看上传列表',
'data': {'code': code, 'key': key, 'name': name, 'text': _text}
}
@@ -222,4 +208,4 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
if __name__ == '__main__':
import uvicorn
uvicorn.run('main:app', host='0.0.0.0', port=12345)
uvicorn.run('main:app', host='0.0.0.0', port=settings.PORT, reload=settings.DEBUG)
+108 -77
View File
@@ -1,126 +1,157 @@
# 文件快递柜
<div style="text-align: center">
<h1>文件快递柜-轻量</h1>
<h2>FileCoxBox-Lite</h2>
<p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p>
</div>
## 解决问题
---
很多时候,我们都想将一些文件或文本传送给别人,或者跨端传递一些信息,但是我们又不想为了分享,而去下载一些七里八里的软件,这时候,我们就可以使用口令传送箱,像拿快递一样取文件。
[简体中文](./readme.md) | [English](./readme_en.md)
## 主要特色
- [x] 轻量简洁,Fastapi+sqlite3
- [x] 拖拽,复制粘贴上传
- [x] 文件口令传输,生成二维码
- [x] 分享文件:多种上传方式供你选择
- [x] 分享文本:直接复制粘贴直接上传
- [x] 防爆破:错误五次拉黑十分钟
- [x] 完全匿名:不记录任何信息
- [x] 无需注册:无需注册,无需登录
- [x] Sqlite3数据库:无需安装数据库
- [x] 可以加get参数code,这样打开就会读取取件码如:http://host?code=12345
- [x] 管理面板:简单列表页删除违规文件
- [x] 口令使用次数,口令有效期,二维码分享
- [x] 轻量简洁:Fastapi+Sqlite3+Vue2+ElementUI
- [x] 轻松上传:复制粘贴,拖拽选择
- [x] 多种类型:文本,文件
- [x] 防止爆破:错误次数限制
- [x] 防止滥用:IP限制上传次数
- [x] 口令分享:随机口令,存取文件,自定义次数以及有效期
- [x] 匿名分享:无需注册,无需登录
- [x] 管理面板:查看所有文件,删除文件
- [x] 一键部署:docker一键部署
## 更新记录
## 未来规划
### 2022年12月10日 01:56:43
2022年12月14日
1. 管理面板已新增,一如既往的极简,只有删除
2. 二维码图片(调用的网络接口,如果离线环境将无法使用,一切为了极简)
这个项目的灵感来源于丁丁快传,然后写了这么一个基于本机存储的快传系统,本系统主要是以轻量,单用户,离线环境(`私有化`
)为主,因此也不需要加太多东西,所以其实这个项目到这基本功能已经完成了,剩下的就是维护和完善现有功能。
### 2022年12月10日 21:10:00
也不会再加入新的大功能了,如果有新的功能的话,那就是我们的Pro版本了,当然也是继续开源的,能和@veoco一起开源挺荣幸的,在他的代码中我学到了许多,此前我基本上是使用Django那一套,对Fastapi仅限于使用,他的许多写法让我受益匪浅,也让我对Fastapi有了更深的了解,所以我也会在Pro版本中使用Fastapi。
1. 取件码有效期,取件码使用次数
2. 优化代码逻辑
3. 限制上传文件大小
4. 完善配置参数
根据目前一些使用反馈来说,希望加入登录功能,还有多存储引擎等,欢迎各位继续提意见,加入我们共同开发。
### 2022年12月10日 23:50:00
如果你有更好的想法和建议欢迎提issue。
1. 修复取件不显示码的问题
2. 修复文件次数为1时,文件被删除的问题
## 预览
## 系统截图
### 例站
### 2022年12月11日 14:55:00
1. 隐藏文件真实地址
### 取件
![取件](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img.png)
![取件](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_1.png)
[https://share.lanol.cn](https://share.lanol.cn)
### 寄件
![取件](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png)
![取件](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_3.png)
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_1.png" alt="寄文件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png" alt="寄文本">
</td>
</tr>
<tr style="width: 100%;">
<td colspan="2" style="width: 100%;">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_3.png" alt="寄文本">
</td>
</tr>
</table>
### 管理面板
### 取件
![取件](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_4.png)
![取件](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png)
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_6.png" alt="取件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png" alt="取件码错误">
</td>
</tr>
<tr style="width: 100%;">
<td colspan="2" style="width: 100%;">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_4.png" alt="取文件">
</td>
</tr>
</table>
## 部署教程
### 管理
https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v
![管理](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_7.png)
## 部署方式
为持久化,不管怎么样,先第一步,建一个文件夹,然后再下载代码
### Docker一键部署
```bash
mkdir /opt/FileCodeBox
cd /opt/FileCodeBox
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
```
新建一个`.env`文件
### 其他方式
```bash
vi .env
```
将下列字段内容替换成你自己的
仅供参考,历史版本->[部署文档](https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v)
## 配置文件
如果需要修改配置,可以将该文件放在`/opt/FileCodeBox/`目录下,并命名为`.env`,然后重启容器即可。
如果不是Docker,则需要在项目同目录下新建一个`data`文件夹,然后在创建`.env`文件
```dotenv
DEBUG=False
# 端口
PORT=12345
# Sqlite数据库文件
DATABASE_URL=sqlite+aiosqlite:///database.db
# 静态文件夹
DATA_ROOT=./static
# 静态文件夹URL
STATIC_URL=/static
# 开启上传
ENABLE_UPLOAD=True
# 错误次数
ERROR_COUNT=5
# 错误限制分钟数
ERROR_MINUTE=10
# 上传次数
UPLOAD_COUNT=60
# 上传限制分钟数
UPLOAD_MINUTE=1
# 删除过期文件的间隔(分钟)
DELETE_EXPIRE_FILES_INTERVAL=10
# 管理地址
ADMIN_ADDRESS=admin
# 管理密码
ADMIN_PASSWORD=admin
# 文件大小限制,默认10MB
FILE_SIZE_LIMIT=10
# 网站标题
TITLE=文件快递柜
# 网站描述
DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
# 网站关键词
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
```
### 服务端部署
1. 安装Python3
2. 拉取代码,解压缩
3. 安装依赖包:`pip install -r requirements.txt`
4. 运行` uvicorn main:app --host 0.0.0.0 --port 12345`
5. 然后你自己看怎么进程守护吧
### 宝塔部署
1. 安装宝塔Python Manager
2. 然后你自己看着填吧
### Docker部署
```bash
mkdir "/opt/FileCodeBox"
cd "/opt/FileCodeBox"
wget https://github.com/vastsa/FileCodeBox/releases/download/Main/code.zip
unzip code.zip
docker build --file Dockerfile --tag filecodebox .
docker run -d -p 12345:12345 --name filecodebox --volume /opt/FileCodeBox:/app filecodebox
# 存储引擎
STORAGE_ENGINE=filesystem
```
## 状态
![Alt](https://repobeats.axiom.co/api/embed/7a6c92f1d96ee57e6fb67f0df371528397b0c9ac.svg "Repobeats analytics image")
## 赞赏
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%;text-align: center;">
支付宝
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_9.png" alt="支付宝">
</td>
<td style="width: 50%;text-align: center">
微信
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_8.png" alt="微信">
</td>
</tr>
</table>
## 免责声明
本项目开源仅供学习使用,不得用于商业用途以及任何违法用途,否则后果自负,与本人无关。使用请保留项目地址谢谢。
本项目开源仅供学习使用,不得用于任何违法用途,否则后果自负,与本人无关。使用请保留项目地址谢谢。
+164
View File
@@ -0,0 +1,164 @@
<div style="text-align: center">
<h1>File Express Cabinet - Lite</h1>
<h2>FileCodeBox - Lite</h2>
<p><em>share text and files with anonymous passwords, and take files like express delivery </em></p>
</div>
---
[简体中文](./readme.md) | [English](./readme_en.md)
## Main features
- [x] lightweight and simple: Fastapi + Sqlite3 + Vue2 + ElementUI
- [x] easy upload: copy and paste, drag and drop
- [x] multiple types: Text, File
- [x] explosion Prevention: error count limit
- [x] prevent abuse: IP address limits the number of uploads
- [x] password sharing: random password, file access, custom times, and validity period
- [x] anonymous sharing: no registration, no login
- [x] management Panel: View all files and delete them
- [x] one-click deployment: docker one-click deployment
## Future Plan
December 14, 2022
This project is mainly light-weight, mainly single-user, offline environment, so there is no need to add too many
things, so in fact, the basic functions of this project have been completed, and the rest is to maintain and improve the
existing functions.
No new major functions will be added. If there are new functions, it will be our Pro version. Of course, it will
continue to be open source. It is an honor to be open source with @veoco. I learned from his code Many, I basically used
the Django set before, and only used Fastapi. Many of his writing methods have benefited me a lot, and I have a deeper
understanding of Fastapi, so I will also use Fastapi in the Pro version .
According to some current feedback, I hope to add multi-user functions and multi-storage engines, etc. Welcome to
continue to give comments and join us in joint development.
If you have better ideas and suggestions, welcome to file an issue.
## Preview
### Demo
[https://share.lanol.cn](https://share.lanol.cn)
### Send
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_1.png" alt="寄文件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png" alt="寄文本">
</td>
</tr>
<tr style="width: 100%;">
<td colspan="2" style="width: 100%;">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_3.png" alt="寄文本">
</td>
</tr>
</table>
### Receive
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_6.png" alt="取件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png" alt="取件码错误">
</td>
</tr>
<tr style="width: 100%;">
<td colspan="2" style="width: 100%;">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_4.png" alt="取文件">
</td>
</tr>
</table>
### Manage
![管理](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_7.png)
## Deployment method
### One-click Docker deployment
```bash
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
```
### Other methods
For reference only, historical version->[部署文档](https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v)
## Configuration file
if you need to modify the configuration, you can put the file in `/opt/FileCodeBox/` directory and name it `.env` , and
then restart the container.
If it is not Docker, you need to create a `data` folder in the same directory as the project, and then create a `.env`
file
```dotenv
# 端口
PORT=12345
# Sqlite数据库文件
DATABASE_URL=sqlite+aiosqlite:///database.db
# 静态文件夹
DATA_ROOT=./static
# 静态文件夹URL
STATIC_URL=/static
# 开启上传
ENABLE_UPLOAD=True
# 错误次数
ERROR_COUNT=5
# 错误限制分钟数
ERROR_MINUTE=10
# 上传次数
UPLOAD_COUNT=60
# 上传限制分钟数
UPLOAD_MINUTE=1
# 删除过期文件的间隔(分钟)
DELETE_EXPIRE_FILES_INTERVAL=10
# 管理地址
ADMIN_ADDRESS=admin
# 管理密码
ADMIN_PASSWORD=admin
# 文件大小限制,默认10MB
FILE_SIZE_LIMIT=10
# 网站标题
TITLE=文件快递柜
# 网站描述
DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
# 网站关键词
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
# 存储引擎
STORAGE_ENGINE=filesystem
```
## Status
![Alt](https://repobeats.axiom.co/api/embed/7a6c92f1d96ee57e6fb67f0df371528397b0c9ac.svg "Repobeats analytics image")
## Appreciate
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%;text-align: center;">
支付宝
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_9.png" alt="支付宝">
</td>
<td style="width: 50%;text-align: center">
微信
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_8.png" alt="微信">
</td>
</tr>
</table>
## Disclaimer
this project is open source for learning only and cannot be used for any illegal purposes. Otherwise, you will be
responsible for the consequences and have nothing to do with yourself. Please keep the project address. Thank you.
+34 -16
View File
@@ -1,27 +1,45 @@
from starlette.config import Config
config = Config(".env")
# 配置文件.env
# 请将.env移动至data目录,方便docker部署
config = Config("data/.env")
# 是否开启DEBUG模式
DEBUG = config('DEBUG', cast=bool, default=False)
DATABASE_URL = config('DATABASE_URL', cast=str, default="sqlite+aiosqlite:///database.db")
DATA_ROOT = config('DATA_ROOT', cast=str, default="./static")
# 端口
PORT = config('PORT', cast=int, default=12345)
# Sqlite数据库文件
DATABASE_FILE = config('DATABASE_FILE', cast=str, default='data/database.db')
# Sqlite套接字
DATABASE_URL = config('DATABASE_URL', cast=str, default=f"sqlite+aiosqlite:///{DATABASE_FILE}")
# 数据存储文件夹,文件就不暴露在静态资源里面了
DATA_ROOT = './data/' + config('DATA_ROOT', cast=str, default=f"static")
# 静态文件夹URL
STATIC_URL = config('STATIC_URL', cast=str, default="/static")
# 开启上传
ENABLE_UPLOAD = config('ENABLE_UPLOAD', cast=bool, default=False)
# 最长天数
MAX_DAYS = config('MAX_DAYS', cast=int, default=7)
# 错误次数
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)
# 删除过期文件的间隔(分钟)
DELETE_EXPIRE_FILES_INTERVAL = config('DELETE_EXPIRE_FILES_INTERVAL', cast=int, default=10)
# 管理地址
ADMIN_ADDRESS = config('ADMIN_ADDRESS', cast=str, default="admin")
ADMIN_PASSWORD = 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")
-1
View File
@@ -1 +0,0 @@
var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c<a.length&&0==a[c];)c++;this.num=new Array(a.length-c+b);for(var d=0;d<a.length-c;d++)this.num[d]=a[d+c]}function j(a,b){this.totalCount=a,this.dataCount=b}function k(){this.buffer=[],this.length=0}function m(){return"undefined"!=typeof CanvasRenderingContext2D}function n(){var a=!1,b=navigator.userAgent;return/android/i.test(b)&&(a=!0,aMat=b.toString().match(/android ([0-9]\.[0-9])/i),aMat&&aMat[1]&&(a=parseFloat(aMat[1]))),a}function r(a,b){for(var c=1,e=s(a),f=0,g=l.length;g>=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=new Array(this.moduleCount);for(var e=0;e<this.moduleCount;e++)this.modules[d][e]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,c),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f<this.modules.length;f++)for(var g=f*e,h=0;h<this.modules[f].length;h++){var i=h*e,j=this.modules[f][h];j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}return d},setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(var b=8;b<this.moduleCount-8;b++)null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)},setupPositionAdjustPattern:function(){for(var a=f.getPatternPosition(this.typeNumber),b=0;b<a.length;b++)for(var c=0;c<a.length;c++){var d=a[b],e=a[c];if(null==this.modules[d][e])for(var g=-2;2>=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g<a.length&&(j=1==(1&a[g]>>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,cLine truncated
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

File renamed without changes.
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

+61
View File
@@ -0,0 +1,61 @@
import os
import asyncio
from datetime import datetime
from pathlib import Path
from typing import BinaryIO
from fastapi import UploadFile
import settings
class FileSystemStorage:
DATA_ROOT = Path(settings.DATA_ROOT)
STATIC_URL = settings.STATIC_URL
NAME = "filesystem"
async def get_filepath(self, text: str):
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
async def get_text(self, file: UploadFile, key: str):
ext = file.filename.split('.')[-1]
now = datetime.now()
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
if not path.exists():
path.mkdir(parents=True)
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT)}"
return text
@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
@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 = {
"filesystem": FileSystemStorage
}
+183 -37
View File
@@ -5,22 +5,37 @@
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/assert/index.css">
<link rel="stylesheet" href="/static/asserts/index.css">
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
<title>后台管理-{{title}}</title>
<meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/>
<meta name="template" content="Lan"/>
<script src="/static/asserts/vue.min.js"></script>
<script src="/static/asserts/index.js"></script>
<style>
.el-menu-demo {
text-align: center;
}
body {
background: #f5f5f5;
}
</style>
</head>
<body>
<div id="app">
<el-row v-if="login" :gutter="10">
<el-col :xs="0" :sm="4" :md="4" :lg="4" :xl="4">
&nbsp;
<el-col :span="24" style="text-align: center">
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
<el-menu-item index="2">文件管理</el-menu-item>
<el-menu-item index="3">系统配置</el-menu-item>
</el-menu>
</el-col>
<el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
<el-card>
<el-empty v-if="files.length===0" description="暂时还没有文件"></el-empty>
<el-col v-if="activeIndex === '2'">
<el-card style="height: 80vh;overflow: scroll;margin-bottom: 1rem">
<el-empty v-if="files.length === 0" description="暂时还没有文件"></el-empty>
<el-card v-for="file in files" :key="file.code">
<el-row>
<el-col :span="20">
@@ -29,7 +44,7 @@
<div>文件名:${ file.name }</div>
<div>次&nbsp;&nbsp; 数:${ file.count }</div>
<div>到&nbsp;&nbsp; 期:${ file.exp_time.slice(0,19) }</div>
<div v-if="file.name==='分享文本'">
<div v-if="file.type==='text'">
<span>内&nbsp;&nbsp; 容:${ file.text }</span>
</div>
<div v-else>
@@ -46,8 +61,87 @@
</el-row>
</el-card>
</el-card>
<el-pagination
background
style="text-align: center"
layout="prev, pager, next, sizes"
:page-size="paginate.page_size"
@current-change="updatePage"
@size-change="updateSize"
:total="paginate.total"
>
</el-pagination>
</el-col>
<el-col v-if="activeIndex === '3'">
<el-form ref="form" style="width: 50%;margin:2rem auto" :model="config" label-width="200px">
<!--? <el-form-item label="错误限制">-->
<!--? <div>-->
<!--? 间隔:-->
<!--? <el-input-number v-model="config.error_count" :min="1"></el-input-number>-->
<!--? 分钟-->
<!--? </div>-->
<!--? <div>-->
<!--? 数量:-->
<!--? <el-input-number v-model="config.error_minute" :min="1"></el-input-number>-->
<!--? 个-->
<!--? </div>-->
<!--? </el-form-item>-->
<!--? <el-form-item label="上传限制">-->
<!--? <div>-->
<!--? 开启上传:-->
<!--? <el-switch-->
<!--? v-model="config.enable_upload"-->
<!--? active-color="#13ce66"-->
<!--? inactive-color="#ff4949">-->
<!--? </el-switch>-->
<!--? </div>-->
<!--? <div>-->
<!--? 间隔:-->
<!--? <el-input-number v-model="config.upload_minute" :min="1"></el-input-number>-->
<!--? 分钟-->
<!--? </div>-->
<!--? <div>-->
<!--? 数量:-->
<!--? <el-input-number v-model="config.upload_count" :min="1"></el-input-number>-->
<!--? 个-->
<!--? </div>-->
<!--? <div>-->
<!--? 最长:-->
<!--? <el-input-number v-model="config.max_days" :min="1"></el-input-number>-->
<!--? 天-->
<!--? </div>-->
<!--? <div>-->
<!--? 大小:-->
<!--? <el-input-number v-model="config.file_size_limit" :min="1"></el-input-number>-->
<!--? MB-->
<!--? </div>-->
<!--? </el-form-item>-->
<!--? <el-form-item label="删除间隔">-->
<!--? 时长:-->
<!--? <el-input-number v-model="config.delete_expire_files_interval"></el-input-number>-->
<!--? 分钟-->
<!--? </el-form-item>-->
<!--? <el-form-item label="管理员密码">-->
<!--? <el-input v-model="config.admin_password" type="password"></el-input>-->
<!--? </el-form-item>-->
<el-form-item v-for="(banner,index) in config.banners" :label="'Banner'+ (index+1)">
<div style="width: 50%;display: inline-block">
<el-input v-model="banner.text" placeholder="文本"></el-input>
<el-input v-model="banner.url" placeholder="跳转链接"></el-input>
<el-input v-model="banner.src" placeholder="图片路径"></el-input>
</div>
<div style="display: inline-block">
<el-button type="danger" @click="deleteBanner(index)">删除</el-button>
</div>
</el-form-item>
<el-form-item>
<el-button size="mini" @click="addBanner" type="primary">新增Banner</el-button>
</el-form-item>
<el-form-item>
<el-button @click="updateConfig" type="primary">更新</el-button>
</el-form-item>
</el-form>
</el-col>
<el-col :xs="0" :sm="4" :md="4" :lg="4" :xl="4">&nbsp;</el-col>
</el-row>
<div v-else style="width: 250px;text-align: center;margin: 40vh auto">
<el-input v-model="pwd" placeholder="请输入登录密码">
@@ -57,9 +151,7 @@
</div>
</body>
<script src="/static/assert/vue.min.js"></script>
<script src="/static/assert/index.js"></script>
<script src="/static/assert/axios.min.js"></script>
<script src="/static/asserts/axios.min.js"></script>
<script>
new Vue({
el: '#app',
@@ -68,12 +160,25 @@
return {
login: false,
pwd: '',
files: [],
activeIndex: '2',
config: {
error_count: 0,
file_size: 0,
admin_pwd: 'admin'
}
// enable_upload: true,
// max_days: 7,
// error_count: 3,
// error_minute: 10,
// upload_count: 10,
// upload_minute: 10,
// delete_expire_files_interval: 10,
// admin_password: 'admin',
// file_size_limit: 10,
banners: []
},
files: [],
paginate: {
page: 1,
size: 10,
total: 0,
},
};
},
mounted: function () {
@@ -81,37 +186,78 @@
if (pwd) {
login = true;
this.pwd = pwd;
axios.get('/config', {
headers: {
pwd: pwd
}
}).then(res => {
console.log(res.data.data)
this.config = res.data.data;
});
this.loginAdmin();
}
},
methods: {
loginAdmin: function () {
axios.post('', {}, {'headers': {'pwd': this.pwd}}).then(res => {
if (res.data.code === 200) {
this.files = res.data.data;
this.login = true;
localStorage.setItem('pwd', this.pwd);
} else {
localStorage.clear()
this.$message({
message: res.data.msg,
type: 'error'
});
}
updateSize: function (value) {
this.paginate.size = value;
this.loginAdmin();
},
updatePage: function (value) {
this.paginate.page = value;
this.loginAdmin();
},
deleteBanner: function (index) {
this.config.banners.splice(index, 1);
},
addBanner: function () {
this.config.banners.push({
'url': '',
'src': '',
'text': '',
})
},
updateConfig: function () {
axios.patch('', this.config, {
'headers': {
'pwd': this.pwd,
'Content-Type': 'multipart/json'
}
}).then(res => {
this.$message({
message: res.data.detail,
type: 'success'
});
})
},
loginAdmin: function () {
axios.post('', this.paginate, {
'headers': {
'pwd': this.pwd,
'Content-Type': 'multipart/form-data'
}
}).then(res => {
this.paginate = res.data.paginate;
this.files = res.data.data
this.login = true;
localStorage.setItem('pwd', this.pwd);
}).catch(e => {
localStorage.clear()
this.$message({'message': e.response.data.detail, 'type': 'error'});
});
},
handleSelect(key, keyPath) {
this.activeIndex = key;
},
deleteFile: function (code) {
axios.delete('?code=' + code, {'headers': {'pwd': this.pwd}}).then(res => {
if (res.data.code === 200) {
this.files = this.files.filter(item => item.code !== code)
this.$message({
message: res.data.msg,
type: 'success'
});
}
this.files = this.files.filter(item => item.code !== code)
this.$message({
message: res.data.detail,
type: 'success'
});
})
},
}
})
</script>
</html>
</html>
+239 -141
View File
@@ -5,13 +5,22 @@
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/assert/index.css">
<link rel="stylesheet" href="/static/asserts/index.css">
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
<title>{{title}}</title>
<meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/>
<meta name="template" content="Lan-V1.4.2"/>
<meta name="template" content="Lan-V1.5.8"/>
<meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/>
<meta name="template" content="Lan-V1.5.8"/>
<style>
body {
background: #f5f5f5;
}
.qu .el-button {
width: 100px;
height: 100px;
@@ -25,91 +34,140 @@
margin: 1rem 0;
font-size: 30px;
font-weight: bold;
border-radius: 20px;
}
.el-card {
border-radius: 20px;
}
</style>
<script src="/static/asserts/vue.min.js"></script>
<script src="/static/asserts/index.js"></script>
</head>
<body>
<div id="app" style="text-align: center;">
<el-row v-if="tool === 0" class="qu" style="width:400px;margin: 6vh auto 0 auto">
<div id="app" style="text-align: center">
<el-row v-if="pageNum === 0" class="qu" style="width:400px;height: 596px;margin: 6vh auto 0 auto">
<el-card style="padding-bottom: 1rem">
<el-col :span="24">
<el-input autofocus @input="inputing" clearable v-model:value="code" maxlength="5"
:disabled="inout_disable"
placeholder="请输入取件码"></el-input>
<el-input round autofocus @change="changeInput" clearable v-model:value="code" maxlength="5"
:disabled="inputDisable" placeholder="请输入五位取件码">
</el-input>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('1')">1</el-button>
<el-button round @click="listenInput('1')">1</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('2')">2</el-button>
<el-button round @click="listenInput('2')">2</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('3')">3</el-button>
<el-button round @click="listenInput('3')">3</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('4')">4</el-button>
<el-button round @click="listenInput('4')">4</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('5')">5</el-button>
<el-button round @click="listenInput('5')">5</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('6')">6</el-button>
<el-button round @click="listenInput('6')">6</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('7')">7</el-button>
<el-button round @click="listenInput('7')">7</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('8')">8</el-button>
<el-button round @click="listenInput('8')">8</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('9')">9</el-button>
<el-button round @click="listenInput('9')">9</el-button>
</el-col>
<el-col :span=8>
<el-button @click="tool=1">寄</el-button>
<el-button round @click="pageNum=1">
<div style="height: 10px" class="el-icon-upload2"></div>
</el-button>
</el-col>
<el-col :span=8>
<el-button @click="inputNumber('0')">0</el-button>
<el-button round @click="listenInput('0')">0</el-button>
</el-col>
<el-col :span=8>
<el-button @click="quDrawer=true">取</el-button>
<el-button round @click="quDrawer=true">
<div class="el-icon-takeaway-box"></div>
</el-button>
</el-col>
</el-card>
</el-row>
<el-row v-else style="width:400px;margin: 20vh auto 0 auto">
<el-col :span="24" style="margin: 1rem 0">
<el-card>
<div style="margin-bottom: 1rem">
<el-radio-group v-model="destoryData.style">
<el-radio label="1">次数</el-radio>
<el-radio label="2">天数</el-radio>
</el-radio-group>
<el-input-number
placeholder="输入数量,默认1"
style="margin-left: 1rem" v-model="destoryData.value" controls-position="right" :min="1">
</el-input-number>
<el-row v-else style="width:400px;margin: 6vh auto 0 auto">
<el-col :span="24">
<el-card :body-style="{ padding: '0px 0px 20px 0px' }">
<div class="block" style="margin-bottom: 1rem">
<el-carousel height="150px">
<el-carousel-item v-for="item in banners" :key="item">
<a :href="item.url" target="_blank">
<img class="image" style="width: 400px" :src="item.src" :alt="item.text">
</a>
</el-carousel-item>
</el-carousel>
</div>
<el-row>
<el-input style="width: 190px" placeholder="数量" v-model="uploadData.value"
class="input-with-select">
<el-select style="width: 75px" v-model="uploadData.style" slot="prepend" placeholder="请选择">
<el-option label="天数" value="2"></el-option>
<el-option label="次数" value="1"></el-option>
</el-select>
<el-button v-if="uploadData.style === '1'" slot="append" disabled>次</el-button>
<el-button v-else slot="append" disabled>天</el-button>
</el-input>
<el-radio-group style="margin-left: 18px" v-model="uploadData.type">
<el-radio label="1">
文件
</el-radio>
<el-radio label="2">
文本
</el-radio>
</el-radio-group>
</el-row>
<el-upload
v-if="uploadData.type === '1'"
drag
action="/share"
multiple
:data="destoryData"
style="margin: 1rem 0;"
:data="uploadData"
:before-upload="beforeUpload"
:headers="{'pwd':pwd}"
:on-success="successUpload"
:on-error="errorUpload"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文字、文件拖、粘贴到此处,或<em>点击上传</em></div>
<div class="el-upload__text" style="font-size: 10px">天数<7或限制次数(24h后删除)</div>
<div class="el-upload__tip" slot="tip">
<el-button @click="tool=0">去取件</el-button>
<el-button @click="cunDrawer=true">取件码</el-button>
</div>
</el-upload>
<el-input
v-else
type="textarea"
:autosize="{ minRows: 8}"
style="margin: 1rem 0"
placeholder="请输入内容,使用按钮存入"
v-model="uploadData.text">
</el-input>
<div class="el-upload__tip">
<el-button round @click="pageNum=0">
<div class="el-icon-back"></div>
取件
</el-button>
<el-button round @click="jiDrawer=true">
<div class="el-icon-takeaway-box"></div>
我的文件
</el-button>
<el-button round v-if="uploadData.type === '2'" @click="toUploadData">
<div class="el-icon-upload2"></div>
存入
</el-button>
</div>
</el-card>
</el-col>
</el-row>
<div style="text-align: center; margin-top: 1rem;color: #606266">
<span> <a style="text-decoration: none;color: #606266" target="_blank"
href="https://github.com/vastsa/FileCodeBox">FileCodeBox</a></span>
</div>
<el-drawer
title="文件箱"
:visible.sync="quDrawer"
@@ -117,11 +175,11 @@
size="50%"
>
<el-card v-for="(file,index) in files" :key="index" class="box-card">
<div style="cursor: pointer;text-align: left">
<div style="cursor: pointer;text-align: left;margin-left: 2rem">
<div>取件码:${ file.code }</div>
<div>文件名:${ file.name }</div>
<div v-if="file.name==='文本分享'">
<span>内&nbsp;&nbsp; 容:${ file.text }</span>
<span @click="copyText(file.text,1)">内&nbsp;&nbsp; 容:${ file.text }</span>
</div>
<div v-else>
<span>链&nbsp;&nbsp; 接:</span>
@@ -135,38 +193,40 @@
</el-drawer>
<el-drawer
title="文件箱"
:visible.sync="cunDrawer"
direction="btt"
:visible.sync="jiDrawer"
:direction="direction"
size="50%">
<el-card>
<el-empty v-if="files.length===0" description="请上传文件"></el-empty>
<el-card style="margin-top: 0.2rem" v-for="(file,index) in files" :key="index">
<el-row>
<el-col :span="20">
<el-col :span="15">
<el-row>
<el-col :span="24" style="line-height: 45px">
${ file.name }
</el-col>
<el-col :span="24">
取件码:<h1 style="margin: 0;display: inline">${ file.code }</h1>
取件码:
<h1 @click="copyText(file.code,0)" style="margin: 0;display: inline;cursor: pointer">
${ file.code }
</h1>
</el-col>
</el-row>
</el-col>
<el-col :span="4">
<img style="width: 80px;height: 80px;"
:src="qrcodeUrl(file)" :alt="file.code">
:src="qrcodeUrl(file)" alt="二维码" :alt="file.code">
</el-col>
</el-row>
</el-card>
</el-card>
</el-drawer>
<div style="text-align: center; margin-top: 1rem;color: #606266">
<a style="text-decoration: none;color: #606266" target="_blank" href="https://github.com/vastsa/FileCodeBox">FileCodeBox</a>
</div>
</div>
</body>
<script src="/static/assert/qrcode.min.js"></script>
<script src="/static/assert/vue.min.js"></script>
<script src="/static/assert/index.js"></script>
<script src="/static/assert/axios.min.js"></script>
<script src="/static/asserts/axios.min.js"></script>
<script>
new Vue({
el: '#app',
@@ -174,135 +234,173 @@
data: function () {
return {
code: '',
inout_disable: false,
files: [],
quDrawer: false,
cunDrawer: false,
jiDrawer: false,
direction: 'btt',
tool: 0,
destoryData: {
files: [],
pageNum: 0,
inputDisable: false,
fileSizeLimit: '{{fileSizeLimit}}',
pwd: localStorage.getItem('pwd') || '',
banners: [],
uploadData: {
style: '2',
value: 1
type: '1',
value: 1,
file: null,
text: ''
},
};
},
mounted: function () {
this.code = window.location.search.substring('code=='.length)
if (this.code) {
this.get_file();
// 进入网站时,判断Get是否有code参数,有则直接进行取件操作
let code = window.location.search.substring('code=='.length)
if (code) {
this.code = code
this.getFile()
}
// 剪切板监听
const that = this
document.addEventListener('paste', function (event) {
if (that.tool === 1) {
if (that.pageNum === 1) {
const items = event.clipboardData && event.clipboardData.items;
if (items && items.length) {
for (let i = 0; i < items.length; i++) {
if (items[i].kind === 'string') {
if (items[i].type.match(/^text\/plain/)) {
const FileData = new FormData();
if (items[i].type.match(/^text\/plain/) && that.uploadData.type !== '2') {
that.$message('剪切板文字正在上传,请稍等');
items[i].getAsString(function (str) {
FileData.append('text', str);
FileData.append('style', that.destoryData.style);
FileData.append('value', that.destoryData.value);
axios.post('/share', FileData)
.then(function (res) {
if (res.data.code === 200) {
that.$message({'message': res.data.msg, 'type': 'success'});
that.files.push(res.data.data)
} else {
that.$message({'message': res.data.msg, 'type': 'error'});
}
})
.catch(function (error) {
that.$message({'message': error.data.msg, 'type': 'error'});
});
that.uploadData.text = str;
that.toUploadData();
});
}
} else {
const file = items[i].getAsFile();
that.$message('剪切板文件正在上传,请稍等');
const FileData = new FormData();
FileData.append('file', file || '');
FileData.append('style', that.destoryData.style);
FileData.append('value', that.destoryData.value);
axios.post('/share', FileData).then(async res => {
if (res.data.code === 200) {
that.$message({'message': res.data.msg, 'type': 'success'});
that.files.push(res.data.data)
} else {
that.$message({'message': res.data.msg, 'type': 'error'});
}
})
that.uploadData.file = file
that.toUploadData();
}
}
}
}
});
// 获取Banner
axios.get('/banner').then(res => {
this.banners = res.data.data
})
},
watch: {
code: function (code) {
if (code.length === 5) {
this.inout_disable = true;
this.getFile();
}
}
},
methods: {
inputing: function (value) {
if (value.length === 5) {
this.inout_disable = true;
this.get_file();
}
},
get_file: function () {
const that = this;
axios.post('?code=' + this.code).then(function (response) {
if (response.data.code === 404) {
that.$message({
message: response.data.msg,
type: 'error'
});
} else {
that.files.push(response.data.data);
that.$message({
message: response.data.msg,
http: function (method, url, data = {}, config = {}) {
return new Promise((resolve, reject) => {
axios({
method: method,
url: url,
data: data,
...config
}).then(res => {
this.$message({
message: res.data.detail,
type: 'success'
});
that.quDrawer = true;
}
that.code = '';
that.inout_disable = false
}).catch(function (error) {
console.log(error);
});
resolve(res.data)
}).catch(err => {
this.$message({
message: err.response.data.detail,
type: 'error'
});
})
})
},
inputNumber: function (number) {
if (number === 'C') {
this.code = '';
} else if (number === 'X') {
this.code = this.code.substring(0, this.code.length - 1);
} else {
if (this.code.length < 5) {
this.code += number;
}
copyText: function (value, style = 1) {
if (style === 0) {
value = `我在分享了给你文件,取件码:${value},${window.location.href}?code=${value}`;
}
if (this.code.length === 5) {
this.inout_disable = true
this.get_file()
}
},
successUpload(response, file, fileList) {
if (response.code === 200) {
const input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.setAttribute('value', value);
document.body.appendChild(input);
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
this.$message({
message: response.msg,
message: '复制成功,快去分享给你的朋友吧',
type: 'success'
});
this.files.push(response.data);
} else {
this.$message({
message: response.msg,
type: 'error'
});
}
document.body.removeChild(input);
},
getFile: function () {
const that = this;
this.http('post', `?code=${that.code}`).then(res => {
that.quDrawer = true;
that.files.unshift(res.data);
})
that.code = '';
that.input_disable = false
},
qrcodeUrl(file) {
return 'https://api.qrserver.com/v1/create-qr-code/?data=' + window.location.origin + '/?code=' + file.code
},
listenInput: function (value) {
if (this.code.length < 5) {
this.code += value;
}
},
changeInput: function (value) {
this.code = value;
},
toUploadData: function () {
if (this.uploadData.text === '' && this.uploadData.file === null) {
this.$message({
message: '请先粘贴文字或者上传文件',
type: 'error'
});
} else {
this.http('post', '/share', this.uploadData, {
headers: {
'Content-Type': 'multipart/form-data',
'pwd': this.pwd
}
}).then(res => {
this.files.unshift(res.data);
this.jiDrawer = true;
this.uploadData.text = '';
this.uploadData.file = null;
});
}
},
successUpload(response, file, fileList) {
this.$message({
message: response.detail,
type: 'success'
});
this.files.unshift(response.data);
},
errorUpload(error, file, fileList) {
error = JSON.parse(error.message)
this.$message({
message: error.detail,
type: 'error'
});
},
beforeUpload: function (file) {
if (file.size > this.fileSizeLimit) {
this.$message({
message: `文件大小不能超过${this.fileSizeLimit/1024/1024}MB`,
type: 'error'
});
return false
}
}
}
})
</script>
</html>
</html>
+43
View File
@@ -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(settings.DELETE_EXPIRE_FILES_INTERVAL * 60)
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)