Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -9,10 +9,6 @@ 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
|
|
@@ -21,24 +17,39 @@ import google.generativeai as genai
|
|
| 21 |
app = Flask(__name__)
|
| 22 |
CORS(app)
|
| 23 |
|
| 24 |
-
# ---
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# 1. Setup Firebase
|
| 29 |
print("--- SYSTEM STARTUP ---", flush=True)
|
| 30 |
try:
|
| 31 |
cred_env = os.environ.get('FIREBASE_CREDENTIALS')
|
| 32 |
-
if not cred_env:
|
| 33 |
-
raise ValueError("FIREBASE_CREDENTIALS secret is missing!")
|
| 34 |
-
|
| 35 |
cred_json = json.loads(cred_env)
|
| 36 |
cred = credentials.Certificate(cred_json)
|
| 37 |
firebase_admin.initialize_app(cred)
|
| 38 |
db = firestore.client()
|
| 39 |
print("✅ Firebase Connected", flush=True)
|
| 40 |
except Exception as e:
|
| 41 |
-
firebase_error = str(e)
|
| 42 |
print(f"❌ Firebase Failed: {e}", flush=True)
|
| 43 |
|
| 44 |
# 2. Setup Telegram
|
|
@@ -50,96 +61,88 @@ API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
|
|
| 50 |
|
| 51 |
# --- HELPER FUNCTIONS ---
|
| 52 |
def upload_to_telegram(file_path, caption):
|
| 53 |
-
|
| 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()
|
| 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 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
# --- WEB SERVER ROUTES ---
|
| 90 |
@app.route('/')
|
| 91 |
def home():
|
| 92 |
-
|
| 93 |
-
return f"CyberNotes Backend Status: {status}"
|
| 94 |
|
| 95 |
@app.route('/upload', methods=['POST'])
|
| 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
|
| 105 |
-
|
| 106 |
file = request.files['file']
|
| 107 |
title = request.form.get('title')
|
| 108 |
subject = request.form.get('subject')
|
| 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,
|
| 128 |
-
'subject': subject,
|
| 129 |
-
'downloadUrl': link,
|
| 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
|
| 138 |
|
| 139 |
except Exception as e:
|
| 140 |
print(f"🔥 CRITICAL CRASH: {e}", flush=True)
|
| 141 |
traceback.print_exc()
|
| 142 |
-
return jsonify({'error':
|
| 143 |
|
| 144 |
if __name__ == '__main__':
|
| 145 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 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
|
|
|
|
| 17 |
app = Flask(__name__)
|
| 18 |
CORS(app)
|
| 19 |
|
| 20 |
+
# --- PROXY LIST (SOCKS5) ---
|
| 21 |
+
PROXY_LIST = [
|
| 22 |
+
"152.53.171.242:27531", "152.53.171.242:20580", "152.53.171.242:50159",
|
| 23 |
+
"152.53.171.242:32671", "152.53.171.242:46254", "152.53.171.242:18561",
|
| 24 |
+
"152.53.171.242:44695", "152.53.171.242:35920", "152.53.171.242:40778",
|
| 25 |
+
"152.53.171.242:28938", "152.53.171.242:25091", "152.53.171.242:49787",
|
| 26 |
+
"152.53.171.242:49799", "152.53.171.242:13932", "152.53.171.242:42438",
|
| 27 |
+
"152.53.171.242:19387", "152.53.171.242:58521", "152.53.171.242:57759",
|
| 28 |
+
"152.53.171.242:29600", "152.53.171.242:32788", "152.53.171.242:54461",
|
| 29 |
+
"152.53.171.242:11757", "152.53.171.242:54167", "152.53.171.242:44706",
|
| 30 |
+
"152.53.171.242:33944", "152.53.171.242:44806", "152.53.171.242:22677",
|
| 31 |
+
"152.53.171.242:56656", "152.53.171.242:47484", "152.53.171.242:19500",
|
| 32 |
+
"152.53.171.242:47439", "152.53.171.242:40052", "152.53.171.242:38237",
|
| 33 |
+
"152.53.171.242:44878", "152.53.171.242:36927", "152.53.171.242:17504",
|
| 34 |
+
"152.53.171.242:10374", "152.53.171.242:16743", "152.53.171.242:20061",
|
| 35 |
+
"152.53.171.242:55961", "152.53.171.242:38373", "152.53.171.242:46310",
|
| 36 |
+
"152.53.171.242:28766", "152.53.171.242:59148", "152.53.171.242:27849",
|
| 37 |
+
"152.53.171.242:31814", "152.53.171.242:17547", "152.53.171.242:47115",
|
| 38 |
+
"152.53.171.242:21797", "152.53.171.242:23422", "152.53.171.242:26254",
|
| 39 |
+
"152.53.171.242:41561", "152.53.171.242:27778", "152.53.171.242:57664",
|
| 40 |
+
"152.53.171.242:26260", "152.53.171.242:18091"
|
| 41 |
+
]
|
| 42 |
|
| 43 |
# 1. Setup Firebase
|
| 44 |
print("--- SYSTEM STARTUP ---", flush=True)
|
| 45 |
try:
|
| 46 |
cred_env = os.environ.get('FIREBASE_CREDENTIALS')
|
|
|
|
|
|
|
|
|
|
| 47 |
cred_json = json.loads(cred_env)
|
| 48 |
cred = credentials.Certificate(cred_json)
|
| 49 |
firebase_admin.initialize_app(cred)
|
| 50 |
db = firestore.client()
|
| 51 |
print("✅ Firebase Connected", flush=True)
|
| 52 |
except Exception as e:
|
|
|
|
| 53 |
print(f"❌ Firebase Failed: {e}", flush=True)
|
| 54 |
|
| 55 |
# 2. Setup Telegram
|
|
|
|
| 61 |
|
| 62 |
# --- HELPER FUNCTIONS ---
|
| 63 |
def upload_to_telegram(file_path, caption):
|
| 64 |
+
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
with open(file_path, 'rb') as f:
|
| 67 |
+
file_data = f.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
# Retry Logic with Proxies
|
| 70 |
+
max_retries = 5
|
| 71 |
+
for attempt in range(max_retries):
|
| 72 |
+
proxy_ip = random.choice(PROXY_LIST)
|
| 73 |
+
print(f"🔄 Attempt {attempt+1}/{max_retries} using Proxy: {proxy_ip}", flush=True)
|
| 74 |
+
|
| 75 |
+
# 'socks5h' means -> DNS resolution happens on the Proxy Server (Bypasses local DNS error)
|
| 76 |
+
proxies = {
|
| 77 |
+
'http': f'socks5h://{proxy_ip}',
|
| 78 |
+
'https': f'socks5h://{proxy_ip}'
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
files = {'document': file_data}
|
| 83 |
+
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 84 |
+
|
| 85 |
+
response = requests.post(url, files=files, data=data, proxies=proxies, timeout=15)
|
| 86 |
+
|
| 87 |
+
if response.status_code == 200:
|
| 88 |
+
print("✅ Telegram Upload Success via Proxy!", flush=True)
|
| 89 |
+
msg_id = response.json()['result']['message_id']
|
| 90 |
+
clean_channel = CHANNEL_ID.replace("@", "")
|
| 91 |
+
return f"https://t.me/{clean_channel}/{msg_id}"
|
| 92 |
+
else:
|
| 93 |
+
print(f"⚠️ Proxy Connected but API Error: {response.text}", flush=True)
|
| 94 |
+
|
| 95 |
+
except Exception as e:
|
| 96 |
+
print(f"❌ Proxy {proxy_ip} Failed: {e}", flush=True)
|
| 97 |
+
|
| 98 |
+
raise Exception("All Proxies Failed to Connect to Telegram")
|
| 99 |
|
| 100 |
# --- WEB SERVER ROUTES ---
|
| 101 |
@app.route('/')
|
| 102 |
def home():
|
| 103 |
+
return "CyberNotes Backend Online with SOCKS5 Support."
|
|
|
|
| 104 |
|
| 105 |
@app.route('/upload', methods=['POST'])
|
| 106 |
def upload_note():
|
| 107 |
print("⬇️ Request Received", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
try:
|
| 109 |
if 'file' not in request.files:
|
| 110 |
+
return jsonify({'error': 'No file part'}), 400
|
| 111 |
+
|
| 112 |
file = request.files['file']
|
| 113 |
title = request.form.get('title')
|
| 114 |
subject = request.form.get('subject')
|
| 115 |
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 116 |
|
| 117 |
if file:
|
|
|
|
| 118 |
filename = f"/tmp/user_{int(time.time())}_{file.filename}"
|
| 119 |
file.save(filename)
|
| 120 |
|
|
|
|
| 121 |
try:
|
| 122 |
link = upload_to_telegram(filename, f"Uploaded by {uploader}: {title}")
|
| 123 |
+
|
| 124 |
+
# Save to Firebase
|
| 125 |
+
if link:
|
| 126 |
+
db.collection('notes').add({
|
| 127 |
+
'title': title,
|
| 128 |
+
'subject': subject,
|
| 129 |
+
'downloadUrl': link,
|
| 130 |
+
'uploaderName': uploader,
|
| 131 |
+
'timestamp': firestore.SERVER_TIMESTAMP
|
| 132 |
+
})
|
| 133 |
+
os.remove(filename)
|
| 134 |
+
return jsonify({'success': True, 'link': link}), 200
|
| 135 |
+
|
| 136 |
except Exception as e:
|
|
|
|
| 137 |
if os.path.exists(filename): os.remove(filename)
|
| 138 |
return jsonify({'error': str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
return jsonify({'error': 'File empty'}), 400
|
| 141 |
|
| 142 |
except Exception as e:
|
| 143 |
print(f"🔥 CRITICAL CRASH: {e}", flush=True)
|
| 144 |
traceback.print_exc()
|
| 145 |
+
return jsonify({'error': str(e)}), 500
|
| 146 |
|
| 147 |
if __name__ == '__main__':
|
| 148 |
app.run(host='0.0.0.0', port=7860)
|