from selenium import webdriver
import re
import requests
import os

# Input Snapchat profile URL
snapchat_url = input("Enter the Snapchat profile URL: ").strip()

# Set up Selenium and fetch the page source
print(f"Opening Snapchat profile: {snapchat_url}")
driver = webdriver.Chrome()  # Ensure ChromeDriver is installed
driver.get(snapchat_url)

import time
time.sleep(2)  # Give time for the page to load fully

html_content = driver.page_source
driver.quit()

# Extract the username using regex
username_pattern = r'<span class="Header_desktopSubscriberTextOnMedia__U_dVM Header_subscribersDesktop__lTKg1">(.*?)</span>'
username_match = re.search(username_pattern, html_content)

if username_match:
    creator_name = username_match.group(1).strip().replace(" ", "_")
    print(f"Creator's username extracted: {creator_name}")
else:
    print("Could not extract the username. Exiting...")
    exit()

# Create a main folder to save all Snapchat photos
main_folder = "snapchat_photos"
if not os.path.exists(main_folder):
    os.makedirs(main_folder)

# Create a subfolder for the specific creator
creator_folder = os.path.join(main_folder, creator_name)
if not os.path.exists(creator_folder):
    os.makedirs(creator_folder)

# Use regex to find all photo embed links
pattern = r'"mediaPreviewUrl":\{"value":"(https://.*?)"}'
matches = re.findall(pattern, html_content)

# Download and save each photo in the creator's folder
if matches:
    print(f"Extracted Embed Links and Saving Photos to '{creator_folder}':")
    for idx, link in enumerate(matches):
        try:
            # Request the image
            response = requests.get(link)
            if response.status_code == 200:
                filename = os.path.join(creator_folder, f"photo{idx + 1}.jpg")
                with open(filename, 'wb') as f:
                    f.write(response.content)
                print(f"Saved: {filename}")
            else:
                print(f"Failed to download: {link}")
        except Exception as e:
            print(f"Error downloading {link}: {e}")
else:
    print("No embed links were found.")
