File size: 20,328 Bytes
35cdf61 |
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 |
import psycopg2
from psycopg2 import sql
import uuid
from datetime import datetime, timedelta
db_params = {
'dbname': 'API_DB',
'user': 'postgres',
'password': '4b95dfe8-4644-46ce-a4fe-648d6d4860a4',
'host': 'localhost',
'port': '5432'
}
# conn = psycopg2.connect(**db_params)
# conn.autocommit = True
# cur = conn.cursor()
#user db
def insert_user(db_params ,uid: uuid.UUID, paid: bool, first_name: str, last_name: str, email: str, password: str):
if uid is None or paid is None:
return False
insert_query = """
INSERT INTO users (id, paid, first_name, last_name, email, dor, la, password)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
"""
try:
current_time = datetime.now()
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(insert_query, (str(uid), paid, first_name, last_name, email, current_time, current_time, password))
conn.commit()
return True
except Exception as e:
print(f"Error: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def user_exists(db_params, user_id: uuid.UUID) -> bool:
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
query = "SELECT EXISTS (SELECT 1 FROM users WHERE id = %s);"
cur.execute(query, (str(user_id),))
result = cur.fetchone()
if result:
exists = result[0]
return exists
else:
return False
except Exception as e:
print(f"Error checking if user exists: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def has_user_paid(db_params, user_id: uuid.UUID) -> bool:
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
query = "SELECT paid FROM users WHERE id = %s;"
cur.execute(query, (str(user_id),))
result = cur.fetchone()
if result:
paid_status = result[0]
return paid_status
else:
return False
except Exception as e:
print(f"Error checking if user has paid: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def get_user_id_by_email(db_params, email: str) -> uuid.UUID:
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
query = "SELECT id FROM users WHERE email = %s;"
cur.execute(query, (email,))
result = cur.fetchone()
if result:
user_id = result[0]
return uuid.UUID(user_id)
else:
return None
except Exception as e:
print(f"Error retrieving user ID by email: {e}")
return None
finally:
if cur:
cur.close()
if conn:
conn.close()
def user_change_password(db_params, email: str, old_password: str, new_password: str) -> bool:
try:
user_id = get_user_id_by_email(db_params, email)
if user_id is None:
return False
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
query = "SELECT password FROM users WHERE id = %s;"
cur.execute(query, (str(user_id),))
result = cur.fetchone()
if result:
current_password = result[0]
if current_password == old_password:
update_query = "UPDATE users SET password = %s WHERE id = %s;"
cur.execute(update_query, (new_password, str(user_id)))
conn.commit()
return True
else:
return False
else:
return False
except Exception as e:
print(f"Error changing password: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def update_user_paid_state(db_params, email: str = None, user_id: uuid.UUID = None, paid_state: bool = False) -> bool:
if email is None and user_id is None:
print("Error: Either email or user ID must be provided.")
return False
if email is not None:
user_id = get_user_id_by_email(db_params, email)
if user_id is None:
return False
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
update_query = "UPDATE users SET paid = %s WHERE id = %s;"
cur.execute(update_query, (paid_state, str(user_id)))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error updating paid state: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def delete_user_by_id(db_params, user_id: uuid.UUID) -> bool:
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
delete_query = "DELETE FROM users WHERE id = %s;"
cur.execute(delete_query, (str(user_id),))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error deleting user by ID: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def update_last_activity(db_params, email: str = None, user_id: uuid.UUID = None) -> bool:
if email is None and user_id is None:
print("Error: Either email or user ID must be provided.")
return False
if email is not None:
user_id = get_user_id_by_email(db_params, email)
if user_id is None:
return False
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
current_time = datetime.now()
update_query = "UPDATE users SET la = %s WHERE id = %s;"
cur.execute(update_query, (current_time, str(user_id)))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error updating last activity: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
#request table
def insert_request(db_params, request_id: uuid.UUID, video_id: uuid.UUID, user_id: uuid.UUID, image_base64: str, public: bool, report: bool,
request_service: str, registration_token: str) -> bool:
if not user_exists(db_params, user_id):
print("Error: User does not exist.")
return False
paid = has_user_paid(db_params, user_id)
insert_query = """
INSERT INTO request (id, video_id, user_id, image_base64, status, tor, toc, public, paid, report, request_service, registration_token)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
"""
conn = None
cur = None
try:
current_time = datetime.now()
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(insert_query, (
str(request_id),
str(video_id),
str(user_id),
image_base64,
'Requested',
current_time,
None,
public,
paid,
report,
request_service,
registration_token
))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error inserting request: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def get_request_data(db_params, request_id: uuid.UUID):
select_query = """
SELECT image_base64, video_id, request_service, registration_token
FROM request
WHERE id = %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(select_query, (str(request_id),))
result = cur.fetchone()
if result is None:
return None
image_base64 = result[0]
video_id = result[1]
request_service = result[2]
registration_token = result[3]
return [image_base64, video_id, request_service, registration_token]
except Exception as e:
print(f"Error retrieving image and video: {e}")
return None
finally:
if cur:
cur.close()
if conn:
conn.close()
def update_request_status(db_params, request_id: uuid.UUID, new_status: str) -> bool:
update_query = """
UPDATE request
SET status = %s,
dor = %s
WHERE id = %s;
"""
conn = None
cur = None
try:
current_time = datetime.now()
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(update_query, (new_status, current_time, str(request_id)))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error updating request status: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def check_and_update_request(db_params, request_service: str, video_id: uuid.UUID, image_base64: str, registration_token: str):
five_minutes_ago = datetime.now() - timedelta(minutes=5)
check_query = """
SELECT id, dor
FROM request
WHERE video_id = %s
AND image_base64 = %s
AND created_at >= %s
AND status = 'Requested'
AND request_service = %s
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(check_query, (str(video_id), image_base64, five_minutes_ago, request_service))
existing_request = cur.fetchone()
if existing_request:
existing_request_id, dor, existing_token, existing_ls = existing_request
update_query = """
UPDATE request
SET dor = %s,
registration_token = %s,
ls = %s
WHERE id = %s
"""
cur.execute(update_query, (datetime.now(), registration_token, datetime.now(), str(existing_request_id)))
conn.commit()
return existing_request_id
return None
except Exception as e:
print(f"Error checking or updating request: {e}")
return None
finally:
if cur:
cur.close()
if conn:
conn.close()
def update_reported_status(db_params, request_id: uuid.UUID) -> bool:
update_query = """
UPDATE request
SET report = TRUE
WHERE id = %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(update_query, (str(request_id),))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error updating reported status: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def request_id_exists(db_params, request_id: uuid.UUID) -> bool:
check_query = """
SELECT EXISTS (
SELECT 1
FROM request
WHERE id = %s
);
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(check_query, (str(request_id),))
exists = cur.fetchone()[0]
return exists
except Exception as e:
print(f"Error checking if request ID exists: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def delete_request(db_params, request_id: uuid.UUID) -> bool:
delete_query = """
DELETE FROM request
WHERE id = %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(delete_query, (str(request_id),))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error deleting request: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def update_request_status(db_params, request_id: uuid.UUID, new_status: str) -> bool:
update_query = """
UPDATE request
SET status = %s
WHERE id = %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(update_query, (new_status, str(request_id)))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error updating request status: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def get_oldest_requests(db_params, limit: int):
select_query = """
SELECT id, video_id, image_base64, tor, paid
FROM request
WHERE status = 'Requested'-- AND paid = True
ORDER BY CASE WHEN paid THEN 0 ELSE 1 END, tor ASC
LIMIT %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(select_query, (limit,))
rows = cur.fetchall()
if rows:
return rows
else:
return None
except Exception as e:
print(f"Error retrieving oldest requests: {e}")
return None
finally:
if cur:
cur.close()
if conn:
conn.close()
def request_remove_image(db_params, request_id: uuid.UUID) -> bool:
check_query = """
SELECT image_base64
FROM request
WHERE id = %s;
"""
update_query = """
UPDATE request
SET image_base64 = 'image_placeholder'
WHERE id = %s AND image_base64 IS NOT NULL AND image_base64 <> '';
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(check_query, (str(request_id),))
result = cur.fetchone()
if result is None or result[0] in (None, ''):
return False
cur.execute(update_query, (str(request_id),))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error updating image_base64: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
# ban list
def insert_ban(db_params, ip: str, reason: str) -> bool:
try:
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
cursor.execute('''INSERT INTO ban_list (ip, reason) VALUES (%s, %s)''', (ip, reason))
conn.commit()
return True
except Exception as e:
print(f"Error inserting ban: {e}")
return False
finally:
if cursor:
cursor.close()
if conn:
conn.close()
def search_ban(db_params, ip: str) -> bool:
try:
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
cursor.execute('''SELECT * FROM ban_list WHERE ip = %s''', (ip,))
rows = cursor.fetchall()
return len(rows) > 0
except Exception as e:
print(f"Error searching ban list: {e}")
return False
finally:
if cursor:
cursor.close()
if conn:
conn.close()
#content
def get_videos_data(db_params):
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
try:
cursor.execute('''
SELECT id, title, backend_video_url, backend_thumbnail_url
FROM videos
ORDER BY created_at DESC
LIMIT 4
''')
latest_videos = cursor.fetchall()
cursor.execute('''
SELECT id, title, backend_video_url, backend_thumbnail_url
FROM videos
ORDER BY likes DESC
LIMIT 4
''')
trending_videos = cursor.fetchall()
cursor.execute('''
SELECT id, title, backend_video_url, backend_thumbnail_url
FROM videos
ORDER BY hits DESC
LIMIT 4
''')
hot_videos = cursor.fetchall()
cursor.execute('''
SELECT DISTINCT category FROM videos
''')
categories = cursor.fetchall()
def format_video(video):
return {
"id": video[0],
"url": video[2],
"title": video[1],
"info": "",
"thumbnail": video[3]
}
response = []
latest_category = {
"id": "latest",
"title": "Latest",
"urls": [format_video(video) for video in latest_videos]
}
trending_category = {
"id": "trending",
"title": "Trending",
"urls": [format_video(video) for video in trending_videos]
}
hot_category = {
"id": "hot",
"title": "Hot",
"urls": [format_video(video) for video in hot_videos]
}
response.extend([trending_category, latest_category, hot_category])
for category in categories:
category_name = category[0]
cursor.execute('''
SELECT id, title, backend_video_url, backend_thumbnail_url
FROM videos
WHERE category = %s
''', (category_name,))
videos_in_category = cursor.fetchall()
category_data = {
"id": category_name,
"title": category_name,
"urls": [format_video(video) for video in videos_in_category]
}
response.append(category_data)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if cursor is not None:
cursor.close()
if conn is not None:
conn.close()
return response
def video_id_exists(db_params, video_id: uuid.UUID) -> bool:
check_query = """
SELECT EXISTS (
SELECT 1
FROM videos
WHERE id = %s
);
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(check_query, (str(video_id),))
exists = cur.fetchone()[0]
return exists
except Exception as e:
print(f"Error checking if video ID exists: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def increment_likes(db_params, video_id: uuid.UUID) -> bool:
increment_query = """
UPDATE videos
SET likes = likes + 1
WHERE id = %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(increment_query, (str(video_id),))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error incrementing likes: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
def increment_dislikes(db_params, video_id: uuid.UUID) -> bool:
increment_query = """
UPDATE videos
SET dislikes = dislikes + 1
WHERE id = %s;
"""
try:
conn = psycopg2.connect(**db_params)
cur = conn.cursor()
cur.execute(increment_query, (str(video_id),))
conn.commit()
if cur.rowcount > 0:
return True
else:
return False
except Exception as e:
print(f"Error incrementing dislikes: {e}")
return False
finally:
if cur:
cur.close()
if conn:
conn.close()
|