Sim-tracker / main.py
Wasifali95's picture
Upload main.py
ef6b6af verified
Raw
History Blame Contribute Delete
8.12 kB
# main.py
from fastapi import FastAPI, Query
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import requests
import re
from bs4 import BeautifulSoup
import uvicorn
app = FastAPI(title="SIM Tracker API", version="1.0.0", docs_url=None, redoc_url=None)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Headers exactly as in your request
HEADERS = {
"Host": "simlivetracker.com.pk",
"sec-ch-ua-platform": "Android",
"user-agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Mobile Safari/537.36",
"sec-ch-ua": '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"',
"dnt": "1",
"sec-ch-ua-mobile": "?1",
"accept": "*/*",
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
"referer": "https://simlivetracker.com.pk/",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "en-US,en;q=0.9,ur-PK;q=0.8,ur;q=0.7",
"priority": "u=1, i"
}
def detect_network(mobile: str) -> str:
if not mobile or len(mobile) < 4:
return "Unknown"
try:
prefix = int(mobile[:4])
if 301 <= prefix <= 329:
return "Jazz"
elif 310 <= prefix <= 319:
return "Zong"
elif 330 <= prefix <= 339:
return "Ufone"
elif 340 <= prefix <= 359:
return "Telenor"
else:
return "Unknown"
except:
return "Unknown"
def parse_html_to_json(html: str, search: str, search_type: str) -> dict:
"""Convert HTML response to clean JSON"""
soup = BeautifulSoup(html, 'html.parser')
text = html
if search_type == "mobile":
# Extract single record
name_match = re.search(r'Name[:\s]*([^<\n]+)', text, re.IGNORECASE)
mobile_match = re.search(r'Mobile[:\s]*([0-9]+)', text, re.IGNORECASE)
cnic_match = re.search(r'CNIC[:\s]*([0-9-]+)', text, re.IGNORECASE)
address_match = re.search(r'Address[:\s]*([^<\n]+)', text, re.IGNORECASE)
result = {}
if mobile_match:
mobile_num = mobile_match.group(1).strip()
result["mobile"] = mobile_num
result["network"] = detect_network(mobile_num)
if name_match:
result["name"] = name_match.group(1).strip()
if cnic_match:
result["cnic"] = cnic_match.group(1).strip()
if address_match:
result["address"] = address_match.group(1).strip()
return result
else: # CNIC search
records = []
# Try table format
rows = soup.find_all('tr')
for row in rows:
cols = row.find_all('td')
if len(cols) >= 3:
mobile = cols[0].get_text(strip=True)
name = cols[1].get_text(strip=True)
cnic_val = cols[2].get_text(strip=True)
address_val = cols[3].get_text(strip=True) if len(cols) > 3 else ""
if mobile and re.match(r'^03[0-9]{9}$', mobile):
records.append({
"name": name,
"mobile": mobile,
"cnic": cnic_val,
"network": detect_network(mobile),
"address": address_val
})
# If no table, try regex
if not records:
pattern = r'([0-9]{11}).*?([A-Za-z\s]+).*?([0-9-]{13,15})'
matches = re.findall(pattern, text, re.DOTALL)
for match in matches:
mobile = match[0].strip()
name = match[1].strip()
cnic_val = match[2].strip()
if mobile and re.match(r'^03[0-9]{9}$', mobile):
records.append({
"name": name,
"mobile": mobile,
"cnic": cnic_val,
"network": detect_network(mobile)
})
return {
"cnic": search,
"total_sims": len(records),
"records": records
}
def fetch_from_your_api(search: str, search_type: str) -> dict:
"""Fetch from simlivetracker.com.pk/api.php"""
url = "https://simlivetracker.com.pk/api.php"
params = {
"search": search,
"type": search_type
}
try:
response = requests.get(url, params=params, headers=HEADERS, timeout=15)
if response.status_code == 200:
html = response.text
# Parse HTML to JSON
data = parse_html_to_json(html, search, search_type)
if data:
return {"success": True, "data": data}
else:
return {"success": False, "message": "Could not parse data from HTML"}
else:
return {"success": False, "message": f"API returned status {response.status_code}"}
except Exception as e:
return {"success": False, "message": str(e)}
@app.get("/")
async def root():
return JSONResponse({
"status": "active",
"service": "SIM Database Tracker",
"endpoints": {
"mobile": "/api?search=03007058868",
"cnic": "/api?search=35201-1234567-8"
},
"developer": "WASIF ALI",
"telegram": "@THE_FREE_HACKS"
})
@app.get("/api")
async def search(search: str = Query(..., description="Mobile number or CNIC")):
search_clean = re.sub(r'\s+', '', search)
# Detect type
if re.match(r'^03[0-9]{9}$', search_clean):
search_type = "mobile"
elif re.match(r'^[0-9]{5}-[0-9]{7}-[0-9]$', search_clean) or re.match(r'^[0-9]{13}$', search_clean):
search_type = "cnic"
if re.match(r'^[0-9]{13}$', search_clean):
search_clean = f"{search_clean[:5]}-{search_clean[5:12]}-{search_clean[12]}"
else:
return JSONResponse({
"status": False,
"message": "Invalid format. Use mobile (03xxxxxxxxx) or CNIC (xxxxx-xxxxxxx-x)",
"developer": "WASIF ALI",
"telegram": "@THE_FREE_HACKS"
}, status_code=400)
# Fetch from your API
result = fetch_from_your_api(search_clean, search_type)
if result.get("success"):
response_data = {
"status": True,
"developer": "WASIF ALI",
"telegram": "@THE_FREE_HACKS"
}
if search_type == "mobile":
data = result["data"]
if data.get("name"):
response_data["name"] = data["name"]
if data.get("mobile"):
response_data["mobile"] = data["mobile"]
if data.get("cnic"):
response_data["cnic"] = data["cnic"]
if data.get("network"):
response_data["network"] = data["network"]
if data.get("address"):
response_data["address"] = data["address"]
else:
data = result["data"]
if data.get("cnic"):
response_data["cnic"] = data["cnic"]
if data.get("total_sims"):
response_data["total_sims"] = data["total_sims"]
if data.get("records"):
response_data["records"] = data["records"]
return JSONResponse(response_data)
else:
return JSONResponse({
"status": False,
"message": result.get("message", "No data found"),
"developer": "WASIF ALI",
"telegram": "@THE_FREE_HACKS"
}, status_code=404)
@app.get("/test")
async def test():
return JSONResponse({
"status": True,
"message": "API is working. Using your API: simlivetracker.com.pk",
"developer": "WASIF ALI",
"telegram": "@THE_FREE_HACKS"
})
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)