main.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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, processing = 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. if (processing) {
  111. progressPercent.innerHTML = '<span class="flex items-center gap-1"><svg class="animate-spin h-4 w-4 inline mr-1" 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>Processing...</span>';
  112. } else {
  113. progressPercent.textContent = percent + '%';
  114. }
  115. if (isDone || processing) {
  116. uploadSpeed.textContent = '';
  117. timeRemaining.textContent = '';
  118. return;
  119. }
  120. const elapsed = (Date.now() - uploadStartTime) / 1000;
  121. const speed = loaded / elapsed;
  122. const speedMB = (speed / (1024 * 1024)).toFixed(2);
  123. uploadSpeed.textContent = `${speedMB} MB/s`;
  124. if (speed > 0) {
  125. const remaining = (total - loaded) / speed;
  126. const minutes = Math.floor(remaining / 60);
  127. const seconds = Math.floor(remaining % 60);
  128. timeRemaining.textContent = `${minutes}:${seconds.toString().padStart(2, '0')} remaining`;
  129. }
  130. }
  131. // Manejo de selección de archivo
  132. function handleFileSelection(file) {
  133. const fileInfo = document.getElementById('file-info');
  134. const fileName = document.getElementById('file-name');
  135. const fileSize = document.getElementById('file-size');
  136. const maxFileSizeMB = window.maxFileSizeMB || 16;
  137. if (file) {
  138. if (file.size > maxFileSizeMB * 1024 * 1024) {
  139. showToast(`File size exceeds the allowed limit (${maxFileSizeMB} MB)`, 'error');
  140. clearFileSelection();
  141. return;
  142. }
  143. fileName.textContent = file.name;
  144. fileName.classList.add('truncate');
  145. fileName.setAttribute('data-tooltip', file.name);
  146. fileSize.textContent = formatFileSize(file.size);
  147. fileInfo.classList.remove('hidden');
  148. } else {
  149. fileInfo.classList.add('hidden');
  150. }
  151. }
  152. function clearFileSelection() {
  153. const fileInput = document.getElementById('file-upload');
  154. const fileInfo = document.getElementById('file-info');
  155. fileInput.value = '';
  156. fileInfo.classList.add('hidden');
  157. }
  158. // Cargar archivos del usuario
  159. async function loadUserFiles() {
  160. const userSession = getUserSession();
  161. try {
  162. const response = await fetch(`/files/${userSession}`);
  163. const files = await response.json();
  164. const filesList = document.getElementById('filesList');
  165. const noFiles = document.getElementById('noFiles');
  166. if (files.length === 0) {
  167. filesList.innerHTML = '';
  168. noFiles.classList.remove('hidden');
  169. } else {
  170. noFiles.classList.add('hidden');
  171. filesList.innerHTML = files.map(file => `
  172. <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">
  173. <div class="flex items-center justify-between">
  174. <div class="flex-1">
  175. <div class="flex items-center space-x-3">
  176. <div class="flex-shrink-0">
  177. <svg class="w-8 h-8 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  178. <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>
  179. </svg>
  180. </div>
  181. <div class="flex-1 min-w-0">
  182. <p class="text-sm font-medium text-gray-900 dark:text-white truncate file-tooltip" data-tooltip="${file.original_filename}">${file.original_filename}</p>
  183. <p class="text-xs text-gray-500 dark:text-gray-400">${formatFileSize(file.file_size)} • Uploaded ${formatDate(file.upload_date)}</p>
  184. </div>
  185. </div>
  186. </div>
  187. <div class="flex items-center space-x-2">
  188. <div class="text-right">
  189. <p class="text-xs text-gray-500 dark:text-gray-400 file-remaining-time" data-expiration="${file.expiration_date}">${getTimeRemaining(file.expiration_date)}</p>
  190. </div>
  191. <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">
  192. Download
  193. </a>
  194. <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">
  195. Copy Link
  196. </button>
  197. <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">
  198. Delete
  199. </button>
  200. </div>
  201. </div>
  202. </div>
  203. `).join('');
  204. }
  205. document.querySelectorAll('.file-tooltip').forEach(el => {
  206. el.addEventListener('mouseenter', function(e) {
  207. showCustomTooltip(e.target, e.target.getAttribute('data-tooltip'));
  208. });
  209. el.addEventListener('mouseleave', hideCustomTooltip);
  210. });
  211. updateRemainingTimes();
  212. } catch (error) {
  213. showToast('Error loading files', 'error');
  214. }
  215. }
  216. // Variables para el modal de eliminación
  217. let fileIdToDelete = null;
  218. function openDeleteModal(fileId) {
  219. fileIdToDelete = fileId;
  220. document.getElementById('deleteModal').classList.remove('hidden');
  221. }
  222. function closeDeleteModal() {
  223. fileIdToDelete = null;
  224. document.getElementById('deleteModal').classList.add('hidden');
  225. }
  226. // Eliminar archivo (ahora solo ejecuta si se confirma en el modal)
  227. async function confirmDeleteFile() {
  228. if (!fileIdToDelete) return;
  229. const userSession = getUserSession();
  230. try {
  231. const response = await fetch(`/delete/${fileIdToDelete}`, {
  232. method: 'DELETE',
  233. headers: { 'Content-Type': 'application/json' },
  234. body: JSON.stringify({ user_session: userSession })
  235. });
  236. const result = await response.json();
  237. if (result.success) {
  238. showToast('File deleted successfully');
  239. loadUserFiles();
  240. } else {
  241. showToast(result.error || 'Error deleting file', 'error');
  242. }
  243. } catch (error) {
  244. showToast('Error deleting file: ' + error.message, 'error');
  245. } finally {
  246. closeDeleteModal();
  247. }
  248. }
  249. // Reemplazar deleteFile para abrir el modal
  250. window.deleteFile = openDeleteModal;
  251. // Eventos del modal
  252. function setupDeleteModalEvents() {
  253. document.getElementById('cancelDeleteBtn').addEventListener('click', closeDeleteModal);
  254. document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDeleteFile);
  255. // Cerrar modal con Escape
  256. document.addEventListener('keydown', function(e) {
  257. if (e.key === 'Escape') closeDeleteModal();
  258. });
  259. }
  260. // Inicialización de eventos
  261. function setupEventListeners() {
  262. // Tema
  263. document.getElementById('themeToggle').addEventListener('click', toggleTheme);
  264. // Selección de archivo
  265. document.getElementById('file-upload').addEventListener('change', function(e) {
  266. const file = e.target.files[0];
  267. handleFileSelection(file);
  268. });
  269. // Limpiar selección
  270. document.getElementById('clear-file').addEventListener('click', clearFileSelection);
  271. // Subida de archivo
  272. document.getElementById('uploadForm').addEventListener('submit', async function(e) {
  273. e.preventDefault();
  274. const fileInput = document.getElementById('file-upload');
  275. const file = fileInput.files[0];
  276. const duration = document.getElementById('duration').value;
  277. const uploadBtn = document.getElementById('uploadBtn');
  278. const uploadBtnText = document.getElementById('uploadBtnText');
  279. const uploadProgress = document.getElementById('uploadProgress');
  280. const progressBar = document.getElementById('progressBar');
  281. const progressPercent = document.getElementById('progressPercent');
  282. const maxFileSizeMB = window.maxFileSizeMB || 16;
  283. if (!file) {
  284. showToast('Please select a file', 'error');
  285. return;
  286. }
  287. if (file.size > maxFileSizeMB * 1024 * 1024) {
  288. showToast(`File size exceeds the allowed limit (${maxFileSizeMB} MB)`, 'error');
  289. clearFileSelection();
  290. return;
  291. }
  292. uploadBtn.disabled = true;
  293. uploadBtnText.textContent = 'Uploading...';
  294. uploadProgress.classList.remove('hidden');
  295. uploadStartTime = Date.now();
  296. uploadedBytes = 0;
  297. const formData = new FormData();
  298. formData.append('file', file);
  299. formData.append('user_session', getUserSession());
  300. formData.append('duration_hours', duration);
  301. // Barra de progreso manual con fetch
  302. let waitingTimeout, errorTimeout;
  303. try {
  304. // Simular barra de progreso basada en tamaño y tiempo estimado
  305. let loaded = 0;
  306. const total = file.size;
  307. const chunkSize = 1024 * 256; // 256KB
  308. let isProcessing = false;
  309. function simulateProgress() {
  310. if (isProcessing) return;
  311. if (loaded < total) {
  312. loaded = Math.min(loaded + chunkSize, total);
  313. updateProgress(loaded, total);
  314. setTimeout(simulateProgress, 30);
  315. } else {
  316. // Barra llena, mostrar processing
  317. updateProgress(total, total, false, true);
  318. isProcessing = true;
  319. }
  320. }
  321. simulateProgress();
  322. // Real upload
  323. const response = await fetch('/upload', {
  324. method: 'POST',
  325. body: formData
  326. });
  327. clearTimeout(waitingTimeout);
  328. clearTimeout(errorTimeout);
  329. document.getElementById('waitingServer')?.remove();
  330. if (response.ok) {
  331. const result = await response.json();
  332. if (result.success) {
  333. updateProgress(total, total, true, false);
  334. showToast('File uploaded successfully!');
  335. clearFileSelection();
  336. loadUserFiles();
  337. } else {
  338. showToast(result.error || 'Error uploading file', 'error');
  339. }
  340. } else {
  341. showToast('Error uploading file', 'error');
  342. }
  343. } catch (error) {
  344. showToast('Error uploading file: ' + error.message, 'error');
  345. } finally {
  346. uploadBtn.disabled = false;
  347. uploadBtnText.textContent = 'Upload File';
  348. uploadProgress.classList.add('hidden');
  349. }
  350. });
  351. // Refrescar lista
  352. document.getElementById('refreshBtn').addEventListener('click', loadUserFiles);
  353. }
  354. document.addEventListener('DOMContentLoaded', function() {
  355. initTheme();
  356. setupEventListeners();
  357. setupDeleteModalEvents();
  358. loadUserFiles();
  359. setInterval(updateRemainingTimes, 60000);
  360. });
  361. function updateRemainingTimes() {
  362. document.querySelectorAll('.file-remaining-time').forEach(el => {
  363. const expiration = el.getAttribute('data-expiration');
  364. el.textContent = getTimeRemaining(expiration);
  365. });
  366. }
  367. window.copyDownloadUrl = function(url) {
  368. navigator.clipboard.writeText(url).then(() => {
  369. showToast('Download link copied!');
  370. }, () => {
  371. showToast('Failed to copy link', 'error');
  372. });
  373. }