| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268 |
- // HokoriTemp - JavaScript para la página de vista
- // DOM Elements
- const linksContainer = document.getElementById('linksContainer');
- const emptyState = document.getElementById('emptyState');
- const loadingState = document.getElementById('loadingState');
- const confirmModal = document.getElementById('confirmModal');
- const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
- const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
- // Variable para almacenar el ID del archivo a eliminar
- let fileToDelete = null;
- // Load links on page load
- document.addEventListener('DOMContentLoaded', loadLinks);
- // Event listeners para el modal
- confirmDeleteBtn.addEventListener('click', confirmDelete);
- cancelDeleteBtn.addEventListener('click', hideModal);
- // Cerrar modal al hacer clic fuera de él
- confirmModal.addEventListener('click', (e) => {
- if (e.target === confirmModal) {
- hideModal();
- }
- });
- // Cerrar modal con Escape
- document.addEventListener('keydown', (e) => {
- if (e.key === 'Escape' && !confirmModal.classList.contains('hidden')) {
- hideModal();
- }
- });
- async function loadLinks() {
- try {
- const response = await fetch('/api/links');
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- const links = await response.json();
-
- // Hide loading
- loadingState.classList.add('hidden');
- if (links.length === 0) {
- showEmptyState();
- } else {
- showLinks(links);
- }
- } catch (error) {
- console.error('Error cargando enlaces:', error);
- loadingState.classList.add('hidden');
- showError('Error al cargar los enlaces');
- }
- }
- function showEmptyState() {
- emptyState.classList.remove('hidden');
- }
- function showLinks(links) {
- const linksHTML = links.map(link => createLinkCard(link)).join('');
- linksContainer.innerHTML = linksHTML;
- }
- function createLinkCard(link) {
- const createdAt = new Date(link.created_at);
- const expiresAt = new Date(link.expires_at);
- const timeLeft = getTimeLeft(expiresAt);
- const isExpired = expiresAt <= new Date();
- const fileSize = formatFileSize(link.file_size);
- return `
- <div class="bg-white rounded-lg shadow-lg p-6 mb-4 ${isExpired ? 'opacity-50' : ''}">
- <div class="flex items-start justify-between">
- <div class="flex-1">
- <div class="flex items-center space-x-3">
- <svg class="h-8 w-8 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
- </svg>
- <div>
- <h3 class="text-lg font-medium text-gray-900">${link.filename}</h3>
- <p class="text-sm text-gray-500">Creado: ${formatDate(createdAt)} • ${fileSize} • ${link.download_count} descarga${link.download_count !== 1 ? 's' : ''}</p>
- </div>
- </div>
-
- <div class="mt-4">
- <div class="flex items-center space-x-2">
- <span class="text-sm text-gray-500">Enlace:</span>
- <input type="text" value="${link.url}" class="flex-1 px-3 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" readonly>
- <button onclick="copyLink('${link.url}')" class="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
- Copiar
- </button>
- </div>
- </div>
- <div class="mt-3 flex items-center justify-between">
- <div class="flex items-center space-x-4">
- <span class="text-sm text-gray-500">
- ${isExpired ? 'Expirado' : `Expira en: ${timeLeft}`}
- </span>
- ${isExpired ? '' : `
- <button onclick="openLink('${link.url}')" class="text-sm text-blue-600 hover:text-blue-800 underline">
- Abrir enlace
- </button>
- `}
- </div>
- <button onclick="showDeleteModal('${link.id}')" class="text-sm text-red-600 hover:text-red-800 underline">
- Eliminar
- </button>
- </div>
- </div>
- </div>
- </div>
- `;
- }
- function getTimeLeft(expiresAt) {
- const now = new Date();
- const diff = expiresAt - now;
-
- if (diff <= 0) return 'Expirado';
-
- const hours = Math.floor(diff / (1000 * 60 * 60));
- const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
-
- if (hours > 0) {
- return `${hours}h ${minutes}m`;
- } else {
- return `${minutes}m`;
- }
- }
- function formatDate(date) {
- return date.toLocaleString('es-ES', {
- year: 'numeric',
- month: 'short',
- day: 'numeric',
- hour: '2-digit',
- minute: '2-digit'
- });
- }
- function formatFileSize(bytes) {
- if (bytes === 0) return '0 Bytes';
- const k = 1024;
- const sizes = ['Bytes', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
- }
- function copyLink(url) {
- navigator.clipboard.writeText(url).then(() => {
- // Show feedback
- const button = event.target;
- const originalText = button.textContent;
- button.textContent = '¡Copiado!';
- setTimeout(() => {
- button.textContent = originalText;
- }, 2000);
-
- // Show notification
- showNotification('Enlace copiado al portapapeles', 'success');
- }).catch(() => {
- // Fallback for older browsers
- const textArea = document.createElement('textarea');
- textArea.value = url;
- document.body.appendChild(textArea);
- textArea.select();
- document.execCommand('copy');
- document.body.removeChild(textArea);
-
- const button = event.target;
- const originalText = button.textContent;
- button.textContent = '¡Copiado!';
- setTimeout(() => {
- button.textContent = originalText;
- }, 2000);
-
- showNotification('Enlace copiado al portapapeles', 'success');
- });
- }
- function openLink(url) {
- window.open(url, '_blank');
- }
- function showDeleteModal(linkId) {
- fileToDelete = linkId;
- confirmModal.classList.remove('hidden');
- }
- function hideModal() {
- confirmModal.classList.add('hidden');
- fileToDelete = null;
- }
- async function confirmDelete() {
- if (!fileToDelete) return;
-
- try {
- const response = await fetch(`/api/delete/${fileToDelete}`, {
- method: 'DELETE'
- });
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- const result = await response.json();
-
- if (result.success) {
- showNotification('Archivo eliminado permanentemente', 'success');
- hideModal();
- // Recargar la página para actualizar la lista
- location.reload();
- } else {
- throw new Error(result.error || 'Error al eliminar el archivo');
- }
- } catch (error) {
- console.error('Error eliminando archivo:', error);
- showNotification('Error al eliminar el archivo', 'error');
- hideModal();
- }
- }
- // Función para mostrar notificaciones
- function showNotification(message, type = 'info') {
- // Crear elemento de notificación
- const notification = document.createElement('div');
- notification.className = `notification ${type}`;
- notification.textContent = message;
-
- // Agregar al DOM
- document.body.appendChild(notification);
-
- // Mostrar con animación
- setTimeout(() => {
- notification.classList.add('show');
- }, 100);
-
- // Ocultar después de 3 segundos
- setTimeout(() => {
- notification.classList.remove('show');
- setTimeout(() => {
- document.body.removeChild(notification);
- }, 300);
- }, 3000);
- }
- // Función para mostrar errores
- function showError(message) {
- showNotification(message, 'error');
- }
- // Auto-refresh every minute to update expiration times
- setInterval(() => {
- const links = document.querySelectorAll('[data-expires-at]');
- links.forEach(linkElement => {
- const expiresAt = new Date(linkElement.dataset.expiresAt);
- const timeLeftElement = linkElement.querySelector('.time-left');
- if (timeLeftElement) {
- timeLeftElement.textContent = getTimeLeft(expiresAt);
- }
- });
- }, 60000);
|