Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d6f5ba9f4 | ||
|
|
422ae8adff | ||
|
|
cb340b6b22 | ||
|
|
b3533e897a | ||
|
|
0bc73796e7 | ||
|
|
594c105190 | ||
|
|
6caca3cb7b | ||
|
|
2d9348c293 | ||
|
|
ec6939f824 | ||
|
|
6d83e94c2f | ||
|
|
3c0376b63c | ||
|
|
f021673961 | ||
|
|
de190e6345 | ||
|
|
f9daa3cab3 | ||
|
|
965384500a | ||
|
|
eb9a656ee1 | ||
|
|
5543811c20 | ||
|
|
1f14997e4a | ||
|
|
5297146a63 | ||
|
|
d77dcb3f92 | ||
|
|
133e85fa49 | ||
|
|
a432f8d80f | ||
|
|
2a102bfb1f | ||
|
|
1994ba5917 | ||
|
|
68175f9583 | ||
|
|
0caabe3ee8 | ||
|
|
5c350cbfc6 | ||
|
|
0a200da28b | ||
|
|
7f2c1c9e7c | ||
|
|
12d28ec691 | ||
|
|
65ad220bb4 | ||
|
|
585bf0948c | ||
|
|
a258bb4ea3 | ||
|
|
d8985db3e1 | ||
|
|
a17a7e1d58 | ||
|
|
63d60022d2 | ||
|
|
1e2d83aeb6 | ||
|
|
fadb2ffeeb | ||
|
|
cc2a02cc65 | ||
|
|
676ef1e924 | ||
|
|
b948263519 | ||
|
|
8ffddd5870 | ||
|
|
2d7331269c | ||
|
|
11fb809b62 | ||
|
|
7ea84f0941 | ||
|
|
c9ec40803d | ||
|
|
9ecd2c2770 | ||
|
|
e6fa174c0b | ||
|
|
66d9e432bc | ||
|
|
b300463f54 | ||
|
|
bcf0be3d12 | ||
|
|
d4209bb3f7 | ||
|
|
2ba3057f72 | ||
|
|
bdf508264b | ||
|
|
4218caeaf7 | ||
|
|
24ad5e08ca | ||
|
|
31f67fae3f | ||
|
|
27fc665239 | ||
|
|
541d49d636 | ||
|
|
68881c6df0 | ||
|
|
fb80d26b70 | ||
|
|
9cf0d9418d | ||
|
|
4e069486bf | ||
|
|
8935da813b | ||
|
|
387a3babfd | ||
|
|
42dedfae1e | ||
|
|
cfd2989bc0 | ||
|
|
31b61a2f7a | ||
|
|
802b8a0a8f | ||
|
|
ef89de6294 | ||
|
|
74a835f8b6 | ||
|
|
2ef6c752ee | ||
|
|
bec3eb2ea1 | ||
|
|
ae7aa63e2a | ||
|
|
b999073da4 | ||
|
|
e5d18a5bf3 | ||
|
|
d25a92199f | ||
|
|
b7315bb840 | ||
|
|
ea647519c6 | ||
|
|
1dbcd8bd57 | ||
|
|
dd39423d1a | ||
|
|
ff831e39f4 | ||
|
|
0883eafa49 | ||
|
|
1dc6a741b6 | ||
|
|
f4e6dfef0d | ||
|
|
195c6f9ae4 | ||
|
|
710bb55a93 | ||
|
|
8ab74728ac | ||
|
|
1cbb7534f3 | ||
|
|
132aeee4cc | ||
|
|
896992aff6 | ||
|
|
2eb2c341eb | ||
|
|
ce6bc749c1 | ||
|
|
5f99457d14 | ||
|
|
e5eb071c2d | ||
|
|
9b8b1e81fe | ||
|
|
77b7c58885 | ||
|
|
94fc0e856b | ||
|
|
5cbb122ddf | ||
|
|
5eec46605b | ||
|
|
b273d38b31 | ||
|
|
90d1ab7330 | ||
|
|
f4ba56138d |
No files matched your search
@@ -0,0 +1,3 @@
|
||||
*.js linguist-language=python
|
||||
*.css linguist-language=python
|
||||
*.html linguist-language=python
|
||||
@@ -1,7 +1,7 @@
|
||||
media/
|
||||
logs/
|
||||
.idea
|
||||
/static/upload
|
||||
/data
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
@@ -111,7 +111,7 @@ celerybeat.pid
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
data/.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
@@ -150,6 +150,6 @@ for_test.py
|
||||
.html
|
||||
/evaluate/temp.py
|
||||
/evaluation/back.json
|
||||
.env*
|
||||
data/.env
|
||||
.backup/
|
||||
/cloc-1.64.exe
|
||||
@@ -1,13 +1,11 @@
|
||||
FROM python:3.9.5
|
||||
FROM python:3.9.5-slim-buster
|
||||
LABEL author="Lan"
|
||||
LABEL email="vast@tom.com"
|
||||
LABEL version="1.0"
|
||||
LABEL version="1.5.4"
|
||||
|
||||
|
||||
COPY . /app
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
RUN echo 'Asia/Shanghai' >/etc/timezone
|
||||
WORKDIR /app
|
||||
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
|
||||
RUN pip install -r requirements.txt
|
||||
EXPOSE 12345
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "12345"]
|
||||
CMD ["python","main.py"]
|
||||
@@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
@@ -1,17 +1,27 @@
|
||||
import datetime
|
||||
|
||||
from sqlalchemy import create_engine, DateTime
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import Boolean, Column, Integer, String, DateTime
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy import Boolean, Column, Integer, String
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
import settings
|
||||
|
||||
engine = create_async_engine(settings.DATABASE_URL)
|
||||
|
||||
engine = create_engine('sqlite:///database.db', connect_args={"check_same_thread": False})
|
||||
Base = declarative_base()
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
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 Codes(Base):
|
||||
__tablename__ = 'codes'
|
||||
__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)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
from typing import Union
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import Header, HTTPException, Request
|
||||
|
||||
import settings
|
||||
|
||||
|
||||
async def admin_required(pwd: Union[str, None] = Header(default=None), request: Request = None):
|
||||
if 'share' in request.url.path:
|
||||
if pwd != settings.ADMIN_PASSWORD and not settings.ENABLE_UPLOAD:
|
||||
raise HTTPException(status_code=403, detail='本站上传功能已关闭,仅管理员可用')
|
||||
else:
|
||||
if not pwd or pwd != settings.ADMIN_PASSWORD:
|
||||
raise HTTPException(status_code=401, detail="密码错误,请重新登录")
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
ips = {}
|
||||
count = 0
|
||||
minutes = 0
|
||||
|
||||
def __init__(self, count, minutes):
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
|
||||
def check_ip(self, ip):
|
||||
# 检查ip是否被禁止
|
||||
if ip in self.ips:
|
||||
if self.ips[ip]['count'] >= self.count:
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
else:
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip):
|
||||
ip_info = self.ips.get(ip, {'count': 0, 'time': datetime.now()})
|
||||
ip_info['count'] += 1
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info['count']
|
||||
|
||||
async def remove_expired_ip(self):
|
||||
for ip in list(self.ips.keys()):
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) < datetime.now():
|
||||
self.ips.pop(ip)
|
||||
|
||||
def __call__(self, request: Request):
|
||||
ip = request.headers.get('X-Real-IP', request.headers.get('X-Forwarded-For', request.client.host))
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=400, detail=f"请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -0,0 +1,33 @@
|
||||
## 更新记录
|
||||
|
||||
### 2022年12月13日
|
||||
|
||||
- [x] 完善手机版上传文本
|
||||
- [x] 优化Index.html首页
|
||||
- [x] 填补了由于上面修改带来的坑
|
||||
- [x] 更新了
|
||||
|
||||
### 2022年12月12日
|
||||
|
||||
- [x] 重写用户登录和 IP 检查并重定义状态码
|
||||
- [x] 新增存储引擎统一文件读写
|
||||
- [x] 设置PORT
|
||||
|
||||
### 2022年12月11日
|
||||
|
||||
1. 修复取件不显示码的问题
|
||||
2. 修复文件次数为1时,文件被删除的问题
|
||||
3. 使用 aiosqlite 驱动异步化数据库操作
|
||||
4. 增加定时清理过期文件
|
||||
5. 优化部署方式,Docker映射,后续更新直接覆盖代码重启
|
||||
6. 优化配置文件,增加配置项
|
||||
7. 发布V1.4.5稳定版
|
||||
|
||||
### 2022年12月10日
|
||||
|
||||
1. 管理面板已新增,一如既往的极简,只有删除
|
||||
2. 二维码图片(调用的网络接口,如果离线环境将无法使用,一切为了极简)
|
||||
3. 取件码有效期,取件码使用次数
|
||||
4. 优化代码逻辑
|
||||
5. 限制上传文件大小
|
||||
6. 完善配置参数
|
||||
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 121 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 40 KiB |
@@ -1,95 +1,79 @@
|
||||
import datetime
|
||||
import os
|
||||
import uuid
|
||||
import threading
|
||||
from fastapi import FastAPI, Depends, UploadFile, Form, File
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import HTMLResponse
|
||||
import random
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
|
||||
from starlette.responses import HTMLResponse, FileResponse
|
||||
from starlette.staticfiles import StaticFiles
|
||||
|
||||
import database
|
||||
from database import engine, SessionLocal, Base
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
app = FastAPI()
|
||||
if not os.path.exists('./static'):
|
||||
os.makedirs('./static')
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
index_html = open('templates/index.html', 'r', encoding='utf-8').read()
|
||||
admin_html = open('templates/admin.html', 'r', encoding='utf-8').read()
|
||||
# 过期时间
|
||||
exp_hour = 24
|
||||
# 允许错误次数
|
||||
error_count = 5
|
||||
# 禁止分钟数
|
||||
error_minute = 60
|
||||
# 后台地址
|
||||
admin_address = 'admin'
|
||||
# 管理密码
|
||||
admin_password = 'admin'
|
||||
error_ip_count = {}
|
||||
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
|
||||
from depends import admin_required
|
||||
|
||||
# 实例化FastAPI
|
||||
app = FastAPI(debug=settings.DEBUG, docs_url=None, redoc_url=None)
|
||||
|
||||
# 数据存储文件夹
|
||||
DATA_ROOT = Path(settings.DATA_ROOT)
|
||||
if not DATA_ROOT.exists():
|
||||
DATA_ROOT.mkdir(parents=True)
|
||||
|
||||
# 静态文件夹,这个固定就行了,静态资源都放在这里
|
||||
app.mount(settings.STATIC_URL, StaticFiles(directory='./static'), name="static")
|
||||
|
||||
|
||||
def delete_file(files):
|
||||
for file in files:
|
||||
os.remove('.' + file)
|
||||
@app.on_event('startup')
|
||||
async def startup():
|
||||
# 初始化数据库
|
||||
await init_models()
|
||||
# 启动后台任务,不定时删除过期文件
|
||||
asyncio.create_task(delete_expire_files())
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
# 首页页面
|
||||
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)
|
||||
|
||||
|
||||
def get_code(db: Session = Depends(get_db)):
|
||||
code = random.randint(10000, 99999)
|
||||
while db.query(database.Codes).filter(database.Codes.code == code).first():
|
||||
code = random.randint(10000, 99999)
|
||||
return str(code)
|
||||
|
||||
|
||||
def get_file_name(key, ext, file):
|
||||
now = datetime.datetime.now()
|
||||
path = f'./static/upload/{now.year}/{now.month}/{now.day}/'
|
||||
name = f'{key}.{ext}'
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
file = file.file.read()
|
||||
with open(f'{os.path.join(path, name)}', 'wb') as f:
|
||||
f.write(file)
|
||||
return key, len(file), path[1:] + name
|
||||
|
||||
|
||||
@app.get(f'/{admin_address}')
|
||||
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面', response_class=HTMLResponse)
|
||||
async def admin():
|
||||
return HTMLResponse(admin_html)
|
||||
|
||||
|
||||
@app.post(f'/{admin_address}')
|
||||
async def admin_post(request: Request, db: Session = Depends(get_db)):
|
||||
if request.headers.get('pwd') == admin_password:
|
||||
codes = db.query(database.Codes).all()
|
||||
return {'code': 200, 'msg': '查询成功', 'data': codes}
|
||||
else:
|
||||
return {'code': 400, 'msg': '密码错误'}
|
||||
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='查询数据库列表')
|
||||
async def admin_post(s: AsyncSession = Depends(get_session)):
|
||||
# 查询数据库列表
|
||||
codes = (await s.execute(select(Codes))).scalars().all()
|
||||
return {'detail': '查询成功', 'data': codes}
|
||||
|
||||
|
||||
@app.delete(f'/{admin_address}')
|
||||
async def admin_delete(request: Request, code: str, db: Session = Depends(get_db)):
|
||||
if request.headers.get('pwd') == admin_password:
|
||||
file = db.query(database.Codes).filter(database.Codes.code == code)
|
||||
if file.first().type != 'text/plain':
|
||||
threading.Thread(target=delete_file, args=([file.first().text],)).start()
|
||||
file.delete()
|
||||
db.commit()
|
||||
return {'code': 200, 'msg': '删除成功'}
|
||||
else:
|
||||
return {'code': 400, 'msg': '密码错误'}
|
||||
@app.delete(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='删除数据库记录')
|
||||
async def admin_delete(code: str, s: AsyncSession = Depends(get_session)):
|
||||
# 找到相应记录
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
# 找到第一条记录
|
||||
file = (await s.execute(query)).scalars().first()
|
||||
# 如果记录存在,并且不是文本
|
||||
if file and file.type != 'text':
|
||||
# 删除文件
|
||||
await storage.delete_file(file.text)
|
||||
# 删除数据库记录
|
||||
await s.delete(file)
|
||||
await s.commit()
|
||||
return {'detail': '删除成功'}
|
||||
|
||||
|
||||
@app.get('/')
|
||||
@@ -97,60 +81,81 @@ async def index():
|
||||
return HTMLResponse(index_html)
|
||||
|
||||
|
||||
@app.get('/select')
|
||||
async def get_file(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
|
||||
# 查出数据库记录
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
info = (await s.execute(query)).scalars().first()
|
||||
# 如果记录不存在,IP错误次数+1
|
||||
if not info:
|
||||
error_ip_limit.add_ip(ip)
|
||||
raise HTTPException(status_code=404, detail="口令不存在,次数过多将被禁止访问")
|
||||
# 如果是文本,直接返回
|
||||
if info.type == 'text':
|
||||
return {'detail': '查询成功', 'data': info.text}
|
||||
# 如果是文件,返回文件
|
||||
else:
|
||||
filepath = await storage.get_filepath(info.text)
|
||||
return FileResponse(filepath, filename=info.name)
|
||||
|
||||
|
||||
@app.post('/')
|
||||
async def index(request: Request, code: str, db: Session = Depends(get_db)):
|
||||
info = db.query(database.Codes).filter(database.Codes.code == code).first()
|
||||
error = error_ip_count.get(request.client.host, {'count': 0, 'time': datetime.datetime.now()})
|
||||
if error['count'] > error_count:
|
||||
if datetime.datetime.now() - error['time'] < datetime.timedelta(minutes=error_minute):
|
||||
return {'code': 404, 'msg': '请求过于频繁,请稍后再试'}
|
||||
else:
|
||||
error['count'] = 0
|
||||
else:
|
||||
if not info:
|
||||
error['count'] += 1
|
||||
error_ip_count[request.client.host] = error
|
||||
return {'code': 404, 'msg': f'取件码错误,错误5次将被禁止10分钟'}
|
||||
else:
|
||||
return {'code': 200, 'msg': '取件成功,请点击“取”查看', 'data': info}
|
||||
async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
|
||||
query = select(Codes).where(Codes.code == code)
|
||||
info = (await s.execute(query)).scalars().first()
|
||||
if not info:
|
||||
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:
|
||||
raise HTTPException(status_code=404, detail="取件码已失效,请联系寄件人")
|
||||
await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
|
||||
await s.commit()
|
||||
if info.type != 'text':
|
||||
info.text = f'/select?code={code}'
|
||||
return {
|
||||
'detail': f'取件成功,文件将在{settings.DELETE_EXPIRE_FILES_INTERVAL}分钟后删除',
|
||||
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
|
||||
}
|
||||
|
||||
|
||||
@app.post('/share')
|
||||
async def share(text: str = Form(default=None), file: UploadFile = File(default=None), db: Session = Depends(get_db)):
|
||||
cutoff_time = datetime.datetime.now() - datetime.timedelta(hours=exp_hour)
|
||||
olds = db.query(database.Codes).filter(database.Codes.use_time < cutoff_time)
|
||||
threading.Thread(target=delete_file, args=([old.text for old in olds if old.type != 'text/plain'],)).start()
|
||||
olds.delete()
|
||||
db.commit()
|
||||
code = get_code(db)
|
||||
if text:
|
||||
info = database.Codes(
|
||||
code=code,
|
||||
text=text,
|
||||
type='text/plain',
|
||||
key=uuid.uuid4().hex,
|
||||
size=len(text),
|
||||
used=True,
|
||||
name='分享文本'
|
||||
)
|
||||
db.add(info)
|
||||
db.commit()
|
||||
return {'code': 200, 'msg': '上传成功,请点击文件库查看',
|
||||
'data': {'code': code, 'name': '分享文本', 'text': text}}
|
||||
elif file:
|
||||
key, size, full_path = get_file_name(uuid.uuid4().hex, file.filename.split('.')[-1], file)
|
||||
info = database.Codes(
|
||||
code=code,
|
||||
text=full_path,
|
||||
type=file.content_type,
|
||||
key=key,
|
||||
size=size,
|
||||
used=True,
|
||||
name=file.filename
|
||||
)
|
||||
db.add(info)
|
||||
db.commit()
|
||||
return {'code': 200, 'msg': '上传成功,请点击文件库查看',
|
||||
'data': {'code': code, 'name': file.filename, 'text': full_path}}
|
||||
@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:
|
||||
return {'code': 422, 'msg': '参数错误', 'data': []}
|
||||
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)
|
||||
await s.commit()
|
||||
upload_ip_limit.add_ip(ip)
|
||||
return {
|
||||
'detail': '分享成功,请点击取件码按钮查看上传列表',
|
||||
'data': {'code': code, 'key': key, 'name': name, 'text': _text}
|
||||
}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run('main:app', host='0.0.0.0', port=settings.PORT, reload=settings.DEBUG)
|
||||
@@ -1,72 +1,157 @@
|
||||
# 口令传送箱
|
||||
<div style="text-align: center">
|
||||
<h1>文件快递柜-轻量</h1>
|
||||
<h2>FileCoxBox-Lite</h2>
|
||||
<p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p>
|
||||
</div>
|
||||
|
||||
## 解决问题
|
||||
---
|
||||
|
||||
很多时候,我们都想将一些文件或文本传送给别人,或者跨端传递一些信息,但是我们又不想为了分享,而去下载一些七里八里端软件,这时候,我们就可以使用口令传送箱。
|
||||
[简体中文](./readme.md) | [English](./readme_en.md)
|
||||
|
||||
## 主要特色
|
||||
|
||||
- [x] 轻量简洁,Fastapi+sqlite3
|
||||
- [x] 拖拽,复制粘贴上传
|
||||
- [x] 文件口令传输,生成二维码
|
||||
- [x] 分享文件:多种上传方式供你选择
|
||||
- [x] 分享文本:直接复制粘贴直接上传
|
||||
- [x] 防爆破:错误五次拉黑十分钟
|
||||
- [x] 完全匿名:不记录任何信息
|
||||
- [x] 无需注册:无需注册,无需登录
|
||||
- [x] Sqlite3数据库:无需安装数据库
|
||||
- [x] 可以加get参数code,这样打开就会读取取件码如:http://xxx.com?code=12345
|
||||
- [x] 管理面板:简单列表页删除违规文件
|
||||
- [ ] 口令使用次数,口令有效期,二维码分享
|
||||
- [x] 轻量简洁:Fastapi+Sqlite3+Vue2+ElementUI
|
||||
- [x] 轻松上传:复制粘贴,拖拽选择
|
||||
- [x] 多种类型:文本,文件
|
||||
- [x] 防止爆破:错误次数限制
|
||||
- [x] 防止滥用:IP限制上传次数
|
||||
- [x] 口令分享:随机口令,存取文件,自定义次数以及有效期
|
||||
- [x] 匿名分享:无需注册,无需登录
|
||||
- [x] 管理面板:查看所有文件,删除文件
|
||||
- [x] 一键部署:docker一键部署
|
||||
|
||||
## 更新记录
|
||||
## 未来规划
|
||||
|
||||
### 2022年12月10日 01:56:43
|
||||
2022年12月14日
|
||||
|
||||
1. 管理面板已新增,一如既往的极简,只有删除
|
||||
2. 二维码图片(调用的网络接口,如果离线环境将无法使用,一切为了极简)
|
||||
这个项目的灵感来源于丁丁快传,然后写了这么一个基于本机存储的快传系统,本系统主要是以轻量,单用户,离线环境(`私有化`
|
||||
)为主,因此也不需要加太多东西,所以其实这个项目到这基本功能已经完成了,剩下的就是维护和完善现有功能。
|
||||
|
||||
## 系统截图
|
||||
也不会再加入新的大功能了,如果有新的功能的话,那就是我们的Pro版本了,当然也是继续开源的,能和@veoco一起开源挺荣幸的,在他的代码中我学到了许多,此前我基本上是使用Django那一套,对Fastapi仅限于使用,他的许多写法让我受益匪浅,也让我对Fastapi有了更深的了解,所以我也会在Pro版本中使用Fastapi。
|
||||
|
||||
### 取件
|
||||
根据目前一些使用反馈来说,希望加入登录功能,还有多存储引擎等,欢迎各位继续提意见,加入我们共同开发。
|
||||
|
||||

|
||||

|
||||
如果你有更好的想法和建议欢迎提issue。
|
||||
|
||||
## 预览
|
||||
|
||||
### 例站
|
||||
|
||||
[https://share.lanol.cn](https://share.lanol.cn)
|
||||
|
||||
### 寄件
|
||||
|
||||

|
||||

|
||||
<table style="width: 100%">
|
||||
<tr style="width: 100%">
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_1.png" alt="寄文件">
|
||||
</td>
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png" alt="寄文本">
|
||||
</td>
|
||||
</tr>
|
||||
<tr style="width: 100%;">
|
||||
<td colspan="2" style="width: 100%;">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_3.png" alt="寄文本">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### 管理面板
|
||||
### 取件
|
||||
|
||||

|
||||

|
||||
<table style="width: 100%">
|
||||
<tr style="width: 100%">
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_6.png" alt="取件">
|
||||
</td>
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png" alt="取件码错误">
|
||||
</td>
|
||||
</tr>
|
||||
<tr style="width: 100%;">
|
||||
<td colspan="2" style="width: 100%;">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_4.png" alt="取文件">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### 管理
|
||||
|
||||

|
||||
|
||||
## 部署方式
|
||||
|
||||
先拉取代码,然后修改main.py文件,将里面写了注释的可以根据需求改一下
|
||||
|
||||
### 服务端部署
|
||||
|
||||
1. 安装Python3
|
||||
2. 拉取代码,解压缩
|
||||
3. 安装依赖包:`pip install -r requirements.txt`
|
||||
4. 运行` uvicorn main:app --host 0.0.0.0 --port 12345`
|
||||
5. 然后你自己看怎么进程守护吧
|
||||
|
||||
### 宝塔部署
|
||||
|
||||
1. 安装宝塔Python Manager
|
||||
2. 然后你自己看着填吧
|
||||
|
||||
### Docker部署
|
||||
### Docker一键部署
|
||||
|
||||
```bash
|
||||
docker build --file Dockerfile --tag filecodebox .
|
||||
docker run -d -p 12345:12345 --name filecodebox filecodebox
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### 其他方式
|
||||
|
||||
仅供参考,历史版本->[部署文档](https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v)
|
||||
|
||||
## 配置文件
|
||||
|
||||
如果需要修改配置,可以将该文件放在`/opt/FileCodeBox/`目录下,并命名为`.env`,然后重启容器即可。
|
||||
如果不是Docker,则需要在项目同目录下新建一个`data`文件夹,然后在创建`.env`文件
|
||||
|
||||
```dotenv
|
||||
# 端口
|
||||
PORT=12345
|
||||
# Sqlite数据库文件
|
||||
DATABASE_URL=sqlite+aiosqlite:///database.db
|
||||
# 静态文件夹
|
||||
DATA_ROOT=./static
|
||||
# 静态文件夹URL
|
||||
STATIC_URL=/static
|
||||
# 开启上传
|
||||
ENABLE_UPLOAD=True
|
||||
# 错误次数
|
||||
ERROR_COUNT=5
|
||||
# 错误限制分钟数
|
||||
ERROR_MINUTE=10
|
||||
# 上传次数
|
||||
UPLOAD_COUNT=60
|
||||
# 上传限制分钟数
|
||||
UPLOAD_MINUTE=1
|
||||
# 删除过期文件的间隔(分钟)
|
||||
DELETE_EXPIRE_FILES_INTERVAL=10
|
||||
# 管理地址
|
||||
ADMIN_ADDRESS=admin
|
||||
# 管理密码
|
||||
ADMIN_PASSWORD=admin
|
||||
# 文件大小限制,默认10MB
|
||||
FILE_SIZE_LIMIT=10
|
||||
# 网站标题
|
||||
TITLE=文件快递柜
|
||||
# 网站描述
|
||||
DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
|
||||
# 网站关键词
|
||||
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
|
||||
# 存储引擎
|
||||
STORAGE_ENGINE=filesystem
|
||||
```
|
||||
|
||||
## 状态
|
||||
|
||||

|
||||
|
||||
## 赞赏
|
||||
|
||||
<table style="width: 100%">
|
||||
<tr style="width: 100%">
|
||||
<td style="width: 50%;text-align: center;">
|
||||
支付宝
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_9.png" alt="支付宝">
|
||||
</td>
|
||||
<td style="width: 50%;text-align: center">
|
||||
微信
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_8.png" alt="微信">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 免责声明
|
||||
|
||||
本项目开源仅供学习使用,不得用于商业用途以及任何违法用途,否则后果自负,与本人无关。
|
||||
本项目开源仅供学习使用,不得用于任何违法用途,否则后果自负,与本人无关。使用请保留项目地址谢谢。
|
||||
@@ -0,0 +1,164 @@
|
||||
<div style="text-align: center">
|
||||
<h1>File Express Cabinet - Lite</h1>
|
||||
<h2>FileCodeBox - Lite</h2>
|
||||
<p><em>share text and files with anonymous passwords, and take files like express delivery </em></p>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
[简体中文](./readme.md) | [English](./readme_en.md)
|
||||
|
||||
## Main features
|
||||
|
||||
- [x] lightweight and simple: Fastapi + Sqlite3 + Vue2 + ElementUI
|
||||
- [x] easy upload: copy and paste, drag and drop
|
||||
- [x] multiple types: Text, File
|
||||
- [x] explosion Prevention: error count limit
|
||||
- [x] prevent abuse: IP address limits the number of uploads
|
||||
- [x] password sharing: random password, file access, custom times, and validity period
|
||||
- [x] anonymous sharing: no registration, no login
|
||||
- [x] management Panel: View all files and delete them
|
||||
- [x] one-click deployment: docker one-click deployment
|
||||
|
||||
## Future Plan
|
||||
|
||||
December 14, 2022
|
||||
This project is mainly light-weight, mainly single-user, offline environment, so there is no need to add too many
|
||||
things, so in fact, the basic functions of this project have been completed, and the rest is to maintain and improve the
|
||||
existing functions.
|
||||
|
||||
No new major functions will be added. If there are new functions, it will be our Pro version. Of course, it will
|
||||
continue to be open source. It is an honor to be open source with @veoco. I learned from his code Many, I basically used
|
||||
the Django set before, and only used Fastapi. Many of his writing methods have benefited me a lot, and I have a deeper
|
||||
understanding of Fastapi, so I will also use Fastapi in the Pro version .
|
||||
|
||||
According to some current feedback, I hope to add multi-user functions and multi-storage engines, etc. Welcome to
|
||||
continue to give comments and join us in joint development.
|
||||
|
||||
If you have better ideas and suggestions, welcome to file an issue.
|
||||
|
||||
## Preview
|
||||
|
||||
### Demo
|
||||
|
||||
[https://share.lanol.cn](https://share.lanol.cn)
|
||||
|
||||
### Send
|
||||
|
||||
<table style="width: 100%">
|
||||
<tr style="width: 100%">
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_1.png" alt="寄文件">
|
||||
</td>
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_2.png" alt="寄文本">
|
||||
</td>
|
||||
</tr>
|
||||
<tr style="width: 100%;">
|
||||
<td colspan="2" style="width: 100%;">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_3.png" alt="寄文本">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### Receive
|
||||
|
||||
<table style="width: 100%">
|
||||
<tr style="width: 100%">
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_6.png" alt="取件">
|
||||
</td>
|
||||
<td style="width: 50%">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_5.png" alt="取件码错误">
|
||||
</td>
|
||||
</tr>
|
||||
<tr style="width: 100%;">
|
||||
<td colspan="2" style="width: 100%;">
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_4.png" alt="取文件">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### Manage
|
||||
|
||||

|
||||
|
||||
## Deployment method
|
||||
|
||||
### One-click Docker deployment
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### Other methods
|
||||
|
||||
For reference only, historical version->[部署文档](https://www.yuque.com/lxyo/work/zd0kvzy7fofx6w7v)
|
||||
|
||||
## Configuration file
|
||||
|
||||
if you need to modify the configuration, you can put the file in `/opt/FileCodeBox/` directory and name it `.env` , and
|
||||
then restart the container.
|
||||
If it is not Docker, you need to create a `data` folder in the same directory as the project, and then create a `.env`
|
||||
file
|
||||
|
||||
```dotenv
|
||||
# 端口
|
||||
PORT=12345
|
||||
# Sqlite数据库文件
|
||||
DATABASE_URL=sqlite+aiosqlite:///database.db
|
||||
# 静态文件夹
|
||||
DATA_ROOT=./static
|
||||
# 静态文件夹URL
|
||||
STATIC_URL=/static
|
||||
# 开启上传
|
||||
ENABLE_UPLOAD=True
|
||||
# 错误次数
|
||||
ERROR_COUNT=5
|
||||
# 错误限制分钟数
|
||||
ERROR_MINUTE=10
|
||||
# 上传次数
|
||||
UPLOAD_COUNT=60
|
||||
# 上传限制分钟数
|
||||
UPLOAD_MINUTE=1
|
||||
# 删除过期文件的间隔(分钟)
|
||||
DELETE_EXPIRE_FILES_INTERVAL=10
|
||||
# 管理地址
|
||||
ADMIN_ADDRESS=admin
|
||||
# 管理密码
|
||||
ADMIN_PASSWORD=admin
|
||||
# 文件大小限制,默认10MB
|
||||
FILE_SIZE_LIMIT=10
|
||||
# 网站标题
|
||||
TITLE=文件快递柜
|
||||
# 网站描述
|
||||
DESCRIPTION=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
|
||||
# 网站关键词
|
||||
KEYWORDS=FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件,图片,视频,音频,压缩包等文件
|
||||
# 存储引擎
|
||||
STORAGE_ENGINE=filesystem
|
||||
```
|
||||
|
||||
## Status
|
||||
|
||||

|
||||
|
||||
## Appreciate
|
||||
|
||||
<table style="width: 100%">
|
||||
<tr style="width: 100%">
|
||||
<td style="width: 50%;text-align: center;">
|
||||
支付宝
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_9.png" alt="支付宝">
|
||||
</td>
|
||||
<td style="width: 50%;text-align: center">
|
||||
微信
|
||||
<img src="https://raw.githubusercontent.com/vastsa/FileCodeBox/master/images/img_8.png" alt="微信">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Disclaimer
|
||||
|
||||
this project is open source for learning only and cannot be used for any illegal purposes. Otherwise, you will be
|
||||
responsible for the consequences and have nothing to do with yourself. Please keep the project address. Thank you.
|
||||
@@ -1,4 +1,7 @@
|
||||
fastapi==0.88.0
|
||||
python-multipart==0.0.5
|
||||
aiosqlite==0.17.0
|
||||
SQLAlchemy==1.4.44
|
||||
uvicorn==0.20.0
|
||||
python-multipart==0.0.5
|
||||
uvicorn==0.15.0
|
||||
greenlet==2.0.1
|
||||
starlette~=0.22.0
|
||||
@@ -0,0 +1,45 @@
|
||||
from starlette.config import Config
|
||||
|
||||
# 配置文件.env
|
||||
# 请将.env移动至data目录,方便docker部署
|
||||
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=False)
|
||||
# 最长天数
|
||||
MAX_DAYS = config('MAX_DAYS', cast=int, default=7)
|
||||
# 错误次数
|
||||
ERROR_COUNT = config('ERROR_COUNT', cast=int, default=5)
|
||||
# 错误限制分钟数
|
||||
ERROR_MINUTE = config('ERROR_MINUTE', cast=int, default=10)
|
||||
# 上传次数
|
||||
UPLOAD_COUNT = config('UPLOAD_COUNT', cast=int, default=60)
|
||||
# 上传限制分钟数
|
||||
UPLOAD_MINUTE = config('UPLOAD_MINUTE', cast=int, default=1)
|
||||
# 删除过期文件的间隔(分钟)
|
||||
DELETE_EXPIRE_FILES_INTERVAL = config('DELETE_EXPIRE_FILES_INTERVAL', cast=int, default=10)
|
||||
# 管理地址
|
||||
ADMIN_ADDRESS = config('ADMIN_ADDRESS', cast=str, default="admin")
|
||||
# 管理密码
|
||||
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default="admin")
|
||||
# 文件大小限制,默认10MB
|
||||
FILE_SIZE_LIMIT = config('FILE_SIZE_LIMIT', cast=int, default=10) * 1024 * 1024
|
||||
# 网站标题
|
||||
TITLE = config('TITLE', cast=str, default="文件快递柜")
|
||||
# 网站描述
|
||||
DESCRIPTION = config('DESCRIPTION', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
|
||||
# 网站关键词
|
||||
KEYWORDS = config('KEYWORDS', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
|
||||
# 存储引擎
|
||||
STORAGE_ENGINE = config('STORAGE_ENGINE', cast=str, default="filesystem")
|
||||
@@ -1 +0,0 @@
|
||||
var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c<a.length&&0==a[c];)c++;this.num=new Array(a.length-c+b);for(var d=0;d<a.length-c;d++)this.num[d]=a[d+c]}function j(a,b){this.totalCount=a,this.dataCount=b}function k(){this.buffer=[],this.length=0}function m(){return"undefined"!=typeof CanvasRenderingContext2D}function n(){var a=!1,b=navigator.userAgent;return/android/i.test(b)&&(a=!0,aMat=b.toString().match(/android ([0-9]\.[0-9])/i),aMat&&aMat[1]&&(a=parseFloat(aMat[1]))),a}function r(a,b){for(var c=1,e=s(a),f=0,g=l.length;g>=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=new Array(this.moduleCount);for(var e=0;e<this.moduleCount;e++)this.modules[d][e]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,c),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f<this.modules.length;f++)for(var g=f*e,h=0;h<this.modules[f].length;h++){var i=h*e,j=this.modules[f][h];j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}return d},setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(var b=8;b<this.moduleCount-8;b++)null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)},setupPositionAdjustPattern:function(){for(var a=f.getPatternPosition(this.typeNumber),b=0;b<a.length;b++)for(var c=0;c<a.length;c++){var d=a[b],e=a[c];if(null==this.modules[d][e])for(var g=-2;2>=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g<a.length&&(j=1==(1&a[g]>>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,cLine truncated
|
||||
|
After Width: | Height: | Size: 264 KiB |
|
After Width: | Height: | Size: 33 KiB |
@@ -0,0 +1,61 @@
|
||||
import os
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
from fastapi import UploadFile
|
||||
|
||||
import settings
|
||||
|
||||
|
||||
class FileSystemStorage:
|
||||
DATA_ROOT = Path(settings.DATA_ROOT)
|
||||
STATIC_URL = settings.STATIC_URL
|
||||
NAME = "filesystem"
|
||||
|
||||
async def get_filepath(self, text: str):
|
||||
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
|
||||
|
||||
async def get_text(self, file: UploadFile, key: str):
|
||||
ext = file.filename.split('.')[-1]
|
||||
now = datetime.now()
|
||||
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
||||
if not path.exists():
|
||||
path.mkdir(parents=True)
|
||||
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT)}"
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
async def get_size(file: UploadFile):
|
||||
f = file.file
|
||||
f.seek(0, os.SEEK_END)
|
||||
size = f.tell()
|
||||
f.seek(0, os.SEEK_SET)
|
||||
return size
|
||||
|
||||
@staticmethod
|
||||
def _save(filepath, file: BinaryIO):
|
||||
with open(filepath, 'wb') as f:
|
||||
chunk_size = 256 * 1024
|
||||
chunk = file.read(chunk_size)
|
||||
while chunk:
|
||||
f.write(chunk)
|
||||
chunk = file.read(chunk_size)
|
||||
|
||||
async def save_file(self, file: UploadFile, text: str):
|
||||
filepath = await self.get_filepath(text)
|
||||
await asyncio.to_thread(self._save, filepath, file.file)
|
||||
|
||||
async def delete_file(self, text: str):
|
||||
filepath = await self.get_filepath(text)
|
||||
await asyncio.to_thread(os.remove, filepath)
|
||||
|
||||
async def delete_files(self, texts):
|
||||
tasks = [self.delete_file(text) for text in texts]
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
|
||||
STORAGE_ENGINE = {
|
||||
"filesystem": FileSystemStorage
|
||||
}
|
||||
@@ -5,14 +5,23 @@
|
||||
<meta name="viewport"
|
||||
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<link rel="stylesheet" href="/static/assert/index.css">
|
||||
<title>后台管理-口令传送箱</title>
|
||||
<link rel="stylesheet" href="/static/asserts/index.css">
|
||||
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
|
||||
<title>后台管理-{{title}}</title>
|
||||
<meta name="description" content="{{description}}"/>
|
||||
<meta name="keywords" content="{{keywords}}"/>
|
||||
<meta name="generator" content="FileCodeBox"/>
|
||||
<meta name="template" content="Lan"/>
|
||||
<script src="/static/asserts/vue.min.js"></script>
|
||||
<script src="/static/asserts/index.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<el-row v-if="login">
|
||||
<el-col :span="4"> </el-col>
|
||||
<el-col :span="16">
|
||||
<el-row v-if="login" :gutter="10">
|
||||
<el-col :xs="0" :sm="4" :md="4" :lg="4" :xl="4">
|
||||
|
||||
</el-col>
|
||||
<el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
|
||||
<el-card>
|
||||
<el-empty v-if="files.length===0" description="暂时还没有文件"></el-empty>
|
||||
<el-card v-for="file in files" :key="file.code">
|
||||
@@ -21,7 +30,9 @@
|
||||
<div style="cursor: pointer;text-align: left">
|
||||
<div>取件码:${ file.code }</div>
|
||||
<div>文件名:${ file.name }</div>
|
||||
<div v-if="file.name==='分享文本'">
|
||||
<div>次 数:${ file.count }</div>
|
||||
<div>到 期:${ file.exp_time.slice(0,19) }</div>
|
||||
<div v-if="file.type==='text'">
|
||||
<span>内 容:${ file.text }</span>
|
||||
</div>
|
||||
<div v-else>
|
||||
@@ -39,7 +50,7 @@
|
||||
</el-card>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<el-col :span="4"> </el-col>
|
||||
<el-col :xs="0" :sm="4" :md="4" :lg="4" :xl="4"> </el-col>
|
||||
</el-row>
|
||||
<div v-else style="width: 250px;text-align: center;margin: 40vh auto">
|
||||
<el-input v-model="pwd" placeholder="请输入登录密码">
|
||||
@@ -49,9 +60,7 @@
|
||||
</div>
|
||||
|
||||
</body>
|
||||
<script src="/static/assert/vue.min.js"></script>
|
||||
<script src="/static/assert/index.js"></script>
|
||||
<script src="/static/assert/axios.min.js"></script>
|
||||
<script src="/static/asserts/axios.min.js"></script>
|
||||
<script>
|
||||
new Vue({
|
||||
el: '#app',
|
||||
@@ -60,7 +69,12 @@
|
||||
return {
|
||||
login: false,
|
||||
pwd: '',
|
||||
files: []
|
||||
files: [],
|
||||
config: {
|
||||
error_count: 0,
|
||||
file_size: 0,
|
||||
admin_pwd: 'admin'
|
||||
}
|
||||
};
|
||||
},
|
||||
mounted: function () {
|
||||
@@ -74,30 +88,23 @@
|
||||
methods: {
|
||||
loginAdmin: function () {
|
||||
axios.post('', {}, {'headers': {'pwd': this.pwd}}).then(res => {
|
||||
if (res.data.code === 200) {
|
||||
this.files = res.data.data;
|
||||
this.login = true;
|
||||
localStorage.setItem('pwd', this.pwd);
|
||||
} else {
|
||||
localStorage.clear()
|
||||
this.$message({
|
||||
message: res.data.msg,
|
||||
type: 'error'
|
||||
});
|
||||
}
|
||||
})
|
||||
this.files = res.data.data;
|
||||
this.login = true;
|
||||
localStorage.setItem('pwd', this.pwd);
|
||||
}).catch(e => {
|
||||
localStorage.clear()
|
||||
this.$message({'message': e.response.data.detail, 'type': 'error'});
|
||||
});
|
||||
},
|
||||
deleteFile: function (code) {
|
||||
axios.delete('?code=' + code, {'headers': {'pwd': this.pwd}}).then(res => {
|
||||
if (res.data.code === 200) {
|
||||
this.files = this.files.filter(item => item.code !== code)
|
||||
this.$message({
|
||||
message: res.data.msg,
|
||||
type: 'success'
|
||||
});
|
||||
}
|
||||
this.files = this.files.filter(item => item.code !== code)
|
||||
this.$message({
|
||||
message: res.data.detail,
|
||||
type: 'success'
|
||||
});
|
||||
})
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -5,9 +5,13 @@
|
||||
<meta name="viewport"
|
||||
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<link rel="stylesheet" href="/static/assert/index.css">
|
||||
<!-- 引入组件库 -->
|
||||
<title>口令传送箱</title>
|
||||
<link rel="stylesheet" href="/static/asserts/index.css">
|
||||
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
|
||||
<title>{{title}}</title>
|
||||
<meta name="description" content="{{description}}"/>
|
||||
<meta name="keywords" content="{{keywords}}"/>
|
||||
<meta name="generator" content="FileCodeBox"/>
|
||||
<meta name="template" content="Lan-V1.5.5"/>
|
||||
<style>
|
||||
.qu .el-button {
|
||||
width: 100px;
|
||||
@@ -22,81 +26,131 @@
|
||||
margin: 1rem 0;
|
||||
font-size: 30px;
|
||||
font-weight: bold;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
|
||||
</style>
|
||||
<script src="/static/asserts/vue.min.js"></script>
|
||||
<script src="/static/asserts/index.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" style="text-align: center;">
|
||||
<el-row v-if="tool==0" class="qu" style="width:400px;margin: auto">
|
||||
<div id="app" style="text-align: center">
|
||||
<el-row v-if="pageNum === 0" class="qu" style="width:400px;margin: 6vh auto 0 auto">
|
||||
<el-card style="padding-bottom: 1rem">
|
||||
<el-col :span="24">
|
||||
<el-input autofocus @input="inputing" clearable v-model:value="code" maxlength="5"
|
||||
:disabled="inout_disable"
|
||||
placeholder="请输入取件码"></el-input>
|
||||
<el-input round autofocus @change="changeInput" clearable v-model:value="code" maxlength="5"
|
||||
:disabled="inputDisable" placeholder="请输入五位取件码">
|
||||
</el-input>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('1')">1</el-button>
|
||||
<el-button round @click="listenInput('1')">1</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('2')">2</el-button>
|
||||
<el-button round @click="listenInput('2')">2</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('3')">3</el-button>
|
||||
<el-button round @click="listenInput('3')">3</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('4')">4</el-button>
|
||||
<el-button round @click="listenInput('4')">4</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('5')">5</el-button>
|
||||
<el-button round @click="listenInput('5')">5</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('6')">6</el-button>
|
||||
<el-button round @click="listenInput('6')">6</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('7')">7</el-button>
|
||||
<el-button round @click="listenInput('7')">7</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('8')">8</el-button>
|
||||
<el-button round @click="listenInput('8')">8</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('9')">9</el-button>
|
||||
<el-button round @click="listenInput('9')">9</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="tool=1">寄</el-button>
|
||||
<el-button round @click="pageNum=1">
|
||||
<div style="height: 10px" class="el-icon-upload2"></div>
|
||||
</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="inputNumber('0')">0</el-button>
|
||||
<el-button round @click="listenInput('0')">0</el-button>
|
||||
</el-col>
|
||||
<el-col :span=8>
|
||||
<el-button @click="quDrawer=true">取</el-button>
|
||||
<el-button round @click="quDrawer=true">
|
||||
<div class="el-icon-takeaway-box"></div>
|
||||
</el-button>
|
||||
</el-col>
|
||||
</el-card>
|
||||
</el-row>
|
||||
<el-row v-else style="width:400px;margin: auto">
|
||||
<el-row v-else style="width:400px;margin: 20vh auto 0 auto">
|
||||
<el-col :span="24" style="margin: 1rem 0">
|
||||
<el-card>
|
||||
<el-row>
|
||||
<el-input style="width: 190px" placeholder="数量" v-model="uploadData.value"
|
||||
class="input-with-select">
|
||||
<el-select style="width: 75px" v-model="uploadData.style" slot="prepend" placeholder="请选择">
|
||||
<el-option label="天数" value="2"></el-option>
|
||||
<el-option label="次数" value="1"></el-option>
|
||||
</el-select>
|
||||
<el-button v-if="uploadData.style === '1'" slot="append" disabled>次</el-button>
|
||||
<el-button v-else slot="append" disabled>天</el-button>
|
||||
</el-input>
|
||||
<el-radio-group style="margin-left: 18px" v-model="uploadData.type">
|
||||
<el-radio label="1">
|
||||
文件
|
||||
</el-radio>
|
||||
<el-radio label="2">
|
||||
文本
|
||||
</el-radio>
|
||||
</el-radio-group>
|
||||
</el-row>
|
||||
|
||||
<el-upload
|
||||
v-if="uploadData.type === '1'"
|
||||
drag
|
||||
action="/share"
|
||||
multiple
|
||||
style="margin: 1rem 0;"
|
||||
:data="uploadData"
|
||||
:before-upload="beforeUpload"
|
||||
:headers="{'pwd':pwd}"
|
||||
:on-success="successUpload"
|
||||
:on-error="errorUpload"
|
||||
>
|
||||
<i class="el-icon-upload"></i>
|
||||
<div class="el-upload__text">将文件拖、粘贴到此处,或<em>点击上传</em>,24h后删除</div>
|
||||
<div class="el-upload__tip" slot="tip">
|
||||
<el-button @click="tool=0">去取件</el-button>
|
||||
<el-button @click="cunDrawer=true">文件箱</el-button>
|
||||
</div>
|
||||
<div class="el-upload__text">将文字、文件拖、粘贴到此处,或<em>点击上传</em></div>
|
||||
<div class="el-upload__text" style="font-size: 10px">天数<7或限制次数(24h后删除)</div>
|
||||
</el-upload>
|
||||
<el-input
|
||||
v-else
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 8}"
|
||||
style="margin: 1rem 0"
|
||||
placeholder="请输入内容,使用按钮存入"
|
||||
v-model="uploadData.text">
|
||||
</el-input>
|
||||
<div class="el-upload__tip">
|
||||
<el-button round @click="pageNum=0">
|
||||
<div class="el-icon-back"></div>
|
||||
取件
|
||||
</el-button>
|
||||
<el-button round @click="jiDrawer=true">
|
||||
<div class="el-icon-takeaway-box"></div>
|
||||
我的文件
|
||||
</el-button>
|
||||
<el-button round v-if="uploadData.type === '2'" @click="toUploadData">
|
||||
<div class="el-icon-upload2"></div>
|
||||
存入
|
||||
</el-button>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<div style="text-align: center; margin-top: 1rem;color: #606266">
|
||||
<span> <a style="text-decoration: none;color: #606266" target="_blank"
|
||||
href="https://github.com/vastsa/FileCodeBox">FileCodeBox</a></span>
|
||||
</div>
|
||||
<el-drawer
|
||||
title="文件库"
|
||||
title="文件箱"
|
||||
:visible.sync="quDrawer"
|
||||
:direction="direction"
|
||||
size="50%"
|
||||
@@ -105,7 +159,7 @@
|
||||
<div style="cursor: pointer;text-align: left">
|
||||
<div>取件码:${ file.code }</div>
|
||||
<div>文件名:${ file.name }</div>
|
||||
<div v-if="file.name==='分享文本'">
|
||||
<div v-if="file.name==='文本分享'">
|
||||
<span>内 容:${ file.text }</span>
|
||||
</div>
|
||||
<div v-else>
|
||||
@@ -119,13 +173,13 @@
|
||||
<el-empty v-if="files.length===0" description="请输入取件码,收取文件"></el-empty>
|
||||
</el-drawer>
|
||||
<el-drawer
|
||||
title="文件库"
|
||||
:visible.sync="cunDrawer"
|
||||
direction="btt"
|
||||
title="文件箱"
|
||||
:visible.sync="jiDrawer"
|
||||
:direction="direction"
|
||||
size="50%">
|
||||
<el-card>
|
||||
<el-empty v-if="files.length===0" description="请上传文件"></el-empty>
|
||||
<el-card style="margin-top: 0.2rem" v-for="file in files" :key="file.code">
|
||||
<el-card style="margin-top: 0.2rem" v-for="(file,index) in files" :key="index">
|
||||
<el-row>
|
||||
<el-col :span="20">
|
||||
<el-row>
|
||||
@@ -139,19 +193,18 @@
|
||||
</el-col>
|
||||
<el-col :span="4">
|
||||
<img style="width: 80px;height: 80px;"
|
||||
:src="qrcodeUrl(file)">
|
||||
:src="qrcodeUrl(file)" alt="二维码" :alt="file.code">
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-card>
|
||||
</el-card>
|
||||
</el-drawer>
|
||||
<div style="text-align: center; margin-top: 1rem;color: #606266">
|
||||
<a style="text-decoration: none;color: #606266" target="_blank" href="https://github.com/vastsa/FileCodeBox">FileCodeBox</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
<script src="/static/assert/qrcode.min.js"></script>
|
||||
<script src="/static/assert/vue.min.js"></script>
|
||||
<script src="/static/assert/index.js"></script>
|
||||
<script src="/static/assert/axios.min.js"></script>
|
||||
<script src="/static/asserts/axios.min.js"></script>
|
||||
<script>
|
||||
new Vue({
|
||||
el: '#app',
|
||||
@@ -159,107 +212,149 @@
|
||||
data: function () {
|
||||
return {
|
||||
code: '',
|
||||
inout_disable: false,
|
||||
files: [],
|
||||
quDrawer: false,
|
||||
cunDrawer: false,
|
||||
jiDrawer: false,
|
||||
direction: 'btt',
|
||||
tool: 0
|
||||
files: [],
|
||||
pageNum: 0,
|
||||
inputDisable: false,
|
||||
fileSizeLimit: '{{fileSizeLimit}}',
|
||||
pwd: localStorage.getItem('pwd') || '',
|
||||
uploadData: {
|
||||
style: '2',
|
||||
type: '1',
|
||||
value: 1,
|
||||
file: null,
|
||||
text: ''
|
||||
},
|
||||
};
|
||||
},
|
||||
mounted: function () {
|
||||
this.code = window.location.search.substring('code=='.length)
|
||||
if (this.code) {
|
||||
this.get_file();
|
||||
// 进入网站时,判断Get是否有code参数,有则直接进行取件操作
|
||||
let code = window.location.search.substring('code=='.length)
|
||||
if (code) {
|
||||
this.code = code
|
||||
this.getFile()
|
||||
}
|
||||
// 剪切板监听
|
||||
const that = this
|
||||
document.addEventListener('paste', function (event) {
|
||||
if (that.tool === 1) {
|
||||
if (that.pageNum === 1) {
|
||||
const items = event.clipboardData && event.clipboardData.items;
|
||||
if (items && items.length) {
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
if (items[i].kind === 'string') {
|
||||
if (items[i].type.match(/^text\/plain/)) {
|
||||
const FileData = new FormData();
|
||||
if (items[i].type.match(/^text\/plain/) && that.uploadData.type !== '2') {
|
||||
that.$message('剪切板文字正在上传,请稍等');
|
||||
items[i].getAsString(function (str) {
|
||||
FileData.append('text', str);
|
||||
axios.post('/share', FileData)
|
||||
.then(function (response) {
|
||||
that.$message({'message': response.data.msg, 'type': 'success'});
|
||||
that.files.push(response.data.data)
|
||||
})
|
||||
.catch(function (error) {
|
||||
that.$message({'message': error.data.msg, 'type': 'error'});
|
||||
});
|
||||
that.uploadData.text = str;
|
||||
that.toUploadData();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const file = items[i].getAsFile();
|
||||
that.$message('剪切板文件正在上传,请稍等');
|
||||
const FileData = new FormData();
|
||||
FileData.append('file', file || '');
|
||||
axios.post('/share', FileData).then(async res => {
|
||||
that.files.push(res.data.data);
|
||||
that.$message({'message': res.data.msg, 'type': 'success'});
|
||||
})
|
||||
that.uploadData.file = file
|
||||
that.toUploadData();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
methods: {
|
||||
inputing: function (value) {
|
||||
if (value.length === 5) {
|
||||
watch: {
|
||||
code: function (code) {
|
||||
if (code.length === 5) {
|
||||
this.inout_disable = true;
|
||||
this.get_file();
|
||||
this.getFile();
|
||||
}
|
||||
},
|
||||
get_file: function () {
|
||||
const that = this;
|
||||
axios.post('?code=' + this.code).then(function (response) {
|
||||
if (response.data.code === 404) {
|
||||
that.$message({
|
||||
message: response.data.msg,
|
||||
type: 'error'
|
||||
});
|
||||
} else {
|
||||
that.files.push(response.data.data);
|
||||
that.$message({
|
||||
message: response.data.msg,
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
http: function (method, url, data = {}, config = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
axios({
|
||||
method: method,
|
||||
url: url,
|
||||
data: data,
|
||||
...config
|
||||
}).then(res => {
|
||||
this.$message({
|
||||
message: res.data.detail,
|
||||
type: 'success'
|
||||
});
|
||||
}
|
||||
that.code = '';
|
||||
that.inout_disable = false
|
||||
}).catch(function (error) {
|
||||
console.log(error);
|
||||
});
|
||||
resolve(res.data)
|
||||
}).catch(err => {
|
||||
this.$message({
|
||||
message: err.response.data.detail,
|
||||
type: 'error'
|
||||
});
|
||||
})
|
||||
})
|
||||
},
|
||||
inputNumber: function (number) {
|
||||
if (number === 'C') {
|
||||
this.code = '';
|
||||
} else if (number === 'X') {
|
||||
this.code = this.code.substring(0, this.code.length - 1);
|
||||
} else {
|
||||
if (this.code.length < 5) {
|
||||
this.code += number;
|
||||
}
|
||||
getFile: function () {
|
||||
const that = this;
|
||||
this.http('post', `?code=${that.code}`).then(res => {
|
||||
that.quDrawer = true;
|
||||
that.files.unshift(res.data);
|
||||
})
|
||||
that.code = '';
|
||||
that.input_disable = false
|
||||
},
|
||||
qrcodeUrl(file) {
|
||||
return 'https://api.qrserver.com/v1/create-qr-code/?data=' + window.location.origin + '/?code=' + file.code
|
||||
},
|
||||
listenInput: function (value) {
|
||||
if (this.code.length < 5) {
|
||||
this.code += value;
|
||||
}
|
||||
if (this.code.length === 5) {
|
||||
this.inout_disable = true
|
||||
this.get_file()
|
||||
},
|
||||
changeInput: function (value) {
|
||||
this.code = value;
|
||||
},
|
||||
toUploadData: function () {
|
||||
if (this.uploadData.text === '' && this.uploadData.file === null) {
|
||||
this.$message({
|
||||
message: '请先粘贴文字或者上传文件',
|
||||
type: 'error'
|
||||
});
|
||||
} else {
|
||||
this.http('post', '/share', this.uploadData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'pwd': this.pwd
|
||||
}
|
||||
}).then(res => {
|
||||
this.files.unshift(res.data);
|
||||
this.jiDrawer = true;
|
||||
this.uploadData.text = '';
|
||||
this.uploadData.file = null;
|
||||
});
|
||||
}
|
||||
},
|
||||
successUpload(response, file, fileList) {
|
||||
this.$message({'message': '上传成功,请点击文件库查看', 'type': 'success'});
|
||||
this.files.push(response.data)
|
||||
this.$message({
|
||||
message: response.detail,
|
||||
type: 'success'
|
||||
});
|
||||
this.files.unshift(response.data);
|
||||
},
|
||||
qrcodeUrl(file) {
|
||||
return 'https://api.qrserver.com/v1/create-qr-code?data=' + window.location.origin + '/?code=' + file.code
|
||||
errorUpload(error, file, fileList) {
|
||||
error = JSON.parse(error.message)
|
||||
this.$message({
|
||||
message: error.detail,
|
||||
type: 'error'
|
||||
});
|
||||
},
|
||||
beforeUpload: function (file) {
|
||||
if (file.size > this.fileSizeLimit) {
|
||||
this.$message({
|
||||
message: `文件大小不能超过${this.fileSizeLimit/1024/1024}MB`,
|
||||
type: 'error'
|
||||
});
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import datetime
|
||||
import random
|
||||
import asyncio
|
||||
from sqlalchemy import or_, select, delete
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
import settings
|
||||
from database import Codes, engine
|
||||
from depends import IPRateLimit
|
||||
from storage import STORAGE_ENGINE
|
||||
|
||||
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
|
||||
|
||||
# 错误IP限制器
|
||||
error_ip_limit = IPRateLimit(settings.ERROR_COUNT, settings.ERROR_MINUTE)
|
||||
# 上传文件限制器
|
||||
upload_ip_limit = IPRateLimit(settings.UPLOAD_COUNT, settings.UPLOAD_MINUTE)
|
||||
|
||||
|
||||
async def delete_expire_files():
|
||||
while True:
|
||||
async with AsyncSession(engine, expire_on_commit=False) as s:
|
||||
await error_ip_limit.remove_expired_ip()
|
||||
await upload_ip_limit.remove_expired_ip()
|
||||
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
|
||||
exps = (await s.execute(query)).scalars().all()
|
||||
files = []
|
||||
exps_ids = []
|
||||
for exp in exps:
|
||||
if exp.type != "text":
|
||||
files.append(exp.text)
|
||||
exps_ids.append(exp.id)
|
||||
await storage.delete_files(files)
|
||||
query = delete(Codes).where(Codes.id.in_(exps_ids))
|
||||
await s.execute(query)
|
||||
await s.commit()
|
||||
await asyncio.sleep(settings.DELETE_EXPIRE_FILES_INTERVAL * 60)
|
||||
|
||||
|
||||
async def get_code(s: AsyncSession):
|
||||
code = random.randint(10000, 99999)
|
||||
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
|
||||
code = random.randint(10000, 99999)
|
||||
return str(code)
|
||||