File size: 6,666 Bytes
b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 752f5cc b4856f1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
import os
import time
import json
import logging
from playwright.sync_api import sync_playwright
# Setup logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("SessionManager")
# Configuration
SESSIONS_DIR = ".sessions"
USER_DATA_DIR = ".browser_data" # Folder to store actual browser profile data
# Platform Configuration Mapping
PLATFORMS = {
"twitter": {
"name": "Twitter/X",
"login_url": "https://twitter.com/i/flow/login",
"domain": "twitter.com",
},
"facebook": {
"name": "Facebook",
"login_url": "https://www.facebook.com/login",
"domain": "facebook.com",
},
"linkedin": {
"name": "LinkedIn",
"login_url": "https://www.linkedin.com/login",
"domain": "linkedin.com",
},
"reddit": {
"name": "Reddit",
"login_url": "https://old.reddit.com/login", # Default to Old Reddit for easier login
"domain": "reddit.com",
},
"instagram": {
"name": "Instagram",
"login_url": "https://www.instagram.com/accounts/login/",
"domain": "instagram.com",
},
}
def ensure_dirs():
"""Creates necessary directories."""
if not os.path.exists(SESSIONS_DIR):
os.makedirs(SESSIONS_DIR)
if not os.path.exists(USER_DATA_DIR):
os.makedirs(USER_DATA_DIR)
def create_session(platform_key: str):
"""
Launches a Persistent Browser Context.
- Uses FIREFOX for Reddit (bypasses Google-focused bot detection).
- Uses CHROMIUM for others (standard compatibility).
"""
platform = PLATFORMS.get(platform_key)
if not platform:
logger.error(f"Platform '{platform_key}' not found.")
return
ensure_dirs()
session_file = os.path.join(SESSIONS_DIR, f"{platform_key}_storage_state.json")
platform_user_data = os.path.join(USER_DATA_DIR, platform_key)
logger.info(f"Starting Persistent Session for {platform['name']}...")
with sync_playwright() as p:
# ---------------------------------------------------------
# STRATEGY 1: REDDIT (Use Firefox + Old Reddit)
# ---------------------------------------------------------
if platform_key == "reddit":
logger.info("Using Firefox Engine (Best for Reddit evasion)...")
context = p.firefox.launch_persistent_context(
user_data_dir=platform_user_data,
headless=False,
viewport={"width": 1280, "height": 720},
# Use a standard Firefox User Agent
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0",
)
# ---------------------------------------------------------
# STRATEGY 2: OTHERS (Use Chromium + Stealth Args)
# ---------------------------------------------------------
else:
logger.info("Using Chromium Engine (Standard)...")
context = p.chromium.launch_persistent_context(
user_data_dir=platform_user_data,
headless=False,
viewport={"width": 1280, "height": 720},
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
args=[
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--disable-infobars",
"--disable-dev-shm-usage",
"--disable-browser-side-navigation",
"--disable-features=IsolateOrigins,site-per-process",
],
)
# Apply Anti-Detection Script (Removes 'navigator.webdriver' property)
page = context.pages[0] if context.pages else context.new_page()
page.add_init_script(
"""
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
"""
)
try:
logger.info(f"Navigating to {platform['login_url']}...")
page.goto(platform["login_url"], wait_until="domcontentloaded")
# Interactive Loop
print("\n" + "=" * 50)
print(f"ACTION REQUIRED: Log in to {platform['name']} manually.")
if platform_key == "reddit":
print(
">> You are on 'Old Reddit'. The login box is on the right-hand side."
)
print(
">> Once logged in, it might redirect you to New Reddit. That is fine."
)
print("=" * 50 + "\n")
input(
f"Press ENTER here ONLY after you see the {platform['name']} Home Feed... "
)
# Save State
logger.info("Capturing storage state...")
context.storage_state(path=session_file)
# Verify file
if os.path.exists(session_file):
size = os.path.getsize(session_file)
logger.info(f"SUCCESS: Session saved to {session_file} ({size} bytes)")
else:
logger.error("Failed to save session file.")
except Exception as e:
logger.error(f"An error occurred: {e}")
finally:
context.close()
def list_sessions():
ensure_dirs()
files = [f for f in os.listdir(SESSIONS_DIR) if f.endswith("_storage_state.json")]
if not files:
print("No sessions found.")
else:
print(f"Found {len(files)} active sessions:")
for f in files:
print(f" - {f}")
if __name__ == "__main__":
while True:
print("\n--- Roger Session Manager (Stealth Mode) ---")
print("1. Create/Refresh Twitter Session")
print("2. Create/Refresh Facebook Session")
print("3. Create/Refresh LinkedIn Session")
print("4. Create/Refresh Reddit Session")
print("5. Create/Refresh Instagram Session")
print("6. List Saved Sessions")
print("q. Quit")
choice = input("Select an option: ").strip().lower()
if choice == "1":
create_session("twitter")
elif choice == "2":
create_session("facebook")
elif choice == "3":
create_session("linkedin")
elif choice == "4":
create_session("reddit")
elif choice == "5":
create_session("instagram")
elif choice == "6":
list_sessions()
elif choice == "q":
break
else:
print("Invalid option.")
|