app.js 10 KB

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