view.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // HokoriTemp - JavaScript para la página de vista
  2. // DOM Elements
  3. const linksContainer = document.getElementById('linksContainer');
  4. const emptyState = document.getElementById('emptyState');
  5. const loadingState = document.getElementById('loadingState');
  6. const confirmModal = document.getElementById('confirmModal');
  7. const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
  8. const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
  9. // Variable para almacenar el ID del archivo a eliminar
  10. let fileToDelete = null;
  11. // Load links on page load
  12. document.addEventListener('DOMContentLoaded', loadLinks);
  13. // Event listeners para el modal
  14. confirmDeleteBtn.addEventListener('click', confirmDelete);
  15. cancelDeleteBtn.addEventListener('click', hideModal);
  16. // Cerrar modal al hacer clic fuera de él
  17. confirmModal.addEventListener('click', (e) => {
  18. if (e.target === confirmModal) {
  19. hideModal();
  20. }
  21. });
  22. // Cerrar modal con Escape
  23. document.addEventListener('keydown', (e) => {
  24. if (e.key === 'Escape' && !confirmModal.classList.contains('hidden')) {
  25. hideModal();
  26. }
  27. });
  28. async function loadLinks() {
  29. try {
  30. const response = await fetch('/api/links');
  31. if (!response.ok) {
  32. throw new Error(`HTTP error! status: ${response.status}`);
  33. }
  34. const links = await response.json();
  35. // Hide loading
  36. loadingState.classList.add('hidden');
  37. if (links.length === 0) {
  38. showEmptyState();
  39. } else {
  40. showLinks(links);
  41. }
  42. } catch (error) {
  43. console.error('Error cargando enlaces:', error);
  44. loadingState.classList.add('hidden');
  45. showError('Error al cargar los enlaces');
  46. }
  47. }
  48. function showEmptyState() {
  49. emptyState.classList.remove('hidden');
  50. }
  51. function showLinks(links) {
  52. const linksHTML = links.map(link => createLinkCard(link)).join('');
  53. linksContainer.innerHTML = linksHTML;
  54. }
  55. function createLinkCard(link) {
  56. const createdAt = new Date(link.created_at);
  57. const expiresAt = new Date(link.expires_at);
  58. const timeLeft = getTimeLeft(expiresAt);
  59. const isExpired = expiresAt <= new Date();
  60. const fileSize = formatFileSize(link.file_size);
  61. return `
  62. <div class="bg-white rounded-lg shadow-lg p-6 mb-4 ${isExpired ? 'opacity-50' : ''}">
  63. <div class="flex items-start justify-between">
  64. <div class="flex-1">
  65. <div class="flex items-center space-x-3">
  66. <svg class="h-8 w-8 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  67. <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>
  68. </svg>
  69. <div>
  70. <h3 class="text-lg font-medium text-gray-900">${link.filename}</h3>
  71. <p class="text-sm text-gray-500">Creado: ${formatDate(createdAt)} • ${fileSize} • ${link.download_count} descarga${link.download_count !== 1 ? 's' : ''}</p>
  72. </div>
  73. </div>
  74. <div class="mt-4">
  75. <div class="flex items-center space-x-2">
  76. <span class="text-sm text-gray-500">Enlace:</span>
  77. <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>
  78. <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">
  79. Copiar
  80. </button>
  81. </div>
  82. </div>
  83. <div class="mt-3 flex items-center justify-between">
  84. <div class="flex items-center space-x-4">
  85. <span class="text-sm text-gray-500">
  86. ${isExpired ? 'Expirado' : `Expira en: ${timeLeft}`}
  87. </span>
  88. ${isExpired ? '' : `
  89. <button onclick="openLink('${link.url}')" class="text-sm text-blue-600 hover:text-blue-800 underline">
  90. Abrir enlace
  91. </button>
  92. `}
  93. </div>
  94. <button onclick="showDeleteModal('${link.id}')" class="text-sm text-red-600 hover:text-red-800 underline">
  95. Eliminar
  96. </button>
  97. </div>
  98. </div>
  99. </div>
  100. </div>
  101. `;
  102. }
  103. function getTimeLeft(expiresAt) {
  104. const now = new Date();
  105. const diff = expiresAt - now;
  106. if (diff <= 0) return 'Expirado';
  107. const hours = Math.floor(diff / (1000 * 60 * 60));
  108. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  109. if (hours > 0) {
  110. return `${hours}h ${minutes}m`;
  111. } else {
  112. return `${minutes}m`;
  113. }
  114. }
  115. function formatDate(date) {
  116. return date.toLocaleString('es-ES', {
  117. year: 'numeric',
  118. month: 'short',
  119. day: 'numeric',
  120. hour: '2-digit',
  121. minute: '2-digit'
  122. });
  123. }
  124. function formatFileSize(bytes) {
  125. if (bytes === 0) return '0 Bytes';
  126. const k = 1024;
  127. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  128. const i = Math.floor(Math.log(bytes) / Math.log(k));
  129. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  130. }
  131. function copyLink(url) {
  132. navigator.clipboard.writeText(url).then(() => {
  133. // Show feedback
  134. const button = event.target;
  135. const originalText = button.textContent;
  136. button.textContent = '¡Copiado!';
  137. setTimeout(() => {
  138. button.textContent = originalText;
  139. }, 2000);
  140. // Show notification
  141. showNotification('Enlace copiado al portapapeles', 'success');
  142. }).catch(() => {
  143. // Fallback for older browsers
  144. const textArea = document.createElement('textarea');
  145. textArea.value = url;
  146. document.body.appendChild(textArea);
  147. textArea.select();
  148. document.execCommand('copy');
  149. document.body.removeChild(textArea);
  150. const button = event.target;
  151. const originalText = button.textContent;
  152. button.textContent = '¡Copiado!';
  153. setTimeout(() => {
  154. button.textContent = originalText;
  155. }, 2000);
  156. showNotification('Enlace copiado al portapapeles', 'success');
  157. });
  158. }
  159. function openLink(url) {
  160. window.open(url, '_blank');
  161. }
  162. function showDeleteModal(linkId) {
  163. fileToDelete = linkId;
  164. confirmModal.classList.remove('hidden');
  165. }
  166. function hideModal() {
  167. confirmModal.classList.add('hidden');
  168. fileToDelete = null;
  169. }
  170. async function confirmDelete() {
  171. if (!fileToDelete) return;
  172. try {
  173. const response = await fetch(`/api/delete/${fileToDelete}`, {
  174. method: 'DELETE'
  175. });
  176. if (!response.ok) {
  177. throw new Error(`HTTP error! status: ${response.status}`);
  178. }
  179. const result = await response.json();
  180. if (result.success) {
  181. showNotification('Archivo eliminado permanentemente', 'success');
  182. hideModal();
  183. // Recargar la página para actualizar la lista
  184. location.reload();
  185. } else {
  186. throw new Error(result.error || 'Error al eliminar el archivo');
  187. }
  188. } catch (error) {
  189. console.error('Error eliminando archivo:', error);
  190. showNotification('Error al eliminar el archivo', 'error');
  191. hideModal();
  192. }
  193. }
  194. // Función para mostrar notificaciones
  195. function showNotification(message, type = 'info') {
  196. // Crear elemento de notificación
  197. const notification = document.createElement('div');
  198. notification.className = `notification ${type}`;
  199. notification.textContent = message;
  200. // Agregar al DOM
  201. document.body.appendChild(notification);
  202. // Mostrar con animación
  203. setTimeout(() => {
  204. notification.classList.add('show');
  205. }, 100);
  206. // Ocultar después de 3 segundos
  207. setTimeout(() => {
  208. notification.classList.remove('show');
  209. setTimeout(() => {
  210. document.body.removeChild(notification);
  211. }, 300);
  212. }, 3000);
  213. }
  214. // Función para mostrar errores
  215. function showError(message) {
  216. showNotification(message, 'error');
  217. }
  218. // Auto-refresh every minute to update expiration times
  219. setInterval(() => {
  220. const links = document.querySelectorAll('[data-expires-at]');
  221. links.forEach(linkElement => {
  222. const expiresAt = new Date(linkElement.dataset.expiresAt);
  223. const timeLeftElement = linkElement.querySelector('.time-left');
  224. if (timeLeftElement) {
  225. timeLeftElement.textContent = getTimeLeft(expiresAt);
  226. }
  227. });
  228. }, 60000);