-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservers.py
284 lines (228 loc) · 9.41 KB
/
servers.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
from fastapi import FastAPI
from fastapi import APIRouter, Request, Response, HTTPException
from fastapi.responses import HTMLResponse, FileResponse
from pathlib import Path
import os
import datetime as dt
from typing import Optional
from typing import Union
from fastapi.responses import FileResponse
from os import getcwd, remove
from fastapi.responses import JSONResponse
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
current_directory = os.getcwd()
current_path = os.path.abspath(os.getcwd())
FolderPath = os.getcwd()
def getReadableByteSize(num, suffix="B") -> str:
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, "Y", suffix)
def getTimeStampString(tSec: float) -> str:
tObj = dt.datetime.fromtimestamp(tSec)
tStr = dt.datetime.strftime(tObj, "%Y-%m-%d %H:%M:%S")
return tStr
def getIconClassForFilename(fName):
fileExt = Path(fName).suffix
fileExt = fileExt[1:] if fileExt.startswith(".") else fileExt
fileTypes = ["aac","ai","bmp","cs","css","csv","doc","docx","exe",
"gif","heic","html","java","jpg","js","json","jsx",
"key","m4p","md","mdx","mov","mp3","mp4","otf","pdf",
"php","png","pptx","psd","py","raw","rb","sass","scss",
"sh","sql","svg","tiff","tsx","ttf","txt","wav","woff",
"xlsx","xml","yml",
]
fileIconClass = f"bi bi-filetype-{fileExt}" if fileExt in fileTypes else "bi bi-file-earmark"
return fileIconClass
@app.get("/cwd")
async def cwd():
allpaths = {
"current_directory": current_directory,
"current_path": current_path,
}
return(allpaths)
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
with open(file.filename, 'wb') as image:
content = await file.read()
image.write(content)
image.close()
return JSONResponse(content={"filename": file.filename},
status_code=200)
@app.get("/download/{name_file}")
def download_file(name_file: str):
return FileResponse(path=getcwd() + "/" + name_file, media_type='application/octet-stream', filename=name_file)
@app.get("/file/{name_file}")
def get_file(name_file: str):
return FileResponse(path=getcwd() + "/" + name_file)
@app.delete("/delete/file/{name_file}")
def delete_file(name_file: str):
try:
remove(getcwd() + "/" + name_file)
return JSONResponse(content={
"removed": True
}, status_code=200)
except FileNotFoundError:
return JSONResponse(content={
"removed": False,
"error_message": "File not found"
}, status_code=404)
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pathlib import Path
from typing import Union
@app.get("/reports/{path:path}")
@app.get("/reports/")
async def get_files(request: Request, path: Union[str, None] = None):
abs_path = Path(FolderPath) / path if path else Path(FolderPath)
file_list = []
for f in abs_path.iterdir():
file_stat = f.stat()
file_obj = {
"name": f.name,
"fIcon": "bi bi-folder-fill" if f.is_dir() else getIconClassForFilename(f.name),
"relPath": str(f.relative_to(Path(FolderPath))).replace("\\", "/"),
"mTime": getTimeStampString(file_stat.st_mtime),
"size": getReadableByteSize(file_stat.st_size),
}
if f.is_dir():
file_obj["hasFiles"] = any(f.is_file() for f in f.iterdir())
file_list.append(file_obj)
return JSONResponse(content=file_list)
@app.post('/reports/')
async def get_files(request: Request):
data = await request.json()
req_path = data['path']
abs_path = Path(FolderPath) / req_path
def f_obj_from_scan(x):
file_stat = x.stat()
# return file information for rendering
return {
"name": x.name,
"fIcon": "bi bi-folder-fill" if x.is_dir() else getIconClassForFilename(x.name),
"relPath": str(x.relative_to(Path(FolderPath))).replace("\\", "/"),
"mTime": getTimeStampString(file_stat.st_mtime),
"size": getReadableByteSize(file_stat.st_size),
}
file_list = [f_obj_from_scan(f) for f in abs_path.iterdir()]
return JSONResponse(content=file_list)
@app.post('/files-display/{item}')
def displayfiles():
html_content = """
<html>
<body>
<div id='directory' class='table table-striped table-responsive'></div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css'>
<style>
table {table-layout:fixed; width:100%;}
table td, th {word-wrap:break-word;}
th {text-align: left;}
</style>
<script>
subdirectory_path = "";
$.ajax({
url: '/reports/' + subdirectory_path,
//url: '/reports/',
type: 'GET',
success: function(response) {
$('#directory').append(
"<table>"+
"<tbody>"
);
$.each(response, function(i, item) {
num = i + 1;
$('#directory').append(
"<tr>"+
" <td scope='row'>"+num+"</td>"+
" <td>"+
" <a href='http://127.0.0.1:8000/files-display/"+item.relPath+"' >"+
" <span><i class='"+item.fIcon+"' style='margin-right:0.3em'></i></span>"+
" </a>"+
" </td>"+
" <th> "+item.name+" </th>"+
" <th> "+item.mTime+" </th>"+
" <th> "+item.size+" </th>"+
"</tr>"
);
});
$('#directory').append(
" </tbody>"+
"</table>"+
"<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css'>"+
"<style>"+
" table {table-layout:fixed; width:100%;}"+
" table td, th {word-wrap:break-word;}"+
" th {text-align: left;}"+
"</style>");
}
});
</script>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css'>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
@app.get('/files-display')
def displayfiles():
html_content = """
<html>
<body>
<div id='directory' class='table table-striped table-responsive'></div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css'>
<style>
table {table-layout:fixed; width:100%;}
table td, th {word-wrap:break-word;}
th {text-align: left;}
</style>
<script>
subdirectory_path = "";
$.ajax({
url: '/reports/' + subdirectory_path,
//url: '/reports/',
type: 'GET',
success: function(response) {
$('#directory').append(
"<table>"+
"<tbody>"
);
$.each(response, function(i, item) {
num = i + 1;
$('#directory').append(
"<tr>"+
" <td scope='row'>"+num+"</td>"+
" <td>"+
" <a href='http://127.0.0.1:8000/files-display/"+item.relPath+"' >"+
" <span><i class='"+item.fIcon+"' style='margin-right:0.3em'></i></span>"+
" </a>"+
" </td>"+
" <th> "+item.name+" </th>"+
" <th> "+item.mTime+" </th>"+
" <th> "+item.size+" </th>"+
"</tr>"
);
});
$('#directory').append(
" </tbody>"+
"</table>"+
"<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css'>"+
"<style>"+
" table {table-layout:fixed; width:100%;}"+
" table td, th {word-wrap:break-word;}"+
" th {text-align: left;}"+
"</style>");
}
});
</script>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css'>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)