-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
1578 lines (1247 loc) · 53.5 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
from quart import Quart, request, jsonify, render_template
from quart_cors import cors
from telethon.sync import TelegramClient, functions, types
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.sessions import StringSession
from telethon.tl.functions.messages import AddChatUserRequest
import os
import aiofiles
import sqlite3
import random
import hashlib
icon_colors = [0x6FB9F0, 0xFFD67E, 0xCB86DB, 0x8EEE98, 0xFF93B2, 0xFB6F5F]
app = Quart(__name__)
app = cors(app) # Habilita CORS para todas las rutas
api_id = 24182212
api_hash = 'f375f3e2c8e1f5b47639379c7b654c8c'
# Conecta o crea la base de datos
# Conectarse a la base de datos o crearla si no existe
conn = sqlite3.connect('./tgpersonalcloud.db')
# Crea un cursor para ejecutar comandos SQL
cursor = conn.cursor()
# Crer la tabla 'usuario'
cursor.execute('''
CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
string_session TEXT NOT NULL UNIQUE,
phone_number TEXT NOT NULL UNIQUE,
password TEXT NOT NULL UNIQUE
)
''')
# Crear la tabla 'channel'
cursor.execute('''
CREATE TABLE IF NOT EXISTS channel (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
users INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES user(id)
)
''')
# Crear la tabla 'topic'
cursor.execute('''
CREATE TABLE IF NOT EXISTS topic (
id INTEGER,
channel_id INTEGER NOT NULL,
title TEXT NOT NULL,
color TEXT NOT NULL,
FOREIGN KEY (channel_id) REFERENCES channel(id)
)
''')
# Crear la tabla 'right'
cursor.execute('''
CREATE TABLE IF NOT EXISTS right (
channel_id INTEGER,
contact_id INTEGER,
send_messages BOOLEAN,
send_media BOOLEAN,
send_stickers BOOLEAN,
send_gifs BOOLEAN,
send_games BOOLEAN,
send_inline BOOLEAN,
embed_link BOOLEAN,
send_polls BOOLEAN,
change_info BOOLEAN,
invite_users BOOLEAN,
pin_messages BOOLEAN,
FOREIGN KEY (channel_id) REFERENCES channel(id),
FOREIGN KEY (contact_id) REFERENCES contact(id)
)
''')
# Crear la tabla 'contact'
cursor.execute('''
CREATE TABLE IF NOT EXISTS contact (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
first_name TEXT,
last_name TEXT,
user_name TEXT UNIQUE,
phone_number TEXT UNIQUE
)
''')
# Guarda los cambios y cierra la conexión
conn.commit()
conn.close()
@app.route("/")
async def index():
return await render_template("index.html")
# --- DATABASE MANAGEMENT FUNCTIONS --------------------------------------------------------------------------------------------------------------------
# Function to insert a user's session information into the database
def insert_user_into_database(string_session, phone_number, password):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
password = hashlib.sha256(password.encode()).hexdigest()
# Insert user session data into the 'sessions' table
cursor.execute("INSERT INTO user (string_session, phone_number, password) VALUES (?, ?, ?)",
(string_session, phone_number, password))
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# Return True to indicate successful insertion
return True
except sqlite3.Error as e:
# Handle any errors that occur during the insertion process
print("Error inserting into the database:", e)
return False
# Function to insert a user's session information into the database
def insert_password_into_database(phone_number, password):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# password = hashlib.sha256(password.encode()).hexdigest()
cursor.execute("SELECT id FROM user WHERE phone_number = ?", (phone_number,))
result = cursor.fetchone()
user_id = result[0]
print("ID", result, user_id)
# Insert user session data into the 'sessions' table
cursor.execute("UPDATE user SET password = ? WHERE id = ?",
(password, user_id))
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# Return True to indicate successful insertion
return True
except sqlite3.Error as e:
# Handle any errors that occur during the insertion process
print("Error inserting into the database:", e)
return False
#################################################################################################################################
# CHANNELS
def insert_channel(id, user_id, title, desc):
print("CREANDO CANAL")
try:
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Datos que deseas insertar en la tabla channels
channel_data = (id, user_id, title, desc, 1)
# Sentencia SQL para insertar datos en la tabla channels
insert_query = '''
INSERT INTO channel (id, user_id, title, description, users)
VALUES (?, ?, ?, ?, ?);
'''
# Ejecutar la sentencia SQL
cursor.execute(insert_query, channel_data)
# Guardar los cambios en la base de datos
conn.commit()
print("CANAL CREADO")
except Exception as e:
print("Fallo al crear el canal", e)
# Cerrar la conexión
conn.close()
def update_channel_title(id, title, about):
try:
import sqlite3
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Sentencia SQL para la actualización
update_query = '''
UPDATE channel
SET title = ?,
description = ?
WHERE id = ?;
'''
# Ejecutar la sentencia SQL con los valores proporcionados
cursor.execute(update_query, (title, about, id))
# Guardar los cambios en la base de datos
conn.commit()
except Exception as e:
print("Fallo al editar el canal", e)
# Cerrar la conexión
conn.close()
def update_channel_users(id, users):
try:
import sqlite3
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Sentencia SQL para la actualización
update_query = '''
UPDATE channel
SET users = ?
WHERE id = ?;
'''
# Ejecutar la sentencia SQL con los valores proporcionados
cursor.execute(update_query, (users, id))
# Guardar los cambios en la base de datos
conn.commit()
except Exception as e:
print("Fallo al editar los usuarios", e)
# Cerrar la conexión
conn.close()
def delete_channel_db(id):
try:
import sqlite3
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Sentencia SQL para la actualización
update_query = '''
DELETE FROM channel
WHERE id = ?;
'''
# Ejecutar la sentencia SQL con los valores proporcionados
cursor.execute(update_query, (id,))
# Sentencia SQL para la actualización
update_query = '''
DELETE FROM right
WHERE channel_id = ?;
'''
# Ejecutar la sentencia SQL con los valores proporcionados
cursor.execute(update_query, (id,))
# Sentencia SQL para la actualización
update_query = '''
DELETE FROM topic
WHERE channel_id = ?;
'''
# Ejecutar la sentencia SQL con los valores proporcionados
cursor.execute(update_query, (id,))
# Guardar los cambios en la base de datos
conn.commit()
except Exception as e:
print("Fallo al eliminar el canal", e)
# Cerrar la conexión
conn.close()
def delete_topic_db(topic_id, channel_id):
try:
import sqlite3
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Sentencia SQL para la actualización
update_query = '''
DELETE FROM topic
WHERE id = ? AND channel_id = ?;
'''
# Ejecutar la sentencia SQL con los valores proporcionados
cursor.execute(update_query, (topic_id, channel_id,))
# Guardar los cambios en la base de datos
conn.commit()
except Exception as e:
print("Fallo al eliminar el topic", e)
# Cerrar la conexión
conn.close()
#################################################################################################################################
# TOPICS
def insert_topic(id, channel_id, title, color):
print("CREANDO CANAL")
try:
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Datos que deseas insertar en la tabla channels
channel_data = (id, channel_id, title, color)
# Sentencia SQL para insertar datos en la tabla channels
insert_query = '''
INSERT INTO topic (id, channel_id, title, color)
VALUES (?, ?, ?, ?);
'''
# Ejecutar la sentencia SQL
cursor.execute(insert_query, channel_data)
# Guardar los cambios en la base de datos
conn.commit()
print("CANAL CREADO")
except Exception as e:
print("Fallo al crear el canal", e)
# Cerrar la conexión
conn.close()
#################################################################################################################################
def insert_rights(channel_id, contact_id, send_messages, send_media, send_stickers, send_gifs,
send_games, send_inline, embed_link_previews, send_polls, change_info, invite_users, pin_messages):
print("CREANDO RIGHT")
try:
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Datos que deseas insertar en la tabla rights
rights_data = (channel_id, contact_id, send_messages, send_media, send_stickers, send_gifs,
send_games, send_inline, embed_link_previews, send_polls, change_info, invite_users, pin_messages)
# Sentencia SQL para insertar datos en la tabla rights
insert_query = '''
INSERT INTO right (channel_id, contact_id, send_messages, send_media, send_stickers, send_gifs,
send_games, send_inline, embed_link, send_polls, change_info, invite_users, pin_messages)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
'''
# Ejecutar la sentencia SQL
cursor.execute(insert_query, rights_data)
# Guardar los cambios en la base de datos
conn.commit()
print("RIGHT CREADO")
except Exception as e:
print("FALLO AL CREAR EL RIGHT", e)
# Cerrar la conexión
conn.close()
def update_rights(channel_id, contact_id, selected_permissions):
try:
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Actualizar las columnas excepto los IDs a 0
cursor.execute('''
UPDATE right
SET send_messages = 0,
send_media = 0,
send_stickers = 0,
send_gifs = 0,
send_games = 0,
send_inline = 0,
embed_link = 0,
send_polls = 0,
change_info = 0,
invite_users = 0,
pin_messages = 0
WHERE channel_id = ? AND contact_id = ?
''', (channel_id, contact_id,))
for permission in selected_permissions:
print(permission)
update_query = f'''
UPDATE right
SET {permission} = 1
WHERE channel_id = ? AND contact_id = ?
'''
cursor.execute(update_query, (channel_id, contact_id,))
# Guarda los cambios en la base de datos
conn.commit()
# Cierra la conexión
conn.close()
# Return True to indicate successful insertion
return True
except sqlite3.Error as e:
# Handle any errors that occur during the insertion process
print("Error inserting into the database:", e)
return False
# Function to retrieve a user's session string by their phone number
def get_string_session_from_database(phone_number):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Retrieve the session string from the 'sessions' table based on phone number
cursor.execute("SELECT string_session FROM user WHERE phone_number=?", (phone_number,))
result = cursor.fetchone()
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# If a result is found, return the session string; otherwise, return None
if result:
string_session = result[0]
return string_session
else:
return None
except Exception as e:
# Handle any errors that occur during the database query
print(f"Error querying the database: {str(e)}")
return None
def select_user_id_from_user(phone_number):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Retrieve the session string from the 'sessions' table based on phone number
cursor.execute("SELECT id FROM user WHERE phone_number=?", (phone_number,))
result = cursor.fetchone()
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# If a result is found, return the session string; otherwise, return None
if result:
user_id = result[0]
return user_id
else:
return None
except Exception as e:
# Handle any errors that occur during the database query
print(f"Error querying the database: {str(e)}")
return None
def select_contact_id_from_contact(contact_id):
print(contact_id)
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Retrieve the session string from the 'sessions' table based on phone number
cursor.execute("SELECT * FROM contact WHERE id=?", (contact_id,))
result = cursor.fetchone()
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# If a result is found, return the session string; otherwise, return None
if result:
user_id = result[0]
return user_id
else:
return None
except Exception as e:
# Handle any errors that occur during the database query
print(f"Error querying the database: {str(e)}")
return None
# Function to check if a user with a given phone number exists in the database
def check_user_from_database(phone_number):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Count the number of records with the specified phone number in the 'sessions' table
cursor.execute("SELECT COUNT(*) FROM user WHERE phone_number=?", (phone_number,))
count = cursor.fetchone()[0]
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# If the count is greater than 0, the user exists; otherwise, they do not
if count > 0:
return True
else:
return False
except Exception as e:
# Handle any errors that occur during the database query
print(f"Error checking user existence in the database: {str(e)}")
return False
# Function to check if a user with a given phone number exists in the database
def check_user_from_database_password(phone_number):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Count the number of records with the specified phone number in the 'sessions' table
cursor.execute("SELECT password FROM user WHERE phone_number=?", (phone_number,))
result = cursor.fetchone()[0]
print("RESULT", result)
print(hashlib.sha256("".encode()).hexdigest())
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# If the count is greater than 0, the user exists; otherwise, they do not
if result != hashlib.sha256("".encode()).hexdigest():
print("true")
return True
else:
print("false")
return False
except Exception as e:
# Handle any errors that occur during the database query
print(f"Error checking user existence in the database: {str(e)}")
return False
# Function to check if a given password matches the password stored for a user's phone number
def check_password_from_database(phone_number, password):
try:
# Connect to the './tgpersonalcloud.db' SQLite database
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Retrieve the stored password from the 'sessions' table based on phone number
cursor.execute("SELECT password FROM user WHERE phone_number=?", (phone_number,))
result = cursor.fetchone()
# Commit the transaction and close the database connection
conn.commit()
conn.close()
# If a result is found, compare the stored password with the provided password
if result:
stored_password = result[0]
if password == stored_password:
return True
else:
return False
else:
return False
except Exception as e:
# Handle any errors that occur during the database query
print(f"Error checking the password in the database: {str(e)}")
return False
# ------------------------------------------------------------------------------------------------------------------------------------------------------
# --- USER LOGIN FUNCTIONS -----------------------------------------------------------------------------------------------------------------------------
# Create dictionaries to store client and phone number data
clients = {}
# Endpoint to handle sending a phone number to Telegram
# This endpoint expects a POST request with JSON data containing a 'phone_number' field.
@app.route('/send_phone_number', methods=['POST'])
async def send_phone_number():
data = await request.get_json()
phone_number = data['phone_number']
print(phone_number)
if check_user_from_database(phone_number):
print("DENTRO")
return jsonify({'message': 'User already exists in database.'}), 200
else:
print("FUERA")
# Create a Telegram client object with a string session
client = TelegramClient(StringSession(), api_id, api_hash)
# Connect to the Telegram service
await client.connect()
# Check if the user is authorized; if not, send a code request to the phone number
if not await client.is_user_authorized():
try:
await client.send_code_request(phone_number)
# Store the client object in the 'clients' dictionary
clients[phone_number] = client
except:
print("The phone number is invalid.")
return jsonify({'message': 'The phone number is invalid'}), 777
return jsonify({'message': 'User does not exists in database.'}), 500
# Endpoint to handle sending a verification code
# This endpoint expects a POST request with JSON data containing 'code' and 'phone_number' fields.
@app.route('/send_verification_code', methods=['POST'])
async def send_verification_code():
data = await request.get_json()
code = data['code']
phone_number = data['phone_number']
# Check if the user exists in the database
if check_user_from_database(phone_number):
print("The user already exists in the database")
# Return a JSON response indicating that the number is already registered
return jsonify({'message': 'This number has already been registered'}), 200
else:
print("User does not exists in the database")
# If the user doesn't exist, retrieve the client object from the 'clients' dictionary
client = clients.get(phone_number)
# Connect the client and sign in with the code
await client.connect()
try:
await client.sign_in(phone_number, code)
except:
print("This code is invalid.")
return jsonify({'message': 'This code is invalid.'}), 777
# Save the client's string session and insert user data into the database
string_session = client.session.save()
if insert_user_into_database(string_session, phone_number, ""):
print("Record inserted successfully into the database without password")
else:
print("Error inserting the record into the database")
# Return a JSON response indicating that the number is not registered
return jsonify({'message': 'This number is not registered'}), 500
# Endpoint to handle sending a password and code
# This endpoint expects a POST request with JSON data containing 'code', 'phone_number', and 'password' fields.
@app.route('/send_password', methods=['POST'])
async def send_password():
data = await request.get_json()
code = data['code']
phone_number = data['phone_number']
password = data['password']
print(code, phone_number, password)
# Check if the user exists in the database
if check_user_from_database(phone_number):
if check_user_from_database_password(phone_number):
print(password)
# If the user exists, check the password from the database
password = hashlib.sha256(password.encode()).hexdigest()
if check_password_from_database(phone_number, password):
# If the password matches, create a Telegram client with a saved session and return success
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
return jsonify({'message': 'Logged in successfully'}), 200
else:
return jsonify({'message': 'Password incorrect.'}), 500
else:
print(password)
password = hashlib.sha256(password.encode()).hexdigest()
print(password)
insert_password_into_database(phone_number, password)
# Return a JSON response indicating that a user has been created
return jsonify({'message': 'User updated'}), 200
# ------------------------------------------------------------------------------------------------------------------------------------------------------
########################################################################
# USER
async def getInfo(client):
await client.connect()
me = await client.get_me()
print(me)
try:
user_info = {
"id": me.id,
"nombre": me.first_name,
"apellido": me.last_name,
"username": me.username,
"phone": me.phone
}
return user_info
except Exception as e:
print(e)
@app.route('/get_user_info', methods=['POST'])
async def get_user_info():
data = await request.get_json()
phone_number = data['phone_number']
print("DENTRO", phone_number)
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
print(string_session, client)
me = await client.get_me()
print(me)
user_info = {
"id": me.id,
"nombre": me.first_name,
"apellido": me.last_name,
"username": me.username,
"phone": me.phone
}
print(user_info)
return jsonify(user_info)
########################################################################
@app.route('/log_out', methods=['POST'])
async def log_out():
try:
data = await request.get_json()
phone_number = data['phone_number']
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
if client:
await client.log_out()
return "Se ha cerrado la sesión", 200
except:
return "No se ha cerrado la sesión", 500
@app.route('/get_messages', methods=['POST'])
async def get_messages():
data = await request.get_json()
phone_number = data['phone_number']
channel_id = data['channel_id']
topic_id = data['topic_id']
messages = []
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
try:
async for message in client.iter_messages(int(channel_id), reply_to=int(topic_id)):
message_data = {'text': None, 'file_size': None}
if message.text is not None and message.text.strip() != "":
# print(f"Mensaje de texto: {message.text}")
message_data['text'] = message.text
if message.media and message.file.size is not None:
tamaño_del_archivo = message.file.size
# print(f"Tamaño del archivo adjunto: {tamaño_del_archivo} bytes")
message_data['file_size'] = tamaño_del_archivo
# Agregar el diccionario al conjunto solo si tiene valores
if message_data:
messages.append(message_data)
# Devuelve los mensajes en formato JSON, incluyendo el texto y el tamaño del archivo
return jsonify({'messages': messages}), 200
except:
return 'Error obteniendo los mensajes', 500
@app.route('/delete_messages', methods=['POST'])
async def delete_messages():
data = await request.get_json()
phone_number = data['phone_number']
channel_id = data['channel_id']
topic_id = data['topic_id']
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
try:
async for message in client.iter_messages(int(channel_id), reply_to=int(topic_id)):
if message.text is not None:
try:
await client(functions.channels.DeleteMessagesRequest(int(channel_id),[message.id]))
except Exception as e:
print(e)
# Devuelve los mensajes en formato JSON, incluyendo el texto y el tamaño del archivo
return "Mensajes eliminados", 200
except:
return 'Error obteniendo los mensajes', 500
@app.route('/check_authorization', methods=['POST'])
async def check_authorization():
data = await request.get_json()
phone_number = data['phone_number']
if check_user_from_database(phone_number):
return jsonify({'authorized': True}), 200
else:
return jsonify({'authorized': False}), 500
@app.route('/send_message/<phone_number>', methods=['POST'])
async def send_message(phone_number):
phone_number = "+" + phone_number
data = await request.get_json()
message = data['message']
# await send_message_to_telegram(message, phone_number)
return jsonify({'message': 'Mensaje enviado correctamente'}), 200
@app.route('/upload/<group_id>/<phone_number>', methods=['POST'])
async def upload_file(group_id, phone_number):
phone_number = "+" + phone_number
file = (await request.files).get('file')
if file:
filename = file.filename
content_type = file.content_type
# Crear y escribir el contenido del archivo en la ubicación actual
async with aiofiles.open(filename, 'wb') as f:
await f.write(file.read()) # No se utiliza 'await' aquí
# Enviar el archivo a Telegram
await send_file_to_telegram(filename, group_id, phone_number)
# Borrar el archivo local
try:
os.remove(filename)
except Exception as e:
print(f"No se pudo eliminar el archivo local: {e}")
return 'Archivo enviado a Telegram con éxito y archivo local eliminado', 200
else:
return 'Error al enviar el archivo', 400
# Función para enviar un archivo a Telegram
async def send_file_to_telegram(filename, group_id, phone_number):
phone_number = "+" + phone_number
try:
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
# Enviar el archivo con los atributos especificados
await client.send_file(int(group_id), filename, caption=filename)
except Exception as e:
print(f"No se pudo enviar el archivo {filename}.")
@app.route('/send_media_topic/<group_id>/<topic_id>/<phone_number>/<file_size>', methods=['POST'])
async def send_media_topic(group_id, topic_id, phone_number, file_size):
phone_number = "+" + phone_number
file = (await request.files).get('file')
if file:
filename = file.filename
# Crear y escribir el contenido del archivo en la ubicación actual
async with aiofiles.open(filename, 'wb') as f:
await f.write(file.read()) # No se utiliza 'await' aquí
# Enviar el archivo a Telegram
await send_file_to_telegram_topic(filename, group_id, topic_id, phone_number, file_size)
# Borrar el archivo local
try:
os.remove(filename)
except Exception as e:
print(f"No se pudo eliminar el archivo local: {e}")
return 'Archivo enviado a Telegram con éxito y archivo local eliminado', 200
else:
return 'Error al enviar el archivo', 400
# Función para enviar un archivo a Telegram
async def send_file_to_telegram_topic(filename, group_id, topic_id, phone_number, file_size_file):
try:
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
# Crear el atributo DocumentAttributeFileSize con el tamaño del archivo
# attributes.append(types.DocumentAttributeFileSize(file_size))
# Printing upload progress
def callback(current, total):
print('Uploaded', current, 'out of', total,'bytes: {:.2%}'.format(current / total))
await client.connect()
# Crear el atributo DocumentAttributeFilename con el nombre del archivo
attributes = [types.DocumentAttributeFilename(file_name=str(filename))]
await client.send_file(int(group_id), filename, caption=filename, reply_to=int(topic_id), silent=True, attributes=attributes, file_size=len(file_size_file), progress_callback=callback, force_document=True)
except Exception as e:
print(f"No se pudo enviar el archivo {filename}. {e}")
def select_channels(user_id):
channels = []
try:
# Conectar a la base de datos
conn = sqlite3.connect('./tgpersonalcloud.db')
cursor = conn.cursor()
# Ejecutar la sentencia SQL
cursor.execute("SELECT * FROM channel WHERE user_id = ?", (user_id,))
rows = cursor.fetchall()
for row in rows:
channels.append({
'id': row[0],
'title': row[2],
'desc' : row[3],
'users': row[4]
})
return channels
except Exception as e:
print("Fallo al obtener los canales", e)
# Cerrar la conexión
conn.close()
@app.route('/get_channels', methods=['POST'])
async def get_channels():
channels = []
data = await request.get_json()
phone_number = data['phone_number']
user_id = select_user_id_from_user(phone_number)
channels = select_channels(user_id)
'''
string_session = get_string_session_from_database(phone_number)
client = TelegramClient(StringSession(string_session), api_id, api_hash)
await client.connect()
dialogs = await client.get_dialogs()
channels = []
for dialog in dialogs:
if dialog.is_group and dialog.title.startswith("::") and dialog.title.endswith("::") and dialog.title != ":::PersonalCloud:::":
ch = await client.get_entity(dialog.id)
ch_full = await client(GetFullChannelRequest(channel=ch))
channel_info = {
'id': dialog.id,
'title': dialog.title.replace("::", ""),
'desc': ch_full.full_chat.about
}
channels.append(channel_info)
update_channel_users(dialog.id, ch_full.full_chat.participants_count)
'''
return jsonify({'channels': channels})