Bahawal Ali commited on
Commit
e07743d
Β·
verified Β·
1 Parent(s): 92fafb0

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -101
main.py CHANGED
@@ -1,42 +1,21 @@
1
  import os
2
  import json
3
  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
- 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
20
-
21
- # --- CONFIGURATION ---
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
36
  print("--- SYSTEM STARTUP ---", flush=True)
37
  try:
38
- cred_env = os.environ.get('FIREBASE_CREDENTIALS')
39
- cred_json = json.loads(cred_env)
40
  cred = credentials.Certificate(cred_json)
41
  firebase_admin.initialize_app(cred)
42
  db = firestore.client()
@@ -44,75 +23,47 @@ try:
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
-
51
- # 3. Setup Gemini
52
- API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
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():
@@ -126,11 +77,15 @@ def upload_note():
126
  uploader = request.form.get('uploaderName', 'Anonymous')
127
 
128
  if file:
129
- filename = f"/tmp/user_{int(time.time())}_{file.filename}"
130
- file.save(filename)
 
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,
@@ -139,16 +94,17 @@ def upload_note():
139
  'uploaderName': uploader,
140
  'timestamp': firestore.SERVER_TIMESTAMP
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
147
-
148
- return jsonify({'error': 'File empty'}), 400
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__':
 
1
  import os
2
  import json
3
  import time
 
 
 
 
4
  import firebase_admin
5
  from firebase_admin import credentials, firestore
6
  from flask import Flask, request, jsonify
7
  from flask_cors import CORS
8
+ from google.oauth2 import service_account
9
+ from googleapiclient.discovery import build
10
+ from googleapiclient.http import MediaFileUpload
11
 
 
 
 
 
 
 
 
 
12
  app = Flask(__name__)
13
  CORS(app)
14
 
15
+ # --- 1. FIREBASE SETUP ---
 
 
 
 
 
 
 
 
 
 
16
  print("--- SYSTEM STARTUP ---", flush=True)
17
  try:
18
+ cred_json = json.loads(os.environ.get('FIREBASE_CREDENTIALS'))
 
19
  cred = credentials.Certificate(cred_json)
20
  firebase_admin.initialize_app(cred)
21
  db = firestore.client()
 
23
  except Exception as e:
24
  print(f"❌ Firebase Failed: {e}", flush=True)
25
 
26
+ # --- 2. GOOGLE DRIVE SETUP ---
27
+ FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID')
28
+ SCOPES = ['https://www.googleapis.com/auth/drive']
29
+
30
+ def get_drive_service():
31
+ # Load Credentials from Secret
32
+ creds_json = json.loads(os.environ.get('GDRIVE_CREDENTIALS'))
33
+ creds = service_account.Credentials.from_service_account_info(creds_json, scopes=SCOPES)
34
+ return build('drive', 'v3', credentials=creds)
35
+
36
+ def upload_to_drive(file_path, filename):
37
+ print("πŸš€ Uploading to Google Drive...", flush=True)
38
+ service = get_drive_service()
39
+
40
+ file_metadata = {
41
+ 'name': filename,
42
+ 'parents': [FOLDER_ID] # File sirf tumhare Shared Folder mein jaye gi
43
+ }
44
+
45
+ media = MediaFileUpload(file_path, resumable=True)
46
+
47
+ # A. File Upload
48
+ file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
49
+ file_id = file.get('id')
50
+ print(f"βœ… Uploaded! File ID: {file_id}", flush=True)
51
+
52
+ # B. Permission Change (Make Public)
53
+ service.permissions().create(
54
+ fileId=file_id,
55
+ body={'type': 'anyone', 'role': 'reader'},
56
+ fields='id',
57
+ ).execute()
58
+
59
+ # C. Get View Link
60
+ result = service.files().get(fileId=file_id, fields='webViewLink').execute()
61
+ return result.get('webViewLink')
62
+
63
+ # --- ROUTES ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  @app.route('/')
65
  def home():
66
+ return "Google Drive Backend is Online"
67
 
68
  @app.route('/upload', methods=['POST'])
69
  def upload_note():
 
77
  uploader = request.form.get('uploaderName', 'Anonymous')
78
 
79
  if file:
80
+ # Temp Save (Server par 2 pal ke liye)
81
+ local_filename = f"/tmp/{int(time.time())}_{file.filename}"
82
+ file.save(local_filename)
83
 
84
  try:
85
+ # 1. Drive Upload
86
+ link = upload_to_drive(local_filename, file.filename)
87
+
88
+ # 2. Firebase Save
89
  if link:
90
  db.collection('notes').add({
91
  'title': title,
 
94
  'uploaderName': uploader,
95
  'timestamp': firestore.SERVER_TIMESTAMP
96
  })
97
+ # Cleanup
98
+ if os.path.exists(local_filename): os.remove(local_filename)
99
  return jsonify({'success': True, 'link': link}), 200
100
+
101
  except Exception as e:
102
+ print(f"❌ Error: {e}", flush=True)
103
+ if os.path.exists(local_filename): os.remove(local_filename)
104
  return jsonify({'error': str(e)}), 500
 
 
105
 
106
  except Exception as e:
107
+ print(f"πŸ”₯ Critical Error: {e}", flush=True)
108
  return jsonify({'error': str(e)}), 500
109
 
110
  if __name__ == '__main__':