{"repo_name": "cursor-free-vip", "file_name": "/cursor-free-vip/new_signup.py", "inference_info": {"prefix_code": "from DrissionPage import ChromiumOptions, ChromiumPage\nimport time\nimport os\nimport signal\nimport random\nfrom colorama import Fore, Style\nimport configparser\nfrom pathlib import Path\nimport sys\nfrom config import get_config \nfrom utils import get_default_browser_path as utils_get_default_browser_path\n\n# Add global variable at the beginning of the file\n_translator = None\n\n# Add global variable to track our Chrome processes\n_chrome_process_ids = []\n\ndef cleanup_chrome_processes(translator=None):\n \"\"\"Clean only Chrome processes launched by this script\"\"\"\n global _chrome_process_ids\n \n if not _chrome_process_ids:\n print(\"\\nNo Chrome processes to clean...\")\n return\n \n print(\"\\nCleaning Chrome processes launched by this script...\")\n try:\n if os.name == 'nt':\n for pid in _chrome_process_ids:\n try:\n os.system(f'taskkill /F /PID {pid} /T 2>nul')\n except:\n pass\n else:\n for pid in _chrome_process_ids:\n try:\n os.kill(pid, signal.SIGTERM)\n except:\n pass\n _chrome_process_ids = [] # Reset the list after cleanup\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.cleanup_error', error=str(e))}{Style.RESET_ALL}\")\n else:\n print(f\"清理进程时出错: {e}\")\n\ndef signal_handler(signum, frame):\n \"\"\"Handle Ctrl+C signal\"\"\"\n global _translator\n if _translator:\n print(f\"{Fore.CYAN}{_translator.get('register.exit_signal')}{Style.RESET_ALL}\")\n else:\n print(\"\\n接收到退出信号,正在关闭...\")\n cleanup_chrome_processes(_translator)\n os._exit(0)\n\ndef simulate_human_input(page, url, config, translator=None):\n \"\"\"Visit URL\"\"\"\n if translator:\n print(f\"{Fore.CYAN}🚀 {translator.get('register.visiting_url')}: {url}{Style.RESET_ALL}\")\n \n # First visit blank page\n page.get('about:blank')\n time.sleep(get_random_wait_time(config, 'page_load_wait'))\n \n # Visit target page\n page.get(url)\n time.sleep(get_random_wait_time(config, 'page_load_wait'))\n\ndef fill_signup_form(page, first_name, last_name, email, config, translator=None):\n \"\"\"Fill signup form\"\"\"\n try:\n if translator:\n print(f\"{Fore.CYAN}📧 {translator.get('register.filling_form')}{Style.RESET_ALL}\")\n else:\n print(\"\\n正在填写注册表单...\")\n \n # Fill first name\n first_name_input = page.ele(\"@name=first_name\")\n if first_name_input:\n first_name_input.input(first_name)\n time.sleep(get_random_wait_time(config, 'input_wait'))\n \n # Fill last name\n last_name_input = page.ele(\"@name=last_name\")\n if last_name_input:\n last_name_input.input(last_name)\n time.sleep(get_random_wait_time(config, 'input_wait'))\n \n # Fill email\n email_input = page.ele(\"@name=email\")\n if email_input:\n email_input.input(email)\n time.sleep(get_random_wait_time(config, 'input_wait'))\n \n # Click submit button\n submit_button = page.ele(\"@type=submit\")\n if submit_button:\n submit_button.click()\n time.sleep(get_random_wait_time(config, 'submit_wait'))\n \n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.form_success')}{Style.RESET_ALL}\")\n else:\n print(\"Form filled successfully\")\n return True\n \n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.form_error', error=str(e))}{Style.RESET_ALL}\")\n else:\n print(f\"Error filling form: {e}\")\n return False\n\ndef get_user_documents_path():\n \"\"\"Get user Documents folder path\"\"\"\n if sys.platform == \"win32\":\n try:\n import winreg\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Shell Folders\") as key:\n documents_path, _ = winreg.QueryValueEx(key, \"Personal\")\n return documents_path\n except Exception as e:\n # fallback\n return os.path.join(os.path.expanduser(\"~\"), \"Documents\")\n elif sys.platform == \"darwin\":\n return os.path.join(os.path.expanduser(\"~\"), \"Documents\")\n else: # Linux\n # Get actual user's home directory\n sudo_user = os.environ.get('SUDO_USER')\n if sudo_user:\n return os.path.join(\"/home\", sudo_user, \"Documents\")\n return os.path.join(os.path.expanduser(\"~\"), \"Documents\")\n\ndef get_random_wait_time(config, timing_type='page_load_wait'):\n \"\"\"\n Get random wait time from config\n Args:\n config: ConfigParser object\n timing_type: Type of timing to get (page_load_wait, input_wait, submit_wait)\n Returns:\n float: Random wait time or fixed time\n \"\"\"\n try:\n if not config.has_section('Timing'):\n return random.uniform(0.1, 0.8) # Default value\n \n if timing_type == 'random':\n min_time = float(config.get('Timing', 'min_random_time', fallback='0.1'))\n max_time = float(config.get('Timing', 'max_random_time', fallback='0.8'))\n return random.uniform(min_time, max_time)\n \n time_value = config.get('Timing', timing_type, fallback='0.1-0.8')\n \n # Check if it's a fixed time value\n if '-' not in time_value and ',' not in time_value:\n return float(time_value) # Return fixed time\n \n # Process range time\n min_time, max_time = map(float, time_value.split('-' if '-' in time_value else ','))\n return random.uniform(min_time, max_time)\n except:\n return random.uniform(0.1, 0.8) # Return default value when error\n\ndef setup_driver(translator=None):\n \"\"\"Setup browser driver\"\"\"\n global _chrome_process_ids\n \n try:\n # Get config\n config = get_config(translator)\n \n # Get browser type and path\n browser_type = config.get('Browser', 'default_browser', fallback='chrome')\n browser_path = config.get('Browser', f'{browser_type}_path', fallback=utils_get_default_browser_path(browser_type))\n \n if not browser_path or not os.path.exists(browser_path):\n if translator:\n print(f\"{Fore.YELLOW}⚠️ {browser_type} {translator.get('register.browser_path_invalid')}{Style.RESET_ALL}\")\n browser_path = utils_get_default_browser_path(browser_type)\n\n # For backward compatibility, also check Chrome path\n if browser_type == 'chrome':\n chrome_path = config.get('Chrome', 'chromepath', fallback=None)\n if chrome_path and os.path.exists(chrome_path):\n browser_path = chrome_path\n\n # Set browser options\n co = ChromiumOptions()\n \n # Set browser path\n co.set_browser_path(browser_path)\n \n # Use incognito mode\n co.set_argument(\"--incognito\")\n\n if sys.platform == \"linux\":\n # Set Linux specific options\n co.set_argument(\"--no-sandbox\")\n \n # Set random port\n co.auto_port()\n \n # Use headless mode (must be set to False, simulate human operation)\n co.headless(False)\n \n # Log browser info\n if translator:\n print(f\"{Fore.CYAN}🌐 {translator.get('register.using_browser', browser=browser_type, path=browser_path)}{Style.RESET_ALL}\")\n \n try:\n # Load extension\n extension_path = os.path.join(os.getcwd(), \"turnstilePatch\")\n if os.path.exists(extension_path):\n co.set_argument(\"--allow-extensions-in-incognito\")\n co.add_extension(extension_path)\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.extension_load_error', error=str(e))}{Style.RESET_ALL}\")\n else:\n print(f\"Error loading extension: {e}\")\n \n if translator:\n print(f\"{Fore.CYAN}🚀 {translator.get('register.starting_browser')}{Style.RESET_ALL}\")\n else:\n print(\"Starting browser...\")\n \n # Record Chrome processes before launching\n before_pids = []\n try:\n import psutil\n browser_process_names = {\n 'chrome': ['chrome', 'chromium'],\n 'edge': ['msedge', 'edge'],\n 'firefox': ['firefox'],\n 'brave': ['brave', 'brave-browser']\n }\n process_names = browser_process_names.get(browser_type, ['chrome'])\n before_pids = [p.pid for p in psutil.process_iter() if any(name in p.name().lower() for name in process_names)]\n except:\n pass\n \n # Launch browser\n page = ChromiumPage(co)\n \n # Wait a moment for browser to fully launch\n time.sleep(1)\n \n # Record browser processes after launching and find new ones\n try:\n import psutil\n process_names = browser_process_names.get(browser_type, ['chrome'])\n after_pids = [p.pid for p in psutil.process_iter() if any(name in p.name().lower() for name in process_names)]\n # Find new browser processes\n new_pids = [pid for pid in after_pids if pid not in before_pids]\n _chrome_process_ids.extend(new_pids)\n \n if _chrome_process_ids:\n print(f\"{translator.get('register.tracking_processes', count=len(_chrome_process_ids), browser=browser_type)}\")\n else:\n print(f\"{Fore.YELLOW}Warning: {translator.get('register.no_new_processes_detected', browser=browser_type)}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{translator.get('register.could_not_track_processes', browser=browser_type, error=str(e))}\")\n \n return config, page\n\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.browser_setup_error', error=str(e))}{Style.RESET_ALL}\")\n else:\n print(f\"Error setting up browser: {e}\")\n raise\n\ndef handle_turnstile(page, config, translator=None):\n \"\"\"Handle Turnstile verification\"\"\"\n try:\n if translator:\n print(f\"{Fore.CYAN}🔄 {translator.get('register.handling_turnstile')}{Style.RESET_ALL}\")\n else:\n print(\"\\nHandling Turnstile verification...\")\n \n # from config\n turnstile_time = float(config.get('Turnstile', 'handle_turnstile_time', fallback='2'))\n random_time_str = config.get('Turnstile', 'handle_turnstile_random_time', fallback='1-3')\n \n # Parse random time range\n try:\n min_time, max_time = map(float, random_time_str.split('-'))\n except:\n min_time, max_time = 1, 3 # Default value\n \n max_retries = 2\n retry_count = 0\n\n while retry_count < max_retries:\n retry_count += 1\n if translator:\n print(f\"{Fore.CYAN}🔄 {translator.get('register.retry_verification', attempt=retry_count)}{Style.RESET_ALL}\")\n else:\n print(f\"Attempt {retry_count} of verification...\")\n\n try:\n # Try to reset turnstile\n page.run_js(\"try { turnstile.reset() } catch(e) { }\")\n time.sleep(turnstile_time) # from config\n\n # Locate verification box element\n challenge_check = (\n page.ele(\"@id=cf-turnstile\", timeout=2)\n .child()\n .shadow_root.ele(\"tag:iframe\")\n .ele(\"tag:body\")\n .sr(\"tag:input\")\n )\n\n if challenge_check:\n if translator:\n print(f\"{Fore.CYAN}🔄 {translator.get('register.detect_turnstile')}{Style.RESET_ALL}\")\n else:\n print(\"Detected verification box...\")\n \n # from config\n time.sleep(random.uniform(min_time, max_time))\n challenge_check.click()\n time.sleep(turnstile_time) # from config\n\n # check verification result\n if check_verification_success(page, translator):\n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n else:\n print(\"Verification successful!\")\n return True\n\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_failed')}{Style.RESET_ALL}\")\n else:\n print(f\"Verification attempt failed: {e}\")\n\n # Check if verification has been successful\n if check_verification_success(page, translator):\n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n else:\n print(\"Verification successful!\")\n return True\n\n time.sleep(random.uniform(min_time, max_time))\n\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_failed')}{Style.RESET_ALL}\")\n else:\n print(\"Exceeded maximum retry attempts\")\n return False\n\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_error', error=str(e))}{Style.RESET_ALL}\")\n else:\n print(f\"Error in verification process: {e}\")\n return False\n\ndef check_verification_success(page, translator=None):\n \"\"\"Check if verification is successful\"\"\"\n try:\n # Check if there is a subsequent form element, indicating verification has passed\n if (page.ele(\"@name=password\", timeout=0.5) or \n page.ele(\"@name=email\", timeout=0.5) or\n page.ele(\"@data-index=0\", timeout=0.5) or\n page.ele(\"Account Settings\", timeout=0.5)):\n return True\n \n # Check if there is an error message\n error_messages = [\n 'xpath://div[contains(text(), \"Can\\'t verify the user is human\")]',\n 'xpath://div[contains(text(), \"Error: 600010\")]',\n 'xpath://div[contains(text(), \"Please try again\")]'\n ]\n \n for error_xpath in error_messages:\n if page.ele(error_xpath):\n return False\n \n return False\n except:\n return False\n\ndef generate_password(length=12):\n \"\"\"Generate random password\"\"\"\n chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*\"\n return ''.join(random.choices(chars, k=length))\n\ndef fill_password(page, password: str, config, translator=None):\n \"\"\"\n Fill password form\n \"\"\"\n try:\n print(f\"{Fore.CYAN}🔑 {translator.get('register.setting_password') if translator else 'Setting password'}{Style.RESET_ALL}\")\n \n # Fill password\n password_input = page.ele(\"@name=password\")\n print(f\"{Fore.CYAN}🔑 {translator.get('register.setting_on_password')}: {password}{Style.RESET_ALL}\")\n if password_input:\n password_input.input(password)\n\n # Click submit button\n submit_button = page.ele(\"@type=submit\")\n if submit_button:\n submit_button.click()\n time.sleep(get_random_wait_time(config, 'submit_wait'))\n \n print(f\"{Fore.GREEN}✅ {translator.get('register.password_submitted') if translator else 'Password submitted'}{Style.RESET_ALL}\")\n \n return True\n \n except Exception as e:\n print(f\"{Fore.RED}❌ {translator.get('register.password_error', error=str(e)) if translator else f'Error setting password: {str(e)}'}{Style.RESET_ALL}\")\n\n return False\n\ndef handle_verification_code(browser_tab, email_tab, controller, config, translator=None):\n \"\"\"Handle verification code\"\"\"\n try:\n if translator:\n print(f\"\\n{Fore.CYAN}🔄 {translator.get('register.waiting_for_verification_code')}{Style.RESET_ALL}\")\n \n # Check if using manual input verification code\n if hasattr(controller, 'get_verification_code') and email_tab is None: # Manual mode\n verification_code = controller.get_verification_code()\n if verification_code:\n # Fill verification code in registration page\n for i, digit in enumerate(verification_code):\n browser_tab.ele(f\"@data-index={i}\").input(digit)\n time.sleep(get_random_wait_time(config, 'verification_code_input'))\n \n print(f\"{translator.get('register.verification_success')}\")\n time.sleep(get_random_wait_time(config, 'verification_success_wait'))\n \n # Handle last Turnstile verification\n if handle_turnstile(browser_tab, config, translator):\n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'verification_retry_wait'))\n \n # Visit settings page\n print(f\"{Fore.CYAN}🔑 {translator.get('register.visiting_url')}: https://www.cursor.com/settings{Style.RESET_ALL}\")\n browser_tab.get(\"https://www.cursor.com/settings\")\n time.sleep(get_random_wait_time(config, 'settings_page_load_wait'))\n return True, browser_tab\n \n return False, None\n \n # Automatic verification code logic\n elif email_tab:\n print(f\"{Fore.CYAN}🔄 {translator.get('register.waiting_for_verification_code')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'email_check_initial_wait'))\n\n # Use existing email_tab to refresh email\n email_tab.refresh_inbox()\n time.sleep(get_random_wait_time(config, 'email_refresh_wait'))\n\n # Check if there is a verification code email\n if email_tab.check_for_cursor_email():\n verification_code = email_tab.get_verification_code()\n if verification_code:\n # Fill verification code in registration page\n for i, digit in enumerate(verification_code):\n browser_tab.ele(f\"@data-index={i}\").input(digit)\n time.sleep(get_random_wait_time(config, 'verification_code_input'))\n \n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'verification_success_wait'))\n \n # Handle last Turnstile verification\n if handle_turnstile(browser_tab, config, translator):\n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'verification_retry_wait'))\n \n # Visit settings page\n if translator:\n print(f\"{Fore.CYAN}🔑 {translator.get('register.visiting_url')}: https://www.cursor.com/settings{Style.RESET_ALL}\")\n browser_tab.get(\"https://www.cursor.com/settings\")\n time.sleep(get_random_wait_time(config, 'settings_page_load_wait'))\n return True, browser_tab\n \n else:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_failed')}{Style.RESET_ALL}\")\n else:\n print(\"最后一次验证失败\")\n return False, None\n \n # Get verification code, set timeout\n verification_code = None\n max_attempts = 20\n retry_interval = get_random_wait_time(config, 'retry_interval') # Use get_random_wait_time\n start_time = time.time()\n timeout = float(config.get('Timing', 'max_timeout', fallback='160')) # This can be kept unchanged because it is a fixed value\n\n if translator:\n print(f\"{Fore.CYAN}{translator.get('register.start_getting_verification_code')}{Style.RESET_ALL}\")\n \n for attempt in range(max_attempts):\n # Check if timeout\n if time.time() - start_time > timeout:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_timeout')}{Style.RESET_ALL}\")\n break\n \n verification_code = controller.get_verification_code()\n if verification_code:\n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n break\n \n remaining_time = int(timeout - (time.time() - start_time))\n if translator:\n print(f\"{Fore.CYAN}{translator.get('register.try_get_code', attempt=attempt + 1, time=remaining_time)}{Style.RESET_ALL}\")\n \n # Refresh email\n email_tab.refresh_inbox()\n time.sleep(retry_interval) # Use get_random_wait_time\n \n if verification_code:\n # Fill verification code in registration page\n for i, digit in enumerate(verification_code):\n browser_tab.ele(f\"@data-index={i}\").input(digit)\n time.sleep(get_random_wait_time(config, 'verification_code_input'))\n \n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'verification_success_wait'))\n \n # Handle last Turnstile verification\n if handle_turnstile(browser_tab, config, translator):\n if translator:\n print(f\"{Fore.GREEN}✅ {translator.get('register.verification_success')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'verification_retry_wait'))\n \n # Visit settings page\n if translator:\n print(f\"{Fore.CYAN}{translator.get('register.visiting_url')}: https://www.cursor.com/settings{Style.RESET_ALL}\")\n browser_tab.get(\"https://www.cursor.com/settings\")\n time.sleep(get_random_wait_time(config, 'settings_page_load_wait'))\n \n # Return success directly, let cursor_register.py handle account information acquisition\n return True, browser_tab\n \n else:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_failed')}{Style.RESET_ALL}\")\n return False, None\n \n return False, None\n \n except Exception as e:\n if translator:\n print(f\"{Fore.RED}❌ {translator.get('register.verification_error', error=str(e))}{Style.RESET_ALL}\")\n return False, None\n\ndef handle_sign_in(browser_tab, email, password, translator=None):\n \"\"\"Handle login process\"\"\"\n try:\n # Check if on login page\n sign_in_header = browser_tab.ele('xpath://h1[contains(text(), \"Sign in\")]')\n if not sign_in_header:\n return True # If not on login page, it means login is successful\n \n print(f\"{Fore.CYAN}检测到登录页面,开始登录...{Style.RESET_ALL}\")\n \n # Fill email\n email_input = browser_tab.ele('@name=email')\n if email_input:\n email_input.input(email)\n time.sleep(1)\n \n # Click Continue\n continue_button = browser_tab.ele('xpath://button[contains(@class, \"BrandedButton\") and text()=\"Continue\"]')\n if continue_button:\n continue_button.click()\n time.sleep(2)\n \n # Handle Turnstile verification\n if handle_turnstile(browser_tab, translator):\n # Fill password\n password_input = browser_tab.ele('@name=password')\n ", "suffix_code": "\n \n print(f\"{Fore.RED}Login failed{Style.RESET_ALL}\")\n return False\n \n except Exception as e:\n print(f\"{Fore.RED}Login process error: {str(e)}{Style.RESET_ALL}\")\n return False\n\ndef main(email=None, password=None, first_name=None, last_name=None, email_tab=None, controller=None, translator=None):\n \"\"\"Main function, can receive account information, email tab, and translator\"\"\"\n global _translator\n global _chrome_process_ids\n _translator = translator # Save to global variable\n _chrome_process_ids = [] # Reset the process IDs list\n \n signal.signal(signal.SIGINT, signal_handler)\n signal.signal(signal.SIGTERM, signal_handler)\n \n page = None\n success = False\n try:\n config, page = setup_driver(translator)\n if translator:\n print(f\"{Fore.CYAN}🚀 {translator.get('register.browser_started')}{Style.RESET_ALL}\")\n \n # Visit registration page\n url = \"https://authenticator.cursor.sh/sign-up\"\n \n # Visit page\n simulate_human_input(page, url, config, translator)\n if translator:\n print(f\"{Fore.CYAN}🔄 {translator.get('register.waiting_for_page_load')}{Style.RESET_ALL}\")\n time.sleep(get_random_wait_time(config, 'page_load_wait'))\n \n # If account information is not provided, generate random information\n if not all([email, password, first_name, last_name]):\n first_name = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=6)).capitalize()\n last_name = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=6)).capitalize()\n email = f\"{first_name.lower()}{random.randint(100,999)}@example.com\"\n password = generate_password()\n \n # Save account information\n with open('test_accounts.txt', 'a', encoding='utf-8') as f:\n f.write(f\"\\n{'='*50}\\n\")\n f.write(f\"Email: {email}\\n\")\n f.write(f\"Password: {password}\\n\")\n f.write(f\"{'='*50}\\n\")\n \n # Fill form\n if fill_signup_form(page, first_name, last_name, email, config, translator):\n if translator:\n print(f\"\\n{Fore.GREEN}✅ {translator.get('register.form_submitted')}{Style.RESET_ALL}\")\n \n # Handle first Turnstile verification\n if handle_turnstile(page, config, translator):\n if translator:\n print(f\"\\n{Fore.GREEN}✅ {translator.get('register.first_verification_passed')}{Style.RESET_ALL}\")\n \n # Fill password\n if fill_password(page, password, config, translator):\n if translator:\n print(f\"\\n{Fore.CYAN}🔄 {translator.get('register.waiting_for_second_verification')}{Style.RESET_ALL}\")\n \n # Handle second Turnstile verification\n if handle_turnstile(page, config, translator):\n if translator:\n print(f\"\\n{Fore.CYAN}🔄 {translator.get('register.waiting_for_verification_code')}{Style.RESET_ALL}\")\n if handle_verification_code(page, email_tab, controller, config, translator):\n success = True\n return True, page\n else:\n print(f\"\\n{Fore.RED}❌ {translator.get('register.verification_code_processing_failed') if translator else 'Verification code processing failed'}{Style.RESET_ALL}\")\n else:\n print(f\"\\n{Fore.RED}❌ {translator.get('register.second_verification_failed') if translator else 'Second verification failed'}{Style.RESET_ALL}\")\n else:\n print(f\"\\n{Fore.RED}❌ {translator.get('register.second_verification_failed') if translator else 'Second verification failed'}{Style.RESET_ALL}\")\n else:\n print(f\"\\n{Fore.RED}❌ {translator.get('register.first_verification_failed') if translator else 'First verification failed'}{Style.RESET_ALL}\")\n \n return False, None\n \n except Exception as e:\n print(f\"发生错误: {e}\")\n return False, None\n finally:\n if page and not success: # Only clean up when failed\n try:\n page.quit()\n except:\n pass\n cleanup_chrome_processes(translator)\n\nif __name__ == \"__main__\":\n main() # Run without parameters, use randomly generated information ", "middle_code": "if password_input:\n password_input.input(password)\n time.sleep(1)\n sign_in_button = browser_tab.ele('xpath://button[@name=\"intent\" and @value=\"password\"]')\n if sign_in_button:\n sign_in_button.click()\n time.sleep(2)\n if handle_turnstile(browser_tab, translator):\n print(f\"{Fore.GREEN}Login successful!{Style.RESET_ALL}\")\n time.sleep(3)\n return True", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "python", "sub_task_type": "if_statement"}, "context_code": [["/cursor-free-vip/config.py", "import os\nimport sys\nimport configparser\nfrom colorama import Fore, Style\nfrom utils import get_user_documents_path, get_linux_cursor_path, get_default_driver_path, get_default_browser_path\nimport shutil\nimport datetime\n\nEMOJI = {\n \"INFO\": \"ℹ️\",\n \"WARNING\": \"⚠️\",\n \"ERROR\": \"❌\",\n \"SUCCESS\": \"✅\",\n \"ADMIN\": \"🔒\",\n \"ARROW\": \"➡️\",\n \"USER\": \"👤\",\n \"KEY\": \"🔑\",\n \"SETTINGS\": \"⚙️\"\n}\n\n# global config cache\n_config_cache = None\n\ndef setup_config(translator=None):\n \"\"\"Setup configuration file and return config object\"\"\"\n try:\n # get documents path\n docs_path = get_user_documents_path()\n if not docs_path or not os.path.exists(docs_path):\n # if documents path not found, use current directory\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.documents_path_not_found', fallback='Documents path not found, using current directory') if translator else 'Documents path not found, using current directory'}{Style.RESET_ALL}\")\n docs_path = os.path.abspath('.')\n \n # normalize path\n config_dir = os.path.normpath(os.path.join(docs_path, \".cursor-free-vip\"))\n config_file = os.path.normpath(os.path.join(config_dir, \"config.ini\"))\n \n # create config directory, only print message when directory not exists\n dir_exists = os.path.exists(config_dir)\n try:\n os.makedirs(config_dir, exist_ok=True)\n if not dir_exists: # only print message when directory not exists\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.config_dir_created', path=config_dir) if translator else f'Config directory created: {config_dir}'}{Style.RESET_ALL}\")\n except Exception as e:\n # if cannot create directory, use temporary directory\n import tempfile\n temp_dir = os.path.normpath(os.path.join(tempfile.gettempdir(), \".cursor-free-vip\"))\n temp_exists = os.path.exists(temp_dir)\n config_dir = temp_dir\n config_file = os.path.normpath(os.path.join(config_dir, \"config.ini\"))\n os.makedirs(config_dir, exist_ok=True)\n if not temp_exists: # only print message when temporary directory not exists\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.using_temp_dir', path=config_dir, error=str(e)) if translator else f'Using temporary directory due to error: {config_dir} (Error: {str(e)})'}{Style.RESET_ALL}\")\n \n # create config object\n config = configparser.ConfigParser()\n \n # Default configuration\n default_config = {\n 'Browser': {\n 'default_browser': 'chrome',\n 'chrome_path': get_default_browser_path('chrome'),\n 'chrome_driver_path': get_default_driver_path('chrome'),\n 'edge_path': get_default_browser_path('edge'),\n 'edge_driver_path': get_default_driver_path('edge'),\n 'firefox_path': get_default_browser_path('firefox'),\n 'firefox_driver_path': get_default_driver_path('firefox'),\n 'brave_path': get_default_browser_path('brave'),\n 'brave_driver_path': get_default_driver_path('brave'),\n 'opera_path': get_default_browser_path('opera'),\n 'opera_driver_path': get_default_driver_path('opera'),\n 'operagx_path': get_default_browser_path('operagx'),\n 'operagx_driver_path': get_default_driver_path('chrome') # Opera GX 使用 Chrome 驱动\n },\n 'Turnstile': {\n 'handle_turnstile_time': '2',\n 'handle_turnstile_random_time': '1-3'\n },\n 'Timing': {\n 'min_random_time': '0.1',\n 'max_random_time': '0.8',\n 'page_load_wait': '0.1-0.8',\n 'input_wait': '0.3-0.8',\n 'submit_wait': '0.5-1.5',\n 'verification_code_input': '0.1-0.3',\n 'verification_success_wait': '2-3',\n 'verification_retry_wait': '2-3',\n 'email_check_initial_wait': '4-6',\n 'email_refresh_wait': '2-4',\n 'settings_page_load_wait': '1-2',\n 'failed_retry_time': '0.5-1',\n 'retry_interval': '8-12',\n 'max_timeout': '160'\n },\n 'Utils': {\n 'enabled_update_check': 'True',\n 'enabled_force_update': 'False',\n 'enabled_account_info': 'True'\n },\n 'OAuth': {\n 'show_selection_alert': False, # 默认不显示选择提示弹窗\n 'timeout': 120,\n 'max_attempts': 3\n },\n 'Token': {\n 'refresh_server': 'https://token.cursorpro.com.cn',\n 'enable_refresh': True\n },\n 'Language': {\n 'current_language': '', # Set by local system detection if empty\n 'fallback_language': 'en',\n 'auto_update_languages': 'True',\n 'language_cache_dir': os.path.join(config_dir, \"language_cache\")\n }\n }\n\n # Add system-specific path configuration\n if sys.platform == \"win32\":\n appdata = os.getenv(\"APPDATA\")\n localappdata = os.getenv(\"LOCALAPPDATA\", \"\")\n default_config['WindowsPaths'] = {\n 'storage_path': os.path.join(appdata, \"Cursor\", \"User\", \"globalStorage\", \"storage.json\"),\n 'sqlite_path': os.path.join(appdata, \"Cursor\", \"User\", \"globalStorage\", \"state.vscdb\"),\n 'machine_id_path': os.path.join(appdata, \"Cursor\", \"machineId\"),\n 'cursor_path': os.path.join(localappdata, \"Programs\", \"Cursor\", \"resources\", \"app\"),\n 'updater_path': os.path.join(localappdata, \"cursor-updater\"),\n 'update_yml_path': os.path.join(localappdata, \"Programs\", \"Cursor\", \"resources\", \"app-update.yml\"),\n 'product_json_path': os.path.join(localappdata, \"Programs\", \"Cursor\", \"resources\", \"app\", \"product.json\")\n }\n # Create storage directory\n os.makedirs(os.path.dirname(default_config['WindowsPaths']['storage_path']), exist_ok=True)\n \n elif sys.platform == \"darwin\":\n default_config['MacPaths'] = {\n 'storage_path': os.path.abspath(os.path.expanduser(\"~/Library/Application Support/Cursor/User/globalStorage/storage.json\")),\n 'sqlite_path': os.path.abspath(os.path.expanduser(\"~/Library/Application Support/Cursor/User/globalStorage/state.vscdb\")),\n 'machine_id_path': os.path.expanduser(\"~/Library/Application Support/Cursor/machineId\"),\n 'cursor_path': \"/Applications/Cursor.app/Contents/Resources/app\",\n 'updater_path': os.path.expanduser(\"~/Library/Application Support/cursor-updater\"),\n 'update_yml_path': \"/Applications/Cursor.app/Contents/Resources/app-update.yml\",\n 'product_json_path': \"/Applications/Cursor.app/Contents/Resources/app/product.json\"\n }\n # Create storage directory\n os.makedirs(os.path.dirname(default_config['MacPaths']['storage_path']), exist_ok=True)\n \n elif sys.platform == \"linux\":\n # Get the actual user's home directory, handling both sudo and normal cases\n sudo_user = os.environ.get('SUDO_USER')\n current_user = sudo_user if sudo_user else (os.getenv('USER') or os.getenv('USERNAME'))\n \n if not current_user:\n current_user = os.path.expanduser('~').split('/')[-1]\n \n # Handle sudo case\n if sudo_user:\n actual_home = f\"/home/{sudo_user}\"\n root_home = \"/root\"\n else:\n actual_home = f\"/home/{current_user}\"\n root_home = None\n \n if not os.path.exists(actual_home):\n actual_home = os.path.expanduser(\"~\")\n \n # Define base config directory\n config_base = os.path.join(actual_home, \".config\")\n \n # Try both \"Cursor\" and \"cursor\" directory names in both user and root locations\n cursor_dir = None\n possible_paths = [\n os.path.join(config_base, \"Cursor\"),\n os.path.join(config_base, \"cursor\"),\n os.path.join(root_home, \".config\", \"Cursor\") if root_home else None,\n os.path.join(root_home, \".config\", \"cursor\") if root_home else None\n ]\n \n for path in possible_paths:\n if path and os.path.exists(path):\n cursor_dir = path\n break\n \n if not cursor_dir:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.neither_cursor_nor_cursor_directory_found', config_base=config_base) if translator else f'Neither Cursor nor cursor directory found in {config_base}'}{Style.RESET_ALL}\")\n if root_home:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.also_checked', path=f'{root_home}/.config') if translator else f'Also checked {root_home}/.config'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.please_make_sure_cursor_is_installed_and_has_been_run_at_least_once') if translator else 'Please make sure Cursor is installed and has been run at least once'}{Style.RESET_ALL}\")\n \n # Define Linux paths using the found cursor directory\n storage_path = os.path.abspath(os.path.join(cursor_dir, \"User/globalStorage/storage.json\")) if cursor_dir else \"\"\n storage_dir = os.path.dirname(storage_path) if storage_path else \"\"\n \n # Verify paths and permissions\n try:\n # Check storage directory\n if storage_dir and not os.path.exists(storage_dir):\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.storage_directory_not_found', storage_dir=storage_dir) if translator else f'Storage directory not found: {storage_dir}'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.please_make_sure_cursor_is_installed_and_has_been_run_at_least_once') if translator else 'Please make sure Cursor is installed and has been run at least once'}{Style.RESET_ALL}\")\n \n # Check storage.json with more detailed verification\n if storage_path and os.path.exists(storage_path):\n # Get file stats\n try:\n stat = os.stat(storage_path)\n print(f\"{Fore.GREEN}{EMOJI['INFO']} {translator.get('config.storage_file_found', storage_path=storage_path) if translator else f'Storage file found: {storage_path}'}{Style.RESET_ALL}\")\n print(f\"{Fore.GREEN}{EMOJI['INFO']} {translator.get('config.file_size', size=stat.st_size) if translator else f'File size: {stat.st_size} bytes'}{Style.RESET_ALL}\")\n print(f\"{Fore.GREEN}{EMOJI['INFO']} {translator.get('config.file_permissions', permissions=oct(stat.st_mode & 0o777)) if translator else f'File permissions: {oct(stat.st_mode & 0o777)}'}{Style.RESET_ALL}\")\n print(f\"{Fore.GREEN}{EMOJI['INFO']} {translator.get('config.file_owner', owner=stat.st_uid) if translator else f'File owner: {stat.st_uid}'}{Style.RESET_ALL}\")\n print(f\"{Fore.GREEN}{EMOJI['INFO']} {translator.get('config.file_group', group=stat.st_gid) if translator else f'File group: {stat.st_gid}'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.error_getting_file_stats', error=str(e)) if translator else f'Error getting file stats: {str(e)}'}{Style.RESET_ALL}\")\n \n # Check if file is readable and writable\n if not os.access(storage_path, os.R_OK | os.W_OK):\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.permission_denied', storage_path=storage_path) if translator else f'Permission denied: {storage_path}'}{Style.RESET_ALL}\")\n if sudo_user:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.try_running', command=f'chown {sudo_user}:{sudo_user} {storage_path}') if translator else f'Try running: chown {sudo_user}:{sudo_user} {storage_path}'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.and') if translator else 'And'}: chmod 644 {storage_path}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.try_running', command=f'chown {current_user}:{current_user} {storage_path}') if translator else f'Try running: chown {current_user}:{current_user} {storage_path}'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.and') if translator else 'And'}: chmod 644 {storage_path}{Style.RESET_ALL}\")\n \n # Try to read the file to verify it's not corrupted\n try:\n with open(storage_path, 'r') as f:\n content = f.read()\n if not content.strip():\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.storage_file_is_empty', storage_path=storage_path) if translator else f'Storage file is empty: {storage_path}'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.the_file_might_be_corrupted_please_reinstall_cursor') if translator else 'The file might be corrupted, please reinstall Cursor'}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('config.storage_file_is_valid_and_contains_data') if translator else 'Storage file is valid and contains data'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.error_reading_storage_file', error=str(e)) if translator else f'Error reading storage file: {str(e)}'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.the_file_might_be_corrupted_please_reinstall_cursor') if translator else 'The file might be corrupted. Please reinstall Cursor'}{Style.RESET_ALL}\")\n elif storage_path:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.storage_file_not_found', storage_path=storage_path) if translator else f'Storage file not found: {storage_path}'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.please_make_sure_cursor_is_installed_and_has_been_run_at_least_once') if translator else 'Please make sure Cursor is installed and has been run at least once'}{Style.RESET_ALL}\")\n \n except (OSError, IOError) as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.error_checking_linux_paths', error=str(e)) if translator else f'Error checking Linux paths: {str(e)}'}{Style.RESET_ALL}\")\n \n # Define all paths using the found cursor directory\n default_config['LinuxPaths'] = {\n 'storage_path': storage_path,\n 'sqlite_path': os.path.abspath(os.path.join(cursor_dir, \"User/globalStorage/state.vscdb\")) if cursor_dir else \"\",\n 'machine_id_path': os.path.join(cursor_dir, \"machineid\") if cursor_dir else \"\",\n 'cursor_path': get_linux_cursor_path(),\n 'updater_path': os.path.join(config_base, \"cursor-updater\"),\n 'update_yml_path': os.path.join(cursor_dir, \"resources/app-update.yml\") if cursor_dir else \"\",\n 'product_json_path': os.path.join(cursor_dir, \"resources/app/product.json\") if cursor_dir else \"\"\n }\n\n # Add tempmail_plus configuration\n default_config['TempMailPlus'] = {\n 'enabled': 'false',\n 'email': '',\n 'epin': ''\n }\n\n # Read existing configuration and merge\n if os.path.exists(config_file):\n config.read(config_file, encoding='utf-8')\n config_modified = False\n \n for section, options in default_config.items():\n if not config.has_section(section):\n config.add_section(section)\n config_modified = True\n for option, value in options.items():\n if not config.has_option(section, option):\n config.set(section, option, str(value))\n config_modified = True\n if translator:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('config.config_option_added', option=f'{section}.{option}') if translator else f'Config option added: {section}.{option}'}{Style.RESET_ALL}\")\n\n if config_modified:\n with open(config_file, 'w', encoding='utf-8') as f:\n config.write(f)\n if translator:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('config.config_updated') if translator else 'Config updated'}{Style.RESET_ALL}\")\n else:\n for section, options in default_config.items():\n config.add_section(section)\n for option, value in options.items():\n config.set(section, option, str(value))\n\n with open(config_file, 'w', encoding='utf-8') as f:\n config.write(f)\n if translator:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('config.config_created', config_file=config_file) if translator else f'Config created: {config_file}'}{Style.RESET_ALL}\")\n\n return config\n\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.config_setup_error', error=str(e)) if translator else f'Error setting up config: {str(e)}'}{Style.RESET_ALL}\")\n return None\n \ndef print_config(config, translator=None):\n \"\"\"Print configuration in a readable format\"\"\"\n if not config:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {translator.get('config.config_not_available') if translator else 'Configuration not available'}{Style.RESET_ALL}\")\n return\n \n print(f\"\\n{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.configuration') if translator else 'Configuration'}:{Style.RESET_ALL}\")\n print(f\"\\n{Fore.CYAN}{'─' * 70}{Style.RESET_ALL}\")\n for section in config.sections():\n print(f\"{Fore.GREEN}[{section}]{Style.RESET_ALL}\")\n for key, value in config.items(section):\n # 对布尔值进行特殊处理,使其显示为彩色\n if value.lower() in ('true', 'yes', 'on', '1'):\n value_display = f\"{Fore.GREEN}{translator.get('config.enabled') if translator else 'Enabled'}{Style.RESET_ALL}\"\n elif value.lower() in ('false', 'no', 'off', '0'):\n value_display = f\"{Fore.RED}{translator.get('config.disabled') if translator else 'Disabled'}{Style.RESET_ALL}\"\n else:\n value_display = value\n \n print(f\" {key} = {value_display}\")\n \n print(f\"\\n{Fore.CYAN}{'─' * 70}{Style.RESET_ALL}\")\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\", \"config.ini\")\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.config_directory') if translator else 'Config Directory'}: {config_dir}{Style.RESET_ALL}\")\n\n print() \n\ndef force_update_config(translator=None):\n \"\"\"\n Force update configuration file with latest defaults if update check is enabled.\n Args:\n translator: Translator instance\n Returns:\n ConfigParser instance or None if failed\n \"\"\"\n try:\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\")\n config_file = os.path.join(config_dir, \"config.ini\")\n current_time = datetime.datetime.now()\n\n # If the config file exists, check if forced update is enabled\n if os.path.exists(config_file):\n # First, read the existing configuration\n existing_config = configparser.ConfigParser()\n existing_config.read(config_file, encoding='utf-8')\n # Check if \"enabled_update_check\" is True\n update_enabled = True # Default to True if not set\n if existing_config.has_section('Utils') and existing_config.has_option('Utils', 'enabled_force_update'):\n update_enabled = existing_config.get('Utils', 'enabled_force_update').strip().lower() in ('true', 'yes', '1', 'on')\n\n if update_enabled:\n try:\n # Create a backup\n backup_file = f\"{config_file}.bak.{current_time.strftime('%Y%m%d_%H%M%S')}\"\n shutil.copy2(config_file, backup_file)\n if translator:\n print(f\"\\n{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.backup_created', path=backup_file) if translator else f'Backup created: {backup_file}'}{Style.RESET_ALL}\")\n print(f\"\\n{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.config_force_update_enabled') if translator else 'Config file force update enabled'}{Style.RESET_ALL}\")\n # Delete the original config file (forced update)\n os.remove(config_file)\n if translator:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.config_removed') if translator else 'Config file removed for forced update'}{Style.RESET_ALL}\")\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.backup_failed', error=str(e)) if translator else f'Failed to backup config: {str(e)}'}{Style.RESET_ALL}\")\n else:\n if translator:\n print(f\"\\n{Fore.CYAN}{EMOJI['INFO']} {translator.get('config.config_force_update_disabled', fallback='Config file force update disabled by configuration. Keeping existing config file.') if translator else 'Config file force update disabled by configuration. Keeping existing config file.'}{Style.RESET_ALL}\")\n\n # Generate a new (or updated) configuration if needed\n return setup_config(translator)\n\n except Exception as e:\n if translator:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('config.force_update_failed', error=str(e)) if translator else f'Force update config failed: {str(e)}'}{Style.RESET_ALL}\")\n return None\n\ndef get_config(translator=None):\n \"\"\"Get existing config or create new one\"\"\"\n global _config_cache\n if _config_cache is None:\n _config_cache = setup_config(translator)\n return _config_cache"], ["/cursor-free-vip/utils.py", "import os\nimport sys\nimport platform\nimport random\n\ndef get_user_documents_path():\n \"\"\"Get user documents path\"\"\"\n if platform.system() == \"Windows\":\n try:\n import winreg\n # 打开注册表\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Shell Folders\") as key:\n # 获取 \"Personal\" 键的值,这指向用户的文档目录\n documents_path, _ = winreg.QueryValueEx(key, \"Personal\")\n return documents_path\n except Exception as e:\n # fallback\n return os.path.expanduser(\"~\\\\Documents\")\n else:\n return os.path.expanduser(\"~/Documents\")\n \ndef get_default_driver_path(browser_type='chrome'):\n \"\"\"Get default driver path based on browser type\"\"\"\n browser_type = browser_type.lower()\n if browser_type == 'chrome':\n return get_default_chrome_driver_path()\n elif browser_type == 'edge':\n return get_default_edge_driver_path()\n elif browser_type == 'firefox':\n return get_default_firefox_driver_path()\n elif browser_type == 'brave':\n # Brave 使用 Chrome 的 driver\n return get_default_chrome_driver_path()\n else:\n # Default to Chrome if browser type is unknown\n return get_default_chrome_driver_path()\n\ndef get_default_chrome_driver_path():\n \"\"\"Get default Chrome driver path\"\"\"\n if sys.platform == \"win32\":\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"drivers\", \"chromedriver.exe\")\n elif sys.platform == \"darwin\":\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"drivers\", \"chromedriver\")\n else:\n return \"/usr/local/bin/chromedriver\"\n\ndef get_default_edge_driver_path():\n \"\"\"Get default Edge driver path\"\"\"\n if sys.platform == \"win32\":\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"drivers\", \"msedgedriver.exe\")\n elif sys.platform == \"darwin\":\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"drivers\", \"msedgedriver\")\n else:\n return \"/usr/local/bin/msedgedriver\"\n \ndef get_default_firefox_driver_path():\n \"\"\"Get default Firefox driver path\"\"\"\n if sys.platform == \"win32\":\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"drivers\", \"geckodriver.exe\")\n elif sys.platform == \"darwin\":\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"drivers\", \"geckodriver\")\n else:\n return \"/usr/local/bin/geckodriver\"\n\ndef get_default_brave_driver_path():\n \"\"\"Get default Brave driver path (uses Chrome driver)\"\"\"\n # Brave 浏览器基于 Chromium,所以使用相同的 chromedriver\n return get_default_chrome_driver_path()\n\ndef get_default_browser_path(browser_type='chrome'):\n \"\"\"Get default browser executable path\"\"\"\n browser_type = browser_type.lower()\n \n if sys.platform == \"win32\":\n if browser_type == 'chrome':\n # 尝试在 PATH 中找到 Chrome\n try:\n import shutil\n chrome_in_path = shutil.which(\"chrome\")\n if chrome_in_path:\n return chrome_in_path\n except:\n pass\n # 使用默认路径\n return r\"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"\n elif browser_type == 'edge':\n return r\"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe\"\n elif browser_type == 'firefox':\n return r\"C:\\Program Files\\Mozilla Firefox\\firefox.exe\"\n elif browser_type == 'opera':\n # 尝试多个可能的 Opera 路径\n opera_paths = [\n r\"C:\\Program Files\\Opera\\opera.exe\",\n r\"C:\\Program Files (x86)\\Opera\\opera.exe\",\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera', 'launcher.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera', 'opera.exe')\n ]\n for path in opera_paths:\n if os.path.exists(path):\n return path\n return opera_paths[0] # 返回第一个路径,即使它不存在\n elif browser_type == 'operagx':\n # 尝试多个可能的 Opera GX 路径\n operagx_paths = [\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera GX', 'launcher.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera GX', 'opera.exe'),\n r\"C:\\Program Files\\Opera GX\\opera.exe\",\n r\"C:\\Program Files (x86)\\Opera GX\\opera.exe\"\n ]\n for path in operagx_paths:\n if os.path.exists(path):\n return path\n return operagx_paths[0] # 返回第一个路径,即使它不存在\n elif browser_type == 'brave':\n # Brave 浏览器的默认安装路径\n paths = [\n os.path.join(os.environ.get('PROGRAMFILES', ''), 'BraveSoftware/Brave-Browser/Application/brave.exe'),\n os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'BraveSoftware/Brave-Browser/Application/brave.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'BraveSoftware/Brave-Browser/Application/brave.exe')\n ]\n for path in paths:\n if os.path.exists(path):\n return path\n return paths[0] # 返回第一个路径,即使它不存在\n \n elif sys.platform == \"darwin\":\n if browser_type == 'chrome':\n return \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\"\n elif browser_type == 'edge':\n return \"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge\"\n elif browser_type == 'firefox':\n return \"/Applications/Firefox.app/Contents/MacOS/firefox\"\n elif browser_type == 'brave':\n return \"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser\"\n elif browser_type == 'opera':\n return \"/Applications/Opera.app/Contents/MacOS/Opera\"\n elif browser_type == 'operagx':\n return \"/Applications/Opera GX.app/Contents/MacOS/Opera\"\n \n else: # Linux\n if browser_type == 'chrome':\n # 尝试多种可能的名称\n chrome_names = [\"google-chrome\", \"chrome\", \"chromium\", \"chromium-browser\"]\n for name in chrome_names:\n try:\n import shutil\n path = shutil.which(name)\n if path:\n return path\n except:\n pass\n return \"/usr/bin/google-chrome\"\n elif browser_type == 'edge':\n return \"/usr/bin/microsoft-edge\"\n elif browser_type == 'firefox':\n return \"/usr/bin/firefox\"\n elif browser_type == 'opera':\n return \"/usr/bin/opera\"\n elif browser_type == 'operagx':\n # 尝试常见的 Opera GX 路径\n operagx_names = [\"opera-gx\"]\n for name in operagx_names:\n try:\n import shutil\n path = shutil.which(name)\n if path:\n return path\n except:\n pass\n return \"/usr/bin/opera-gx\"\n elif browser_type == 'brave':\n # 尝试常见的 Brave 路径\n brave_names = [\"brave\", \"brave-browser\"]\n for name in brave_names:\n try:\n import shutil\n path = shutil.which(name)\n if path:\n return path\n except:\n pass\n return \"/usr/bin/brave-browser\"\n \n # 如果找不到指定的浏览器类型,则返回 Chrome 的路径\n return get_default_browser_path('chrome')\n\ndef get_linux_cursor_path():\n \"\"\"Get Linux Cursor path\"\"\"\n possible_paths = [\n \"/opt/Cursor/resources/app\",\n \"/usr/share/cursor/resources/app\",\n \"/opt/cursor-bin/resources/app\",\n \"/usr/lib/cursor/resources/app\",\n os.path.expanduser(\"~/.local/share/cursor/resources/app\")\n ]\n \n # return the first path that exists\n return next((path for path in possible_paths if os.path.exists(path)), possible_paths[0])\n\ndef get_random_wait_time(config, timing_key):\n \"\"\"Get random wait time based on configuration timing settings\n \n Args:\n config (dict): Configuration dictionary containing timing settings\n timing_key (str): Key to look up in the timing settings\n \n Returns:\n float: Random wait time in seconds\n \"\"\"\n try:\n # Get timing value from config\n timing = config.get('Timing', {}).get(timing_key)\n if not timing:\n # Default to 0.5-1.5 seconds if timing not found\n return random.uniform(0.5, 1.5)\n \n # Check if timing is a range (e.g., \"0.5-1.5\" or \"0.5,1.5\")\n if isinstance(timing, str):\n if '-' in timing:\n min_time, max_time = map(float, timing.split('-'))\n elif ',' in timing:\n min_time, max_time = map(float, timing.split(','))\n else:\n # Single value, use it as both min and max\n min_time = max_time = float(timing)\n else:\n # If timing is a number, use it as both min and max\n min_time = max_time = float(timing)\n \n return random.uniform(min_time, max_time)\n \n except (ValueError, TypeError, AttributeError):\n # Return default value if any error occurs\n return random.uniform(0.5, 1.5) "], ["/cursor-free-vip/oauth_auth.py", "# oauth_auth.py\nimport os\nfrom colorama import Fore, Style, init\nimport time\nimport random\nimport webbrowser\nimport sys\nimport json\nfrom DrissionPage import ChromiumPage, ChromiumOptions\nfrom cursor_auth import CursorAuth\nfrom utils import get_random_wait_time, get_default_browser_path\nfrom config import get_config\nimport platform\nfrom get_user_token import get_token_from_cookie\n\n# Initialize colorama\ninit()\n\n# Define emoji constants\nEMOJI = {\n 'START': '🚀',\n 'OAUTH': '🔑',\n 'SUCCESS': '✅',\n 'ERROR': '❌',\n 'WAIT': '⏳',\n 'INFO': 'ℹ️',\n 'WARNING': '⚠️'\n}\n\nclass OAuthHandler:\n def __init__(self, translator=None, auth_type=None):\n self.translator = translator\n self.config = get_config(translator)\n self.auth_type = auth_type\n os.environ['BROWSER_HEADLESS'] = 'False'\n self.browser = None\n self.selected_profile = None\n \n def _get_available_profiles(self, user_data_dir):\n \"\"\"Get list of available Chrome profiles with their names\"\"\"\n try:\n profiles = []\n profile_names = {}\n \n # Read Local State file to get profile names\n local_state_path = os.path.join(user_data_dir, 'Local State')\n if os.path.exists(local_state_path):\n with open(local_state_path, 'r', encoding='utf-8') as f:\n local_state = json.load(f)\n info_cache = local_state.get('profile', {}).get('info_cache', {})\n for profile_dir, info in info_cache.items():\n profile_dir = profile_dir.replace('\\\\', '/')\n if profile_dir == 'Default':\n profile_names['Default'] = info.get('name', 'Default')\n elif profile_dir.startswith('Profile '):\n profile_names[profile_dir] = info.get('name', profile_dir)\n\n # Get list of profile directories\n for item in os.listdir(user_data_dir):\n if item == 'Default' or (item.startswith('Profile ') and os.path.isdir(os.path.join(user_data_dir, item))):\n profiles.append((item, profile_names.get(item, item)))\n return sorted(profiles)\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('chrome_profile.error_loading', error=str(e)) if self.translator else f'Error loading Chrome profiles: {e}'}{Style.RESET_ALL}\")\n return []\n\n def _select_profile(self):\n \"\"\"Allow user to select a browser profile to use\"\"\"\n try:\n # 从配置中获取浏览器类型\n config = get_config(self.translator)\n browser_type = config.get('Browser', 'default_browser', fallback='chrome')\n browser_type_display = browser_type.capitalize()\n \n if self.translator:\n # 动态使用浏览器类型\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.select_profile', browser=browser_type_display)}{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{self.translator.get('oauth.profile_list', browser=browser_type_display)}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} Select {browser_type_display} profile to use:{Style.RESET_ALL}\")\n print(f\"Available {browser_type_display} profiles:\")\n \n # Get the user data directory for the browser type\n user_data_dir = self._get_user_data_directory()\n \n # Load available profiles from the selected browser type\n try:\n local_state_file = os.path.join(user_data_dir, \"Local State\")\n if os.path.exists(local_state_file):\n with open(local_state_file, 'r', encoding='utf-8') as f:\n state_data = json.load(f)\n profiles_data = state_data.get('profile', {}).get('info_cache', {})\n \n # Create a list of available profiles\n profiles = []\n for profile_id, profile_info in profiles_data.items():\n name = profile_info.get('name', profile_id)\n # Mark the default profile\n if profile_id.lower() == 'default':\n name = f\"{name} (Default)\"\n profiles.append((profile_id, name))\n \n # Sort profiles by name\n profiles.sort(key=lambda x: x[1])\n \n # Show available profiles\n if self.translator:\n print(f\"{Fore.CYAN}0. {self.translator.get('menu.exit')}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.CYAN}0. Exit{Style.RESET_ALL}\")\n \n for i, (profile_id, name) in enumerate(profiles, 1):\n print(f\"{Fore.CYAN}{i}. {name}{Style.RESET_ALL}\")\n \n # Get user's choice\n max_choice = len(profiles)\n choice_str = input(f\"\\n{Fore.CYAN}{self.translator.get('menu.input_choice', choices=f'0-{max_choice}') if self.translator else f'Please enter your choice (0-{max_choice})'}{Style.RESET_ALL}\")\n \n try:\n choice = int(choice_str)\n if choice == 0:\n return False\n elif 1 <= choice <= max_choice:\n selected_profile = profiles[choice-1][0]\n self.selected_profile = selected_profile\n \n if self.translator:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.profile_selected', profile=selected_profile)}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} Selected profile: {selected_profile}{Style.RESET_ALL}\")\n return True\n else:\n if self.translator:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.invalid_selection')}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} Invalid selection. Please try again.{Style.RESET_ALL}\")\n return self._select_profile()\n except ValueError:\n if self.translator:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.invalid_selection')}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} Invalid selection. Please try again.{Style.RESET_ALL}\")\n return self._select_profile()\n else:\n # No Local State file, use Default profile\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('oauth.no_profiles', browser=browser_type_display) if self.translator else f'No {browser_type_display} profiles found'}{Style.RESET_ALL}\")\n self.selected_profile = \"Default\"\n return True\n \n except Exception as e:\n # Error loading profiles, use Default profile\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_loading', error=str(e), browser=browser_type_display) if self.translator else f'Error loading {browser_type_display} profiles: {str(e)}'}{Style.RESET_ALL}\")\n self.selected_profile = \"Default\"\n return True\n \n except Exception as e:\n # General error, use Default profile\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.profile_selection_error', error=str(e)) if self.translator else f'Error during profile selection: {str(e)}'}{Style.RESET_ALL}\")\n self.selected_profile = \"Default\"\n return True\n\n def setup_browser(self):\n \"\"\"Setup browser for OAuth flow using selected profile\"\"\"\n try:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.initializing_browser_setup') if self.translator else 'Initializing browser setup...'}{Style.RESET_ALL}\")\n \n # Platform-specific initialization\n platform_name = platform.system().lower()\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.detected_platform', platform=platform_name) if self.translator else f'Detected platform: {platform_name}'}{Style.RESET_ALL}\")\n \n # 从配置中获取浏览器类型\n config = get_config(self.translator)\n browser_type = config.get('Browser', 'default_browser', fallback='chrome')\n \n # Get browser paths and user data directory\n user_data_dir = self._get_user_data_directory()\n browser_path = self._get_browser_path()\n \n if not browser_path:\n error_msg = (\n f\"{self.translator.get('oauth.no_compatible_browser_found') if self.translator else 'No compatible browser found. Please install Google Chrome or Chromium.'}\" + \n \"\\n\" +\n f\"{self.translator.get('oauth.supported_browsers', platform=platform_name)}\\n\" + \n \"- Windows: Google Chrome, Chromium\\n\" +\n \"- macOS: Google Chrome, Chromium\\n\" +\n \"- Linux: Google Chrome, Chromium, google-chrome-stable\"\n )\n raise Exception(error_msg)\n \n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_browser_data_directory', path=user_data_dir) if self.translator else f'Found browser data directory: {user_data_dir}'}{Style.RESET_ALL}\")\n \n # Show warning about closing browser first - 使用动态提示\n if self.translator:\n warning_msg = self.translator.get('oauth.warning_browser_close', browser=browser_type)\n else:\n warning_msg = f'Warning: This will close all running {browser_type} processes'\n \n print(f\"\\n{Fore.YELLOW}{EMOJI['WARNING']} {warning_msg}{Style.RESET_ALL}\")\n \n choice = input(f\"{Fore.YELLOW} {self.translator.get('menu.continue_prompt', choices='y/N')} {Style.RESET_ALL}\").lower()\n if choice != 'y':\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('menu.operation_cancelled_by_user') if self.translator else 'Operation cancelled by user'}{Style.RESET_ALL}\")\n return False\n\n # Kill existing browser processes\n self._kill_browser_processes()\n \n # Let user select a profile\n if not self._select_profile():\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('menu.operation_cancelled_by_user') if self.translator else 'Operation cancelled by user'}{Style.RESET_ALL}\")\n return False\n \n # Configure browser options\n co = self._configure_browser_options(browser_path, user_data_dir, self.selected_profile)\n \n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_browser', path=browser_path) if self.translator else f'Starting browser at: {browser_path}'}{Style.RESET_ALL}\")\n self.browser = ChromiumPage(co)\n \n # Verify browser launched successfully\n if not self.browser:\n raise Exception(f\"{self.translator.get('oauth.browser_failed_to_start', error=str(e)) if self.translator else 'Failed to initialize browser instance'}\")\n \n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.browser_setup_completed') if self.translator else 'Browser setup completed successfully'}{Style.RESET_ALL}\")\n return True\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.browser_setup_failed', error=str(e)) if self.translator else f'Browser setup failed: {str(e)}'}{Style.RESET_ALL}\")\n if \"DevToolsActivePort file doesn't exist\" in str(e):\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.try_running_without_sudo_admin') if self.translator else 'Try running without sudo/administrator privileges'}{Style.RESET_ALL}\")\n elif \"Chrome failed to start\" in str(e):\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.make_sure_chrome_chromium_is_properly_installed') if self.translator else 'Make sure Chrome/Chromium is properly installed'}{Style.RESET_ALL}\")\n if platform_name == 'linux':\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.try_install_chromium') if self.translator else 'Try: sudo apt install chromium-browser'}{Style.RESET_ALL}\")\n return False\n\n def _kill_browser_processes(self):\n \"\"\"Kill existing browser processes based on platform and browser type\"\"\"\n try:\n # 从配置中获取浏览器类型\n config = get_config(self.translator)\n browser_type = config.get('Browser', 'default_browser', fallback='chrome')\n browser_type = browser_type.lower()\n \n # 根据浏览器类型和平台定义要关闭的进程\n browser_processes = {\n 'chrome': {\n 'win': ['chrome.exe', 'chromium.exe'],\n 'linux': ['chrome', 'chromium', 'chromium-browser', 'google-chrome-stable'],\n 'mac': ['Chrome', 'Chromium']\n },\n 'brave': {\n 'win': ['brave.exe'],\n 'linux': ['brave', 'brave-browser'],\n 'mac': ['Brave Browser']\n },\n 'edge': {\n 'win': ['msedge.exe'],\n 'linux': ['msedge'],\n 'mac': ['Microsoft Edge']\n },\n 'firefox': {\n 'win': ['firefox.exe'],\n 'linux': ['firefox'],\n 'mac': ['Firefox']\n },\n 'opera': {\n 'win': ['opera.exe', 'launcher.exe'],\n 'linux': ['opera'],\n 'mac': ['Opera']\n }\n }\n \n # 获取平台类型\n if os.name == 'nt':\n platform_type = 'win'\n elif sys.platform == 'darwin':\n platform_type = 'mac'\n else:\n platform_type = 'linux'\n \n # 获取要关闭的进程列表\n processes = browser_processes.get(browser_type, browser_processes['chrome']).get(platform_type, [])\n \n if self.translator:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.killing_browser_processes', browser=browser_type) if self.translator else f'Killing {browser_type} processes...'}{Style.RESET_ALL}\")\n \n # 根据平台关闭进程\n if os.name == 'nt': # Windows\n for proc in processes:\n os.system(f'taskkill /f /im {proc} >nul 2>&1')\n else: # Linux/Mac\n for proc in processes:\n os.system(f'pkill -f {proc} >/dev/null 2>&1')\n \n time.sleep(1) # Wait for processes to close\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.warning_could_not_kill_existing_browser_processes', error=str(e)) if self.translator else f'Warning: Could not kill existing browser processes: {e}'}{Style.RESET_ALL}\")\n\n def _get_user_data_directory(self):\n \"\"\"Get the default user data directory based on browser type and platform\"\"\"\n try:\n # 从配置中获取浏览器类型\n config = get_config(self.translator)\n browser_type = config.get('Browser', 'default_browser', fallback='chrome')\n browser_type = browser_type.lower()\n \n # 根据操作系统和浏览器类型获取用户数据目录\n if os.name == 'nt': # Windows\n user_data_dirs = {\n 'chrome': os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Google', 'Chrome', 'User Data'),\n 'brave': os.path.join(os.environ.get('LOCALAPPDATA', ''), 'BraveSoftware', 'Brave-Browser', 'User Data'),\n 'edge': os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Microsoft', 'Edge', 'User Data'),\n 'firefox': os.path.join(os.environ.get('APPDATA', ''), 'Mozilla', 'Firefox', 'Profiles'),\n 'opera': os.path.join(os.environ.get('APPDATA', ''), 'Opera Software', 'Opera Stable'),\n 'operagx': os.path.join(os.environ.get('APPDATA', ''), 'Opera Software', 'Opera GX Stable')\n }\n elif sys.platform == 'darwin': # macOS\n user_data_dirs = {\n 'chrome': os.path.expanduser('~/Library/Application Support/Google/Chrome'),\n 'brave': os.path.expanduser('~/Library/Application Support/BraveSoftware/Brave-Browser'),\n 'edge': os.path.expanduser('~/Library/Application Support/Microsoft Edge'),\n 'firefox': os.path.expanduser('~/Library/Application Support/Firefox/Profiles'),\n 'opera': os.path.expanduser('~/Library/Application Support/com.operasoftware.Opera'),\n 'operagx': os.path.expanduser('~/Library/Application Support/com.operasoftware.OperaGX')\n }\n else: # Linux\n user_data_dirs = {\n 'chrome': os.path.expanduser('~/.config/google-chrome'),\n 'brave': os.path.expanduser('~/.config/BraveSoftware/Brave-Browser'),\n 'edge': os.path.expanduser('~/.config/microsoft-edge'),\n 'firefox': os.path.expanduser('~/.mozilla/firefox'),\n 'opera': os.path.expanduser('~/.config/opera'),\n 'operagx': os.path.expanduser('~/.config/opera-gx')\n }\n \n # 获取选定浏览器的用户数据目录,如果找不到则使用 Chrome 的\n user_data_dir = user_data_dirs.get(browser_type)\n \n if user_data_dir and os.path.exists(user_data_dir):\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.found_browser_user_data_dir', browser=browser_type, path=user_data_dir) if self.translator else f'Found {browser_type} user data directory: {user_data_dir}'}{Style.RESET_ALL}\")\n return user_data_dir\n else:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('oauth.user_data_dir_not_found', browser=browser_type, path=user_data_dir) if self.translator else f'{browser_type} user data directory not found at {user_data_dir}, will try Chrome instead'}{Style.RESET_ALL}\")\n return user_data_dirs['chrome'] # 回退到 Chrome 目录\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_getting_user_data_directory', error=str(e)) if self.translator else f'Error getting user data directory: {e}'}{Style.RESET_ALL}\")\n # 在出错时提供一个默认目录\n if os.name == 'nt':\n return os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Google', 'Chrome', 'User Data')\n elif sys.platform == 'darwin':\n return os.path.expanduser('~/Library/Application Support/Google/Chrome')\n else:\n return os.path.expanduser('~/.config/google-chrome')\n\n def _get_browser_path(self):\n \"\"\"Get appropriate browser path based on platform and selected browser type\"\"\"\n try:\n # 从配置中获取浏览器类型\n config = get_config(self.translator)\n browser_type = config.get('Browser', 'default_browser', fallback='chrome')\n browser_type = browser_type.lower()\n \n # 首先检查配置中是否有明确指定的浏览器路径\n browser_path = config.get('Browser', f'{browser_type}_path', fallback=None)\n if browser_path and os.path.exists(browser_path):\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.using_configured_browser_path', browser=browser_type, path=browser_path) if self.translator else f'Using configured {browser_type} path: {browser_path}'}{Style.RESET_ALL}\")\n return browser_path\n \n # 尝试获取默认路径\n browser_path = get_default_browser_path(browser_type)\n if browser_path and os.path.exists(browser_path):\n return browser_path\n \n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.searching_for_alternative_browser_installations') if self.translator else 'Searching for alternative browser installations...'}{Style.RESET_ALL}\")\n \n # 如果未找到配置中指定的浏览器,则尝试查找其他兼容浏览器\n if os.name == 'nt': # Windows\n possible_paths = []\n if browser_type == 'brave':\n possible_paths = [\n os.path.join(os.environ.get('PROGRAMFILES', ''), 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),\n os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe')\n ]\n elif browser_type == 'edge':\n possible_paths = [\n os.path.join(os.environ.get('PROGRAMFILES', ''), 'Microsoft', 'Edge', 'Application', 'msedge.exe'),\n os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'Microsoft', 'Edge', 'Application', 'msedge.exe')\n ]\n elif browser_type == 'firefox':\n possible_paths = [\n os.path.join(os.environ.get('PROGRAMFILES', ''), 'Mozilla Firefox', 'firefox.exe'),\n os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'Mozilla Firefox', 'firefox.exe')\n ]\n elif browser_type == 'opera':\n possible_paths = [\n os.path.join(os.environ.get('PROGRAMFILES', ''), 'Opera', 'opera.exe'),\n os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'Opera', 'opera.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera', 'launcher.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera', 'opera.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera GX', 'launcher.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera GX', 'opera.exe')\n ]\n else: # 默认为 Chrome\n possible_paths = [\n os.path.join(os.environ.get('PROGRAMFILES', ''), 'Google', 'Chrome', 'Application', 'chrome.exe'),\n os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'Google', 'Chrome', 'Application', 'chrome.exe'),\n os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Google', 'Chrome', 'Application', 'chrome.exe')\n ]\n \n elif sys.platform == 'darwin': # macOS\n possible_paths = []\n if browser_type == 'brave':\n possible_paths = ['/Applications/Brave Browser.app/Contents/MacOS/Brave Browser']\n elif browser_type == 'edge':\n possible_paths = ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge']\n elif browser_type == 'firefox':\n possible_paths = ['/Applications/Firefox.app/Contents/MacOS/firefox']\n else: # 默认为 Chrome\n possible_paths = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']\n \n else: # Linux\n possible_paths = []\n if browser_type == 'brave':\n possible_paths = ['/usr/bin/brave-browser', '/usr/bin/brave']\n elif browser_type == 'edge':\n possible_paths = ['/usr/bin/microsoft-edge']\n elif browser_type == 'firefox':\n possible_paths = ['/usr/bin/firefox']\n else: # 默认为 Chrome\n possible_paths = [\n '/usr/bin/google-chrome-stable', # 优先检查 google-chrome-stable\n '/usr/bin/google-chrome',\n '/usr/bin/chromium',\n '/usr/bin/chromium-browser'\n ]\n \n # 检查每个可能的路径\n for path in possible_paths:\n if os.path.exists(path):\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.found_browser_at', path=path) if self.translator else f'Found browser at: {path}'}{Style.RESET_ALL}\")\n return path\n \n # 如果找不到指定浏览器,则尝试使用 Chrome\n if browser_type != 'chrome':\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('oauth.browser_not_found_trying_chrome', browser=browser_type) if self.translator else f'Could not find {browser_type}, trying Chrome instead'}{Style.RESET_ALL}\")\n return self._get_chrome_path()\n \n return None\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_finding_browser_path', error=str(e)) if self.translator else f'Error finding browser path: {e}'}{Style.RESET_ALL}\")\n return None\n\n def _configure_browser_options(self, browser_path, user_data_dir, active_profile):\n \"\"\"Configure browser options based on platform\"\"\"\n try:\n co = ChromiumOptions()\n co.set_paths(browser_path=browser_path, user_data_path=user_data_dir)\n co.set_argument(f'--profile-directory={active_profile}')\n \n # Basic options\n co.set_argument('--no-first-run')\n co.set_argument('--no-default-browser-check')\n co.set_argument('--disable-gpu')\n co.set_argument('--remote-debugging-port=9222') # 明确指定调试端口\n \n # Platform-specific options\n if sys.platform.startswith('linux'):\n co.set_argument('--no-sandbox')\n co.set_argument('--disable-dev-shm-usage')\n co.set_argument('--disable-setuid-sandbox')\n elif sys.platform == 'darwin':\n co.set_argument('--disable-gpu-compositing')\n elif os.name == 'nt':\n co.set_argument('--disable-features=TranslateUI')\n co.set_argument('--disable-features=RendererCodeIntegrity')\n \n return co\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_configuring_browser_options', error=str(e)) if self.translator else f'Error configuring browser options: {e}'}{Style.RESET_ALL}\")\n raise\n\n def _fix_chrome_permissions(self, user_data_dir):\n \"\"\"Fix permissions for Chrome user data directory\"\"\"\n try:\n if sys.platform == 'darwin': # macOS\n import subprocess\n import pwd\n \n # Get current user\n current_user = pwd.getpwuid(os.getuid()).pw_name\n \n # Fix permissions for Chrome directory\n chrome_dir = os.path.expanduser('~/Library/Application Support/Google/Chrome')\n if os.path.exists(chrome_dir):\n subprocess.run(['chmod', '-R', 'u+rwX', chrome_dir])\n subprocess.run(['chown', '-R', f'{current_user}:staff', chrome_dir])\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.chrome_permissions_fixed') if self.translator else 'Fixed Chrome user data directory permissions'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('oauth.chrome_permissions_fix_failed', error=str(e)) if self.translator else f'Failed to fix Chrome permissions: {str(e)}'}{Style.RESET_ALL}\")\n\n def handle_google_auth(self):\n \"\"\"Handle Google OAuth authentication\"\"\"\n try:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.google_start') if self.translator else 'Starting Google OAuth authentication...'}{Style.RESET_ALL}\")\n \n # Setup browser\n if not self.setup_browser():\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.browser_failed') if self.translator else 'Browser failed to initialize'}{Style.RESET_ALL}\")\n return False, None\n \n # Get user data directory for later use\n user_data_dir = self._get_user_data_directory()\n \n # Navigate to auth URL\n try:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.navigating_to_authentication_page') if self.translator else 'Navigating to authentication page...'}{Style.RESET_ALL}\")\n self.browser.get(\"https://authenticator.cursor.sh/sign-up\")\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n # Look for Google auth button\n selectors = [\n \"//a[contains(@href,'GoogleOAuth')]\",\n \"//a[contains(@class,'auth-method-button') and contains(@href,'GoogleOAuth')]\",\n \"(//a[contains(@class,'auth-method-button')])[1]\" # First auth button as fallback\n ]\n \n auth_btn = None\n for selector in selectors:\n try:\n auth_btn = self.browser.ele(f\"xpath:{selector}\", timeout=2)\n if auth_btn and auth_btn.is_displayed():\n break\n except:\n continue\n \n if not auth_btn:\n raise Exception(\"Could not find Google authentication button\")\n \n # Click the button and wait for page load\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_google_authentication') if self.translator else 'Starting Google authentication...'}{Style.RESET_ALL}\")\n auth_btn.click()\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n # Check if we're on account selection page\n if \"accounts.google.com\" in self.browser.url:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.please_select_your_google_account_to_continue') if self.translator else 'Please select your Google account to continue...'}{Style.RESET_ALL}\")\n \n # 获取配置中是否启用 alert 选项\n config = get_config(self.translator)\n show_alert = config.getboolean('OAuth', 'show_selection_alert', fallback=False)\n \n if show_alert:\n alert_message = self.translator.get('oauth.please_select_your_google_account_to_continue') if self.translator else 'Please select your Google account to continue with Cursor authentication'\n try:\n self.browser.run_js(f\"\"\"\n alert('{alert_message}');\n \"\"\")\n except:\n pass # Alert is optional\n \n # Wait for authentication to complete\n auth_info = self._wait_for_auth()\n if not auth_info:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.timeout') if self.translator else 'Timeout'}{Style.RESET_ALL}\")\n return False, None\n \n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.success') if self.translator else 'Success'}{Style.RESET_ALL}\")\n return True, auth_info\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_error', error=str(e)) if self.translator else f'Authentication error: {str(e)}'}{Style.RESET_ALL}\")\n return False, None\n finally:\n try:\n if self.browser:\n self.browser.quit()\n # Fix Chrome permissions after browser is closed\n self._fix_chrome_permissions(user_data_dir)\n except:\n pass\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed', error=str(e))}{Style.RESET_ALL}\")\n return False, None\n\n def _wait_for_auth(self):\n \"\"\"Wait for authentication to complete and extract auth info\"\"\"\n try:\n max_wait = 300 # 5 minutes\n start_time = time.time()\n check_interval = 2 # Check every 2 seconds\n \n print(f\"{Fore.CYAN}{EMOJI['WAIT']} {self.translator.get('oauth.waiting_for_authentication', timeout='5 minutes') if self.translator else 'Waiting for authentication (timeout: 5 minutes)'}{Style.RESET_ALL}\")\n \n while time.time() - start_time < max_wait:\n try:\n # Check for authentication cookies\n cookies = self.browser.cookies()\n \n for cookie in cookies:\n if cookie.get(\"name\") == \"WorkosCursorSessionToken\":\n value = cookie.get(\"value\", \"\")\n token = get_token_from_cookie(value, self.translator)\n if token:\n # Get email from settings page\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.authentication_successful_getting_account_info') if self.translator else 'Authentication successful, getting account info...'}{Style.RESET_ALL}\")\n self.browser.get(\"https://www.cursor.com/settings\")\n time.sleep(3)\n \n email = None\n try:\n email_element = self.browser.ele(\"css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)\")\n if email_element:\n email = email_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_email', email=email) if self.translator else f'Found email: {email}'}{Style.RESET_ALL}\")\n except:\n email = \"user@cursor.sh\" # Fallback email\n \n # Check usage count\n try:\n usage_element = self.browser.ele(\"css:div[class='flex flex-col gap-4 lg:flex-row'] div:nth-child(1) div:nth-child(1) span:nth-child(2)\")\n if usage_element:\n usage_text = usage_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.usage_count', usage=usage_text) if self.translator else f'Usage count: {usage_text}'}{Style.RESET_ALL}\")\n \n def check_usage_limits(usage_str):\n try:\n parts = usage_str.split('/')\n if len(parts) != 2:\n return False\n current = int(parts[0].strip())\n limit = int(parts[1].strip())\n return (limit == 50 and current >= 50) or (limit == 150 and current >= 150)\n except:\n return False\n\n if check_usage_limits(usage_text):\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.account_has_reached_maximum_usage', deleting='deleting') if self.translator else 'Account has reached maximum usage, deleting...'}{Style.RESET_ALL}\")\n if self._delete_current_account():\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_new_authentication_process') if self.translator else 'Starting new authentication process...'}{Style.RESET_ALL}\")\n if self.auth_type == \"google\":\n return self.handle_google_auth()\n else:\n return self.handle_github_auth()\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed_to_delete_expired_account') if self.translator else 'Failed to delete expired account'}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.account_is_still_valid', usage=usage_text) if self.translator else f'Account is still valid (Usage: {usage_text})'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_check_usage_count', error=str(e)) if self.translator else f'Could not check usage count: {str(e)}'}{Style.RESET_ALL}\")\n \n return {\"email\": email, \"token\": token}\n \n # Also check URL as backup\n if \"cursor.com/settings\" in self.browser.url:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.detected_successful_login') if self.translator else 'Detected successful login'}{Style.RESET_ALL}\")\n \n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.waiting_for_authentication', error=str(e)) if self.translator else f'Waiting for authentication... ({str(e)})'}{Style.RESET_ALL}\")\n \n time.sleep(check_interval)\n \n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_timeout') if self.translator else 'Authentication timeout'}{Style.RESET_ALL}\")\n return None\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_waiting_for_authentication', error=str(e)) if self.translator else f'Error while waiting for authentication: {str(e)}'}{Style.RESET_ALL}\")\n return None\n \n def handle_github_auth(self):\n \"\"\"Handle GitHub OAuth authentication\"\"\"\n try:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.github_start')}{Style.RESET_ALL}\")\n \n # Setup browser\n if not self.setup_browser():\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.browser_failed', error=str(e)) if self.translator else 'Browser failed to initialize'}{Style.RESET_ALL}\")\n return False, None\n \n # Navigate to auth URL\n try:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.navigating_to_authentication_page') if self.translator else 'Navigating to authentication page...'}{Style.RESET_ALL}\")\n self.browser.get(\"https://authenticator.cursor.sh/sign-up\")\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n # Look for GitHub auth button\n selectors = [\n \"//a[contains(@href,'GitHubOAuth')]\",\n \"//a[contains(@class,'auth-method-button') and contains(@href,'GitHubOAuth')]\",\n \"(//a[contains(@class,'auth-method-button')])[2]\" # Second auth button as fallback\n ]\n \n auth_btn = None\n for selector in selectors:\n try:\n auth_btn = self.browser.ele(f\"xpath:{selector}\", timeout=2)\n if auth_btn and auth_btn.is_displayed():\n break\n except:\n continue\n \n if not auth_btn:\n raise Exception(\"Could not find GitHub authentication button\")\n \n # Click the button and wait for page load\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_github_authentication') if self.translator else 'Starting GitHub authentication...'}{Style.RESET_ALL}\")\n auth_btn.click()\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n # Wait for authentication to complete\n auth_info = self._wait_for_auth()\n if not auth_info:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.timeout') if self.translator else 'Timeout'}{Style.RESET_ALL}\")\n return False, None\n \n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.success')}{Style.RESET_ALL}\")\n return True, auth_info\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_error', error=str(e)) if self.translator else f'Authentication error: {str(e)}'}{Style.RESET_ALL}\")\n return False, None\n finally:\n try:\n if self.browser:\n self.browser.quit()\n except:\n pass\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed', error=str(e))}{Style.RESET_ALL}\")\n return False, None\n \n def _handle_oauth(self, auth_type):\n \"\"\"Handle OAuth authentication for both Google and GitHub\n \n Args:\n auth_type (str): Type of authentication ('google' or 'github')\n \"\"\"\n try:\n if not self.setup_browser():\n return False, None\n \n # Navigate to auth URL\n self.browser.get(\"https://authenticator.cursor.sh/sign-up\")\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n # Set selectors based on auth type\n if auth_type == \"google\":\n selectors = [\n \"//a[@class='rt-reset rt-BaseButton rt-r-size-3 rt-variant-surface rt-high-contrast rt-Button auth-method-button_AuthMethodButton__irESX'][contains(@href,'GoogleOAuth')]\",\n \"(//a[@class='rt-reset rt-BaseButton rt-r-size-3 rt-variant-surface rt-high-contrast rt-Button auth-method-button_AuthMethodButton__irESX'])[1]\"\n ]\n else: # github\n selectors = [\n \"(//a[@class='rt-reset rt-BaseButton rt-r-size-3 rt-variant-surface rt-high-contrast rt-Button auth-method-button_AuthMethodButton__irESX'])[2]\"\n ]\n \n # Wait for the button to be available\n auth_btn = None\n max_button_wait = 30 # 30 seconds\n button_start_time = time.time()\n \n while time.time() - button_start_time < max_button_wait:\n for selector in selectors:\n try:\n auth_btn = self.browser.ele(f\"xpath:{selector}\", timeout=1)\n if auth_btn and auth_btn.is_displayed():\n break\n except:\n continue\n if auth_btn:\n break\n time.sleep(1)\n \n if auth_btn:\n # Click the button and wait for page load\n auth_btn.click()\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n # Check if we're on account selection page\n if auth_type == \"google\" and \"accounts.google.com\" in self.browser.url:\n alert_message = self.translator.get('oauth.please_select_your_google_account_to_continue') if self.translator else 'Please select your Google account to continue with Cursor authentication'\n try:\n self.browser.run_js(f\"\"\"\n alert('{alert_message}');\n \"\"\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.alert_display_failed', error=str(e)) if self.translator else f'Alert display failed: {str(e)}'}{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.please_select_your_google_account_manually_to_continue_with_cursor_authentication') if self.translator else 'Please select your Google account manually to continue with Cursor authentication...'}{Style.RESET_ALL}\")\n \n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.waiting_for_authentication_to_complete') if self.translator else 'Waiting for authentication to complete...'}{Style.RESET_ALL}\")\n \n # Wait for authentication to complete\n max_wait = 300 # 5 minutes\n start_time = time.time()\n last_url = self.browser.url\n \n print(f\"{Fore.CYAN}{EMOJI['WAIT']} {self.translator.get('oauth.checking_authentication_status') if self.translator else 'Checking authentication status...'}{Style.RESET_ALL}\")\n \n while time.time() - start_time < max_wait:\n try:\n # Check for authentication cookies\n cookies = self.browser.cookies()\n \n for cookie in cookies:\n if cookie.get(\"name\") == \"WorkosCursorSessionToken\":\n value = cookie.get(\"value\", \"\")\n token = get_token_from_cookie(value, self.translator)\n if token:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.authentication_successful') if self.translator else 'Authentication successful!'}{Style.RESET_ALL}\")\n # Navigate to settings page\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.navigating_to_settings_page') if self.translator else 'Navigating to settings page...'}{Style.RESET_ALL}\")\n self.browser.get(\"https://www.cursor.com/settings\")\n time.sleep(3) # Wait for settings page to load\n \n # Get email from settings page\n try:\n email_element = self.browser.ele(\"css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)\")\n if email_element:\n actual_email = email_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_email', email=actual_email) if self.translator else f'Found email: {actual_email}'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_find_email', error=str(e)) if self.translator else f'Could not find email: {str(e)}'}{Style.RESET_ALL}\")\n actual_email = \"user@cursor.sh\"\n \n # Check usage count\n try:\n usage_element = self.browser.ele(\"css:div[class='flex flex-col gap-4 lg:flex-row'] div:nth-child(1) div:nth-child(1) span:nth-child(2)\")\n if usage_element:\n usage_text = usage_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.usage_count', usage=usage_text) if self.translator else f'Usage count: {usage_text}'}{Style.RESET_ALL}\")\n \n def check_usage_limits(usage_str):\n try:\n parts = usage_str.split('/')\n if len(parts) != 2:\n return False\n current = int(parts[0].strip())\n limit = int(parts[1].strip())\n return (limit == 50 and current >= 50) or (limit == 150 and current >= 150)\n except:\n return False\n\n if check_usage_limits(usage_text):\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.account_has_reached_maximum_usage', deleting='deleting') if self.translator else 'Account has reached maximum usage, deleting...'}{Style.RESET_ALL}\")\n if self._delete_current_account():\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_new_authentication_process') if self.translator else 'Starting new authentication process...'}{Style.RESET_ALL}\")\n if self.auth_type == \"google\":\n return self.handle_google_auth()\n else:\n return self.handle_github_auth()\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed_to_delete_expired_account') if self.translator else 'Failed to delete expired account'}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.account_is_still_valid', usage=usage_text) if self.translator else f'Account is still valid (Usage: {usage_text})'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_check_usage_count', error=str(e)) if self.translator else f'Could not check usage count: {str(e)}'}{Style.RESET_ALL}\")\n \n # Remove the browser stay open prompt and input wait\n return True, {\"email\": actual_email, \"token\": token}\n \n # Also check URL as backup\n current_url = self.browser.url\n if \"cursor.com/settings\" in current_url:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.already_on_settings_page') if self.translator else 'Already on settings page!'}{Style.RESET_ALL}\")\n time.sleep(1)\n cookies = self.browser.cookies()\n for cookie in cookies:\n if cookie.get(\"name\") == \"WorkosCursorSessionToken\":\n value = cookie.get(\"value\", \"\")\n token = get_token_from_cookie(value, self.translator)\n if token:\n # Get email and check usage here too\n try:\n email_element = self.browser.ele(\"css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)\")\n if email_element:\n actual_email = email_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_email', email=actual_email) if self.translator else f'Found email: {actual_email}'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_find_email', error=str(e)) if self.translator else f'Could not find email: {str(e)}'}{Style.RESET_ALL}\")\n actual_email = \"user@cursor.sh\"\n \n # Check usage count\n try:\n usage_element = self.browser.ele(\"css:div[class='flex flex-col gap-4 lg:flex-row'] div:nth-child(1) div:nth-child(1) span:nth-child(2)\")\n if usage_element:\n usage_text = usage_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.usage_count', usage=usage_text) if self.translator else f'Usage count: {usage_text}'}{Style.RESET_ALL}\")\n \n def check_usage_limits(usage_str):\n try:\n parts = usage_str.split('/')\n if len(parts) != 2:\n return False\n current = int(parts[0].strip())\n limit = int(parts[1].strip())\n return (limit == 50 and current >= 50) or (limit == 150 and current >= 150)\n except:\n return False\n\n if check_usage_limits(usage_text):\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.account_has_reached_maximum_usage', deleting='deleting') if self.translator else 'Account has reached maximum usage, deleting...'}{Style.RESET_ALL}\")\n if self._delete_current_account():\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_new_authentication_process') if self.translator else 'Starting new authentication process...'}{Style.RESET_ALL}\")\n if self.auth_type == \"google\":\n return self.handle_google_auth()\n else:\n return self.handle_github_auth()\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed_to_delete_expired_account') if self.translator else 'Failed to delete expired account'}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.account_is_still_valid', usage=usage_text) if self.translator else f'Account is still valid (Usage: {usage_text})'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_check_usage_count', error=str(e)) if self.translator else f'Could not check usage count: {str(e)}'}{Style.RESET_ALL}\")\n \n # Remove the browser stay open prompt and input wait\n return True, {\"email\": actual_email, \"token\": token}\n elif current_url != last_url:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.page_changed_checking_auth') if self.translator else 'Page changed, checking auth...'}{Style.RESET_ALL}\")\n last_url = current_url\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.status_check_error', error=str(e)) if self.translator else f'Status check error: {str(e)}'}{Style.RESET_ALL}\")\n time.sleep(1)\n continue\n time.sleep(1)\n \n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_timeout') if self.translator else 'Authentication timeout'}{Style.RESET_ALL}\")\n return False, None\n \n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_button_not_found') if self.translator else 'Authentication button not found'}{Style.RESET_ALL}\")\n return False, None\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_failed', error=str(e)) if self.translator else f'Authentication failed: {str(e)}'}{Style.RESET_ALL}\")\n return False, None\n finally:\n if self.browser:\n self.browser.quit()\n\n def _extract_auth_info(self):\n \"\"\"Extract authentication information after successful OAuth\"\"\"\n try:\n # Get cookies with retry\n max_retries = 3\n for attempt in range(max_retries):\n try:\n cookies = self.browser.cookies()\n if cookies:\n break\n time.sleep(1)\n except:\n if attempt == max_retries - 1:\n raise\n time.sleep(1)\n \n # Debug cookie information\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_cookies', count=len(cookies)) if self.translator else f'Found {len(cookies)} cookies'}{Style.RESET_ALL}\")\n \n email = None\n token = None\n \n for cookie in cookies:\n name = cookie.get(\"name\", \"\")\n if name == \"WorkosCursorSessionToken\":\n try:\n value = cookie.get(\"value\", \"\")\n token = get_token_from_cookie(value, self.translator)\n except Exception as e:\n error_message = f'Failed to extract auth info: {str(e)}' if not self.translator else self.translator.get('oauth.failed_to_extract_auth_info', error=str(e))\n print(f\"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}\")\n elif name == \"cursor_email\":\n email = cookie.get(\"value\")\n \n if email and token:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.authentication_successful', email=email) if self.translator else f'Authentication successful - Email: {email}'}{Style.RESET_ALL}\")\n return True, {\"email\": email, \"token\": token}\n else:\n missing = []\n if not email:\n missing.append(\"email\")\n if not token:\n missing.append(\"token\")\n error_message = f\"Missing authentication data: {', '.join(missing)}\" if not self.translator else self.translator.get('oauth.missing_authentication_data', data=', '.join(missing))\n print(f\"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}\")\n return False, None\n \n except Exception as e:\n error_message = f'Failed to extract auth info: {str(e)}' if not self.translator else self.translator.get('oauth.failed_to_extract_auth_info', error=str(e))\n print(f\"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}\")\n return False, None\n\n def _delete_current_account(self):\n \"\"\"Delete the current account using the API\"\"\"\n try:\n delete_js = \"\"\"\n function deleteAccount() {\n return new Promise((resolve, reject) => {\n fetch('https://www.cursor.com/api/dashboard/delete-account', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include'\n })\n .then(response => {\n if (response.status === 200) {\n resolve('Account deleted successfully');\n } else {\n reject('Failed to delete account: ' + response.status);\n }\n })\n .catch(error => {\n reject('Error: ' + error);\n });\n });\n }\n return deleteAccount();\n \"\"\"\n \n result = self.browser.run_js(delete_js)\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} Delete account result: {result}{Style.RESET_ALL}\")\n \n # Navigate back to auth page\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.redirecting_to_authenticator_cursor_sh') if self.translator else 'Redirecting to authenticator.cursor.sh...'}{Style.RESET_ALL}\")\n self.browser.get(\"https://authenticator.cursor.sh/sign-up\")\n time.sleep(get_random_wait_time(self.config, 'page_load_wait'))\n \n return True\n \n except Exception as e:\n error_message = f'Failed to delete account: {str(e)}' if not self.translator else self.translator.get('oauth.failed_to_delete_account', error=str(e))\n print(f\"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}\")\n return False\n\ndef main(auth_type, translator=None):\n \"\"\"Main function to handle OAuth authentication\n \n Args:\n auth_type (str): Type of authentication ('google' or 'github')\n translator: Translator instance for internationalization\n \"\"\"\n handler = OAuthHandler(translator, auth_type)\n \n if auth_type.lower() == 'google':\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('oauth.google_start') if translator else 'Google start'}{Style.RESET_ALL}\")\n success, auth_info = handler.handle_google_auth()\n elif auth_type.lower() == 'github':\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('oauth.github_start') if translator else 'Github start'}{Style.RESET_ALL}\")\n success, auth_info = handler.handle_github_auth()\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('oauth.invalid_authentication_type') if translator else 'Invalid authentication type'}{Style.RESET_ALL}\")\n return False\n \n if success and auth_info:\n # Update Cursor authentication\n auth_manager = CursorAuth(translator)\n if auth_manager.update_auth(\n email=auth_info[\"email\"],\n access_token=auth_info[\"token\"],\n refresh_token=auth_info[\"token\"],\n auth_type=auth_type\n ):\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('oauth.auth_update_success') if translator else 'Auth update success'}{Style.RESET_ALL}\")\n # Close the browser after successful authentication\n if handler.browser:\n handler.browser.quit()\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('oauth.browser_closed') if translator else 'Browser closed'}{Style.RESET_ALL}\")\n return True\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('oauth.auth_update_failed') if translator else 'Auth update failed'}{Style.RESET_ALL}\")\n \n return False "], ["/cursor-free-vip/cursor_register_manual.py", "import os\nfrom colorama import Fore, Style, init\nimport time\nimport random\nfrom faker import Faker\nfrom cursor_auth import CursorAuth\nfrom reset_machine_manual import MachineIDResetter\nfrom get_user_token import get_token_from_cookie\nfrom config import get_config\nfrom account_manager import AccountManager\n\nos.environ[\"PYTHONVERBOSE\"] = \"0\"\nos.environ[\"PYINSTALLER_VERBOSE\"] = \"0\"\n\n# Initialize colorama\ninit()\n\n# Define emoji constants\nEMOJI = {\n 'START': '🚀',\n 'FORM': '📝',\n 'VERIFY': '🔄',\n 'PASSWORD': '🔑',\n 'CODE': '📱',\n 'DONE': '✨',\n 'ERROR': '❌',\n 'WAIT': '⏳',\n 'SUCCESS': '✅',\n 'MAIL': '📧',\n 'KEY': '🔐',\n 'UPDATE': '🔄',\n 'INFO': 'ℹ️'\n}\n\nclass CursorRegistration:\n def __init__(self, translator=None):\n self.translator = translator\n # Set to display mode\n os.environ['BROWSER_HEADLESS'] = 'False'\n self.browser = None\n self.controller = None\n self.sign_up_url = \"https://authenticator.cursor.sh/sign-up\"\n self.settings_url = \"https://www.cursor.com/settings\"\n self.email_address = None\n self.signup_tab = None\n self.email_tab = None\n \n # initialize Faker instance\n self.faker = Faker()\n \n # generate account information\n self.password = self._generate_password()\n self.first_name = self.faker.first_name()\n self.last_name = self.faker.last_name()\n \n # modify the first letter of the first name(keep the original function)\n new_first_letter = random.choice(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n self.first_name = new_first_letter + self.first_name[1:]\n \n print(f\"\\n{Fore.CYAN}{EMOJI['PASSWORD']} {self.translator.get('register.password')}: {self.password} {Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{EMOJI['FORM']} {self.translator.get('register.first_name')}: {self.first_name} {Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{EMOJI['FORM']} {self.translator.get('register.last_name')}: {self.last_name} {Style.RESET_ALL}\")\n\n def _generate_password(self, length=12):\n \"\"\"Generate password\"\"\"\n return self.faker.password(length=length, special_chars=True, digits=True, upper_case=True, lower_case=True)\n\n def setup_email(self):\n \"\"\"Setup Email\"\"\"\n try:\n # Try to get a suggested email\n account_manager = AccountManager(self.translator)\n suggested_email = account_manager.suggest_email(self.first_name, self.last_name)\n \n if suggested_email:\n print(f\"{Fore.CYAN}{EMOJI['START']} {self.translator.get('register.suggest_email', suggested_email=suggested_email) if self.translator else f'Suggested email: {suggested_email}'}\")\n print(f\"{Fore.CYAN}{EMOJI['START']} {self.translator.get('register.use_suggested_email_or_enter') if self.translator else 'Type \"yes\" to use this email or enter your own email:'}\")\n user_input = input().strip()\n \n if user_input.lower() == 'yes' or user_input.lower() == 'y':\n self.email_address = suggested_email\n else:\n # User input is their own email address\n self.email_address = user_input\n else:\n # If there's no suggested email\n print(f\"{Fore.CYAN}{EMOJI['START']} {self.translator.get('register.manual_email_input') if self.translator else 'Please enter your email address:'}\")\n self.email_address = input().strip()\n \n # Validate if the email is valid\n if '@' not in self.email_address:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.invalid_email') if self.translator else 'Invalid email address'}{Style.RESET_ALL}\")\n return False\n \n print(f\"{Fore.CYAN}{EMOJI['MAIL']} {self.translator.get('register.email_address')}: {self.email_address}\" + \"\\n\" + f\"{Style.RESET_ALL}\")\n return True\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.email_setup_failed', error=str(e))}{Style.RESET_ALL}\")\n return False\n\n def get_verification_code(self):\n \"\"\"Manually Get Verification Code\"\"\"\n try:\n print(f\"{Fore.CYAN}{EMOJI['CODE']} {self.translator.get('register.manual_code_input') if self.translator else 'Please enter the verification code:'}\")\n code = input().strip()\n \n if not code.isdigit() or len(code) != 6:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.invalid_code') if self.translator else 'Invalid verification code'}{Style.RESET_ALL}\")\n return None\n \n return code\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.code_input_failed', error=str(e))}{Style.RESET_ALL}\")\n return None\n\n def register_cursor(self):\n \"\"\"Register Cursor\"\"\"\n browser_tab = None\n try:\n print(f\"{Fore.CYAN}{EMOJI['START']} {self.translator.get('register.register_start')}...{Style.RESET_ALL}\")\n \n # Check if tempmail_plus is enabled\n config = get_config(self.translator)\n email_tab = None\n if config and config.has_section('TempMailPlus'):\n if config.getboolean('TempMailPlus', 'enabled'):\n email = config.get('TempMailPlus', 'email')\n epin = config.get('TempMailPlus', 'epin')\n if email and epin:\n from email_tabs.tempmail_plus_tab import TempMailPlusTab\n email_tab = TempMailPlusTab(email, epin, self.translator)\n print(f\"{Fore.CYAN}{EMOJI['MAIL']} {self.translator.get('register.using_tempmail_plus')}{Style.RESET_ALL}\")\n \n # Use new_signup.py directly for registration\n from new_signup import main as new_signup_main\n \n # Execute new registration process, passing translator\n result, browser_tab = new_signup_main(\n email=self.email_address,\n password=self.password,\n first_name=self.first_name,\n last_name=self.last_name,\n email_tab=email_tab, # Pass email_tab if tempmail_plus is enabled\n controller=self, # Pass self instead of self.controller\n translator=self.translator\n )\n \n if result:\n # Use the returned browser instance to get account information\n self.signup_tab = browser_tab # Save browser instance\n success = self._get_account_info()\n \n # Close browser after getting information\n if browser_tab:\n try:\n browser_tab.quit()\n except:\n pass\n \n return success\n \n return False\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.register_process_error', error=str(e))}{Style.RESET_ALL}\")\n return False\n finally:\n # Ensure browser is closed in any case\n if browser_tab:\n try:\n browser_tab.quit()\n except:\n pass\n \n def _get_account_info(self):\n \"\"\"Get Account Information and Token\"\"\"\n try:\n self.signup_tab.get(self.settings_url)\n time.sleep(2)\n \n usage_selector = (\n \"css:div.col-span-2 > div > div > div > div > \"\n \"div:nth-child(1) > div.flex.items-center.justify-between.gap-2 > \"\n \"span.font-mono.text-sm\\\\/\\\\[0\\\\.875rem\\\\]\"\n )\n usage_ele = self.signup_tab.ele(usage_selector)\n total_usage = \"未知\"\n if usage_ele:\n total_usage = usage_ele.text.split(\"/\")[-1].strip()\n\n print(f\"Total Usage: {total_usage}\\n\")\n print(f\"{Fore.CYAN}{EMOJI['WAIT']} {self.translator.get('register.get_token')}...{Style.RESET_ALL}\")\n max_attempts = 30\n retry_interval = 2\n attempts = 0\n\n while attempts < max_attempts:\n try:\n cookies = self.signup_tab.cookies()\n for cookie in cookies:\n if cookie.get(\"name\") == \"WorkosCursorSessionToken\":\n token = get_token_from_cookie(cookie[\"value\"], self.translator)\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('register.token_success')}{Style.RESET_ALL}\")\n self._save_account_info(token, total_usage)\n return True\n\n attempts += 1\n if attempts < max_attempts:\n print(f\"{Fore.YELLOW}{EMOJI['WAIT']} {self.translator.get('register.token_attempt', attempt=attempts, time=retry_interval)}{Style.RESET_ALL}\")\n time.sleep(retry_interval)\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.token_max_attempts', max=max_attempts)}{Style.RESET_ALL}\")\n\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.token_failed', error=str(e))}{Style.RESET_ALL}\")\n attempts += 1\n if attempts < max_attempts:\n print(f\"{Fore.YELLOW}{EMOJI['WAIT']} {self.translator.get('register.token_attempt', attempt=attempts, time=retry_interval)}{Style.RESET_ALL}\")\n time.sleep(retry_interval)\n\n return False\n\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.account_error', error=str(e))}{Style.RESET_ALL}\")\n return False\n\n def _save_account_info(self, token, total_usage):\n \"\"\"Save Account Information to File\"\"\"\n try:\n # Update authentication information first\n print(f\"{Fore.CYAN}{EMOJI['KEY']} {self.translator.get('register.update_cursor_auth_info')}...{Style.RESET_ALL}\")\n if self.update_cursor_auth(email=self.email_address, access_token=token, refresh_token=token, auth_type=\"Auth_0\"):\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('register.cursor_auth_info_updated')}...{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.cursor_auth_info_update_failed')}...{Style.RESET_ALL}\")\n\n # Reset machine ID\n print(f\"{Fore.CYAN}{EMOJI['UPDATE']} {self.translator.get('register.reset_machine_id')}...{Style.RESET_ALL}\")\n resetter = MachineIDResetter(self.translator) # Create instance with translator\n if not resetter.reset_machine_ids(): # Call reset_machine_ids method directly\n raise Exception(\"Failed to reset machine ID\")\n \n # Save account information to file using AccountManager\n account_manager = AccountManager(self.translator)\n if account_manager.save_account_info(self.email_address, self.password, token, total_usage):\n return True\n else:\n return False\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.save_account_info_failed', error=str(e))}{Style.RESET_ALL}\")\n return False\n\n def start(self):\n \"\"\"Start Registration Process\"\"\"\n try:\n if self.setup_email():\n if self.register_cursor():\n print(f\"\\n{Fore.GREEN}{EMOJI['DONE']} {self.translator.get('register.cursor_registration_completed')}...{Style.RESET_ALL}\")\n return True\n return False\n finally:\n # Close email tab\n if hasattr(self, 'temp_email'):\n try:\n self.temp_email.close()\n except:\n pass\n\n def update_cursor_auth(self, email=None, access_token=None, refresh_token=None, auth_type=\"Auth_0\"):\n \"\"\"Convenient function to update Cursor authentication information\"\"\"\n auth_manager = CursorAuth(translator=self.translator)\n return auth_manager.update_auth(email, access_token, refresh_token, auth_type)\n\ndef main(translator=None):\n \"\"\"Main function to be called from main.py\"\"\"\n print(f\"\\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{EMOJI['START']} {translator.get('register.title')}{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{'='*50}{Style.RESET_ALL}\")\n\n registration = CursorRegistration(translator)\n registration.start()\n\n print(f\"\\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}\")\n input(f\"{EMOJI['INFO']} {translator.get('register.press_enter')}...\")\n\nif __name__ == \"__main__\":\n from main import translator as main_translator\n main(main_translator) "], ["/cursor-free-vip/delete_cursor_google.py", "from oauth_auth import OAuthHandler\nimport time\nfrom colorama import Fore, Style, init\nimport sys\n\n# Initialize colorama\ninit()\n\n# Define emoji constants\nEMOJI = {\n 'START': '🚀',\n 'DELETE': '🗑️',\n 'SUCCESS': '✅',\n 'ERROR': '❌',\n 'WAIT': '⏳',\n 'INFO': 'ℹ️',\n 'WARNING': '⚠️'\n}\n\nclass CursorGoogleAccountDeleter(OAuthHandler):\n def __init__(self, translator=None):\n super().__init__(translator, auth_type='google')\n \n def delete_google_account(self):\n \"\"\"Delete Cursor account using Google OAuth\"\"\"\n try:\n # Setup browser and select profile\n if not self.setup_browser():\n return False\n \n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('account_delete.starting_process') if self.translator else 'Starting account deletion process...'}{Style.RESET_ALL}\")\n \n # Navigate to Cursor auth page - using the same URL as in registration\n self.browser.get(\"https://authenticator.cursor.sh/sign-up\")\n time.sleep(2)\n \n # Click Google auth button using same selectors as in registration\n selectors = [\n \"//a[contains(@href,'GoogleOAuth')]\",\n \"//a[contains(@class,'auth-method-button') and contains(@href,'GoogleOAuth')]\",\n \"(//a[contains(@class,'auth-method-button')])[1]\" # First auth button as fallback\n ]\n \n auth_btn = None\n for selector in selectors:\n try:\n auth_btn = self.browser.ele(f\"xpath:{selector}\", timeout=2)\n if auth_btn:\n break\n except:\n continue\n \n if not auth_btn:\n raise Exception(self.translator.get('account_delete.google_button_not_found') if self.translator else \"Google login button not found\")\n \n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('account_delete.logging_in') if self.translator else 'Logging in with Google...'}{Style.RESET_ALL}\")\n auth_btn.click()\n \n # Wait for authentication to complete using a more robust method\n print(f\"{Fore.CYAN}{EMOJI['WAIT']} {self.translator.get('account_delete.waiting_for_auth', fallback='Waiting for Google authentication...')}{Style.RESET_ALL}\")\n \n # Dynamic wait for authentication\n max_wait_time = 120 # Increase maximum wait time to 120 seconds\n start_time = time.time()\n check_interval = 3 # Check every 3 seconds\n google_account_alert_shown = False # Track if we've shown the alert already\n \n while time.time() - start_time < max_wait_time:\n current_url = self.browser.url\n \n # If we're already on the settings or dashboard page, we're successful\n if \"/dashboard\" in current_url or \"/settings\" in current_url or \"cursor.com\" in current_url:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.login_successful') if self.translator else 'Login successful'}{Style.RESET_ALL}\")\n break\n \n # If we're on Google accounts page or accounts.google.com, wait for user selection\n if \"accounts.google.com\" in current_url:\n # Only show the alert once to avoid spamming\n if not google_account_alert_shown:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('account_delete.select_google_account', fallback='Please select your Google account...')}{Style.RESET_ALL}\")\n # Alert to indicate user action needed\n try:\n self.browser.run_js(\"\"\"\n alert('Please select your Google account to continue with Cursor authentication');\n \"\"\")\n google_account_alert_shown = True # Mark that we've shown the alert\n except:\n pass # Alert is optional\n \n # Sleep before checking again\n time.sleep(check_interval)\n else:\n # If the loop completed without breaking, it means we hit the timeout\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('account_delete.auth_timeout', fallback='Authentication timeout, continuing anyway...')}{Style.RESET_ALL}\")\n \n # Check current URL to determine next steps\n current_url = self.browser.url\n \n # If we're already on the settings page, no need to navigate\n if \"/settings\" in current_url and \"cursor.com\" in current_url:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.already_on_settings', fallback='Already on settings page')}{Style.RESET_ALL}\")\n # If we're on the dashboard or any Cursor page but not settings, navigate to settings\n elif \"cursor.com\" in current_url or \"authenticator.cursor.sh\" in current_url:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('account_delete.navigating_to_settings', fallback='Navigating to settings page...')}{Style.RESET_ALL}\")\n self.browser.get(\"https://www.cursor.com/settings\")\n # If we're still on Google auth or somewhere else, try directly going to settings\n else:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('account_delete.login_redirect_failed', fallback='Login redirection failed, trying direct navigation...')}{Style.RESET_ALL}\")\n self.browser.get(\"https://www.cursor.com/settings\")\n \n # Wait for the settings page to load\n time.sleep(3) # Reduced from 5 seconds\n \n # First look for the email element to confirm we're logged in\n try:\n email_element = self.browser.ele(\"css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)\")\n if email_element:\n email = email_element.text\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('account_delete.found_email', email=email, fallback=f'Found email: {email}')}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('account_delete.email_not_found', error=str(e), fallback=f'Email not found: {str(e)}')}{Style.RESET_ALL}\")\n \n # Click on \"Advanced\" tab or dropdown - keep only the successful approach\n advanced_found = False\n \n # Direct JavaScript querySelector approach that worked according to logs\n try:\n advanced_element_js = self.browser.run_js(\"\"\"\n // Try to find the Advanced dropdown using querySelector with the exact classes\n let advancedElement = document.querySelector('div.mb-0.flex.cursor-pointer.items-center.text-xs:not([style*=\"display: none\"])');\n \n // If not found, try a more general approach\n if (!advancedElement) {\n const allDivs = document.querySelectorAll('div');\n for (const div of allDivs) {\n if (div.textContent.includes('Advanced') && \n div.className.includes('mb-0') && \n div.className.includes('flex') &&\n div.className.includes('cursor-pointer')) {\n advancedElement = div;\n break;\n }\n }\n }\n \n // Click the element if found\n if (advancedElement) {\n advancedElement.click();\n return true;\n }\n \n return false;\n \"\"\")\n \n if advanced_element_js:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.advanced_tab_clicked', fallback='Found and clicked Advanced using direct JavaScript selector')}{Style.RESET_ALL}\")\n advanced_found = True\n time.sleep(1) # Reduced from 2 seconds\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('account_delete.advanced_tab_error', error=str(e), fallback='JavaScript querySelector approach failed: {str(e)}')}{Style.RESET_ALL}\")\n \n if not advanced_found:\n # Fallback to direct URL navigation which is faster and more reliable\n try:\n self.browser.get(\"https://www.cursor.com/settings?tab=advanced\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('account_delete.direct_advanced_navigation', fallback='Trying direct navigation to advanced tab')}{Style.RESET_ALL}\")\n advanced_found = True\n except:\n raise Exception(self.translator.get('account_delete.advanced_tab_not_found') if self.translator else \"Advanced option not found after multiple attempts\")\n \n # Wait for dropdown/tab content to load\n time.sleep(2) # Reduced from 4 seconds\n \n # Find and click the \"Delete Account\" button \n delete_button_found = False\n \n # Simplified approach for delete button based on what worked\n delete_button_selectors = [\n 'xpath://button[contains(., \"Delete Account\")]',\n 'xpath://button[text()=\"Delete Account\"]',\n 'xpath://div[contains(text(), \"Delete Account\")]',\n 'xpath://button[contains(text(), \"Delete\") and contains(text(), \"Account\")]'\n ]\n \n for selector in delete_button_selectors:\n try:\n delete_button = self.browser.ele(selector, timeout=2)\n if delete_button:\n delete_button.click()\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('account_delete.delete_button_clicked') if self.translator else 'Clicked on Delete Account button'}{Style.RESET_ALL}\")\n delete_button_found = True\n break\n except:\n continue\n \n if not delete_button_found:\n raise Exception(self.translator.get('account_delete.delete_button_not_found') if self.translator else \"Delete Account button not found\")\n \n # Wait for confirmation dialog to appear\n time.sleep(2)\n \n # Check if we need to input \"Delete\" at all - some modals might not require it\n input_required = True\n try:\n # Try detecting if the DELETE button is already enabled\n delete_button_enabled = self.browser.run_js(\"\"\"\n const buttons = Array.from(document.querySelectorAll('button'));\n const deleteButtons = buttons.filter(btn => \n btn.textContent.trim() === 'DELETE' || \n btn.textContent.trim() === 'Delete'\n );\n \n if (deleteButtons.length > 0) {\n return !deleteButtons.some(btn => btn.disabled);\n }\n return false;\n \"\"\")\n \n if delete_button_enabled:\n print(f\"{Fore.CYAN}{EMOJI['INFO']} DELETE button appears to be enabled already. Input may not be required.{Style.RESET_ALL}\")\n input_required = False\n except:\n pass\n \n # Type \"Delete\" in the confirmation input - only if required\n delete_input_found = False\n \n if input_required:\n # Try common selectors for the input field\n delete_input_selectors = [\n 'xpath://input[@placeholder=\"Delete\"]',\n 'xpath://div[contains(@class, \"modal\")]//input',\n 'xpath://input',\n 'css:input'\n ]\n \n for selector in delete_input_selectors:\n try:\n delete_input = self.browser.ele(selector, timeout=3)\n if delete_input:\n delete_input.clear()\n delete_input.input(\"Delete\")\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.typed_delete', fallback='Typed \\\"Delete\\\" in confirmation box')}{Style.RESET_ALL}\")\n delete_input_found = True\n time.sleep(2)\n break\n except:\n # Try direct JavaScript input as fallback\n try:\n self.browser.run_js(r\"\"\"\n arguments[0].value = \"Delete\";\n const event = new Event('input', { bubbles: true });\n arguments[0].dispatchEvent(event);\n const changeEvent = new Event('change', { bubbles: true });\n arguments[0].dispatchEvent(changeEvent);\n \"\"\", delete_input)\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.typed_delete_js', fallback='Typed \\\"Delete\\\" using JavaScript')}{Style.RESET_ALL}\")\n delete_input_found = True\n time.sleep(2)\n break\n except:\n continue\n \n if not delete_input_found:\n print(f\"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('account_delete.delete_input_not_found', fallback='Delete confirmation input not found, continuing anyway')}{Style.RESET_ALL}\")\n time.sleep(2)\n \n # Wait before clicking the final DELETE button\n time.sleep(2)\n \n # Click on the final DELETE button\n confirm_button_found = False\n \n # Use JavaScript approach for the DELETE button\n try:\n delete_button_js = self.browser.run_js(\"\"\"\n // Try to find the DELETE button by exact text content\n const buttons = Array.from(document.querySelectorAll('button'));\n const deleteButton = buttons.find(btn => \n btn.textContent.trim() === 'DELETE' || \n btn.textContent.trim() === 'Delete'\n );\n \n if (deleteButton) {\n console.log(\"Found DELETE button with JavaScript\");\n deleteButton.click();\n return true;\n }\n \n // If not found by text, try to find right-most button in the modal\n const modalButtons = Array.from(document.querySelectorAll('.relative button, [role=\"dialog\"] button, .modal button, [aria-modal=\"true\"] button'));\n \n if (modalButtons.length > 1) {\n modalButtons.sort((a, b) => {\n const rectA = a.getBoundingClientRect();\n const rectB = b.getBoundingClientRect();\n return rectB.right - rectA.right;\n });\n \n console.log(\"Clicking right-most button in modal\");\n modalButtons[0].click();\n return true;\n } else if (modalButtons.length === 1) {\n console.log(\"Clicking single button found in modal\");\n modalButtons[0].click();\n return true;\n }\n \n return false;\n \"\"\")\n \n if delete_button_js:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.delete_button_clicked', fallback='Clicked DELETE button')}{Style.RESET_ALL}\")\n confirm_button_found = True\n except:\n pass\n \n if not confirm_button_found:\n # Fallback to simple selectors\n delete_button_selectors = [\n 'xpath://button[text()=\"DELETE\"]',\n 'xpath://div[contains(@class, \"modal\")]//button[last()]'\n ]\n \n for selector in delete_button_selectors:\n try:\n delete_button = self.browser.ele(selector, timeout=2)\n if delete_button:\n delete_button.click()\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('account_delete.delete_button_clicked', fallback='Account deleted successfully!')}{Style.RESET_ALL}\")\n confirm_button_found = True\n break\n except:\n continue\n \n if not confirm_button_found:\n raise Exception(self.translator.get('account_delete.confirm_button_not_found') if self.translator else \"Confirm button not found\")\n \n # Wait a moment to see the confirmation\n time.sleep(2)\n \n return True\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('account_delete.error', error=str(e)) if self.translator else f'Error during account deletion: {str(e)}'}{Style.RESET_ALL}\")\n return False\n finally:\n # Clean up browser\n if self.browser:\n try:\n self.browser.quit()\n except:\n pass\n \ndef main(translator=None):\n \"\"\"Main function to handle Google account deletion\"\"\"\n print(f\"\\n{Fore.CYAN}{EMOJI['START']} {translator.get('account_delete.title') if translator else 'Cursor Google Account Deletion Tool'}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{'─' * 50}{Style.RESET_ALL}\")\n \n deleter = CursorGoogleAccountDeleter(translator)\n \n try:\n # Ask for confirmation\n print(f\"{Fore.RED}{EMOJI['WARNING']} {translator.get('account_delete.warning') if translator else 'WARNING: This will permanently delete your Cursor account. This action cannot be undone.'}{Style.RESET_ALL}\")\n confirm = input(f\"{Fore.RED} {translator.get('account_delete.confirm_prompt') if translator else 'Are you sure you want to proceed? (y/N): '}{Style.RESET_ALL}\").lower()\n \n if confirm != 'y':\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('account_delete.cancelled') if translator else 'Account deletion cancelled.'}{Style.RESET_ALL}\")\n return\n \n success = deleter.delete_google_account()\n \n if success:\n print(f\"\\n{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('account_delete.success') if translator else 'Your Cursor account has been successfully deleted!'}{Style.RESET_ALL}\")\n else:\n print(f\"\\n{Fore.RED}{EMOJI['ERROR']} {translator.get('account_delete.failed') if translator else 'Account deletion process failed or was cancelled.'}{Style.RESET_ALL}\")\n \n except KeyboardInterrupt:\n print(f\"\\n{Fore.YELLOW}{EMOJI['INFO']} {translator.get('account_delete.interrupted') if translator else 'Account deletion process interrupted by user.'}{Style.RESET_ALL}\")\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('account_delete.unexpected_error', error=str(e)) if translator else f'Unexpected error: {str(e)}'}{Style.RESET_ALL}\")\n finally:\n print(f\"{Fore.YELLOW}{'─' * 50}{Style.RESET_ALL}\")\n\nif __name__ == \"__main__\":\n main() "], ["/cursor-free-vip/main.py", "# main.py\n# This script allows the user to choose which script to run.\nimport os\nimport sys\nimport json\nfrom logo import print_logo, version\nfrom colorama import Fore, Style, init\nimport locale\nimport platform\nimport requests\nimport subprocess\nfrom config import get_config, force_update_config\nimport shutil\nimport re\nfrom utils import get_user_documents_path \n\n# Add these imports for Arabic support\ntry:\n import arabic_reshaper\n from bidi.algorithm import get_display\nexcept ImportError:\n arabic_reshaper = None\n get_display = None\n\n# Only import windll on Windows systems\nif platform.system() == 'Windows':\n import ctypes\n # Only import windll on Windows systems\n from ctypes import windll\n\n# Initialize colorama\ninit()\n\n# Define emoji and color constants\nEMOJI = {\n \"FILE\": \"📄\",\n \"BACKUP\": \"💾\",\n \"SUCCESS\": \"✅\",\n \"ERROR\": \"❌\",\n \"INFO\": \"ℹ️\",\n \"RESET\": \"🔄\",\n \"MENU\": \"📋\",\n \"ARROW\": \"➜\",\n \"LANG\": \"🌐\",\n \"UPDATE\": \"🔄\",\n \"ADMIN\": \"🔐\",\n \"AIRDROP\": \"💰\",\n \"ROCKET\": \"🚀\",\n \"STAR\": \"⭐\",\n \"SUN\": \"🌟\",\n \"CONTRIBUTE\": \"🤝\",\n \"SETTINGS\": \"⚙️\"\n}\n\n# Function to check if running as frozen executable\ndef is_frozen():\n \"\"\"Check if the script is running as a frozen executable.\"\"\"\n return getattr(sys, 'frozen', False)\n\n# Function to check admin privileges (Windows only)\ndef is_admin():\n \"\"\"Check if the script is running with admin privileges (Windows only).\"\"\"\n if platform.system() == 'Windows':\n try:\n return ctypes.windll.shell32.IsUserAnAdmin() != 0\n except Exception:\n return False\n # Always return True for non-Windows to avoid changing behavior\n return True\n\n# Function to restart with admin privileges\ndef run_as_admin():\n \"\"\"Restart the current script with admin privileges (Windows only).\"\"\"\n if platform.system() != 'Windows':\n return False\n \n try:\n args = [sys.executable] + sys.argv\n \n # Request elevation via ShellExecute\n print(f\"{Fore.YELLOW}{EMOJI['ADMIN']} Requesting administrator privileges...{Style.RESET_ALL}\")\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", args[0], \" \".join('\"' + arg + '\"' for arg in args[1:]), None, 1)\n return True\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} Failed to restart with admin privileges: {e}{Style.RESET_ALL}\")\n return False\n\nclass Translator:\n def __init__(self):\n self.translations = {}\n self.config = get_config()\n \n # Create language cache directory if it doesn't exist\n if self.config and self.config.has_section('Language'):\n self.language_cache_dir = self.config.get('Language', 'language_cache_dir')\n os.makedirs(self.language_cache_dir, exist_ok=True)\n else:\n self.language_cache_dir = None\n \n # Set fallback language from config if available\n self.fallback_language = 'en'\n if self.config and self.config.has_section('Language') and self.config.has_option('Language', 'fallback_language'):\n self.fallback_language = self.config.get('Language', 'fallback_language')\n \n # Load saved language from config if available, otherwise detect system language\n if self.config and self.config.has_section('Language') and self.config.has_option('Language', 'current_language'):\n saved_language = self.config.get('Language', 'current_language')\n if saved_language and saved_language.strip():\n self.current_language = saved_language\n else:\n self.current_language = self.detect_system_language()\n # Save detected language to config\n if self.config.has_section('Language'):\n self.config.set('Language', 'current_language', self.current_language)\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\")\n config_file = os.path.join(config_dir, \"config.ini\")\n with open(config_file, 'w', encoding='utf-8') as f:\n self.config.write(f)\n else:\n self.current_language = self.detect_system_language()\n \n self.load_translations()\n \n def detect_system_language(self):\n \"\"\"Detect system language and return corresponding language code\"\"\"\n try:\n system = platform.system()\n \n if system == 'Windows':\n return self._detect_windows_language()\n else:\n return self._detect_unix_language()\n \n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} Failed to detect system language: {e}{Style.RESET_ALL}\")\n return 'en'\n \n def _detect_windows_language(self):\n \"\"\"Detect language on Windows systems\"\"\"\n try:\n # Ensure we are on Windows\n if platform.system() != 'Windows':\n return 'en'\n \n # Get keyboard layout\n user32 = ctypes.windll.user32\n hwnd = user32.GetForegroundWindow()\n threadid = user32.GetWindowThreadProcessId(hwnd, 0)\n layout_id = user32.GetKeyboardLayout(threadid) & 0xFFFF\n \n # Map language ID to our language codes using match-case\n match layout_id:\n case 0x0409:\n return 'en' # English\n case 0x0404:\n return 'zh_tw' # Traditional Chinese\n case 0x0804:\n return 'zh_cn' # Simplified Chinese\n case 0x0422:\n return 'vi' # Vietnamese\n case 0x0419:\n return 'ru' # Russian\n case 0x0415:\n return 'tr' # Turkish\n case 0x0402:\n return 'bg' # Bulgarian\n case 0x0401:\n return 'ar' # Arabic\n case _:\n return 'en' # Default to English\n except:\n return self._detect_unix_language()\n \n def _detect_unix_language(self):\n \"\"\"Detect language on Unix-like systems (Linux, macOS)\"\"\"\n try:\n # Get the system locale\n locale.setlocale(locale.LC_ALL, '')\n system_locale = locale.getlocale()[0]\n if not system_locale:\n return 'en'\n \n system_locale = system_locale.lower()\n \n # Map locale to our language codes using match-case\n match system_locale:\n case s if s.startswith('zh_tw') or s.startswith('zh_hk'):\n return 'zh_tw'\n case s if s.startswith('zh_cn'):\n return 'zh_cn'\n case s if s.startswith('en'):\n return 'en'\n case s if s.startswith('vi'):\n return 'vi'\n case s if s.startswith('nl'):\n return 'nl'\n case s if s.startswith('de'):\n return 'de'\n case s if s.startswith('fr'):\n return 'fr'\n case s if s.startswith('pt'):\n return 'pt'\n case s if s.startswith('ru'):\n return 'ru'\n case s if s.startswith('tr'):\n return 'tr'\n case s if s.startswith('bg'):\n return 'bg'\n case s if s.startswith('ar'):\n return 'ar'\n case _:\n # Try to get language from LANG environment variable as fallback\n env_lang = os.getenv('LANG', '').lower()\n match env_lang:\n case s if 'tw' in s or 'hk' in s:\n return 'zh_tw'\n case s if 'cn' in s:\n return 'zh_cn'\n case s if 'vi' in s:\n return 'vi'\n case s if 'nl' in s:\n return 'nl'\n case s if 'de' in s:\n return 'de'\n case s if 'fr' in s:\n return 'fr'\n case s if 'pt' in s:\n return 'pt'\n case s if 'ru' in s:\n return 'ru'\n case s if 'tr' in s:\n return 'tr'\n case s if 'bg' in s:\n return 'bg'\n case s if 'ar' in s:\n return 'ar'\n case _:\n return 'en'\n except:\n return 'en'\n \n def download_language_file(self, lang_code):\n \"\"\"Method kept for compatibility but now returns False as language files are integrated\"\"\"\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} Languages are now integrated into the package, no need to download.{Style.RESET_ALL}\")\n return False\n \n def load_translations(self):\n \"\"\"Load all available translations from the integrated package\"\"\"\n try:\n # Collection of languages we've successfully loaded\n loaded_languages = set()\n \n locales_paths = []\n \n # Check for PyInstaller bundle first\n if hasattr(sys, '_MEIPASS'):\n locales_paths.append(os.path.join(sys._MEIPASS, 'locales'))\n \n # Check script directory next\n script_dir = os.path.dirname(os.path.abspath(__file__))\n locales_paths.append(os.path.join(script_dir, 'locales'))\n \n # Also check current working directory\n locales_paths.append(os.path.join(os.getcwd(), 'locales'))\n \n for locales_dir in locales_paths:\n if os.path.exists(locales_dir) and os.path.isdir(locales_dir):\n for file in os.listdir(locales_dir):\n if file.endswith('.json'):\n lang_code = file[:-5] # Remove .json\n try:\n with open(os.path.join(locales_dir, file), 'r', encoding='utf-8') as f:\n self.translations[lang_code] = json.load(f)\n loaded_languages.add(lang_code)\n loaded_any = True\n except (json.JSONDecodeError, UnicodeDecodeError) as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} Error loading {file}: {e}{Style.RESET_ALL}\")\n continue\n\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} Failed to load translations: {e}{Style.RESET_ALL}\")\n # Create at least minimal English translations for basic functionality\n self.translations['en'] = {\"menu\": {\"title\": \"Menu\", \"exit\": \"Exit\", \"invalid_choice\": \"Invalid choice\"}}\n \n def fix_arabic(self, text):\n if self.current_language == 'ar' and arabic_reshaper and get_display:\n try:\n reshaped_text = arabic_reshaper.reshape(text)\n bidi_text = get_display(reshaped_text)\n return bidi_text\n except Exception:\n return text\n return text\n\n def get(self, key, **kwargs):\n \"\"\"Get translated text with fallback support\"\"\"\n try:\n # Try current language\n result = self._get_translation(self.current_language, key)\n if result == key and self.current_language != self.fallback_language:\n # Try fallback language if translation not found\n result = self._get_translation(self.fallback_language, key)\n formatted = result.format(**kwargs) if kwargs else result\n return self.fix_arabic(formatted)\n except Exception:\n return key\n \n def _get_translation(self, lang_code, key):\n \"\"\"Get translation for a specific language\"\"\"\n try:\n keys = key.split('.')\n value = self.translations.get(lang_code, {})\n for k in keys:\n if isinstance(value, dict):\n value = value.get(k, key)\n else:\n return key\n return value\n except Exception:\n return key\n \n def set_language(self, lang_code):\n \"\"\"Set current language with validation\"\"\"\n if lang_code in self.translations:\n self.current_language = lang_code\n return True\n return False\n\n def get_available_languages(self):\n \"\"\"Get list of available languages\"\"\"\n # Get currently loaded languages\n available_languages = list(self.translations.keys())\n \n # Sort languages alphabetically for better display\n return sorted(available_languages)\n\n# Create translator instance\ntranslator = Translator()\n\ndef print_menu():\n \"\"\"Print menu options\"\"\"\n try:\n config = get_config()\n if config.getboolean('Utils', 'enabled_account_info'):\n import cursor_acc_info\n cursor_acc_info.display_account_info(translator)\n except Exception as e:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('menu.account_info_error', error=str(e))}{Style.RESET_ALL}\")\n \n print(f\"\\n{Fore.CYAN}{EMOJI['MENU']} {translator.get('menu.title')}:{Style.RESET_ALL}\")\n if translator.current_language == 'zh_cn' or translator.current_language == 'zh_tw':\n print(f\"{Fore.YELLOW}{'─' * 70}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.YELLOW}{'─' * 110}{Style.RESET_ALL}\")\n \n # Get terminal width\n try:\n terminal_width = shutil.get_terminal_size().columns\n except:\n terminal_width = 80 # Default width\n \n # Define all menu items\n menu_items = {\n 0: f\"{Fore.GREEN}0{Style.RESET_ALL}. {EMOJI['ERROR']} {translator.get('menu.exit')}\",\n 1: f\"{Fore.GREEN}1{Style.RESET_ALL}. {EMOJI['RESET']} {translator.get('menu.reset')}\",\n 2: f\"{Fore.GREEN}2{Style.RESET_ALL}. {EMOJI['SUCCESS']} {translator.get('menu.register_manual')}\",\n 3: f\"{Fore.GREEN}3{Style.RESET_ALL}. {EMOJI['ERROR']} {translator.get('menu.quit')}\",\n 4: f\"{Fore.GREEN}4{Style.RESET_ALL}. {EMOJI['LANG']} {translator.get('menu.select_language')}\",\n 5: f\"{Fore.GREEN}5{Style.RESET_ALL}. {EMOJI['SUN']} {translator.get('menu.register_google')}\",\n 6: f\"{Fore.GREEN}6{Style.RESET_ALL}. {EMOJI['STAR']} {translator.get('menu.register_github')}\",\n 7: f\"{Fore.GREEN}7{Style.RESET_ALL}. {EMOJI['UPDATE']} {translator.get('menu.disable_auto_update')}\",\n 8: f\"{Fore.GREEN}8{Style.RESET_ALL}. {EMOJI['RESET']} {translator.get('menu.totally_reset')}\",\n 9: f\"{Fore.GREEN}9{Style.RESET_ALL}. {EMOJI['CONTRIBUTE']} {translator.get('menu.contribute')}\",\n 10: f\"{Fore.GREEN}10{Style.RESET_ALL}. {EMOJI['SETTINGS']} {translator.get('menu.config')}\",\n 11: f\"{Fore.GREEN}11{Style.RESET_ALL}. {EMOJI['UPDATE']} {translator.get('menu.bypass_version_check')}\",\n 12: f\"{Fore.GREEN}12{Style.RESET_ALL}. {EMOJI['UPDATE']} {translator.get('menu.check_user_authorized')}\",\n 13: f\"{Fore.GREEN}13{Style.RESET_ALL}. {EMOJI['UPDATE']} {translator.get('menu.bypass_token_limit')}\",\n 14: f\"{Fore.GREEN}14{Style.RESET_ALL}. {EMOJI['BACKUP']} {translator.get('menu.restore_machine_id')}\",\n 15: f\"{Fore.GREEN}15{Style.RESET_ALL}. {EMOJI['ERROR']} {translator.get('menu.delete_google_account')}\",\n 16: f\"{Fore.GREEN}16{Style.RESET_ALL}. {EMOJI['SETTINGS']} {translator.get('menu.select_chrome_profile')}\",\n 17: f\"{Fore.GREEN}17{Style.RESET_ALL}. {EMOJI['UPDATE']} {translator.get('menu.manual_custom_auth')}\"\n }\n \n # Automatically calculate the number of menu items in the left and right columns\n total_items = len(menu_items)\n left_column_count = (total_items + 1) // 2 # The number of options displayed on the left (rounded up)\n \n # Build left and right columns of menus\n sorted_indices = sorted(menu_items.keys())\n left_menu = [menu_items[i] for i in sorted_indices[:left_column_count]]\n right_menu = [menu_items[i] for i in sorted_indices[left_column_count:]]\n \n # Calculate the maximum display width of left menu items\n ansi_escape = re.compile(r'\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])')\n \n def get_display_width(s):\n \"\"\"Calculate the display width of a string, considering Chinese characters and emojis\"\"\"\n # Remove ANSI color codes\n clean_s = ansi_escape.sub('', s)\n width = 0\n for c in clean_s:\n # Chinese characters and some emojis occupy two character widths\n if ord(c) > 127:\n width += 2\n else:\n width += 1\n return width\n \n max_left_width = 0\n for item in left_menu:\n width = get_display_width(item)\n max_left_width = max(max_left_width, width)\n \n # Set the starting position of right menu\n fixed_spacing = 4 # Fixed spacing\n right_start = max_left_width + fixed_spacing\n \n # Calculate the number of spaces needed for right menu items\n spaces_list = []\n for i in range(len(left_menu)):\n if i < len(left_menu):\n left_item = left_menu[i]\n left_width = get_display_width(left_item)\n spaces = right_start - left_width\n spaces_list.append(spaces)\n \n # Print menu items\n max_rows = max(len(left_menu), len(right_menu))\n \n for i in range(max_rows):\n # Print left menu items\n if i < len(left_menu):\n left_item = left_menu[i]\n print(left_item, end='')\n \n # Use pre-calculated spaces\n spaces = spaces_list[i]\n else:\n # If left side has no items, print only spaces\n spaces = right_start\n print('', end='')\n \n # Print right menu items\n if i < len(right_menu):\n print(' ' * spaces + right_menu[i])\n else:\n print() # Change line\n if translator.current_language == 'zh_cn' or translator.current_language == 'zh_tw':\n print(f\"{Fore.YELLOW}{'─' * 70}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.YELLOW}{'─' * 110}{Style.RESET_ALL}\")\n\ndef select_language():\n \"\"\"Language selection menu\"\"\"\n print(f\"\\n{Fore.CYAN}{EMOJI['LANG']} {translator.get('menu.select_language')}:{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{'─' * 40}{Style.RESET_ALL}\")\n \n # Get available languages either from local directory or GitHub\n languages = translator.get_available_languages()\n languages_count = len(languages)\n \n # Display all available languages with proper indices\n for i, lang in enumerate(languages):\n lang_name = translator.get(f\"languages.{lang}\", fallback=lang)\n print(f\"{Fore.GREEN}{i}{Style.RESET_ALL}. {lang_name}\")\n \n try:\n # Use the actual number of languages in the prompt\n choice = input(f\"\\n{EMOJI['ARROW']} {Fore.CYAN}{translator.get('menu.input_choice', choices=f'0-{languages_count-1}')}: {Style.RESET_ALL}\")\n \n if choice.isdigit() and 0 <= int(choice) < languages_count:\n selected_language = languages[int(choice)]\n translator.set_language(selected_language)\n \n # Save selected language to config\n config = get_config()\n if config and config.has_section('Language'):\n config.set('Language', 'current_language', selected_language)\n \n # Get config path from user documents\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\")\n config_file = os.path.join(config_dir, \"config.ini\")\n \n # Write updated config\n with open(config_file, 'w', encoding='utf-8') as f:\n config.write(f)\n \n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('menu.language_config_saved', language=translator.get(f'languages.{selected_language}', fallback=selected_language))}{Style.RESET_ALL}\")\n \n return True\n else:\n # Show invalid choice message with the correct range\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('menu.lang_invalid_choice', lang_choices=f'0-{languages_count-1}')}{Style.RESET_ALL}\")\n return False\n except (ValueError, IndexError) as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('menu.lang_invalid_choice', lang_choices=f'0-{languages_count-1}')}{Style.RESET_ALL}\")\n return False\n\ndef check_latest_version():\n \"\"\"Check if current version matches the latest release version\"\"\"\n try:\n print(f\"\\n{Fore.CYAN}{EMOJI['UPDATE']} {translator.get('updater.checking')}{Style.RESET_ALL}\")\n \n # First try GitHub API\n headers = {\n 'Accept': 'application/vnd.github.v3+json',\n 'User-Agent': 'CursorFreeVIP-Updater'\n }\n \n latest_version = None\n github_error = None\n \n # Try GitHub API first\n try:\n github_response = requests.get(\n \"https://api.github.com/repos/yeongpin/cursor-free-vip/releases/latest\",\n headers=headers,\n timeout=10\n )\n \n # Check if rate limit exceeded\n if github_response.status_code == 403 and \"rate limit exceeded\" in github_response.text.lower():\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.rate_limit_exceeded', fallback='GitHub API rate limit exceeded. Trying backup API...')}{Style.RESET_ALL}\")\n raise Exception(\"Rate limit exceeded\")\n \n # Check if response is successful\n if github_response.status_code != 200:\n raise Exception(f\"GitHub API returned status code {github_response.status_code}\")\n \n github_data = github_response.json()\n if \"tag_name\" not in github_data:\n raise Exception(\"No version tag found in GitHub response\")\n \n latest_version = github_data[\"tag_name\"].lstrip('v')\n \n except Exception as e:\n github_error = str(e)\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.github_api_failed', fallback='GitHub API failed, trying backup API...')}{Style.RESET_ALL}\")\n \n # If GitHub API fails, try backup API\n try:\n backup_headers = {\n 'Accept': 'application/json',\n 'User-Agent': 'CursorFreeVIP-Updater'\n }\n backup_response = requests.get(\n \"https://pinnumber.rr.nu/badges/release/yeongpin/cursor-free-vip\",\n headers=backup_headers,\n timeout=10\n )\n \n # Check if response is successful\n if backup_response.status_code != 200:\n raise Exception(f\"Backup API returned status code {backup_response.status_code}\")\n \n backup_data = backup_response.json()\n if \"message\" not in backup_data:\n raise Exception(\"No version tag found in backup API response\")\n \n latest_version = backup_data[\"message\"].lstrip('v')\n \n except Exception as backup_e:\n # If both APIs fail, raise the original GitHub error\n raise Exception(f\"Both APIs failed. GitHub error: {github_error}, Backup error: {str(backup_e)}\")\n \n # Validate version format\n if not latest_version:\n raise Exception(\"Invalid version format received\")\n \n # Parse versions for proper comparison\n def parse_version(version_str):\n \"\"\"Parse version string into tuple for proper comparison\"\"\"\n try:\n return tuple(map(int, version_str.split('.')))\n except ValueError:\n # Fallback to string comparison if parsing fails\n return version_str\n \n current_version_tuple = parse_version(version)\n latest_version_tuple = parse_version(latest_version)\n \n # Compare versions properly\n is_newer_version_available = False\n if isinstance(current_version_tuple, tuple) and isinstance(latest_version_tuple, tuple):\n is_newer_version_available = current_version_tuple < latest_version_tuple\n else:\n # Fallback to string comparison\n is_newer_version_available = version != latest_version\n \n if is_newer_version_available:\n print(f\"\\n{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.new_version_available', current=version, latest=latest_version)}{Style.RESET_ALL}\")\n \n # get and show changelog\n try:\n changelog_url = \"https://raw.githubusercontent.com/yeongpin/cursor-free-vip/main/CHANGELOG.md\"\n changelog_response = requests.get(changelog_url, timeout=10)\n \n if changelog_response.status_code == 200:\n changelog_content = changelog_response.text\n \n # get latest version changelog\n latest_version_pattern = f\"## v{latest_version}\"\n changelog_sections = changelog_content.split(\"## v\")\n \n latest_changes = None\n for section in changelog_sections:\n if section.startswith(latest_version):\n latest_changes = section\n break\n \n if latest_changes:\n print(f\"\\n{Fore.CYAN}{'─' * 40}{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{translator.get('updater.changelog_title')}:{Style.RESET_ALL}\")\n \n # show changelog content (max 10 lines)\n changes_lines = latest_changes.strip().split('\\n')\n for i, line in enumerate(changes_lines[1:11]): # skip version number line, max 10 lines\n if line.strip():\n print(f\"{Fore.WHITE}{line.strip()}{Style.RESET_ALL}\")\n \n # if changelog more than 10 lines, show ellipsis\n if len(changes_lines) > 11:\n print(f\"{Fore.WHITE}...{Style.RESET_ALL}\")\n \n print(f\"{Fore.CYAN}{'─' * 40}{Style.RESET_ALL}\")\n except Exception as changelog_error:\n # get changelog failed\n pass\n \n # Ask user if they want to update\n while True:\n choice = input(f\"\\n{EMOJI['ARROW']} {Fore.CYAN}{translator.get('updater.update_confirm', choices='Y/n')}: {Style.RESET_ALL}\").lower()\n if choice in ['', 'y', 'yes']:\n break\n elif choice in ['n', 'no']:\n print(f\"\\n{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.update_skipped')}{Style.RESET_ALL}\")\n return\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('menu.invalid_choice')}{Style.RESET_ALL}\")\n \n try:\n # Execute update command based on platform\n if platform.system() == 'Windows':\n update_command = 'irm https://raw.githubusercontent.com/yeongpin/cursor-free-vip/main/scripts/install.ps1 | iex'\n subprocess.run(['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', update_command], check=True)\n else:\n # For Linux/Mac, download and execute the install script\n install_script_url = 'https://raw.githubusercontent.com/yeongpin/cursor-free-vip/main/scripts/install.sh'\n \n # First verify the script exists\n script_response = requests.get(install_script_url, timeout=5)\n if script_response.status_code != 200:\n raise Exception(\"Installation script not found\")\n \n # Save and execute the script\n with open('install.sh', 'wb') as f:\n f.write(script_response.content)\n \n os.chmod('install.sh', 0o755) # Make executable\n subprocess.run(['./install.sh'], check=True)\n \n # Clean up\n if os.path.exists('install.sh'):\n os.remove('install.sh')\n \n print(f\"\\n{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('updater.updating')}{Style.RESET_ALL}\")\n sys.exit(0)\n \n except Exception as update_error:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('updater.update_failed', error=str(update_error))}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.manual_update_required')}{Style.RESET_ALL}\")\n return\n else:\n # If current version is newer or equal to latest version\n if current_version_tuple > latest_version_tuple:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('updater.development_version', current=version, latest=latest_version)}{Style.RESET_ALL}\")\n else:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('updater.up_to_date')}{Style.RESET_ALL}\")\n \n except requests.exceptions.RequestException as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('updater.network_error', error=str(e))}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.continue_anyway')}{Style.RESET_ALL}\")\n return\n \n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('updater.check_failed', error=str(e))}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('updater.continue_anyway')}{Style.RESET_ALL}\")\n return\n\ndef main():\n # Check for admin privileges if running as executable on Windows only\n if platform.system() == 'Windows' and is_frozen() and not is_admin():\n print(f\"{Fore.YELLOW}{EMOJI['ADMIN']} {translator.get('menu.admin_required')}{Style.RESET_ALL}\")\n if run_as_admin():\n sys.exit(0) # Exit after requesting admin privileges\n else:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('menu.admin_required_continue')}{Style.RESET_ALL}\")\n \n print_logo()\n \n # Initialize configuration\n config = get_config(translator)\n if not config:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('menu.config_init_failed')}{Style.RESET_ALL}\")\n return\n force_update_config(translator)\n\n if config.getboolean('Utils', 'enabled_update_check'):\n check_latest_version() # Add version check before showing menu\n print_menu()\n \n while True:\n try:\n choice_num = 17\n choice = input(f\"\\n{EMOJI['ARROW']} {Fore.CYAN}{translator.get('menu.input_choice', choices=f'0-{choice_num}')}: {Style.RESET_ALL}\")\n\n match choice:\n case \"0\":\n print(f\"\\n{Fore.YELLOW}{EMOJI['INFO']} {translator.get('menu.exit')}...{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{'═' * 50}{Style.RESET_ALL}\")\n return\n case \"1\":\n import reset_machine_manual\n reset_machine_manual.run(translator)\n print_menu() \n case \"2\":\n import cursor_register_manual\n cursor_register_manual.main(translator)\n print_menu() \n case \"3\":\n import quit_cursor\n quit_cursor.quit_cursor(translator)\n print_menu()\n case \"4\":\n if select_language():\n print_menu()\n continue\n case \"5\":\n from oauth_auth import main as oauth_main\n oauth_main('google',translator)\n print_menu()\n case \"6\":\n from oauth_auth import main as oauth_main\n oauth_main('github',translator)\n print_menu()\n case \"7\":\n import disable_auto_update\n disable_auto_update.run(translator)\n print_menu()\n case \"8\":\n import totally_reset_cursor\n totally_reset_cursor.run(translator)\n # print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('menu.fixed_soon')}{Style.RESET_ALL}\")\n print_menu()\n case \"9\":\n import logo\n print(logo.CURSOR_CONTRIBUTORS)\n print_menu()\n case \"10\":\n from config import print_config\n print_config(get_config(), translator)\n print_menu()\n case \"11\":\n import bypass_version\n bypass_version.main(translator)\n print_menu()\n case \"12\":\n import check_user_authorized\n check_user_authorized.main(translator)\n print_menu()\n case \"13\":\n import bypass_token_limit\n bypass_token_limit.run(translator)\n print_menu()\n case \"14\":\n import restore_machine_id\n restore_machine_id.run(translator)\n print_menu()\n case \"15\":\n import delete_cursor_google\n delete_cursor_google.main(translator)\n print_menu()\n case \"16\":\n from oauth_auth import OAuthHandler\n oauth = OAuthHandler(translator)\n oauth._select_profile()\n print_menu()\n case \"17\":\n import manual_custom_auth\n manual_custom_auth.main(translator)\n print_menu()\n case _:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('menu.invalid_choice')}{Style.RESET_ALL}\")\n print_menu()\n\n except KeyboardInterrupt:\n print(f\"\\n{Fore.YELLOW}{EMOJI['INFO']} {translator.get('menu.program_terminated')}{Style.RESET_ALL}\")\n print(f\"{Fore.CYAN}{'═' * 50}{Style.RESET_ALL}\")\n return\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('menu.error_occurred', error=str(e))}{Style.RESET_ALL}\")\n print_menu()\n\nif __name__ == \"__main__\":\n main()"], ["/cursor-free-vip/email_tabs/tempmail_plus_tab.py", "import requests\nimport re\nimport datetime\nimport time\nfrom typing import Optional\nfrom .email_tab_interface import EmailTabInterface\n\nclass TempMailPlusTab(EmailTabInterface):\n \"\"\"Implementation of EmailTabInterface for tempmail.plus\"\"\"\n \n def __init__(self, email: str, epin: str, translator=None, \n polling_interval: int = 2, max_attempts: int = 10):\n \"\"\"Initialize TempMailPlusTab\n \n Args:\n email: The email address to check\n epin: The epin token for authentication\n translator: Optional translator for internationalization\n polling_interval: Time in seconds between polling attempts\n max_attempts: Maximum number of polling attempts\n \"\"\"\n self.email = email\n self.epin = epin\n self.translator = translator\n self.base_url = \"https://tempmail.plus/api\"\n self.headers = {\n 'accept': 'application/json',\n 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',\n 'cache-control': 'no-cache',\n 'pragma': 'no-cache',\n 'referer': 'https://tempmail.plus/zh/',\n 'sec-ch-ua': '\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': '\"macOS\"',\n 'sec-fetch-dest': 'empty',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-site': 'same-origin',\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',\n 'x-requested-with': 'XMLHttpRequest'\n }\n self.cookies = {'email': email}\n self._cached_mail_id = None # Cache for mail_id\n self._cached_verification_code = None # Cache for verification code\n \n # Polling configuration\n self.polling_interval = polling_interval\n self.max_attempts = max_attempts\n self.current_attempt = 0\n \n def refresh_inbox(self) -> None:\n \"\"\"Refresh the email inbox\"\"\"\n pass\n \n def check_for_cursor_email(self) -> bool:\n \"\"\"Check if there is a new email and immediately retrieve verification code\n \n Returns:\n bool: True if new email found and verification code retrieved, False otherwise\n \"\"\"\n # Reset attempt counter\n self.current_attempt = 0\n \n # Polling logic\n while self.current_attempt < self.max_attempts:\n found = self._check_email_once()\n if found:\n # Successfully found email and retrieved verification code\n self.current_attempt = 0 # Reset counter for next use\n return True\n \n # Not found, continue polling\n self.current_attempt += 1\n if self.current_attempt < self.max_attempts:\n # Print polling status information\n if self.translator:\n print(self.translator.get('tempmail.polling', \n attempt=self.current_attempt, \n max=self.max_attempts))\n else:\n print(f\"Polling for email: attempt {self.current_attempt}/{self.max_attempts}\")\n time.sleep(self.polling_interval)\n \n # Exceeded maximum attempts\n if self.translator:\n print(self.translator.get('tempmail.max_attempts_reached'))\n else:\n print(f\"Max attempts ({self.max_attempts}) reached. No verification email found.\")\n return False\n \n def _check_email_once(self) -> bool:\n \"\"\"Single attempt to check for email\n \n Returns:\n bool: True if new email found and verification code retrieved, False otherwise\n \"\"\"\n try:\n params = {\n 'email': self.email,\n 'epin': self.epin\n }\n response = requests.get(\n f\"{self.base_url}/mails\",\n params=params,\n headers=self.headers,\n cookies=self.cookies\n )\n response.raise_for_status()\n \n data = response.json()\n if data.get('result') and data.get('mail_list'):\n # Check if the first email in the list is a new email\n if data['mail_list'][0].get('is_new') == True:\n self._cached_mail_id = data['mail_list'][0].get('mail_id') # Cache the mail_id\n \n # Immediately retrieve verification code\n verification_code = self._extract_verification_code()\n if verification_code:\n self._cached_verification_code = verification_code\n return True\n return False\n except Exception as e:\n print(f\"{self.translator.get('tempmail.check_email_failed', error=str(e)) if self.translator else f'Check email failed: {str(e)}'}\")\n return False\n \n def _extract_verification_code(self) -> str:\n \"\"\"Extract verification code from email content\n \n Returns:\n str: The verification code if found, empty string otherwise\n \"\"\"\n try:\n if not self._cached_mail_id:\n return \"\"\n \n params = {\n 'email': self.email,\n 'epin': self.epin\n }\n response = requests.get(\n f\"{self.base_url}/mails/{self._cached_mail_id}\",\n params=params,\n headers=self.headers,\n cookies=self.cookies\n )\n response.raise_for_status()\n \n data = response.json()\n if not data.get('result'):\n return \"\"\n \n # Verify if sender email contains cursor string\n from_mail = data.get('from_mail', '')\n if 'cursor' not in from_mail.lower():\n return \"\"\n \n # Extract verification code from text content using regex\n text = data.get('text', '')\n match = re.search(r'\\n\\n(\\d{6})\\n\\n', text)\n if match:\n return match.group(1)\n \n return \"\"\n except Exception as e:\n print(f\"{self.translator.get('tempmail.extract_code_failed', error=str(e)) if self.translator else f'Extract verification code failed: {str(e)}'}\")\n return \"\"\n \n def get_verification_code(self) -> str:\n \"\"\"Get the verification code from cache\n \n Returns:\n str: The cached verification code if available, empty string otherwise\n \"\"\"\n return self._cached_verification_code or \"\"\n\nif __name__ == \"__main__\":\n import os\n import sys\n import configparser\n \n from config import get_config\n \n # Try to import translator\n try:\n from main import Translator\n translator = Translator()\n except ImportError:\n translator = None\n \n config = get_config(translator)\n \n try:\n email = config.get('TempMailPlus', 'email')\n epin = config.get('TempMailPlus', 'epin')\n \n print(f\"{translator.get('tempmail.configured_email', email=email) if translator else f'Configured email: {email}'}\")\n \n # Initialize TempMailPlusTab, pass translator\n mail_tab = TempMailPlusTab(email, epin, translator)\n \n # Check if there is a Cursor email\n print(f\"{translator.get('tempmail.checking_email') if translator else 'Checking for Cursor verification email...'}\")\n if mail_tab.check_for_cursor_email():\n print(f\"{translator.get('tempmail.email_found') if translator else 'Found Cursor verification email'}\")\n \n # Get verification code\n verification_code = mail_tab.get_verification_code()\n if verification_code:\n print(f\"{translator.get('tempmail.verification_code', code=verification_code) if translator else f'Verification code: {verification_code}'}\")\n else:\n print(f\"{translator.get('tempmail.no_code') if translator else 'Could not get verification code'}\")\n else:\n print(f\"{translator.get('tempmail.no_email') if translator else 'No Cursor verification email found'}\")\n \n except configparser.Error as e:\n print(f\"{translator.get('tempmail.config_error', error=str(e)) if translator else f'Config file error: {str(e)}'}\")\n except Exception as e:\n print(f\"{translator.get('tempmail.general_error', error=str(e)) if translator else f'An error occurred: {str(e)}'}\") "], ["/cursor-free-vip/reset_machine_manual.py", "import os\nimport sys\nimport json\nimport uuid\nimport hashlib\nimport shutil\nimport sqlite3\nimport platform\nimport re\nimport tempfile\nimport glob\nfrom colorama import Fore, Style, init\nfrom typing import Tuple\nimport configparser\nimport traceback\nfrom config import get_config\nfrom datetime import datetime\n\n# Initialize colorama\ninit()\n\n# Define emoji constants\nEMOJI = {\n \"FILE\": \"📄\",\n \"BACKUP\": \"💾\",\n \"SUCCESS\": \"✅\",\n \"ERROR\": \"❌\",\n \"INFO\": \"ℹ️\",\n \"RESET\": \"🔄\",\n \"WARNING\": \"⚠️\",\n}\n\ndef get_user_documents_path():\n \"\"\"Get user Documents folder path\"\"\"\n if sys.platform == \"win32\":\n try:\n import winreg\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Shell Folders\") as key:\n documents_path, _ = winreg.QueryValueEx(key, \"Personal\")\n return documents_path\n except Exception as e:\n # fallback\n return os.path.join(os.path.expanduser(\"~\"), \"Documents\")\n elif sys.platform == \"darwin\":\n return os.path.join(os.path.expanduser(\"~\"), \"Documents\")\n else: # Linux\n # Get actual user's home directory\n sudo_user = os.environ.get('SUDO_USER')\n if sudo_user:\n return os.path.join(\"/home\", sudo_user, \"Documents\")\n return os.path.join(os.path.expanduser(\"~\"), \"Documents\")\n \n\ndef get_cursor_paths(translator=None) -> Tuple[str, str]:\n \"\"\" Get Cursor related paths\"\"\"\n system = platform.system()\n \n # Read config file\n config = configparser.ConfigParser()\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\")\n config_file = os.path.join(config_dir, \"config.ini\")\n \n # Create config directory if it doesn't exist\n if not os.path.exists(config_dir):\n os.makedirs(config_dir)\n \n # Default paths for different systems\n default_paths = {\n \"Darwin\": \"/Applications/Cursor.app/Contents/Resources/app\",\n \"Windows\": os.path.join(os.getenv(\"LOCALAPPDATA\", \"\"), \"Programs\", \"Cursor\", \"resources\", \"app\"),\n \"Linux\": [\"/opt/Cursor/resources/app\", \"/usr/share/cursor/resources/app\", os.path.expanduser(\"~/.local/share/cursor/resources/app\"), \"/usr/lib/cursor/app/\"]\n }\n \n if system == \"Linux\":\n # Look for extracted AppImage with correct usr structure\n extracted_usr_paths = glob.glob(os.path.expanduser(\"~/squashfs-root/usr/share/cursor/resources/app\"))\n # Also check current directory for extraction without home path prefix\n current_dir_paths = glob.glob(\"squashfs-root/usr/share/cursor/resources/app\")\n \n # Add any found paths to the Linux paths list\n default_paths[\"Linux\"].extend(extracted_usr_paths)\n default_paths[\"Linux\"].extend(current_dir_paths)\n \n # Print debug information\n print(f\"{Fore.CYAN}{EMOJI['INFO']} Available paths found:{Style.RESET_ALL}\")\n for path in default_paths[\"Linux\"]:\n if os.path.exists(path):\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {path} (exists){Style.RESET_ALL}\")\n else:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {path} (not found){Style.RESET_ALL}\")\n \n \n # If config doesn't exist, create it with default paths\n if not os.path.exists(config_file):\n for section in ['MacPaths', 'WindowsPaths', 'LinuxPaths']:\n if not config.has_section(section):\n config.add_section(section)\n \n if system == \"Darwin\":\n config.set('MacPaths', 'cursor_path', default_paths[\"Darwin\"])\n elif system == \"Windows\":\n config.set('WindowsPaths', 'cursor_path', default_paths[\"Windows\"])\n elif system == \"Linux\":\n # For Linux, try to find the first existing path\n for path in default_paths[\"Linux\"]:\n if os.path.exists(path):\n config.set('LinuxPaths', 'cursor_path', path)\n break\n else:\n # If no path exists, use the first one as default\n config.set('LinuxPaths', 'cursor_path', default_paths[\"Linux\"][0])\n \n with open(config_file, 'w', encoding='utf-8') as f:\n config.write(f)\n else:\n config.read(config_file, encoding='utf-8')\n \n # Get path based on system\n if system == \"Darwin\":\n section = 'MacPaths'\n elif system == \"Windows\":\n section = 'WindowsPaths'\n elif system == \"Linux\":\n section = 'LinuxPaths'\n else:\n raise OSError(translator.get('reset.unsupported_os', system=system) if translator else f\"不支持的操作系统: {system}\")\n \n if not config.has_section(section) or not config.has_option(section, 'cursor_path'):\n raise OSError(translator.get('reset.path_not_configured') if translator else \"未配置 Cursor 路徑\")\n \n base_path = config.get(section, 'cursor_path')\n \n # For Linux, try to find the first existing path if the configured one doesn't exist\n if system == \"Linux\" and not os.path.exists(base_path):\n for path in default_paths[\"Linux\"]:\n if os.path.exists(path):\n base_path = path\n # Update config with the found path\n config.set(section, 'cursor_path', path)\n with open(config_file, 'w', encoding='utf-8') as f:\n config.write(f)\n break\n \n if not os.path.exists(base_path):\n raise OSError(translator.get('reset.path_not_found', path=base_path) if translator else f\"找不到 Cursor 路徑: {base_path}\")\n \n pkg_path = os.path.join(base_path, \"package.json\")\n main_path = os.path.join(base_path, \"out/main.js\")\n \n # Check if files exist\n if not os.path.exists(pkg_path):\n raise OSError(translator.get('reset.package_not_found', path=pkg_path) if translator else f\"找不到 package.json: {pkg_path}\")\n if not os.path.exists(main_path):\n raise OSError(translator.get('reset.main_not_found', path=main_path) if translator else f\"找不到 main.js: {main_path}\")\n \n return (pkg_path, main_path)\n\ndef get_cursor_machine_id_path(translator=None) -> str:\n \"\"\"\n Get Cursor machineId file path based on operating system\n Returns:\n str: Path to machineId file\n \"\"\"\n # Read configuration\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\")\n config_file = os.path.join(config_dir, \"config.ini\")\n config = configparser.ConfigParser()\n \n if os.path.exists(config_file):\n config.read(config_file)\n \n if sys.platform == \"win32\": # Windows\n if not config.has_section('WindowsPaths'):\n config.add_section('WindowsPaths')\n config.set('WindowsPaths', 'machine_id_path', \n os.path.join(os.getenv(\"APPDATA\"), \"Cursor\", \"machineId\"))\n return config.get('WindowsPaths', 'machine_id_path')\n \n elif sys.platform == \"linux\": # Linux\n if not config.has_section('LinuxPaths'):\n config.add_section('LinuxPaths')\n config.set('LinuxPaths', 'machine_id_path',\n os.path.expanduser(\"~/.config/cursor/machineid\"))\n return config.get('LinuxPaths', 'machine_id_path')\n \n elif sys.platform == \"darwin\": # macOS\n if not config.has_section('MacPaths'):\n config.add_section('MacPaths')\n config.set('MacPaths', 'machine_id_path',\n os.path.expanduser(\"~/Library/Application Support/Cursor/machineId\"))\n return config.get('MacPaths', 'machine_id_path')\n \n else:\n raise OSError(f\"Unsupported operating system: {sys.platform}\")\n\n # Save any changes to config file\n with open(config_file, 'w', encoding='utf-8') as f:\n config.write(f)\n\ndef get_workbench_cursor_path(translator=None) -> str:\n \"\"\"Get Cursor workbench.desktop.main.js path\"\"\"\n system = platform.system()\n\n # Read configuration\n config_dir = os.path.join(get_user_documents_path(), \".cursor-free-vip\")\n config_file = os.path.join(config_dir, \"config.ini\")\n config = configparser.ConfigParser()\n\n if os.path.exists(config_file):\n config.read(config_file)\n \n paths_map = {\n \"Darwin\": { # macOS\n \"base\": \"/Applications/Cursor.app/Contents/Resources/app\",\n \"main\": \"out/vs/workbench/workbench.desktop.main.js\"\n },\n \"Windows\": {\n \"main\": \"out\\\\vs\\\\workbench\\\\workbench.desktop.main.js\"\n },\n \"Linux\": {\n \"bases\": [\"/opt/Cursor/resources/app\", \"/usr/share/cursor/resources/app\", \"/usr/lib/cursor/app/\"],\n \"main\": \"out/vs/workbench/workbench.desktop.main.js\"\n }\n }\n \n if system == \"Linux\":\n # Add extracted AppImage with correct usr structure\n extracted_usr_paths = glob.glob(os.path.expanduser(\"~/squashfs-root/usr/share/cursor/resources/app\"))\n \n paths_map[\"Linux\"][\"bases\"].extend(extracted_usr_paths)\n\n if system not in paths_map:\n raise OSError(translator.get('reset.unsupported_os', system=system) if translator else f\"不支持的操作系统: {system}\")\n\n if system == \"Linux\":\n for base in paths_map[\"Linux\"][\"bases\"]:\n main_path = os.path.join(base, paths_map[\"Linux\"][\"main\"])\n print(f\"{Fore.CYAN}{EMOJI['INFO']} Checking path: {main_path}{Style.RESET_ALL}\")\n if os.path.exists(main_path):\n return main_path\n\n if system == \"Windows\":\n base_path = config.get('WindowsPaths', 'cursor_path')\n elif system == \"Darwin\":\n base_path = paths_map[system][\"base\"]\n if config.has_section('MacPaths') and config.has_option('MacPaths', 'cursor_path'):\n base_path = config.get('MacPaths', 'cursor_path')\n else: # Linux\n # For Linux, we've already checked all bases in the loop above\n # If we're here, it means none of the bases worked, so we'll use the first one\n base_path = paths_map[system][\"bases\"][0]\n if config.has_section('LinuxPaths') and config.has_option('LinuxPaths', 'cursor_path'):\n base_path = config.get('LinuxPaths', 'cursor_path')\n\n main_path = os.path.join(base_path, paths_map[system][\"main\"])\n \n if not os.path.exists(main_path):\n raise OSError(translator.get('reset.file_not_found', path=main_path) if translator else f\"未找到 Cursor main.js 文件: {main_path}\")\n \n return main_path\n\ndef version_check(version: str, min_version: str = \"\", max_version: str = \"\", translator=None) -> bool:\n \"\"\"Version number check\"\"\"\n version_pattern = r\"^\\d+\\.\\d+\\.\\d+$\"\n try:\n if not re.match(version_pattern, version):\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.invalid_version_format', version=version)}{Style.RESET_ALL}\")\n return False\n\n def parse_version(ver: str) -> Tuple[int, ...]:\n return tuple(map(int, ver.split(\".\")))\n\n current = parse_version(version)\n\n if min_version and current < parse_version(min_version):\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.version_too_low', version=version, min_version=min_version)}{Style.RESET_ALL}\")\n return False\n\n if max_version and current > parse_version(max_version):\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.version_too_high', version=version, max_version=max_version)}{Style.RESET_ALL}\")\n return False\n\n return True\n\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.version_check_error', error=str(e))}{Style.RESET_ALL}\")\n return False\n\ndef check_cursor_version(translator) -> bool:\n \"\"\"Check Cursor version\"\"\"\n try:\n pkg_path, _ = get_cursor_paths(translator)\n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('reset.reading_package_json', path=pkg_path)}{Style.RESET_ALL}\")\n \n try:\n with open(pkg_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n except UnicodeDecodeError:\n # If UTF-8 reading fails, try other encodings\n with open(pkg_path, \"r\", encoding=\"latin-1\") as f:\n data = json.load(f)\n \n if not isinstance(data, dict):\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.invalid_json_object')}{Style.RESET_ALL}\")\n return False\n \n if \"version\" not in data:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.no_version_field')}{Style.RESET_ALL}\")\n return False\n \n version = str(data[\"version\"]).strip()\n if not version:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.version_field_empty')}{Style.RESET_ALL}\")\n return False\n \n print(f\"{Fore.CYAN}{EMOJI['INFO']} {translator.get('reset.found_version', version=version)}{Style.RESET_ALL}\")\n \n # Check version format\n if not re.match(r\"^\\d+\\.\\d+\\.\\d+$\", version):\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.invalid_version_format', version=version)}{Style.RESET_ALL}\")\n return False\n \n # Compare versions\n try:\n current = tuple(map(int, version.split(\".\")))\n min_ver = (0, 45, 0) # Use tuple directly instead of string\n \n if current >= min_ver:\n print(f\"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('reset.version_check_passed', version=version, min_version='0.45.0')}{Style.RESET_ALL}\")\n return True\n else:\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('reset.version_too_low', version=version, min_version='0.45.0')}{Style.RESET_ALL}\")\n return False\n except ValueError as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.version_parse_error', error=str(e))}{Style.RESET_ALL}\")\n return False\n \n except FileNotFoundError as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.package_not_found', path=pkg_path)}{Style.RESET_ALL}\")\n return False\n except json.JSONDecodeError as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.invalid_json_object')}{Style.RESET_ALL}\")\n return False\n except Exception as e:\n print(f\"{Fore.RED}{EMOJI['ERROR']} {translator.get('reset.check_version_failed', error=str(e))}{Style.RESET_ALL}\")\n print(f\"{Fore.YELLOW}{EMOJI['INFO']} {translator.get('reset.stack_trace')}: {traceback.format_exc()}{Style.RESET_ALL}\")\n return False\n\ndef modify_workbench_js(file_path: str, translator=None) -> bool:\n \"\"\"\n Modify file content\n \"\"\"\n try:\n # Save original file permissions\n original_stat = os.stat(file_path)\n original_mode = original_stat.st_mode\n original_uid = original_stat.st_uid\n original_gid = original_stat.st_gid\n\n # Create temporary file\n with tempfile.NamedTemporaryFile(mode=\"w\", encoding=\"utf-8\", errors=\"ignore\", delete=False) as tmp_file:\n # Read original content\n with open(file_path, \"r\", encoding=\"utf-8\", errors=\"ignore\") as main_file:\n content = main_file.read()\n\n patterns = {\n # 通用按钮替换模式\n r'B(k,D(Ln,{title:\"Upgrade to Pro\",size:\"small\",get codicon(){return A.rocket},get onClick(){return t.pay}}),null)': r'B(k,D(Ln,{title:\"yeongpin GitHub\",size:\"small\",get codicon(){return A.github},get onClick(){return function(){window.open(\"https://github.com/yeongpin/cursor-free-vip\",\"_blank\")}}}),null)',\n \n # Windows/Linux/Mac 通用按钮替换模式\n r'M(x,I(as,{title:\"Upgrade to Pro\",size:\"small\",get codicon(){return $.rocket},get onClick(){return t.pay}}),null)': r'M(x,I(as,{title:\"yeongpin GitHub\",size:\"small\",get codicon(){return $.rocket},get onClick(){return function(){window.open(\"https://github.com/yeongpin/cursor-free-vip\",\"_blank\")}}}),null)',\n \n # Badge 替换\n r'