Add file viwer route

This commit is contained in:
Ana Custura 2026-02-17 13:52:59 +00:00
parent ebfd20da3f
commit 3829abaa03
17 changed files with 179 additions and 14 deletions

View file

@ -1,15 +1,11 @@
from email.mime import image
from alembic.util import obfuscate_url_pw
from app import app
from flask import render_template, flash, redirect, url_for, request, session
from flask import render_template, flash, redirect, url_for, request, session, send_file
from app.forms import LoginForm, SettingsForm
from flask_login import login_user, current_user, logout_user, login_required
import sqlalchemy as sa
from app import db
from app.models import User, Setting
from werkzeug.datastructures import FileStorage
import os
import json
from flask_babel import _
import base64
@ -17,18 +13,45 @@ import random
from wordfreq import top_n_list
import secrets
import string
import glob
import time
def gen_username():
def gen_username() -> str:
words = top_n_list("en", 5000)
prefix = random.randint(1000, 9999)
return f"{random.choice(words)}{random.choice(words)}{prefix}"
def gen_password():
def gen_password() -> str:
characters = string.ascii_letters + string.digits
password = ''.join(secrets.choice(characters) for i in range(20))
return password
def get_file_suffix(path: str) -> str:
return os.path.splitext(path)[1].strip('.') # in case of multiple exts, like .tar.gz, it only splits on the last one
def get_file_icon_url(path: str) -> str:
if os.path.isdir(path):
return url_for("static", filename=f"images/extension-icons/directory.svg")
suffix = get_file_suffix(path)
if suffix:
if suffix in ['apk', 'deb', 'dmg', 'exe', 'jpg', 'mp3', 'pbf', 'pdf', 'png',
'ppt', 'pptx']:
return url_for("static", filename=f"images/extension-icons/ext-{suffix}.svg")
return url_for("static", filename=f"images/extension-icons/ext-unknown.svg")
def get_files_in_path(path: str):
file_list = []
if os.path.exists(path):
list_of_files = glob.glob(path + "/*", recursive=True)
file_list = [
{"name": x.replace(path, "").strip("/"), "path": x, "is_file": os.path.isfile(x),
"is_dir": os.path.isdir(x),
"filetype": get_file_suffix(x), "last_modified": time.ctime(os.path.getmtime(x)),
"icon_url": get_file_icon_url(x),
"relative_path": x.replace(app.config["BUTTERBOX_USB_PATH"], "")} for x
in list_of_files]
print(file_list)
return file_list
def get_setting(name) -> str:
setting = db.session.scalar(sa.select(Setting).where(Setting.key == name))
@ -36,7 +59,6 @@ def get_setting(name) -> str:
def set_setting(name: str, value: str):
setting = db.session.scalar(sa.select(Setting).where(Setting.key == name))
print(f"I have changed {setting.key}")
setting.value = value
db.session.add(setting)
@ -56,6 +78,8 @@ def index():
enable_deltachat = get_setting("enable_deltachat")
service_array = []
usb_inserted = False # actual test of whether USB is inserted
if os.path.exists(app.config["BUTTERBOX_USB_PATH"]):
usb_inserted = True
usb_has_maps = False # actual test of whether USB has maps folder
usb_has_appstore = False # actual test of whether USB has an appstore
if enable_deltachat == 'true':
@ -73,12 +97,31 @@ def index():
service_array.append({
"name": name,
"image": url_for("static", filename="images/explore-icon.svg"),
"url": url_for("usb")})
"url": url_for("files", path=""),})
return render_template('index.html', title='Home', get_setting=get_setting, services=service_array)
@app.route('/usb')
def usb():
return render_template('usb-file-viewer.html', title='File Viewer')
@app.route('/files/', defaults={'path': ''})
@app.route('/files/<path:path>')
def files(path):
base_path = app.config["BUTTERBOX_USB_PATH"]
if not os.path.exists(base_path):
flash(_('No USB inserted.'))
current_path = os.path.join(base_path, path)
render_files = []
if os.path.exists(current_path):
render_files = get_files_in_path(current_path)
if not render_files:
flash(_('Empty directory.'))
else:
flash(_('Path does not exist.'))
return render_template('usb-file-viewer.html', title='File Viewer', current_path=current_path, render_files=render_files, get_setting=get_setting)
@app.route('/serve_file/<path:filepath>')
def serve_file(filepath):
full_path = os.path.realpath(filepath)
if not filepath.startswith(app.config["BUTTERBOX_USB_PATH"]):
redirect(url_for('files', path=""))
return send_file(full_path)
@app.route('/login', methods=['GET', 'POST'])
def login():
@ -159,7 +202,6 @@ def admin():
dump_settings("settings.txt")
flash(_("⚠️ Changes applied! Please wait for the box to restart."))
return render_template('admin.html', get_setting=get_setting, form=form)