248 lines
11 KiB
Python
Executable File
248 lines
11 KiB
Python
Executable File
from nicegui import ui
|
|
import os
|
|
import shutil
|
|
import datetime
|
|
|
|
ROOT_DIR = "/downloads"
|
|
|
|
# --- UTILITÁRIOS ---
|
|
def get_human_size(size):
|
|
for unit in ['B', 'KB', 'MB', 'GB']:
|
|
if size < 1024: return f"{size:.2f} {unit}"
|
|
size /= 1024
|
|
return f"{size:.2f} TB"
|
|
|
|
def get_subfolders(root):
|
|
folders = [root]
|
|
try:
|
|
for r, d, f in os.walk(root):
|
|
if "finalizados" in r or "temp" in r: continue
|
|
for folder in d:
|
|
if not folder.startswith('.'): folders.append(os.path.join(r, folder))
|
|
except: pass
|
|
return sorted(folders)
|
|
|
|
# --- CLASSE GERENCIADORA ---
|
|
class FileManager:
|
|
def __init__(self):
|
|
self.path = ROOT_DIR
|
|
self.view_mode = 'grid'
|
|
self.container = None
|
|
|
|
def navigate(self, path):
|
|
if os.path.exists(path) and os.path.isdir(path):
|
|
self.path = path
|
|
self.refresh()
|
|
else:
|
|
ui.notify('Caminho inválido', type='negative')
|
|
|
|
def navigate_up(self):
|
|
parent = os.path.dirname(self.path)
|
|
if self.path != ROOT_DIR:
|
|
self.navigate(parent)
|
|
|
|
def toggle_view(self):
|
|
self.view_mode = 'list' if self.view_mode == 'grid' else 'grid'
|
|
self.refresh()
|
|
|
|
def refresh(self):
|
|
if self.container:
|
|
self.container.clear()
|
|
with self.container:
|
|
self.render_header()
|
|
self.render_content()
|
|
|
|
# --- DIÁLOGOS DE AÇÃO (ORDEM CORRIGIDA) ---
|
|
def open_delete_dialog(self, path):
|
|
with ui.dialog() as dialog, ui.card():
|
|
ui.label('Excluir item permanentemente?').classes('text-lg font-bold')
|
|
ui.label(os.path.basename(path))
|
|
with ui.row().classes('w-full justify-end'):
|
|
ui.button('Cancelar', on_click=dialog.close).props('flat')
|
|
def confirm():
|
|
try:
|
|
if os.path.isdir(path): shutil.rmtree(path)
|
|
else: os.remove(path)
|
|
# 1. Notifica e Fecha ANTES de destruir a UI
|
|
ui.notify('Excluído!', type='positive')
|
|
dialog.close()
|
|
# 2. Atualiza a tela (Destrói elementos antigos)
|
|
self.refresh()
|
|
except Exception as e: ui.notify(str(e), type='negative')
|
|
ui.button('Excluir', on_click=confirm).props('color=red')
|
|
dialog.open()
|
|
|
|
def open_rename_dialog(self, path):
|
|
with ui.dialog() as dialog, ui.card():
|
|
ui.label('Renomear').classes('text-lg')
|
|
name_input = ui.input('Novo Nome', value=os.path.basename(path)).classes('w-full')
|
|
def save():
|
|
try:
|
|
new_path = os.path.join(os.path.dirname(path), name_input.value)
|
|
os.rename(path, new_path)
|
|
ui.notify('Renomeado!', type='positive')
|
|
dialog.close()
|
|
self.refresh()
|
|
except Exception as e: ui.notify(str(e), type='negative')
|
|
ui.button('Salvar', on_click=save).props('color=primary')
|
|
dialog.open()
|
|
|
|
def open_move_dialog(self, path):
|
|
folders = get_subfolders(ROOT_DIR)
|
|
if os.path.isdir(path) and path in folders: folders.remove(path)
|
|
|
|
opts = {f: f.replace(ROOT_DIR, "Raiz") if f != ROOT_DIR else "Raiz" for f in folders}
|
|
|
|
with ui.dialog() as dialog, ui.card().classes('w-96'):
|
|
ui.label('Mover Para...').classes('text-lg')
|
|
target = ui.select(opts, value=ROOT_DIR, with_input=True).classes('w-full')
|
|
def confirm():
|
|
try:
|
|
shutil.move(path, target.value)
|
|
ui.notify('Movido!', type='positive')
|
|
dialog.close()
|
|
self.refresh()
|
|
except Exception as e: ui.notify(str(e), type='negative')
|
|
ui.button('Mover', on_click=confirm).props('color=primary')
|
|
dialog.open()
|
|
|
|
def open_create_folder(self):
|
|
with ui.dialog() as dialog, ui.card():
|
|
ui.label('Nova Pasta')
|
|
name = ui.input('Nome')
|
|
def create():
|
|
try:
|
|
os.makedirs(os.path.join(self.path, name.value))
|
|
ui.notify('Pasta criada!', type='positive')
|
|
dialog.close()
|
|
self.refresh()
|
|
except Exception as e: ui.notify(str(e), type='negative')
|
|
ui.button('Criar', on_click=create)
|
|
dialog.open()
|
|
|
|
# --- MENU DE CONTEXTO (CORRIGIDO) ---
|
|
def bind_context_menu(self, element, entry):
|
|
"""
|
|
CORREÇÃO: Usa 'contextmenu.prevent' para bloquear o menu do navegador.
|
|
"""
|
|
with ui.menu() as m:
|
|
ui.menu_item('Renomear', on_click=lambda: self.open_rename_dialog(entry.path))
|
|
ui.menu_item('Mover Para...', on_click=lambda: self.open_move_dialog(entry.path))
|
|
ui.separator()
|
|
ui.menu_item('Excluir', on_click=lambda: self.open_delete_dialog(entry.path)).props('text-color=red')
|
|
|
|
# Sintaxe correta do NiceGUI para prevenir default (Botão direito nativo)
|
|
element.on('contextmenu.prevent', lambda: m.open())
|
|
|
|
# --- RENDERIZADORES ---
|
|
def render_header(self):
|
|
with ui.row().classes('w-full items-center bg-gray-100 p-2 rounded-lg gap-2'):
|
|
if self.path != ROOT_DIR:
|
|
ui.button(icon='arrow_upward', on_click=self.navigate_up).props('flat round dense').tooltip('Subir')
|
|
else:
|
|
ui.button(icon='home').props('flat round dense disabled text-color=grey')
|
|
|
|
# Breadcrumbs
|
|
rel = os.path.relpath(self.path, ROOT_DIR)
|
|
parts = rel.split(os.sep) if rel != '.' else []
|
|
|
|
with ui.row().classes('items-center gap-0'):
|
|
ui.button('/', on_click=lambda: self.navigate(ROOT_DIR)).props('flat dense no-caps min-w-0 px-2')
|
|
acc = ROOT_DIR
|
|
for part in parts:
|
|
acc = os.path.join(acc, part)
|
|
ui.label('/')
|
|
ui.button(part, on_click=lambda p=acc: self.navigate(p)).props('flat dense no-caps min-w-0 px-2')
|
|
|
|
ui.space()
|
|
ui.button(icon='create_new_folder', on_click=self.open_create_folder).props('flat round dense').tooltip('Nova Pasta')
|
|
|
|
icon_view = 'view_list' if self.view_mode == 'grid' else 'grid_view'
|
|
ui.button(icon=icon_view, on_click=self.toggle_view).props('flat round dense').tooltip('Mudar Visualização')
|
|
|
|
ui.button(icon='refresh', on_click=self.refresh).props('flat round dense')
|
|
|
|
def render_content(self):
|
|
try:
|
|
entries = sorted(os.scandir(self.path), key=lambda e: (not e.is_dir(), e.name.lower()))
|
|
except:
|
|
ui.label('Erro ao ler pasta').classes('text-red')
|
|
return
|
|
|
|
if not entries:
|
|
ui.label('Pasta vazia').classes('w-full text-center text-gray-400 mt-10')
|
|
return
|
|
|
|
# === GRID ===
|
|
if self.view_mode == 'grid':
|
|
with ui.grid().classes('w-full grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3'):
|
|
for entry in entries:
|
|
is_dir = entry.is_dir()
|
|
icon = 'folder' if is_dir else 'description'
|
|
if not is_dir and entry.name.lower().endswith(('.mkv', '.mp4', '.avi')): icon = 'movie'
|
|
color = 'amber-8' if is_dir else 'blue-grey'
|
|
if icon == 'movie': color = 'purple-6'
|
|
|
|
with ui.card().classes('w-full aspect-square p-2 items-center justify-center relative group hover:shadow-md cursor-pointer select-none') as card:
|
|
if is_dir: card.on('click', lambda p=entry.path: self.navigate(p))
|
|
|
|
# CORREÇÃO: Bind correto do menu de contexto
|
|
self.bind_context_menu(card, entry)
|
|
|
|
ui.icon(icon, size='3rem', color=color)
|
|
ui.label(entry.name).classes('text-xs text-center leading-tight line-clamp-2 w-full break-all')
|
|
|
|
if not is_dir:
|
|
ui.label(get_human_size(entry.stat().st_size)).classes('text-[10px] text-gray-400')
|
|
|
|
with ui.button(icon='more_vert').props('flat round dense size=sm').classes('absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity bg-white/90'):
|
|
with ui.menu():
|
|
ui.menu_item('Renomear', on_click=lambda p=entry.path: self.open_rename_dialog(p))
|
|
ui.menu_item('Mover Para...', on_click=lambda p=entry.path: self.open_move_dialog(p))
|
|
ui.separator()
|
|
ui.menu_item('Excluir', on_click=lambda p=entry.path: self.open_delete_dialog(p)).props('text-color=red')
|
|
|
|
# === LIST ===
|
|
else:
|
|
with ui.column().classes('w-full gap-0'):
|
|
with ui.row().classes('w-full px-2 py-1 bg-gray-100 text-xs font-bold text-gray-500 hidden sm:flex'):
|
|
ui.label('Nome').classes('flex-grow')
|
|
ui.label('Tamanho').classes('w-24 text-right')
|
|
ui.label('Data').classes('w-32 text-right')
|
|
ui.label('').classes('w-8')
|
|
|
|
for entry in entries:
|
|
is_dir = entry.is_dir()
|
|
icon = 'folder' if is_dir else 'description'
|
|
color = 'amber-8' if is_dir else 'blue-grey'
|
|
|
|
with ui.row().classes('w-full items-center px-2 py-2 border-b hover:bg-blue-50 cursor-pointer group') as row:
|
|
if is_dir: row.on('click', lambda p=entry.path: self.navigate(p))
|
|
|
|
self.bind_context_menu(row, entry)
|
|
|
|
ui.icon(icon, color=color).classes('mr-2')
|
|
|
|
with ui.column().classes('flex-grow gap-0'):
|
|
ui.label(entry.name).classes('text-sm font-medium break-all')
|
|
if not is_dir:
|
|
ui.label(get_human_size(entry.stat().st_size)).classes('text-[10px] text-gray-400 sm:hidden')
|
|
|
|
sz = "-" if is_dir else get_human_size(entry.stat().st_size)
|
|
ui.label(sz).classes('w-24 text-right text-xs text-gray-500 hidden sm:block')
|
|
|
|
dt = datetime.datetime.fromtimestamp(entry.stat().st_mtime).strftime('%d/%m/%Y')
|
|
ui.label(dt).classes('w-32 text-right text-xs text-gray-500 hidden sm:block')
|
|
|
|
with ui.button(icon='more_vert').props('flat round dense size=sm').classes('sm:opacity-0 group-hover:opacity-100'):
|
|
with ui.menu():
|
|
ui.menu_item('Renomear', on_click=lambda p=entry.path: self.open_rename_dialog(p))
|
|
ui.menu_item('Mover Para...', on_click=lambda p=entry.path: self.open_move_dialog(p))
|
|
ui.separator()
|
|
ui.menu_item('Excluir', on_click=lambda p=entry.path: self.open_delete_dialog(p)).props('text-color=red')
|
|
|
|
# --- INICIALIZADOR ---
|
|
def create_ui():
|
|
fm = FileManager()
|
|
fm.container = ui.column().classes('w-full h-full p-2 md:p-4 gap-4')
|
|
fm.refresh() |