diff --git a/utils/instagram_client.py b/utils/instagram_client.py index e530746..6243613 100644 --- a/utils/instagram_client.py +++ b/utils/instagram_client.py @@ -1,38 +1,47 @@ import os import json -import uuid -from pathlib import Path from instagrapi import Client -from dotenv import dotenv_values -# Load IG accounts from env (expects a JSON list string) INSTAGRAM_ACCOUNTS = json.loads(os.getenv("INSTAGRAM_ACCOUNTS", "[]")) - -# Path for storing session files SESSION_DIR = os.path.join(os.getcwd(), "instagram_sessions") os.makedirs(SESSION_DIR, exist_ok=True) +# Global cache of logged-in clients +client_cache: dict[str, Client] = {} + def get_logged_in_client() -> Client: + global client_cache + for account in INSTAGRAM_ACCOUNTS: username = account["username"] password = account["password"] - session_path = os.path.join(SESSION_DIR, f"{username}.json") + # โœ… Return from memory if already logged in + if username in client_cache: + return client_cache[username] + + session_path = os.path.join(SESSION_DIR, f"{username}.json") client = Client() try: if os.path.exists(session_path): with open(session_path, "r") as f: - settings = json.load(f) - client.load_settings(settings) - client.login(username, password) - print(f"โœ… Reused session: {username}") - else: - client.login(username, password) + session_data = json.load(f) + if isinstance(session_data, dict): + client.load_settings(session_data) + else: + raise ValueError("Invalid session format") + + client.login(username, password) + + # Save session if freshly logged in + if not os.path.exists(session_path): with open(session_path, "w") as f: json.dump(client.get_settings(), f) - print(f"โœ… Fresh login: {username}") + + print(f"โœ… Logged in and cached: {username}") + client_cache[username] = client return client except Exception as e: @@ -41,4 +50,4 @@ def get_logged_in_client() -> Client: os.remove(session_path) print(f"๐Ÿงน Removed invalid session for {username}") - raise Exception("โŒ All Instagram accounts failed login.") \ No newline at end of file + raise Exception("โŒ All Instagram accounts failed login.")