|
| 1 | +from flask import Flask, render_template, send_from_directory, abort, url_for, jsonify |
| 2 | +import os |
| 3 | + |
| 4 | +app = Flask(__name__) |
| 5 | + |
| 6 | +# Define your local directory here |
| 7 | +local_directory = '/root' # Replace with the path to your local directory |
| 8 | + |
| 9 | +@app.route('/') |
| 10 | +def explore_root(): |
| 11 | + contents = list_directory_contents(local_directory) |
| 12 | + return render_template('explorer.html', folder_path=local_directory, contents=contents) |
| 13 | + |
| 14 | + |
| 15 | +@app.route('/download/<path:file_path>') |
| 16 | +def download_file(file_path): |
| 17 | + full_file_path = os.path.join(local_directory, file_path) |
| 18 | + |
| 19 | + # Check if the file exists |
| 20 | + if os.path.exists(full_file_path): |
| 21 | + try: |
| 22 | + # Use send_from_directory to serve the file as an attachment |
| 23 | + return send_from_directory(local_directory, file_path, as_attachment=True) |
| 24 | + except Exception as e: |
| 25 | + return f"Error downloading file: {str(e)}" |
| 26 | + else: |
| 27 | + abort(404) |
| 28 | + |
| 29 | +@app.route('/explore/<path:folder_path>') |
| 30 | +def explore_directory(folder_path): |
| 31 | + full_folder_path = os.path.join(local_directory, folder_path) |
| 32 | + contents = list_directory_contents(full_folder_path) |
| 33 | + return render_template('explorer.html', folder_path=folder_path, contents=contents) |
| 34 | + |
| 35 | +@app.route('/get_contents/<path:folder_path>') |
| 36 | +def get_contents(folder_path): |
| 37 | + full_folder_path = os.path.join(local_directory, folder_path) |
| 38 | + contents = list_directory_contents(full_folder_path) |
| 39 | + return jsonify(contents) |
| 40 | + |
| 41 | +def list_directory_contents(directory_path): |
| 42 | + try: |
| 43 | + contents = [] |
| 44 | + for item in os.listdir(directory_path): |
| 45 | + full_item_path = os.path.join(directory_path, item) |
| 46 | + is_directory = os.path.isdir(full_item_path) |
| 47 | + timestamp = get_timestamp(full_item_path) |
| 48 | + relative_path = os.path.relpath(full_item_path, local_directory) |
| 49 | + contents.append((relative_path, is_directory, timestamp)) |
| 50 | + return contents |
| 51 | + except Exception as e: |
| 52 | + return [str(e)] |
| 53 | + |
| 54 | +def get_timestamp(file_path): |
| 55 | + try: |
| 56 | + timestamp = os.path.getmtime(file_path) |
| 57 | + return timestamp |
| 58 | + except Exception as e: |
| 59 | + return None |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + app.run(host='0.0.0.0', port=3030) |
| 63 | + app.debug = True |
| 64 | + |
0 commit comments