Spaces:
Running
Running
File size: 46,458 Bytes
07b55d8 edee679 16c32c6 07b55d8 3571158 07b55d8 326d2da 07b55d8 d140f2b 07b55d8 ffb87b3 d140f2b eeec488 f72d601 94b99a4 f72d601 5c2a467 f72d601 5c2a467 f72d601 1678e8c 0517bea 1678e8c f72d601 1678e8c 9bc1664 f72d601 58cae0c 6e5ec17 1d05f9c 1258d21 14af27b 1258d21 1d05f9c 40c4f6f 1258d21 1d05f9c d140f2b 4f85554 ae929a2 4f85554 283f5a6 4f85554 9fd04af d6656be 4f85554 d1209d9 4f85554 2db0a09 14be26d 88a38c2 4cb190b 8ab0f21 88a38c2 14be26d 96e4ac8 3c89330 1747067 62f3dfd 58b1dae 1747067 3c89330 58b1dae 1747067 58b1dae 1747067 3c89330 1747067 58b1dae 1747067 3c89330 58b1dae 1747067 d640d5d 1747067 3c89330 1747067 62f3dfd 58b1dae 1747067 58b1dae 1747067 3c89330 ae929a2 1747067 3c89330 1747067 3c89330 1747067 3c89330 1747067 3c89330 1747067 d6656be 1747067 3c89330 1747067 3c89330 ae929a2 1747067 3c89330 1747067 3c89330 0d7e504 59a0954 3c89330 1747067 3c89330 1747067 3c89330 1747067 42aa29c 3c89330 1747067 3c89330 1747067 f85174e 1747067 3c89330 ae929a2 3c89330 ae929a2 3c89330 58b1dae 15fb9dc 2867343 214e460 2db0a09 214e460 2db0a09 214e460 77c2c3d 214e460 2db0a09 214e460 2db0a09 214e460 d1209d9 214e460 2db0a09 214e460 283f5a6 214e460 2db0a09 214e460 96e4ac8 2867343 96e4ac8 15fb9dc ffba69b 15fb9dc ffba69b 15fb9dc c050188 15fb9dc a66cca9 d71b420 2867343 a66cca9 d71b420 a66cca9 d71b420 a66cca9 3985ad4 d71b420 a66cca9 d71b420 a66cca9 15fb9dc 8ab0f21 df450da 214e460 8ab0f21 df450da efb748b d6656be df450da 9fd04af d6656be df450da 8ab0f21 df450da 8ab0f21 fcc9d8d 95de908 dbdcf4a 1747067 dbdcf4a d6656be dbdcf4a 2eb948a 95de908 13dbf68 3adb4d2 d6656be 3adb4d2 2eb948a 3adb4d2 2eb948a 8ab0f21 13dbf68 d6656be 13dbf68 8ab0f21 df450da 214e460 d140f2b fe727bb f1e11eb fe727bb 79ecbe0 454b4e5 79ecbe0 bfef43e 79ecbe0 fe727bb 79ecbe0 fe727bb aa378f4 fe727bb 40c4f6f b9df598 7ff616c 6d5cbcf 40c4f6f 7ff616c 14af27b 40c4f6f 14af27b 2138b6a 6d5cbcf f381854 5fa984e 4e3dd9f 9ede144 b9757a6 5fa984e 4e3dd9f 77bdeeb 4e3dd9f 5fa984e 1258d21 e976dab 7f021d7 0753094 080f0bc 96393fc 080f0bc eeec488 739886f 8d74358 eeec488 8d74358 eeec488 080f0bc f18f04b 96393fc |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 |
from flask import Flask, request, render_template_string, render_template, jsonify, Response, send_from_directory, render_template
import sqlite3
import os
import random
import requests
import time
import re
import json
import base64
import logging
import csv
import io
from urllib.parse import quote
import string
from datetime import datetime
import pytz
import socket
from unidecode import unidecode
import uuid
import psutil
from base import replace_null_with_empty_string
from ns import send_ns
api_key_sys = os.getenv('api_key_sys')
import logging
logging.basicConfig(level=logging.DEBUG)
# Глобальная переменная для управления верификацией
current_curator_index = 0
verifikation_start = "1" # Глобальная переменная для управления верификацией
curator_on_off = "0" # Глобальная переменная для управления назначением куратора
curators = ["Anna", "Ekaterina", "Ivan", "Maria", "Sergey", "Olga", "Alex", "Natalia", "Dmitry", "Elena"]
# Глобальная переменная для
wa_url = os.getenv('wa_url')
wa_api_key = os.getenv('wa_api_key')
wa_ak = os.getenv('ws_ak')
ws_url_mes = "/sendMessage/"
ws_url_ver = "/checkWhatsapp/"
app = Flask(__name__, template_folder="./")
app.config['DEBUG'] = True
UPLOAD_FOLDER = 'static'
HTML_FOLDER = 'html'
# Создание директорий, если они не существуют
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
if not os.path.exists(HTML_FOLDER):
os.makedirs(HTML_FOLDER)
DATABASES = ['data_gc.db', 'site_data.db', 'ws_data.db', 'vk_data.db', 'tg_data.db', 'gk_data.db']
def init_db(db_name):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
phone TEXT NOT NULL,
email TEXT NOT NULL,
vk_id TEXT,
chat_id TEXT,
ws_st TEXT,
ws_stop TEXT,
web_st INTEGER,
fin_prog INTEGER,
b_city TEXT,
b_fin TEXT,
b_ban TEXT,
b_ign TEXT,
b_baners TEXT,
b_butt TEXT,
b_mess TEXT,
orders TEXT,
curator TEXT,
bonus TEXT,
shop_status TEXT,
pr3 TEXT,
pr4 TEXT,
pr5 TEXT,
gc_url TEXT,
key_pr TEXT,
n_con TEXT,
canal TEXT,
data_on TEXT,
data_t TEXT,
utm_source TEXT,
utm_medium TEXT,
utm_campaign TEXT,
utm_term TEXT,
utm_content TEXT,
gcpc TEXT
)
''')
conn.commit()
conn.close()
for db in DATABASES:
init_db(db)
DATABASE_NEW = 'data_gc.db'
mapping_template = {
"username": "name",
"phone": "phone",
"email": "email",
"city": "b_city",
"finished": "b_fin",
"ban": "b_ban",
"ignore": "b_ign",
"banners": "b_baners",
"buttons": "b_butt",
"messages": "b_mess"
}
# Отдаем дату онлайн
@app.route('/get_current_time', methods=['GET'])
def get_current_time():
utc_now = datetime.utcnow()
msk_tz = pytz.timezone('Europe/Moscow')
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
current_time = msk_now.strftime('%Y-%m-%d %H:%M:%S')
return jsonify({'current_time': current_time})
# Функция для очистки номера телефона
def clean_phone_number_ss(phone_number):
return re.sub(r'\D', '', phone_number)
# Добавляем пользователя
mt_site = {
'name': 'name',
'phone': 'phone',
'email': 'email',
'utm_campaign': 'utm_campaign',
'utm_content': 'utm_content',
'utm_medium': 'utm_medium',
'utm_source': 'utm_source',
'utm_term': 'utm_term',
'gcpc': 'gcpc'
}
mt_vk = {
'name': 'name',
'phone': 'phone',
'email': 'email',
'vk_id': 'vk_id',
'utm_campaign': 'utm_campaign',
'utm_content': 'utm_content',
'utm_medium': 'utm_medium',
'utm_source': 'utm_source',
'utm_term': 'utm_term',
'gcpc': 'gcpc'
}
mt_tg = {
'name': 'name',
'phone': 'phone',
'email': 'email',
'chat_id': 'chat_id',
'utm_campaign': 'utm_campaign',
'utm_content': 'utm_content',
'utm_medium': 'utm_medium',
'utm_source': 'utm_source',
'utm_term': 'utm_term',
'gcpc': 'gcpc'
}
mt_gc = {
'name': 'name',
'phone': 'phone',
'email': 'email',
'gc_url': 'gc_url',
'utm_campaign': 'utm_campaign',
'utm_content': 'utm_content',
'utm_medium': 'utm_medium',
'utm_source': 'utm_source',
'utm_term': 'utm_term',
'gcpc': 'gcpc'
}
mt_pass = {
'name': 'name',
'phone': 'phone',
'email': 'email',
'kol': 'pr1',
'pr2': 'pr2',
'gen_pass': 'pr5',
'utm_campaign': 'utm_campaign',
'utm_content': 'utm_content',
'utm_medium': 'utm_medium',
'utm_source': 'utm_source',
'utm_term': 'utm_term',
'gcpc': 'gcpc'
}
tl_quest = {
'name': 'name',
'phone': 'phone',
'email': 'email',
'pr2': 'pr2',
'utm_campaign': 'utm_campaign',
'utm_content': 'utm_content',
'utm_medium': 'utm_medium',
'utm_source': 'utm_source',
'utm_term': 'utm_term',
'gcpc': 'gcpc'
}
mapp_templates = {
'site': mt_site,
'vk': mt_vk,
'tg': mt_tg,
'gc': mt_gc,
'tilda': mt_pass,
'quest': tl_quest
}
def verify_phone_number(phone_number):
full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
payload = {"phoneNumber": phone_number}
headers = {'Content-Type': 'application/json'}
response = requests.post(full_url_ver, headers=headers, json=payload)
if response.status_code == 200:
response_body = response.json()
return response_body.get('existsWhatsapp', 'false')
else:
return "false"
def generate_password(length=8):
letters_and_digits = string.ascii_letters + string.digits
return ''.join(random.choice(letters_and_digits) for i in range(length))
def add_or_update_contact(contact_data, db_name):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
email = contact_data.get('email')
if not email:
logging.error(f"Missing email in contact data: {contact_data}")
return
utc_now = datetime.utcnow()
msk_tz = pytz.timezone('Europe/Moscow')
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
contact_data['data_t'] = msk_now.strftime('%Y-%m-%d %H:%M:%S')
fields = [
'name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog',
'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'orders', 'curator',
'bonus', 'shop_status', 'pr3', 'pr4', 'pr5', 'gc_url', 'key_pr', 'n_con', 'canal', 'data_on', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gcpc'
]
for field in fields:
if field not in contact_data:
contact_data[field] = ''
cursor.execute("SELECT id FROM contacts WHERE email = ?", (email,))
contact = cursor.fetchone()
if contact:
update_fields = [f"{field} = ?" for field in fields if contact_data[field] != '']
update_values = [contact_data[field] for field in fields if contact_data[field] != '']
update_values.append(contact[0])
update_query = f"UPDATE contacts SET {', '.join(update_fields)} WHERE id = ?"
cursor.execute(update_query, update_values)
else:
insert_query = f"INSERT INTO contacts ({', '.join(fields)}) VALUES ({', '.join(['?' for _ in fields])})"
cursor.execute(insert_query, tuple(contact_data[field] for field in fields))
conn.commit()
conn.close()
@app.route('/add_user_home', methods=['GET'])
def add_user_home():
global current_curator_index
veref_on_off = request.args.get('ver', '0')
curator_on_off = request.args.get('cur', '0')
db_name = request.args.get('db', 'data_gc.db') # Получаем имя базы данных из запроса
template_key = request.args.get('player', 'site')
mapping_template_cur = mapp_templates.get(template_key, mt_site)
user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}
logging.debug(f"Received data: {user_data}")
if curator_on_off == "1":
user_data['curator'] = curators[current_curator_index]
current_curator_index = (current_curator_index + 1) % len(curators)
else:
user_data['curator'] = user_data.get('curator', '')
if veref_on_off == "1":
phone_number = user_data.get('phone', '')
if not phone_number:
logging.error("Phone number is empty")
return jsonify({'status': 'error', 'message': 'Phone number is empty'}), 400
phone_verification_response = verify_phone_number(phone_number)
if phone_verification_response is not None:
user_data['ws_st'] = '1' if phone_verification_response else '0'
else:
user_data['ws_st'] = user_data.get('ws_st', '')
try:
add_or_update_contact(user_data, db_name)
return jsonify({'status': 'success', 'message': f'User added {user_data.get("curator", "not assigned")}'})
except Exception as e:
logging.error(f"Error adding user: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/user', methods=['GET'])
def user():
global current_curator_index
veref_on_off = request.args.get('ver', '0')
curator_on_off = request.args.get('cur', '0')
db_name = request.args.get('db', 'data_gc.db') # Получаем имя базы данных из запроса
template_key = request.args.get('player', 'site')
mapping_template_cur = mapp_templates.get(template_key, mt_site)
user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}
logging.debug(f"Received data: {user_data}")
if curator_on_off == "1":
user_data['curator'] = curators[current_curator_index]
current_curator_index = (current_curator_index + 1) % len(curators)
else:
user_data['curator'] = user_data.get('curator', '')
if veref_on_off == "1":
phone_number = user_data.get('phone', '')
if not phone_number:
logging.error("Phone number is empty")
return jsonify({'status': 'error', 'message': 'Phone number is empty'}), 400
phone_verification_response = verify_phone_number(phone_number)
if phone_verification_response is not None:
user_data['ws_st'] = '1' if phone_verification_response else '0'
else:
user_data['ws_st'] = user_data.get('ws_st', '')
try:
add_or_update_contact(user_data, db_name)
return jsonify({'status': 'success', 'message': f'User added {user_data.get("curator", "not assigned")}'})
except Exception as e:
logging.error(f"Error adding user: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/add_user_mess', methods=['GET'])
def add_user_mess():
global current_curator_index
veref_on_off = request.args.get('ver', '0')
curator_on_off = request.args.get('cur', '0')
db_name = request.args.get('db', 'site_data.db') # Получаем имя базы данных из запроса
template_key = request.args.get('player', 'site')
mapping_template_cur = mapp_templates.get(template_key, mt_site)
user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}
logging.debug(f"Received data: {user_data}")
if curator_on_off == "1":
user_data['curator'] = curators[current_curator_index]
current_curator_index = (current_curator_index + 1) % len(curators)
else:
user_data['curator'] = user_data.get('curator', '')
if veref_on_off == "1":
phone_number = user_data.get('phone', '')
if not phone_number:
logging.error("Phone number is empty")
return jsonify({'status': 'error', 'message': 'Phone number is empty'}), 400
phone_verification_response = verify_phone_number(phone_number)
if phone_verification_response is not None:
user_data['ws_st'] = '1' if phone_verification_response else '0'
else:
user_data['ws_st'] = user_data.get('ws_st', '')
try:
add_or_update_contact(user_data, db_name)
return jsonify({'status': 'success', 'message': f'User added {user_data.get("curator", "not assigned")}'})
except Exception as e:
logging.error(f"Error adding user: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
# Работа с ордером из сайта без VK_ID
@app.route('/wr_order', methods=['GET'])
def shop_order_new():
try:
logging.debug("Starting shop_order_new")
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
logging.warning("Unauthorized access attempt")
return json.dumps({"error": "Unauthorized access"}), 403
name = request.args.get('name', '')
email = request.args.get('email', '')
phone = request.args.get('phone', '').lstrip('+')
order = request.args.get('order', '')
status = request.args.get('status', '')
del_flag = request.args.get('del', '')
n_con_flag = request.args.get('n_con', '')
if not email or not phone:
logging.error("Email and phone are required")
return json.dumps({"error": "Email and phone are required"}), 400
phone = clean_phone_number_ss(phone)
conn = sqlite3.connect(DATABASE_NEW)
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts WHERE email = ? OR phone = ?", (email, phone))
result = cursor.fetchone()
if result:
shop_st = result[17] if result[17] else '{}'
shop_st_data = json.loads(shop_st)
logging.debug(f"Existing record found. Loaded JSON: {shop_st_data}")
else:
shop_st_data = {}
if del_flag == '1':
if order in shop_st_data:
del shop_st_data[order]
elif order and status:
shop_st_data[order] = status
shop_st_json = json.dumps(shop_st_data)
utc_now = datetime.utcnow()
msk_tz = pytz.timezone('Europe/Moscow')
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
data_on = msk_now.strftime('%Y-%m-%d %H:%M:%S')
columns_to_update = ['name', 'phone', 'email', 'orders', 'n_con', 'data_on']
values_to_update = [name, phone, email, shop_st_json, n_con_flag, data_on]
if result:
set_clause = ', '.join([f"{col} = ?" for col in columns_to_update])
query = f"UPDATE contacts SET {set_clause} WHERE email = ? OR phone = ?"
cursor.execute(query, values_to_update + [email, phone])
else:
query = f"INSERT INTO contacts ({', '.join(columns_to_update)}) VALUES ({', '.join(['?' for _ in columns_to_update])})"
cursor.execute(query, values_to_update)
conn.commit()
replace_null_with_empty_string(conn)
conn.close()
return json.dumps(shop_st_data), 200
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
return json.dumps({"error": str(e)}), 500
# Работа из VK_ID Запись ордер
@app.route('/wr_order_vk', methods=['GET'])
def write_or():
try:
logging.debug("Starting shop_order_new")
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
logging.warning("Unauthorized access attempt")
return json.dumps({"error": "Unauthorized access"}), 403
name = request.args.get('name', '')
email = request.args.get('email', '')
vkid = request.args.get('vk_id', '')
phone = request.args.get('phone', '').lstrip('+')
order = request.args.get('order', '')
status = request.args.get('status', '')
del_flag = request.args.get('del', '')
n_con_flag = request.args.get('n_con', '')
if not email or not phone:
logging.error("Email and phone are required")
return json.dumps({"error": "Email and phone are required"}), 400
phone = clean_phone_number_ss(phone)
conn = sqlite3.connect(DATABASE_NEW)
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts WHERE email = ? OR phone = ?", (email, phone))
result = cursor.fetchone()
if result:
shop_st = result[17] if result[17] else '{}'
shop_st_data = json.loads(shop_st)
logging.debug(f"Existing record found. Loaded JSON: {shop_st_data}")
else:
shop_st_data = {}
if del_flag == '1':
if order in shop_st_data:
del shop_st_data[order]
elif order and status:
shop_st_data[order] = status
shop_st_json = json.dumps(shop_st_data)
utc_now = datetime.utcnow()
msk_tz = pytz.timezone('Europe/Moscow')
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
data_on = msk_now.strftime('%Y-%m-%d %H:%M:%S')
columns_to_update = ['name', 'phone', 'email', 'vk_id', 'orders', 'n_con', 'data_on']
values_to_update = [name, phone, email, vkid, shop_st_json, n_con_flag, data_on]
if result:
set_clause = ', '.join([f"{col} = ?" for col in columns_to_update])
query = f"UPDATE contacts SET {set_clause} WHERE email = ? OR phone = ?"
cursor.execute(query, values_to_update + [email, phone])
else:
query = f"INSERT INTO contacts ({', '.join(columns_to_update)}) VALUES ({', '.join(['?' for _ in columns_to_update])})"
cursor.execute(query, values_to_update)
conn.commit()
replace_null_with_empty_string(conn)
conn.close()
return json.dumps(shop_st_data), 200
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
return json.dumps({"error": str(e)}), 500
# Работа с бонусами из сайта без VK_ID
@app.route('/wr_bonus', methods=['GET'])
def shop_bonus_new():
try:
logging.debug("Starting shop_bonus_new")
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
logging.warning("Unauthorized access attempt")
return json.dumps({"error": "Unauthorized access"}), 403
name = request.args.get('name', '')
email = request.args.get('email', '')
phone = request.args.get('phone', '').lstrip('+')
bonus = request.args.get('bonus', '')
status = request.args.get('status', '')
del_flag = request.args.get('del', '')
if not email or not phone:
logging.error("Email and phone are required")
return json.dumps({"error": "Email and phone are required"}), 400
phone = clean_phone_number_ss(phone)
conn = sqlite3.connect(DATABASE_NEW)
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts WHERE email = ? OR phone = ?", (email, phone))
result = cursor.fetchone()
if result:
bonus_st = result[19] if result[19] else '{}'
bonus_st_data = json.loads(bonus_st)
logging.debug(f"Existing record found. Loaded JSON: {bonus_st_data}")
else:
bonus_st_data = {}
if del_flag == '1':
if bonus in bonus_st_data:
del bonus_st_data[bonus]
elif bonus and status:
bonus_st_data[bonus] = status
bonus_st_json = json.dumps(bonus_st_data)
utc_now = datetime.utcnow()
msk_tz = pytz.timezone('Europe/Moscow')
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
data_on = msk_now.strftime('%Y-%m-%d %H:%M:%S')
columns_to_update = ['name', 'phone', 'email', 'bonus', 'data_on']
values_to_update = [name, phone, email, bonus_st_json, data_on]
if result:
set_clause = ', '.join([f"{col} = ?" for col in columns_to_update])
query = f"UPDATE contacts SET {set_clause} WHERE email = ? OR phone = ?"
cursor.execute(query, values_to_update + [email, phone])
else:
query = f"INSERT INTO contacts ({', '.join(columns_to_update)}) VALUES ({', '.join(['?' for _ in columns_to_update])})"
cursor.execute(query, values_to_update)
conn.commit()
replace_null_with_empty_string(conn)
conn.close()
return json.dumps(bonus_st_data), 200
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
return json.dumps({"error": str(e)}), 500
# Поднятие страницы с таблицей
@app.route('/data_gc_tab', methods=['GET'])
def data_gc_tab():
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
return "EUR 22", 200
return render_template('data_gc_tab.html')
# Данные в таблицу
@app.route('/data_gc_tab_out', methods=['GET'])
def data_gc_tab_out():
try:
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
return "EUR 22", 200
conn = sqlite3.connect('data_gc.db')
cursor = conn.cursor()
cursor.execute('''
SELECT id, name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog,
b_city, b_fin, b_ban, b_ign, b_baners, b_butt, b_mess, orders, curator,
bonus, shop_status, pr3, pr4, pr5, gc_url, key_pr, n_con, canal, data_on, data_t, utm_source, utm_medium, utm_campaign, utm_term, utm_content, gcpc
FROM contacts
''')
contacts = cursor.fetchall()
conn.close()
contacts_json = [{
'id': contact[0], 'name': contact[1], 'phone': contact[2], 'email': contact[3],
'vk_id': contact[4], 'chat_id': contact[5], 'ws_st': contact[6], 'ws_stop': contact[7],
'web_st': contact[8], 'fin_prog': contact[9], 'b_city': contact[10], 'b_fin': contact[11],
'b_ban': contact[12], 'b_ign': contact[13], 'b_baners': contact[14], 'b_butt': contact[15],
'b_mess': contact[16], 'orders': contact[17], 'curator': contact[18], 'bonus': contact[19],
'shop_status': contact[20], 'pr3': contact[21], 'pr4': contact[22], 'pr5': contact[23],
'gc_url': contact[24], 'key_pr': contact[25], 'n_con': contact[26], 'canal': contact[27],'data_on': contact[28],
'data_t': contact[29],'utm_source': contact[30], 'utm_medium': contact[31], 'utm_campaign': contact[32],
'utm_term': contact[33], 'utm_content': contact[34], 'gcpc': contact[34]
} for contact in contacts]
return jsonify(contacts_json), 200
except Exception as e:
error_message = f"Error getting data from data_gc: {e}"
print(error_message)
return error_message, 500
# Поднимаем страницу обновления базы
@app.route('/biz_v', methods=['GET'])
def biz_v():
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
return "EUR 22", 200
return render_template('biz_v.html')
# ОБНОВЛЯЕМ CSV-файла
DATABASE2 = 'data_gc.db'
def parse_csv_data(data):
parsed_data = []
for item in data:
for key, value in item.items():
headers = key.split(';')
row = value.split(';')
parsed_data.append(dict(zip(headers, row)))
return parsed_data
def insert_data(data, verify_phone, add_curator):
global current_curator_index
with sqlite3.connect(DATABASE2) as conn:
cursor = conn.cursor()
for row in data:
name = row.get('Name', '')
phone = row.get('Phone', '').lstrip('+')
email = row.get('Email', '')
data_t = row.get('Date', '').strip('"')
cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
user_exists = cursor.fetchone()
if user_exists:
print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
continue
if add_curator == "1":
curator = curators[current_curator_index]
current_curator_index = (current_curator_index + 1) % len(curators)
else:
curator = row.get('curator', '')
if verify_phone == "1":
ws_st = verify_phone_number(phone)
else:
ws_st = row.get('ws_st', '')
columns = ['name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog', 'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'orders', 'curator', 'bonus', 'shop_status', 'pr3', 'pr4', 'pr5', 'gc_url', 'key_pr', 'n_con', 'canal', 'data_on', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gcpc']
values = [name, phone, email, row.get('vk_id', ''), row.get('chat_id', ''), ws_st, row.get('ws_stop', ''), row.get('web_st', 0), row.get('fin_prog', 0), row.get('b_city', ''), row.get('b_fin', ''), row.get('b_ban', ''), row.get('b_ign', ''), row.get('b_baners', ''), row.get('b_butt', ''), row.get('b_mess', ''), row.get('orders', ''), curator, row.get('bonus', ''), row.get('shop_status', ''), row.get('pr3', ''), row.get('pr4', ''), row.get('pr5', ''), row.get('gc_url', ''), row.get('key_pr', ''), row.get('n_con', ''), row.get('canal', ''), row.get('data_on', ''), row.get('data_t', ''), row.get('utm_source', ''), row.get('utm_medium', ''), row.get('utm_campaign', ''), row.get('utm_term', ''), row.get('utm_content', ''), row.get('gcpc', '')]
placeholders = ', '.join(['?' for _ in columns])
columns_str = ', '.join(columns)
query = f'''
INSERT INTO contacts ({columns_str})
VALUES ({placeholders})
'''
try:
cursor.execute(query, values)
except Exception as e:
print(f"Error inserting row: {row}")
print(f"Error message: {str(e)}")
conn.rollback()
raise
conn.commit()
@app.route('/upload_csv', methods=['POST'])
def upload_csv():
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and file.filename.endswith('.csv'):
stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
csv_input = csv.DictReader(stream)
data = [row for row in csv_input]
parsed_data = parse_csv_data(data)
verify_phone = request.form.get('verify_phone', '0')
add_curator = request.form.get('add_curator', '0')
print(f"Verify Phone: {verify_phone}")
print(f"Add Curator: {add_curator}")
insert_data(parsed_data, verify_phone, add_curator)
return jsonify({"message": "Data uploaded and inserted successfully"})
return jsonify({"error": "Invalid file format"}), 400
# ОБНОВЛЯЕМ JSON-файла
DATABASE = 'data_gc.db'
# Функция для очистки номера телефона
def clean_phone_number_j(phone_number):
return re.sub(r'\D', '', phone_number)
# Функция для вставки данных в базу данных
def insert_data_j(data):
conn = sqlite3.connect(DATABASE) # Подключаемся к базе данных
cursor = conn.cursor()
for row in data:
name = row.get('name', '')
phone = row.get('phone', '').lstrip('+')
email = row.get('email', '')
data_t = row.get('data_t', '').strip('"')
# Очистка номера телефона
phone = clean_phone_number_j(phone)
cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
user_exists = cursor.fetchone()
if user_exists:
print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
continue
columns = ['name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog', 'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'orders', 'curator', 'bonus', 'shop_status', 'pr3', 'pr4', 'pr5', 'gc_url', 'key_pr', 'n_con', 'canal', 'data_on', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gcpc']
values = [name, phone, email, row.get('vk_id', ''), row.get('chat_id', ''), row.get('ws_st', ''), row.get('ws_stop', ''), row.get('web_st', 0), row.get('fin_prog', 0), row.get('b_city', ''), row.get('b_fin', ''), row.get('b_ban', ''), row.get('b_ign', ''), row.get('b_baners', ''), row.get('b_butt', ''), row.get('b_mess', ''), row.get('orders', ''), row.get('curator', ''), row.get('bonus', ''), row.get('shop_status', ''), row.get('pr3', ''), row.get('pr4', ''), row.get('pr5', ''), row.get('gc_url', ''), row.get('key_pr', ''), row.get('n_con', ''), row.get('canal', ''), row.get('data_on', ''), row.get('data_t', ''), row.get('utm_source', ''), row.get('utm_medium', ''), row.get('utm_campaign', ''), row.get('utm_term', ''), row.get('utm_content', ''), row.get('gcpc', '')]
placeholders = ', '.join(['?' for _ in columns])
columns_str = ', '.join(columns)
query = f'''
INSERT INTO contacts ({columns_str})
VALUES ({placeholders})
'''
try:
cursor.execute(query, values)
except Exception as e:
print(f"Error inserting row: {row}")
print(f"Error message: {str(e)}")
conn.rollback()
continue
conn.commit()
conn.close()
# Маршрут для загрузки JSON-файла
@app.route('/upload_json', methods=['POST'])
def upload_json():
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and file.filename.endswith('.json'):
data = json.load(file)
insert_data_j(data)
return jsonify({"message": "Data uploaded and inserted successfully"})
return jsonify({"error": "Invalid file format"}), 400
# ОБНОВЛЯЕМ Бизон 365
DATABASE_NAME = 'data_gc.db'
def update_or_insert_user(db_name, user_data, mapping_template):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
# Получение email пользователя из данных
email = user_data.get('email')
if not email:
logging.error(f"User data missing email: {user_data}")
return
logging.debug(f"Processing user with email: {email}")
# Проверка существования пользователя в базе данных по email
cursor.execute("SELECT web_st, ws_st, b_mess FROM contacts WHERE email = ?", (email,))
user = cursor.fetchone()
logging.debug(f"User found: {user}")
# Вынесение увеличения значения web_st в отдельный блок
web_st_value = 1 # Инициализация значения web_st
if user:
# Проверка текущего значения web_st и его инкрементация
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
web_st_value = int(current_web_st) + 1
logging.debug(f"Calculated web_st_value: {web_st_value}")
# Обновление значения web_st
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
conn.commit()
conn.close()
logging.debug(f"User {email} web_st updated to {web_st_value}")
else:
conn.close()
logging.debug(f"User {email} not found, proceeding with insert")
# Открываем соединение снова для остальных операций
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
# Преобразование данных пользователя на основе шаблона сопоставления
transformed_data = {}
for json_key, db_column in mapping_template.items():
value = user_data.get(json_key, "")
if isinstance(value, list):
# Проверяем тип элементов списка
if all(isinstance(item, str) for item in value):
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
else:
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
transformed_data[db_column] = ""
else:
transformed_data[db_column] = str(value)
logging.debug(f"Transformed data: {transformed_data}")
# Заполнение обязательных полей значениями по умолчанию
required_fields = [
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
"orders", "curator", "bonus", "shop_status", "pr3", "pr4", "pr5", "gc_url",
"key_pr", "n_con", "canal", "data_on", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gcpc'
]
for field in required_fields:
if field not in transformed_data:
transformed_data[field] = ""
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
# Обработка номера телефона, если он есть
if 'phone' in user_data:
phone = user_data['phone']
if phone.startswith('+'):
phone = phone[1:]
transformed_data['phone'] = phone
logging.debug(f"Transformed data after phone processing: {transformed_data}")
# Добавление значения web_st в данные для вставки
transformed_data['web_st'] = web_st_value
# Обновление данных пользователя в базе данных
if user:
# Объединение новых сообщений с существующими
if 'b_mess' in transformed_data and user[2]:
transformed_data['b_mess'] = user[2] + "; " + transformed_data['b_mess']
update_query = "UPDATE contacts SET "
update_values = []
for column, value in transformed_data.items():
if column != 'ws_st' or not user[1]: # Проверка на наличие существующего ws_st
update_query += f"{column} = ?, "
update_values.append(value)
update_query = update_query.rstrip(", ") + " WHERE email = ?"
update_values.append(email)
logging.debug(f"Update query: {update_query} with values: {update_values}")
cursor.execute(update_query, update_values)
else:
columns = ', '.join(transformed_data.keys())
placeholders = ', '.join('?' for _ in transformed_data)
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
insert_values = list(transformed_data.values())
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
cursor.execute(insert_query, insert_values)
# Подтверждение изменений и закрытие соединения
conn.commit()
conn.close()
logging.debug(f"User with email {email} processed successfully")
@app.route('/send_request', methods=['POST'])
def send_request():
token = request.form.get('token')
min_date = request.form.get('minDate')
type = request.form.get('type')
url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&limit=100&type={type}'
response = requests.get(url, headers={'X-Token': token})
if response.status_code == 200:
data = response.json()
webinar_ids = [item['webinarId'] for item in data['list']]
return jsonify(webinar_ids)
else:
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
@app.route('/send_get_request', methods=['GET'])
def send_get_request():
token = request.args.get('token')
webinarId = request.args.get('webinarId')
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
try:
response = requests.get(url, headers={'X-Token': token})
response.raise_for_status() # Проверка на ошибки HTTP
data = response.json()
# Убедитесь, что report существует в данных
if data is None or 'report' not in data:
return jsonify({'error': 'No report data found'}), 500
report = data.get('report', {})
messages = data.get('messages', {})
# Проверка на None перед использованием
if report is None:
return jsonify({'error': 'No report data found in the response'}), 500
report_json_str = report.get('report', '{}')
try:
report_json = json.loads(report_json_str)
except json.JSONDecodeError:
report_json = {}
messages_json_str = report.get('messages', '{}')
try:
messages_json = json.loads(messages_json_str)
except json.JSONDecodeError:
messages_json = {}
users_meta = report_json.get('usersMeta', {})
processed_emails = set()
for user_id, user_data in users_meta.items():
user_messages = messages_json.get(user_id, [])
user_data['messages'] = user_messages
email = user_data.get('email')
if email and email not in processed_emails:
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
processed_emails.add(email)
return jsonify({'status': 'User data saved successfully'})
except requests.exceptions.RequestException as e:
return jsonify({'error': f'API request failed: {str(e)}'}), 500
api_bz = "SkrIONpr3ByeSIuEaBhr1bB8u4aBhSJfH8uEpB2rk7rI_ETrn"
@app.route('/webhookbz', methods=['POST'])
def webhookbz():
api_sys_control = request.args.get('api_sys')
if api_sys_control != api_key_sys:
return "EUR 22", 200
data = request.json
webinar_id = data.get('webinarId')
if not webinar_id:
return jsonify({'error': 'webinarId is required'}), 400
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
response = requests.get(url, headers={'X-Token': api_key_sys})
if response.status_code == 200:
data = response.json()
report = data.get('report', {})
messages = data.get('messages', {})
report_json_str = report.get('report', '{}')
try:
report_json = json.loads(report_json_str)
except json.JSONDecodeError:
report_json = {}
messages_json_str = report.get('messages', '{}')
try:
messages_json = json.loads(messages_json_str)
except json.JSONDecodeError:
messages_json = {}
users_meta = report_json.get('usersMeta', {})
processed_emails = set()
for user_id, user_data in users_meta.items():
user_messages = messages_json.get(user_id, [])
user_data['messages'] = user_messages
email = user_data.get('email')
if email and email not in processed_emails:
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
processed_emails.add(email)
return jsonify({'status': 'User data saved successfully'})
else:
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
# Отправка в НС1 в раб. дни нужно поправить нас групп
@app.route('/add_ns', methods=['GET'])
def handle_in1():
name = request.args.get('name')
email = request.args.get('email')
phone = request.args.get('phone')
base_url = 'https://api.notisend.ru/v1'
token = request.args.get('token')
list_id = request.args.get('list_id')
phone_id = request.args.get('phone_id')
name_id = request.args.get('name_id')
# Проверка наличия всех необходимых параметров
if not all([name, email, phone, token, list_id, phone_id, name_id]):
return jsonify({'error': 'Missing required parameters'}), 400
# Отправляем запросы в три разных места
response_ns = send_ns(base_url, token, list_id, email, phone, name, phone_id, name_id)
# Возвращаем список ответов
return jsonify({'responses': [response_ns]})
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return "No file part", 400
file = request.files['file']
if file.filename == '':
return "No selected file", 400
# Генерация уникального имени файла
unique_filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1]
save_path = os.path.join(UPLOAD_FOLDER, unique_filename)
file.save(save_path)
# Возвращаем полный URL загруженного файла с протоколом https
full_url = request.url_root.replace('http://', 'https://') + 'uploads/' + unique_filename
return f"File uploaded successfully and saved to {full_url}", 200
@app.route('/uploads/<filename>', methods=['GET'])
def uploaded_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
@app.route('/up_fa', methods=['GET'])
def up_fa():
return render_template('up_fa.html')
@app.route('/ns_info', methods=['GET'])
def ns_info():
return render_template('ns_info.html')
@app.route('/api/group/<int:group_id>/parameters', methods=['GET'])
def get_group_parameters(group_id):
api_token = request.args.get('apiToken')
if not api_token:
return jsonify({'error': 'API Token is required'}), 400
url = f'https://api.notisend.ru/v1/email/lists/{group_id}/parameters'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_token}'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
return jsonify(data)
except requests.RequestException as e:
return jsonify({'error': str(e)}), 500
@app.route('/up_page', methods=['POST'])
def upload_page():
if 'file' not in request.files:
return "No file part", 400
file = request.files['file']
if file.filename == '':
return "No selected file", 400
filename = request.form.get('filename')
if not filename:
return "Filename is required", 400
save_path = os.path.join(HTML_FOLDER, filename + '.html')
file.save(save_path)
# Возвращаем полный URL загруженного файла с протоколом https
full_url = request.url_root.replace('http://', 'https://') + filename
return f"Page uploaded successfully and saved to {full_url}", 200
@app.route('/<path:filename>', methods=['GET'])
def serve_html(filename):
if not filename.endswith('.html'):
filename += '.html'
return send_from_directory(HTML_FOLDER, filename)
@app.route('/up_page', methods=['GET'])
def up_page():
return render_template('up_page.html')
@app.route('/monitor', methods=['GET'])
def monitor():
# Получаем информацию о загруженных файлах
files = os.listdir(UPLOAD_FOLDER)
html_files = os.listdir(HTML_FOLDER)
# Получаем информацию о дисковом пространстве
total, used, free = shutil.disk_usage("/")
# Преобразуем байты в гигабайты для удобства чтения
total_gb = total // (2**30)
used_gb = used // (2**30)
free_gb = free // (2**30)
# Получаем информацию об использовании оперативной памяти
memory = psutil.virtual_memory()
memory_total_gb = memory.total // (2**30)
memory_used_gb = memory.used // (2**30)
memory_free_gb = memory.free // (2**30)
# Получаем информацию о количестве процессоров
cpu_count = psutil.cpu_count(logical=True)
return render_template('monitor.html',
uploaded_files=files,
uploaded_html_files=html_files,
disk_space={
'total': f"{total_gb} GB",
'used': f"{used_gb} GB",
'free': f"{free_gb} GB"
},
memory_usage={
'total': f"{memory_total_gb} GB",
'used': f"{memory_used_gb} GB",
'free': f"{memory_free_gb} GB"
},
cpu_count=cpu_count)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860))) |