← back to Resize It

scripts/spoonflower_full_workflow.py

232 lines

#!/usr/bin/env python3
"""
Complete Spoonflower workflow: Download, Resize, and Re-upload
"""

import sys
import time
import os
from playwright.sync_api import sync_playwright

def full_spoonflower_workflow(design_url, email, password, resized_image_path):
    """
    Complete workflow:
    1. Login to Spoonflower
    2. Navigate to design page
    3. Click "File Options" > "Replace Current File"
    4. Upload the resized image
    5. Return the design URL for user to verify
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            accept_downloads=True,
            viewport={'width': 1920, 'height': 1080}
        )
        page = context.new_page()

        # Login first
        print('🔐 Logging in to Spoonflower...')
        page.goto('https://www.spoonflower.com/login', wait_until='networkidle')
        time.sleep(2)

        try:
            # Find email input
            email_selectors = [
                'input[type="email"]',
                'input[type="text"]',
                'label:has-text("Email") + input',
                'input[placeholder*="email" i]'
            ]

            for selector in email_selectors:
                try:
                    if page.locator(selector).first.is_visible(timeout=5000):
                        page.locator(selector).first.fill(email)
                        print(f'   ✅ Email entered')
                        break
                except:
                    continue

            # Find password input
            password_selectors = [
                'input[type="password"]',
                'label:has-text("Password") + input'
            ]

            for selector in password_selectors:
                try:
                    if page.locator(selector).first.is_visible(timeout=5000):
                        page.locator(selector).first.fill(password)
                        print(f'   ✅ Password entered')
                        break
                except:
                    continue

            # Click submit
            submit_selectors = [
                'button[type="submit"]',
                'button:has-text("Sign In")',
                'button:has-text("Log In")',
                'input[type="submit"]'
            ]

            for selector in submit_selectors:
                try:
                    if page.locator(selector).first.is_visible(timeout=2000):
                        page.locator(selector).first.click()
                        print(f'   ✅ Login submitted')
                        break
                except:
                    continue

            print('⏳ Waiting for login to complete...')
            time.sleep(5)

        except Exception as e:
            print(f'❌ Login failed: {e}')
            browser.close()
            return None

        # Navigate to the design page
        print(f'🌐 Navigating to design page: {design_url}...')
        page.goto(design_url, wait_until='networkidle', timeout=60000)
        time.sleep(5)

        # Check if we got a 404
        content = page.content()
        if 'wrong turn' in content.lower() or ('404' in content and 'albuquerque' in content.lower()):
            print('❌ Design page returned 404 error')
            browser.close()
            return None

        print('✅ Design page loaded successfully')

        # Find and click File Options button
        print('🔍 Looking for File Options button...')
        time.sleep(3)

        file_options_selectors = [
            'button:has-text("File Options")',
            'button.chakra-menu__menu-button:has-text("File Options")',
            'button[id*="menu-button"]:has-text("File Options")',
            'button[aria-haspopup="menu"]:has-text("File Options")',
        ]

        file_options_clicked = False
        for selector in file_options_selectors:
            try:
                locator = page.locator(selector).first
                if locator.is_visible(timeout=5000):
                    print(f'   ✅ Found File Options button')
                    locator.scroll_into_view_if_needed()
                    time.sleep(1)
                    locator.click()
                    file_options_clicked = True
                    time.sleep(2)
                    break
            except Exception as e:
                continue

        if not file_options_clicked:
            print('❌ Could not find File Options button')
            page.screenshot(path='/tmp/no_file_options.png')
            browser.close()
            return None

        # Click "Replace Current File" option
        print('🔄 Looking for Replace Current File option...')

        replace_selectors = [
            '[role="menuitem"]:has-text("Replace")',
            'button[role="menuitem"]:has-text("Replace")',
            '.chakra-menu__menuitem:has-text("Replace")',
            'text=Replace Current File',
            'button:has-text("Replace Current File")'
        ]

        replace_clicked = False
        for selector in replace_selectors:
            try:
                if page.locator(selector).first.is_visible(timeout=5000):
                    print(f'   ✅ Found Replace option')
                    page.locator(selector).first.click()
                    replace_clicked = True
                    time.sleep(2)
                    break
            except Exception as e:
                continue

        if not replace_clicked:
            print('❌ Could not find Replace Current File option')
            page.screenshot(path='/tmp/no_replace_option.png')
            browser.close()
            return None

        # Find file input and upload the resized image
        print(f'📤 Uploading resized image: {resized_image_path}...')

        try:
            # Wait for file input to appear
            file_input = page.locator('input[type="file"]').first
            file_input.set_input_files(resized_image_path)
            print('   ✅ File selected for upload')
            time.sleep(3)

            # Look for upload/submit button if needed
            upload_selectors = [
                'button:has-text("Upload")',
                'button:has-text("Submit")',
                'button:has-text("Save")',
                'button[type="submit"]'
            ]

            for selector in upload_selectors:
                try:
                    if page.locator(selector).first.is_visible(timeout=2000):
                        page.locator(selector).first.click()
                        print(f'   ✅ Upload initiated')
                        break
                except:
                    continue

            # Wait for upload to complete
            print('⏳ Waiting for upload to complete...')
            time.sleep(10)

            # Check for success message or confirmation
            page.screenshot(path='/tmp/after_upload.png')
            print('   📸 Screenshot saved: /tmp/after_upload.png')

            print(f'\n✅ Upload complete!')
            print(f'🌐 View your design at: {design_url}')

            browser.close()
            return design_url

        except Exception as e:
            print(f'❌ Upload failed: {e}')
            page.screenshot(path='/tmp/upload_error.png')
            browser.close()
            return None


if __name__ == '__main__':
    if len(sys.argv) < 4:
        print('Usage: python3 spoonflower_full_workflow.py <design_url> <email> <password> <resized_image_path>')
        sys.exit(1)

    design_url = sys.argv[1]
    email = sys.argv[2]
    password = sys.argv[3]
    resized_image_path = sys.argv[4]

    result = full_spoonflower_workflow(design_url, email, password, resized_image_path)

    if result:
        print(f'\n✅ Success! Design updated at: {result}')
        sys.exit(0)
    else:
        print(f'\n❌ Failed to complete workflow')
        sys.exit(1)