Update app.py
Browse files
app.py
CHANGED
@@ -13,11 +13,112 @@ load_dotenv()
|
|
13 |
|
14 |
# Get credentials from environment variables
|
15 |
INSTAGRAM_USERNAME = os.getenv('INSTAGRAM_USERNAME')
|
|
|
16 |
|
17 |
# Configure logging
|
18 |
logging.basicConfig(level=logging.INFO)
|
19 |
logger = logging.getLogger(__name__)
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
# Directly embed session data
|
22 |
SESSION_DATA = {
|
23 |
"sessionid": "49379440378%3AAMKUUgo79iWhmt%3A1%3AAYcuPYtZFJAwzPlT0u_xuXkaiBHbDJ-8igmXkPBmzQ",
|
|
|
13 |
|
14 |
# Get credentials from environment variables
|
15 |
INSTAGRAM_USERNAME = os.getenv('INSTAGRAM_USERNAME')
|
16 |
+
INSTAGRAM_PASSWORD = os.getenv('INSTAGRAM_PASSWORD')
|
17 |
|
18 |
# Configure logging
|
19 |
logging.basicConfig(level=logging.INFO)
|
20 |
logger = logging.getLogger(__name__)
|
21 |
|
22 |
+
|
23 |
+
# Check if credentials are available
|
24 |
+
if not INSTAGRAM_USERNAME or not INSTAGRAM_PASSWORD:
|
25 |
+
logger.error("Instagram credentials are not set in the environment variables.")
|
26 |
+
raise RuntimeError("Instagram credentials missing.")
|
27 |
+
|
28 |
+
app = FastAPI(title="Instagram Post Downloader")
|
29 |
+
|
30 |
+
# Add CORS middleware
|
31 |
+
app.add_middleware(
|
32 |
+
CORSMiddleware,
|
33 |
+
allow_origins=["*"],
|
34 |
+
allow_credentials=True,
|
35 |
+
allow_methods=["*"],
|
36 |
+
allow_headers=["*"],
|
37 |
+
)
|
38 |
+
|
39 |
+
class PostRequest(BaseModel):
|
40 |
+
url: str
|
41 |
+
|
42 |
+
class DownloadResponse(BaseModel):
|
43 |
+
download_url: str
|
44 |
+
|
45 |
+
def extract_shortcode(url: str) -> str:
|
46 |
+
"""Extract Instagram post shortcode from URL"""
|
47 |
+
url = url.strip()
|
48 |
+
parts = url.split('/')
|
49 |
+
|
50 |
+
if 'instagram.com' not in parts:
|
51 |
+
raise ValueError("Invalid Instagram URL")
|
52 |
+
|
53 |
+
for i, part in enumerate(parts):
|
54 |
+
if part in ['p', 'reel', 'tv'] and (i+1) < len(parts):
|
55 |
+
shortcode = parts[i+1].split('?')[0]
|
56 |
+
return shortcode
|
57 |
+
|
58 |
+
if 'instagram.com/p/' in url:
|
59 |
+
return url.split('/p/')[1].split('/')[0].split('?')[0]
|
60 |
+
|
61 |
+
raise ValueError("Invalid Instagram URL")
|
62 |
+
|
63 |
+
@app.post("/dl", response_model=DownloadResponse)
|
64 |
+
async def download_post(request: PostRequest):
|
65 |
+
"""Download Instagram post and return media URL"""
|
66 |
+
try:
|
67 |
+
shortcode = extract_shortcode(request.url)
|
68 |
+
logger.info(f"Extracted shortcode: {shortcode}")
|
69 |
+
except ValueError as e:
|
70 |
+
logger.error(f"Invalid URL: {request.url}")
|
71 |
+
raise HTTPException(status_code=400, detail=str(e))
|
72 |
+
|
73 |
+
L = instaloader.Instaloader()
|
74 |
+
|
75 |
+
# Configure retry parameters
|
76 |
+
max_retries = 3
|
77 |
+
retry_delay = random.uniform(1, 3)
|
78 |
+
|
79 |
+
for attempt in range(max_retries):
|
80 |
+
try:
|
81 |
+
# Login to Instagram
|
82 |
+
L.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
|
83 |
+
logger.info("Successfully logged in to Instagram")
|
84 |
+
|
85 |
+
# Fetch post by shortcode
|
86 |
+
post = instaloader.Post.from_shortcode(L.context, shortcode)
|
87 |
+
logger.info(f"Fetched post: {post}")
|
88 |
+
break
|
89 |
+
|
90 |
+
except instaloader.exceptions.ConnectionException as e:
|
91 |
+
logger.error(f"Connection error (attempt {attempt + 1}): {e}")
|
92 |
+
if attempt == max_retries - 1:
|
93 |
+
raise HTTPException(status_code=500, detail="Failed to connect to Instagram after multiple attempts")
|
94 |
+
time.sleep(retry_delay)
|
95 |
+
retry_delay *= 2 # Exponential backoff
|
96 |
+
|
97 |
+
except instaloader.exceptions.InvalidArgumentException:
|
98 |
+
logger.error(f"Post not found for shortcode: {shortcode}")
|
99 |
+
raise HTTPException(status_code=404, detail="Post not found")
|
100 |
+
|
101 |
+
except instaloader.exceptions.InstaloaderException as e:
|
102 |
+
logger.error(f"Instaloader error: {e}")
|
103 |
+
raise HTTPException(status_code=500, detail="Error fetching post")
|
104 |
+
|
105 |
+
except Exception as e:
|
106 |
+
logger.error(f"Unexpected error: {e}")
|
107 |
+
raise HTTPException(status_code=500, detail="Internal server error")
|
108 |
+
|
109 |
+
# Get download URL based on media type
|
110 |
+
if post.is_video:
|
111 |
+
download_url = post.video_url
|
112 |
+
else:
|
113 |
+
download_url = post.url
|
114 |
+
|
115 |
+
if not download_url:
|
116 |
+
logger.error("No media found in post")
|
117 |
+
raise HTTPException(status_code=404, detail="No media found in post")
|
118 |
+
|
119 |
+
return {"download_url": download_url}
|
120 |
+
|
121 |
+
|
122 |
# Directly embed session data
|
123 |
SESSION_DATA = {
|
124 |
"sessionid": "49379440378%3AAMKUUgo79iWhmt%3A1%3AAYcuPYtZFJAwzPlT0u_xuXkaiBHbDJ-8igmXkPBmzQ",
|