Compare commits

..
2 Commits
Author SHA1 Message Date
lan 222c048e38 fix: 基础目录设置 2024-01-18 18:46:16 +08:00
lan 31de5b7ea1 test:1 2023-08-16 13:03:56 +08:00
14 changed files with 239 additions and 3555 deletions

No files matched your search

+4 -1
View File
@@ -1 +1,4 @@
custom: https://gitlab.com/Vastsa/lanpicbed/-/raw/master/zb_users/upload/2023/02/6402263fb2ff4fddad51cb64fa66f4fb.png # These are supported funding model platforms
github: [ vastsa ]
custom: [ https://share.lanol.cn ]
-2
View File
@@ -5,8 +5,6 @@ LABEL version="6"
COPY . /app COPY . /app
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' >/etc/timezone
WORKDIR /app WORKDIR /app
RUN pip install -r requirements.txt RUN pip install -r requirements.txt
EXPOSE 12345 EXPOSE 12345
View File
Whitespace-only changes.
+8 -35
View File
@@ -36,41 +36,14 @@ class Codes(Base):
async def init_models(s): async def init_models(s):
async with engine.begin() as conn: async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all) await conn.run_sync(Base.metadata.create_all)
if await conn.scalar(select(Options).filter(Options.key == 'INSTALL')) is None: print(
# 如果没有存在install,则清空表,并插入默认数据 f'初始化数据库成功!\n'
await conn.execute(delete(table=Options)) f'如您未配置.env文件,将为您随机生成信息\n'
await conn.execute(insert(table=Options, values=[ f'您的后台地址为:/{settings.ADMIN_ADDRESS}\n'
{'key': 'INSTALL', 'value': settings.VERSION}, f'您的管理员密码为:{settings.ADMIN_PASSWORD}\n'
{'key': 'DEBUG', 'value': settings.DEBUG}, f'请尽快修改后台信息!\n'
{'key': 'DATABASE_FILE', 'value': settings.DATABASE_FILE}, f'FileCodeBox https://github.com/vastsa/FileCodeBox'
{'key': 'PORT', 'value': settings.PORT}, )
{'key': 'DATA_ROOT', 'value': settings.DATA_ROOT},
{'key': 'STATIC_URL', 'value': settings.STATIC_URL},
{'key': 'BANNERS', 'value': settings.BANNERS},
{'key': 'ENABLE_UPLOAD', 'value': settings.ENABLE_UPLOAD},
{'key': 'MAX_DAYS', 'value': settings.MAX_DAYS},
{'key': 'ERROR_COUNT', 'value': settings.ERROR_COUNT},
{'key': 'ERROR_MINUTE', 'value': settings.ERROR_COUNT},
{'key': 'UPLOAD_COUNT', 'value': settings.UPLOAD_COUNT},
{'key': 'UPLOAD_MINUTE', 'value': settings.UPLOAD_MINUTE},
{'key': 'DELETE_EXPIRE_FILES_INTERVAL', 'value': settings.DELETE_EXPIRE_FILES_INTERVAL},
{'key': 'ADMIN_ADDRESS', 'value': settings.ADMIN_ADDRESS},
{'key': 'ADMIN_PASSWORD', 'value': settings.ADMIN_PASSWORD},
{'key': 'FILE_SIZE_LIMIT', 'value': settings.FILE_SIZE_LIMIT},
{'key': 'TITLE', 'value': settings.TITLE},
{'key': 'DESCRIPTION', 'value': settings.DESCRIPTION},
{'key': 'KEYWORDS', 'value': settings.KEYWORDS},
{'key': 'STORAGE_ENGINE', 'value': settings.STORAGE_ENGINE},
{'key': 'STORAGE_CONFIG', 'value': {}},
]))
print(
f'初始化数据库成功!\n'
f'如您未配置.env文件,将为您随机生成信息\n'
f'您的后台地址为:/{settings.ADMIN_ADDRESS}\n'
f'您的管理员密码为:{settings.ADMIN_PASSWORD}\n'
f'请尽快修改后台信息!\n'
f'FileCodeBox https://github.com/vastsa/FileCodeBox'
)
await settings.updates(await conn.execute(select(Options).filter())) await settings.updates(await conn.execute(select(Options).filter()))
+63 -97
View File
@@ -1,7 +1,5 @@
import os import os
import asyncio import asyncio
import time
import uuid
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import BinaryIO from typing import BinaryIO
@@ -18,101 +16,6 @@ if settings.STORAGE_ENGINE == 'aliyunsystem':
import oss2 import oss2
class FileSystemStorage:
def __init__(self):
self.DATA_ROOT = Path(settings.DATA_ROOT)
self.STATIC_URL = settings.STATIC_URL
self.NAME = "filesystem"
self.DOWN_PATH = '/select'
async def get_filepath(self, text: str):
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
async def get_url(self, info: Codes):
return f'{self.DOWN_PATH}?code={info.code}'
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)
@staticmethod
def _save_chunk(filepath, file: bytes):
with open(filepath, 'wb') as f:
f.write(file)
async def create_upload_file(self):
file_key = uuid.uuid4().hex
file_path = self.DATA_ROOT / f"temp/{file_key}"
if not file_path.exists():
file_path.mkdir(parents=True)
return file_key
async def save_chunk_file(self, file_key, file_chunk, chunk_index, chunk_total):
file_path = self.DATA_ROOT / f"temp/{file_key}/"
await asyncio.to_thread(self._save_chunk, file_path / f"{chunk_total}-{chunk_index}.temp", file_chunk)
async def merge_chunks(self, file_key, file_name, total_chunks: int):
ext = file_name.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'{file_key}.{ext}').relative_to(self.DATA_ROOT)}"
with open(path / f'{file_key}.{ext}', 'wb') as f:
for i in range(1, total_chunks + 1):
now_temp = self.DATA_ROOT / f'temp/{file_key}/{total_chunks}-{i}.temp'
with open(now_temp, 'rb') as r:
f.write(r.read())
await asyncio.to_thread(os.remove, now_temp)
await asyncio.to_thread(os.rmdir, self.DATA_ROOT / f'temp/{file_key}/')
return text
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)
if filepath.exists():
await asyncio.to_thread(os.remove, filepath)
await asyncio.to_thread(self.judge_delete_folder, filepath)
async def delete_files(self, texts):
tasks = [self.delete_file(text) for text in texts]
await asyncio.gather(*tasks)
def judge_delete_folder(self, filepath):
current = filepath.parent
while current != self.DATA_ROOT:
if not list(current.iterdir()):
os.rmdir(current)
current = current.parent
else:
break
class AliyunFileStorage: class AliyunFileStorage:
def __init__(self): def __init__(self):
auth = oss2.Auth(settings.KeyId, settings.KeySecret) auth = oss2.Auth(settings.KeyId, settings.KeySecret)
@@ -168,6 +71,69 @@ class AliyunFileStorage:
self.bucket.delete_object(text) self.bucket.delete_object(text)
class FileSystemStorage:
def __init__(self):
self.DATA_ROOT = Path(settings.DATA_ROOT)
self.STATIC_URL = settings.STATIC_URL
self.NAME = "filesystem"
self.DOWN_PATH = '/select'
async def get_filepath(self, text: str):
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
async def get_url(self, info: Codes):
return f'{self.DOWN_PATH}?code={info.code}'
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)
if filepath.exists():
await asyncio.to_thread(os.remove, filepath)
await asyncio.to_thread(self.judge_delete_folder, filepath)
async def delete_files(self, texts):
tasks = [self.delete_file(text) for text in texts]
await asyncio.gather(*tasks)
def judge_delete_folder(self, filepath):
current = filepath.parent
while current != self.DATA_ROOT:
if not list(current.iterdir()):
os.rmdir(current)
current = current.parent
else:
break
STORAGE_ENGINE = { STORAGE_ENGINE = {
"filesystem": FileSystemStorage, "filesystem": FileSystemStorage,
"aliyunsystem": AliyunFileStorage "aliyunsystem": AliyunFileStorage
+3 -43
View File
@@ -1,10 +1,6 @@
import datetime import datetime
import hashlib
import random import random
import asyncio import asyncio
import string
import time
from sqlalchemy import or_, select, delete from sqlalchemy import or_, select, delete
from sqlalchemy.ext.asyncio.session import AsyncSession from sqlalchemy.ext.asyncio.session import AsyncSession
from .database import Codes, engine from .database import Codes, engine
@@ -40,44 +36,8 @@ async def delete_expire_files():
await asyncio.sleep(settings.DELETE_EXPIRE_FILES_INTERVAL * 60) await asyncio.sleep(settings.DELETE_EXPIRE_FILES_INTERVAL * 60)
async def get_random_num(): async def get_code(s: AsyncSession):
return random.randint(10000, 99999) code = random.randint(10000, 99999)
async def get_random_string():
r_s = string.ascii_letters + string.digits
return ''.join(random.choice(r_s) for _ in range(5)).upper()
async def get_code(s: AsyncSession, exp_style):
if exp_style == 'forever':
generate = get_random_string
else:
generate = get_random_num
code = await generate()
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar(): while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
code = await generate() code = random.randint(10000, 99999)
return str(code) return str(code)
async def get_token(ip, code):
return hashlib.sha256(f"{ip}{code}{int(time.time() / 1000)}000{settings.ADMIN_PASSWORD}".encode()).hexdigest()
async def get_expire_info(expire_style, expire_value, s):
now = datetime.datetime.now()
if expire_value <= 0 or expire_value > 999:
return True, None, None
code = await get_code(s, expire_style)
if expire_style == 'day':
return False, now + datetime.timedelta(days=expire_value), -1, code
elif expire_style == 'hour':
return False, now + datetime.timedelta(hours=expire_value), -1, code
elif expire_style == 'minute':
return False, now + datetime.timedelta(minutes=expire_value), -1, code
elif expire_style == 'forever':
return False, None, -1, code
elif expire_style == 'count':
return False, None, expire_value, code
else:
return True, None, None
+80 -80
View File
@@ -2,22 +2,21 @@ import asyncio
import datetime import datetime
import uuid import uuid
from pathlib import Path from pathlib import Path
from pydantic import BaseModel
from sqlalchemy import select, func, update from sqlalchemy import select, func, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request from starlette.requests import Request
from starlette.responses import HTMLResponse, FileResponse, RedirectResponse from starlette.responses import HTMLResponse, FileResponse
from starlette.staticfiles import StaticFiles from starlette.staticfiles import StaticFiles
from core.utils import error_ip_limit, upload_ip_limit, get_code, storage, delete_expire_files, get_token, \ import os
get_expire_info import shutil
from core.utils import error_ip_limit, upload_ip_limit, get_code, storage, delete_expire_files
from core.depends import admin_required from core.depends import admin_required
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks, Header from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
from core.database import init_models, Options, Codes, get_session from core.database import init_models, Options, Codes, get_session
from settings import settings from settings import settings
# 实例化FastAPI # 实例化FastAPI
app = FastAPI(debug=settings.DEBUG, redoc_url=None, ) app = FastAPI(debug=settings.DEBUG, redoc_url=None, docs_url=None, openapi_url=None)
@app.on_event('startup') @app.on_event('startup')
@@ -28,10 +27,15 @@ async def startup(s: AsyncSession = Depends(get_session)):
asyncio.create_task(delete_expire_files()) asyncio.create_task(delete_expire_files())
BASE_DIR = Path(__file__).resolve().parent.parent
# 数据存储文件夹 # 数据存储文件夹
DATA_ROOT = Path(settings.DATA_ROOT) DATA_ROOT = BASE_DIR / settings.DATA_ROOT
if not DATA_ROOT.exists(): if not DATA_ROOT.exists():
DATA_ROOT.mkdir(parents=True) DATA_ROOT.mkdir(parents=True)
# 本地文件文件夹
LOCAL_ROOT = BASE_DIR / settings.LOCAL_ROOT
if not LOCAL_ROOT.exists():
LOCAL_ROOT.mkdir(parents=True)
# 静态文件夹,这个固定就行了,静态资源都放在这里 # 静态文件夹,这个固定就行了,静态资源都放在这里
app.mount('/static', StaticFiles(directory='./static'), name="static") app.mount('/static', StaticFiles(directory='./static'), name="static")
@@ -45,25 +49,52 @@ admin_html = open('templates/admin.html', 'r', encoding='utf-8').read()
@app.get('/') @app.get('/')
async def index(): async def index():
return HTMLResponse( return HTMLResponse(
index_html index_html.replace('{{title}}', settings.TITLE).replace('{{description}}', settings.DESCRIPTION).replace(
.replace('{{title}}', settings.TITLE) '{{keywords}}', settings.KEYWORDS).replace("'{{fileSizeLimit}}'", str(settings.FILE_SIZE_LIMIT))
.replace('{{description}}', settings.DESCRIPTION)
.replace('{{keywords}}', settings.KEYWORDS)
.replace("'{{fileSizeLimit}}'", str(settings.FILE_SIZE_LIMIT))
) )
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面') @app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面')
async def admin(): async def admin():
return HTMLResponse( return HTMLResponse(
admin_html admin_html.replace('{{title}}', settings.TITLE).replace('{{description}}', settings.DESCRIPTION).replace(
.replace('{{title}}', settings.TITLE) '{{admin_address}}', settings.ADMIN_ADDRESS).replace('{{keywords}}', settings.KEYWORDS)
.replace('{{description}}', settings.DESCRIPTION)
.replace('{{admin_address}}', settings.ADMIN_ADDRESS)
.replace('{{keywords}}', settings.KEYWORDS)
) )
@app.get(f'/{settings.ADMIN_ADDRESS}/files', dependencies=[Depends(admin_required)])
async def get_files():
files = []
for i, j, k in os.walk(f'{LOCAL_ROOT}'):
files.extend([{'name': _.split('/')[-1], 'path': i} for _ in k])
return {'data': files}
@app.post(f'/{settings.ADMIN_ADDRESS}/files', dependencies=[Depends(admin_required)])
async def share_file(name=Form(...), path=File(...), s: AsyncSession = Depends(get_session)):
file_path = path + f'/{name}'
key = uuid.uuid4().hex
code = await get_code(s)
now = datetime.datetime.now()
path = f"{settings.LOCAL_ROOT}/upload/{now.year}/{now.month}/{now.day}/"
if not os.path.exists(path):
os.makedirs(path)
text = f"{path}/{f'{key}{name}'}"
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
s.add(Codes(code=code, text=text.replace(f'{settings.LOCAL_ROOT}/', ''), type='file', name=name, count=-1,
exp_time=exp_time, key=key))
await s.commit()
shutil.move(file_path, text)
return {
'detail': '分享成功!请在24小时内使用分享使用!',
'data': {
'code': code,
'text': text,
'name': name,
}
}
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='查询数据库列表') @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)): async def admin_post(page: int = Form(default=1), size: int = Form(default=10), s: AsyncSession = Depends(get_session)):
infos = (await s.execute(select(Codes).offset((page - 1) * size).limit(size))).scalars().all() infos = (await s.execute(select(Codes).offset((page - 1) * size).limit(size))).scalars().all()
@@ -134,12 +165,12 @@ async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession =
if not info: if not info:
error_count = settings.ERROR_COUNT - error_ip_limit.add_ip(ip) error_count = settings.ERROR_COUNT - error_ip_limit.add_ip(ip)
raise HTTPException(status_code=404, detail=f"取件码错误,{error_count}次后将被禁止{settings.ERROR_MINUTE}分钟") raise HTTPException(status_code=404, detail=f"取件码错误,{error_count}次后将被禁止{settings.ERROR_MINUTE}分钟")
if (info.exp_time and info.exp_time < datetime.datetime.now()) or info.count == 0: if info.exp_time < datetime.datetime.now() or info.count == 0:
raise HTTPException(status_code=404, detail="取件码已失效,请联系寄件人") raise HTTPException(status_code=404, detail="取件码已失效,请联系寄件人")
await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1)) await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
await s.commit() await s.commit()
if info.type != 'text': if info.type != 'text':
info.text = f'/select?code={info.code}&token={await get_token(code, ip)}' info.text = await storage.get_url(info)
return { return {
'detail': f'取件成功,请立即下载,避免失效!', 'detail': f'取件成功,请立即下载,避免失效!',
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code} 'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
@@ -148,6 +179,7 @@ async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession =
@app.get('/banner') @app.get('/banner')
async def banner(request: Request): async def banner(request: Request):
# 数据库查询config
return { return {
'detail': '查询成功', 'detail': '查询成功',
'data': settings.BANNERS, 'data': settings.BANNERS,
@@ -156,11 +188,7 @@ async def banner(request: Request):
@app.get('/select') @app.get('/select')
async def get_file(code: str, token: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)): async def get_file(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
# 验证token
if token != await get_token(code, ip):
error_ip_limit.add_ip(ip)
raise HTTPException(status_code=403, detail="口令错误,或已过期,次数过多将被禁止访问")
# 查出数据库记录 # 查出数据库记录
query = select(Codes).where(Codes.code == code) query = select(Codes).where(Codes.code == code)
info = (await s.execute(query)).scalars().first() info = (await s.execute(query)).scalars().first()
@@ -172,66 +200,38 @@ async def get_file(code: str, token: str, ip: str = Depends(error_ip_limit), s:
if info.type == 'text': if info.type == 'text':
return {'detail': '查询成功', 'data': info.text} return {'detail': '查询成功', 'data': info.text}
# 如果是文件,返回文件 # 如果是文件,返回文件
elif storage.NAME != 'filesystem':
# 重定向到文件存储服务器
return RedirectResponse(await storage.get_url(info))
else: else:
filepath = await storage.get_filepath(info.text) filepath = await storage.get_filepath(info.text)
return FileResponse(filepath, filename=info.name) return FileResponse(filepath, filename=info.name)
@app.post('/file/create/') @app.post('/share', dependencies=[Depends(admin_required)], description='分享文件')
async def create_file(): 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),
return {'code': 200, 'data': await storage.create_upload_file()} ip: str = Depends(upload_ip_limit), s: AsyncSession = Depends(get_session)):
code = await get_code(s)
if style == '2':
@app.post('/file/upload/{file_key}/') if value > settings.MAX_DAYS:
async def upload_file(file_key: str, file: bytes = File(...), chunk_index: int = Form(...), raise HTTPException(status_code=400, detail=f"最大有效天数为{settings.MAX_DAYS}天")
total_chunks: int = Form(...)): exp_time = datetime.datetime.now() + datetime.timedelta(days=value)
await storage.save_chunk_file(file_key, file, chunk_index, total_chunks) exp_count = -1
return {'code': 200} elif style == '1':
if value < 1:
raise HTTPException(status_code=400, detail="最小有效次数为1次")
@app.get('/file/merge/{file_key}/') exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
async def merge_chunks(file_key: str, file_name: str, total_chunks: int): exp_count = value
return {'code': 200, 'data': await storage.merge_chunks(file_key, file_name, total_chunks)} else:
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = -1
class ShareDataModel(BaseModel): key = uuid.uuid4().hex
text: str if file:
size: int = 0 size = await storage.get_size(file)
exp_style: str if size > settings.FILE_SIZE_LIMIT:
exp_value: int raise HTTPException(status_code=400, detail="文件过大")
type: str _text, _type, name = await storage.get_text(file, key), file.content_type, file.filename
name: str background_tasks.add_task(storage.save_file, file, _text)
key: str = uuid.uuid4 else:
size, _text, _type, name = len(text), text, 'text', '文本分享'
@app.post('/share/file/', dependencies=[Depends(admin_required)], description='分享文件')
async def share_file(file_model: ShareDataModel, s: AsyncSession = Depends(get_session),
ip: str = Depends(error_ip_limit)):
exp_error, exp_time, exp_count, code = await get_expire_info(file_model.exp_style, file_model.exp_value, s)
if exp_error:
raise HTTPException(status_code=400, detail='过期值异常')
s.add(Codes(code=code, text=file_model.text, size=file_model.size, type=file_model.type, name=file_model.name,
count=exp_count, exp_time=exp_time, key=file_model.key))
await s.commit()
upload_ip_limit.add_ip(ip)
return {
'detail': '分享成功,请点击我的文件按钮查看上传列表',
'data': {'code': code, 'key': file_model.key, 'name': file_model.name}
}
@app.post('/share/text/', dependencies=[Depends(admin_required)])
async def share_text(text_model: ShareDataModel, s: AsyncSession = Depends(get_session),
ip: str = Depends(error_ip_limit)):
exp_error, exp_time, exp_count, code = await get_expire_info(text_model.exp_style, text_model.exp_value, s, )
if exp_error:
raise HTTPException(status_code=400, detail='过期值异常')
exp_status, exp_time, exp_count, code = await get_expire_info(text_model.exp_style, text_model.exp_value, s)
size, _text, _type, name, key = len(text_model.text), text_model.text, 'text', '文本分享', text_model.key().hex
s.add(Codes(code=code, text=_text, size=size, type=_type, name=name, count=exp_count, exp_time=exp_time, key=key)) s.add(Codes(code=code, text=_text, size=size, type=_type, name=name, count=exp_count, exp_time=exp_time, key=key))
await s.commit() await s.commit()
upload_ip_limit.add_ip(ip) upload_ip_limit.add_ip(ip)
+1 -7
View File
@@ -2,7 +2,6 @@
<h1>文件快递柜-轻量</h1> <h1>文件快递柜-轻量</h1>
<h2>FileCodeBox-Lite</h2> <h2>FileCodeBox-Lite</h2>
<p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p> <p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p>
<p>交流Q群:739673698,欢迎各位集思广益,项目构思重构中</p>
</div> </div>
![banner](https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png) ![banner](https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png)
@@ -22,8 +21,7 @@
- [x] 匿名分享:无需注册,无需登录 - [x] 匿名分享:无需注册,无需登录
- [x] 管理面板:查看所有文件,删除文件 - [x] 管理面板:查看所有文件,删除文件
- [x] 一键部署:docker一键部署 - [x] 一键部署:docker一键部署
- [x] 自由拓展:阿里云OSS、本地文件流,可根据需求在storage文件中新增存储引擎 - [x] 多种存储方式:阿里云OSS、本地文件流
- [x] 简单明了:适合新手练手项目
## 部署方式 ## 部署方式
@@ -41,10 +39,6 @@ docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --n
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:arm docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:arm
``` ```
### 宝塔部署
https://www.yuque.com/lxyo/work/lc1oe0xqk8t9b976
### 更新方式 ### 更新方式
```bash ```bash
+4 -4
View File
@@ -18,7 +18,9 @@ class Settings:
# Sqlite套接字 # Sqlite套接字
DATABASE_URL = config('DATABASE_URL', cast=str, default=f"sqlite+aiosqlite:///{DATABASE_FILE}") DATABASE_URL = config('DATABASE_URL', cast=str, default=f"sqlite+aiosqlite:///{DATABASE_FILE}")
# 数据存储文件夹,文件就不暴露在静态资源里面了 # 数据存储文件夹,文件就不暴露在静态资源里面了
DATA_ROOT = config('DATA_ROOT', cast=str, default=f"./data/static") DATA_ROOT = './data/' + config('DATA_ROOT', cast=str, default=f"static")
# 本地文件夹
LOCAL_ROOT = './data/' + config('LOCAL_ROOT', cast=str, default=f"local")
# 静态文件夹URL # 静态文件夹URL
STATIC_URL = config('STATIC_URL', cast=str, default="/static") STATIC_URL = config('STATIC_URL', cast=str, default="/static")
# 开启上传 # 开启上传
@@ -31,8 +33,6 @@ class Settings:
ERROR_MINUTE = config('ERROR_MINUTE', cast=int, default=10) ERROR_MINUTE = config('ERROR_MINUTE', cast=int, default=10)
# 上传次数 # 上传次数
UPLOAD_COUNT = config('UPLOAD_COUNT', cast=int, default=60) UPLOAD_COUNT = config('UPLOAD_COUNT', cast=int, default=60)
# 是否允许永久保存
ENABLE_PERMANENT = config('ENABLE_PERMANENT', cast=bool, default=True)
# 上传限制分钟数 # 上传限制分钟数
UPLOAD_MINUTE = config('UPLOAD_MINUTE', cast=int, default=1) UPLOAD_MINUTE = config('UPLOAD_MINUTE', cast=int, default=1)
# 删除过期文件的间隔(分钟) # 删除过期文件的间隔(分钟)
@@ -42,7 +42,7 @@ class Settings:
# 管理密码 # 管理密码
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default=uuid.uuid4().hex) ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default=uuid.uuid4().hex)
# 文件大小限制,默认10MB # 文件大小限制,默认10MB
FILE_SIZE_LIMIT = config('FILE_SIZE_LIMIT', cast=int, default=10 * 1024 * 1024) FILE_SIZE_LIMIT = config('FILE_SIZE_LIMIT', cast=int, default=10) * 1024 * 1024
# 网站标题 # 网站标题
TITLE = config('TITLE', cast=str, default="文件快递柜") TITLE = config('TITLE', cast=str, default="文件快递柜")
# 网站描述 # 网站描述
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+21 -2
View File
@@ -30,6 +30,7 @@
<el-col :span="24" style="text-align: center"> <el-col :span="24" style="text-align: center">
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"> <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="2">分享文件管理</el-menu-item>
<el-menu-item index="3">本地文件列表</el-menu-item>
<el-menu-item index="4">系统配置</el-menu-item> <el-menu-item index="4">系统配置</el-menu-item>
</el-menu> </el-menu>
</el-col> </el-col>
@@ -43,8 +44,7 @@
<div>取件码:${ file.code }</div> <div>取件码:${ file.code }</div>
<div>文件名:${ file.name }</div> <div>文件名:${ file.name }</div>
<div>次&nbsp;&nbsp; 数:${ file.count }</div> <div>次&nbsp;&nbsp; 数:${ file.count }</div>
<div v-if="file.exp_time">到&nbsp;&nbsp; 期:${ file.exp_time.slice(0,19) }</div> <div>到&nbsp;&nbsp; 期:${ file.exp_time.slice(0,19) }</div>
<div v-else>到&nbsp;&nbsp; 期:永不过期</div>
<div v-if="file.name==='文本分享'"> <div v-if="file.name==='文本分享'">
<span style="white-space: pre-line">内&nbsp;&nbsp; 容:${ file.text }</span> <span style="white-space: pre-line">内&nbsp;&nbsp; 容:${ file.text }</span>
</div> </div>
@@ -73,6 +73,25 @@
> >
</el-pagination> </el-pagination>
</el-col> </el-col>
<el-col v-if="activeIndex === '3'">
<el-card style="height: 80vh;overflow: scroll;margin-bottom: 1rem">
<el-empty v-if="locals.length === 0"
description="暂时还没有文件,请上传至/opt/data/locals目录"></el-empty>
<el-card v-for="file in locals" :key="file.code">
<el-row>
<el-col :span="20">
<div style="cursor: pointer;text-align: left">
<div>文件名:${ file.name }</div>
<div>路径:${ file.path }</div>
</div>
</el-col>
<el-col :span="4">
<el-button type="primary" @click="shareFile(file)">分享</el-button>
</el-col>
</el-row>
</el-card>
</el-card>
</el-col>
<el-col v-if="activeIndex === '4'"> <el-col v-if="activeIndex === '4'">
<el-row> <el-row>
<el-col :span="4" style="height: 88vh;overflow: scroll;text-align: center" :gutter="10"> <el-col :span="4" style="height: 88vh;overflow: scroll;text-align: center" :gutter="10">
+55 -169
View File
@@ -6,23 +6,22 @@
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 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"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/asserts/index.css"> <link rel="stylesheet" href="/static/asserts/index.css">
<link rel="stylesheet" href="/static/asserts/github-markdown-css/github-markdown.css">
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/> <link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
<title>{{title}}</title> <title>{{title}}</title>
<meta name="description" content="{{description}}"/> <meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/> <meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/> <meta name="generator" content="FileCodeBox"/>
<meta name="template" content="V1.7 Beta"/> <meta name="template" content="V1.6 Beta"/>
<style> <style>
body { body {
background: #f5f5f5; background: #f5f5f5;
} }
.qu .el-button { .qu .el-button {
width: 6rem; width: 100px;
height: 6rem; height: 100px;
margin: 0.2rem; margin: 0.2rem;
font-size: 2rem; font-size: 30px;
font-weight: bold; font-weight: bold;
} }
@@ -44,6 +43,7 @@
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
body { body {
background-color: #18181c; background-color: #18181c;
} }
@@ -64,14 +64,6 @@
background-color: rgba(0, 0, 0, 0.2); background-color: rgba(0, 0, 0, 0.2);
} }
.el-button:focus, .el-button:hover {
background-color: rgba(0, 0, 0, 0.3);
}
.el-button:active, .el-select-dropdown__item.hover, .el-select-dropdown__item:hover, .el-input.is-disabled .el-input__inner {
background-color: rgba(0, 0, 0, 0.4);
}
.el-drawer, #el-drawer__title, .el-drawer__body, .el-drawer__wrapper { .el-drawer, #el-drawer__title, .el-drawer__body, .el-drawer__wrapper {
background-color: rgba(0, 0, 0, 0.5); background-color: rgba(0, 0, 0, 0.5);
border: 1px solid transparent; border: 1px solid transparent;
@@ -146,39 +138,29 @@
</el-carousel> </el-carousel>
</div> </div>
<el-row> <el-row>
<el-input style="width: 190px" :disabled="uploadData.exp_style==='forever'" placeholder="数量" <el-input style="width: 190px" placeholder="数量" v-model="uploadData.value"
v-model="uploadData.exp_value"
class="input-with-select"> class="input-with-select">
<el-select style="width: 75px" v-model="uploadData.exp_style" slot="prepend" <el-select style="width: 75px" v-model="uploadData.style" slot="prepend" placeholder="请选择">
placeholder="请选择"> <el-option label="天数" value="2"></el-option>
<el-option label="天数" value="day"></el-option> <el-option label="次数" value="1"></el-option>
<el-option label="小时" value="hour"></el-option>
<el-option label="分钟" value="minute"></el-option>
<el-option label="永久" value="forever"></el-option>
<el-option label="次数" value="count"></el-option>
</el-select> </el-select>
<el-button slot="append" disabled>${exp_style_dict[uploadData.exp_style]}</el-button> <el-button v-if="uploadData.style === '1'" slot="append" disabled>次</el-button>
<el-button v-else slot="append" disabled>天</el-button>
</el-input> </el-input>
<el-radio-group style="margin-left: 18px" v-model="uploadData.is_file"> <el-radio-group style="margin-left: 18px" v-model="uploadData.type">
<el-radio label="1"> <el-radio label="1">
文件 文件
</el-radio> </el-radio>
<el-radio label="0"> <el-radio label="2">
文本 文本
</el-radio> </el-radio>
</el-radio-group> </el-radio-group>
</el-row> </el-row>
<el-upload <el-upload
v-if="uploadData.is_file === '1'" v-if="uploadData.type === '1'"
drag drag
v-loading="uploading"
action="/share" action="/share"
:element-loading-text="loadingText"
element-loading-spinner="el-icon-loading"
multiple multiple
:disabled="uploading"
:http-request="uploadFile"
style="margin: 1rem 0;" style="margin: 1rem 0;"
:data="uploadData" :data="uploadData"
:before-upload="beforeUpload" :before-upload="beforeUpload"
@@ -198,6 +180,7 @@
placeholder="请输入内容,使用按钮存入" placeholder="请输入内容,使用按钮存入"
v-model="uploadData.text"> v-model="uploadData.text">
</el-input> </el-input>
<div class="el-upload__tip"> <div class="el-upload__tip">
<el-button round @click="pageNum=0"> <el-button round @click="pageNum=0">
<div class="el-icon-back"></div> <div class="el-icon-back"></div>
@@ -207,7 +190,7 @@
<div class="el-icon-takeaway-box"></div> <div class="el-icon-takeaway-box"></div>
我的文件 我的文件
</el-button> </el-button>
<el-button round v-if="uploadData.is_file === '0'" @click="uploadText"> <el-button round v-if="uploadData.type === '2'" @click="toUploadData">
<div class="el-icon-upload2"></div> <div class="el-icon-upload2"></div>
存入 存入
</el-button> </el-button>
@@ -226,7 +209,8 @@
<div>取件码:${ file.code }</div> <div>取件码:${ file.code }</div>
<div>文件名:${ file.name }</div> <div>文件名:${ file.name }</div>
<div v-if="file.name==='文本分享'"> <div v-if="file.name==='文本分享'">
<article v-html="file.text" class="markdown-body" @click="copyText(file.text,1)"></article> <span style="white-space: pre-line"
@click="copyText(file.text,1)">内&nbsp;&nbsp; 容:${ file.text }</span>
</div> </div>
<div v-else> <div v-else>
<span>链&nbsp;&nbsp; 接:</span> <span>链&nbsp;&nbsp; 接:</span>
@@ -268,7 +252,7 @@
</el-drawer> </el-drawer>
<div style="text-align: center; margin-top: 1rem;color: #606266"> <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 style="text-decoration: none;color: #606266" target="_blank" href="https://github.com/vastsa/FileCodeBox">FileCodeBox
V1.7 Beta</a> V1.6 Beta</a>
</div> </div>
</div> </div>
</body> </body>
@@ -283,16 +267,8 @@
quDrawer: false, quDrawer: false,
jiDrawer: false, jiDrawer: false,
direction: 'btt', direction: 'btt',
exp_style_dict: {
'day': '天',
'hour': '时',
'minute': '分',
'forever': '无',
'count': '次',
},
quFiles: [], quFiles: [],
jiFiles: [], jiFiles: [],
uploadGroup: [],
pageNum: 0, pageNum: 0,
inputDisable: false, inputDisable: false,
fileSizeLimit: '{{fileSizeLimit}}', fileSizeLimit: '{{fileSizeLimit}}',
@@ -300,16 +276,12 @@
banners: [], banners: [],
enableUpload: false, enableUpload: false,
uploadData: { uploadData: {
exp_style: 'day', style: '2',
exp_value: 1, type: '1',
type: 'text', value: 1,
name: '文本分享', file: null,
is_file: '1', text: ''
text: '',
size: 0,
}, },
uploading: false,
loadingText: '正在上传中...',
}; };
}, },
mounted: function () { mounted: function () {
@@ -331,13 +303,14 @@
that.$message('剪切板文字正在上传,请稍等'); that.$message('剪切板文字正在上传,请稍等');
items[i].getAsString(function (str) { items[i].getAsString(function (str) {
that.uploadData.text = str; that.uploadData.text = str;
that.uploadText(); that.toUploadData();
}); });
} }
} else { } else {
const file = items[i].getAsFile(); const file = items[i].getAsFile();
that.$message('剪切板文件正在上传,请稍等'); that.$message('剪切板文件正在上传,请稍等');
that.uploadFile({file: file}); that.uploadData.file = file
that.toUploadData();
} }
} }
} }
@@ -370,35 +343,19 @@
data: data, data: data,
...config ...config
}).then(res => { }).then(res => {
if (res.data.detail) { this.$message({
this.$message({ message: res.data.detail,
message: res.data.detail, type: 'success'
type: 'success' });
});
}
resolve(res.data) resolve(res.data)
}).catch(err => { }).catch(err => {
if (err.response.data.detail) { this.$message({
this.$message({ message: err.response.data.detail,
message: err.response.data.detail, type: 'error'
type: 'error' });
});
}
}) })
}) })
}, },
uploadChunk: async function (chunk, file_key, chunk_index, total_chunks) {
const formData = new FormData();
formData.append('file', chunk);
formData.append('file_key', file_key);
formData.append('chunk_index', chunk_index);
formData.append('total_chunks', total_chunks);
this.http('post', `/file/upload/${file_key}/`, formData).then((res) => {
this.upload_groups[chunk_index - 1] = 1;
}).catch((res) => {
this.upload_groups[chunk_index - 1] = 2;
})
},
copyText: function (value, style = 1) { copyText: function (value, style = 1) {
if (style === 0) { if (style === 0) {
value = `我给你分享了文件,取件码:${value},${window.location.href}?code=${value}`; value = `我给你分享了文件,取件码:${value},${window.location.href}?code=${value}`;
@@ -456,105 +413,34 @@
} }
return true; return true;
}, },
uploadText: function () { toUploadData: function () {
if (this.uploadData.text === '') { if (this.uploadData.text === '' && this.uploadData.file === null) {
this.$message({ this.$message({
message: '请先粘贴文字', message: '请先粘贴文字或者上传文件',
type: 'error' type: 'error'
}); });
} else { } else {
this.http('post', '/share/text/', this.uploadData, { if (this.checkFile(this.uploadData.file)) {
headers: { this.http('post', '/share', this.uploadData, {
'pwd': this.pwd headers: {
} 'Content-Type': 'multipart/form-data',
}).then(res => { 'pwd': this.pwd
this.jiFiles.unshift(res.data); }
this.jiDrawer = true; }).then(res => {
this.uploadData.text = ''; this.jiFiles.unshift(res.data);
this.$message({ this.jiDrawer = true;
message: '上传成功', this.uploadData.text = '';
type: 'success' this.uploadData.file = null;
}); });
}) }
}
},
uploadFile: async function (e) {
const that = this;
if (this.checkFile(e.file)) {
that.uploading = true;
that.loadingText = '正在上传中...';
this.http('post', '/file/create/').then(async res => {
const file = e.file;
let chunk_index = 0;
const shardSize = 1024 * 1024 * 5;
const {name, size, type} = file;
const total_chunks = Math.ceil(size / shardSize);
this.upload_groups = [];
for (let i = 0; i < total_chunks; i++) {
this.upload_groups.push(0);
}
while (chunk_index < total_chunks) {
const start = chunk_index * shardSize
const end = Math.min(start + shardSize, size)
chunk_index += 1;
this.uploadChunk(file.slice(start, end), res.data, chunk_index, total_chunks);
}
const interval = setInterval(() => {
let success = 0;
let flag = true;
for (let i = 0; i < total_chunks; i++) {
if (this.upload_groups[i] === 0) {
flag = false;
} else if (this.upload_groups[i] === 2) {
flag = false;
start = chunk_index * shardSize;
const end = Math.min(start + shardSize, size);
this.uploadChunk(file.slice(start, end), res.data, chunk_index, total_chunks);
} else {
success += 1;
}
}
that.loadingText = `已上传${ (success/total_chunks*100).toFixed(2) }%`;
if (flag) {
clearInterval(interval);
this.http('get', `/file/merge/${res.data}/?file_name=${name}&total_chunks=${total_chunks}`).then(text => {
this.http('post', '/share/file/', {
text: text.data,
size: size,
exp_style: this.uploadData.exp_style,
exp_value: this.uploadData.exp_value,
type: type,
name: name,
key: res.data,
}, {
headers: {
'pwd': this.pwd
}
}).then(res => {
this.jiFiles.unshift(res.data);
this.jiDrawer = true;
this.uploadData.text = '';
this.uploadData.file = null;
that.uploading = false;
this.$message({
message: '上传成功',
type: 'success'
});
})
});
}
}, 100);
});
} }
}, },
successUpload(response, file, fileList) { successUpload(response, file, fileList) {
if (response) { this.$message({
this.$message({ message: response.detail,
message: response.detail, type: 'success'
type: 'success' });
}); this.jiFiles.unshift(response.data);
this.jiFiles.unshift(response.data);
}
}, },
errorUpload(error, file, fileList) { errorUpload(error, file, fileList) {
error = JSON.parse(error.message) error = JSON.parse(error.message)