adicionado dowloader do youtube e a opão'deploy' mover o arquivo para diretório final
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
from nicegui import ui
|
||||
from nicegui import ui, app
|
||||
import os
|
||||
import shutil
|
||||
import datetime
|
||||
import subprocess
|
||||
import json
|
||||
|
||||
ROOT_DIR = "/downloads"
|
||||
|
||||
@@ -22,6 +24,45 @@ def get_subfolders(root):
|
||||
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):
|
||||
@@ -52,10 +93,69 @@ class FileManager:
|
||||
self.render_header()
|
||||
self.render_content()
|
||||
|
||||
# --- DIÁLOGOS DE AÇÃO (ORDEM CORRIGIDA) ---
|
||||
# --- 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 permanentemente?').classes('text-lg font-bold')
|
||||
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')
|
||||
@@ -63,47 +163,42 @@ class FileManager:
|
||||
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()
|
||||
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').classes('text-lg')
|
||||
name_input = ui.input('Novo Nome', value=os.path.basename(path)).classes('w-full')
|
||||
ui.label('Renomear')
|
||||
name = 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')
|
||||
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).props('color=primary')
|
||||
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...').classes('text-lg')
|
||||
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)
|
||||
ui.notify('Movido!', type='positive')
|
||||
dialog.close()
|
||||
self.refresh()
|
||||
ui.notify('Movido!')
|
||||
except Exception as e: ui.notify(str(e), type='negative')
|
||||
ui.button('Mover', on_click=confirm).props('color=primary')
|
||||
ui.button('Mover', on_click=confirm)
|
||||
dialog.open()
|
||||
|
||||
def open_create_folder(self):
|
||||
@@ -113,25 +208,24 @@ class FileManager:
|
||||
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) ---
|
||||
# --- MENU DE CONTEXTO ---
|
||||
def bind_context_menu(self, element, entry):
|
||||
"""
|
||||
CORREÇÃO: Usa 'contextmenu.prevent' para bloquear o menu do navegador.
|
||||
"""
|
||||
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')
|
||||
|
||||
# Sintaxe correta do NiceGUI para prevenir default (Botão direito nativo)
|
||||
element.on('contextmenu.prevent', lambda: m.open())
|
||||
|
||||
# --- RENDERIZADORES ---
|
||||
@@ -142,10 +236,8 @@ class FileManager:
|
||||
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
|
||||
@@ -155,25 +247,19 @@ class FileManager:
|
||||
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='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:
|
||||
ui.label('Erro ao ler pasta').classes('text-red')
|
||||
return
|
||||
except: 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:
|
||||
@@ -184,33 +270,30 @@ class FileManager:
|
||||
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))
|
||||
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))
|
||||
|
||||
# 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')
|
||||
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 Para...', on_click=lambda p=entry.path: self.open_move_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')
|
||||
|
||||
# === 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'
|
||||
@@ -218,30 +301,26 @@ class FileManager:
|
||||
|
||||
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-[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')
|
||||
|
||||
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 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')
|
||||
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))
|
||||
|
||||
# --- INICIALIZADOR ---
|
||||
def create_ui():
|
||||
fm = FileManager()
|
||||
fm.container = ui.column().classes('w-full h-full p-2 md:p-4 gap-4')
|
||||
|
||||
Reference in New Issue
Block a user