Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -4,11 +4,15 @@ import time
|
|
| 4 |
import threading
|
| 5 |
import requests
|
| 6 |
import random
|
| 7 |
-
import traceback
|
| 8 |
import firebase_admin
|
| 9 |
from firebase_admin import credentials, firestore
|
| 10 |
from flask import Flask, request, jsonify
|
| 11 |
from flask_cors import CORS
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
from reportlab.pdfgen import canvas
|
| 13 |
from reportlab.lib.pagesizes import letter
|
| 14 |
import google.generativeai as genai
|
|
@@ -21,7 +25,7 @@ CORS(app)
|
|
| 21 |
db = None
|
| 22 |
firebase_error = None
|
| 23 |
|
| 24 |
-
# 1. Setup Firebase
|
| 25 |
print("--- SYSTEM STARTUP ---", flush=True)
|
| 26 |
try:
|
| 27 |
cred_env = os.environ.get('FIREBASE_CREDENTIALS')
|
|
@@ -47,25 +51,39 @@ API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
|
|
| 47 |
# --- HELPER FUNCTIONS ---
|
| 48 |
def upload_to_telegram(file_path, caption):
|
| 49 |
if not BOT_TOKEN or not CHANNEL_ID:
|
| 50 |
-
raise ValueError("Telegram Bot Token
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
print(f"📤 Uploading to Telegram: {CHANNEL_ID}", flush=True)
|
| 54 |
|
| 55 |
with open(file_path, 'rb') as f:
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 58 |
-
response = requests.post(
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
print(f"Telegram Response Code: {response.status_code}", flush=True)
|
| 61 |
-
print(f"Telegram Body: {response.text}", flush=True)
|
| 62 |
|
| 63 |
if response.status_code == 200:
|
| 64 |
msg_id = response.json()['result']['message_id']
|
| 65 |
clean_channel = CHANNEL_ID.replace("@", "")
|
| 66 |
return f"https://t.me/{clean_channel}/{msg_id}"
|
| 67 |
else:
|
| 68 |
-
# Return the EXACT error from Telegram
|
| 69 |
raise Exception(f"Telegram Error: {response.text}")
|
| 70 |
|
| 71 |
# --- WEB SERVER ROUTES ---
|
|
@@ -78,14 +96,12 @@ def home():
|
|
| 78 |
def upload_note():
|
| 79 |
print("⬇️ Request Received", flush=True)
|
| 80 |
|
| 81 |
-
# 1. Check Global Errors
|
| 82 |
if firebase_error:
|
| 83 |
return jsonify({'error': f"Server Config Error: {firebase_error}"}), 500
|
| 84 |
|
| 85 |
try:
|
| 86 |
-
# 2. Check File
|
| 87 |
if 'file' not in request.files:
|
| 88 |
-
return jsonify({'error': 'No file part sent
|
| 89 |
|
| 90 |
file = request.files['file']
|
| 91 |
title = request.form.get('title')
|
|
@@ -93,21 +109,19 @@ def upload_note():
|
|
| 93 |
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 94 |
|
| 95 |
if file:
|
| 96 |
-
#
|
| 97 |
filename = f"/tmp/user_{int(time.time())}_{file.filename}"
|
| 98 |
file.save(filename)
|
| 99 |
-
print(f"💾 File Saved Locally: {filename}", flush=True)
|
| 100 |
|
| 101 |
-
#
|
| 102 |
try:
|
| 103 |
link = upload_to_telegram(filename, f"Uploaded by {uploader}: {title}")
|
| 104 |
except Exception as e:
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
os.remove(filename)
|
| 108 |
return jsonify({'error': str(e)}), 500
|
| 109 |
|
| 110 |
-
#
|
| 111 |
if link:
|
| 112 |
db.collection('notes').add({
|
| 113 |
'title': title,
|
|
@@ -116,14 +130,13 @@ def upload_note():
|
|
| 116 |
'uploaderName': uploader,
|
| 117 |
'timestamp': firestore.SERVER_TIMESTAMP
|
| 118 |
})
|
| 119 |
-
os.remove(filename)
|
| 120 |
print("✅ Full Success!", flush=True)
|
| 121 |
return jsonify({'success': True, 'link': link}), 200
|
| 122 |
|
| 123 |
return jsonify({'error': 'File object empty'}), 400
|
| 124 |
|
| 125 |
except Exception as e:
|
| 126 |
-
# CATCH ALL CRASHES
|
| 127 |
print(f"🔥 CRITICAL CRASH: {e}", flush=True)
|
| 128 |
traceback.print_exc()
|
| 129 |
return jsonify({'error': f"Internal Crash: {str(e)}"}), 500
|
|
|
|
| 4 |
import threading
|
| 5 |
import requests
|
| 6 |
import random
|
| 7 |
+
import traceback
|
| 8 |
import firebase_admin
|
| 9 |
from firebase_admin import credentials, firestore
|
| 10 |
from flask import Flask, request, jsonify
|
| 11 |
from flask_cors import CORS
|
| 12 |
+
# Warnigs hide karne k liay (Direct IP use krnay pr warning aati ha)
|
| 13 |
+
import urllib3
|
| 14 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 15 |
+
|
| 16 |
from reportlab.pdfgen import canvas
|
| 17 |
from reportlab.lib.pagesizes import letter
|
| 18 |
import google.generativeai as genai
|
|
|
|
| 25 |
db = None
|
| 26 |
firebase_error = None
|
| 27 |
|
| 28 |
+
# 1. Setup Firebase
|
| 29 |
print("--- SYSTEM STARTUP ---", flush=True)
|
| 30 |
try:
|
| 31 |
cred_env = os.environ.get('FIREBASE_CREDENTIALS')
|
|
|
|
| 51 |
# --- HELPER FUNCTIONS ---
|
| 52 |
def upload_to_telegram(file_path, caption):
|
| 53 |
if not BOT_TOKEN or not CHANNEL_ID:
|
| 54 |
+
raise ValueError("Telegram Bot Token/Channel ID missing!")
|
| 55 |
|
| 56 |
+
# METHOD 1: Normal Domain
|
| 57 |
+
url_domain = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
|
| 58 |
+
# METHOD 2: Direct IP (Backup for DNS Errors)
|
| 59 |
+
url_ip = f"https://149.154.167.220/bot{BOT_TOKEN}/sendDocument"
|
| 60 |
+
|
| 61 |
print(f"📤 Uploading to Telegram: {CHANNEL_ID}", flush=True)
|
| 62 |
|
| 63 |
with open(file_path, 'rb') as f:
|
| 64 |
+
file_data = f.read() # Read once to use multiple times
|
| 65 |
+
|
| 66 |
+
# Try 1: Domain Name
|
| 67 |
+
try:
|
| 68 |
+
print("🔹 Trying Standard Connection...", flush=True)
|
| 69 |
+
files = {'document': file_data}
|
| 70 |
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 71 |
+
response = requests.post(url_domain, files=files, data=data, timeout=10)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"⚠️ Standard DNS Failed ({e}). Switching to Direct IP...", flush=True)
|
| 74 |
+
# Try 2: Direct IP (The Fix)
|
| 75 |
+
files = {'document': file_data}
|
| 76 |
+
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 77 |
+
# verify=False is needed because IP doesn't match Cert, but it works safely here
|
| 78 |
+
response = requests.post(url_ip, files=files, data=data, timeout=10, verify=False)
|
| 79 |
+
|
| 80 |
print(f"Telegram Response Code: {response.status_code}", flush=True)
|
|
|
|
| 81 |
|
| 82 |
if response.status_code == 200:
|
| 83 |
msg_id = response.json()['result']['message_id']
|
| 84 |
clean_channel = CHANNEL_ID.replace("@", "")
|
| 85 |
return f"https://t.me/{clean_channel}/{msg_id}"
|
| 86 |
else:
|
|
|
|
| 87 |
raise Exception(f"Telegram Error: {response.text}")
|
| 88 |
|
| 89 |
# --- WEB SERVER ROUTES ---
|
|
|
|
| 96 |
def upload_note():
|
| 97 |
print("⬇️ Request Received", flush=True)
|
| 98 |
|
|
|
|
| 99 |
if firebase_error:
|
| 100 |
return jsonify({'error': f"Server Config Error: {firebase_error}"}), 500
|
| 101 |
|
| 102 |
try:
|
|
|
|
| 103 |
if 'file' not in request.files:
|
| 104 |
+
return jsonify({'error': 'No file part sent'}), 400
|
| 105 |
|
| 106 |
file = request.files['file']
|
| 107 |
title = request.form.get('title')
|
|
|
|
| 109 |
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 110 |
|
| 111 |
if file:
|
| 112 |
+
# Save Temp File
|
| 113 |
filename = f"/tmp/user_{int(time.time())}_{file.filename}"
|
| 114 |
file.save(filename)
|
|
|
|
| 115 |
|
| 116 |
+
# Upload with Retries
|
| 117 |
try:
|
| 118 |
link = upload_to_telegram(filename, f"Uploaded by {uploader}: {title}")
|
| 119 |
except Exception as e:
|
| 120 |
+
print(f"❌ Upload Failed: {e}", flush=True)
|
| 121 |
+
if os.path.exists(filename): os.remove(filename)
|
|
|
|
| 122 |
return jsonify({'error': str(e)}), 500
|
| 123 |
|
| 124 |
+
# Save to Firebase
|
| 125 |
if link:
|
| 126 |
db.collection('notes').add({
|
| 127 |
'title': title,
|
|
|
|
| 130 |
'uploaderName': uploader,
|
| 131 |
'timestamp': firestore.SERVER_TIMESTAMP
|
| 132 |
})
|
| 133 |
+
if os.path.exists(filename): os.remove(filename)
|
| 134 |
print("✅ Full Success!", flush=True)
|
| 135 |
return jsonify({'success': True, 'link': link}), 200
|
| 136 |
|
| 137 |
return jsonify({'error': 'File object empty'}), 400
|
| 138 |
|
| 139 |
except Exception as e:
|
|
|
|
| 140 |
print(f"🔥 CRITICAL CRASH: {e}", flush=True)
|
| 141 |
traceback.print_exc()
|
| 142 |
return jsonify({'error': f"Internal Crash: {str(e)}"}), 500
|