main.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/30 hover:bg-green-200 dark:hover:bg-green-900/50 rounded-full transition-colors" target="_blank">
  192. View
  193. </a>
  194. <a href="${file.download_url}/direct" 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">
  195. Download
  196. </a>
  197. <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">
  198. Copy Link
  199. </button>
  200. <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">
  201. Delete
  202. </button>
  203. </div>
  204. </div>
  205. </div>
  206. `).join('');
  207. }
  208. document.querySelectorAll('.file-tooltip').forEach(el => {
  209. el.addEventListener('mouseenter', function(e) {
  210. showCustomTooltip(e.target, e.target.getAttribute('data-tooltip'));
  211. });
  212. el.addEventListener('mouseleave', hideCustomTooltip);
  213. });
  214. updateRemainingTimes();
  215. } catch (error) {
  216. showToast('Error loading files', 'error');
  217. }
  218. }
  219. // Variables para el modal de eliminación
  220. let fileIdToDelete = null;
  221. function openDeleteModal(fileId) {
  222. fileIdToDelete = fileId;
  223. document.getElementById('deleteModal').classList.remove('hidden');
  224. }
  225. function closeDeleteModal() {
  226. fileIdToDelete = null;
  227. document.getElementById('deleteModal').classList.add('hidden');
  228. }
  229. // Eliminar archivo (ahora solo ejecuta si se confirma en el modal)
  230. async function confirmDeleteFile() {
  231. if (!fileIdToDelete) return;
  232. const userSession = getUserSession();
  233. try {
  234. const response = await fetch(`/delete/${fileIdToDelete}`, {
  235. method: 'DELETE',
  236. headers: { 'Content-Type': 'application/json' },
  237. body: JSON.stringify({ user_session: userSession })
  238. });
  239. const result = await response.json();
  240. if (result.success) {
  241. showToast('File deleted successfully');
  242. loadUserFiles();
  243. } else {
  244. showToast(result.error || 'Error deleting file', 'error');
  245. }
  246. } catch (error) {
  247. showToast('Error deleting file: ' + error.message, 'error');
  248. } finally {
  249. closeDeleteModal();
  250. }
  251. }
  252. // Reemplazar deleteFile para abrir el modal
  253. window.deleteFile = openDeleteModal;
  254. // Eventos del modal
  255. function setupDeleteModalEvents() {
  256. document.getElementById('cancelDeleteBtn').addEventListener('click', closeDeleteModal);
  257. document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDeleteFile);
  258. // Cerrar modal con Escape
  259. document.addEventListener('keydown', function(e) {
  260. if (e.key === 'Escape') closeDeleteModal();
  261. });
  262. }
  263. // Inicialización de eventos
  264. function setupEventListeners() {
  265. // Tema
  266. document.getElementById('themeToggle').addEventListener('click', toggleTheme);
  267. // Selección de archivo
  268. document.getElementById('file-upload').addEventListener('change', function(e) {
  269. const file = e.target.files[0];
  270. handleFileSelection(file);
  271. });
  272. // Limpiar selección
  273. document.getElementById('clear-file').addEventListener('click', clearFileSelection);
  274. // Subida de archivo
  275. document.getElementById('uploadForm').addEventListener('submit', async function(e) {
  276. e.preventDefault();
  277. const fileInput = document.getElementById('file-upload');
  278. const file = fileInput.files[0];
  279. const duration = document.getElementById('duration').value;
  280. const uploadBtn = document.getElementById('uploadBtn');
  281. const uploadBtnText = document.getElementById('uploadBtnText');
  282. const uploadProgress = document.getElementById('uploadProgress');
  283. const progressBar = document.getElementById('progressBar');
  284. const progressPercent = document.getElementById('progressPercent');
  285. const maxFileSizeMB = window.maxFileSizeMB || 16;
  286. if (!file) {
  287. showToast('Please select a file', 'error');
  288. return;
  289. }
  290. if (file.size > maxFileSizeMB * 1024 * 1024) {
  291. showToast(`File size exceeds the allowed limit (${maxFileSizeMB} MB)`, 'error');
  292. clearFileSelection();
  293. return;
  294. }
  295. uploadBtn.disabled = true;
  296. uploadBtnText.textContent = 'Uploading...';
  297. uploadProgress.classList.remove('hidden');
  298. uploadStartTime = Date.now();
  299. uploadedBytes = 0;
  300. const formData = new FormData();
  301. formData.append('file', file);
  302. formData.append('user_session', getUserSession());
  303. formData.append('duration_hours', duration);
  304. // Barra de progreso manual con fetch
  305. let waitingTimeout, errorTimeout;
  306. try {
  307. // Simular barra de progreso basada en tamaño y tiempo estimado
  308. let loaded = 0;
  309. const total = file.size;
  310. const chunkSize = 1024 * 256; // 256KB
  311. let isProcessing = false;
  312. function simulateProgress() {
  313. if (isProcessing) return;
  314. if (loaded < total) {
  315. loaded = Math.min(loaded + chunkSize, total);
  316. updateProgress(loaded, total);
  317. setTimeout(simulateProgress, 30);
  318. } else {
  319. // Barra llena, mostrar processing
  320. updateProgress(total, total, false, true);
  321. isProcessing = true;
  322. }
  323. }
  324. simulateProgress();
  325. // Real upload
  326. const response = await fetch('/upload', {
  327. method: 'POST',
  328. body: formData
  329. });
  330. clearTimeout(waitingTimeout);
  331. clearTimeout(errorTimeout);
  332. document.getElementById('waitingServer')?.remove();
  333. if (response.ok) {
  334. const result = await response.json();
  335. if (result.success) {
  336. updateProgress(total, total, true, false);
  337. showToast('File uploaded successfully!');
  338. clearFileSelection();
  339. loadUserFiles();
  340. } else {
  341. showToast(result.error || 'Error uploading file', 'error');
  342. }
  343. } else {
  344. showToast('Error uploading file', 'error');
  345. }
  346. } catch (error) {
  347. showToast('Error uploading file: ' + error.message, 'error');
  348. } finally {
  349. uploadBtn.disabled = false;
  350. uploadBtnText.textContent = 'Upload File';
  351. uploadProgress.classList.add('hidden');
  352. }
  353. });
  354. // Refrescar lista
  355. document.getElementById('refreshBtn').addEventListener('click', loadUserFiles);
  356. }
  357. document.addEventListener('DOMContentLoaded', function() {
  358. initTheme();
  359. setupEventListeners();
  360. setupDeleteModalEvents();
  361. loadUserFiles();
  362. setInterval(updateRemainingTimes, 60000);
  363. });
  364. function updateRemainingTimes() {
  365. document.querySelectorAll('.file-remaining-time').forEach(el => {
  366. const expiration = el.getAttribute('data-expiration');
  367. el.textContent = getTimeRemaining(expiration);
  368. });
  369. }
  370. window.copyDownloadUrl = function(url) {
  371. navigator.clipboard.writeText(url).then(() => {
  372. showToast('Download link copied!');
  373. }, () => {
  374. showToast('Failed to copy link', 'error');
  375. });
  376. }