main.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // Gestión de tema (light/dark)
  2. function initTheme() {
  3. const savedTheme = localStorage.getItem('theme') || 'light';
  4. if (savedTheme === 'dark') {
  5. document.documentElement.classList.add('dark');
  6. } else {
  7. document.documentElement.classList.remove('dark');
  8. }
  9. }
  10. function toggleTheme() {
  11. const isDark = document.documentElement.classList.contains('dark');
  12. if (isDark) {
  13. document.documentElement.classList.remove('dark');
  14. localStorage.setItem('theme', 'light');
  15. } else {
  16. document.documentElement.classList.add('dark');
  17. localStorage.setItem('theme', 'dark');
  18. }
  19. }
  20. // Gestión de sesión de usuario
  21. function getUserSession() {
  22. let session = localStorage.getItem('userSession');
  23. if (!session) {
  24. session = 'user_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
  25. localStorage.setItem('userSession', session);
  26. }
  27. return session;
  28. }
  29. // Notificación tipo toast
  30. function showToast(message, type = 'success') {
  31. const toast = document.getElementById('toast');
  32. const toastMessage = document.getElementById('toastMessage');
  33. toastMessage.textContent = message;
  34. toast.classList.remove('bg-green-500', 'bg-red-500', 'bg-blue-500');
  35. if (type === 'success') {
  36. toast.classList.add('bg-green-500');
  37. } else if (type === 'error') {
  38. toast.classList.add('bg-red-500');
  39. } else if (type === 'info') {
  40. toast.classList.add('bg-blue-500');
  41. }
  42. toast.classList.remove('translate-x-full');
  43. setTimeout(() => {
  44. toast.classList.add('translate-x-full');
  45. }, 3000);
  46. }
  47. // Tooltip personalizado
  48. let tooltipTimeout;
  49. function showCustomTooltip(target, text) {
  50. let tooltip = document.getElementById('custom-tooltip');
  51. if (!tooltip) {
  52. tooltip = document.createElement('div');
  53. tooltip.id = 'custom-tooltip';
  54. tooltip.className = 'custom-tooltip';
  55. document.body.appendChild(tooltip);
  56. }
  57. tooltip.textContent = text;
  58. const rect = target.getBoundingClientRect();
  59. tooltip.style.top = (window.scrollY + rect.bottom + 4) + 'px';
  60. tooltip.style.left = (window.scrollX + rect.left) + 'px';
  61. tooltip.classList.add('visible');
  62. clearTimeout(tooltipTimeout);
  63. }
  64. function hideCustomTooltip() {
  65. const tooltip = document.getElementById('custom-tooltip');
  66. if (tooltip) {
  67. tooltip.classList.remove('visible');
  68. tooltipTimeout = setTimeout(() => {
  69. tooltip.remove();
  70. }, 200);
  71. }
  72. }
  73. // Formateo de tamaño de archivo
  74. function formatFileSize(bytes) {
  75. if (bytes === 0) return '0 Bytes';
  76. const k = 1024;
  77. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  78. const i = Math.floor(Math.log(bytes) / Math.log(k));
  79. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  80. }
  81. // Formateo de fecha
  82. function formatDate(dateString) {
  83. const date = new Date(dateString);
  84. return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
  85. }
  86. // Tiempo restante
  87. function getTimeRemaining(expirationDate) {
  88. const now = new Date();
  89. const expiry = new Date(expirationDate);
  90. const diff = expiry - now;
  91. if (diff <= 0) return 'Expired';
  92. const hours = Math.floor(diff / (1000 * 60 * 60));
  93. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  94. if (hours > 0) {
  95. return `${hours}h ${minutes}m remaining`;
  96. } else {
  97. return `${minutes}m remaining`;
  98. }
  99. }
  100. // Progreso de subida
  101. let uploadStartTime = 0;
  102. let uploadedBytes = 0;
  103. function updateProgress(loaded, total, isDone = false) {
  104. const percent = isDone ? 100 : Math.round((loaded / total) * 100);
  105. const progressBar = document.getElementById('progressBar');
  106. const progressPercent = document.getElementById('progressPercent');
  107. const uploadSpeed = document.getElementById('uploadSpeed');
  108. const timeRemaining = document.getElementById('timeRemaining');
  109. progressBar.style.width = percent + '%';
  110. progressPercent.textContent = percent + '%';
  111. if (isDone) {
  112. uploadSpeed.textContent = '';
  113. timeRemaining.textContent = '';
  114. return;
  115. }
  116. const elapsed = (Date.now() - uploadStartTime) / 1000;
  117. const speed = loaded / elapsed;
  118. const speedMB = (speed / (1024 * 1024)).toFixed(2);
  119. uploadSpeed.textContent = `${speedMB} MB/s`;
  120. if (speed > 0) {
  121. const remaining = (total - loaded) / speed;
  122. const minutes = Math.floor(remaining / 60);
  123. const seconds = Math.floor(remaining % 60);
  124. timeRemaining.textContent = `${minutes}:${seconds.toString().padStart(2, '0')} remaining`;
  125. }
  126. }
  127. // Manejo de selección de archivo
  128. function handleFileSelection(file) {
  129. const fileInfo = document.getElementById('file-info');
  130. const fileName = document.getElementById('file-name');
  131. const fileSize = document.getElementById('file-size');
  132. const maxFileSizeMB = window.maxFileSizeMB || 16;
  133. if (file) {
  134. if (file.size > maxFileSizeMB * 1024 * 1024) {
  135. showToast(`File size exceeds the allowed limit (${maxFileSizeMB} MB)`, 'error');
  136. clearFileSelection();
  137. return;
  138. }
  139. fileName.textContent = file.name;
  140. fileName.classList.add('truncate');
  141. fileName.setAttribute('data-tooltip', file.name);
  142. fileSize.textContent = formatFileSize(file.size);
  143. fileInfo.classList.remove('hidden');
  144. } else {
  145. fileInfo.classList.add('hidden');
  146. }
  147. }
  148. function clearFileSelection() {
  149. const fileInput = document.getElementById('file-upload');
  150. const fileInfo = document.getElementById('file-info');
  151. fileInput.value = '';
  152. fileInfo.classList.add('hidden');
  153. }
  154. // Cargar archivos del usuario
  155. async function loadUserFiles() {
  156. const userSession = getUserSession();
  157. try {
  158. const response = await fetch(`/files/${userSession}`);
  159. const files = await response.json();
  160. const filesList = document.getElementById('filesList');
  161. const noFiles = document.getElementById('noFiles');
  162. if (files.length === 0) {
  163. filesList.innerHTML = '';
  164. noFiles.classList.remove('hidden');
  165. } else {
  166. noFiles.classList.add('hidden');
  167. filesList.innerHTML = files.map(file => `
  168. <div class="border border-gray-200 dark:border-gray-600 rounded-lg p-4 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors animate-slide-up">
  169. <div class="flex items-center justify-between">
  170. <div class="flex-1">
  171. <div class="flex items-center space-x-3">
  172. <div class="flex-shrink-0">
  173. <svg class="w-8 h-8 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  174. <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>
  175. </svg>
  176. </div>
  177. <div class="flex-1 min-w-0">
  178. <p class="text-sm font-medium text-gray-900 dark:text-white truncate file-tooltip" data-tooltip="${file.original_filename}">${file.original_filename}</p>
  179. <p class="text-xs text-gray-500 dark:text-gray-400">${formatFileSize(file.file_size)} • Uploaded ${formatDate(file.upload_date)}</p>
  180. </div>
  181. </div>
  182. </div>
  183. <div class="flex items-center space-x-2">
  184. <div class="text-right">
  185. <p class="text-xs text-gray-500 dark:text-gray-400 file-remaining-time" data-expiration="${file.expiration_date}">${getTimeRemaining(file.expiration_date)}</p>
  186. </div>
  187. <a href="${file.download_url}" class="inline-flex items-center px-3 py-1 text-xs font-medium text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/30 hover:bg-blue-200 dark:hover:bg-blue-900/50 rounded-full transition-colors" target="_blank">
  188. Download
  189. </a>
  190. <button onclick="copyDownloadUrl('${file.download_url}')" class="inline-flex items-center px-3 py-1 text-xs font-medium text-gray-700 dark:text-gray-200 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-full transition-colors">
  191. Copy Link
  192. </button>
  193. <button onclick="deleteFile('${file.id}')" class="inline-flex items-center px-3 py-1 text-xs font-medium text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/30 hover:bg-red-200 dark:hover:bg-red-900/50 rounded-full transition-colors">
  194. Delete
  195. </button>
  196. </div>
  197. </div>
  198. </div>
  199. `).join('');
  200. }
  201. document.querySelectorAll('.file-tooltip').forEach(el => {
  202. el.addEventListener('mouseenter', function(e) {
  203. showCustomTooltip(e.target, e.target.getAttribute('data-tooltip'));
  204. });
  205. el.addEventListener('mouseleave', hideCustomTooltip);
  206. });
  207. updateRemainingTimes();
  208. } catch (error) {
  209. showToast('Error loading files', 'error');
  210. }
  211. }
  212. // Variables para el modal de eliminación
  213. let fileIdToDelete = null;
  214. function openDeleteModal(fileId) {
  215. fileIdToDelete = fileId;
  216. document.getElementById('deleteModal').classList.remove('hidden');
  217. }
  218. function closeDeleteModal() {
  219. fileIdToDelete = null;
  220. document.getElementById('deleteModal').classList.add('hidden');
  221. }
  222. // Eliminar archivo (ahora solo ejecuta si se confirma en el modal)
  223. async function confirmDeleteFile() {
  224. if (!fileIdToDelete) return;
  225. const userSession = getUserSession();
  226. try {
  227. const response = await fetch(`/delete/${fileIdToDelete}`, {
  228. method: 'DELETE',
  229. headers: { 'Content-Type': 'application/json' },
  230. body: JSON.stringify({ user_session: userSession })
  231. });
  232. const result = await response.json();
  233. if (result.success) {
  234. showToast('File deleted successfully');
  235. loadUserFiles();
  236. } else {
  237. showToast(result.error || 'Error deleting file', 'error');
  238. }
  239. } catch (error) {
  240. showToast('Error deleting file: ' + error.message, 'error');
  241. } finally {
  242. closeDeleteModal();
  243. }
  244. }
  245. // Reemplazar deleteFile para abrir el modal
  246. window.deleteFile = openDeleteModal;
  247. // Eventos del modal
  248. function setupDeleteModalEvents() {
  249. document.getElementById('cancelDeleteBtn').addEventListener('click', closeDeleteModal);
  250. document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDeleteFile);
  251. // Cerrar modal con Escape
  252. document.addEventListener('keydown', function(e) {
  253. if (e.key === 'Escape') closeDeleteModal();
  254. });
  255. }
  256. // Inicialización de eventos
  257. function setupEventListeners() {
  258. // Tema
  259. document.getElementById('themeToggle').addEventListener('click', toggleTheme);
  260. // Selección de archivo
  261. document.getElementById('file-upload').addEventListener('change', function(e) {
  262. const file = e.target.files[0];
  263. handleFileSelection(file);
  264. });
  265. // Limpiar selección
  266. document.getElementById('clear-file').addEventListener('click', clearFileSelection);
  267. // Subida de archivo
  268. document.getElementById('uploadForm').addEventListener('submit', async function(e) {
  269. e.preventDefault();
  270. const fileInput = document.getElementById('file-upload');
  271. const file = fileInput.files[0];
  272. const duration = document.getElementById('duration').value;
  273. const uploadBtn = document.getElementById('uploadBtn');
  274. const uploadBtnText = document.getElementById('uploadBtnText');
  275. const uploadProgress = document.getElementById('uploadProgress');
  276. const maxFileSizeMB = window.maxFileSizeMB || 16;
  277. if (!file) {
  278. showToast('Please select a file', 'error');
  279. return;
  280. }
  281. if (file.size > maxFileSizeMB * 1024 * 1024) {
  282. showToast(`File size exceeds the allowed limit (${maxFileSizeMB} MB)`, 'error');
  283. clearFileSelection();
  284. return;
  285. }
  286. uploadBtn.disabled = true;
  287. uploadBtnText.textContent = 'Uploading...';
  288. uploadProgress.classList.remove('hidden');
  289. uploadStartTime = Date.now();
  290. uploadedBytes = 0;
  291. const formData = new FormData();
  292. formData.append('file', file);
  293. formData.append('user_session', getUserSession());
  294. formData.append('duration_hours', duration);
  295. let waitingTimeout, errorTimeout;
  296. try {
  297. const xhr = new XMLHttpRequest();
  298. xhr.upload.addEventListener('progress', function(e) {
  299. if (e.lengthComputable) {
  300. updateProgress(e.loaded, e.total);
  301. }
  302. });
  303. xhr.addEventListener('load', function() {
  304. clearTimeout(waitingTimeout);
  305. clearTimeout(errorTimeout);
  306. updateProgress(file.size, file.size, true);
  307. document.getElementById('uploadSpeed').textContent = '';
  308. document.getElementById('timeRemaining').textContent = '';
  309. document.getElementById('waitingServer')?.remove();
  310. if (xhr.status === 200) {
  311. const result = JSON.parse(xhr.responseText);
  312. if (result.success) {
  313. showToast('File uploaded successfully!');
  314. clearFileSelection();
  315. loadUserFiles();
  316. } else {
  317. showToast(result.error || 'Error uploading file', 'error');
  318. }
  319. } else {
  320. showToast('Error uploading file', 'error');
  321. }
  322. });
  323. xhr.addEventListener('error', function() {
  324. clearTimeout(waitingTimeout);
  325. clearTimeout(errorTimeout);
  326. document.getElementById('waitingServer')?.remove();
  327. showToast('Network error while uploading', 'error');
  328. });
  329. xhr.upload.addEventListener('load', function() {
  330. // Barra llegó a 100%, pero aún esperando respuesta
  331. updateProgress(file.size, file.size, true);
  332. let waiting = document.getElementById('waitingServer');
  333. if (!waiting) {
  334. waiting = document.createElement('div');
  335. waiting.id = 'waitingServer';
  336. waiting.className = 'text-xs text-blue-600 dark:text-blue-400 mt-2 flex items-center gap-2';
  337. waiting.innerHTML = '<svg class="animate-spin h-4 w-4 mr-1 inline" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path></svg>Waiting for server confirmation...';
  338. uploadProgress.appendChild(waiting);
  339. }
  340. // Si pasan 60s tras barra 100%, mostrar advertencia
  341. waitingTimeout = setTimeout(() => {
  342. waiting.textContent = 'The upload is taking longer than expected. Please check your connection.';
  343. }, 60000);
  344. // Si pasan 2 minutos, mostrar error y permitir reintentar
  345. errorTimeout = setTimeout(() => {
  346. waiting.remove();
  347. showToast('Upload failed: server did not respond. Please try again.', 'error');
  348. uploadBtn.disabled = false;
  349. uploadBtnText.textContent = 'Upload File';
  350. uploadProgress.classList.add('hidden');
  351. }, 120000);
  352. });
  353. xhr.open('POST', '/upload');
  354. xhr.send(formData);
  355. } catch (error) {
  356. showToast('Error uploading file: ' + error.message, 'error');
  357. } finally {
  358. setTimeout(() => {
  359. uploadBtn.disabled = false;
  360. uploadBtnText.textContent = 'Upload File';
  361. uploadProgress.classList.add('hidden');
  362. }, 1000);
  363. }
  364. });
  365. // Refrescar lista
  366. document.getElementById('refreshBtn').addEventListener('click', loadUserFiles);
  367. }
  368. document.addEventListener('DOMContentLoaded', function() {
  369. initTheme();
  370. setupEventListeners();
  371. setupDeleteModalEvents();
  372. loadUserFiles();
  373. setInterval(updateRemainingTimes, 60000);
  374. });
  375. function updateRemainingTimes() {
  376. document.querySelectorAll('.file-remaining-time').forEach(el => {
  377. const expiration = el.getAttribute('data-expiration');
  378. el.textContent = getTimeRemaining(expiration);
  379. });
  380. }
  381. window.copyDownloadUrl = function(url) {
  382. navigator.clipboard.writeText(url).then(() => {
  383. showToast('Download link copied!');
  384. }, () => {
  385. showToast('Failed to copy link', 'error');
  386. });
  387. }