Compare commits

...
11 Commits
Author SHA1 Message Date
lan-air 4218caeaf7 完善手机版上传文本 2022-12-13 10:50:48 +08:00
lan-air 24ad5e08ca 重构index.html 2022-12-13 10:48:09 +08:00
vastsa 31f67fae3f Merge pull request #10 from veoco/master
重写用户登录和 IP 检查并重定义状态码
2022-12-13 08:01:40 +08:00
lan-air 27fc665239 update version 2022-12-13 07:52:20 +08:00
lan-air 541d49d636 update version 2022-12-13 07:46:46 +08:00
veoco 68881c6df0 重写用户登录和 IP 检查并重定义状态码 2022-12-12 22:30:03 +08:00
lan-air fb80d26b70 add setting port 2022-12-12 15:15:17 +08:00
vastsa 9cf0d9418d Merge pull request #7 from veoco/master
新增存储引擎统一文件读写
2022-12-12 11:47:49 +08:00
veoco 4e069486bf 新增存储引擎统一文件读写 2022-12-12 11:18:55 +08:00
lan-air 8935da813b .gitattributes 2022-12-12 11:11:45 +08:00
lan-air 387a3babfd readme.md 2022-12-12 01:02:50 +08:00
10 changed files with 316 additions and 257 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
*.js linguist-language=python
*.css linguist-language=python
*.html linguist-language=python
+37
View File
@@ -0,0 +1,37 @@
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)):
if not pwd or pwd != settings.ADMIN_PASSWORD:
raise HTTPException(status_code=401, detail="密码错误")
class IPRateLimit:
ips = {}
def check_ip(self, ip):
# 检查ip是否被禁止
if ip in self.ips:
if self.ips[ip]['count'] >= settings.ERROR_COUNT:
if self.ips[ip]['time'] + timedelta(minutes=settings.ERROR_MINUTE) > datetime.now():
return False
else:
self.ips.pop(ip)
return True
def add_ip(cls, ip):
ip_info = cls.ips.get(ip, {'count': 0, 'time': datetime.now()})
ip_info['count'] += 1
cls.ips[ip] = ip_info
return ip_info['count']
def __call__(self, request: Request):
ip = request.client.host
if not self.check_ip(ip):
raise HTTPException(status_code=400, detail="错误次数过多,请稍后再试")
return ip
+41 -87
View File
@@ -1,13 +1,10 @@
import datetime import datetime
import os
import uuid import uuid
import threading
import random import random
import asyncio import asyncio
from pathlib import Path from pathlib import Path
from fastapi import FastAPI, Depends, UploadFile, Form, File from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException
from starlette.requests import Request
from starlette.responses import HTMLResponse, FileResponse from starlette.responses import HTMLResponse, FileResponse
from starlette.staticfiles import StaticFiles from starlette.staticfiles import StaticFiles
@@ -16,6 +13,8 @@ from sqlalchemy.ext.asyncio.session import AsyncSession
import settings import settings
from database import get_session, Codes, init_models, engine from database import get_session, Codes, init_models, engine
from storage import STORAGE_ENGINE
from depends import admin_required, IPRateLimit
app = FastAPI(debug=settings.DEBUG) app = FastAPI(debug=settings.DEBUG)
@@ -26,6 +25,8 @@ if not DATA_ROOT.exists():
STATIC_URL = settings.STATIC_URL STATIC_URL = settings.STATIC_URL
app.mount(STATIC_URL, StaticFiles(directory=DATA_ROOT), name="static") app.mount(STATIC_URL, StaticFiles(directory=DATA_ROOT), name="static")
storage = STORAGE_ENGINE[settings.STORAGE_ENGINE]()
@app.on_event('startup') @app.on_event('startup')
async def startup(): async def startup():
@@ -42,13 +43,7 @@ admin_html = open('templates/admin.html', 'r', encoding='utf-8').read() \
.replace('{{description}}', settings.DESCRIPTION) \ .replace('{{description}}', settings.DESCRIPTION) \
.replace('{{keywords}}', settings.KEYWORDS) .replace('{{keywords}}', settings.KEYWORDS)
error_ip_count = {} ip_limit = IPRateLimit()
def delete_file(files):
for file in files:
if file['type'] != 'text':
os.remove(DATA_ROOT / file['text'].lstrip(STATIC_URL + '/'))
async def delete_expire_files(): async def delete_expire_files():
@@ -56,7 +51,8 @@ async def delete_expire_files():
async with AsyncSession(engine, expire_on_commit=False) as s: async with AsyncSession(engine, expire_on_commit=False) as s:
query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0)) query = select(Codes).where(or_(Codes.exp_time < datetime.datetime.now(), Codes.count == 0))
exps = (await s.execute(query)).scalars().all() exps = (await s.execute(query)).scalars().all()
await asyncio.to_thread(delete_file, [{'type': old.type, 'text': old.text} for old in exps]) files = [{'type': old.type, 'text': old.text} for old in exps]
await storage.delete_files(files)
exps_ids = [exp.id for exp in exps] exps_ids = [exp.id for exp in exps]
query = delete(Codes).where(Codes.id.in_(exps_ids)) query = delete(Codes).where(Codes.id.in_(exps_ids))
await s.execute(query) await s.execute(query)
@@ -71,44 +67,26 @@ async def get_code(s: AsyncSession):
return str(code) return str(code)
def get_file_name(key, ext, file, file_bytes):
now = datetime.datetime.now()
path = DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
name = f'{key}.{ext}'
if not path.exists():
path.mkdir(parents=True)
filepath = path / name
with open(filepath, 'wb') as f:
f.write(file_bytes)
return f"{STATIC_URL}/{filepath.relative_to(DATA_ROOT)}", file.content_type, file.filename
@app.get(f'/{settings.ADMIN_ADDRESS}') @app.get(f'/{settings.ADMIN_ADDRESS}')
async def admin(): async def admin():
return HTMLResponse(admin_html) return HTMLResponse(admin_html)
@app.post(f'/{settings.ADMIN_ADDRESS}') @app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)])
async def admin_post(request: Request, s: AsyncSession = Depends(get_session)): async def admin_post(s: AsyncSession = Depends(get_session)):
if request.headers.get('pwd') == settings.ADMIN_PASSWORD: query = select(Codes)
query = select(Codes) codes = (await s.execute(query)).scalars().all()
codes = (await s.execute(query)).scalars().all() return {'detail': '查询成功', 'data': codes}
return {'code': 200, 'msg': '查询成功', 'data': codes}
else:
return {'code': 404, 'msg': '密码错误'}
@app.delete(f'/{settings.ADMIN_ADDRESS}') @app.delete(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)])
async def admin_delete(request: Request, code: str, s: AsyncSession = Depends(get_session)): async def admin_delete(code: str, s: AsyncSession = Depends(get_session)):
if request.headers.get('pwd') == settings.ADMIN_PASSWORD: query = select(Codes).where(Codes.code == code)
query = select(Codes).where(Codes.code == code) file = (await s.execute(query)).scalars().first()
file = (await s.execute(query)).scalars().first() await storage.delete_file({'type': file.type, 'text': file.text})
await asyncio.to_thread(delete_file, [{'type': file.type, 'text': file.text}]) await s.delete(file)
await s.delete(file) await s.commit()
await s.commit() return {'detail': '删除成功'}
return {'code': 200, 'msg': '删除成功'}
else:
return {'code': 404, 'msg': '密码错误'}
@app.get('/') @app.get('/')
@@ -116,60 +94,37 @@ async def index():
return HTMLResponse(index_html) return HTMLResponse(index_html)
def check_ip(ip):
# 检查ip是否被禁止
if ip in error_ip_count:
if error_ip_count[ip]['count'] >= settings.ERROR_COUNT:
if error_ip_count[ip]['time'] + datetime.timedelta(minutes=settings.ERROR_MINUTE) > datetime.datetime.now():
return False
else:
error_ip_count.pop(ip)
return True
def ip_error(ip):
ip_info = error_ip_count.get(ip, {'count': 0, 'time': datetime.datetime.now()})
ip_info['count'] += 1
error_ip_count[ip] = ip_info
return ip_info['count']
@app.get('/select') @app.get('/select')
async def get_file(code: str, s: AsyncSession = Depends(get_session)): async def get_file(code: str, s: AsyncSession = Depends(get_session)):
query = select(Codes).where(Codes.code == code) query = select(Codes).where(Codes.code == code)
info = (await s.execute(query)).scalars().first() info = (await s.execute(query)).scalars().first()
if info: if not info:
if info.type == 'text': raise HTTPException(status_code=404, detail="口令不存在")
return {'code': code, 'msg': '查询成功', 'data': info.text} if info.type == 'text':
else: return {'detail': '查询成功', 'data': info.text}
return FileResponse(DATA_ROOT / info.text.lstrip(STATIC_URL + '/'), filename=info.name)
else: else:
return {'code': 404, 'msg': '口令不存在'} filepath = await storage.get_filepath(info.text)
return FileResponse(filepath, filename=info.name)
@app.post('/') @app.post('/')
async def index(request: Request, code: str, s: AsyncSession = Depends(get_session)): async def index(code: str, ip: str = Depends(ip_limit), s: AsyncSession = Depends(get_session)):
ip = request.client.host
if not check_ip(ip):
return {'code': 404, 'msg': '错误次数过多,请稍后再试'}
query = select(Codes).where(Codes.code == code) query = select(Codes).where(Codes.code == code)
info = (await s.execute(query)).scalars().first() info = (await s.execute(query)).scalars().first()
if not info: if not info:
return {'code': 404, 'msg': f'取件码错误,错误{settings.ERROR_COUNT - ip_error(ip)}次将被禁止10分钟'} error_count = settings.ERROR_COUNT - ip_limit.add_ip(ip)
raise HTTPException(status_code=404, detail=f"取件码错误,错误{error_count}次将被禁止10分钟")
if info.exp_time < datetime.datetime.now() or info.count == 0: if info.exp_time < datetime.datetime.now() or info.count == 0:
threading.Thread(target=delete_file, args=([{'type': info.type, 'text': info.text}],)).start() await storage.delete_file({'type': info.type, 'text': info.text})
await s.delete(info) await s.delete(info)
await s.commit() await s.commit()
return {'code': 404, 'msg': '取件码已过期,请联系寄件人'} raise HTTPException(status_code=404, detail="取件码已过期,请联系寄件人")
count = info.count - 1 await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
query = update(Codes).where(Codes.id == info.id).values(count=count)
await s.execute(query)
await s.commit() await s.commit()
if info.type != 'text': if info.type != 'text':
info.text = f'/select?code={code}' info.text = f'/select?code={code}'
return { return {
'code': 200, 'detail': '取件成功,请点击"取"查看',
'msg': '取件成功,请点击"取"查看',
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code} 'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
} }
@@ -180,12 +135,12 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
code = await get_code(s) code = await get_code(s)
if style == '2': if style == '2':
if value > 7: if value > 7:
return {'code': 404, 'msg': '最大有效天数为7天'} raise HTTPException(status_code=400, detail="最大有效天数为7天")
exp_time = datetime.datetime.now() + datetime.timedelta(days=value) exp_time = datetime.datetime.now() + datetime.timedelta(days=value)
exp_count = -1 exp_count = -1
elif style == '1': elif style == '1':
if value < 1: if value < 1:
return {'code': 404, 'msg': '最小有效次数为1次'} raise HTTPException(status_code=400, detail="最小有效次数为1次")
exp_time = datetime.datetime.now() + datetime.timedelta(days=1) exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
exp_count = value exp_count = value
else: else:
@@ -193,11 +148,11 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
exp_count = -1 exp_count = -1
key = uuid.uuid4().hex key = uuid.uuid4().hex
if file: if file:
file_bytes = file.file.read() file_bytes = await file.read()
size = len(file_bytes) size = len(file_bytes)
if size > settings.FILE_SIZE_LIMIT: if size > settings.FILE_SIZE_LIMIT:
return {'code': 404, 'msg': '文件过大'} raise HTTPException(status_code=400, detail="文件过大")
_text, _type, name = get_file_name(key, file.filename.split('.')[-1], file, file_bytes) _text, _type, name = await storage.save_file(file, file_bytes, key), file.content_type, file.filename
else: else:
size, _text, _type, name = len(text), text, 'text', '文本分享' size, _text, _type, name = len(text), text, 'text', '文本分享'
info = Codes( info = Codes(
@@ -213,8 +168,7 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
s.add(info) s.add(info)
await s.commit() await s.commit()
return { return {
'code': 200, 'detail': '分享成功,请点击文件箱查看取件码',
'msg': '分享成功,请点击文件箱查看取件码',
'data': {'code': code, 'key': key, 'name': name, 'text': _text} 'data': {'code': code, 'key': key, 'name': name, 'text': _text}
} }
@@ -222,4 +176,4 @@ async def share(text: str = Form(default=None), style: str = Form(default='2'),
if __name__ == '__main__': if __name__ == '__main__':
import uvicorn import uvicorn
uvicorn.run('main:app', host='0.0.0.0', port=12345) uvicorn.run('main:app', host='0.0.0.0', port=settings.PORT, debug=settings.DEBUG)
+23 -12
View File
@@ -20,28 +20,38 @@
- [x] 口令使用次数,口令有效期,二维码分享 - [x] 口令使用次数,口令有效期,二维码分享
## 更新记录 ## 更新记录
### 2022年12月13日
### 2022年12月10日 01:56:43 - [x] 完善手机版上传文本
- [x] 优化Index.html首页
1. 管理面板已新增,一如既往的极简,只有删除 ### 2022年12月12日
2. 二维码图片(调用的网络接口,如果离线环境将无法使用,一切为了极简)
### 2022年12月10日 21:10:00 - [x] 重写用户登录和 IP 检查并重定义状态码
- [x] 新增存储引擎统一文件读写
- [x] 设置PORT
1. 取件码有效期,取件码使用次数 ### 2022年12月11日
2. 优化代码逻辑
3. 限制上传文件大小
4. 完善配置参数
### 2022年12月10日 23:50:00
1. 修复取件不显示码的问题 1. 修复取件不显示码的问题
2. 修复文件次数为1时,文件被删除的问题 2. 修复文件次数为1时,文件被删除的问题
3. 使用 aiosqlite 驱动异步化数据库操作
4. 增加定时清理过期文件
5. 优化部署方式,Docker映射,后续更新直接覆盖代码重启
6. 优化配置文件,增加配置项
7. 发布V1.4.5稳定版
### 2022年12月10日
1. 管理面板已新增,一如既往的极简,只有删除
2. 二维码图片(调用的网络接口,如果离线环境将无法使用,一切为了极简)
3. 取件码有效期,取件码使用次数
4. 优化代码逻辑
5. 限制上传文件大小
6. 完善配置参数
## 系统截图 ## 系统截图
### 2022年12月11日 14:55:00
1. 隐藏文件真实地址 1. 隐藏文件真实地址
### 取件 ### 取件
@@ -77,6 +87,7 @@ cd /opt/FileCodeBox
```bash ```bash
vi .env vi .env
``` ```
将下列字段内容替换成你自己的 将下列字段内容替换成你自己的
```dotenv ```dotenv
+4
View File
@@ -4,6 +4,8 @@ config = Config(".env")
DEBUG = config('DEBUG', cast=bool, default=False) DEBUG = config('DEBUG', cast=bool, default=False)
PORT = config('PORT', cast=int, default=12345)
DATABASE_URL = config('DATABASE_URL', cast=str, default="sqlite+aiosqlite:///database.db") DATABASE_URL = config('DATABASE_URL', cast=str, default="sqlite+aiosqlite:///database.db")
DATA_ROOT = config('DATA_ROOT', cast=str, default="./static") DATA_ROOT = config('DATA_ROOT', cast=str, default="./static")
@@ -25,3 +27,5 @@ TITLE = config('TITLE', cast=str, default="文件快递柜")
DESCRIPTION = config('DESCRIPTION', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件") DESCRIPTION = config('DESCRIPTION', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
KEYWORDS = config('KEYWORDS', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件") KEYWORDS = config('KEYWORDS', cast=str, default="FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件等文件")
STORAGE_ENGINE = config('STORAGE_ENGINE', cast=str, default="filesystem")
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

-1
View File
@@ -1 +0,0 @@
var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c<a.length&&0==a[c];)c++;this.num=new Array(a.length-c+b);for(var d=0;d<a.length-c;d++)this.num[d]=a[d+c]}function j(a,b){this.totalCount=a,this.dataCount=b}function k(){this.buffer=[],this.length=0}function m(){return"undefined"!=typeof CanvasRenderingContext2D}function n(){var a=!1,b=navigator.userAgent;return/android/i.test(b)&&(a=!0,aMat=b.toString().match(/android ([0-9]\.[0-9])/i),aMat&&aMat[1]&&(a=parseFloat(aMat[1]))),a}function r(a,b){for(var c=1,e=s(a),f=0,g=l.length;g>=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=new Array(this.moduleCount);for(var e=0;e<this.moduleCount;e++)this.modules[d][e]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,c),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f<this.modules.length;f++)for(var g=f*e,h=0;h<this.modules[f].length;h++){var i=h*e,j=this.modules[f][h];j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}return d},setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(var b=8;b<this.moduleCount-8;b++)null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)},setupPositionAdjustPattern:function(){for(var a=f.getPatternPosition(this.typeNumber),b=0;b<a.length;b++)for(var c=0;c<a.length;c++){var d=a[b],e=a[c];if(null==this.modules[d][e])for(var g=-2;2>=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g<a.length&&(j=1==(1&a[g]>>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,cLine truncated
+47
View File
@@ -0,0 +1,47 @@
import os
import asyncio
import datetime
from pathlib import Path
import settings
class FileSystemStorage:
DATA_ROOT = Path(settings.DATA_ROOT)
STATIC_URL = settings.STATIC_URL
NAME = "filesystem"
async def get_filepath(self, path):
return self.DATA_ROOT / path.lstrip(self.STATIC_URL + '/')
def _save(self, filepath, file_bytes):
with open(filepath, 'wb') as f:
f.write(file_bytes)
async def save_file(self, file, file_bytes, key):
now = datetime.datetime.now()
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
ext = file.filename.split('.')[-1]
name = f'{key}.{ext}'
if not path.exists():
path.mkdir(parents=True)
filepath = path / name
await asyncio.to_thread(self._save, filepath, file_bytes)
text = f"{self.STATIC_URL}/{filepath.relative_to(self.DATA_ROOT)}"
return text
async def delete_file(self, file):
# 是文件就删除
if file['type'] != 'text':
filepath = self.DATA_ROOT / file['text'].lstrip(self.STATIC_URL + '/')
await asyncio.to_thread(os.remove, filepath)
async def delete_files(self, files):
for file in files:
if file['type'] != 'text':
await self.delete_file(file)
STORAGE_ENGINE = {
"filesystem": FileSystemStorage
}
+15 -21
View File
@@ -6,11 +6,14 @@
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/assert/index.css"> <link rel="stylesheet" href="/static/assert/index.css">
<link rel="shortcut icon" href="/static/assert/favicon.ico" type="image/x-icon"/>
<title>后台管理-{{title}}</title> <title>后台管理-{{title}}</title>
<meta name="description" content="{{description}}"/> <meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/> <meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/> <meta name="generator" content="FileCodeBox"/>
<meta name="template" content="Lan"/> <meta name="template" content="Lan"/>
<script src="/static/assert/vue.min.js"></script>
<script src="/static/assert/index.js"></script>
</head> </head>
<body> <body>
<div id="app"> <div id="app">
@@ -57,8 +60,6 @@
</div> </div>
</body> </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/assert/axios.min.js"></script>
<script> <script>
new Vue({ new Vue({
@@ -87,28 +88,21 @@
methods: { methods: {
loginAdmin: function () { loginAdmin: function () {
axios.post('', {}, {'headers': {'pwd': this.pwd}}).then(res => { axios.post('', {}, {'headers': {'pwd': this.pwd}}).then(res => {
if (res.data.code === 200) { this.files = res.data.data;
this.files = res.data.data; this.login = true;
this.login = true; localStorage.setItem('pwd', this.pwd);
localStorage.setItem('pwd', this.pwd); }).catch(e => {
} else { localStorage.clear()
localStorage.clear() this.$message({'message': e.response.data.detail, 'type': 'error'});
this.$message({ });
message: res.data.msg,
type: 'error'
});
}
})
}, },
deleteFile: function (code) { deleteFile: function (code) {
axios.delete('?code=' + code, {'headers': {'pwd': this.pwd}}).then(res => { 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.files = this.files.filter(item => item.code !== code) this.$message({
this.$message({ message: res.data.detail,
message: res.data.msg, type: 'success'
type: 'success' });
});
}
}) })
}, },
} }
+146 -136
View File
@@ -6,11 +6,12 @@
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/assert/index.css"> <link rel="stylesheet" href="/static/assert/index.css">
<link rel="shortcut icon" href="/static/assert/favicon.ico" type="image/x-icon"/>
<title>{{title}}</title> <title>{{title}}</title>
<meta name="description" content="{{description}}"/> <meta name="description" content="{{description}}"/>
<meta name="keywords" content="{{keywords}}"/> <meta name="keywords" content="{{keywords}}"/>
<meta name="generator" content="FileCodeBox"/> <meta name="generator" content="FileCodeBox"/>
<meta name="template" content="Lan-V1.4.2"/> <meta name="template" content="Lan-V1.5.1"/>
<style> <style>
.qu .el-button { .qu .el-button {
width: 100px; width: 100px;
@@ -27,48 +28,51 @@
font-weight: bold; font-weight: bold;
} }
</style> </style>
<script src="/static/assert/vue.min.js"></script>
<script src="/static/assert/index.js"></script>
</head> </head>
<body> <body>
<div id="app" style="text-align: center;"> <div id="app" style="text-align: center">
<el-row v-if="tool === 0" class="qu" style="width:400px;margin: 6vh auto 0 auto"> <el-row v-if="pageNum === 0" class="qu" style="width:400px;margin: 6vh auto 0 auto">
<el-card style="padding-bottom: 1rem"> <el-card style="padding-bottom: 1rem">
<el-col :span="24"> <el-col :span="24">
<el-input autofocus @input="inputing" clearable v-model:value="code" maxlength="5" <el-input autofocus @input="listenInput" clearable v-model:value="code" maxlength="5"
:disabled="inout_disable" :disabled="inputDisable" placeholder="请输入五位取件码">
placeholder="请输入取件码"></el-input> </el-input>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('1')">1</el-button> <el-button @click="listenInput('1')">1</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('2')">2</el-button> <el-button @click="listenInput('2')">2</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('3')">3</el-button> <el-button @click="listenInput('3')">3</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('4')">4</el-button> <el-button @click="listenInput('4')">4</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('5')">5</el-button> <el-button @click="listenInput('5')">5</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('6')">6</el-button> <el-button @click="listenInput('6')">6</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('7')">7</el-button> <el-button @click="listenInput('7')">7</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('8')">8</el-button> <el-button @click="listenInput('8')">8</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('9')">9</el-button> <el-button @click="listenInput('9')">9</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="tool=1">寄</el-button> <el-button @click="pageNum=1">寄</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="inputNumber('0')">0</el-button> <el-button @click="listenInput('0')">0</el-button>
</el-col> </el-col>
<el-col :span=8> <el-col :span=8>
<el-button @click="quDrawer=true">取</el-button> <el-button @click="quDrawer=true">取</el-button>
@@ -78,38 +82,49 @@
<el-row v-else style="width:400px;margin: 20vh auto 0 auto"> <el-row v-else style="width:400px;margin: 20vh auto 0 auto">
<el-col :span="24" style="margin: 1rem 0"> <el-col :span="24" style="margin: 1rem 0">
<el-card> <el-card>
<div style="margin-bottom: 1rem"> <el-input style="width: 200px" placeholder="数量" v-model="uploadData.value"
<el-radio-group v-model="destoryData.style"> class="input-with-select">
<el-radio label="1">次数</el-radio> <el-select style="width: 75px" v-model="uploadData.style" slot="prepend" placeholder="请选择">
<el-radio label="2">天数</el-radio> <el-option label="天数" value="2"></el-option>
</el-radio-group> <el-option label="次数" value="1"></el-option>
<el-input-number </el-select>
placeholder="输入数量,默认1" <el-button v-if="uploadData.style === '1'" slot="append" disabled>次</el-button>
style="margin-left: 1rem" v-model="destoryData.value" controls-position="right" :min="1"> <el-button v-else slot="append" disabled>天</el-button>
</el-input-number> </el-input>
</div> <el-radio-group v-model="uploadData.type" style="margin-left: 18px">
<el-radio label="1">文件</el-radio>
<el-radio label="2">文本</el-radio>
</el-radio-group>
<el-upload <el-upload
v-if="uploadData.type === '1'"
drag drag
action="/share" action="/share"
multiple multiple
:data="destoryData" style="margin: 1rem 0;"
:data="uploadData"
:on-success="successUpload" :on-success="successUpload"
:on-error="errorUpload"
> >
<i class="el-icon-upload"></i> <i class="el-icon-upload"></i>
<div class="el-upload__text">将文字、文件拖、粘贴到此处,或<em>点击上传</em></div> <div class="el-upload__text">将文字、文件拖、粘贴到此处,或<em>点击上传</em></div>
<div class="el-upload__text" style="font-size: 10px">天数<7或限制次数(24h后删除)</div> <div class="el-upload__text" style="font-size: 10px">天数<7或限制次数(24h后删除)</div>
<div class="el-upload__tip" slot="tip">
<el-button @click="tool=0">去取件</el-button>
<el-button @click="cunDrawer=true">取件码</el-button>
</div>
</el-upload> </el-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 @click="pageNum=0">去取件</el-button>
<el-button @click="cunDrawer=true">取件码</el-button>
<el-button v-if="uploadData.type === '2'" @click="toUploadData">寄出去</el-button>
</div>
</el-card> </el-card>
</el-col> </el-col>
</el-row> </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 <el-drawer
title="文件箱" title="文件箱"
:visible.sync="quDrawer" :visible.sync="quDrawer"
@@ -135,8 +150,8 @@
</el-drawer> </el-drawer>
<el-drawer <el-drawer
title="文件箱" title="文件箱"
:visible.sync="cunDrawer" :visible.sync="jiDrawer"
direction="btt" :direction="direction"
size="50%"> size="50%">
<el-card> <el-card>
<el-empty v-if="files.length===0" description="请上传文件"></el-empty> <el-empty v-if="files.length===0" description="请上传文件"></el-empty>
@@ -154,18 +169,17 @@
</el-col> </el-col>
<el-col :span="4"> <el-col :span="4">
<img style="width: 80px;height: 80px;" <img style="width: 80px;height: 80px;"
:src="qrcodeUrl(file)" :alt="file.code"> :src="qrcodeUrl(file)" alt="二维码" :alt="file.code">
</el-col> </el-col>
</el-row> </el-row>
</el-card> </el-card>
</el-card> </el-card>
</el-drawer> </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> </div>
</body> </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/assert/axios.min.js"></script>
<script> <script>
new Vue({ new Vue({
@@ -174,134 +188,130 @@
data: function () { data: function () {
return { return {
code: '', code: '',
inout_disable: false,
files: [],
quDrawer: false, quDrawer: false,
cunDrawer: false, jiDrawer: false,
direction: 'btt', direction: 'btt',
tool: 0, files: [],
destoryData: { pageNum: 0,
inputDisable: false,
uploadData: {
style: '2', style: '2',
value: 1 type: '1',
value: 1,
file: null,
text: ''
}, },
}; };
}, },
mounted: function () { mounted: function () {
this.code = window.location.search.substring('code=='.length) // 进入网站时,判断Get是否有code参数,有则直接进行取件操作
if (this.code) { let code = window.location.search.substring('code=='.length)
this.get_file(); if (code) {
this.code = code
this.getFile()
} }
// 剪切板监听
const that = this const that = this
document.addEventListener('paste', function (event) { document.addEventListener('paste', function (event) {
if (that.tool === 1) { if (that.pageNum === 1) {
const items = event.clipboardData && event.clipboardData.items; const items = event.clipboardData && event.clipboardData.items;
if (items && items.length) { if (items && items.length) {
for (let i = 0; i < items.length; i++) { for (let i = 0; i < items.length; i++) {
if (items[i].kind === 'string') { if (items[i].kind === 'string') {
if (items[i].type.match(/^text\/plain/)) { if (items[i].type.match(/^text\/plain/) && that.uploadData.type !== '2') {
const FileData = new FormData();
that.$message('剪切板文字正在上传,请稍等'); that.$message('剪切板文字正在上传,请稍等');
items[i].getAsString(function (str) { items[i].getAsString(function (str) {
FileData.append('text', str); that.uploadData.text = str;
FileData.append('style', that.destoryData.style); that.toUploadData();
FileData.append('value', that.destoryData.value);
axios.post('/share', FileData)
.then(function (res) {
if (res.data.code === 200) {
that.$message({'message': res.data.msg, 'type': 'success'});
that.files.push(res.data.data)
} else {
that.$message({'message': res.data.msg, 'type': 'error'});
}
})
.catch(function (error) {
that.$message({'message': error.data.msg, 'type': 'error'});
});
}); });
} }
} else { } else {
const file = items[i].getAsFile(); const file = items[i].getAsFile();
that.$message('剪切板文件正在上传,请稍等'); that.$message('剪切板文件正在上传,请稍等');
const FileData = new FormData(); that.uploadData.file = file
FileData.append('file', file || ''); that.toUploadData();
FileData.append('style', that.destoryData.style);
FileData.append('value', that.destoryData.value);
axios.post('/share', FileData).then(async res => {
if (res.data.code === 200) {
that.$message({'message': res.data.msg, 'type': 'success'});
that.files.push(res.data.data)
} else {
that.$message({'message': res.data.msg, 'type': 'error'});
}
})
} }
} }
} }
} }
}); });
}, },
methods: { methods: {
inputing: function (value) { http: function (method, url, data = {}, config = {}) {
if (value.length === 5) { return new Promise((resolve, reject) => {
this.inout_disable = true; axios({
this.get_file(); method: method,
} url: url,
}, data: data,
get_file: function () { ...config
const that = this; }).then(res => {
axios.post('?code=' + this.code).then(function (response) { this.$message({
if (response.data.code === 404) { message: res.data.detail,
that.$message({
message: response.data.msg,
type: 'error'
});
} else {
that.files.push(response.data.data);
that.$message({
message: response.data.msg,
type: 'success' type: 'success'
}); });
that.quDrawer = true; resolve(res.data)
} }).catch(err => {
that.code = ''; this.$message({
that.inout_disable = false message: err.response.data.detail,
}).catch(function (error) { type: 'error'
console.log(error); });
}); })
})
}, },
inputNumber: function (number) { getFile: function () {
if (number === 'C') { const that = this;
this.code = ''; this.http('post', `?code=${that.code}`).then(res => {
} else if (number === 'X') { that.quDrawer = true;
this.code = this.code.substring(0, this.code.length - 1); that.files.unshift(res.data);
} else { })
if (this.code.length < 5) { that.code = '';
this.code += number; that.input_disable = false
}
}
if (this.code.length === 5) {
this.inout_disable = true
this.get_file()
}
},
successUpload(response, file, fileList) {
if (response.code === 200) {
this.$message({
message: response.msg,
type: 'success'
});
this.files.push(response.data);
} else {
this.$message({
message: response.msg,
type: 'error'
});
}
}, },
qrcodeUrl(file) { qrcodeUrl(file) {
return 'https://api.qrserver.com/v1/create-qr-code/?data=' + window.location.origin + '/?code=' + file.code 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.getFile();
}
},
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'
}
}).then(res => {
this.files.unshift(res.data);
this.jiDrawer = true;
this.uploadData.text = '';
this.uploadData.file = null;
});
}
},
successUpload(response, file, fileList) {
this.$message({
message: response.msg,
type: 'success'
});
this.files.unshift(response.data);
},
errorUpload(error, file, fileList) {
error = JSON.parse(error.message)
this.$message({
message: error.detail,
type: 'error'
});
},
} }
}) })
</script> </script>