codebybrody commited on
Commit
48902b8
·
verified ·
1 Parent(s): 3b63be1

Upload 79 files

Browse files
README.md CHANGED
@@ -1,10 +1,10 @@
1
- ---
2
- title: Twisted brody mangaflow
3
- emoji: 🏢
4
- colorFrom: pink
5
- colorTo: blue
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Twisted brody mangaflow
3
+ emoji: 🏢
4
+ colorFrom: pink
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
check_db.ts CHANGED
@@ -1,44 +1,44 @@
1
- import { initializeApp } from 'firebase/app';
2
- import { getFirestore, collection, getDocs, query, orderBy, limit } from 'firebase/firestore';
3
-
4
- const firebaseConfig = {
5
- apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
6
- authDomain: "twistedbrody-9d163.firebaseapp.com",
7
- projectId: "twistedbrody-9d163",
8
- storageBucket: "twistedbrody-9d163.firebasestorage.app",
9
- messagingSenderId: "733213514129",
10
- appId: "1:733213514129:web:e9694684f5c3994ed06230",
11
- measurementId: "G-N8TQ7MY42W"
12
- };
13
-
14
- const app = initializeApp(firebaseConfig);
15
- const db = getFirestore(app);
16
-
17
- async function check() {
18
- console.log("Fetching mangas from DB...");
19
- const q = query(collection(db, 'mangas'), orderBy('created_at', 'desc'), limit(3));
20
- const snap = await getDocs(q);
21
-
22
- if (snap.empty) {
23
- console.log("NO MANGAS IN DB!");
24
- } else {
25
- snap.forEach(doc => {
26
- console.log(`Manga ${doc.id}: ${doc.data().title}`);
27
- console.log(JSON.stringify(doc.data(), null, 2));
28
- });
29
- }
30
-
31
- console.log("\nFetching chapters...");
32
- const q2 = query(collection(db, 'chapters'), orderBy('created_at', 'desc'), limit(3));
33
- const snap2 = await getDocs(q2);
34
- if (snap2.empty) {
35
- console.log("NO CHAPTERS IN DB!");
36
- } else {
37
- snap2.forEach(doc => {
38
- console.log(`Chapter ${doc.id}: ${doc.data().title}`);
39
- console.log(JSON.stringify(doc.data(), null, 2));
40
- });
41
- }
42
- }
43
-
44
- check().catch(console.error).finally(() => process.exit(0));
 
1
+ import { initializeApp } from 'firebase/app';
2
+ import { getFirestore, collection, getDocs, query, orderBy, limit } from 'firebase/firestore';
3
+
4
+ const firebaseConfig = {
5
+ apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
6
+ authDomain: "twistedbrody-9d163.firebaseapp.com",
7
+ projectId: "twistedbrody-9d163",
8
+ storageBucket: "twistedbrody-9d163.firebasestorage.app",
9
+ messagingSenderId: "733213514129",
10
+ appId: "1:733213514129:web:e9694684f5c3994ed06230",
11
+ measurementId: "G-N8TQ7MY42W"
12
+ };
13
+
14
+ const app = initializeApp(firebaseConfig);
15
+ const db = getFirestore(app);
16
+
17
+ async function check() {
18
+ console.log("Fetching mangas from DB...");
19
+ const q = query(collection(db, 'mangas'), orderBy('created_at', 'desc'), limit(3));
20
+ const snap = await getDocs(q);
21
+
22
+ if (snap.empty) {
23
+ console.log("NO MANGAS IN DB!");
24
+ } else {
25
+ snap.forEach(doc => {
26
+ console.log(`Manga ${doc.id}: ${doc.data().title}`);
27
+ console.log(JSON.stringify(doc.data(), null, 2));
28
+ });
29
+ }
30
+
31
+ console.log("\nFetching chapters...");
32
+ const q2 = query(collection(db, 'chapters'), orderBy('created_at', 'desc'), limit(3));
33
+ const snap2 = await getDocs(q2);
34
+ if (snap2.empty) {
35
+ console.log("NO CHAPTERS IN DB!");
36
+ } else {
37
+ snap2.forEach(doc => {
38
+ console.log(`Chapter ${doc.id}: ${doc.data().title}`);
39
+ console.log(JSON.stringify(doc.data(), null, 2));
40
+ });
41
+ }
42
+ }
43
+
44
+ check().catch(console.error).finally(() => process.exit(0));
src/components/ConfirmModal.tsx ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { AlertTriangle, X } from 'lucide-react';
2
+
3
+ interface ConfirmModalProps {
4
+ isOpen: boolean;
5
+ onClose: () => void;
6
+ onConfirm: () => void;
7
+ title: string;
8
+ message: string;
9
+ confirmText?: string;
10
+ cancelText?: string;
11
+ variant?: 'danger' | 'warning' | 'info';
12
+ }
13
+
14
+ export function ConfirmModal({
15
+ isOpen,
16
+ onClose,
17
+ onConfirm,
18
+ title,
19
+ message,
20
+ confirmText = 'Confirmar',
21
+ cancelText = 'Cancelar',
22
+ variant = 'warning',
23
+ }: ConfirmModalProps) {
24
+ if (!isOpen) return null;
25
+
26
+ const colorClasses = {
27
+ danger: 'from-red-500 to-red-600 shadow-red-500/20',
28
+ warning: 'from-[#bb86fc] to-[#9966dd] shadow-[#bb86fc]/30',
29
+ info: 'from-blue-500 to-blue-600 shadow-blue-500/20',
30
+ };
31
+
32
+ const iconClasses = {
33
+ danger: 'bg-red-500/10 text-red-500',
34
+ warning: 'bg-[#bb86fc]/10 text-[#bb86fc]',
35
+ info: 'bg-blue-500/10 text-blue-500',
36
+ };
37
+
38
+ return (
39
+ <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-[100] p-4 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]">
40
+ <div className="bg-gradient-to-b from-[#1f1f1f] to-[#121212] rounded-2xl border border-gray-700/40 w-full max-w-md shadow-2xl overflow-hidden scale-in-center">
41
+ <div className="bg-gradient-to-b from-[#2a2a2a] to-[#1f1f1f] border-b border-gray-700/30 px-6 py-4 flex items-center justify-between">
42
+ <div className="flex items-center gap-3">
43
+ <div className={`p-2 rounded-lg ${iconClasses[variant]}`}>
44
+ <AlertTriangle className="w-5 h-5" />
45
+ </div>
46
+ <h2 className="text-xl font-bold text-white tracking-tight">{title}</h2>
47
+ </div>
48
+ <button
49
+ onClick={onClose}
50
+ className="text-gray-500 hover:text-white hover:bg-white/10 transition-all p-1.5 rounded-lg"
51
+ >
52
+ <X className="w-5 h-5" />
53
+ </button>
54
+ </div>
55
+
56
+ <div className="p-8">
57
+ <p className="text-gray-300 leading-relaxed">
58
+ {message}
59
+ </p>
60
+
61
+ <div className="flex gap-3 mt-8">
62
+ <button
63
+ onClick={onClose}
64
+ className="flex-1 bg-[#1a1a1a] border border-gray-600/40 hover:border-gray-500 hover:bg-[#242424] text-white px-5 py-3 rounded-xl font-semibold text-sm transition-all shadow-md active:scale-95"
65
+ >
66
+ {cancelText}
67
+ </button>
68
+ <button
69
+ onClick={() => {
70
+ onConfirm();
71
+ onClose();
72
+ }}
73
+ className={`flex-1 bg-gradient-to-r ${colorClasses[variant]} text-white px-5 py-3 rounded-xl font-bold text-sm transition-all shadow-lg hover:brightness-110 active:scale-95`}
74
+ >
75
+ {confirmText}
76
+ </button>
77
+ </div>
78
+ </div>
79
+ </div>
80
+ </div>
81
+ );
82
+ }
src/components/NewMangaModal.tsx CHANGED
@@ -11,6 +11,7 @@ import { db } from '../lib/firebase';
11
  import { doc, updateDoc, Timestamp } from 'firebase/firestore';
12
  import { getBatchSize, saveBatchSize } from '../utils/batchSizeManager';
13
  import { parseLinkText } from '../utils/linkParser';
 
14
 
15
  interface NewMangaModalProps {
16
  isOpen: boolean;
@@ -41,6 +42,13 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
41
  const [uploadingImages, setUploadingImages] = useState(false);
42
  const [currentUploadingImage, setCurrentUploadingImage] = useState(0);
43
  const [totalImagesToUpload, setTotalImagesToUpload] = useState(0);
 
 
 
 
 
 
 
44
 
45
 
46
  const [showCoverSelector, setShowCoverSelector] = useState(false);
@@ -48,6 +56,8 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
48
  const [coverFromExistingPage, setCoverFromExistingPage] = useState<{ thumbnail: string; original: string } | null>(null);
49
  const [showBatchSizeModal, setShowBatchSizeModal] = useState(false);
50
  const [batchSize, setBatchSize] = useState(getBatchSize());
 
 
51
 
52
  const isEditMode = !!editingManga;
53
 
@@ -207,7 +217,22 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
207
  let text = '';
208
 
209
  if (e.target instanceof HTMLInputElement && e.target.files && e.target.files.length > 0) {
210
- const file = e.target.files[0];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  try {
212
  text = await file.text();
213
  } catch (err) {
@@ -246,6 +271,89 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
246
 
247
 
248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  const handleRemovePage = (index: number) => {
250
  setChapterPages(prev => prev.filter((_, i) => i !== index));
251
  };
@@ -982,8 +1090,9 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
982
  <input
983
  type="file"
984
  accept=".txt"
 
985
  onChange={handleChapterPagesChange}
986
- disabled={isProcessingPages}
987
  className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-20"
988
  />
989
  </div>
@@ -992,6 +1101,44 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
992
  )}
993
  </div>
994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995
  {uploadingImages && (
996
  <div className="mb-6 bg-gradient-to-br from-[#242424] to-[#1a1a1a] rounded-xl p-5 border border-[#bb86fc]/30 shadow-xl">
997
  <div className="flex items-center justify-between mb-3">
@@ -1020,14 +1167,7 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
1020
  <div className="flex gap-3 pt-6 border-t border-gray-700/50">
1021
  {isEditMode && onDelete && (
1022
  <button
1023
- onClick={() => {
1024
- if (window.confirm('¿Estás seguro de que deseas eliminar este manga? Esta acción no se puede deshacer.')) {
1025
- if (editingManga) {
1026
- onDelete(editingManga.id);
1027
- onClose();
1028
- }
1029
- }
1030
- }}
1031
  className="bg-red-500/10 border border-red-500/30 hover:bg-red-500/20 text-red-500 px-4 py-3 rounded-lg font-semibold text-sm transition-all flex items-center gap-2 mr-auto"
1032
  >
1033
  <Trash2 className="w-4 h-4" />
@@ -1256,6 +1396,35 @@ export function NewMangaModal({ isOpen, onClose, onMangaCreated, editingManga, o
1256
  </div>
1257
  </div>
1258
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1259
  </div>
1260
  );
1261
  }
 
11
  import { doc, updateDoc, Timestamp } from 'firebase/firestore';
12
  import { getBatchSize, saveBatchSize } from '../utils/batchSizeManager';
13
  import { parseLinkText } from '../utils/linkParser';
14
+ import { ConfirmModal } from './ConfirmModal';
15
 
16
  interface NewMangaModalProps {
17
  isOpen: boolean;
 
42
  const [uploadingImages, setUploadingImages] = useState(false);
43
  const [currentUploadingImage, setCurrentUploadingImage] = useState(0);
44
  const [totalImagesToUpload, setTotalImagesToUpload] = useState(0);
45
+ const [bulkStatus, setBulkStatus] = useState<{
46
+ uploading: boolean;
47
+ current: number;
48
+ total: number;
49
+ currentName: string;
50
+ errors: string[];
51
+ } | null>(null);
52
 
53
 
54
  const [showCoverSelector, setShowCoverSelector] = useState(false);
 
56
  const [coverFromExistingPage, setCoverFromExistingPage] = useState<{ thumbnail: string; original: string } | null>(null);
57
  const [showBatchSizeModal, setShowBatchSizeModal] = useState(false);
58
  const [batchSize, setBatchSize] = useState(getBatchSize());
59
+ const [pendingBulkFiles, setPendingBulkFiles] = useState<File[] | null>(null);
60
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
61
 
62
  const isEditMode = !!editingManga;
63
 
 
217
  let text = '';
218
 
219
  if (e.target instanceof HTMLInputElement && e.target.files && e.target.files.length > 0) {
220
+ const files = Array.from(e.target.files);
221
+
222
+ if (files.length > 1) {
223
+ setPendingBulkFiles(files);
224
+ return;
225
+ }
226
+
227
+ const file = files[0];
228
+
229
+ // Auto-populate title from filename if not in edit mode or title is empty
230
+ if (!isEditMode || !formData.title.trim()) {
231
+ const fileName = file.name.split('.').slice(0, -1).join('.');
232
+ const cleanName = fileName.replace(/[_-]/g, ' ').trim();
233
+ setFormData(prev => ({ ...prev, title: cleanName }));
234
+ }
235
+
236
  try {
237
  text = await file.text();
238
  } catch (err) {
 
271
 
272
 
273
 
274
+ const handleBulkUpload = async (files: File[]) => {
275
+ if (isEditMode) {
276
+ alert('La subida masiva solo está disponible al crear nuevos mangas.');
277
+ return;
278
+ }
279
+
280
+ setBulkStatus({
281
+ uploading: true,
282
+ current: 0,
283
+ total: files.length,
284
+ currentName: '',
285
+ errors: []
286
+ });
287
+
288
+ try {
289
+ for (let i = 0; i < files.length; i++) {
290
+ const file = files[i];
291
+ const fileName = file.name.split('.').slice(0, -1).join('.');
292
+ const cleanTitle = fileName.replace(/[_-]/g, ' ').trim();
293
+
294
+ setBulkStatus(prev => prev ? { ...prev, current: i + 1, currentName: cleanTitle } : null);
295
+
296
+ try {
297
+ const text = await file.text();
298
+ const parsedPages = parseLinkText(text);
299
+
300
+ if (parsedPages.length === 0) {
301
+ throw new Error('No se encontraron enlaces válidos.');
302
+ }
303
+
304
+ // Create Manga
305
+ const mangaPayload: any = {
306
+ title: cleanTitle,
307
+ author: formData.name?.trim() || 'Anónimo',
308
+ categoryIds: formData.selectedCategories,
309
+ };
310
+
311
+ if (formData.description?.trim()) {
312
+ mangaPayload.description = formData.description.trim();
313
+ }
314
+
315
+ // Set cover from first page
316
+ if (parsedPages.length > 0) {
317
+ mangaPayload.thumbnail_url = parsedPages[0].webpDisplay;
318
+ mangaPayload.cover_url = parsedPages[0].originalUnmodified;
319
+ }
320
+
321
+ const manga = await createManga(mangaPayload);
322
+
323
+ // Create Chapter
324
+ await createChapter({
325
+ manga_id: manga.id,
326
+ number: 1,
327
+ title: 'Páginas',
328
+ pages: parsedPages.map(p => p.webpDisplay),
329
+ page_formats: parsedPages.map(p => p.originalFormat),
330
+ original_pages: parsedPages.map(p => p.original),
331
+ });
332
+
333
+ } catch (err: any) {
334
+ console.error(`Error processing ${file.name}:`, err);
335
+ setBulkStatus(prev => prev ? {
336
+ ...prev,
337
+ errors: [...prev.errors, `${file.name}: ${err.message || 'Error desconocido'}`]
338
+ } : null);
339
+ }
340
+ }
341
+
342
+ setBulkStatus(prev => prev ? { ...prev, currentName: '¡Completado!' } : null);
343
+
344
+ setTimeout(() => {
345
+ setBulkStatus(null);
346
+ handleClose();
347
+ onMangaCreated();
348
+ }, 2000);
349
+
350
+ } catch (error) {
351
+ console.error('Error general en subida masiva:', error);
352
+ alert('Ocurrió un error inesperado durante la subida masiva.');
353
+ setBulkStatus(null);
354
+ }
355
+ };
356
+
357
  const handleRemovePage = (index: number) => {
358
  setChapterPages(prev => prev.filter((_, i) => i !== index));
359
  };
 
1090
  <input
1091
  type="file"
1092
  accept=".txt"
1093
+ multiple
1094
  onChange={handleChapterPagesChange}
1095
+ disabled={isProcessingPages || (bulkStatus?.uploading ?? false)}
1096
  className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-20"
1097
  />
1098
  </div>
 
1101
  )}
1102
  </div>
1103
 
1104
+ {bulkStatus?.uploading && (
1105
+ <div className="mb-6 bg-gradient-to-br from-[#242424] to-[#1a1a1a] rounded-xl p-5 border border-[#bb86fc]/30 shadow-xl">
1106
+ <div className="flex items-center justify-between mb-3">
1107
+ <div className="flex items-center gap-2">
1108
+ <LoadingSpinner size={16} borderWidth={2} />
1109
+ <span className="text-sm font-semibold text-white">
1110
+ Subida Masiva: {bulkStatus.current} de {bulkStatus.total}
1111
+ </span>
1112
+ </div>
1113
+ <span className="text-sm font-bold text-[#bb86fc]">
1114
+ {Math.round((bulkStatus.current / bulkStatus.total) * 100)}%
1115
+ </span>
1116
+ </div>
1117
+ <div className="w-full bg-gray-700/40 rounded-full h-3 overflow-hidden border border-[#bb86fc]/40 shadow-inner">
1118
+ <div
1119
+ className="bg-gradient-to-r from-[#bb86fc] via-[#9966dd] to-[#bb86fc] h-full transition-all duration-500 ease-out relative overflow-hidden"
1120
+ style={{ width: `${(bulkStatus.current / bulkStatus.total) * 100}%` }}
1121
+ >
1122
+ <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-pulse" />
1123
+ </div>
1124
+ </div>
1125
+ <p className="text-xs text-[#bb86fc] mt-2 font-medium">
1126
+ {bulkStatus.currentName}
1127
+ </p>
1128
+ {bulkStatus.errors.length > 0 && (
1129
+ <div className="mt-3 text-[10px] text-red-400 max-h-20 overflow-y-auto bg-black/20 p-2 rounded border border-red-500/20">
1130
+ <p className="font-bold mb-1">Errores ({bulkStatus.errors.length}):</p>
1131
+ {bulkStatus.errors.map((err, i) => (
1132
+ <div key={i}>• {err}</div>
1133
+ ))}
1134
+ </div>
1135
+ )}
1136
+ <p className="text-xs text-gray-400 mt-2 text-center">
1137
+ Procesando archivos... Por favor espera.
1138
+ </p>
1139
+ </div>
1140
+ )}
1141
+
1142
  {uploadingImages && (
1143
  <div className="mb-6 bg-gradient-to-br from-[#242424] to-[#1a1a1a] rounded-xl p-5 border border-[#bb86fc]/30 shadow-xl">
1144
  <div className="flex items-center justify-between mb-3">
 
1167
  <div className="flex gap-3 pt-6 border-t border-gray-700/50">
1168
  {isEditMode && onDelete && (
1169
  <button
1170
+ onClick={() => setShowDeleteConfirm(true)}
 
 
 
 
 
 
 
1171
  className="bg-red-500/10 border border-red-500/30 hover:bg-red-500/20 text-red-500 px-4 py-3 rounded-lg font-semibold text-sm transition-all flex items-center gap-2 mr-auto"
1172
  >
1173
  <Trash2 className="w-4 h-4" />
 
1396
  </div>
1397
  </div>
1398
  )}
1399
+
1400
+ <ConfirmModal
1401
+ isOpen={!!pendingBulkFiles}
1402
+ onClose={() => setPendingBulkFiles(null)}
1403
+ onConfirm={() => {
1404
+ if (pendingBulkFiles) {
1405
+ handleBulkUpload(pendingBulkFiles);
1406
+ setPendingBulkFiles(null);
1407
+ }
1408
+ }}
1409
+ title="Subida Masiva"
1410
+ message={`Estás a punto de subir ${pendingBulkFiles?.length} archivos TXT. Se creará un manga por cada archivo usando la información de Autor y Categorías actual.`}
1411
+ confirmText="Empezar Subida"
1412
+ />
1413
+
1414
+ <ConfirmModal
1415
+ isOpen={showDeleteConfirm}
1416
+ onClose={() => setShowDeleteConfirm(false)}
1417
+ onConfirm={() => {
1418
+ if (editingManga && onDelete) {
1419
+ onDelete(editingManga.id);
1420
+ onClose();
1421
+ }
1422
+ }}
1423
+ title="Eliminar Manga"
1424
+ message="¿Estás seguro de que deseas eliminar este manga? Esta acción no se puede deshacer y se borrarán todos sus capítulos."
1425
+ confirmText="Eliminar permanentemente"
1426
+ variant="danger"
1427
+ />
1428
  </div>
1429
  );
1430
  }
src/services/upload.ts CHANGED
@@ -1,127 +1,127 @@
1
- import { getBatchSize } from '../utils/batchSizeManager';
2
-
3
- const UPLOAD_API_URL = 'https://codebydante-brodyfilestreambot.hf.space/upload';
4
-
5
- export interface UploadResponse {
6
- success: boolean;
7
- message_id?: number;
8
- hash?: string;
9
- url: string;
10
- }
11
-
12
- // Convert base64 to File
13
- function base64ToFile(base64: string, filename: string): File {
14
- const arr = base64.split(',');
15
- const mimeMatch = arr[0].match(/:(.*?);/);
16
- const mime = mimeMatch ? mimeMatch[1] : 'image/jpeg';
17
- const bstr = atob(arr[arr.length - 1]);
18
- let n = bstr.length;
19
- const u8arr = new Uint8Array(n);
20
- while(n--){
21
- u8arr[n] = bstr.charCodeAt(n);
22
- }
23
- return new File([u8arr], filename, {type:mime});
24
- }
25
-
26
- const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
27
-
28
- export async function uploadImage(base64Image: string, name?: string, retries = 3): Promise<{ data: { url: string } }> {
29
- const filename = name ? `${name}.jpg` : 'image.jpg';
30
- const file = base64ToFile(base64Image, filename);
31
-
32
- const formData = new FormData();
33
- formData.append('file', file);
34
-
35
- let attempt = 0;
36
- while (attempt < retries) {
37
- attempt++;
38
- const controller = new AbortController();
39
- const timeoutId = setTimeout(() => controller.abort(), 60000); // 60s timeout due to bot wake up
40
-
41
- try {
42
- const response = await fetch(UPLOAD_API_URL, {
43
- method: 'POST',
44
- body: formData,
45
- signal: controller.signal
46
- });
47
- clearTimeout(timeoutId);
48
-
49
- if (!response.ok) {
50
- const errorText = await response.text();
51
- if (response.status >= 500 && attempt < retries) {
52
- console.warn(`Upload error ${response.status}. Reintentando ${attempt}/${retries}...`);
53
- await delay(2000 * attempt);
54
- continue;
55
- }
56
- throw new Error(`Error al subir imagen: ${errorText}`);
57
- }
58
-
59
- const data: UploadResponse = await response.json();
60
-
61
- if (!data.success || !data.url) {
62
- throw new Error('Upload failed: Invalid server response');
63
- }
64
-
65
- return {
66
- data: {
67
- url: data.url
68
- }
69
- };
70
-
71
- } catch (error: any) {
72
- clearTimeout(timeoutId);
73
-
74
- const isNetworkOrTimeout = error.name === 'AbortError' ||
75
- error.message?.includes('network') ||
76
- error.message?.includes('fetch') ||
77
- error.message?.includes('Failed to fetch');
78
-
79
- if (isNetworkOrTimeout && attempt < retries) {
80
- console.warn(`Upload timeout/network error. Reintentando ${attempt}/${retries}...`, error?.message);
81
- await delay(2000 * attempt);
82
- continue;
83
- }
84
-
85
- if (error.name === 'AbortError') {
86
- throw new Error('La conexión al servidor tardó demasiado (Timeout).');
87
- }
88
-
89
- if (attempt >= retries) {
90
- throw error;
91
- }
92
- }
93
- }
94
-
95
- throw new Error('No se pudo subir la imagen tras varios intentos.');
96
- }
97
-
98
- export async function uploadMultipleImages(
99
- base64Images: string[],
100
- namePrefix?: string,
101
- onProgress?: (current: number, total: number) => void
102
- ): Promise<{ data: { url: string } }[]> {
103
- const BATCH_SIZE = getBatchSize() || 5;
104
- const results: { data: { url: string } }[] = [];
105
-
106
- for (let i = 0; i < base64Images.length; i += BATCH_SIZE) {
107
- const batch = base64Images.slice(i, i + BATCH_SIZE);
108
- const uploadPromises = batch.map((image, batchIndex) => {
109
- const globalIndex = i + batchIndex;
110
- const name = namePrefix ? `${namePrefix}_${globalIndex + 1}` : undefined;
111
- return uploadImage(image, name);
112
- });
113
-
114
- const batchResults = await Promise.all(uploadPromises);
115
- results.push(...batchResults);
116
-
117
- if (onProgress) {
118
- onProgress(Math.min(i + BATCH_SIZE, base64Images.length), base64Images.length);
119
- }
120
-
121
- if (i + BATCH_SIZE < base64Images.length) {
122
- await delay(1000);
123
- }
124
- }
125
-
126
- return results;
127
- }
 
1
+ import { getBatchSize } from '../utils/batchSizeManager';
2
+
3
+ const UPLOAD_API_URL = 'https://codebydante-brodyfilestreambot.hf.space/upload';
4
+
5
+ export interface UploadResponse {
6
+ success: boolean;
7
+ message_id?: number;
8
+ hash?: string;
9
+ url: string;
10
+ }
11
+
12
+ // Convert base64 to File
13
+ function base64ToFile(base64: string, filename: string): File {
14
+ const arr = base64.split(',');
15
+ const mimeMatch = arr[0].match(/:(.*?);/);
16
+ const mime = mimeMatch ? mimeMatch[1] : 'image/jpeg';
17
+ const bstr = atob(arr[arr.length - 1]);
18
+ let n = bstr.length;
19
+ const u8arr = new Uint8Array(n);
20
+ while(n--){
21
+ u8arr[n] = bstr.charCodeAt(n);
22
+ }
23
+ return new File([u8arr], filename, {type:mime});
24
+ }
25
+
26
+ const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
27
+
28
+ export async function uploadImage(base64Image: string, name?: string, retries = 3): Promise<{ data: { url: string } }> {
29
+ const filename = name ? `${name}.jpg` : 'image.jpg';
30
+ const file = base64ToFile(base64Image, filename);
31
+
32
+ const formData = new FormData();
33
+ formData.append('file', file);
34
+
35
+ let attempt = 0;
36
+ while (attempt < retries) {
37
+ attempt++;
38
+ const controller = new AbortController();
39
+ const timeoutId = setTimeout(() => controller.abort(), 60000); // 60s timeout due to bot wake up
40
+
41
+ try {
42
+ const response = await fetch(UPLOAD_API_URL, {
43
+ method: 'POST',
44
+ body: formData,
45
+ signal: controller.signal
46
+ });
47
+ clearTimeout(timeoutId);
48
+
49
+ if (!response.ok) {
50
+ const errorText = await response.text();
51
+ if (response.status >= 500 && attempt < retries) {
52
+ console.warn(`Upload error ${response.status}. Reintentando ${attempt}/${retries}...`);
53
+ await delay(2000 * attempt);
54
+ continue;
55
+ }
56
+ throw new Error(`Error al subir imagen: ${errorText}`);
57
+ }
58
+
59
+ const data: UploadResponse = await response.json();
60
+
61
+ if (!data.success || !data.url) {
62
+ throw new Error('Upload failed: Invalid server response');
63
+ }
64
+
65
+ return {
66
+ data: {
67
+ url: data.url
68
+ }
69
+ };
70
+
71
+ } catch (error: any) {
72
+ clearTimeout(timeoutId);
73
+
74
+ const isNetworkOrTimeout = error.name === 'AbortError' ||
75
+ error.message?.includes('network') ||
76
+ error.message?.includes('fetch') ||
77
+ error.message?.includes('Failed to fetch');
78
+
79
+ if (isNetworkOrTimeout && attempt < retries) {
80
+ console.warn(`Upload timeout/network error. Reintentando ${attempt}/${retries}...`, error?.message);
81
+ await delay(2000 * attempt);
82
+ continue;
83
+ }
84
+
85
+ if (error.name === 'AbortError') {
86
+ throw new Error('La conexión al servidor tardó demasiado (Timeout).');
87
+ }
88
+
89
+ if (attempt >= retries) {
90
+ throw error;
91
+ }
92
+ }
93
+ }
94
+
95
+ throw new Error('No se pudo subir la imagen tras varios intentos.');
96
+ }
97
+
98
+ export async function uploadMultipleImages(
99
+ base64Images: string[],
100
+ namePrefix?: string,
101
+ onProgress?: (current: number, total: number) => void
102
+ ): Promise<{ data: { url: string } }[]> {
103
+ const BATCH_SIZE = getBatchSize() || 5;
104
+ const results: { data: { url: string } }[] = [];
105
+
106
+ for (let i = 0; i < base64Images.length; i += BATCH_SIZE) {
107
+ const batch = base64Images.slice(i, i + BATCH_SIZE);
108
+ const uploadPromises = batch.map((image, batchIndex) => {
109
+ const globalIndex = i + batchIndex;
110
+ const name = namePrefix ? `${namePrefix}_${globalIndex + 1}` : undefined;
111
+ return uploadImage(image, name);
112
+ });
113
+
114
+ const batchResults = await Promise.all(uploadPromises);
115
+ results.push(...batchResults);
116
+
117
+ if (onProgress) {
118
+ onProgress(Math.min(i + BATCH_SIZE, base64Images.length), base64Images.length);
119
+ }
120
+
121
+ if (i + BATCH_SIZE < base64Images.length) {
122
+ await delay(1000);
123
+ }
124
+ }
125
+
126
+ return results;
127
+ }
src/utils/linkParser.ts CHANGED
@@ -1,81 +1,81 @@
1
- import { OptimizedImage } from './imageOptimization';
2
-
3
- export function parseLinkText(text: string): OptimizedImage[] {
4
- const pagesMap = new Map<number, Partial<OptimizedImage>>();
5
-
6
- const lines = text.split('\n');
7
- let currentSection = ''; // 'WEB P LINKS' | 'ORIGINAL LINKS'
8
- let currentTarget = ''; // 'Hugging Face' | 'Local'
9
-
10
- for (const line of lines) {
11
- const trimmed = line.trim();
12
-
13
- if (trimmed.includes('---- WEB P LINKS ----')) {
14
- currentSection = 'WEB P LINKS';
15
- continue;
16
- }
17
-
18
- if (trimmed.includes('---- ORIGINAL LINKS ----')) {
19
- currentSection = 'ORIGINAL LINKS';
20
- continue;
21
- }
22
-
23
- if (trimmed.includes('Para Hugging Face (Público):')) {
24
- currentTarget = 'Hugging Face';
25
- continue;
26
- }
27
-
28
- if (trimmed.includes('Para tu PC Local (Pruebas):')) {
29
- currentTarget = 'Local';
30
- continue;
31
- }
32
-
33
- // Process only Hugging Face links
34
- if (currentTarget === 'Hugging Face' && trimmed.match(/^\(\d+\)\s+.*?\s+=\s+http/)) {
35
- const match = trimmed.match(/^\((\d+)\)\s+.*?\s+=\s+(http.*)$/);
36
- if (match) {
37
- const pageNum = parseInt(match[1], 10);
38
- const url = match[2].trim();
39
-
40
- if (!pagesMap.has(pageNum)) {
41
- pagesMap.set(pageNum, {
42
- originalFormat: 'webp',
43
- originalBase64: '', // Indicate this is already uploaded
44
- });
45
- }
46
-
47
- const pageData = pagesMap.get(pageNum)!;
48
-
49
- // Force .webp extension if it isn't one (though original might not be, we don't care that much here, just use 'webp')
50
- const isOriginalUrl = url.includes('/stream/') || url.includes('hash=');
51
-
52
- if (currentSection === 'WEB P LINKS') {
53
- pageData.thumbnail = url;
54
- pageData.webpDisplay = url;
55
- pageData.webpCover = url;
56
- } else if (currentSection === 'ORIGINAL LINKS') {
57
- pageData.original = url;
58
- pageData.originalUnmodified = url;
59
- }
60
- }
61
- }
62
- }
63
-
64
- // Convert map to sorted array
65
- const sortedPages: OptimizedImage[] = [];
66
- const sortedKeys = Array.from(pagesMap.keys()).sort((a, b) => a - b);
67
-
68
- for (const key of sortedKeys) {
69
- const pageData = pagesMap.get(key);
70
- if (pageData && pageData.thumbnail && pageData.original) {
71
- sortedPages.push(pageData as OptimizedImage);
72
- } else if (pageData && pageData.thumbnail) {
73
- // Provide fallback if original is missing
74
- pageData.original = pageData.thumbnail;
75
- pageData.originalUnmodified = pageData.thumbnail;
76
- sortedPages.push(pageData as OptimizedImage);
77
- }
78
- }
79
-
80
- return sortedPages;
81
- }
 
1
+ import { OptimizedImage } from './imageOptimization';
2
+
3
+ export function parseLinkText(text: string): OptimizedImage[] {
4
+ const pagesMap = new Map<number, Partial<OptimizedImage>>();
5
+
6
+ const lines = text.split('\n');
7
+ let currentSection = ''; // 'WEB P LINKS' | 'ORIGINAL LINKS'
8
+ let currentTarget = ''; // 'Hugging Face' | 'Local'
9
+
10
+ for (const line of lines) {
11
+ const trimmed = line.trim();
12
+
13
+ if (trimmed.includes('---- WEB P LINKS ----')) {
14
+ currentSection = 'WEB P LINKS';
15
+ continue;
16
+ }
17
+
18
+ if (trimmed.includes('---- ORIGINAL LINKS ----')) {
19
+ currentSection = 'ORIGINAL LINKS';
20
+ continue;
21
+ }
22
+
23
+ if (trimmed.includes('Para Hugging Face (Público):')) {
24
+ currentTarget = 'Hugging Face';
25
+ continue;
26
+ }
27
+
28
+ if (trimmed.includes('Para tu PC Local (Pruebas):')) {
29
+ currentTarget = 'Local';
30
+ continue;
31
+ }
32
+
33
+ // Process only Hugging Face links
34
+ if (currentTarget === 'Hugging Face' && trimmed.match(/^\(\d+\)\s+.*?\s+=\s+http/)) {
35
+ const match = trimmed.match(/^\((\d+)\)\s+.*?\s+=\s+(http.*)$/);
36
+ if (match) {
37
+ const pageNum = parseInt(match[1], 10);
38
+ const url = match[2].trim();
39
+
40
+ if (!pagesMap.has(pageNum)) {
41
+ pagesMap.set(pageNum, {
42
+ originalFormat: 'webp',
43
+ originalBase64: '', // Indicate this is already uploaded
44
+ });
45
+ }
46
+
47
+ const pageData = pagesMap.get(pageNum)!;
48
+
49
+ // Force .webp extension if it isn't one (though original might not be, we don't care that much here, just use 'webp')
50
+ const isOriginalUrl = url.includes('/stream/') || url.includes('hash=');
51
+
52
+ if (currentSection === 'WEB P LINKS') {
53
+ pageData.thumbnail = url;
54
+ pageData.webpDisplay = url;
55
+ pageData.webpCover = url;
56
+ } else if (currentSection === 'ORIGINAL LINKS') {
57
+ pageData.original = url;
58
+ pageData.originalUnmodified = url;
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ // Convert map to sorted array
65
+ const sortedPages: OptimizedImage[] = [];
66
+ const sortedKeys = Array.from(pagesMap.keys()).sort((a, b) => a - b);
67
+
68
+ for (const key of sortedKeys) {
69
+ const pageData = pagesMap.get(key);
70
+ if (pageData && pageData.thumbnail && pageData.original) {
71
+ sortedPages.push(pageData as OptimizedImage);
72
+ } else if (pageData && pageData.thumbnail) {
73
+ // Provide fallback if original is missing
74
+ pageData.original = pageData.thumbnail;
75
+ pageData.originalUnmodified = pageData.thumbnail;
76
+ sortedPages.push(pageData as OptimizedImage);
77
+ }
78
+ }
79
+
80
+ return sortedPages;
81
+ }
test_parser.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { parseLinkText } from './src/utils/linkParser';
2
- const text = `
3
- ==== Jungle_Party_1_(1) ====
4
-
5
- ---- WEB P LINKS ----
6
-
7
- 🚀 Para Hugging Face (Público):
8
- (1) pagina_001.webp = https://codebydante-brodyfilestreambot.hf.space/stream/778?hash=30af00
9
- (2) pagina_002.webp = https://codebydante-brodyfilestreambot.hf.space/stream/745?hash=1ffd23
10
-
11
- 🖥 Para tu PC Local (Pruebas):
12
-
13
- ---- ORIGINAL LINKS ----
14
-
15
- 🚀 Para Hugging Face (Público):
16
- (1) pagina_001.webp = https://codebydante-brodyfilestreambot.hf.space/stream/778?hash=30af00_orig
17
- (2) pagina_002.webp = https://codebydante-brodyfilestreambot.hf.space/stream/745?hash=1ffd23_orig
18
- `;
19
- console.log(JSON.stringify(parseLinkText(text), null, 2));
 
1
+ import { parseLinkText } from './src/utils/linkParser';
2
+ const text = `
3
+ ==== Jungle_Party_1_(1) ====
4
+
5
+ ---- WEB P LINKS ----
6
+
7
+ 🚀 Para Hugging Face (Público):
8
+ (1) pagina_001.webp = https://codebydante-brodyfilestreambot.hf.space/stream/778?hash=30af00
9
+ (2) pagina_002.webp = https://codebydante-brodyfilestreambot.hf.space/stream/745?hash=1ffd23
10
+
11
+ 🖥 Para tu PC Local (Pruebas):
12
+
13
+ ---- ORIGINAL LINKS ----
14
+
15
+ 🚀 Para Hugging Face (Público):
16
+ (1) pagina_001.webp = https://codebydante-brodyfilestreambot.hf.space/stream/778?hash=30af00_orig
17
+ (2) pagina_002.webp = https://codebydante-brodyfilestreambot.hf.space/stream/745?hash=1ffd23_orig
18
+ `;
19
+ console.log(JSON.stringify(parseLinkText(text), null, 2));