main.js 14 KB

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