-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
347 lines (304 loc) · 13.1 KB
/
Copy pathmain.py
File metadata and controls
347 lines (304 loc) · 13.1 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# Project: file_manager
# File Path: file_manager/main.py
# Last Updated: 2025-08-23 07:35:00
from flask import Flask, render_template, request, jsonify, send_from_directory
import os
import shutil
import stat
import mimetypes
import zipfile
import sys # Added for logging
app = Flask(__name__, static_folder='static', template_folder='templates')
# --- CORRECTED AND ROBUST ROOT DIRECTORY ---
# This points to the mounted /files directory (which is /home/ubuntu on host)
ROOT_DIR = '/files'
# Ensure the root directory exists
os.makedirs(ROOT_DIR, exist_ok=True)
def get_full_path(path):
safe_path = os.path.normpath(os.path.join(ROOT_DIR, path.lstrip('/\\')))
if not safe_path.startswith(os.path.realpath(ROOT_DIR)):
raise ValueError("Access denied: Path is outside the allowed directory.")
return safe_path
def get_file_type(path):
if os.path.isdir(path):
return "Folder"
_, extension = os.path.splitext(path)
return extension.lower() if extension else "File"
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/list', methods=['GET'])
def list_files():
try:
path = request.args.get('path', '')
full_path = get_full_path(path)
items = []
for item_name in os.listdir(full_path):
item_path = os.path.join(full_path, item_name)
try:
file_stat = os.stat(item_path)
items.append({
'name': item_name,
'type': 'dir' if os.path.isdir(item_path) else 'file',
'size': file_stat.st_size,
'last_modified': file_stat.st_mtime,
'permissions': oct(stat.S_IMODE(file_stat.st_mode))[-3:],
'file_type_str': get_file_type(item_path)
})
except OSError as e:
print(f"Could not stat file {item_path}: {e}", file=sys.stderr)
continue
return jsonify({'items': items})
except Exception as e:
print(f"Error in list_files: {e}", file=sys.stderr) # Added logging
return jsonify({'error': str(e)}), 500
# --- All other routes remain the same ---
@app.route('/api/list_dirs', methods=['GET'])
def list_dirs():
try:
def get_dirs(root_path, rel_path):
tree = []
full_root_path = os.path.join(root_path, rel_path)
try:
for name in os.listdir(full_root_path):
full_item_path = os.path.join(full_root_path, name)
if os.path.isdir(full_item_path):
node = {
"name": name,
"path": os.path.join(rel_path, name),
"children": get_dirs(root_path, os.path.join(rel_path, name))
}
tree.append(node)
except PermissionError:
pass
return tree
dir_tree = [{"name": "Root", "path": "", "children": get_dirs(ROOT_DIR, '')}]
return jsonify(dir_tree)
except Exception as e:
print(f"Error in list_dirs: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/read', methods=['GET'])
def read_file():
try:
path = request.args.get('path', '')
full_path = get_full_path(path)
if os.path.isfile(full_path):
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
return jsonify({'content': content})
return jsonify({'error': 'Not a file'}), 400
except Exception as e:
print(f"Error in read_file: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/save', methods=['POST'])
def save_file():
try:
data = request.json
path = data.get('path', '')
content = data.get('content', '')
full_path = get_full_path(path)
if os.path.isfile(full_path):
with open(full_path, 'w', encoding='utf-8') as f:
f.write(content)
return jsonify({'success': True, 'message': 'File saved successfully!'})
return jsonify({'error': 'Not a file'}), 400
except Exception as e:
print(f"Error in save_file: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/upload', methods=['POST'])
def upload_file():
try:
path = request.form.get('path', '')
relative_path = request.form.get('relative_path', '') # For folder structure
full_path = get_full_path(path)
if 'file' not in request.files:
return jsonify({'error': 'No file part in the request'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected for uploading'}), 400
if file:
filename = file.filename
# If relative_path is provided (folder upload), create directory structure
if relative_path:
target_dir = os.path.join(full_path, relative_path)
os.makedirs(target_dir, exist_ok=True)
destination = os.path.join(target_dir, filename)
else:
destination = os.path.join(full_path, filename)
file.save(destination)
return jsonify({'success': True, 'message': f"File '{filename}' uploaded successfully."})
except Exception as e:
print(f"Error in upload_file: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/create', methods=['POST'])
def create_item():
try:
data = request.json
path = data.get('path', '')
name = data.get('name')
item_type = data.get('type')
full_path = os.path.join(get_full_path(path), name)
if os.path.exists(full_path):
return jsonify({'error': f"'{name}' already exists."}), 400
if item_type == 'dir':
os.makedirs(full_path)
message = f"Folder '{name}' created."
elif item_type == 'file':
open(full_path, 'a').close()
message = f"File '{name}' created."
else:
return jsonify({'error': 'Invalid type'}), 400
return jsonify({'success': True, 'message': message})
except Exception as e:
print(f"Error in create_item: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/delete', methods=['POST'])
def delete_items():
try:
data = request.json
items = data.get('items', [])
for item_path in items:
full_path = get_full_path(item_path)
if os.path.isdir(full_path):
shutil.rmtree(full_path)
elif os.path.isfile(full_path):
os.remove(full_path)
return jsonify({'success': True, 'message': f'{len(items)} item(s) deleted.'})
except Exception as e:
print(f"Error in delete_items: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/rename', methods=['POST'])
def rename_item():
try:
data = request.json
path = data.get('path', '')
old_name = data.get('old_name')
new_name = data.get('new_name')
old_full_path = get_full_path(os.path.join(path, old_name))
new_full_path = get_full_path(os.path.join(path, new_name))
os.rename(old_full_path, new_full_path)
return jsonify({'success': True, 'message': f"Renamed to '{new_name}'."})
except Exception as e:
print(f"Error in rename_item: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/chmod', methods=['POST'])
def chmod_item():
try:
data = request.json
path = data.get('path', '')
permissions = data.get('permissions')
full_path = get_full_path(path)
os.chmod(full_path, int(permissions, 8))
return jsonify({'success': True, 'message': f'Permissions for {os.path.basename(path)} set to {permissions}.'})
except Exception as e:
print(f"Error in chmod_item: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/move', methods=['POST'])
def move_items():
try:
data = request.json
items = data.get('items', [])
destination_path = data.get('destination')
full_dest_path = get_full_path(destination_path)
moved_count = 0
for item_path in items:
source_path = get_full_path(item_path)
dest = os.path.join(full_dest_path, os.path.basename(source_path))
# Handle name conflicts by adding a number
counter = 1
original_dest = dest
while os.path.exists(dest):
name, ext = os.path.splitext(os.path.basename(original_dest))
dest = os.path.join(full_dest_path, f"{name}_{counter}{ext}")
counter += 1
shutil.move(source_path, dest)
moved_count += 1
return jsonify({'success': True, 'message': f'{moved_count} item(s) moved successfully.', 'count': moved_count})
except Exception as e:
print(f"Error in move_items: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/copy', methods=['POST'])
def copy_items():
try:
data = request.json
items = data.get('items', [])
destination_path = data.get('destination')
full_dest_path = get_full_path(destination_path)
copied_count = 0
for item_path in items:
source_path = get_full_path(item_path)
dest = os.path.join(full_dest_path, os.path.basename(source_path))
# Handle name conflicts by adding a number
counter = 1
original_dest = dest
while os.path.exists(dest):
name, ext = os.path.splitext(os.path.basename(original_dest))
if os.path.isdir(source_path):
dest = os.path.join(full_dest_path, f"{name}_{counter}")
else:
dest = os.path.join(full_dest_path, f"{name}_{counter}{ext}")
counter += 1
if os.path.isdir(source_path):
shutil.copytree(source_path, dest)
else:
shutil.copy2(source_path, dest)
copied_count += 1
return jsonify({'success': True, 'message': f'{copied_count} item(s) copied successfully.', 'count': copied_count})
except Exception as e:
print(f"Error in copy_items: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/download')
def download_file():
try:
path = request.args.get('path', '')
full_path = get_full_path(path)
if os.path.isfile(full_path):
directory = os.path.dirname(full_path)
filename = os.path.basename(full_path)
return send_from_directory(directory, filename, as_attachment=True)
return "File not found", 404
except Exception as e:
print(f"Error in download_file: {e}", file=sys.stderr)
return str(e), 500
@app.route('/api/compress', methods=['POST'])
def compress_items():
try:
data = request.json
items = data.get('items', [])
path = data.get('path', '')
archive_name = data.get('name', 'archive.zip')
full_path = get_full_path(path)
zip_path = os.path.join(full_path, archive_name)
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for item_path_rel in items:
full_item_path = get_full_path(item_path_rel)
arcname = os.path.basename(full_item_path)
if os.path.isdir(full_item_path):
for root, _, files in os.walk(full_item_path):
for file in files:
file_to_zip = os.path.join(root, file)
zipf.write(file_to_zip, os.path.join(arcname, os.path.relpath(file_to_zip, full_item_path)))
else:
zipf.write(full_item_path, arcname)
return jsonify({'success': True, 'message': f"'{archive_name}' created successfully."})
except Exception as e:
print(f"Error in compress_items: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
@app.route('/api/extract', methods=['POST'])
def extract_item():
try:
data = request.json
path = data.get('path', '')
full_path = get_full_path(path)
if not zipfile.is_zipfile(full_path):
return jsonify({'error': 'Not a valid zip file.'}), 400
extract_dir = os.path.splitext(full_path)[0]
os.makedirs(extract_dir, exist_ok=True)
with zipfile.ZipFile(full_path, 'r') as zip_ref:
zip_ref.extractall(extract_dir)
return jsonify({'success': True, 'message': f"Extracted to '{os.path.basename(extract_dir)}'."})
except Exception as e:
print(f"Error in extract_item: {e}", file=sys.stderr)
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002, debug=True)