-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
220 lines (194 loc) · 9.24 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import os
import shutil
import aiohttp
import tools
import ow_config as config
from zipfile import ZipFile, ZIP_LZMA
from fastapi import FastAPI, Request, UploadFile, Form
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse
MAIN_DIR = 'storage'
MANAGER_URL = 'http://127.0.0.1:8000'
# Создание приложения
app = FastAPI(
title="Open Workshop",
contact={
"name": "GitHub",
"url": "https://github.com/Open-Workshop"
},
license_info={
"name": "MPL-2.0 license",
"identifier": "MPL-2.0"
},
docs_url="/"
)
@app.middleware("http")
async def modify_header(request: Request, call_next):
response = await call_next(request)
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Expose-Headers"] = "Content-Type,Content-Disposition"
return response
@app.get(
"/download/{type}/{path:path}",
status_code=200,
response_class=FileResponse,
responses={
200: {
"description": "File send successfully",
"content": {"application/octet-stream": {}},
},
403: {
"description": "Access denied",
"content": {"text/plain": {'example': 'Access denied'}}
},
404: {
"description": "File not found on server",
"content": {"text/plain": {'example': 'File not found'}}
},
503: {
"description": "Manager unavailable",
"content": {"text/plain": {'example': 'Manager unavailable'}}
}
},
)
async def download(request: Request, type: str, path: str):
"""
Возвращает запрашиваемый файл, если он существует.
"""
path = path.replace('%2', '/')
real_path = f"{MAIN_DIR}/{type}/{path}"
if os.path.exists(real_path):
if type == 'archive' and path.startswith('mod/'):
# Асинхронно спрашиваем у Manager правомерность доступа к файлу
async with aiohttp.ClientSession() as session:
id = int(path.split('/')[1])
user = request.cookies.get('userID', 0)
async with session.get(f"{MANAGER_URL}/list/mods/access/[{id}]?token={config.check_access}&user={user}") as resp:
if resp.status == 200:
# Возвращает такой же список, проверяем, есть ли в нем интересующий нас ID
data = await resp.json()
if id in data:
# Если есть, то возвращаем сам файл
return FileResponse(real_path)
else:
return PlainTextResponse(status_code=403, content="Access denied")
else:
return PlainTextResponse(status_code=503, content="Manager unavailable")
else:
return FileResponse(real_path)
else:
return PlainTextResponse(status_code=404, content="File not found")
@app.post(
"/upload",
status_code=201,
response_class=PlainTextResponse,
response_model=str,
responses={
201: {
"description": "File uploaded successfully",
"content": {"text/plain": {'example': 'file/is/saved/as.tmp'}},
"model": str
},
}
)
async def upload(request: Request, token: str, file: UploadFile, type: str = Form(), path: str = Form()):
"""
Загружает файл в Storage (микросервис хранения, функция управляется другим микросервисов).
type: Тип файла. Поддерживает следующие значения: img, archive. От этого зависит ключевая директория и доп. действия предпринимаемые сервером.
path: Путь и имя файла. В формате "директории/поддиректории/имя.файла". Если под папок нет существует, то они создаются.
"""
if not tools.check_token('upload_file', token):
return PlainTextResponse(status_code=403, content="Access denied")
real_path = f"{MAIN_DIR}/{type}/{path}"
# Проверяем существует ли директория, если нет, то создаем
if not os.path.exists(os.path.dirname(real_path)):
os.makedirs(os.path.dirname(real_path))
match type:
case "archive":
# Если передан просто файл, то конвертируем его в архив
if not path.endswith(".zip"):
# Создаем временный файл для архива
tmp_path = f"{MAIN_DIR}/{type}/{path}.tmp"
# Сохраняем файл в временный файл
with open(tmp_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Валидируем путь (расширение в конце заменяем)
if '.' in real_path:
# Удалем все что после точки
real_path = real_path[:real_path.rindex('.')]
real_path += '.zip'
if '.' not in path:
path += '.'+file.filename.split('.')[-1]
# Создаем архив
with ZipFile(real_path, "w", compression=ZIP_LZMA, compresslevel=9) as zipped:
zipped.write(tmp_path, path.split('/')[-1])
# Удаляем временный файл
os.remove(tmp_path)
# Удаляем из начала "{MAIN_DIR}/{type}/"
real_path = real_path.replace(f"{MAIN_DIR}/{type}/", "")
return real_path
# Если передан архив, то просто сохраняем
else:
# Сохраняем архив
with open(real_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return path
case _:
# Сохраняем файл
with open(real_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return path
@app.delete(
"/delete",
status_code=200,
response_class=PlainTextResponse,
response_model=str,
responses={
200: {
"description": "File deleted successfully",
"content": {"text/plain": {'example': 'File deleted'}},
"model": str
},
404: {
"description": "File not found on server",
"content": {"text/plain": {'example': 'File not found'}},
"model": str
}
},
)
async def delete(request: Request, token: str, type: str = Form(), path: str = Form()):
"""
Удаляет файл из Steam Workshop (микросервис хранения, функция управляется другим микросервисов).
К удалению разрешены только файлы.
Если после удаления файла, папка пуста, то она тоже удаляется (так же происходит со всеми родительскими папками)
"""
if not tools.check_token('delete_file', token):
return PlainTextResponse(status_code=403, content="Access denied")
# Функция которая удаляет файл и после этого рекурсивно удаляет все родительские папки, если они пусты
def delete_file_and_parent_folders(file_path: str):
"""
Удаляет файл и после этого рекурсивно удаляет все родительские папки, если они пусты. Рекурсия прерывается при доходе до неприкосновенной части (no_delete).
Parameters:
file_path (str): The path of the file to be deleted.
Returns:
JSONResponse
"""
# Если файл не существует, то ничего не делаем
if not os.path.isfile(file_path):
return JSONResponse(status_code=404, content="File not found")
# Удаляем файл
os.remove(file_path)
# Получаем путь к родительской папке файла
folder_path = os.path.dirname(file_path)
# Удаляем папку, если она пуста
while folder_path != "":
if not os.listdir(folder_path):
# удаляем ее
os.rmdir(folder_path)
# получаем путь к родительской папке
folder_path = os.path.dirname(folder_path)
# Если в папке есть файлы,
else:
# то ничего не делаем
break
return JSONResponse(status_code=200, content="File deleted")
return delete_file_and_parent_folders(f"{MAIN_DIR}/{type}/{path}")