mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-22 15:07:21 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9947a0927a | ||
|
|
a1210d5182 | ||
|
|
5b7a9f919b | ||
|
|
6e52553cd3 | ||
|
|
d5bc3e1a81 | ||
|
|
31b8cb4016 | ||
|
|
2eafca2f0c | ||
|
|
24200a53a2 | ||
|
|
aaaef095c8 | ||
|
|
7fc733d225 | ||
|
|
4a868865f9 | ||
|
|
0ae8b82c77 | ||
|
|
c77fd35c7d | ||
|
|
7e1120eb62 | ||
|
|
4e5f9fa619 | ||
|
|
00b5bace6d | ||
|
|
77e6e7644f | ||
|
|
fb6f71c93b | ||
|
|
87549fae29 | ||
|
|
e8cc4748d1 | ||
|
|
ba71942caa | ||
|
|
7864d0710d | ||
|
|
12c7d5a1dd | ||
|
|
f2b5490f10 | ||
|
|
10dfb67ac0 | ||
|
|
2b04515c00 | ||
|
|
1f303d3340 | ||
|
|
f4f40e245a | ||
|
|
195e08f818 | ||
|
|
45d8abc439 |
No files matched your search
+1
-4
@@ -1,4 +1 @@
|
|||||||
# These are supported funding model platforms
|
custom: https://gitlab.com/Vastsa/lanpicbed/-/raw/master/zb_users/upload/2023/02/6402263fb2ff4fddad51cb64fa66f4fb.png
|
||||||
|
|
||||||
github: [ vastsa ]
|
|
||||||
custom: [ https://share.lanol.cn ]
|
|
||||||
@@ -5,6 +5,8 @@ LABEL version="6"
|
|||||||
|
|
||||||
|
|
||||||
COPY . /app
|
COPY . /app
|
||||||
|
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||||
|
RUN echo 'Asia/Shanghai' >/etc/timezone
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
RUN pip install -r requirements.txt
|
RUN pip install -r requirements.txt
|
||||||
EXPOSE 12345
|
EXPOSE 12345
|
||||||
|
|||||||
Whitespace-only changes.
@@ -45,7 +45,6 @@ async def init_models(s):
|
|||||||
{'key': 'DATABASE_FILE', 'value': settings.DATABASE_FILE},
|
{'key': 'DATABASE_FILE', 'value': settings.DATABASE_FILE},
|
||||||
{'key': 'PORT', 'value': settings.PORT},
|
{'key': 'PORT', 'value': settings.PORT},
|
||||||
{'key': 'DATA_ROOT', 'value': settings.DATA_ROOT},
|
{'key': 'DATA_ROOT', 'value': settings.DATA_ROOT},
|
||||||
{'key': 'LOCAL_ROOT', 'value': settings.LOCAL_ROOT},
|
|
||||||
{'key': 'STATIC_URL', 'value': settings.STATIC_URL},
|
{'key': 'STATIC_URL', 'value': settings.STATIC_URL},
|
||||||
{'key': 'BANNERS', 'value': settings.BANNERS},
|
{'key': 'BANNERS', 'value': settings.BANNERS},
|
||||||
{'key': 'ENABLE_UPLOAD', 'value': settings.ENABLE_UPLOAD},
|
{'key': 'ENABLE_UPLOAD', 'value': settings.ENABLE_UPLOAD},
|
||||||
|
|||||||
+97
-63
@@ -1,5 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import BinaryIO
|
from typing import BinaryIO
|
||||||
@@ -16,6 +18,101 @@ if settings.STORAGE_ENGINE == 'aliyunsystem':
|
|||||||
import oss2
|
import oss2
|
||||||
|
|
||||||
|
|
||||||
|
class FileSystemStorage:
|
||||||
|
def __init__(self):
|
||||||
|
self.DATA_ROOT = Path(settings.DATA_ROOT)
|
||||||
|
self.STATIC_URL = settings.STATIC_URL
|
||||||
|
self.NAME = "filesystem"
|
||||||
|
self.DOWN_PATH = '/select'
|
||||||
|
|
||||||
|
async def get_filepath(self, text: str):
|
||||||
|
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
|
||||||
|
|
||||||
|
async def get_url(self, info: Codes):
|
||||||
|
return f'{self.DOWN_PATH}?code={info.code}'
|
||||||
|
|
||||||
|
async def get_text(self, file: UploadFile, key: str):
|
||||||
|
ext = file.filename.split('.')[-1]
|
||||||
|
now = datetime.now()
|
||||||
|
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
||||||
|
if not path.exists():
|
||||||
|
path.mkdir(parents=True)
|
||||||
|
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT)}"
|
||||||
|
return text
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def get_size(file: UploadFile):
|
||||||
|
f = file.file
|
||||||
|
f.seek(0, os.SEEK_END)
|
||||||
|
size = f.tell()
|
||||||
|
f.seek(0, os.SEEK_SET)
|
||||||
|
return size
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _save(filepath, file: BinaryIO):
|
||||||
|
with open(filepath, 'wb') as f:
|
||||||
|
chunk_size = 256 * 1024
|
||||||
|
chunk = file.read(chunk_size)
|
||||||
|
while chunk:
|
||||||
|
f.write(chunk)
|
||||||
|
chunk = file.read(chunk_size)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _save_chunk(filepath, file: bytes):
|
||||||
|
with open(filepath, 'wb') as f:
|
||||||
|
f.write(file)
|
||||||
|
|
||||||
|
async def create_upload_file(self):
|
||||||
|
file_key = uuid.uuid4().hex
|
||||||
|
file_path = self.DATA_ROOT / f"temp/{file_key}"
|
||||||
|
if not file_path.exists():
|
||||||
|
file_path.mkdir(parents=True)
|
||||||
|
return file_key
|
||||||
|
|
||||||
|
async def save_chunk_file(self, file_key, file_chunk, chunk_index, chunk_total):
|
||||||
|
file_path = self.DATA_ROOT / f"temp/{file_key}/"
|
||||||
|
await asyncio.to_thread(self._save_chunk, file_path / f"{chunk_total}-{chunk_index}.temp", file_chunk)
|
||||||
|
|
||||||
|
async def merge_chunks(self, file_key, file_name, total_chunks: int):
|
||||||
|
ext = file_name.split('.')[-1]
|
||||||
|
now = datetime.now()
|
||||||
|
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
||||||
|
if not path.exists():
|
||||||
|
path.mkdir(parents=True)
|
||||||
|
text = f"{self.STATIC_URL}/{(path / f'{file_key}.{ext}').relative_to(self.DATA_ROOT)}"
|
||||||
|
with open(path / f'{file_key}.{ext}', 'wb') as f:
|
||||||
|
for i in range(1, total_chunks + 1):
|
||||||
|
now_temp = self.DATA_ROOT / f'temp/{file_key}/{total_chunks}-{i}.temp'
|
||||||
|
with open(now_temp, 'rb') as r:
|
||||||
|
f.write(r.read())
|
||||||
|
await asyncio.to_thread(os.remove, now_temp)
|
||||||
|
await asyncio.to_thread(os.rmdir, self.DATA_ROOT / f'temp/{file_key}/')
|
||||||
|
return text
|
||||||
|
|
||||||
|
async def save_file(self, file: UploadFile, text: str):
|
||||||
|
filepath = await self.get_filepath(text)
|
||||||
|
await asyncio.to_thread(self._save, filepath, file.file)
|
||||||
|
|
||||||
|
async def delete_file(self, text: str):
|
||||||
|
filepath = await self.get_filepath(text)
|
||||||
|
if filepath.exists():
|
||||||
|
await asyncio.to_thread(os.remove, filepath)
|
||||||
|
await asyncio.to_thread(self.judge_delete_folder, filepath)
|
||||||
|
|
||||||
|
async def delete_files(self, texts):
|
||||||
|
tasks = [self.delete_file(text) for text in texts]
|
||||||
|
await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
def judge_delete_folder(self, filepath):
|
||||||
|
current = filepath.parent
|
||||||
|
while current != self.DATA_ROOT:
|
||||||
|
if not list(current.iterdir()):
|
||||||
|
os.rmdir(current)
|
||||||
|
current = current.parent
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
class AliyunFileStorage:
|
class AliyunFileStorage:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
auth = oss2.Auth(settings.KeyId, settings.KeySecret)
|
auth = oss2.Auth(settings.KeyId, settings.KeySecret)
|
||||||
@@ -71,69 +168,6 @@ class AliyunFileStorage:
|
|||||||
self.bucket.delete_object(text)
|
self.bucket.delete_object(text)
|
||||||
|
|
||||||
|
|
||||||
class FileSystemStorage:
|
|
||||||
def __init__(self):
|
|
||||||
self.DATA_ROOT = Path(settings.DATA_ROOT)
|
|
||||||
self.STATIC_URL = settings.STATIC_URL
|
|
||||||
self.NAME = "filesystem"
|
|
||||||
self.DOWN_PATH = '/select'
|
|
||||||
|
|
||||||
async def get_filepath(self, text: str):
|
|
||||||
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
|
|
||||||
|
|
||||||
async def get_url(self, info: Codes):
|
|
||||||
return f'{self.DOWN_PATH}?code={info.code}'
|
|
||||||
|
|
||||||
async def get_text(self, file: UploadFile, key: str):
|
|
||||||
ext = file.filename.split('.')[-1]
|
|
||||||
now = datetime.now()
|
|
||||||
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
|
|
||||||
if not path.exists():
|
|
||||||
path.mkdir(parents=True)
|
|
||||||
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT)}"
|
|
||||||
return text
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
async def get_size(file: UploadFile):
|
|
||||||
f = file.file
|
|
||||||
f.seek(0, os.SEEK_END)
|
|
||||||
size = f.tell()
|
|
||||||
f.seek(0, os.SEEK_SET)
|
|
||||||
return size
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _save(filepath, file: BinaryIO):
|
|
||||||
with open(filepath, 'wb') as f:
|
|
||||||
chunk_size = 256 * 1024
|
|
||||||
chunk = file.read(chunk_size)
|
|
||||||
while chunk:
|
|
||||||
f.write(chunk)
|
|
||||||
chunk = file.read(chunk_size)
|
|
||||||
|
|
||||||
async def save_file(self, file: UploadFile, text: str):
|
|
||||||
filepath = await self.get_filepath(text)
|
|
||||||
await asyncio.to_thread(self._save, filepath, file.file)
|
|
||||||
|
|
||||||
async def delete_file(self, text: str):
|
|
||||||
filepath = await self.get_filepath(text)
|
|
||||||
if filepath.exists():
|
|
||||||
await asyncio.to_thread(os.remove, filepath)
|
|
||||||
await asyncio.to_thread(self.judge_delete_folder, filepath)
|
|
||||||
|
|
||||||
async def delete_files(self, texts):
|
|
||||||
tasks = [self.delete_file(text) for text in texts]
|
|
||||||
await asyncio.gather(*tasks)
|
|
||||||
|
|
||||||
def judge_delete_folder(self, filepath):
|
|
||||||
current = filepath.parent
|
|
||||||
while current != self.DATA_ROOT:
|
|
||||||
if not list(current.iterdir()):
|
|
||||||
os.rmdir(current)
|
|
||||||
current = current.parent
|
|
||||||
else:
|
|
||||||
break
|
|
||||||
|
|
||||||
|
|
||||||
STORAGE_ENGINE = {
|
STORAGE_ENGINE = {
|
||||||
"filesystem": FileSystemStorage,
|
"filesystem": FileSystemStorage,
|
||||||
"aliyunsystem": AliyunFileStorage
|
"aliyunsystem": AliyunFileStorage
|
||||||
|
|||||||
+43
-3
@@ -1,6 +1,10 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
import hashlib
|
||||||
import random
|
import random
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import string
|
||||||
|
import time
|
||||||
|
|
||||||
from sqlalchemy import or_, select, delete
|
from sqlalchemy import or_, select, delete
|
||||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||||
from .database import Codes, engine
|
from .database import Codes, engine
|
||||||
@@ -36,8 +40,44 @@ async def delete_expire_files():
|
|||||||
await asyncio.sleep(settings.DELETE_EXPIRE_FILES_INTERVAL * 60)
|
await asyncio.sleep(settings.DELETE_EXPIRE_FILES_INTERVAL * 60)
|
||||||
|
|
||||||
|
|
||||||
async def get_code(s: AsyncSession):
|
async def get_random_num():
|
||||||
code = random.randint(10000, 99999)
|
return random.randint(10000, 99999)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_random_string():
|
||||||
|
r_s = string.ascii_letters + string.digits
|
||||||
|
return ''.join(random.choice(r_s) for _ in range(5)).upper()
|
||||||
|
|
||||||
|
|
||||||
|
async def get_code(s: AsyncSession, exp_style):
|
||||||
|
if exp_style == 'forever':
|
||||||
|
generate = get_random_string
|
||||||
|
else:
|
||||||
|
generate = get_random_num
|
||||||
|
code = await generate()
|
||||||
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
|
while (await s.execute(select(Codes.id).where(Codes.code == code))).scalar():
|
||||||
code = random.randint(10000, 99999)
|
code = await generate()
|
||||||
return str(code)
|
return str(code)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_token(ip, code):
|
||||||
|
return hashlib.sha256(f"{ip}{code}{int(time.time() / 1000)}000{settings.ADMIN_PASSWORD}".encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def get_expire_info(expire_style, expire_value, s):
|
||||||
|
now = datetime.datetime.now()
|
||||||
|
if expire_value <= 0 or expire_value > 999:
|
||||||
|
return True, None, None
|
||||||
|
code = await get_code(s, expire_style)
|
||||||
|
if expire_style == 'day':
|
||||||
|
return False, now + datetime.timedelta(days=expire_value), -1, code
|
||||||
|
elif expire_style == 'hour':
|
||||||
|
return False, now + datetime.timedelta(hours=expire_value), -1, code
|
||||||
|
elif expire_style == 'minute':
|
||||||
|
return False, now + datetime.timedelta(minutes=expire_value), -1, code
|
||||||
|
elif expire_style == 'forever':
|
||||||
|
return False, None, -1, code
|
||||||
|
elif expire_style == 'count':
|
||||||
|
return False, None, expire_value, code
|
||||||
|
else:
|
||||||
|
return True, None, None
|
||||||
@@ -2,21 +2,22 @@ import asyncio
|
|||||||
import datetime
|
import datetime
|
||||||
import uuid
|
import uuid
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
from sqlalchemy import select, func, update
|
from sqlalchemy import select, func, update
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
from starlette.responses import HTMLResponse, FileResponse
|
from starlette.responses import HTMLResponse, FileResponse, RedirectResponse
|
||||||
from starlette.staticfiles import StaticFiles
|
from starlette.staticfiles import StaticFiles
|
||||||
import os
|
from core.utils import error_ip_limit, upload_ip_limit, get_code, storage, delete_expire_files, get_token, \
|
||||||
import shutil
|
get_expire_info
|
||||||
from core.utils import error_ip_limit, upload_ip_limit, get_code, storage, delete_expire_files
|
|
||||||
from core.depends import admin_required
|
from core.depends import admin_required
|
||||||
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks
|
from fastapi import FastAPI, Depends, UploadFile, Form, File, HTTPException, BackgroundTasks, Header
|
||||||
from core.database import init_models, Options, Codes, get_session
|
from core.database import init_models, Options, Codes, get_session
|
||||||
from settings import settings
|
from settings import settings
|
||||||
|
|
||||||
# 实例化FastAPI
|
# 实例化FastAPI
|
||||||
app = FastAPI(debug=settings.DEBUG, redoc_url=None, docs_url=None, openapi_url=None)
|
app = FastAPI(debug=settings.DEBUG, redoc_url=None, )
|
||||||
|
|
||||||
|
|
||||||
@app.on_event('startup')
|
@app.on_event('startup')
|
||||||
@@ -31,10 +32,6 @@ async def startup(s: AsyncSession = Depends(get_session)):
|
|||||||
DATA_ROOT = Path(settings.DATA_ROOT)
|
DATA_ROOT = Path(settings.DATA_ROOT)
|
||||||
if not DATA_ROOT.exists():
|
if not DATA_ROOT.exists():
|
||||||
DATA_ROOT.mkdir(parents=True)
|
DATA_ROOT.mkdir(parents=True)
|
||||||
# 本地文件文件夹
|
|
||||||
LOCAL_ROOT = Path(settings.LOCAL_ROOT)
|
|
||||||
if not LOCAL_ROOT.exists():
|
|
||||||
LOCAL_ROOT.mkdir(parents=True)
|
|
||||||
|
|
||||||
# 静态文件夹,这个固定就行了,静态资源都放在这里
|
# 静态文件夹,这个固定就行了,静态资源都放在这里
|
||||||
app.mount('/static', StaticFiles(directory='./static'), name="static")
|
app.mount('/static', StaticFiles(directory='./static'), name="static")
|
||||||
@@ -48,52 +45,25 @@ admin_html = open('templates/admin.html', 'r', encoding='utf-8').read()
|
|||||||
@app.get('/')
|
@app.get('/')
|
||||||
async def index():
|
async def index():
|
||||||
return HTMLResponse(
|
return HTMLResponse(
|
||||||
index_html.replace('{{title}}', settings.TITLE).replace('{{description}}', settings.DESCRIPTION).replace(
|
index_html
|
||||||
'{{keywords}}', settings.KEYWORDS).replace("'{{fileSizeLimit}}'", str(settings.FILE_SIZE_LIMIT))
|
.replace('{{title}}', settings.TITLE)
|
||||||
|
.replace('{{description}}', settings.DESCRIPTION)
|
||||||
|
.replace('{{keywords}}', settings.KEYWORDS)
|
||||||
|
.replace("'{{fileSizeLimit}}'", str(settings.FILE_SIZE_LIMIT))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面')
|
@app.get(f'/{settings.ADMIN_ADDRESS}', description='管理页面')
|
||||||
async def admin():
|
async def admin():
|
||||||
return HTMLResponse(
|
return HTMLResponse(
|
||||||
admin_html.replace('{{title}}', settings.TITLE).replace('{{description}}', settings.DESCRIPTION).replace(
|
admin_html
|
||||||
'{{admin_address}}', settings.ADMIN_ADDRESS).replace('{{keywords}}', settings.KEYWORDS)
|
.replace('{{title}}', settings.TITLE)
|
||||||
|
.replace('{{description}}', settings.DESCRIPTION)
|
||||||
|
.replace('{{admin_address}}', settings.ADMIN_ADDRESS)
|
||||||
|
.replace('{{keywords}}', settings.KEYWORDS)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.get(f'/{settings.ADMIN_ADDRESS}/files', dependencies=[Depends(admin_required)])
|
|
||||||
async def get_files():
|
|
||||||
files = []
|
|
||||||
for i, j, k in os.walk(f'{LOCAL_ROOT}'):
|
|
||||||
files.extend([{'name': _.split('/')[-1], 'path': i} for _ in k])
|
|
||||||
return {'data': files}
|
|
||||||
|
|
||||||
|
|
||||||
@app.post(f'/{settings.ADMIN_ADDRESS}/files', dependencies=[Depends(admin_required)])
|
|
||||||
async def share_file(name=Form(...), path=File(...), s: AsyncSession = Depends(get_session)):
|
|
||||||
file_path = path + f'/{name}'
|
|
||||||
key = uuid.uuid4().hex
|
|
||||||
code = await get_code(s)
|
|
||||||
now = datetime.datetime.now()
|
|
||||||
path = f"{settings.LOCAL_ROOT}/upload/{now.year}/{now.month}/{now.day}/"
|
|
||||||
if not os.path.exists(path):
|
|
||||||
os.makedirs(path)
|
|
||||||
text = f"{path}/{f'{key}{name}'}"
|
|
||||||
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
|
|
||||||
s.add(Codes(code=code, text=text.replace(f'{settings.LOCAL_ROOT}/', ''), type='file', name=name, count=-1,
|
|
||||||
exp_time=exp_time, key=key))
|
|
||||||
await s.commit()
|
|
||||||
shutil.move(file_path, text)
|
|
||||||
return {
|
|
||||||
'detail': '分享成功!请在24小时内使用分享使用!',
|
|
||||||
'data': {
|
|
||||||
'code': code,
|
|
||||||
'text': text,
|
|
||||||
'name': name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='查询数据库列表')
|
@app.post(f'/{settings.ADMIN_ADDRESS}', dependencies=[Depends(admin_required)], description='查询数据库列表')
|
||||||
async def admin_post(page: int = Form(default=1), size: int = Form(default=10), s: AsyncSession = Depends(get_session)):
|
async def admin_post(page: int = Form(default=1), size: int = Form(default=10), s: AsyncSession = Depends(get_session)):
|
||||||
infos = (await s.execute(select(Codes).offset((page - 1) * size).limit(size))).scalars().all()
|
infos = (await s.execute(select(Codes).offset((page - 1) * size).limit(size))).scalars().all()
|
||||||
@@ -164,12 +134,12 @@ async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession =
|
|||||||
if not info:
|
if not info:
|
||||||
error_count = settings.ERROR_COUNT - error_ip_limit.add_ip(ip)
|
error_count = settings.ERROR_COUNT - error_ip_limit.add_ip(ip)
|
||||||
raise HTTPException(status_code=404, detail=f"取件码错误,{error_count}次后将被禁止{settings.ERROR_MINUTE}分钟")
|
raise HTTPException(status_code=404, detail=f"取件码错误,{error_count}次后将被禁止{settings.ERROR_MINUTE}分钟")
|
||||||
if info.exp_time < datetime.datetime.now() or info.count == 0:
|
if (info.exp_time and info.exp_time < datetime.datetime.now()) or info.count == 0:
|
||||||
raise HTTPException(status_code=404, detail="取件码已失效,请联系寄件人")
|
raise HTTPException(status_code=404, detail="取件码已失效,请联系寄件人")
|
||||||
await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
|
await s.execute(update(Codes).where(Codes.id == info.id).values(count=info.count - 1))
|
||||||
await s.commit()
|
await s.commit()
|
||||||
if info.type != 'text':
|
if info.type != 'text':
|
||||||
info.text = await storage.get_url(info)
|
info.text = f'/select?code={info.code}&token={await get_token(code, ip)}'
|
||||||
return {
|
return {
|
||||||
'detail': f'取件成功,请立即下载,避免失效!',
|
'detail': f'取件成功,请立即下载,避免失效!',
|
||||||
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
|
'data': {'type': info.type, 'text': info.text, 'name': info.name, 'code': info.code}
|
||||||
@@ -178,7 +148,6 @@ async def index(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession =
|
|||||||
|
|
||||||
@app.get('/banner')
|
@app.get('/banner')
|
||||||
async def banner(request: Request):
|
async def banner(request: Request):
|
||||||
# 数据库查询config
|
|
||||||
return {
|
return {
|
||||||
'detail': '查询成功',
|
'detail': '查询成功',
|
||||||
'data': settings.BANNERS,
|
'data': settings.BANNERS,
|
||||||
@@ -187,7 +156,11 @@ async def banner(request: Request):
|
|||||||
|
|
||||||
|
|
||||||
@app.get('/select')
|
@app.get('/select')
|
||||||
async def get_file(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
|
async def get_file(code: str, token: str, ip: str = Depends(error_ip_limit), s: AsyncSession = Depends(get_session)):
|
||||||
|
# 验证token
|
||||||
|
if token != await get_token(code, ip):
|
||||||
|
error_ip_limit.add_ip(ip)
|
||||||
|
raise HTTPException(status_code=403, detail="口令错误,或已过期,次数过多将被禁止访问")
|
||||||
# 查出数据库记录
|
# 查出数据库记录
|
||||||
query = select(Codes).where(Codes.code == code)
|
query = select(Codes).where(Codes.code == code)
|
||||||
info = (await s.execute(query)).scalars().first()
|
info = (await s.execute(query)).scalars().first()
|
||||||
@@ -199,38 +172,66 @@ async def get_file(code: str, ip: str = Depends(error_ip_limit), s: AsyncSession
|
|||||||
if info.type == 'text':
|
if info.type == 'text':
|
||||||
return {'detail': '查询成功', 'data': info.text}
|
return {'detail': '查询成功', 'data': info.text}
|
||||||
# 如果是文件,返回文件
|
# 如果是文件,返回文件
|
||||||
|
elif storage.NAME != 'filesystem':
|
||||||
|
# 重定向到文件存储服务器
|
||||||
|
return RedirectResponse(await storage.get_url(info))
|
||||||
else:
|
else:
|
||||||
filepath = await storage.get_filepath(info.text)
|
filepath = await storage.get_filepath(info.text)
|
||||||
return FileResponse(filepath, filename=info.name)
|
return FileResponse(filepath, filename=info.name)
|
||||||
|
|
||||||
|
|
||||||
@app.post('/share', dependencies=[Depends(admin_required)], description='分享文件')
|
@app.post('/file/create/')
|
||||||
async def share(background_tasks: BackgroundTasks, text: str = Form(default=None),
|
async def create_file():
|
||||||
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)):
|
return {'code': 200, 'data': await storage.create_upload_file()}
|
||||||
code = await get_code(s)
|
|
||||||
if style == '2':
|
|
||||||
if value > settings.MAX_DAYS:
|
@app.post('/file/upload/{file_key}/')
|
||||||
raise HTTPException(status_code=400, detail=f"最大有效天数为{settings.MAX_DAYS}天")
|
async def upload_file(file_key: str, file: bytes = File(...), chunk_index: int = Form(...),
|
||||||
exp_time = datetime.datetime.now() + datetime.timedelta(days=value)
|
total_chunks: int = Form(...)):
|
||||||
exp_count = -1
|
await storage.save_chunk_file(file_key, file, chunk_index, total_chunks)
|
||||||
elif style == '1':
|
return {'code': 200}
|
||||||
if value < 1:
|
|
||||||
raise HTTPException(status_code=400, detail="最小有效次数为1次")
|
|
||||||
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
|
@app.get('/file/merge/{file_key}/')
|
||||||
exp_count = value
|
async def merge_chunks(file_key: str, file_name: str, total_chunks: int):
|
||||||
else:
|
return {'code': 200, 'data': await storage.merge_chunks(file_key, file_name, total_chunks)}
|
||||||
exp_time = datetime.datetime.now() + datetime.timedelta(days=1)
|
|
||||||
exp_count = -1
|
|
||||||
key = uuid.uuid4().hex
|
class ShareDataModel(BaseModel):
|
||||||
if file:
|
text: str
|
||||||
size = await storage.get_size(file)
|
size: int = 0
|
||||||
if size > settings.FILE_SIZE_LIMIT:
|
exp_style: str
|
||||||
raise HTTPException(status_code=400, detail="文件过大")
|
exp_value: int
|
||||||
_text, _type, name = await storage.get_text(file, key), file.content_type, file.filename
|
type: str
|
||||||
background_tasks.add_task(storage.save_file, file, _text)
|
name: str
|
||||||
else:
|
key: str = uuid.uuid4
|
||||||
size, _text, _type, name = len(text), text, 'text', '文本分享'
|
|
||||||
|
|
||||||
|
@app.post('/share/file/', dependencies=[Depends(admin_required)], description='分享文件')
|
||||||
|
async def share_file(file_model: ShareDataModel, s: AsyncSession = Depends(get_session),
|
||||||
|
ip: str = Depends(error_ip_limit)):
|
||||||
|
exp_error, exp_time, exp_count, code = await get_expire_info(file_model.exp_style, file_model.exp_value, s)
|
||||||
|
if exp_error:
|
||||||
|
raise HTTPException(status_code=400, detail='过期值异常')
|
||||||
|
s.add(Codes(code=code, text=file_model.text, size=file_model.size, type=file_model.type, name=file_model.name,
|
||||||
|
count=exp_count, exp_time=exp_time, key=file_model.key))
|
||||||
|
await s.commit()
|
||||||
|
upload_ip_limit.add_ip(ip)
|
||||||
|
return {
|
||||||
|
'detail': '分享成功,请点击我的文件按钮查看上传列表',
|
||||||
|
'data': {'code': code, 'key': file_model.key, 'name': file_model.name}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/share/text/', dependencies=[Depends(admin_required)])
|
||||||
|
async def share_text(text_model: ShareDataModel, s: AsyncSession = Depends(get_session),
|
||||||
|
ip: str = Depends(error_ip_limit)):
|
||||||
|
exp_error, exp_time, exp_count, code = await get_expire_info(text_model.exp_style, text_model.exp_value, s, )
|
||||||
|
if exp_error:
|
||||||
|
raise HTTPException(status_code=400, detail='过期值异常')
|
||||||
|
exp_status, exp_time, exp_count, code = await get_expire_info(text_model.exp_style, text_model.exp_value, s)
|
||||||
|
size, _text, _type, name, key = len(text_model.text), text_model.text, 'text', '文本分享', text_model.key().hex
|
||||||
s.add(Codes(code=code, text=_text, size=size, type=_type, name=name, count=exp_count, exp_time=exp_time, key=key))
|
s.add(Codes(code=code, text=_text, size=size, type=_type, name=name, count=exp_count, exp_time=exp_time, key=key))
|
||||||
await s.commit()
|
await s.commit()
|
||||||
upload_ip_limit.add_ip(ip)
|
upload_ip_limit.add_ip(ip)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
<h1>文件快递柜-轻量</h1>
|
<h1>文件快递柜-轻量</h1>
|
||||||
<h2>FileCodeBox-Lite</h2>
|
<h2>FileCodeBox-Lite</h2>
|
||||||
<p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p>
|
<p><em>匿名口令分享文本,文件,像拿快递一样取文件</em></p>
|
||||||
|
<p>交流Q群:739673698,欢迎各位集思广益,项目构思重构中</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||

|

|
||||||
@@ -21,7 +22,8 @@
|
|||||||
- [x] 匿名分享:无需注册,无需登录
|
- [x] 匿名分享:无需注册,无需登录
|
||||||
- [x] 管理面板:查看所有文件,删除文件
|
- [x] 管理面板:查看所有文件,删除文件
|
||||||
- [x] 一键部署:docker一键部署
|
- [x] 一键部署:docker一键部署
|
||||||
- [x] 多种存储方式:阿里云OSS、本地文件流
|
- [x] 自由拓展:阿里云OSS、本地文件流,可根据需求在storage文件中新增存储引擎
|
||||||
|
- [x] 简单明了:适合新手练手项目
|
||||||
|
|
||||||
## 部署方式
|
## 部署方式
|
||||||
|
|
||||||
@@ -39,6 +41,10 @@ docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --n
|
|||||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:arm
|
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:arm
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 宝塔部署
|
||||||
|
|
||||||
|
https://www.yuque.com/lxyo/work/lc1oe0xqk8t9b976
|
||||||
|
|
||||||
### 更新方式
|
### 更新方式
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+4
-4
@@ -18,9 +18,7 @@ class Settings:
|
|||||||
# Sqlite套接字
|
# Sqlite套接字
|
||||||
DATABASE_URL = config('DATABASE_URL', cast=str, default=f"sqlite+aiosqlite:///{DATABASE_FILE}")
|
DATABASE_URL = config('DATABASE_URL', cast=str, default=f"sqlite+aiosqlite:///{DATABASE_FILE}")
|
||||||
# 数据存储文件夹,文件就不暴露在静态资源里面了
|
# 数据存储文件夹,文件就不暴露在静态资源里面了
|
||||||
DATA_ROOT = './data/' + config('DATA_ROOT', cast=str, default=f"static")
|
DATA_ROOT = config('DATA_ROOT', cast=str, default=f"./data/static")
|
||||||
# 本地文件夹
|
|
||||||
LOCAL_ROOT = './data/' + config('LOCAL_ROOT', cast=str, default=f"local")
|
|
||||||
# 静态文件夹URL
|
# 静态文件夹URL
|
||||||
STATIC_URL = config('STATIC_URL', cast=str, default="/static")
|
STATIC_URL = config('STATIC_URL', cast=str, default="/static")
|
||||||
# 开启上传
|
# 开启上传
|
||||||
@@ -33,6 +31,8 @@ class Settings:
|
|||||||
ERROR_MINUTE = config('ERROR_MINUTE', cast=int, default=10)
|
ERROR_MINUTE = config('ERROR_MINUTE', cast=int, default=10)
|
||||||
# 上传次数
|
# 上传次数
|
||||||
UPLOAD_COUNT = config('UPLOAD_COUNT', cast=int, default=60)
|
UPLOAD_COUNT = config('UPLOAD_COUNT', cast=int, default=60)
|
||||||
|
# 是否允许永久保存
|
||||||
|
ENABLE_PERMANENT = config('ENABLE_PERMANENT', cast=bool, default=True)
|
||||||
# 上传限制分钟数
|
# 上传限制分钟数
|
||||||
UPLOAD_MINUTE = config('UPLOAD_MINUTE', cast=int, default=1)
|
UPLOAD_MINUTE = config('UPLOAD_MINUTE', cast=int, default=1)
|
||||||
# 删除过期文件的间隔(分钟)
|
# 删除过期文件的间隔(分钟)
|
||||||
@@ -42,7 +42,7 @@ class Settings:
|
|||||||
# 管理密码
|
# 管理密码
|
||||||
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default=uuid.uuid4().hex)
|
ADMIN_PASSWORD = config('ADMIN_PASSWORD', cast=str, default=uuid.uuid4().hex)
|
||||||
# 文件大小限制,默认10MB
|
# 文件大小限制,默认10MB
|
||||||
FILE_SIZE_LIMIT = config('FILE_SIZE_LIMIT', cast=int, default=10) * 1024 * 1024
|
FILE_SIZE_LIMIT = config('FILE_SIZE_LIMIT', cast=int, default=10 * 1024 * 1024)
|
||||||
# 网站标题
|
# 网站标题
|
||||||
TITLE = config('TITLE', cast=str, default="文件快递柜")
|
TITLE = config('TITLE', cast=str, default="文件快递柜")
|
||||||
# 网站描述
|
# 网站描述
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+2
-21
@@ -30,7 +30,6 @@
|
|||||||
<el-col :span="24" style="text-align: center">
|
<el-col :span="24" style="text-align: center">
|
||||||
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
|
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
|
||||||
<el-menu-item index="2">分享文件管理</el-menu-item>
|
<el-menu-item index="2">分享文件管理</el-menu-item>
|
||||||
<el-menu-item index="3">本地文件列表</el-menu-item>
|
|
||||||
<el-menu-item index="4">系统配置</el-menu-item>
|
<el-menu-item index="4">系统配置</el-menu-item>
|
||||||
</el-menu>
|
</el-menu>
|
||||||
</el-col>
|
</el-col>
|
||||||
@@ -44,7 +43,8 @@
|
|||||||
<div>取件码:${ file.code }</div>
|
<div>取件码:${ file.code }</div>
|
||||||
<div>文件名:${ file.name }</div>
|
<div>文件名:${ file.name }</div>
|
||||||
<div>次 数:${ file.count }</div>
|
<div>次 数:${ file.count }</div>
|
||||||
<div>到 期:${ file.exp_time.slice(0,19) }</div>
|
<div v-if="file.exp_time">到 期:${ file.exp_time.slice(0,19) }</div>
|
||||||
|
<div v-else>到 期:永不过期</div>
|
||||||
<div v-if="file.name==='文本分享'">
|
<div v-if="file.name==='文本分享'">
|
||||||
<span style="white-space: pre-line">内 容:${ file.text }</span>
|
<span style="white-space: pre-line">内 容:${ file.text }</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -73,25 +73,6 @@
|
|||||||
>
|
>
|
||||||
</el-pagination>
|
</el-pagination>
|
||||||
</el-col>
|
</el-col>
|
||||||
<el-col v-if="activeIndex === '3'">
|
|
||||||
<el-card style="height: 80vh;overflow: scroll;margin-bottom: 1rem">
|
|
||||||
<el-empty v-if="locals.length === 0"
|
|
||||||
description="暂时还没有文件,请上传至/opt/data/locals目录"></el-empty>
|
|
||||||
<el-card v-for="file in locals" :key="file.code">
|
|
||||||
<el-row>
|
|
||||||
<el-col :span="20">
|
|
||||||
<div style="cursor: pointer;text-align: left">
|
|
||||||
<div>文件名:${ file.name }</div>
|
|
||||||
<div>路径:${ file.path }</div>
|
|
||||||
</div>
|
|
||||||
</el-col>
|
|
||||||
<el-col :span="4">
|
|
||||||
<el-button type="primary" @click="shareFile(file)">分享</el-button>
|
|
||||||
</el-col>
|
|
||||||
</el-row>
|
|
||||||
</el-card>
|
|
||||||
</el-card>
|
|
||||||
</el-col>
|
|
||||||
<el-col v-if="activeIndex === '4'">
|
<el-col v-if="activeIndex === '4'">
|
||||||
<el-row>
|
<el-row>
|
||||||
<el-col :span="4" style="height: 88vh;overflow: scroll;text-align: center" :gutter="10">
|
<el-col :span="4" style="height: 88vh;overflow: scroll;text-align: center" :gutter="10">
|
||||||
|
|||||||
+169
-55
@@ -6,22 +6,23 @@
|
|||||||
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
||||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||||
<link rel="stylesheet" href="/static/asserts/index.css">
|
<link rel="stylesheet" href="/static/asserts/index.css">
|
||||||
|
<link rel="stylesheet" href="/static/asserts/github-markdown-css/github-markdown.css">
|
||||||
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
|
<link rel="shortcut icon" href="/static/asserts/favicon.ico" type="image/x-icon"/>
|
||||||
<title>{{title}}</title>
|
<title>{{title}}</title>
|
||||||
<meta name="description" content="{{description}}"/>
|
<meta name="description" content="{{description}}"/>
|
||||||
<meta name="keywords" content="{{keywords}}"/>
|
<meta name="keywords" content="{{keywords}}"/>
|
||||||
<meta name="generator" content="FileCodeBox"/>
|
<meta name="generator" content="FileCodeBox"/>
|
||||||
<meta name="template" content="V1.6 Beta"/>
|
<meta name="template" content="V1.7 Beta"/>
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {
|
||||||
background: #f5f5f5;
|
background: #f5f5f5;
|
||||||
}
|
}
|
||||||
|
|
||||||
.qu .el-button {
|
.qu .el-button {
|
||||||
width: 100px;
|
width: 6rem;
|
||||||
height: 100px;
|
height: 6rem;
|
||||||
margin: 0.2rem;
|
margin: 0.2rem;
|
||||||
font-size: 30px;
|
font-size: 2rem;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +44,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background-color: #18181c;
|
background-color: #18181c;
|
||||||
}
|
}
|
||||||
@@ -64,6 +64,14 @@
|
|||||||
background-color: rgba(0, 0, 0, 0.2);
|
background-color: rgba(0, 0, 0, 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.el-button:focus, .el-button:hover {
|
||||||
|
background-color: rgba(0, 0, 0, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-button:active, .el-select-dropdown__item.hover, .el-select-dropdown__item:hover, .el-input.is-disabled .el-input__inner {
|
||||||
|
background-color: rgba(0, 0, 0, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
.el-drawer, #el-drawer__title, .el-drawer__body, .el-drawer__wrapper {
|
.el-drawer, #el-drawer__title, .el-drawer__body, .el-drawer__wrapper {
|
||||||
background-color: rgba(0, 0, 0, 0.5);
|
background-color: rgba(0, 0, 0, 0.5);
|
||||||
border: 1px solid transparent;
|
border: 1px solid transparent;
|
||||||
@@ -138,29 +146,39 @@
|
|||||||
</el-carousel>
|
</el-carousel>
|
||||||
</div>
|
</div>
|
||||||
<el-row>
|
<el-row>
|
||||||
<el-input style="width: 190px" placeholder="数量" v-model="uploadData.value"
|
<el-input style="width: 190px" :disabled="uploadData.exp_style==='forever'" placeholder="数量"
|
||||||
|
v-model="uploadData.exp_value"
|
||||||
class="input-with-select">
|
class="input-with-select">
|
||||||
<el-select style="width: 75px" v-model="uploadData.style" slot="prepend" placeholder="请选择">
|
<el-select style="width: 75px" v-model="uploadData.exp_style" slot="prepend"
|
||||||
<el-option label="天数" value="2"></el-option>
|
placeholder="请选择">
|
||||||
<el-option label="次数" value="1"></el-option>
|
<el-option label="天数" value="day"></el-option>
|
||||||
|
<el-option label="小时" value="hour"></el-option>
|
||||||
|
<el-option label="分钟" value="minute"></el-option>
|
||||||
|
<el-option label="永久" value="forever"></el-option>
|
||||||
|
<el-option label="次数" value="count"></el-option>
|
||||||
</el-select>
|
</el-select>
|
||||||
<el-button v-if="uploadData.style === '1'" slot="append" disabled>次</el-button>
|
<el-button slot="append" disabled>${exp_style_dict[uploadData.exp_style]}</el-button>
|
||||||
<el-button v-else slot="append" disabled>天</el-button>
|
|
||||||
</el-input>
|
</el-input>
|
||||||
<el-radio-group style="margin-left: 18px" v-model="uploadData.type">
|
<el-radio-group style="margin-left: 18px" v-model="uploadData.is_file">
|
||||||
<el-radio label="1">
|
<el-radio label="1">
|
||||||
文件
|
文件
|
||||||
</el-radio>
|
</el-radio>
|
||||||
<el-radio label="2">
|
<el-radio label="0">
|
||||||
文本
|
文本
|
||||||
</el-radio>
|
</el-radio>
|
||||||
</el-radio-group>
|
</el-radio-group>
|
||||||
</el-row>
|
</el-row>
|
||||||
|
|
||||||
<el-upload
|
<el-upload
|
||||||
v-if="uploadData.type === '1'"
|
v-if="uploadData.is_file === '1'"
|
||||||
drag
|
drag
|
||||||
|
v-loading="uploading"
|
||||||
action="/share"
|
action="/share"
|
||||||
|
:element-loading-text="loadingText"
|
||||||
|
element-loading-spinner="el-icon-loading"
|
||||||
multiple
|
multiple
|
||||||
|
:disabled="uploading"
|
||||||
|
:http-request="uploadFile"
|
||||||
style="margin: 1rem 0;"
|
style="margin: 1rem 0;"
|
||||||
:data="uploadData"
|
:data="uploadData"
|
||||||
:before-upload="beforeUpload"
|
:before-upload="beforeUpload"
|
||||||
@@ -180,7 +198,6 @@
|
|||||||
placeholder="请输入内容,使用按钮存入"
|
placeholder="请输入内容,使用按钮存入"
|
||||||
v-model="uploadData.text">
|
v-model="uploadData.text">
|
||||||
</el-input>
|
</el-input>
|
||||||
|
|
||||||
<div class="el-upload__tip">
|
<div class="el-upload__tip">
|
||||||
<el-button round @click="pageNum=0">
|
<el-button round @click="pageNum=0">
|
||||||
<div class="el-icon-back"></div>
|
<div class="el-icon-back"></div>
|
||||||
@@ -190,7 +207,7 @@
|
|||||||
<div class="el-icon-takeaway-box"></div>
|
<div class="el-icon-takeaway-box"></div>
|
||||||
我的文件
|
我的文件
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-button round v-if="uploadData.type === '2'" @click="toUploadData">
|
<el-button round v-if="uploadData.is_file === '0'" @click="uploadText">
|
||||||
<div class="el-icon-upload2"></div>
|
<div class="el-icon-upload2"></div>
|
||||||
存入
|
存入
|
||||||
</el-button>
|
</el-button>
|
||||||
@@ -209,8 +226,7 @@
|
|||||||
<div>取件码:${ file.code }</div>
|
<div>取件码:${ file.code }</div>
|
||||||
<div>文件名:${ file.name }</div>
|
<div>文件名:${ file.name }</div>
|
||||||
<div v-if="file.name==='文本分享'">
|
<div v-if="file.name==='文本分享'">
|
||||||
<span style="white-space: pre-line"
|
<article v-html="file.text" class="markdown-body" @click="copyText(file.text,1)"></article>
|
||||||
@click="copyText(file.text,1)">内 容:${ file.text }</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div v-else>
|
<div v-else>
|
||||||
<span>链 接:</span>
|
<span>链 接:</span>
|
||||||
@@ -252,7 +268,7 @@
|
|||||||
</el-drawer>
|
</el-drawer>
|
||||||
<div style="text-align: center; margin-top: 1rem;color: #606266">
|
<div style="text-align: center; margin-top: 1rem;color: #606266">
|
||||||
<a style="text-decoration: none;color: #606266" target="_blank" href="https://github.com/vastsa/FileCodeBox">FileCodeBox
|
<a style="text-decoration: none;color: #606266" target="_blank" href="https://github.com/vastsa/FileCodeBox">FileCodeBox
|
||||||
V1.6 Beta</a>
|
V1.7 Beta</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
@@ -267,8 +283,16 @@
|
|||||||
quDrawer: false,
|
quDrawer: false,
|
||||||
jiDrawer: false,
|
jiDrawer: false,
|
||||||
direction: 'btt',
|
direction: 'btt',
|
||||||
|
exp_style_dict: {
|
||||||
|
'day': '天',
|
||||||
|
'hour': '时',
|
||||||
|
'minute': '分',
|
||||||
|
'forever': '无',
|
||||||
|
'count': '次',
|
||||||
|
},
|
||||||
quFiles: [],
|
quFiles: [],
|
||||||
jiFiles: [],
|
jiFiles: [],
|
||||||
|
uploadGroup: [],
|
||||||
pageNum: 0,
|
pageNum: 0,
|
||||||
inputDisable: false,
|
inputDisable: false,
|
||||||
fileSizeLimit: '{{fileSizeLimit}}',
|
fileSizeLimit: '{{fileSizeLimit}}',
|
||||||
@@ -276,12 +300,16 @@
|
|||||||
banners: [],
|
banners: [],
|
||||||
enableUpload: false,
|
enableUpload: false,
|
||||||
uploadData: {
|
uploadData: {
|
||||||
style: '2',
|
exp_style: 'day',
|
||||||
type: '1',
|
exp_value: 1,
|
||||||
value: 1,
|
type: 'text',
|
||||||
file: null,
|
name: '文本分享',
|
||||||
text: ''
|
is_file: '1',
|
||||||
|
text: '',
|
||||||
|
size: 0,
|
||||||
},
|
},
|
||||||
|
uploading: false,
|
||||||
|
loadingText: '正在上传中...',
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
mounted: function () {
|
mounted: function () {
|
||||||
@@ -303,14 +331,13 @@
|
|||||||
that.$message('剪切板文字正在上传,请稍等');
|
that.$message('剪切板文字正在上传,请稍等');
|
||||||
items[i].getAsString(function (str) {
|
items[i].getAsString(function (str) {
|
||||||
that.uploadData.text = str;
|
that.uploadData.text = str;
|
||||||
that.toUploadData();
|
that.uploadText();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const file = items[i].getAsFile();
|
const file = items[i].getAsFile();
|
||||||
that.$message('剪切板文件正在上传,请稍等');
|
that.$message('剪切板文件正在上传,请稍等');
|
||||||
that.uploadData.file = file
|
that.uploadFile({file: file});
|
||||||
that.toUploadData();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -343,19 +370,35 @@
|
|||||||
data: data,
|
data: data,
|
||||||
...config
|
...config
|
||||||
}).then(res => {
|
}).then(res => {
|
||||||
this.$message({
|
if (res.data.detail) {
|
||||||
message: res.data.detail,
|
this.$message({
|
||||||
type: 'success'
|
message: res.data.detail,
|
||||||
});
|
type: 'success'
|
||||||
|
});
|
||||||
|
}
|
||||||
resolve(res.data)
|
resolve(res.data)
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
this.$message({
|
if (err.response.data.detail) {
|
||||||
message: err.response.data.detail,
|
this.$message({
|
||||||
type: 'error'
|
message: err.response.data.detail,
|
||||||
});
|
type: 'error'
|
||||||
|
});
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
uploadChunk: async function (chunk, file_key, chunk_index, total_chunks) {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', chunk);
|
||||||
|
formData.append('file_key', file_key);
|
||||||
|
formData.append('chunk_index', chunk_index);
|
||||||
|
formData.append('total_chunks', total_chunks);
|
||||||
|
this.http('post', `/file/upload/${file_key}/`, formData).then((res) => {
|
||||||
|
this.upload_groups[chunk_index - 1] = 1;
|
||||||
|
}).catch((res) => {
|
||||||
|
this.upload_groups[chunk_index - 1] = 2;
|
||||||
|
})
|
||||||
|
},
|
||||||
copyText: function (value, style = 1) {
|
copyText: function (value, style = 1) {
|
||||||
if (style === 0) {
|
if (style === 0) {
|
||||||
value = `我给你分享了文件,取件码:${value},${window.location.href}?code=${value}`;
|
value = `我给你分享了文件,取件码:${value},${window.location.href}?code=${value}`;
|
||||||
@@ -413,34 +456,105 @@
|
|||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
toUploadData: function () {
|
uploadText: function () {
|
||||||
if (this.uploadData.text === '' && this.uploadData.file === null) {
|
if (this.uploadData.text === '') {
|
||||||
this.$message({
|
this.$message({
|
||||||
message: '请先粘贴文字或者上传文件',
|
message: '请先粘贴文字',
|
||||||
type: 'error'
|
type: 'error'
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
if (this.checkFile(this.uploadData.file)) {
|
this.http('post', '/share/text/', this.uploadData, {
|
||||||
this.http('post', '/share', this.uploadData, {
|
headers: {
|
||||||
headers: {
|
'pwd': this.pwd
|
||||||
'Content-Type': 'multipart/form-data',
|
}
|
||||||
'pwd': this.pwd
|
}).then(res => {
|
||||||
}
|
this.jiFiles.unshift(res.data);
|
||||||
}).then(res => {
|
this.jiDrawer = true;
|
||||||
this.jiFiles.unshift(res.data);
|
this.uploadData.text = '';
|
||||||
this.jiDrawer = true;
|
this.$message({
|
||||||
this.uploadData.text = '';
|
message: '上传成功',
|
||||||
this.uploadData.file = null;
|
type: 'success'
|
||||||
});
|
});
|
||||||
}
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
uploadFile: async function (e) {
|
||||||
|
const that = this;
|
||||||
|
if (this.checkFile(e.file)) {
|
||||||
|
that.uploading = true;
|
||||||
|
that.loadingText = '正在上传中...';
|
||||||
|
this.http('post', '/file/create/').then(async res => {
|
||||||
|
const file = e.file;
|
||||||
|
let chunk_index = 0;
|
||||||
|
const shardSize = 1024 * 1024 * 5;
|
||||||
|
const {name, size, type} = file;
|
||||||
|
const total_chunks = Math.ceil(size / shardSize);
|
||||||
|
this.upload_groups = [];
|
||||||
|
for (let i = 0; i < total_chunks; i++) {
|
||||||
|
this.upload_groups.push(0);
|
||||||
|
}
|
||||||
|
while (chunk_index < total_chunks) {
|
||||||
|
const start = chunk_index * shardSize
|
||||||
|
const end = Math.min(start + shardSize, size)
|
||||||
|
chunk_index += 1;
|
||||||
|
this.uploadChunk(file.slice(start, end), res.data, chunk_index, total_chunks);
|
||||||
|
}
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
let success = 0;
|
||||||
|
let flag = true;
|
||||||
|
for (let i = 0; i < total_chunks; i++) {
|
||||||
|
if (this.upload_groups[i] === 0) {
|
||||||
|
flag = false;
|
||||||
|
} else if (this.upload_groups[i] === 2) {
|
||||||
|
flag = false;
|
||||||
|
start = chunk_index * shardSize;
|
||||||
|
const end = Math.min(start + shardSize, size);
|
||||||
|
this.uploadChunk(file.slice(start, end), res.data, chunk_index, total_chunks);
|
||||||
|
} else {
|
||||||
|
success += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
that.loadingText = `已上传${ (success/total_chunks*100).toFixed(2) }%`;
|
||||||
|
if (flag) {
|
||||||
|
clearInterval(interval);
|
||||||
|
this.http('get', `/file/merge/${res.data}/?file_name=${name}&total_chunks=${total_chunks}`).then(text => {
|
||||||
|
this.http('post', '/share/file/', {
|
||||||
|
text: text.data,
|
||||||
|
size: size,
|
||||||
|
exp_style: this.uploadData.exp_style,
|
||||||
|
exp_value: this.uploadData.exp_value,
|
||||||
|
type: type,
|
||||||
|
name: name,
|
||||||
|
key: res.data,
|
||||||
|
}, {
|
||||||
|
headers: {
|
||||||
|
'pwd': this.pwd
|
||||||
|
}
|
||||||
|
}).then(res => {
|
||||||
|
this.jiFiles.unshift(res.data);
|
||||||
|
this.jiDrawer = true;
|
||||||
|
this.uploadData.text = '';
|
||||||
|
this.uploadData.file = null;
|
||||||
|
that.uploading = false;
|
||||||
|
this.$message({
|
||||||
|
message: '上传成功',
|
||||||
|
type: 'success'
|
||||||
|
});
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
successUpload(response, file, fileList) {
|
successUpload(response, file, fileList) {
|
||||||
this.$message({
|
if (response) {
|
||||||
message: response.detail,
|
this.$message({
|
||||||
type: 'success'
|
message: response.detail,
|
||||||
});
|
type: 'success'
|
||||||
this.jiFiles.unshift(response.data);
|
});
|
||||||
|
this.jiFiles.unshift(response.data);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
errorUpload(error, file, fileList) {
|
errorUpload(error, file, fileList) {
|
||||||
error = JSON.parse(error.message)
|
error = JSON.parse(error.message)
|
||||||
|
|||||||
Reference in new issue
Block a user