Compare commits

...
60 Commits
Author SHA1 Message Date
lan 9947a0927a update:上传 2023-03-01 18:30:24 +08:00
lan a1210d5182 update:异步分片上传+更新提示 2023-03-01 18:28:35 +08:00
lan 5b7a9f919b update:异步上传 2023-03-01 16:27:39 +08:00
lan 6e52553cd3 update:异步上传 2023-03-01 16:22:40 +08:00
lan d5bc3e1a81 update:宝塔部署教程 2023-03-01 02:34:07 +08:00
lan 31b8cb4016 update:优化过期方式 2023-03-01 01:14:37 +08:00
lan 2eafca2f0c update:优化分析模式 2023-03-01 01:09:47 +08:00
lan 24200a53a2 update:切片上传 2023-02-28 18:34:15 +08:00
lan aaaef095c8 Merge remote-tracking branch 'origin/master' 2023-02-28 17:23:01 +08:00
lan 7fc733d225 update:切片上传 2023-02-28 17:22:49 +08:00
vastsa 4a868865f9 Update readme.md 2023-02-28 00:46:51 +08:00
vastsa 0ae8b82c77 Update readme.md 2023-02-28 00:46:34 +08:00
lan c77fd35c7d update:6 2023-02-23 11:24:59 +08:00
vastsa 7e1120eb62 Update readme.md 2023-02-22 22:52:09 +08:00
vastsa 4e5f9fa619 Update readme.md 2023-02-22 22:51:58 +08:00
vastsa 00b5bace6d Update readme.md 2023-02-14 13:10:20 +08:00
lan 77e6e7644f fix:@issue48 2023-02-13 13:34:21 +08:00
lan fb6f71c93b add:新增永久保存,但是会永久占用一个码,问题待解决 2023-02-11 22:13:42 +08:00
lan 87549fae29 add:新增永久保存,但是会永久占用一个码,问题待解决 2023-02-11 19:47:33 +08:00
lan e8cc4748d1 add:新增永久保存,但是会永久占用一个码,问题待解决 2023-02-11 19:41:44 +08:00
lan ba71942caa add:解决select可跳过次数限制,新增sha256加密token,限制取件码+ip+时间999s内取件 2023-02-09 14:22:56 +08:00
lan 7864d0710d add:解决select可跳过次数限制,新增sha256加密token,限制取件码+ip+时间999s内取件 2023-02-08 03:28:08 +08:00
lan 12c7d5a1dd Merge remote-tracking branch 'origin/master' 2023-02-08 03:27:51 +08:00
lan f2b5490f10 add:解决select可跳过次数限制,新增sha256加密token,限制取件码+ip+时间999s内取件 2023-02-08 03:27:45 +08:00
vastsa 10dfb67ac0 Update FUNDING.yml 2023-02-08 03:20:53 +08:00
vastsa 2b04515c00 Update FUNDING.yml 2023-02-08 03:18:03 +08:00
lan 1f303d3340 add:解决select可跳过次数限制,新增sha256加密token,限制取件码+ip+时间999s内取件 2023-02-08 03:17:22 +08:00
lan f4f40e245a delete:暂时移除本地文件分析 2023-01-31 21:29:34 +08:00
lan 195e08f818 delete:暂时移除本地文件分析 2023-01-31 21:29:06 +08:00
lan 45d8abc439 delete:暂时移除本地文件分析 2023-01-31 21:28:28 +08:00
lan 9b51d592c2 update:后台新增端口设置 2023-01-31 21:07:16 +08:00
lan 4c507fc3cb update:readme 2023-01-19 21:56:19 +08:00
lan fce5194e04 fix:admin 2023-01-18 22:11:58 +08:00
lan 517b7b8a3a fix:admin 2023-01-18 22:11:28 +08:00
lan 8b952eddbf fix:admin 2023-01-18 22:08:01 +08:00
lan 75a94311e4 fix:upload 2023-01-18 11:29:23 +08:00
lan ce828ebb89 fix:upload 2023-01-18 11:19:08 +08:00
lan e593fd8d51 update:readme 2023-01-18 10:56:33 +08:00
lan 3b44b2273c update:readme 2023-01-18 10:53:34 +08:00
lan a21c3a1f6e update:增强iplimit 2023-01-18 10:41:02 +08:00
lan de1096acc4 update:增强iplimit 2023-01-16 22:58:50 +08:00
lan 3864335fca fix:admin 2023-01-16 22:58:09 +08:00
lan 8f3fa8af74 fix:admin 2023-01-16 22:55:53 +08:00
lan 7ed8b68ee8 Merge remote-tracking branch 'origin/master' 2023-01-16 22:55:14 +08:00
lan b6c0bc04fa fix:admin 2023-01-16 22:53:39 +08:00
lan ef4175f191 update:保留文件换行 2023-01-16 20:20:46 +08:00
lan a8052c647d update:保留文件换行 2023-01-16 20:19:52 +08:00
lan 68dd33043e update:保留文件换行 2023-01-16 18:53:45 +08:00
lan 511bfa1632 add:后台分享本地文件 2023-01-16 18:50:46 +08:00
lan f87d61b793 add:后台分享本地文件 2023-01-16 18:47:19 +08:00
lan 1fb758a201 update:后台修改配置信息 2023-01-16 17:54:08 +08:00
lan 9473cb35af fix:后台下载 2023-01-16 16:16:46 +08:00
lan ef2a6551b9 fix:后台下载 2023-01-16 16:14:05 +08:00
lan ee5beb2261 重构中,配置存入数据库,第一次智能生成随机后台地址,登录密码 2023-01-16 16:03:25 +08:00
vastsa c19da62941 Merge pull request #39 from ZHYCarge/master
add:支持使用阿里云OSS进行对象存储服务
2023-01-16 11:22:06 +08:00
ZHYCarge 487895af7e update: 对阿里云OSS的私有Bucket支持访问 2023-01-16 10:38:08 +08:00
ZHYCarge 1b26b03758 add:支持使用阿里云OSS进行对象存储服务
fix:删除utils中未使用的第三方库chardet
2023-01-15 22:06:01 +08:00
lan cfa865c6cd update:update default banner img by @yanyuo 2023-01-14 15:55:14 +08:00
lan fb932f08e4 update:update default banner img by @yanyuo 2023-01-14 15:54:22 +08:00
lan 8f404fbfed update:update default banner img by @yanyuo 2023-01-14 15:51:13 +08:00
25 changed files with 4129 additions and 453 deletions

No files matched your search

+1 -4
View File
@@ -1,4 +1 @@
# These are supported funding model platforms
github: [vastsa]
custom: [https://share.lanol.cn]
custom: https://gitlab.com/Vastsa/lanpicbed/-/raw/master/zb_users/upload/2023/02/6402263fb2ff4fddad51cb64fa66f4fb.png
+3 -1
View File
@@ -1,10 +1,12 @@
FROM python:3.9.5-slim-buster
LABEL author="Lan"
LABEL email="vast@tom.com"
LABEL version="1.5.9.2"
LABEL version="6"
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
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+84
View File
@@ -0,0 +1,84 @@
import datetime
from sqlalchemy import Boolean, Column, Integer, String, DateTime, JSON, Text, select, insert, delete
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio.session import AsyncSession
from settings import settings
engine = create_async_engine(settings.DATABASE_URL)
Base = declarative_base()
class Options(Base):
__tablename__ = 'options'
id = Column(Integer, primary_key=True, index=True)
key = Column(String, unique=True, index=True)
value = Column(JSON)
class Codes(Base):
__tablename__ = "codes"
id = Column(Integer, primary_key=True, index=True)
code = Column(String(10), unique=True, index=True)
key = Column(String(30), unique=True)
name = Column(String(500))
size = Column(Integer)
type = Column(String(20))
text = Column(Text)
used = Column(Boolean, default=False)
count = Column(Integer, default=-1)
use_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
exp_time = Column(DateTime, nullable=True)
async def init_models(s):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
if await conn.scalar(select(Options).filter(Options.key == 'INSTALL')) is None:
# 如果没有存在install,则清空表,并插入默认数据
await conn.execute(delete(table=Options))
await conn.execute(insert(table=Options, values=[
{'key': 'INSTALL', 'value': settings.VERSION},
{'key': 'DEBUG', 'value': settings.DEBUG},
{'key': 'DATABASE_FILE', 'value': settings.DATABASE_FILE},
{'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()))
async def get_config(key):
async with engine.begin() as conn:
return await conn.scalar(select(Options.value).filter(Options.key == key))
async def get_session():
async with AsyncSession(engine, expire_on_commit=False) as s:
yield s
+4 -1
View File
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from fastapi import Header, HTTPException, Request
import settings
from settings import settings
async def admin_required(pwd: Union[str, None] = Header(default=None), request: Request = None):
@@ -11,6 +11,8 @@ async def admin_required(pwd: Union[str, None] = Header(default=None), request:
if pwd != settings.ADMIN_PASSWORD and not settings.ENABLE_UPLOAD:
raise HTTPException(status_code=403, detail='本站上传功能已关闭,仅管理员可用')
else:
if settings.ADMIN_PASSWORD is None:
raise HTTPException(status_code=404, detail='您未设置管理员密码,无法使用此功能,请更新配置文件后,重启系统')
if not pwd or pwd != settings.ADMIN_PASSWORD:
raise HTTPException(status_code=401, detail="密码错误,请重新登录")
@@ -34,6 +36,7 @@ class IPRateLimit:
def add_ip(self, ip):
ip_info = self.ips.get(ip, {'count': 0, 'time': datetime.now()})
ip_info['count'] += 1
ip_info['time'] = datetime.now()
self.ips[ip] = ip_info
return ip_info['count']
+174
View File
@@ -0,0 +1,174 @@
import os
import asyncio
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import BinaryIO
from fastapi import UploadFile
from core.database import Codes
from settings import settings
if settings.STORAGE_ENGINE == 'aliyunsystem':
try:
import oss2
except ImportError:
os.system('pip install 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:
def __init__(self):
auth = oss2.Auth(settings.KeyId, settings.KeySecret)
self.bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.BUCKET_NAME)
def upload_file(self, upload_filepath, remote_filepath):
self.bucket.put_object_from_file(remote_filepath, upload_filepath)
async def get_text(self, file: UploadFile, key: str):
ext = file.filename.split('.')[-1]
now = datetime.now()
path = f"FileCodeBox/upload/{now.year}/{now.month}/{now.day}"
text = f"{path}/{f'{key}.{ext}'}"
return f"https://{settings.BUCKET_NAME}.{settings.OSS_ENDPOINT}/{text}"
async def get_url(self, info: Codes):
text = info.text.strip(f"https://{settings.BUCKET_NAME}.{settings.OSS_ENDPOINT}/")
url = self.bucket.sign_url('GET', text, settings.ACCESSTIME, slash_safe=True)
return url
@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, remote_filepath: str):
now = int(datetime.now().timestamp())
upload_filepath = settings.DATA_ROOT + str(now)
await asyncio.to_thread(self._save, upload_filepath, file.file)
self.upload_file(upload_filepath, remote_filepath)
remote_filepath = remote_filepath.strip(f"https://{settings.BUCKET_NAME}.{settings.OSS_ENDPOINT}/")
self.upload_file(upload_filepath, remote_filepath)
await asyncio.to_thread(os.remove, upload_filepath)
async def delete_files(self, texts):
tasks = [self.delete_file(text) for text in texts]
await asyncio.gather(*tasks)
async def delete_file(self, text: str):
text = text.strip(f"https://{settings.BUCKET_NAME}.{settings.OSS_ENDPOINT}/")
self.bucket.delete_object(text)
STORAGE_ENGINE = {
"filesystem": FileSystemStorage,
"aliyunsystem": AliyunFileStorage
}
+83
View File
@@ -0,0 +1,83 @@
import datetime
import hashlib
import random
import asyncio
import string
import time
from sqlalchemy import or_, select, delete
from sqlalchemy.ext.asyncio.session import AsyncSession
from .database import Codes, engine
from .depends import IPRateLimit
from .storage import STORAGE_ENGINE
from settings import settings
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_random_num():
return 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():
code = await generate()
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
-42
View File
@@ -1,42 +0,0 @@
import datetime
from sqlalchemy import Boolean, Column, Integer, String, DateTime, JSON, Text
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(settings.DATABASE_URL)
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
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)
code = Column(String(10), unique=True, index=True)
key = Column(String(30), unique=True, index=True)
name = Column(String(500))
size = Column(Integer)
type = Column(String(20))
text = Column(Text)
used = Column(Boolean, default=False)
count = Column(Integer, default=-1)
use_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
exp_time = Column(DateTime, nullable=True)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 KiB

After

Width:  |  Height:  |  Size: 56 KiB

+150 -127
View File
@@ -1,34 +1,32 @@
import asyncio
import datetime
import uuid
import asyncio
from pathlib import Path
import os
try:
import chardet
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 select, update, func
from sqlalchemy.ext.asyncio.session import AsyncSession
except ImportError:
os.system("pip install -r requirements.txt")
import chardet
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 select, update, func
from sqlalchemy.ext.asyncio.session import AsyncSession
import settings
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
from pydantic import BaseModel
from sqlalchemy import select, func, update
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request
from starlette.responses import HTMLResponse, FileResponse, RedirectResponse
from starlette.staticfiles import StaticFiles
from core.utils import error_ip_limit, upload_ip_limit, get_code, storage, delete_expire_files, get_token, \
get_expire_info
from core.depends import admin_required
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks, Header
from core.database import init_models, Options, Codes, get_session
from settings import settings
# 实例化FastAPI
app = FastAPI(debug=settings.DEBUG, docs_url=None, redoc_url=None)
app = FastAPI(debug=settings.DEBUG, redoc_url=None, )
@app.on_event('startup')
async def startup(s: AsyncSession = Depends(get_session)):
# 初始化数据库
await init_models(s)
# 启动后台任务,不定时删除过期文件
asyncio.create_task(delete_expire_files())
# 数据存储文件夹
DATA_ROOT = Path(settings.DATA_ROOT)
@@ -36,57 +34,55 @@ if not DATA_ROOT.exists():
DATA_ROOT.mkdir(parents=True)
# 静态文件夹,这个固定就行了,静态资源都放在这里
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())
app.mount('/static', StaticFiles(directory='./static'), name="static")
# 首页页面
index_html = open('templates/index.html', 'r', encoding='utf-8').read() \
.replace('{{title}}', settings.TITLE) \
.replace('{{description}}', settings.DESCRIPTION) \
.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)
index_html = open('templates/index.html', 'r', encoding='utf-8').read()
# 管理页面
admin_html = open('templates/admin.html', 'r', encoding='utf-8').read()
@app.get('/')
async def index():
return HTMLResponse(
index_html
.replace('{{title}}', settings.TITLE)
.replace('{{description}}', settings.DESCRIPTION)
.replace('{{keywords}}', settings.KEYWORDS)
.replace("'{{fileSizeLimit}}'", str(settings.FILE_SIZE_LIMIT))
)
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面')
async def admin():
return HTMLResponse(admin_html)
return HTMLResponse(
admin_html
.replace('{{title}}', settings.TITLE)
.replace('{{description}}', settings.DESCRIPTION)
.replace('{{admin_address}}', settings.ADMIN_ADDRESS)
.replace('{{keywords}}', settings.KEYWORDS)
)
@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.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:
await s.execute(update(Values).where(Values.key == 'config').values(value=await request.json()))
await s.commit()
return {'detail': '修改成功'}
infos = (await s.execute(select(Codes).offset((page - 1) * size).limit(size))).scalars().all()
data = [{
'id': info.id,
'code': info.code,
'name': info.name,
'exp_time': info.exp_time,
'count': info.count,
'text': info.text if info.type == 'text' else await storage.get_url(info),
} for info in infos]
return {
'detail': '查询成功',
'data': data,
'paginate': {
'page': page,
'size': size,
'total': (await s.execute(select(func.count(Codes.id)))).scalar()
}}
@app.delete(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='删除数据库记录')
@@ -105,16 +101,30 @@ async def admin_delete(code: str, s: AsyncSession = Depends(get_session)):
return {'detail': '删除成功'}
@app.get('/config', description='获取系统配置', dependencies=[Depends(admin_required)])
@app.get(f'/{settings.ADMIN_ADDRESS}/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 if data else {'banners': []}}
# 查询数据库
data = {}
for i in (await s.execute(select(Options))).scalars().all():
data[i.key] = i.value
return {'detail': '获取成功', 'data': data, 'menus': [
{'key': 'INSTALL', 'name': '版本信息'},
{'key': 'WEBSITE', 'name': '网站设置'},
{'key': 'SHARE', 'name': '分享设置'},
{'key': 'BANNERS', 'name': 'Banner'},
]}
@app.get('/')
async def index():
return HTMLResponse(index_html)
@app.patch(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='修改数据库数据')
async def admin_patch(request: Request, s: AsyncSession = Depends(get_session)):
data = await request.json()
data.pop('INSTALL')
for key, value in data.items():
await s.execute(update(Options).where(Options.key == key).values(value=value))
await settings.update(key, value)
await s.commit()
await settings.updates([[i.id, i.key, i.value] for i in (await s.execute(select(Options))).scalars().all()])
return {'detail': '修改成功'}
@app.post('/')
@@ -124,47 +134,33 @@ async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession =
if not info:
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:
if (info.exp_time and info.exp_time < datetime.datetime.now()) or info.count == 0:
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}'
info.text = f'/select?code={info.code}&token={await get_token(code, ip)}'
return {
'detail': f'取件成功,文件将在{settings.DELETE_EXPIRE_FILES_INTERVAL}分钟后删除',
'detail': f'取件成功,请立即下载,避免失效!',
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
}
@app.get('/banner')
async def banner(request: Request, 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'],
'enable': request.headers.get('pwd', '') == settings.ADMIN_PASSWORD or settings.ENABLE_UPLOAD,
}
# 如果不存在config,就返回默认的banner
async def banner(request: Request):
return {
'detail': 'banner',
'detail': '查询成功',
'data': settings.BANNERS,
'enable': request.headers.get('pwd', '') == settings.ADMIN_PASSWORD or settings.ENABLE_UPLOAD,
'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, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
async def get_file(code: str, token: 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)
info = (await s.execute(query)).scalars().first()
@@ -176,40 +172,67 @@ async def get_file(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession
if info.type == 'text':
return {'detail': '查询成功', 'data': info.text}
# 如果是文件,返回文件
elif storage.NAME != 'filesystem':
# 重定向到文件存储服务器
return RedirectResponse(await storage.get_url(info))
else:
filepath = await storage.get_filepath(info.text)
return FileResponse(filepath, filename=info.name)
@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 > 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:
raise HTTPException(status_code=400, detail="最小有效次数为1次")
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = value
else:
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = -1
key = uuid.uuid4().hex
if file:
size = await storage.get_size(file)
if size > settings.FILE_SIZE_LIMIT:
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)
s.add(info)
@app.post('/file/create/')
async def create_file():
# 生成随机字符串
return {'code': 200, 'data': await storage.create_upload_file()}
@app.post('/file/upload/{file_key}/')
async def upload_file(file_key: str, file: bytes = File(...), chunk_index: int = Form(...),
total_chunks: int = Form(...)):
await storage.save_chunk_file(file_key, file, chunk_index, total_chunks)
return {'code': 200}
@app.get('/file/merge/{file_key}/')
async def merge_chunks(file_key: str, file_name: str, total_chunks: int):
return {'code': 200, 'data': await storage.merge_chunks(file_key, file_name, total_chunks)}
class ShareDataModel(BaseModel):
text: str
size: int = 0
exp_style: str
exp_value: int
type: str
name: str
key: str = uuid.uuid4
@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))
await s.commit()
upload_ip_limit.add_ip(ip)
return {
+55 -12
View File
@@ -1,9 +1,12 @@
<div style="text-align: center">
<div align="center">
<h1>文件快递柜-轻量</h1>
<h2>FileCodeBox-Lite</h2>
<p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p>
<p>交流Q群:739673698,欢迎各位集思广益,项目构思重构中</p>
</div>
![banner](https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png)
---
[简体中文](./readme.md) | [English](./readme_en.md)
@@ -19,6 +22,8 @@
- [x] 匿名分享:无需注册,无需登录
- [x] 管理面板:查看所有文件,删除文件
- [x] 一键部署:docker一键部署
- [x] 自由拓展:阿里云OSS、本地文件流,可根据需求在storage文件中新增存储引擎
- [x] 简单明了:适合新手练手项目
## 部署方式
@@ -36,6 +41,10 @@ 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
```
### 宝塔部署
https://www.yuque.com/lxyo/work/lc1oe0xqk8t9b976
### 更新方式
```bash
@@ -45,6 +54,17 @@ docker stop filecodebox && docker rm filecodebox
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
```
### 1.6版本注意
这一版改变比较大,如果出现问题可以尝试清空/opt/FileCodeBox目录,有问题欢迎反馈留言
注意,如果是第一次安装,请查看docker日志获取初始密码和后台地址,参考指令
后台本地文件列表,需要将服务器文件移动至目录/opt/FileCodeBox/data/locals,这样就可以显示了。
```bash
docker logs filecodebox
```
### 其他方式
仅供参考,历史版本->[部署文档](https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v)
@@ -68,11 +88,11 @@ docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --n
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_10.png" alt="寄文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_10.png" alt="寄文件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_11.png" alt="寄文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_11.png" alt="寄文件">
</td>
</tr>
@@ -83,15 +103,15 @@ docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --n
<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="寄文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_1.png" alt="寄文件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png" alt="寄文本">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/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="寄文本">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_3.png" alt="寄文本">
</td>
</tr>
</table>
@@ -101,22 +121,36 @@ docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --n
<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="取件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_6.png" alt="取件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png" alt="取件码错误">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/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="取文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_4.png" alt="取文件">
</td>
</tr>
</table>
### 管理
![管理](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_7.png)
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_7.png" alt="admin">
</td>
<td style="width: 50%">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_12.png" alt="admin">
</td>
</tr>
<tr style="width: 100%;">
<td colspan="2" style="width: 100%;">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_13.png" alt="admin">
</td>
</tr>
</table>
## 配置文件
@@ -158,6 +192,15 @@ DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
# 存储引擎
STORAGE_ENGINE=filesystem
# 如果使用阿里云OSS服务的话需要额外创建如下参数:
# 阿里云账号AccessKey
KeyId=阿里云账号AccessKey
# 阿里云账号AccessKeySecret
KeySecret=阿里云账号AccessKeySecret
# 阿里云OSS Bucket的地域节点
OSS_ENDPOINT=阿里云OSS Bucket的地域节点
# 阿里云OSS Bucket的BucketName
BUCKET_NAME=阿里云OSS Bucket的BucketName
```
## 接口文档
@@ -236,11 +279,11 @@ file: 文件
<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="支付宝">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/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="微信">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_8.png" alt="微信">
</td>
</tr>
</table>
+39 -12
View File
@@ -1,9 +1,12 @@
<div style="text-align: center">
<div 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>
![banner](https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png)
---
[简体中文](./readme.md) | [English](./readme_en.md)
@@ -19,6 +22,7 @@
- [x] anonymous sharing: no registration, no login
- [x] management Panel: View all files and delete them
- [x] one-click deployment: docker one-click deployment
- [x] A variety of storage methods : Aliyun OSS、 local file flow
## Deployment method
@@ -80,11 +84,11 @@ If you have better ideas and suggestions, welcome to file an issue.
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_10.png" alt="寄文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_10.png" alt="寄文件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_11.png" alt="寄文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_11.png" alt="寄文件">
</td>
</tr>
@@ -95,15 +99,15 @@ If you have better ideas and suggestions, welcome to file an issue.
<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="寄文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_1.png" alt="寄文件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png" alt="寄文本">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/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="寄文本">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_3.png" alt="寄文本">
</td>
</tr>
</table>
@@ -113,22 +117,36 @@ If you have better ideas and suggestions, welcome to file an issue.
<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="取件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_6.png" alt="取件">
</td>
<td style="width: 50%">
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png" alt="取件码错误">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/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="取文件">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_4.png" alt="取文件">
</td>
</tr>
</table>
### Manage
![管理](https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_7.png)
<table style="width: 100%">
<tr style="width: 100%">
<td style="width: 50%">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_7.png" alt="admin">
</td>
<td style="width: 50%">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_12.png" alt="admin">
</td>
</tr>
<tr style="width: 100%;">
<td colspan="2" style="width: 100%;">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_13.png" alt="admin">
</td>
</tr>
</table>
## Configuration file
@@ -172,6 +190,15 @@ DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
# 存储引擎
STORAGE_ENGINE=filesystem
# 如果使用阿里云OSS服务的话需要额外创建如下参数:
# 阿里云账号AccessKey
KeyId=阿里云账号AccessKey
# 阿里云账号AccessKeySecret
KeySecret=阿里云账号AccessKeySecret
# 阿里云OSS Bucket的地域节点
OSS_ENDPOINT=阿里云OSS Bucket的地域节点
# 阿里云OSS Bucket的BucketName
BUCKET_NAME=阿里云OSS Bucket的BucketName
```
## Status
@@ -188,11 +215,11 @@ STORAGE_ENGINE=filesystem
<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="支付宝">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/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="微信">
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/images/img_8.png" alt="微信">
</td>
</tr>
</table>
+2 -1
View File
@@ -5,4 +5,5 @@ python-multipart==0.0.5
uvicorn==0.15.0
greenlet==2.0.1
starlette~=0.22.0
chardet == 5.1.0
oss2==2.16.0
uvicorn==0.15.0
+85 -49
View File
@@ -1,52 +1,88 @@
import uuid
from starlette.config import Config
import os
import shutil
# 配置文件.env
# 请将.env移动至data目录,方便docker部署
# 判断根目录下是否存在.env文件
if os.path.exists('.env'):
# 将文件复制到data目录
shutil.copy('.env', 'data/.env')
# 配置文件.env,存放为data/.env
config = Config("data/.env")
# 是否开启DEBUG模式
DEBUG = config('DEBUG', cast=bool, default=False)
# 端口
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=True)
# 最长天数
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_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")
class Settings:
# 项目版本
VERSION: str = config("VERSION", default="1.6")
# 是否开启DEBUG模式
DEBUG = config('DEBUG', cast=bool, default=False)
# 端口
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 = config('DATA_ROOT', cast=str, default=f"./data/static")
# 静态文件夹URL
STATIC_URL = config('STATIC_URL', cast=str, default="/static")
# 开启上传
ENABLE_UPLOAD = config('ENABLE_UPLOAD', cast=bool, default=True)
# 最长天数
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)
# 是否允许永久保存
ENABLE_PERMANENT = config('ENABLE_PERMANENT', cast=bool, default=True)
# 上传限制分钟数
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=uuid.uuid4().hex)
# 管理密码
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default=uuid.uuid4().hex)
# 文件大小限制,默认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,文件快递柜,口令传送箱,匿名口令分享文本,文件")
# 存储引擎:['aliyunsystem','filesystem']
STORAGE_ENGINE = config('STORAGE_ENGINE', cast=str, default="filesystem")
# 存储引擎配置
STORAGE_CONFIG = {}
# Banners
BANNERS = [{
'text': 'FileCodeBox',
'url': 'https://github.com/vastsa/FileCodeBox',
'src': '/static/banners/img_1.png'
}, {
'text': 'LanBlog',
'url': 'https://www.lanol.cn',
'src': '/static/banners/img_2.png'
}]
int_dict = {'PORT', 'MAX_DAYS', 'ERROR_COUNT', 'ERROR_MINUTE', 'UPLOAD_COUNT', 'UPLOAD_MINUTE',
'DELETE_EXPIRE_FILES_INTERVAL', 'FILE_SIZE_LIMIT'}
bool_dict = {'DEBUG', 'ENABLE_UPLOAD'}
async def update(self, key, value) -> None:
if hasattr(self, key):
if key in self.int_dict:
value = int(value)
elif key in self.bool_dict:
value = bool(value)
setattr(self, key, value)
async def updates(self, options) -> None:
with open('data/.env', 'w', encoding='utf-8') as f:
for i, key, value in options:
# 更新env文件
f.write(f"{key}={value}\n")
# 更新配置
await self.update(key, value)
f.flush()
settings = Settings()
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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 499 KiB

-72
View File
@@ -1,72 +0,0 @@
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)
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 = {
"filesystem": FileSystemStorage
}
+165 -33
View File
@@ -29,8 +29,8 @@
<el-row v-if="login" :gutter="10">
<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-item index="2">分享文件管理</el-menu-item>
<el-menu-item index="4">系统配置</el-menu-item>
</el-menu>
</el-col>
<el-col v-if="activeIndex === '2'">
@@ -43,9 +43,10 @@
<div>取件码:${ file.code }</div>
<div>文件名:${ file.name }</div>
<div>次&nbsp;&nbsp; 数:${ file.count }</div>
<div>到&nbsp;&nbsp; 期:${ file.exp_time.slice(0,19) }</div>
<div v-if="file.type==='text'">
<span>内&nbsp;&nbsp; 容:${ file.text }</span>
<div v-if="file.exp_time">到&nbsp;&nbsp; 期:${ file.exp_time.slice(0,19) }</div>
<div v-else>到&nbsp;&nbsp; 期:永不过期</div>
<div v-if="file.name==='文本分享'">
<span style="white-space: pre-line">内&nbsp;&nbsp; 容:${ file.text }</span>
</div>
<div v-else>
<span>链&nbsp;&nbsp; 接:</span>
@@ -72,24 +73,123 @@
>
</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 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 v-if="activeIndex === '4'">
<el-row>
<el-col :span="4" style="height: 88vh;overflow: scroll;text-align: center" :gutter="10">
<el-card v-for="menu in menus" :key="menu.key">
<div style="cursor: pointer;" @click="updateTab=menu.key">${menu.name}</div>
</el-card>
</el-col>
<el-col :span="20">
<el-card style="height: 88vh;overflow: scroll">
<div v-if="updateTab=='INSTALL'">
<div>
<h1>FileCodeBox V${config.INSTALL}</h1>
<h2>Github:<a target="_blank"
href="https://github.com/vastsa/FileCodeBox">FileCodeBox</a></h2>
</div>
</div>
<div v-else-if="updateTab=='BANNERS'">
<el-form ref="form" style="margin:1rem auto" :model="config" label-width="200px">
<el-form-item v-for="(banner,index) in config.BANNERS" :label="'Banner'+ (index+1)">
<div style="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>
</div>
<div v-else-if="updateTab=='WEBSITE'">
<el-form ref="form" style="margin:1rem auto" :model="config" label-width="200px">
<el-form-item label="后台密码">
<el-input type="password" v-model="config.ADMIN_PASSWORD"
placeholder="网站名称"></el-input>
</el-form-item>
<el-form-item label="网站名称">
<el-input v-model="config.TITLE" placeholder="网站名称"></el-input>
</el-form-item>
<el-form-item label="网站描述">
<el-input v-model="config.DESCRIPTION" placeholder="网站描述"></el-input>
</el-form-item>
<el-form-item label="网站关键词">
<el-input v-model="config.KEYWORDS" placeholder="网站关键词"></el-input>
</el-form-item>
<el-form-item>
<el-alert
title="下列信息修改后需要手动重启系统"
type="warning">
</el-alert>
</el-form-item>
<el-form-item label="系统端口">
<el-input v-model="config.PORT" placeholder="系统端口"></el-input>
</el-form-item>
<el-form-item label="后台地址">
<el-input v-model="config.ADMIN_ADDRESS" placeholder="后台地址"></el-input>
</el-form-item>
<el-form-item label="存储引擎">
<el-input v-model="config.STORAGE_ENGINE" placeholder="存储引擎"></el-input>
</el-form-item>
<el-form-item>
<el-button @click="updateConfig" type="primary">更新</el-button>
</el-form-item>
</el-form>
</div>
<div v-else-if="updateTab=='SHARE'">
<el-form ref="form" style="margin:1rem auto" :model="config" label-width="200px">
<el-form-item label="开启上传">
<el-input v-model="config.ENABLE_UPLOAD" placeholder="开启上传"></el-input>
</el-form-item>
<el-form-item label="最长天数">
<el-input v-model="config.MAX_DAYS" placeholder="最长允许保留多少天"></el-input>
</el-form-item>
<el-form-item label="删除过期间隔">
<el-input v-model="config.DELETE_EXPIRE_FILES_INTERVAL"
placeholder="删除过期文件的间隔(分钟)"></el-input>
</el-form-item>
<el-form-item label="上传大小限制">
<small>单位:(bit),1mb=1 * 1024 * 1024</small>
<el-input v-model="config.FILE_SIZE_LIMIT"
placeholder="上传大小限制(bit)"></el-input>
</el-form-item>
<el-form-item>
<el-alert
title="下列信息修改后需要手动重启系统"
type="warning">
</el-alert>
</el-form-item>
<el-form-item label="口令错误限制">
<small>每几分钟</small>
<el-input v-model="config.ERROR_MINUTE"
placeholder="错误次数过多后限制时间"></el-input>
<small>允许错误几次</small>
<el-input v-model="config.ERROR_COUNT" placeholder="允许错误次数"></el-input>
</el-form-item>
<el-form-item label="上传次数限制">
<small>每几分钟</small>
<el-input v-model="config.UPLOAD_MINUTE"
placeholder="每几分钟"></el-input>
<small>允许上传几次</small>
<el-input v-model="config.UPLOAD_COUNT"
placeholder="允许次数"></el-input>
</el-form-item>
<el-form-item>
<el-button @click="updateConfig" type="primary">更新</el-button>
</el-form-item>
</el-form>
</div>
</el-card>
</el-col>
</el-row>
</el-col>
</el-row>
<div v-else style="width: 250px;text-align: center;margin: 40vh auto">
@@ -97,6 +197,7 @@
<el-button slot="append" type="primary" @click="loginAdmin">登录</el-button>
</el-input>
</div>
</div>
</body>
@@ -113,7 +214,10 @@
config: {
banners: []
},
menus: [],
updateTab: 'INSTALL',
files: [],
locals: [],
paginate: {
page: 1,
size: 10,
@@ -126,18 +230,21 @@
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();
this.getLocalFiles();
}
},
methods: {
getConfig: function () {
axios.get(window.location.href + '/config', {
headers: {
pwd: this.pwd
}
}).then(res => {
this.config = res.data.data;
this.menus = res.data.menus;
});
},
updateSize: function (value) {
this.paginate.size = value;
this.loginAdmin();
@@ -147,10 +254,10 @@
this.loginAdmin();
},
deleteBanner: function (index) {
this.config.banners.splice(index, 1);
this.config.BANNERS.splice(index, 1);
},
addBanner: function () {
this.config.banners.push({
this.config.BANNERS.push({
'url': '',
'src': '',
'text': '',
@@ -180,6 +287,7 @@
this.files = res.data.data
this.login = true;
localStorage.setItem('pwd', this.pwd);
this.getConfig();
}).catch(e => {
localStorage.clear()
this.$message({'message': e.response.data.detail, 'type': 'error'});
@@ -197,6 +305,30 @@
});
})
},
getLocalFiles: function () {
axios.get(window.location.href + '/files', {
'headers': {
'pwd': this.pwd,
'Content-Type': 'multipart/form-data'
}
}).then(res => {
this.locals = res.data.data;
})
},
shareFile: function (file) {
axios.post(window.location.href + '/files', file, {
'headers': {
'pwd': this.pwd,
'Content-Type': 'multipart/form-data'
}
}).then(res => {
this.getLocalFiles()
this.$alert(`请在24小时内使用:${res.data.data.code}`, '分享成功', {
confirmButtonText: '确定',
});
})
}
}
})
</script>
+169 -54
View File
@@ -6,22 +6,23 @@
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/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"/>
<title>{{title}}</title>
<meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/>
<meta name="template" content="Lan-V1.5.9.2"/>
<meta name="template" content="V1.7 Beta"/>
<style>
body {
background: #f5f5f5;
}
.qu .el-button {
width: 100px;
height: 100px;
width: 6rem;
height: 6rem;
margin: 0.2rem;
font-size: 30px;
font-size: 2rem;
font-weight: bold;
}
@@ -43,7 +44,6 @@
}
@media (prefers-color-scheme: dark) {
body {
background-color: #18181c;
}
@@ -64,6 +64,14 @@
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 {
background-color: rgba(0, 0, 0, 0.5);
border: 1px solid transparent;
@@ -138,29 +146,39 @@
</el-carousel>
</div>
<el-row>
<el-input style="width: 190px" placeholder="数量" v-model="uploadData.value"
<el-input style="width: 190px" :disabled="uploadData.exp_style==='forever'" placeholder="数量"
v-model="uploadData.exp_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 style="width: 75px" v-model="uploadData.exp_style" slot="prepend"
placeholder="请选择">
<el-option label="天数" value="day"></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-button v-if="uploadData.style === '1'" slot="append" disabled>次</el-button>
<el-button v-else slot="append" disabled>天</el-button>
<el-button slot="append" disabled>${exp_style_dict[uploadData.exp_style]}</el-button>
</el-input>
<el-radio-group style="margin-left: 18px" v-model="uploadData.type">
<el-radio-group style="margin-left: 18px" v-model="uploadData.is_file">
<el-radio label="1">
文件
</el-radio>
<el-radio label="2">
<el-radio label="0">
文本
</el-radio>
</el-radio-group>
</el-row>
<el-upload
v-if="uploadData.type === '1'"
v-if="uploadData.is_file === '1'"
drag
v-loading="uploading"
action="/share"
:element-loading-text="loadingText"
element-loading-spinner="el-icon-loading"
multiple
:disabled="uploading"
:http-request="uploadFile"
style="margin: 1rem 0;"
:data="uploadData"
:before-upload="beforeUpload"
@@ -180,7 +198,6 @@
placeholder="请输入内容,使用按钮存入"
v-model="uploadData.text">
</el-input>
<div class="el-upload__tip">
<el-button round @click="pageNum=0">
<div class="el-icon-back"></div>
@@ -190,7 +207,7 @@
<div class="el-icon-takeaway-box"></div>
我的文件
</el-button>
<el-button round v-if="uploadData.type === '2'" @click="toUploadData">
<el-button round v-if="uploadData.is_file === '0'" @click="uploadText">
<div class="el-icon-upload2"></div>
存入
</el-button>
@@ -209,7 +226,7 @@
<div>取件码:${ file.code }</div>
<div>文件名:${ file.name }</div>
<div v-if="file.name==='文本分享'">
<span @click="copyText(file.text,1)">内&nbsp;&nbsp; 容:${ file.text }</span>
<article v-html="file.text" class="markdown-body" @click="copyText(file.text,1)"></article>
</div>
<div v-else>
<span>链&nbsp;&nbsp; 接:</span>
@@ -251,7 +268,7 @@
</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
V1.5.9.2</a>
V1.7 Beta</a>
</div>
</div>
</body>
@@ -266,8 +283,16 @@
quDrawer: false,
jiDrawer: false,
direction: 'btt',
exp_style_dict: {
'day': '天',
'hour': '时',
'minute': '分',
'forever': '无',
'count': '次',
},
quFiles: [],
jiFiles: [],
uploadGroup: [],
pageNum: 0,
inputDisable: false,
fileSizeLimit: '{{fileSizeLimit}}',
@@ -275,12 +300,16 @@
banners: [],
enableUpload: false,
uploadData: {
style: '2',
type: '1',
value: 1,
file: null,
text: ''
exp_style: 'day',
exp_value: 1,
type: 'text',
name: '文本分享',
is_file: '1',
text: '',
size: 0,
},
uploading: false,
loadingText: '正在上传中...',
};
},
mounted: function () {
@@ -302,14 +331,13 @@
that.$message('剪切板文字正在上传,请稍等');
items[i].getAsString(function (str) {
that.uploadData.text = str;
that.toUploadData();
that.uploadText();
});
}
} else {
const file = items[i].getAsFile();
that.$message('剪切板文件正在上传,请稍等');
that.uploadData.file = file
that.toUploadData();
that.uploadFile({file: file});
}
}
}
@@ -342,19 +370,35 @@
data: data,
...config
}).then(res => {
this.$message({
message: res.data.detail,
type: 'success'
});
if (res.data.detail) {
this.$message({
message: res.data.detail,
type: 'success'
});
}
resolve(res.data)
}).catch(err => {
this.$message({
message: err.response.data.detail,
type: 'error'
});
if (err.response.data.detail) {
this.$message({
message: err.response.data.detail,
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) {
if (style === 0) {
value = `我给你分享了文件,取件码:${value},${window.location.href}?code=${value}`;
@@ -412,34 +456,105 @@
}
return true;
},
toUploadData: function () {
if (this.uploadData.text === '' && this.uploadData.file === null) {
uploadText: function () {
if (this.uploadData.text === '') {
this.$message({
message: '请先粘贴文字或者上传文件',
message: '请先粘贴文字',
type: 'error'
});
} else {
if (this.checkFile(this.uploadData.file)) {
this.http('post', '/share', this.uploadData, {
headers: {
'Content-Type': 'multipart/form-data',
'pwd': this.pwd
}
}).then(res => {
this.jiFiles.unshift(res.data);
this.jiDrawer = true;
this.uploadData.text = '';
this.uploadData.file = null;
this.http('post', '/share/text/', this.uploadData, {
headers: {
'pwd': this.pwd
}
}).then(res => {
this.jiFiles.unshift(res.data);
this.jiDrawer = true;
this.uploadData.text = '';
this.$message({
message: '上传成功',
type: 'success'
});
}
})
}
},
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) {
this.$message({
message: response.detail,
type: 'success'
});
this.jiFiles.unshift(response.data);
if (response) {
this.$message({
message: response.detail,
type: 'success'
});
this.jiFiles.unshift(response.data);
}
},
errorUpload(error, file, fileList) {
error = JSON.parse(error.message)
-45
View File
@@ -1,45 +0,0 @@
import datetime
import random
import asyncio
import chardet
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)