app.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // HokoriTemp - JavaScript principal
  2. let selectedFile = null;
  3. // Usar configuración del servidor si está disponible, sino usar valor por defecto
  4. const MAX_FILE_SIZE = (typeof SERVER_CONFIG !== 'undefined' && SERVER_CONFIG.maxFileSize)
  5. ? SERVER_CONFIG.maxFileSize
  6. : 16 * 1024 * 1024; // 16MB por defecto
  7. // DOM Elements
  8. const dropZone = document.getElementById('dropZone');
  9. const fileInput = document.getElementById('fileInput');
  10. const fileInfo = document.getElementById('fileInfo');
  11. const fileName = document.getElementById('fileName');
  12. const fileSize = document.getElementById('fileSize');
  13. const removeFile = document.getElementById('removeFile');
  14. const uploadForm = document.getElementById('uploadForm');
  15. const uploadBtn = document.getElementById('uploadBtn');
  16. const uploadBtnText = document.getElementById('uploadBtnText');
  17. const uploadBtnLoading = document.getElementById('uploadBtnLoading');
  18. const resultSection = document.getElementById('resultSection');
  19. const emptyResultSection = document.getElementById('emptyResultSection');
  20. const errorSection = document.getElementById('errorSection');
  21. const errorMessage = document.getElementById('errorMessage');
  22. const downloadLink = document.getElementById('downloadLink');
  23. // Event Listeners
  24. dropZone.addEventListener('click', () => fileInput.click());
  25. dropZone.addEventListener('dragover', handleDragOver);
  26. dropZone.addEventListener('dragleave', handleDragLeave);
  27. dropZone.addEventListener('drop', handleDrop);
  28. fileInput.addEventListener('change', handleFileSelect);
  29. removeFile.addEventListener('click', removeSelectedFile);
  30. uploadForm.addEventListener('submit', handleUpload);
  31. // Inicializar estado
  32. document.addEventListener('DOMContentLoaded', function() {
  33. // Mostrar el estado vacío del resultado al cargar
  34. emptyResultSection.classList.remove('hidden');
  35. emptyResultSection.classList.add('fade-in');
  36. });
  37. function handleDragOver(e) {
  38. e.preventDefault();
  39. dropZone.classList.add('dragover');
  40. }
  41. function handleDragLeave(e) {
  42. e.preventDefault();
  43. dropZone.classList.remove('dragover');
  44. }
  45. function handleDrop(e) {
  46. e.preventDefault();
  47. dropZone.classList.remove('dragover');
  48. const files = e.dataTransfer.files;
  49. if (files.length > 0) {
  50. handleFile(files[0]);
  51. }
  52. }
  53. function handleFileSelect(e) {
  54. const file = e.target.files[0];
  55. if (file) {
  56. handleFile(file);
  57. }
  58. }
  59. function handleFile(file) {
  60. // Validar tamaño del archivo
  61. if (file.size > MAX_FILE_SIZE) {
  62. showError(`El archivo es demasiado grande. Tamaño máximo: ${getMaxFileSizeMB()}MB`);
  63. return;
  64. }
  65. selectedFile = file;
  66. fileName.textContent = file.name;
  67. fileName.title = file.name; // Agregar título completo para tooltip
  68. fileSize.textContent = formatFileSize(file.size);
  69. // Aplicar clase de advertencia si el archivo es grande (>10MB)
  70. if (file.size > 10 * 1024 * 1024) {
  71. fileInfo.classList.add('file-size-warning');
  72. } else {
  73. fileInfo.classList.remove('file-size-warning');
  74. }
  75. fileInfo.classList.remove('hidden');
  76. uploadBtn.disabled = false;
  77. hideError();
  78. }
  79. function removeSelectedFile() {
  80. selectedFile = null;
  81. fileInput.value = '';
  82. fileInfo.classList.add('hidden');
  83. fileInfo.classList.remove('file-size-warning', 'file-size-error');
  84. uploadBtn.disabled = true;
  85. // Ocultar resultado si hay uno mostrado
  86. hideResult();
  87. }
  88. function formatFileSize(bytes) {
  89. if (bytes === 0) return '0 Bytes';
  90. const k = 1024;
  91. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  92. const i = Math.floor(Math.log(bytes) / Math.log(k));
  93. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  94. }
  95. async function handleUpload(e) {
  96. e.preventDefault();
  97. if (!selectedFile) {
  98. showError('Por favor selecciona un archivo');
  99. return;
  100. }
  101. // Validar tamaño del archivo antes de subir
  102. if (selectedFile.size > MAX_FILE_SIZE) {
  103. showError(`El archivo es demasiado grande. Tamaño máximo: ${getMaxFileSizeMB()}MB`);
  104. return;
  105. }
  106. // Show loading state
  107. uploadBtn.disabled = true;
  108. uploadBtnText.classList.add('hidden');
  109. uploadBtnLoading.classList.remove('hidden');
  110. hideError();
  111. hideResult();
  112. const formData = new FormData();
  113. formData.append('file', selectedFile);
  114. try {
  115. const response = await fetch('/upload', {
  116. method: 'POST',
  117. body: formData
  118. });
  119. // Verificar si la respuesta es JSON válido
  120. const contentType = response.headers.get('content-type');
  121. const isJson = contentType && contentType.includes('application/json');
  122. // Manejar diferentes códigos de respuesta
  123. if (response.status === 413) {
  124. showError(`El archivo es demasiado grande. Tamaño máximo: ${getMaxFileSizeMB()}MB`);
  125. return;
  126. }
  127. if (!response.ok) {
  128. let errorMessage = `Error del servidor (${response.status})`;
  129. if (isJson) {
  130. try {
  131. const errorData = await response.json();
  132. errorMessage = errorData.error || errorMessage;
  133. } catch (e) {
  134. console.error('Error parsing JSON response:', e);
  135. }
  136. } else {
  137. // Si no es JSON, intentar leer como texto
  138. try {
  139. const errorText = await response.text();
  140. console.error('Error response:', errorText);
  141. // Detectar errores específicos basados en el contenido
  142. if (errorText.includes('Request Entity Too Large') || errorText.includes('413')) {
  143. errorMessage = `El archivo es demasiado grande. Tamaño máximo: ${getMaxFileSizeMB()}MB`;
  144. } else if (errorText.includes('413')) {
  145. errorMessage = `El archivo es demasiado grande. Tamaño máximo: ${getMaxFileSizeMB()}MB`;
  146. } else {
  147. errorMessage = `Error del servidor: ${response.statusText}`;
  148. }
  149. } catch (e) {
  150. console.error('Error reading response text:', e);
  151. }
  152. }
  153. showError(errorMessage);
  154. return;
  155. }
  156. if (isJson) {
  157. const result = await response.json();
  158. if (result.success) {
  159. // Save to localStorage
  160. saveLinkToStorage(result);
  161. showResult(result.download_url);
  162. showNotification('Archivo subido exitosamente', 'success');
  163. } else {
  164. showError(result.error || 'Error al subir el archivo');
  165. }
  166. } else {
  167. showError('Respuesta inesperada del servidor');
  168. }
  169. } catch (error) {
  170. console.error('Upload error:', error);
  171. // Determinar el tipo de error
  172. if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
  173. showError('Error de conexión. Verifica tu conexión a internet e intenta de nuevo.');
  174. } else if (error.name === 'TypeError' && error.message.includes('JSON')) {
  175. showError('Error al procesar la respuesta del servidor.');
  176. } else {
  177. showError('Error inesperado. Intenta de nuevo.');
  178. }
  179. } finally {
  180. // Reset loading state
  181. uploadBtn.disabled = false;
  182. uploadBtnText.classList.remove('hidden');
  183. uploadBtnLoading.classList.add('hidden');
  184. }
  185. }
  186. function saveLinkToStorage(result) {
  187. const links = JSON.parse(localStorage.getItem('tempFileLinks') || '[]');
  188. const newLink = {
  189. id: result.file_id,
  190. url: result.download_url,
  191. filename: result.original_filename,
  192. expiresAt: result.expires_at,
  193. createdAt: new Date().toISOString()
  194. };
  195. links.push(newLink);
  196. localStorage.setItem('tempFileLinks', JSON.stringify(links));
  197. }
  198. function showResult(url) {
  199. downloadLink.value = url;
  200. resultSection.classList.remove('hidden');
  201. resultSection.classList.add('fade-in');
  202. emptyResultSection.classList.add('hidden');
  203. }
  204. function showError(message) {
  205. errorMessage.textContent = message;
  206. errorSection.classList.remove('hidden');
  207. showNotification(message, 'error');
  208. }
  209. function hideError() {
  210. errorSection.classList.add('hidden');
  211. }
  212. function hideResult() {
  213. resultSection.classList.add('hidden');
  214. resultSection.classList.remove('fade-in');
  215. emptyResultSection.classList.remove('hidden');
  216. emptyResultSection.classList.add('fade-in');
  217. }
  218. function copyLink() {
  219. downloadLink.select();
  220. document.execCommand('copy');
  221. // Show feedback
  222. const copyBtn = event.target;
  223. const originalText = copyBtn.textContent;
  224. copyBtn.textContent = '¡Copiado!';
  225. setTimeout(() => {
  226. copyBtn.textContent = originalText;
  227. }, 2000);
  228. showNotification('Enlace copiado al portapapeles', 'success');
  229. }
  230. function openLink() {
  231. window.open(downloadLink.value, '_blank');
  232. }
  233. function resetForm() {
  234. removeSelectedFile();
  235. hideResult();
  236. hideError();
  237. // Mostrar el estado vacío del resultado
  238. emptyResultSection.classList.remove('hidden');
  239. }
  240. // Función para mostrar notificaciones
  241. function showNotification(message, type = 'info') {
  242. // Crear elemento de notificación
  243. const notification = document.createElement('div');
  244. notification.className = `notification ${type}`;
  245. notification.textContent = message;
  246. // Agregar al DOM
  247. document.body.appendChild(notification);
  248. // Mostrar con animación
  249. setTimeout(() => {
  250. notification.classList.add('show');
  251. }, 100);
  252. // Ocultar después de 3 segundos
  253. setTimeout(() => {
  254. notification.classList.remove('show');
  255. setTimeout(() => {
  256. document.body.removeChild(notification);
  257. }, 300);
  258. }, 3000);
  259. }
  260. // Función helper para obtener el tamaño máximo en MB
  261. function getMaxFileSizeMB() {
  262. return (typeof SERVER_CONFIG !== 'undefined' && SERVER_CONFIG.maxFileSizeMB)
  263. ? SERVER_CONFIG.maxFileSizeMB
  264. : MAX_FILE_SIZE / (1024 * 1024);
  265. }
  266. // Función para validar archivo antes de subir
  267. function validateFile(file) {
  268. const maxSize = MAX_FILE_SIZE;
  269. const maxSizeMB = getMaxFileSizeMB();
  270. if (file.size > maxSize) {
  271. return {
  272. valid: false,
  273. message: `El archivo es demasiado grande. Tamaño máximo: ${maxSizeMB}MB`
  274. };
  275. }
  276. return { valid: true };
  277. }