codebydante commited on
Commit
df4a9b4
·
verified ·
1 Parent(s): 887794e

Upload 73 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +7 -0
  2. .gitattributes +47 -35
  3. .gitignore +22 -0
  4. .venv/Scripts/python.exe +3 -0
  5. .venv/Scripts/pythonw.exe +3 -0
  6. .venv/pyvenv.cfg +3 -0
  7. Dockerfile +44 -0
  8. README.md +27 -10
  9. __pycache__/ai_service.cpython-311.pyc +0 -0
  10. __pycache__/collage_service.cpython-310.pyc +0 -0
  11. __pycache__/collage_service.cpython-311.pyc +0 -0
  12. __pycache__/config.cpython-310.pyc +0 -0
  13. __pycache__/config.cpython-311.pyc +0 -0
  14. __pycache__/database.cpython-310.pyc +0 -0
  15. __pycache__/database.cpython-311.pyc +0 -0
  16. __pycache__/downloader.cpython-311.pyc +0 -0
  17. __pycache__/firebase_service.cpython-310.pyc +0 -0
  18. __pycache__/firebase_service.cpython-311.pyc +0 -0
  19. __pycache__/google_lens.cpython-311.pyc +0 -0
  20. __pycache__/jav_extractor.cpython-311.pyc +0 -0
  21. __pycache__/main.cpython-310.pyc +0 -0
  22. __pycache__/main.cpython-311.pyc +0 -0
  23. __pycache__/manga_service.cpython-311.pyc +0 -0
  24. __pycache__/tagger_tool.cpython-311.pyc +0 -0
  25. __pycache__/tiktok_tool.cpython-311.pyc +0 -0
  26. __pycache__/tools_fusion.cpython-311.pyc +0 -0
  27. __pycache__/tools_media.cpython-311.pyc +0 -0
  28. __pycache__/tools_x.cpython-311.pyc +0 -0
  29. __pycache__/tts_service.cpython-311.pyc +0 -0
  30. __pycache__/utils.cpython-311.pyc +0 -0
  31. __pycache__/utils_chat_actions.cpython-311.pyc +0 -0
  32. __pycache__/utils_modes.cpython-311.pyc +0 -0
  33. __pycache__/video_mixer.cpython-311.pyc +0 -0
  34. __pycache__/yandex_lens.cpython-311.pyc +0 -0
  35. cleanup_utils.py +166 -0
  36. collage_service.py +180 -0
  37. config.py +31 -0
  38. converter.py +50 -0
  39. data/viral_music.json +23 -0
  40. data/viral_shorts.json +10 -0
  41. database.py +92 -0
  42. debug_firestore.ts +46 -0
  43. deploy_git.bat +17 -0
  44. eslint.config.js +28 -0
  45. firebase_credentials.json +13 -0
  46. firebase_service.py +666 -0
  47. gallery-dl.conf +4 -0
  48. icons/@twistedbrody dowload.png +3 -0
  49. icons/@twistedbrody.png +3 -0
  50. index.html +17 -0
.dockerignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ dist
3
+ downloads
4
+ .git
5
+ *.rar
6
+ .env
7
+ .DS_Store
.gitattributes CHANGED
@@ -1,35 +1,47 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ public/icons/@twistedbrody[[:space:]]dowload.png filter=lfs diff=lfs merge=lfs -text
37
+ public/icons/@twistedbrody.png filter=lfs diff=lfs merge=lfs -text
38
+ public/icons/1.png filter=lfs diff=lfs merge=lfs -text
39
+ public/icons/2.png filter=lfs diff=lfs merge=lfs -text
40
+ public/icons/3.png filter=lfs diff=lfs merge=lfs -text
41
+ public/icons/4.png filter=lfs diff=lfs merge=lfs -text
42
+ public/icons/icones.png filter=lfs diff=lfs merge=lfs -text
43
+ public/icons/logo.png filter=lfs diff=lfs merge=lfs -text
44
+ .venv/Scripts/python.exe filter=lfs diff=lfs merge=lfs -text
45
+ .venv/Scripts/pythonw.exe filter=lfs diff=lfs merge=lfs -text
46
+ icons/@twistedbrody[[:space:]]dowload.png filter=lfs diff=lfs merge=lfs -text
47
+ icons/@twistedbrody.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ venv/
6
+ env/
7
+
8
+ # Project specific
9
+ sessions/
10
+ downloads/
11
+ tmp/
12
+ data/
13
+ tools/
14
+ cookies/
15
+
16
+ # Credentials
17
+ firebase_credentials.json
18
+ config.py
19
+ .env
20
+
21
+ # Logs
22
+ *.log
.venv/Scripts/python.exe ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0978726a27a8c5cc7b329e6d6f02c4c18bc1cdd448cc0ea29fdcdae4e2af7868
3
+ size 266624
.venv/Scripts/pythonw.exe ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b9848da783f2977228b1fa79621e689e7791f49dd457a0df639a605e13c6f01
3
+ size 254848
.venv/pyvenv.cfg ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ home = C:\Users\Gonzalo\AppData\Local\Programs\Python\Python310
2
+ include-system-site-packages = false
3
+ version = 3.10.9
Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Install system dependencies
4
+ RUN apt-get update && apt-get install -y \
5
+ ffmpeg \
6
+ aria2 \
7
+ p7zip-full \
8
+ git \
9
+ git-lfs \
10
+ build-essential \
11
+ && git lfs install \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Set up a new user named "user" with user ID 1000
15
+ RUN useradd -m -u 1000 user
16
+
17
+ # Set working directory to the user's home directory
18
+ WORKDIR /app
19
+
20
+ # Copy requirements first
21
+ COPY requirements.txt .
22
+
23
+ # Install Python dependencies as the new user
24
+ RUN pip install --no-cache-dir -r requirements.txt
25
+
26
+ # Copy the rest of the application
27
+ COPY --chown=user . .
28
+
29
+ # Create necessary directories and set permissions
30
+ RUN mkdir -p downloads tmp tools cookies data sessions && \
31
+ chown -R user:user /app && \
32
+ chmod -R 777 /app/downloads /app/tmp /app/cookies /app/data /app/sessions
33
+
34
+ # Switch to the "user" user
35
+ USER user
36
+
37
+ # Set environment variables
38
+ ENV PYTHONUNBUFFERED=1
39
+
40
+ # Expose port for Hugging Face Spaces
41
+ EXPOSE 7860
42
+
43
+ # Command to run the bot: Start Aria2 daemon and then the Python bot
44
+ CMD aria2c --enable-rpc --rpc-listen-all=false --rpc-listen-port=6800 --daemon && python main.py
README.md CHANGED
@@ -1,10 +1,27 @@
1
- ---
2
- title: Twistedbrodymangaflowbot
3
- emoji: 📊
4
- colorFrom: red
5
- colorTo: purple
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 BOT
3
+ emoji: 🤖
4
+ colorFrom: purple
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 7860
9
+ ---
10
+
11
+ # Twisted Brody Bot Pro
12
+
13
+ Este es un bot de Telegram desplegado en Hugging Face Spaces usando Docker.
14
+
15
+ ## Configuración
16
+
17
+ Para que el bot funcione, debes configurar las siguientes **Secret Variables** en la pestaña `Settings` del Space:
18
+
19
+ 1. `API_ID`: Tu API ID de Telegram.
20
+ 2. `API_HASH`: Tu API Hash de Telegram.
21
+ 3. `BOT_TOKEN`: El token de tu bot.
22
+ 4. `FIREBASE_KEY`: El contenido COMPLETO de tu archivo `firebase_credentials.json` (copia y pega todo el JSON).
23
+ 5. `OWNER_ID`: Tu ID de usuario de Telegram.
24
+
25
+ ## Despliegue
26
+
27
+ El `Dockerfile` ya está configurado para instalar las dependencias (`ffmpeg`, `aria2`, `python`) y ejecutar `main.py`.
__pycache__/ai_service.cpython-311.pyc ADDED
Binary file (59.8 kB). View file
 
__pycache__/collage_service.cpython-310.pyc ADDED
Binary file (4.67 kB). View file
 
__pycache__/collage_service.cpython-311.pyc ADDED
Binary file (10.4 kB). View file
 
__pycache__/config.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
__pycache__/config.cpython-311.pyc ADDED
Binary file (1.55 kB). View file
 
__pycache__/database.cpython-310.pyc ADDED
Binary file (7.28 kB). View file
 
__pycache__/database.cpython-311.pyc ADDED
Binary file (4.17 kB). View file
 
__pycache__/downloader.cpython-311.pyc ADDED
Binary file (88.7 kB). View file
 
__pycache__/firebase_service.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
__pycache__/firebase_service.cpython-311.pyc ADDED
Binary file (38.6 kB). View file
 
__pycache__/google_lens.cpython-311.pyc ADDED
Binary file (7.17 kB). View file
 
__pycache__/jav_extractor.cpython-311.pyc ADDED
Binary file (6.36 kB). View file
 
__pycache__/main.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
__pycache__/main.cpython-311.pyc ADDED
Binary file (15.7 kB). View file
 
__pycache__/manga_service.cpython-311.pyc ADDED
Binary file (67.1 kB). View file
 
__pycache__/tagger_tool.cpython-311.pyc ADDED
Binary file (16.5 kB). View file
 
__pycache__/tiktok_tool.cpython-311.pyc ADDED
Binary file (23 kB). View file
 
__pycache__/tools_fusion.cpython-311.pyc ADDED
Binary file (21.6 kB). View file
 
__pycache__/tools_media.cpython-311.pyc ADDED
Binary file (2.65 kB). View file
 
__pycache__/tools_x.cpython-311.pyc ADDED
Binary file (4.28 kB). View file
 
__pycache__/tts_service.cpython-311.pyc ADDED
Binary file (2.28 kB). View file
 
__pycache__/utils.cpython-311.pyc ADDED
Binary file (65.7 kB). View file
 
__pycache__/utils_chat_actions.cpython-311.pyc ADDED
Binary file (1.91 kB). View file
 
__pycache__/utils_modes.cpython-311.pyc ADDED
Binary file (3.6 kB). View file
 
__pycache__/video_mixer.cpython-311.pyc ADDED
Binary file (11.8 kB). View file
 
__pycache__/yandex_lens.cpython-311.pyc ADDED
Binary file (6.15 kB). View file
 
cleanup_utils.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ file_path = "c:/Users/Gonzalo/Downloads/Twisted Brody Waifus & Creampie/utils.py"
4
+
5
+ # New content for the function
6
+ new_function_code = '''def format_tracemoe_results(data):
7
+ """Formatea resultados de trace.moe + anilist info EXTENDIDO."""
8
+ if not data or isinstance(data, str) or 'result' not in data:
9
+ return "🤷‍♂️ **Trace.moe: Sin resultados.**", None, False
10
+
11
+ results = data['result']
12
+ if not results:
13
+ return "🤷‍♂️ **Trace.moe: Sin coincidencias.**", None, False
14
+
15
+ # Filtrar y tomar el mejor
16
+ best = results[0]
17
+ similarity = float(best.get('similarity', 0)) * 100
18
+
19
+ if similarity < 85.0:
20
+ return "🤷‍♂️ **Trace.moe: Sin coincidencias sólidas (<85%).**", None, False
21
+
22
+ # Obtener info extra de Anilist
23
+ anilist_id = best.get('anilist', None)
24
+ meta = {}
25
+ if anilist_id:
26
+ from utils import get_anilist_info # Ensure import if needed, or rely on global
27
+ meta = get_anilist_info(anilist_id) or {}
28
+
29
+ # --- PROCESAR DATOS DE ANILIST ---
30
+
31
+ # 1. Títulos
32
+ titles = meta.get('title', {})
33
+ title_romaji = titles.get('romaji', 'Desconocido')
34
+ title_native = titles.get('native')
35
+
36
+ # 2. Info
37
+ episodes = meta.get('episodes', '?')
38
+ duration = meta.get('duration', '?')
39
+ fmt = meta.get('format', 'TV')
40
+
41
+ desc_type = f"{episodes} ep. ({duration} min) {fmt} anime."
42
+
43
+ start = meta.get('startDate', {})
44
+ end = meta.get('endDate', {})
45
+ s_date = f"{start.get('year', '?')}-{start.get('month', '?')}-{start.get('day', '?')}"
46
+ e_date = f"{end.get('year', '?')}-{end.get('month', '?')}-{end.get('day', '?')}"
47
+ aired = f"Airing from {s_date} to {e_date}."
48
+
49
+ # 3. Alias
50
+ aliases = meta.get('synonyms', [])
51
+ alias_str = aliases[0] if aliases else "None"
52
+
53
+ # 4. Géneros
54
+ genres = meta.get('genres', [])
55
+ genre_str = ", ".join(genres[:3]) if genres else "Unknown"
56
+
57
+ # 5. Studios
58
+ studios_node = meta.get('studios', {}).get('nodes', [])
59
+ studios_str = "Unknown"
60
+ if studios_node:
61
+ studios_str = ", ".join([s['name'] for s in studios_node])
62
+
63
+ # 6. Clip Match
64
+ match_episode = best.get('episode', '?')
65
+ time_pos = best.get('from', 0)
66
+ m, s = divmod(int(time_pos), 60)
67
+ time_str = f"{m}:{s:02d}"
68
+
69
+ # NSFW Check
70
+ is_adult = meta.get('isAdult', False)
71
+ video_preview = best.get('video', '')
72
+
73
+ # --- CONSTRUIR EL MENSAJE FINAL (EXACTO) ---
74
+ msg = f"""
75
+ 📁 Trace moe resultados
76
+ 📁 Similitud: {similarity:.2f}%
77
+
78
+ 📁 Title: `{title_romaji}`
79
+ 📁 `{title_native if title_native else ''}`
80
+ 📁 Info: {desc_type}
81
+ {aired}
82
+ 📁 Alias: `{alias_str}`
83
+ 📁 Genre: {genre_str}
84
+ 📁 Studio: {studios_str}
85
+ 📁 Clip Match: Episode: {match_episode} (Time: {time_str})
86
+ """
87
+
88
+ return msg, video_preview, is_adult
89
+ '''
90
+
91
+ try:
92
+ with open(file_path, 'r', encoding='utf-8') as f:
93
+ lines = f.readlines()
94
+
95
+ output_lines = []
96
+
97
+ # State machine to skip the FIRST definition of format_tracemoe_results
98
+ # and REPLACE the SECOND definition.
99
+
100
+ found_first_def = False
101
+ skipping_first = False
102
+
103
+ found_second_def = False
104
+ skipping_second = False
105
+ replaced_second = False
106
+
107
+ i = 0
108
+ while i < len(lines):
109
+ line = lines[i]
110
+
111
+ # Detect function start
112
+ if line.strip().startswith("def format_tracemoe_results(data):"):
113
+ if not found_first_def:
114
+ # Found the first one (the duplicate/bad one). Start skipping.
115
+ found_first_def = True
116
+ skipping_first = True
117
+
118
+ # Check where this function ends (naive check: next def or special comment)
119
+ # In the file, it seems followed by # --- TRACE.MOE API SERVICE --- (approx)
120
+ # We will skip until we see a line starting with 'def ' or '# ---' that is NOT this function
121
+ i += 1
122
+ continue
123
+ else:
124
+ # Found the second one! This is where we want to put the NEW code.
125
+ found_second_def = True
126
+ skipping_second = True
127
+
128
+ if not replaced_second:
129
+ output_lines.append(new_function_code + "\n")
130
+ replaced_second = True
131
+
132
+ i += 1
133
+ continue
134
+
135
+ if skipping_first:
136
+ # We are inside the first unwanted function.
137
+ # Stop skipping if we hit a new function definition or section header
138
+ if line.strip().startswith("def ") or line.strip().startswith("# --- TRACE.MOE API SERVICE ---"):
139
+ skipping_first = False
140
+ output_lines.append(line) # Keep this line (it's the next thing)
141
+ # Else: Drop the line
142
+ i += 1
143
+ continue
144
+
145
+ if skipping_second:
146
+ # We are inside the second function (which we already replaced).
147
+ # Stop skipping if we hit end of file or next def (though it's likely EOF)
148
+ if line.strip().startswith("def "): # Safety break if there is another function
149
+ skipping_second = False
150
+ output_lines.append(line)
151
+ # Else: Drop the line
152
+ i += 1
153
+ continue
154
+
155
+ # Normal line, keep it
156
+ output_lines.append(line)
157
+ i += 1
158
+
159
+ # Write back
160
+ with open(file_path, 'w', encoding='utf-8') as f:
161
+ f.writelines(output_lines)
162
+
163
+ print("Successfully cleaned up utils.py")
164
+
165
+ except Exception as e:
166
+ print(f"Error: {e}")
collage_service.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ import random
4
+ import time
5
+ import asyncio
6
+ import logging
7
+ from typing import List
8
+ from pyrogram import Client
9
+ from pyrogram.types import Message
10
+ from PIL import Image
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Temporary storage for downloaded collage images
15
+ COLLAGE_DIR = "downloads/collage_tmp"
16
+ os.makedirs(COLLAGE_DIR, exist_ok=True)
17
+
18
+ async def create_and_send_collage(client: Client, chat_id: int, status_msg: Message, file_ids: List[str]):
19
+ """
20
+ Downloads a list of telegram file_ids, combines them into a grid collage,
21
+ and sends the final image back to the user.
22
+ """
23
+
24
+ if not file_ids:
25
+ await status_msg.edit_text("❌ No se recibieron imágenes válidas.")
26
+ return
27
+
28
+ await status_msg.edit_text(f"📥 Descargando {len(file_ids)} imágenes...")
29
+
30
+ downloaded_paths = []
31
+
32
+ try:
33
+ # 1. Download all images
34
+ for i, f_id in enumerate(file_ids):
35
+ try:
36
+ # Use a unique name for each
37
+ tmp_path = os.path.join(COLLAGE_DIR, f"img_{chat_id}_{int(time.time())}_{i}.jpg")
38
+ file_path = await client.download_media(f_id, file_name=tmp_path)
39
+ if file_path and os.path.exists(file_path):
40
+ downloaded_paths.append(file_path)
41
+ except Exception as e:
42
+ logger.error(f"Error downloading image for collage {f_id}: {e}")
43
+
44
+ if not downloaded_paths:
45
+ await status_msg.edit_text("❌ Hubo un error al descargar las imágenes de Telegram.")
46
+ return
47
+
48
+ await status_msg.edit_text("⚙️ Generando Collage...")
49
+
50
+ # 2. Open all images with PIL
51
+ images = []
52
+ for path in downloaded_paths:
53
+ try:
54
+ img = Image.open(path)
55
+ # Convert to RGB to avoid issues with transparency
56
+ if img.mode in ('RGBA', 'P'):
57
+ img = img.convert('RGB')
58
+ images.append(img)
59
+ except Exception as e:
60
+ logger.error(f"Error opening image {path}: {e}")
61
+
62
+ if not images:
63
+ await status_msg.edit_text("❌ Las imágenes descargadas están corruptas.")
64
+ return
65
+
66
+ # 3. Calculate Layout (Smart Justified Grid - No Cropping)
67
+ num_images = len(images)
68
+
69
+ # Determinar columnas basadas en la cantidad
70
+ if num_images <= 2:
71
+ cols = num_images
72
+ elif num_images <= 4:
73
+ cols = 2
74
+ elif num_images <= 6:
75
+ cols = 3
76
+ else:
77
+ cols = math.ceil(math.sqrt(num_images))
78
+
79
+ # Target total width of the collage
80
+ W = 1600
81
+
82
+ rows_list = []
83
+ row_heights = []
84
+
85
+ # Dividir imágenes en filas
86
+ for i in range(0, num_images, cols):
87
+ row_imgs = images[i:i+cols]
88
+
89
+ # Aspect ratio = ancho / alto
90
+ aspect_ratios = [img.width / img.height for img in row_imgs]
91
+ sum_ratios = sum(aspect_ratios)
92
+
93
+ # Calcular la altura perfecta para esta fila para que llene el ancho total (W)
94
+ row_h = int(W / sum_ratios)
95
+
96
+ # Prevenir estiramiento extremo en imagenes verticales sueltas en la última fila
97
+ max_allowed_h = int(1.5 * (W / len(row_imgs)))
98
+ if row_h > max_allowed_h:
99
+ row_h = max_allowed_h
100
+
101
+ row_heights.append(row_h)
102
+
103
+ # Redimensionar imagenes
104
+ resized_row = []
105
+ current_w = 0
106
+ for j, img in enumerate(row_imgs):
107
+ # La ultima imagen llena el espacio residual EXACTO del ancho (salvo si se capeo en altura)
108
+ if j == len(row_imgs) - 1 and row_h < max_allowed_h:
109
+ new_w = W - current_w
110
+ else:
111
+ new_w = int(row_h * (img.width / img.height))
112
+ current_w += new_w
113
+
114
+ resized = img.resize((new_w, row_h), Image.Resampling.LANCZOS)
115
+ resized_row.append(resized)
116
+
117
+ rows_list.append(resized_row)
118
+
119
+ # Crear lienzo en blanco
120
+ total_h = sum(row_heights)
121
+ collage_img = Image.new('RGB', (W, total_h), color=(0, 0, 0))
122
+
123
+ # Pegar imagenes (centrando la ultima fila si quedó pequeña)
124
+ current_y = 0
125
+ for i, row in enumerate(rows_list):
126
+ current_x = 0
127
+ row_h = row_heights[i]
128
+
129
+ row_w = sum([img.width for img in row])
130
+ if row_w < W:
131
+ current_x = (W - row_w) // 2
132
+
133
+ for img in row:
134
+ collage_img.paste(img, (current_x, current_y))
135
+ current_x += img.width
136
+ current_y += row_h
137
+
138
+ # 4. Save Collage
139
+ output_path = os.path.join(COLLAGE_DIR, f"collage_{chat_id}_{int(time.time())}.jpg")
140
+
141
+ # Guardar en executor para no bloquear el loop
142
+ loop = asyncio.get_running_loop()
143
+ await loop.run_in_executor(None, lambda: collage_img.save(output_path, quality=90))
144
+
145
+ # 5. Send Collage
146
+ await status_msg.edit_text("📤 Enviando collage terminado...")
147
+ try:
148
+ await client.send_photo(
149
+ chat_id,
150
+ photo=output_path,
151
+ caption="🖼 **¡Aquí tienes tu Tira Vertical!**"
152
+ )
153
+ except Exception as e_send:
154
+ err_str = str(e_send).lower()
155
+ if "dimension" in err_str or "size" in err_str:
156
+ await status_msg.edit_text("⚠️ El archivo es demasiado largo para Telegram, enviando como Documento...")
157
+ await client.send_document(
158
+ chat_id,
159
+ document=output_path,
160
+ caption="🖼 **¡Aquí tienes tu Tira Vertical en alta calidad!**\n(Enviado como archivo porque es muy largo)"
161
+ )
162
+ else:
163
+ raise e_send
164
+
165
+ # Cleanup final msg
166
+ await status_msg.delete()
167
+
168
+ except Exception as e:
169
+ logger.error(f"Error fatal generando collage: {e}")
170
+ await status_msg.edit_text(f"❌ Ocurrió un error al crear el collage: {e}")
171
+ finally:
172
+ # 6. Cleanup local files
173
+ for path in downloaded_paths:
174
+ if os.path.exists(path):
175
+ try: os.remove(path)
176
+ except: pass
177
+
178
+ if 'output_path' in locals() and os.path.exists(output_path):
179
+ try: os.remove(output_path)
180
+ except: pass
config.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # ==== Directorios del Proyecto ====
4
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
5
+ DATA_DIR = os.path.join(BASE_DIR, "data")
6
+
7
+ # Crear directorios si no existen
8
+ os.makedirs(DATA_DIR, exist_ok=True)
9
+
10
+ # ==== Bot credentials ====
11
+ API_ID = int(os.getenv("API_ID", "33226415"))
12
+ API_HASH = os.getenv("API_HASH", "01999dae3e5348c7ab0dbcc6f7f4edc5")
13
+ BOT_TOKEN = os.getenv("TELEGRAM_TOKEN") or os.getenv("BOT_TOKEN", "8727849761:AAFUxhvDUgPs7huH2sG6vaylCOo4Y_QXOps")
14
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AIzaSyCIY2Wic63XNx-FffapTqqlck0V8M9ivoo")
15
+
16
+ # CHANNEL FOR BACKGROUND CACHER (Optional)
17
+ try:
18
+ DUMP_CHAT_ID = int(os.getenv("DUMP_CHAT_ID", 0))
19
+ if DUMP_CHAT_ID == 0: DUMP_CHAT_ID = None
20
+ except:
21
+ DUMP_CHAT_ID = None
22
+
23
+ # Admin / Creator
24
+ OWNER_ID = 5565051026
25
+
26
+ # Canal de Base de Datos (Respaldo)
27
+ DATABASE_CHANNEL = -1003688499156
28
+
29
+ DB_FILE = os.path.join(DATA_DIR, "descargas.json")
30
+ SESSION_NAME = os.path.join(DATA_DIR, "mi_bot_pro")
31
+
converter.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import img2pdf
2
+ import requests
3
+ import sys
4
+ import json
5
+ import os
6
+ from concurrent.futures import ThreadPoolExecutor
7
+
8
+ def download_image(args):
9
+ url, index, total = args
10
+ try:
11
+ response = requests.get(url, timeout=15, headers={'User-Agent': 'Mozilla/5.0'})
12
+ if response.status_code == 200:
13
+ # Imprimimos progreso para Node.js
14
+ print(f"PROGRESS:IMAGE_DONE", flush=True)
15
+ return index, response.content
16
+ except Exception as e:
17
+ print(f"DEBUG: Error en imagen {index}: {e}", flush=True)
18
+ return index, None
19
+
20
+ def create_pdf(urls, output_name):
21
+ total = len(urls)
22
+ print(f"DEBUG: Iniciando descarga paralela de {total} imágenes...", flush=True)
23
+
24
+ # Descarga en paralelo (50 hilos a la vez para saturar la conexión)
25
+ # Esto es lo que lo hace igual de rápido que el ZIP
26
+ with ThreadPoolExecutor(max_workers=50) as executor:
27
+ results = list(executor.map(download_image, [(url, i, total) for i, url in enumerate(urls)]))
28
+
29
+ # Ordenamos las imágenes por su índice original para que el manga no esté desordenado
30
+ results.sort(key=lambda x: x[0])
31
+ img_data = [data for index, data in results if data is not None]
32
+
33
+ if img_data:
34
+ print("DEBUG: Empaquetando PDF...", flush=True)
35
+ with open(output_name, "wb") as f:
36
+ # img2pdf es ultra rápido porque no re-comprime
37
+ f.write(img2pdf.convert(img_data))
38
+ print("STATUS:SUCCESS", flush=True)
39
+ else:
40
+ print("STATUS:ERROR", flush=True)
41
+
42
+ if __name__ == "__main__":
43
+ try:
44
+ input_data = sys.stdin.read()
45
+ if not input_data:
46
+ sys.exit(1)
47
+ data = json.loads(input_data)
48
+ create_pdf(data['urls'], data['output'])
49
+ except Exception as e:
50
+ print(f"DEBUG: Error crítico: {e}", flush=True)
data/viral_music.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "track_001",
4
+ "name": "Phonk Brazil",
5
+ "artist": "Viral Mix",
6
+ "file_id": null,
7
+ "path": "data/music/phonk_brazil.mp3"
8
+ },
9
+ {
10
+ "id": "track_002",
11
+ "name": "Sigma Theme",
12
+ "artist": "Patrick Bateman",
13
+ "file_id": null,
14
+ "path": "data/music/sigma_theme.mp3"
15
+ },
16
+ {
17
+ "id": "track_003",
18
+ "name": "Cute Anime Sound",
19
+ "artist": "Kawaii",
20
+ "file_id": null,
21
+ "path": "data/music/cute_anime.mp3"
22
+ }
23
+ ]
data/viral_shorts.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "1768257961982",
4
+ "type": "video",
5
+ "file_id": "BAACAgEAAxkBAAIw_WllealMdOlaTYF395msw1PJFUrIAALUCAACizYpRzyS9S-qDqSFHgQ",
6
+ "date": 1768257961,
7
+ "user": 5565051026,
8
+ "caption": "🎬 Oye vaquero.. 😈🤠 #joseroberto @Dam ⋆* ☆* ⋆\n⚙️ 720x1280 | ⏱ 00:00:15"
9
+ }
10
+ ]
database.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from config import DB_FILE, DATA_DIR
4
+
5
+ DB_CACHE = os.path.join(DATA_DIR, "manga_cache.json")
6
+
7
+ # --- VARIABLES GLOBALES (NO BORRAR) ---
8
+ url_storage = {}
9
+ user_config = {}
10
+ active_downloads = {} # {chat_id: {msg_id: future/task}}
11
+ task_progress = {} # {chat_id: {msg_id: {percent, speed, status, name, url}}}
12
+
13
+ # --- FUNCIONES ---
14
+
15
+ def get_config(chat_id):
16
+ if chat_id not in user_config:
17
+ user_config[chat_id] = {
18
+ 'lang': 'es',
19
+ 'manga_doc_mode': False,
20
+ 'manga_group_mode': True,
21
+ 'manga_hd_mode': True
22
+ }
23
+ return user_config[chat_id]
24
+
25
+ def add_active(chat_id, msg_id, task=None, pid=None):
26
+ if chat_id not in active_downloads:
27
+ active_downloads[chat_id] = {}
28
+ active_downloads[chat_id][msg_id] = {'task': task, 'pid': pid}
29
+
30
+ def remove_active(chat_id, msg_id):
31
+ if chat_id in active_downloads and msg_id in active_downloads[chat_id]:
32
+ del active_downloads[chat_id][msg_id]
33
+ if not active_downloads[chat_id]:
34
+ del active_downloads[chat_id]
35
+ remove_progress(chat_id, msg_id)
36
+
37
+ # --- FUNCIONES DE PROGRESO (TRACKING EN VIVO) ---
38
+
39
+ def update_progress(chat_id, msg_id, percent=None, speed=None, status=None, name=None, url=None):
40
+ if chat_id not in task_progress:
41
+ task_progress[chat_id] = {}
42
+ if msg_id not in task_progress[chat_id]:
43
+ task_progress[chat_id][msg_id] = {'percent': 0, 'speed': 'N/A', 'status': 'Esperando', 'name': 'Archivo', 'url': 'N/A'}
44
+
45
+ if percent is not None: task_progress[chat_id][msg_id]['percent'] = percent
46
+ if speed is not None: task_progress[chat_id][msg_id]['speed'] = speed
47
+ if status is not None: task_progress[chat_id][msg_id]['status'] = status
48
+ if name is not None: task_progress[chat_id][msg_id]['name'] = name
49
+ if url is not None: task_progress[chat_id][msg_id]['url'] = url
50
+
51
+ def get_all_progress():
52
+ return task_progress
53
+
54
+ def remove_progress(chat_id, msg_id):
55
+ if chat_id in task_progress and msg_id in task_progress[chat_id]:
56
+ del task_progress[chat_id][msg_id]
57
+ if not task_progress[chat_id]:
58
+ del task_progress[chat_id]
59
+
60
+ async def cancel_all(chat_id):
61
+ cancelled_items = []
62
+ if chat_id in active_downloads:
63
+ tasks_map = active_downloads[chat_id]
64
+
65
+ for mid, info in tasks_map.items():
66
+ if isinstance(info, dict):
67
+ task = info.get('task')
68
+ pid = info.get('pid')
69
+ else:
70
+ task = info
71
+ pid = None
72
+
73
+ url = "Enlace desconocido"
74
+ if chat_id in task_progress and mid in task_progress[chat_id]:
75
+ url = task_progress[chat_id][mid].get('url', 'Enlace desconocido')
76
+
77
+ cancelled_items.append({'url': url, 'msg_id': mid})
78
+
79
+ if task and not task.done():
80
+ task.cancel()
81
+
82
+ if pid:
83
+ try:
84
+ import signal
85
+ os.kill(pid, signal.SIGTERM)
86
+ except:
87
+ pass
88
+
89
+ active_downloads.pop(chat_id, None)
90
+ task_progress.pop(chat_id, None)
91
+
92
+ return cancelled_items
debug_firestore.ts ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { initializeApp } from "firebase/app";
3
+ import { getFirestore, collection, getDocs, orderBy, query } from "firebase/firestore";
4
+
5
+ const firebaseConfig = {
6
+ apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
7
+ authDomain: "twistedbrody-9d163.firebaseapp.com",
8
+ projectId: "twistedbrody-9d163",
9
+ storageBucket: "twistedbrody-9d163.firebasestorage.app",
10
+ messagingSenderId: "733213514129",
11
+ appId: "1:733213514129:web:e9694684f5c3994ed06230",
12
+ measurementId: "G-N8TQ7MY42W"
13
+ };
14
+
15
+ const app = initializeApp(firebaseConfig);
16
+ const db = getFirestore(app);
17
+
18
+ async function checkDB() {
19
+ console.log("--- DEBUGGING FIRESTORE ---");
20
+ try {
21
+ const mangasRef = collection(db, 'mangas');
22
+
23
+ // 1. Count Total (Raw)
24
+ const snapshotRaw = await getDocs(mangasRef);
25
+ console.log(`[RAW CHECK] Total Documents in 'mangas': ${snapshotRaw.size}`);
26
+
27
+ if (snapshotRaw.size > 0) {
28
+ console.log("Sample ID:", snapshotRaw.docs[0].id);
29
+ console.log("Sample Data:", snapshotRaw.docs[0].data());
30
+ }
31
+
32
+ // 2. Count with Query (orderBy)
33
+ try {
34
+ const q = query(mangasRef, orderBy('created_at', 'desc'));
35
+ const snapshotQuery = await getDocs(q);
36
+ console.log(`[QUERY CHECK] Documents with orderBy('created_at'): ${snapshotQuery.size}`);
37
+ } catch (e) {
38
+ console.error("[QUERY FAIL] orderBy failed. Likely missing index or field:", e.message);
39
+ }
40
+
41
+ } catch (error) {
42
+ console.error("CRITICAL ERROR:", error);
43
+ }
44
+ }
45
+
46
+ checkDB();
deploy_git.bat ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo Inicializando repositorio...
3
+ git init
4
+ echo Configurando usuario...
5
+ git config user.name "CodeByDante"
6
+ git config user.email "codebydante@users.noreply.github.com"
7
+ echo Añadiendo archivos...
8
+ git add .
9
+ echo Committing...
10
+ git commit -m "feat: Update Project via Agent"
11
+ echo Configurando rama y remote...
12
+ git branch -M main
13
+ git remote remove origin
14
+ git remote add origin https://github.com/CodeByDante/twisted-brody-MangaFlow.git
15
+ echo Intentando push (puede requerir autenticacion)...
16
+ git push -u origin main --force
17
+ pause
eslint.config.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js';
2
+ import globals from 'globals';
3
+ import reactHooks from 'eslint-plugin-react-hooks';
4
+ import reactRefresh from 'eslint-plugin-react-refresh';
5
+ import tseslint from 'typescript-eslint';
6
+
7
+ export default tseslint.config(
8
+ { ignores: ['dist'] },
9
+ {
10
+ extends: [js.configs.recommended, ...tseslint.configs.recommended],
11
+ files: ['**/*.{ts,tsx}'],
12
+ languageOptions: {
13
+ ecmaVersion: 2020,
14
+ globals: globals.browser,
15
+ },
16
+ plugins: {
17
+ 'react-hooks': reactHooks,
18
+ 'react-refresh': reactRefresh,
19
+ },
20
+ rules: {
21
+ ...reactHooks.configs.recommended.rules,
22
+ 'react-refresh/only-export-components': [
23
+ 'warn',
24
+ { allowConstantExport: true },
25
+ ],
26
+ },
27
+ }
28
+ );
firebase_credentials.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "waifuofbrody",
4
+ "private_key_id": "75e8653e118381202e6ed64758fd61c3a9bfeb77",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC6PzcP5kBFPPEr\n4uelvIKvbVHbesh6KQnsXS/iUnxHoM1g6fSYJHZA7xvqSrETKOjnYSbys8lUG9V2\ntrlhnnxRFD/v7T26hjefEc5AoO1f8wgtJg/Pq+xGSaeXVf67ZCIq893Zb5tNlFKS\nqsqS555syNEuXLRYL7lO1oIr75vXSaKRk26yyCmtVuH2iZnyDbvdvgDzRsUf638h\nnWnYpQtDE0Fp/PSur8JZ7JZ4J0VFlq9xUvYRzaLp3wPIV9E+uNucizUzD2hoKIhN\nEzZZ7XJIhIyJPwyglMILAVAi2FN46B/NHJ88Y0UJFRe6rayXeMPAEZLM9VUCJ3jV\nYNPAxLQDAgMBAAECggEAGNnDdo8h5zsk8NajUwVuqIqdH/xnkIk2Rj/+2iNoasRF\ncxd0Z/KBhtOAtYfGzcgpH2pioIKlq9/U4TSrUp+rdcQObeyJToCHHmXpT81JLwLG\nBgQsmuiVK6G7R2GVjhpjxrhoUxFltvnB9MjuI6DdDiXTZ2y+MYAYqTDNCKC9egGh\nvnmitUnVS+zEBKztWy5cKUdY7Nlq2dvmsWY2+HFmoIrpEnYPikQ8oLViiByWtvUb\nO2mHtTKg61K9LGlqVs7ScZwWazDGVD/GEk+hzDy69xVpWGUKBVa94246EnEvSS+f\nRgZ/8BR3zilfF9PPx4YaEsHyP8MhUMKPYwKwABI+HQKBgQD/eBKNnnHHpWjupkV4\nSn9Iq+P+OJHmtmHqB8z+i+CkppULpZij6TQfzR6fHiQzoFJOK4hsW9ccsJH0ZMjL\nohvNq9e6Oui5c5EzTvRdCXXbjl3tM92T/nMBunMkfXjcsgzazoCN4bOXk/qGc45s\nRhuzNeGYeODSKuP31Cwb82SJVQKBgQC6ok/Dnac10T2vHi1iKPZw+vlultz8LWmn\n6o0tUaU0p3wgy4Q9jpzK6G/HnjDy4+hJx0irCMnNcCElmsjN89IUaYF2Ve39ofy3\n7Uf2lD08l9uxl624y1RY7ExBq79ZboyuNODlSs6YjQgHU1yuzv0F+bZHemBGIGmL\nDw0UHXdn9wKBgDDzwypb6BWHfpnsRneMXuN//IokMODypcSAhiloiD1Epl669orC\nDvjhBzMaRXmXCO5trRCGcKvQsccQ4OEUSRuaCBZpX1rZ6ELaqDyDqY/OsfTX8WeA\nZG06WwHtARHZFFmBJGULkKxE8MZ+shXRQVGPy5C56OqcyV4dy+33L5aZAoGAcZvY\nXkWbwcDrgawnCDfTPJcqO02Om9uxE0xOQCYRIOpLP1Nj3mzvuPyg/qynM1PU1QSA\nkcy5u1rkcpW0YtpnKZHIAxbv1pNC2VuRkOJQHJB8ZbDlSTZM1AyTpu47ft8yt+Ds\nfed5t5cyKfNu2eKaV4bYlM5DyKx2UvYIihQd2aUCgYAp4ibh6gAebD35facfE3J4\n8OmjYeRGurHnhcm0j3TH5nXWPVwNo6IZS56Qbu975GSSRpJEORWhk4rv+bV5VWUV\n3shdshU+Q41VJCssJ5x3Q9MCoYt6WOdndYc2vuhKuC+7HwVLA0e16+iRu+VxPvA0\neNlgWfKUXedSIrFc5lLKZg==\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "firebase-adminsdk-fbsvc@waifuofbrody.iam.gserviceaccount.com",
7
+ "client_id": "114846004229150488678",
8
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
9
+ "token_uri": "https://oauth2.googleapis.com/token",
10
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40waifuofbrody.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
firebase_service.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import firebase_admin
2
+ from firebase_admin import credentials, firestore
3
+ import os
4
+ import json
5
+ import asyncio
6
+
7
+ # Variable global para el cliente de Firestore
8
+ db = None
9
+
10
+ def init_firebase():
11
+ global db
12
+ if db is not None:
13
+ return db
14
+
15
+ try:
16
+ # 1. Intentar cargar desde variable de entorno (JSON RAW)
17
+ firebase_json = os.environ.get("FIREBASE_JSON")
18
+
19
+ # 2. Si no es JSON raw, intentar ruta de archivo
20
+ if not firebase_json:
21
+ cred_path = os.environ.get("FIREBASE_CREDENTIALS", "firebase_credentials.json")
22
+ if os.path.exists(cred_path):
23
+ cred = credentials.Certificate(cred_path)
24
+ else:
25
+ print("⚠️ [Firebase] No se encontraron credenciales (FIREBASE_JSON ni archivo).")
26
+ return None
27
+ else:
28
+ # Parsear el JSON del string
29
+ try:
30
+ cred_dict = json.loads(firebase_json)
31
+ cred = credentials.Certificate(cred_dict)
32
+ except Exception as e:
33
+ print(f"❌ [Firebase] Error parseando FIREBASE_JSON: {e}")
34
+ return None
35
+
36
+ # Inicializar App
37
+ if not firebase_admin._apps:
38
+ firebase_admin.initialize_app(cred)
39
+
40
+ db = firestore.client()
41
+ print("🔥 [Firebase] Conectado exitosamente a Firestore.")
42
+ return db
43
+
44
+ except Exception as e:
45
+ print(f"❌ [Firebase] Error inicializando: {e}")
46
+ return None
47
+
48
+ # Inicializar al importar (o llamar explícitamente en main)
49
+ init_firebase()
50
+
51
+ from config import BOT_TOKEN
52
+
53
+ # Segregar cache por Bot ID para evitar conflictos al cambiar de bot
54
+ BOT_ID = BOT_TOKEN.split(":")[0] if ":" in BOT_TOKEN else "global"
55
+ CACHE_COLLECTION = f"media_cache_{BOT_ID}"
56
+
57
+ async def get_cached_file(video_id, quality):
58
+ """
59
+ Busca en la colección del bot actual si existe el file_id.
60
+ Retorna el file_id o None.
61
+ """
62
+ if not db: return None
63
+
64
+ try:
65
+ # Usamos el video_id como ID del documento para búsqueda rápida O(1)
66
+ doc_ref = db.collection(CACHE_COLLECTION).document(str(video_id))
67
+
68
+ loop = asyncio.get_running_loop()
69
+ # FIX: Añadir timeout de 5s para evitar hanging si Firebase falla
70
+ try:
71
+ doc = await asyncio.wait_for(loop.run_in_executor(None, doc_ref.get), timeout=5.0)
72
+ except asyncio.TimeoutError:
73
+ print(f"⚠️ [Firebase] Cache Read Timeout ({video_id}) - Saltando cache.")
74
+ return None
75
+
76
+ if doc.exists:
77
+ data = doc.to_dict()
78
+ # data estructura: {'mp3': 'file_id_1', '720': 'file_id_2', ...}
79
+ return data.get(quality)
80
+ return None
81
+ except Exception as e:
82
+ print(f"⚠️ [Firebase] Error leyendo cache: {e}")
83
+ return None
84
+
85
+ async def get_cached_data(video_id):
86
+ """
87
+ Retorna el documento completo del cache (incluyendo meta y todos los formatos).
88
+ """
89
+ if not db: return None
90
+ try:
91
+ doc_ref = db.collection(CACHE_COLLECTION).document(str(video_id))
92
+ loop = asyncio.get_running_loop()
93
+ doc = await loop.run_in_executor(None, doc_ref.get)
94
+
95
+ if doc.exists: return doc.to_dict()
96
+ except Exception as e:
97
+ print(f"⚠️ [Firebase] Error leyendo data cache: {e}")
98
+ return None
99
+
100
+ async def save_cached_file(video_id, quality, file_id, meta=None):
101
+ """
102
+ Guarda o actualiza el file_id para una calidad dada.
103
+ """
104
+ if not db: return
105
+
106
+ try:
107
+ doc_ref = db.collection(CACHE_COLLECTION).document(str(video_id))
108
+
109
+ # Usamos set con merge=True para no borrar otras calidades
110
+ update_data = {
111
+ quality: file_id,
112
+ 'last_updated': firestore.SERVER_TIMESTAMP
113
+ }
114
+
115
+ if meta:
116
+ update_data['meta'] = meta # Título, duración, etc si queremos guardar info extra
117
+
118
+ loop = asyncio.get_running_loop()
119
+ await loop.run_in_executor(None, lambda: doc_ref.set(update_data, merge=True))
120
+
121
+ print(f"🔥 [Firebase] Cache guardado: {video_id} [{quality}]")
122
+ except Exception as e:
123
+ print(f"❌ [Firebase] Error guardando cache: {e}")
124
+
125
+ # --- STRICT CACHE LOGIC (URL + Quality + DocMode) ---
126
+ import hashlib
127
+
128
+ def _compute_variant_key(url, quality, is_doc):
129
+ """Genera un hash único basado en los parámetros estrictos."""
130
+
131
+ # Eporner Direct Link Normalization:
132
+ # URL style: https://www.eporner.com/dload/VIDEO_ID/QUALITY/TOKEN-filename.mp4
133
+ # We want to key ONLY by VIDEO_ID + QUALITY to allow cache hits even if token changes.
134
+ if "eporner.com/dload/" in url:
135
+ try:
136
+ # Extract ID usually after /dload/
137
+ parts = url.split('/dload/')
138
+ if len(parts) > 1:
139
+ # Part 1 is video_id: 2pBe2ZZDqtG
140
+ vid_id_clean = parts[1].split('/')[0]
141
+ # Use this clean ID as the 'url' for the key
142
+ url = f"eporner_{vid_id_clean}"
143
+ except: pass
144
+
145
+ raw = f"{url}|{quality}|{str(is_doc).lower()}"
146
+ return hashlib.sha256(raw.encode()).hexdigest()
147
+
148
+ async def get_cached_file_strict(video_id, url, quality, is_doc):
149
+ """
150
+ Busca una variante exacta en el documento del video.
151
+ """
152
+ if not db: return None
153
+ try:
154
+ doc_ref = db.collection(CACHE_COLLECTION).document(str(video_id))
155
+ loop = asyncio.get_running_loop()
156
+ try:
157
+ doc = await asyncio.wait_for(loop.run_in_executor(None, doc_ref.get), timeout=5.0)
158
+ except asyncio.TimeoutError:
159
+ return None
160
+
161
+ if doc.exists:
162
+ data = doc.to_dict()
163
+ variants = data.get('variants', {})
164
+ v_key = _compute_variant_key(url, quality, is_doc)
165
+
166
+ # DEBUG
167
+ print(f"🔍 [Firebase Debug] Key: {v_key} | Variants: {list(variants.keys())}")
168
+
169
+ variant = variants.get(v_key)
170
+ if variant:
171
+ print(f"✨ [Firebase] Cache Estricto ENCONTRADO: {video_id}")
172
+ return variant.get('file_id')
173
+
174
+ return None
175
+ except Exception as e:
176
+ print(f"⚠️ [Firebase] Error leyendo cache estricto: {e}")
177
+ return None
178
+
179
+ async def save_cached_file_strict(video_id, url, quality, is_doc, file_id, meta=None):
180
+ """
181
+ Guarda una variante estricta en el documento.
182
+ """
183
+ if not db: return
184
+ try:
185
+ doc_ref = db.collection(CACHE_COLLECTION).document(str(video_id))
186
+ v_key = _compute_variant_key(url, quality, is_doc)
187
+
188
+ variant_data = {
189
+ 'file_id': file_id,
190
+ 'url': url,
191
+ 'quality': quality,
192
+ 'is_doc': is_doc,
193
+ 'saved_at': firestore.SERVER_TIMESTAMP
194
+ }
195
+
196
+ # Validar meta
197
+ if meta and isinstance(meta, dict):
198
+ # Limpiar meta para evitar recursión o datos corruptos
199
+ safe_meta = {k: v for k, v in meta.items() if isinstance(v, (str, int, float, bool))}
200
+ variant_data['meta'] = safe_meta
201
+
202
+ # Update map inside map: {'variants': {hash: {...}}}
203
+ loop = asyncio.get_running_loop()
204
+
205
+ # 1. Leer data actual para no sobreescribir otras variantes si set(merge=True) no es suficiente para deep merges de maps
206
+ # Firestore merge de mapas reemplaza todo el mapa si no usas notación de puntos.
207
+ # FIX: Usar diccionario anidado para set(merge=True) en Python para asegurar merge correcto
208
+
209
+ update_payload = {
210
+ 'variants': {
211
+ v_key: variant_data
212
+ },
213
+ 'last_updated': firestore.SERVER_TIMESTAMP
214
+ }
215
+
216
+ if meta:
217
+ update_payload['global_meta'] = meta # Meta general (ej titulo) solo lo último
218
+
219
+ await loop.run_in_executor(None, lambda: doc_ref.set(update_payload, merge=True))
220
+
221
+ print(f"🔥 [Firebase] Cache Estricto Guardado: {video_id} [Q:{quality} D:{is_doc}]")
222
+ except Exception as e:
223
+ print(f"❌ [Firebase] Error guardando cache estricto: {e}")
224
+
225
+ async def delete_cached_file(video_id):
226
+ """
227
+ Elimina un archivo del cache (útil si el link expira o es inválido).
228
+ """
229
+ if not db: return
230
+ try:
231
+ doc_ref = db.collection(CACHE_COLLECTION).document(str(video_id))
232
+ loop = asyncio.get_running_loop()
233
+ await loop.run_in_executor(None, doc_ref.delete)
234
+ print(f"🗑 [Firebase] Cache eliminado: {video_id}")
235
+ except Exception as e:
236
+ print(f"⚠️ [Firebase] Error eliminando cache: {e}")
237
+
238
+ async def get_bot_config():
239
+ """
240
+ Obtiene la configuración global del bot (ej: canal de backup).
241
+ Retorna un dict con las keys.
242
+ """
243
+ if not db: return {}
244
+ try:
245
+ doc_ref = db.collection('bot_settings').document('global_config')
246
+ loop = asyncio.get_running_loop()
247
+ doc = await loop.run_in_executor(None, doc_ref.get)
248
+
249
+ if doc.exists:
250
+ return doc.to_dict()
251
+ return {}
252
+ except Exception as e:
253
+ print(f"⚠️ [Firebase] Error leyendo config global: {e}")
254
+ return {}
255
+
256
+ async def save_bot_config(key, value):
257
+ """
258
+ Guarda una key especifica en la configuración global.
259
+ """
260
+ if not db: return False
261
+ try:
262
+ doc_ref = db.collection('bot_settings').document('global_config')
263
+
264
+ loop = asyncio.get_running_loop()
265
+ await loop.run_in_executor(None, lambda: doc_ref.set({key: value}, merge=True))
266
+
267
+ print(f"🔥 [Firebase] Config guardada: {key} = {value}")
268
+ return True
269
+ except Exception as e:
270
+ print(f"❌ [Firebase] Error guardando config global: {e}")
271
+ return False
272
+
273
+ async def load_all_user_configs():
274
+ """Carga todas las configs de usuarios desde Firestore."""
275
+ if not db: return {}
276
+ try:
277
+ # Ejecutar en thread pool para no bloquear
278
+ loop = asyncio.get_running_loop()
279
+ docs = await loop.run_in_executor(None, lambda: db.collection('user_configs').stream())
280
+
281
+ # Stream devuelve un generador, iterarlo puede bloquear si son muchos,
282
+ # pero es necesario para poblar la RAM inicial.
283
+ data = {}
284
+ for doc in docs:
285
+ try:
286
+ data[int(doc.id)] = doc.to_dict()
287
+ except: pass
288
+ print(f"🔥 [Firebase] Configs cargadas: {len(data)} usuarios.")
289
+ return data
290
+ except Exception as e:
291
+ print(f"⚠️ [Firebase] Config Load Error: {e}")
292
+ return {}
293
+
294
+ async def save_user_config_fb(chat_id, config_data):
295
+ """Guarda/Actualiza la config de un usuario."""
296
+ if not db: return
297
+ try:
298
+ # Fire-and-forget sync wrapper
299
+ loop = asyncio.get_running_loop()
300
+ await loop.run_in_executor(None, lambda: db.collection('user_configs').document(str(chat_id)).set(config_data, merge=True))
301
+ except Exception as e:
302
+ print(f"❌ [Firebase] Save Config Error: {e}")
303
+
304
+ async def load_all_hashtags():
305
+ """Carga todos los hashtags."""
306
+ if not db: return {}
307
+ try:
308
+ loop = asyncio.get_running_loop()
309
+ docs = await loop.run_in_executor(None, lambda: db.collection('hashtags').stream())
310
+
311
+ data = {}
312
+ for doc in docs:
313
+ data[doc.id] = doc.to_dict().get('msgs', [])
314
+ print(f"🔥 [Firebase] Hashtags cargados: {len(data)} tags.")
315
+ return data
316
+ except Exception as e:
317
+ print(f"⚠️ [Firebase] Tags Load Error: {e}")
318
+ return {}
319
+
320
+ async def save_hashtag_fb(tag, msgs_list):
321
+ if not db: return
322
+ try:
323
+ loop = asyncio.get_running_loop()
324
+ await loop.run_in_executor(None, lambda: db.collection('hashtags').document(tag).set({'msgs': msgs_list}, merge=True))
325
+ except Exception as e:
326
+ print(f"❌ [Firebase] Save Tag Error: {e}")
327
+
328
+ async def register_user(user_id, first_name, username):
329
+ """
330
+ Registra al usuario, cuenta el total y detecta cambio de nombre.
331
+ Retorna: (is_new, count, name_changed)
332
+ """
333
+ if not db: return (False, 0, False) # Fallback
334
+
335
+ try:
336
+ # Referencias
337
+ user_ref = db.collection('user_configs').document(str(user_id))
338
+ stats_ref = db.collection('bot_settings').document('stats')
339
+
340
+ # Ejecutar transacción (pseudo-transacción para simplificar en async wrapper)
341
+ # Nota: Firestore async de python no soporta transactions con await facil dentro de lambda
342
+ # Haremos una logica optimista/separada por simplicidad y velocidad
343
+
344
+ # 1. Obtener User
345
+ loop = asyncio.get_running_loop()
346
+ doc = await loop.run_in_executor(None, user_ref.get)
347
+
348
+ if not doc.exists:
349
+ # --- NUEVO USUARIO ---
350
+ # 1. Incrementar contador global
351
+ try:
352
+ # Lectura + Escritura (Riesgo bajo de colision en low traffic)
353
+ st_doc = await loop.run_in_executor(None, stats_ref.get)
354
+ current_count = st_doc.to_dict().get('user_count', 0) if st_doc.exists else 0
355
+ new_count = current_count + 1
356
+ await loop.run_in_executor(None, lambda: stats_ref.set({'user_count': new_count}, merge=True))
357
+ except:
358
+ new_count = 1 # Fallback
359
+
360
+ # 2. Guardar Usuario
361
+ user_data = {
362
+ 'first_name': first_name,
363
+ 'username': username,
364
+ 'joined_at': firestore.SERVER_TIMESTAMP,
365
+ 'user_id': user_id
366
+ }
367
+ await loop.run_in_executor(None, lambda: user_ref.set(user_data, merge=True))
368
+ return (True, new_count, False)
369
+
370
+ else:
371
+ # --- USUARIO EXISTENTE ---
372
+ data = doc.to_dict()
373
+ old_name = data.get('first_name', '')
374
+
375
+ # Detectar cambio de nombre
376
+ if old_name != first_name:
377
+ await loop.run_in_executor(None, lambda: user_ref.set({'first_name': first_name, 'username': username}, merge=True))
378
+ return (False, 0, True)
379
+
380
+ return (False, 0, False)
381
+
382
+ except Exception as e:
383
+ print(f"⚠️ [Firebase] Register Error: {e}")
384
+ return (False, 0, False)
385
+
386
+ async def get_global_stats():
387
+ """Retorna el diccionario de stats (ej: user_count)."""
388
+ if not db: return {}
389
+ try:
390
+ doc_ref = db.collection('bot_settings').document('stats')
391
+ loop = asyncio.get_running_loop()
392
+ doc = await loop.run_in_executor(None, doc_ref.get)
393
+
394
+ if doc.exists: return doc.to_dict()
395
+ return {}
396
+ except: return {}
397
+
398
+ # --- USER RULES (Memoria a largo plazo) ---
399
+ async def get_user_rules_fb(user_id, persona_id="nsfw"):
400
+ """Retorna la lista de reglas de un usuario para una personalidad específica."""
401
+ if not db: return []
402
+ try:
403
+ doc_ref = db.collection('user_rules').document(str(user_id))
404
+ loop = asyncio.get_running_loop()
405
+ doc = await loop.run_in_executor(None, doc_ref.get)
406
+
407
+ if doc.exists:
408
+ data = doc.to_dict()
409
+ # MIGRATION CHECK: If 'rules' is at top level, it's legacy
410
+ if 'rules' in data and isinstance(data['rules'], list):
411
+ # Assume legacy rules belong to 'nsfw' or default
412
+ legacy = data.pop('rules')
413
+ if 'nsfw' not in data: data['nsfw'] = {'rules': legacy}
414
+ else: data['nsfw']['rules'].extend(legacy)
415
+
416
+ # Save migration async
417
+ await loop.run_in_executor(None, lambda: doc_ref.set(data, merge=True))
418
+
419
+ # Retrieve persona rules
420
+ p_data = data.get(persona_id, {})
421
+ return p_data.get('rules', [])
422
+
423
+ return []
424
+ except Exception as e:
425
+ print(f"⚠️ [Firebase] Error leyendo reglas ({persona_id}): {e}")
426
+ return []
427
+
428
+ async def save_user_rule_fb(user_id, rule_text, action="add", persona_id="nsfw"):
429
+ """Guarda, elimina o limpia reglas de un usuario (Scoped by Persona)."""
430
+ if not db: return False
431
+ try:
432
+ doc_ref = db.collection('user_rules').document(str(user_id))
433
+ loop = asyncio.get_running_loop()
434
+
435
+ # Leemos primero para modificar la lista
436
+ doc = await loop.run_in_executor(None, doc_ref.get)
437
+ data = doc.to_dict() if doc.exists else {}
438
+
439
+ # MIGRATION ON SAVE
440
+ if 'rules' in data and isinstance(data['rules'], list):
441
+ legacy = data.pop('rules')
442
+ if 'nsfw' not in data: data['nsfw'] = {'rules': legacy}
443
+ else: data['nsfw']['rules'].extend(legacy)
444
+
445
+ # Get target list
446
+ if persona_id not in data: data[persona_id] = {'rules': []}
447
+ current_rules = data[persona_id].get('rules', [])
448
+
449
+ changed = False
450
+ if action == "add":
451
+ if rule_text not in current_rules:
452
+ current_rules.append(rule_text)
453
+ changed = True
454
+ elif action == "remove":
455
+ # Loose match or exact? Exact for now
456
+ if rule_text in current_rules:
457
+ current_rules = [r for r in current_rules if r != rule_text]
458
+ changed = True
459
+ elif action == "clear":
460
+ current_rules = []
461
+ changed = True
462
+
463
+ if changed:
464
+ data[persona_id]['rules'] = current_rules
465
+ await loop.run_in_executor(None, lambda: doc_ref.set(data, merge=True))
466
+ print(f"🔥 [Firebase] Reglas actualizadas user {user_id} [{persona_id}]: {action}")
467
+ return True
468
+ return True
469
+ except Exception as e:
470
+ print(f"❌ [Firebase] Error guardando regla ({persona_id}): {e}")
471
+ return False
472
+
473
+ # --- GLOBAL PERSONAS (SHARED) ---
474
+ async def save_global_persona(pid, data):
475
+ """Guarda una personalidad global (Nombre, Prompt, Imágenes)."""
476
+ if not db: return
477
+ try:
478
+ # Use a separate collection for scalable global personas
479
+ doc_ref = db.collection('global_personas').document(str(pid))
480
+ loop = asyncio.get_running_loop()
481
+ await loop.run_in_executor(None, lambda: doc_ref.set(data, merge=True))
482
+ print(f"🌍 [Firebase] Personalidad Global Guardada: {pid}")
483
+ except Exception as e:
484
+ print(f"❌ [Firebase] Error guardando global persona: {e}")
485
+
486
+ async def get_all_global_personas():
487
+ """Retorna todas las personalidades globales {pid: data}."""
488
+ if not db: return {}
489
+ try:
490
+ loop = asyncio.get_running_loop()
491
+ docs = await loop.run_in_executor(None, lambda: db.collection('global_personas').stream())
492
+
493
+ data = {}
494
+ for doc in docs:
495
+ data[doc.id] = doc.to_dict()
496
+ return data
497
+ except Exception as e:
498
+ print(f"⚠️ [Firebase] Global Personas Load Error: {e}")
499
+ return {}
500
+
501
+ async def delete_global_persona_fb(pid):
502
+ """Elimina una personalidad global."""
503
+ if not db: return
504
+ try:
505
+ doc_ref = db.collection('global_personas').document(str(pid))
506
+ loop = asyncio.get_running_loop()
507
+ await loop.run_in_executor(None, doc_ref.delete)
508
+ print(f"🗑 [Firebase] Personalidad Global Eliminada: {pid}")
509
+ except Exception as e:
510
+ print(f"❌ [Firebase] Error eliminando global persona: {e}")
511
+
512
+ # --- CLOUD BODY (AVATARS) ---
513
+ async def save_persona_image(persona_id, outfit_id, emotion_id, file_id):
514
+ """
515
+ Guarda un File ID de Telegram en la colección de avatares.
516
+ Estructura: avatars/{persona_id} -> {outfit_id}: {emotion_id: [file_ids]}
517
+ """
518
+ if not db: return False
519
+ try:
520
+ doc_ref = db.collection('avatars').document(str(persona_id))
521
+
522
+ loop = asyncio.get_running_loop()
523
+ doc = await loop.run_in_executor(None, doc_ref.get)
524
+
525
+ data = doc.to_dict() if doc.exists else {}
526
+
527
+ # Estructura profunda: data[outfit][emotion] = list
528
+ if outfit_id not in data: data[outfit_id] = {}
529
+ if emotion_id not in data[outfit_id]: data[outfit_id][emotion_id] = []
530
+
531
+ # Evitar duplicados exactos
532
+ if file_id not in data[outfit_id][emotion_id]:
533
+ data[outfit_id][emotion_id].append(file_id)
534
+
535
+ # Guardar
536
+ await loop.run_in_executor(None, lambda: doc_ref.set(data, merge=True))
537
+ print(f"🔥 [Firebase] Avatar Saved: {persona_id}/{outfit_id}/{emotion_id}")
538
+ return True
539
+
540
+ return True # Ya existía
541
+ except Exception as e:
542
+ print(f"❌ [Firebase] Avatar Save Error: {e}")
543
+ return False
544
+
545
+ async def get_persona_images(persona_id, outfit_id, emotion_id):
546
+ """
547
+ Retorna la lista de File IDs para una combinación específica.
548
+ """
549
+ if not db: return []
550
+ try:
551
+ doc_ref = db.collection('avatars').document(str(persona_id))
552
+ loop = asyncio.get_running_loop()
553
+ doc = await loop.run_in_executor(None, doc_ref.get)
554
+
555
+ if doc.exists:
556
+ data = doc.to_dict()
557
+ outfit_data = data.get(outfit_id, {})
558
+ images = outfit_data.get(emotion_id, [])
559
+ return images
560
+ return []
561
+ except Exception as e:
562
+ print(f"⚠️ [Firebase] Avatar Read Error: {e}")
563
+ return []
564
+
565
+ async def get_all_avatars(persona_id):
566
+ """Retorna toda la estructura de avatares de una persona."""
567
+ if not db: return {}
568
+ try:
569
+ doc_ref = db.collection('avatars').document(str(persona_id))
570
+ loop = asyncio.get_running_loop()
571
+ doc = await loop.run_in_executor(None, doc_ref.get)
572
+ return doc.to_dict() if doc.exists else {}
573
+ except: return {}
574
+
575
+ async def delete_persona_image(persona_id, outfit_id, emotion_id, file_id_target):
576
+ """
577
+ Elimina una imagen específica (por file_id) de la lista.
578
+ file_id_target puede ser string o dict {'id':...}
579
+ """
580
+ if not db: return False
581
+ try:
582
+ doc_ref = db.collection('avatars').document(str(persona_id))
583
+ loop = asyncio.get_running_loop()
584
+ doc = await loop.run_in_executor(None, doc_ref.get)
585
+
586
+ if not doc.exists: return False
587
+
588
+ data = doc.to_dict()
589
+
590
+ if outfit_id not in data or emotion_id not in data[outfit_id]:
591
+ return False
592
+
593
+ current_list = data[outfit_id][emotion_id]
594
+
595
+ # Filtrar
596
+ new_list = []
597
+ found = False
598
+ target_str = file_id_target
599
+ if isinstance(file_id_target, dict): target_str = file_id_target.get('id')
600
+
601
+ for item in current_list:
602
+ item_id = item
603
+ if isinstance(item, dict): item_id = item.get('id')
604
+
605
+ if item_id == target_str:
606
+ found = True
607
+ else:
608
+ new_list.append(item)
609
+
610
+ if found:
611
+ data[outfit_id][emotion_id] = new_list
612
+ await loop.run_in_executor(None, lambda: doc_ref.set(data))
613
+ print(f"🗑 [Firebase] Avatar Deleted: {target_str}")
614
+ return True
615
+
616
+ return False
617
+ except Exception as e:
618
+ print(f"❌ [Firebase] Avatar Delete Error: {e}")
619
+ return False
620
+
621
+ # --- VIRAL SHORTS PERSISTENCE ---
622
+ async def save_viral_item_fb(item):
623
+ """Guarda un item viral en la colección 'viral_shorts'."""
624
+ if not db: return False
625
+ try:
626
+ # Usa el ID del item como ID del documento
627
+ doc_ref = db.collection('viral_shorts').document(str(item['id']))
628
+ loop = asyncio.get_running_loop()
629
+ await loop.run_in_executor(None, lambda: doc_ref.set(item, merge=True))
630
+ print(f"🔥 [Firebase] Viral Item Saved: {item['id']}")
631
+ return True
632
+ except Exception as e:
633
+ print(f"❌ [Firebase] Viral Save Error: {e}")
634
+ return False
635
+
636
+ async def delete_viral_item_fb(item_id):
637
+ """Elimina un item viral de la colección."""
638
+ if not db: return False
639
+ try:
640
+ doc_ref = db.collection('viral_shorts').document(str(item_id))
641
+ loop = asyncio.get_running_loop()
642
+ await loop.run_in_executor(None, doc_ref.delete)
643
+ print(f"🗑 [Firebase] Viral Item Deleted: {item_id}")
644
+ return True
645
+ except Exception as e:
646
+ print(f"❌ [Firebase] Viral Delete Error: {e}")
647
+ return False
648
+
649
+ async def load_all_viral_items_fb():
650
+ """Carga todos los items virales en una lista."""
651
+ if not db: return []
652
+ try:
653
+ loop = asyncio.get_running_loop()
654
+ docs = await loop.run_in_executor(None, lambda: db.collection('viral_shorts').stream())
655
+
656
+ items = []
657
+ for doc in docs:
658
+ try:
659
+ items.append(doc.to_dict())
660
+ except: pass
661
+
662
+ print(f"🔥 [Firebase] Viral Items Loaded: {len(items)}")
663
+ return items
664
+ except Exception as e:
665
+ print(f"⚠️ [Firebase] Viral Load Error: {e}")
666
+ return []
gallery-dl.conf ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "downloader": {
3
+ }
4
+ }
icons/@twistedbrody dowload.png ADDED

Git LFS Details

  • SHA256: 66fc41948d1e7218f432c928873f3ca345f6f4ab020992188b1042f9d3cc0b07
  • Pointer size: 131 Bytes
  • Size of remote file: 290 kB
icons/@twistedbrody.png ADDED

Git LFS Details

  • SHA256: 056fbd5e69e61bebcbd27996ad1a6f837c9cec0d96d3ce0e627dc0085c17c38c
  • Pointer size: 131 Bytes
  • Size of remote file: 329 kB
index.html ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <link rel="icon" type="image/png" href="/icons/logo%20pagina.png" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
8
+ <script src="https://telegram.org/js/telegram-web-app.js"></script>
9
+ <title>Twisted brody</title>
10
+ </head>
11
+
12
+ <body>
13
+ <div id="root"></div>
14
+ <script type="module" src="/src/main.tsx"></script>
15
+ </body>
16
+
17
+ </html>