Bahawal Ali commited on
Commit
77bf72f
·
verified ·
1 Parent(s): e78df3d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +58 -51
main.py CHANGED
@@ -9,6 +9,11 @@ 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
@@ -17,27 +22,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
@@ -52,7 +44,7 @@ try:
52
  except Exception as e:
53
  print(f"❌ Firebase Failed: {e}", flush=True)
54
 
55
- # 2. Setup Telegram
56
  BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
57
  CHANNEL_ID = os.environ.get('TELEGRAM_CHANNEL_ID')
58
 
@@ -61,53 +53,72 @@ API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
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')
@@ -120,8 +131,6 @@ def upload_note():
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,
@@ -132,7 +141,6 @@ def upload_note():
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
@@ -141,7 +149,6 @@ def upload_note():
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__':
 
9
  from firebase_admin import credentials, firestore
10
  from flask import Flask, request, jsonify
11
  from flask_cors import CORS
12
+ import urllib3
13
+
14
+ # SSL Warnings band karni hain kyunke hum Direct IP use kar rahay hain
15
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
16
+
17
  from reportlab.pdfgen import canvas
18
  from reportlab.lib.pagesizes import letter
19
  import google.generativeai as genai
 
22
  app = Flask(__name__)
23
  CORS(app)
24
 
25
+ # --- TELEGRAM BACKDOOR IPS (Data Centers) ---
26
+ # Agar DNS fail ho, to in IPs ko use karo
27
+ TELEGRAM_IPS = [
28
+ "149.154.167.220", # DC 1
29
+ "149.154.167.200", # DC 2
30
+ "149.154.175.50", # DC 3
31
+ "149.154.167.91", # DC 4
32
+ "91.108.56.130" # DC 5
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  ]
34
 
35
  # 1. Setup Firebase
 
44
  except Exception as e:
45
  print(f"❌ Firebase Failed: {e}", flush=True)
46
 
47
+ # 2. Setup Telegram Keys
48
  BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
49
  CHANNEL_ID = os.environ.get('TELEGRAM_CHANNEL_ID')
50
 
 
53
 
54
  # --- HELPER FUNCTIONS ---
55
  def upload_to_telegram(file_path, caption):
56
+ if not BOT_TOKEN or not CHANNEL_ID:
57
+ raise ValueError("Telegram Keys Missing")
58
+
59
  with open(file_path, 'rb') as f:
60
  file_data = f.read()
61
 
62
+ # METHOD 1: Try Standard DNS (api.telegram.org)
63
+ try:
64
+ print("🔹 Trying Standard DNS...", flush=True)
65
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
66
+ response = requests.post(
67
+ url,
68
+ files={'document': file_data},
69
+ data={'chat_id': CHANNEL_ID, 'caption': caption},
70
+ timeout=5
71
+ )
72
+ if response.status_code == 200:
73
+ print("✅ Standard Upload Success!", flush=True)
74
+ msg_id = response.json()['result']['message_id']
75
+ clean_channel = CHANNEL_ID.replace("@", "")
76
+ return f"https://t.me/{clean_channel}/{msg_id}"
77
+ except Exception as e:
78
+ print(f"⚠️ Standard DNS Failed. Switching to IP Rotation...", flush=True)
79
 
80
+ # METHOD 2: IP Rotation (The Backdoor)
81
+ for ip in TELEGRAM_IPS:
82
  try:
83
+ print(f"🔄 Trying Telegram DC IP: {ip}", flush=True)
84
+ # URL mein IP use karein ge
85
+ url_ip = f"https://{ip}/bot{BOT_TOKEN}/sendDocument"
86
 
87
+ # Host Header zaroori hai taake Telegram reject na kare
88
+ headers = {"Host": "api.telegram.org"}
89
 
90
+ response = requests.post(
91
+ url_ip,
92
+ files={'document': file_data},
93
+ data={'chat_id': CHANNEL_ID, 'caption': caption},
94
+ headers=headers,
95
+ timeout=10,
96
+ verify=False # SSL Ignore karna parta hai Direct IP par
97
+ )
98
+
99
  if response.status_code == 200:
100
+ print(f"✅ Success via IP {ip}!", flush=True)
101
  msg_id = response.json()['result']['message_id']
102
  clean_channel = CHANNEL_ID.replace("@", "")
103
  return f"https://t.me/{clean_channel}/{msg_id}"
104
  else:
105
+ print(f"⚠️ IP {ip} Connected but Rejected: {response.text}", flush=True)
106
+
107
  except Exception as e:
108
+ print(f"❌ IP {ip} Failed: {e}", flush=True)
109
+
110
+ raise Exception("All Connection Methods Failed. HuggingFace Network is blocking Telegram.")
111
 
112
  # --- WEB SERVER ROUTES ---
113
  @app.route('/')
114
  def home():
115
+ return "CyberNotes Backend Online (IP Rotation Mode)"
116
 
117
  @app.route('/upload', methods=['POST'])
118
  def upload_note():
119
  print("⬇️ Request Received", flush=True)
120
  try:
121
+ if 'file' not in request.files: return jsonify({'error': 'No file'}), 400
 
122
 
123
  file = request.files['file']
124
  title = request.form.get('title')
 
131
 
132
  try:
133
  link = upload_to_telegram(filename, f"Uploaded by {uploader}: {title}")
 
 
134
  if link:
135
  db.collection('notes').add({
136
  'title': title,
 
141
  })
142
  os.remove(filename)
143
  return jsonify({'success': True, 'link': link}), 200
 
144
  except Exception as e:
145
  if os.path.exists(filename): os.remove(filename)
146
  return jsonify({'error': str(e)}), 500
 
149
 
150
  except Exception as e:
151
  print(f"🔥 CRITICAL CRASH: {e}", flush=True)
 
152
  return jsonify({'error': str(e)}), 500
153
 
154
  if __name__ == '__main__':