327 lines
15 KiB
Python
Executable File
327 lines
15 KiB
Python
Executable File
from nicegui import ui, app
|
|
import os
|
|
import shutil
|
|
import datetime
|
|
import subprocess
|
|
import json
|
|
|
|
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)
|
|
|
|
# --- LEITOR DE METADADOS (FFPROBE) ---
|
|
def get_media_info(filepath):
|
|
"""Lê as faixas de áudio e legenda do arquivo"""
|
|
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-show_format", filepath]
|
|
try:
|
|
res = subprocess.run(cmd, capture_output=True, text=True)
|
|
data = json.loads(res.stdout)
|
|
|
|
info = {
|
|
"duration": float(data['format'].get('duration', 0)),
|
|
"bitrate": int(data['format'].get('bit_rate', 0)),
|
|
"video": [],
|
|
"audio": [],
|
|
"subtitle": []
|
|
}
|
|
|
|
for s in data.get('streams', []):
|
|
type = s['codec_type']
|
|
lang = s.get('tags', {}).get('language', 'und')
|
|
title = s.get('tags', {}).get('title', '')
|
|
codec = s.get('codec_name', 'unknown')
|
|
|
|
desc = f"[{lang.upper()}] {codec}"
|
|
if title: desc += f" - {title}"
|
|
|
|
if type == 'video':
|
|
w = s.get('width', 0)
|
|
h = s.get('height', 0)
|
|
info['video'].append(f"{codec.upper()} ({w}x{h})")
|
|
elif type == 'audio':
|
|
ch = s.get('channels', 0)
|
|
info['audio'].append(f"{desc} ({ch}ch)")
|
|
elif type == 'subtitle':
|
|
info['subtitle'].append(desc)
|
|
|
|
return info
|
|
except:
|
|
return None
|
|
|
|
# --- 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()
|
|
|
|
# --- PLAYER DE VÍDEO ---
|
|
def open_player(self, path):
|
|
filename = os.path.basename(path)
|
|
|
|
# Converte caminho local (/downloads/pasta/video.mkv) para URL (/files/pasta/video.mkv)
|
|
# O prefixo /files foi configurado no main.py
|
|
rel_path = os.path.relpath(path, ROOT_DIR)
|
|
video_url = f"/files/{rel_path}"
|
|
|
|
# Pega dados técnicos
|
|
info = get_media_info(path)
|
|
|
|
with ui.dialog() as dialog, ui.card().classes('w-full max-w-4xl h-[80vh] p-0 gap-0'):
|
|
# Header
|
|
with ui.row().classes('w-full bg-gray-100 p-2 justify-between items-center'):
|
|
ui.label(filename).classes('font-bold text-lg truncate')
|
|
ui.button(icon='close', on_click=dialog.close).props('flat round dense')
|
|
|
|
with ui.row().classes('w-full h-full'):
|
|
# Coluna Esquerda: Player
|
|
with ui.column().classes('w-2/3 h-full bg-black justify-center'):
|
|
# Player HTML5 Nativo
|
|
ui.video(video_url).classes('w-full max-h-full')
|
|
ui.label('Nota: Áudios AC3/DTS podem ficar mudos no navegador.').classes('text-gray-500 text-xs text-center w-full')
|
|
|
|
# Coluna Direita: Informações
|
|
with ui.column().classes('w-1/3 h-full p-4 overflow-y-auto bg-white border-l'):
|
|
ui.label('📋 Detalhes do Arquivo').classes('text-lg font-bold mb-4 text-blue-600')
|
|
|
|
if info:
|
|
# Vídeo
|
|
ui.label('Vídeo').classes('font-bold text-xs text-gray-500 uppercase')
|
|
for v in info['video']:
|
|
ui.label(f"📺 {v}").classes('ml-2 text-sm')
|
|
|
|
ui.separator().classes('my-2')
|
|
|
|
# Áudio
|
|
ui.label('Áudio').classes('font-bold text-xs text-gray-500 uppercase')
|
|
if info['audio']:
|
|
for a in info['audio']:
|
|
ui.label(f"🔊 {a}").classes('ml-2 text-sm')
|
|
else:
|
|
ui.label("Sem áudio").classes('ml-2 text-sm text-gray-400')
|
|
|
|
ui.separator().classes('my-2')
|
|
|
|
# Legenda
|
|
ui.label('Legendas').classes('font-bold text-xs text-gray-500 uppercase')
|
|
if info['subtitle']:
|
|
for s in info['subtitle']:
|
|
ui.label(f"💬 {s}").classes('ml-2 text-sm')
|
|
else:
|
|
ui.label("Sem legendas").classes('ml-2 text-sm text-gray-400')
|
|
else:
|
|
ui.label('Não foi possível ler os metadados.').classes('text-red')
|
|
|
|
dialog.open()
|
|
|
|
# --- DIÁLOGOS DE AÇÃO ---
|
|
def open_delete_dialog(self, path):
|
|
with ui.dialog() as dialog, ui.card():
|
|
ui.label('Excluir item?').classes('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)
|
|
dialog.close()
|
|
self.refresh()
|
|
ui.notify('Excluído!')
|
|
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')
|
|
name = ui.input('Novo Nome', value=os.path.basename(path)).classes('w-full')
|
|
def save():
|
|
try:
|
|
os.rename(path, os.path.join(os.path.dirname(path), name.value))
|
|
dialog.close()
|
|
self.refresh()
|
|
ui.notify('Renomeado!')
|
|
except Exception as e: ui.notify(str(e), type='negative')
|
|
ui.button('Salvar', on_click=save)
|
|
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')
|
|
target = ui.select(opts, value=ROOT_DIR, with_input=True).classes('w-full')
|
|
def confirm():
|
|
try:
|
|
shutil.move(path, target.value)
|
|
dialog.close()
|
|
self.refresh()
|
|
ui.notify('Movido!')
|
|
except Exception as e: ui.notify(str(e), type='negative')
|
|
ui.button('Mover', on_click=confirm)
|
|
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))
|
|
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 ---
|
|
def bind_context_menu(self, element, entry):
|
|
with ui.menu() as m:
|
|
if not entry.is_dir and entry.name.lower().endswith(('.mkv', '.mp4', '.avi')):
|
|
ui.menu_item('▶️ Reproduzir / Detalhes', on_click=lambda: self.open_player(entry.path))
|
|
ui.separator()
|
|
|
|
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')
|
|
|
|
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')
|
|
|
|
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')
|
|
ui.button(icon='view_list' if self.view_mode == 'grid' else 'grid_view', on_click=self.toggle_view).props('flat round dense')
|
|
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: return
|
|
|
|
if not entries:
|
|
ui.label('Pasta vazia').classes('w-full text-center text-gray-400 mt-10')
|
|
return
|
|
|
|
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))
|
|
elif icon == 'movie':
|
|
# Duplo clique no vídeo abre o player
|
|
card.on('dblclick', lambda p=entry.path: self.open_player(p))
|
|
|
|
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():
|
|
if icon == 'movie':
|
|
ui.menu_item('▶️ Play', on_click=lambda p=entry.path: self.open_player(p))
|
|
ui.separator()
|
|
ui.menu_item('Renomear', on_click=lambda p=entry.path: self.open_rename_dialog(p))
|
|
ui.menu_item('Mover', 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')
|
|
|
|
else:
|
|
with ui.column().classes('w-full gap-0'):
|
|
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))
|
|
elif entry.name.lower().endswith(('.mkv', '.mp4')):
|
|
row.on('dblclick', lambda p=entry.path: self.open_player(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-xs text-gray-500 mr-4')
|
|
|
|
with ui.button(icon='more_vert').props('flat round dense size=sm').classes('sm:opacity-0 group-hover:opacity-100'):
|
|
with ui.menu():
|
|
if not is_dir:
|
|
ui.menu_item('▶️ Play', on_click=lambda p=entry.path: self.open_player(p))
|
|
ui.menu_item('Renomear', on_click=lambda p=entry.path: self.open_rename_dialog(p))
|
|
ui.menu_item('Mover', on_click=lambda p=entry.path: self.open_move_dialog(p))
|
|
ui.menu_item('Excluir', on_click=lambda p=entry.path: self.open_delete_dialog(p))
|
|
|
|
def create_ui():
|
|
fm = FileManager()
|
|
fm.container = ui.column().classes('w-full h-full p-2 md:p-4 gap-4')
|
|
fm.refresh() |