mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-20 21:57:02 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42dedfae1e | ||
|
|
cfd2989bc0 | ||
|
|
31b61a2f7a | ||
|
|
802b8a0a8f | ||
|
|
ef89de6294 | ||
|
|
74a835f8b6 | ||
|
|
2ef6c752ee | ||
|
|
bec3eb2ea1 | ||
|
|
ae7aa63e2a | ||
|
|
b999073da4 |
No files matched your search
+3
-5
@@ -1,13 +1,11 @@
|
||||
FROM python:3.9.5
|
||||
LABEL author="Lan"
|
||||
LABEL email="vast@tom.com"
|
||||
LABEL version="1.0"
|
||||
LABEL version="1.4.4"
|
||||
|
||||
|
||||
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 -i https://pypi.tuna.tsinghua.edu.cn/simple/
|
||||
RUN pip install -r requirements.txt
|
||||
EXPOSE 12345
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "12345"]
|
||||
CMD ["python","main.py"]
|
||||
@@ -10,6 +10,11 @@ engine = create_async_engine("sqlite+aiosqlite:///database.db")
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
async def init_models():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
|
||||
async def get_session():
|
||||
async with AsyncSession(engine, expire_on_commit=False) as s:
|
||||
yield s
|
||||
|
||||
@@ -3,6 +3,9 @@ import os
|
||||
import uuid
|
||||
import threading
|
||||
import random
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Depends, UploadFile, Form, File
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import HTMLResponse, FileResponse
|
||||
@@ -11,41 +14,33 @@ from starlette.staticfiles import StaticFiles
|
||||
from sqlalchemy import or_, select, update, delete
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
|
||||
from database import get_session, Codes
|
||||
import settings
|
||||
from database import get_session, Codes, init_models, engine
|
||||
|
||||
app = FastAPI()
|
||||
if not os.path.exists('./static'):
|
||||
os.makedirs('./static')
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
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")
|
||||
|
||||
|
||||
@app.on_event('startup')
|
||||
async def startup():
|
||||
await init_models()
|
||||
asyncio.create_task(delete_expire_files())
|
||||
|
||||
############################################
|
||||
# 需要修改的参数
|
||||
# 允许错误次数
|
||||
error_count = 5
|
||||
# 禁止分钟数
|
||||
error_minute = 10
|
||||
# 后台地址
|
||||
admin_address = 'admin'
|
||||
# 管理密码
|
||||
admin_password = 'admin'
|
||||
# 文件大小限制 10M
|
||||
file_size_limit = 1024 * 1024 * 10
|
||||
# 系统标题
|
||||
title = '文件快递柜'
|
||||
# 系统描述
|
||||
description = 'FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件'
|
||||
# 系统关键字
|
||||
keywords = 'FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件'
|
||||
############################################
|
||||
|
||||
index_html = open('templates/index.html', 'r', encoding='utf-8').read() \
|
||||
.replace('{{title}}', title) \
|
||||
.replace('{{description}}', description) \
|
||||
.replace('{{keywords}}', keywords)
|
||||
.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}}', title) \
|
||||
.replace('{{description}}', description) \
|
||||
.replace('{{keywords}}', keywords)
|
||||
.replace('{{title}}', settings.TITLE) \
|
||||
.replace('{{description}}', settings.DESCRIPTION) \
|
||||
.replace('{{keywords}}', settings.KEYWORDS)
|
||||
|
||||
error_ip_count = {}
|
||||
|
||||
@@ -53,7 +48,20 @@ error_ip_count = {}
|
||||
def delete_file(files):
|
||||
for file in files:
|
||||
if file['type'] != 'text':
|
||||
os.remove('.' + file['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):
|
||||
@@ -63,29 +71,26 @@ async def get_code(s: AsyncSession):
|
||||
return str(code)
|
||||
|
||||
|
||||
def get_file_name(key, ext, file):
|
||||
def get_file_name(key, ext, file, file_bytes):
|
||||
now = datetime.datetime.now()
|
||||
file_bytes = file.file.read()
|
||||
size = len(file_bytes)
|
||||
if size > file_size_limit:
|
||||
return size, '', '', ''
|
||||
path = f'./static/upload/{now.year}/{now.month}/{now.day}/'
|
||||
path = DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
||||
name = f'{key}.{ext}'
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
with open(f'{os.path.join(path, name)}', 'wb') as f:
|
||||
if not path.exists():
|
||||
path.mkdir(parents=True)
|
||||
filepath = path / name
|
||||
with open(filepath, 'wb') as f:
|
||||
f.write(file_bytes)
|
||||
return size, path[1:] + name, file.content_type, file.filename
|
||||
return f"{STATIC_URL}/{filepath.relative_to(DATA_ROOT)}", file.content_type, file.filename
|
||||
|
||||
|
||||
@app.get(f'/{admin_address}')
|
||||
@app.get(f'/{settings.ADMIN_ADDRESS}')
|
||||
async def admin():
|
||||
return HTMLResponse(admin_html)
|
||||
|
||||
|
||||
@app.post(f'/{admin_address}')
|
||||
@app.post(f'/{settings.ADMIN_ADDRESS}')
|
||||
async def admin_post(request: Request, s: AsyncSession = Depends(get_session)):
|
||||
if request.headers.get('pwd') == admin_password:
|
||||
if request.headers.get('pwd') == settings.ADMIN_PASSWORD:
|
||||
query = select(Codes)
|
||||
codes = (await s.execute(query)).scalars().all()
|
||||
return {'code': 200, 'msg': '查询成功', 'data': codes}
|
||||
@@ -93,12 +98,12 @@ async def admin_post(request: Request, s: AsyncSession = Depends(get_session)):
|
||||
return {'code': 404, 'msg': '密码错误'}
|
||||
|
||||
|
||||
@app.delete(f'/{admin_address}')
|
||||
@app.delete(f'/{settings.ADMIN_ADDRESS}')
|
||||
async def admin_delete(request: Request, code: str, s: AsyncSession = Depends(get_session)):
|
||||
if request.headers.get('pwd') == admin_password:
|
||||
if request.headers.get('pwd') == settings.ADMIN_PASSWORD:
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
file = (await s.execute(query)).scalars().first()
|
||||
threading.Thread(target=delete_file, args=([{'type': file.type, 'text': file.text}],)).start()
|
||||
await asyncio.to_thread(delete_file, [{'type': file.type, 'text': file.text}])
|
||||
await s.delete(file)
|
||||
await s.commit()
|
||||
return {'code': 200, 'msg': '删除成功'}
|
||||
@@ -114,8 +119,8 @@ async def index():
|
||||
def check_ip(ip):
|
||||
# 检查ip是否被禁止
|
||||
if ip in error_ip_count:
|
||||
if error_ip_count[ip]['count'] >= error_count:
|
||||
if error_ip_count[ip]['time'] + datetime.timedelta(minutes=error_minute) > datetime.datetime.now():
|
||||
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)
|
||||
@@ -137,7 +142,7 @@ async def get_file(code: str, s: AsyncSession = Depends(get_session)):
|
||||
if info.type == 'text':
|
||||
return {'code': code, 'msg': '查询成功', 'data': info.text}
|
||||
else:
|
||||
return FileResponse('.' + info.text, filename=info.name)
|
||||
return FileResponse(DATA_ROOT / info.text.lstrip(STATIC_URL + '/'), filename=info.name)
|
||||
else:
|
||||
return {'code': 404, 'msg': '口令不存在'}
|
||||
|
||||
@@ -150,7 +155,7 @@ async def index(request: Request, code: str, s: AsyncSession = Depends(get_sessi
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
info = (await s.execute(query)).scalars().first()
|
||||
if not info:
|
||||
return {'code': 404, 'msg': f'取件码错误,错误{error_count - ip_error(ip)}次将被禁止10分钟'}
|
||||
return {'code': 404, 'msg': f'取件码错误,错误{settings.ERROR_COUNT - ip_error(ip)}次将被禁止10分钟'}
|
||||
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)
|
||||
@@ -162,7 +167,6 @@ async def index(request: Request, code: str, s: AsyncSession = Depends(get_sessi
|
||||
await s.commit()
|
||||
if info.type != 'text':
|
||||
info.text = f'/select?code={code}'
|
||||
|
||||
return {
|
||||
'code': 200,
|
||||
'msg': '取件成功,请点击"取"查看',
|
||||
@@ -173,15 +177,6 @@ async def index(request: Request, code: str, s: AsyncSession = Depends(get_sessi
|
||||
@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)):
|
||||
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
|
||||
exps = (await s.execute(query)).scalars().all()
|
||||
threading.Thread(target=delete_file, args=([[{'type': old.type, 'text': old.text}] for old in exps],)).start()
|
||||
|
||||
exps_ids = [exp.id for exp in exps]
|
||||
query = delete(Codes).where(Codes.id.in_(exps_ids))
|
||||
await s.execute(query)
|
||||
await s.commit()
|
||||
|
||||
code = await get_code(s)
|
||||
if style == '2':
|
||||
if value > 7:
|
||||
@@ -198,9 +193,11 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
|
||||
exp_count = -1
|
||||
key = uuid.uuid4().hex
|
||||
if file:
|
||||
size, _text, _type, name = get_file_name(key, file.filename.split('.')[-1], file)
|
||||
if size > file_size_limit:
|
||||
file_bytes = file.file.read()
|
||||
size = len(file_bytes)
|
||||
if size > settings.FILE_SIZE_LIMIT:
|
||||
return {'code': 404, 'msg': '文件过大'}
|
||||
_text, _type, name = get_file_name(key, file.filename.split('.')[-1], file, file_bytes)
|
||||
else:
|
||||
size, _text, _type, name = len(text), text, 'text', '文本分享'
|
||||
info = Codes(
|
||||
|
||||
@@ -65,7 +65,34 @@ https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v
|
||||
|
||||
## 部署方式
|
||||
|
||||
先拉取代码,然后修改main.py文件,将里面写了注释的可以根据需求改一下
|
||||
为持久化,不管怎么样,先第一步,建一个文件夹,然后再下载代码
|
||||
|
||||
```bash
|
||||
mkdir /opt/FileCodeBox
|
||||
cd /opt/FileCodeBox
|
||||
```
|
||||
|
||||
新建一个`.env`文件
|
||||
|
||||
```bash
|
||||
vi .env
|
||||
```
|
||||
将下列字段内容替换成你自己的
|
||||
|
||||
```dotenv
|
||||
DEBUG=False
|
||||
DATABASE_URL=sqlite+aiosqlite:///database.db
|
||||
DATA_ROOT=./static
|
||||
STATIC_URL=/static
|
||||
ERROR_COUNT=5
|
||||
ERROR_MINUTE=10
|
||||
ADMIN_ADDRESS=admin
|
||||
ADMIN_PASSWORD=admin
|
||||
FILE_SIZE_LIMIT=10
|
||||
TITLE=文件快递柜
|
||||
DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
|
||||
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
|
||||
```
|
||||
|
||||
### 服务端部署
|
||||
|
||||
@@ -83,8 +110,12 @@ https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v
|
||||
### 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 filecodebox
|
||||
docker run -d -p 12345:12345 --name filecodebox --volume /opt/FileCodeBox:/app filecodebox
|
||||
```
|
||||
|
||||
## 状态
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
from starlette.config import Config
|
||||
|
||||
config = Config(".env")
|
||||
|
||||
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")
|
||||
|
||||
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)
|
||||
|
||||
ADMIN_ADDRESS = config('ADMIN_ADDRESS', cast=str, default="admin")
|
||||
|
||||
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default="admin")
|
||||
|
||||
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,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
|
||||
@@ -10,7 +10,7 @@
|
||||
<meta name="description" content="{{description}}"/>
|
||||
<meta name="keywords" content="{{keywords}}"/>
|
||||
<meta name="generator" content="FileCodeBox"/>
|
||||
<meta name="template" content="Lan-V1.4.1"/>
|
||||
<meta name="template" content="Lan-V1.4.2"/>
|
||||
<style>
|
||||
.qu .el-button {
|
||||
width: 100px;
|
||||
|
||||
Reference in new issue
Block a user