Compare commits

...

9 Commits

9 changed files with 1031129 additions and 91 deletions

97
account_manager.py Normal file
View File

@ -0,0 +1,97 @@
import os
from colorama import Fore, Style
import re
# Define emoji constants
EMOJI = {
'SUCCESS': '',
'ERROR': '',
'INFO': ''
}
class AccountManager:
def __init__(self, translator=None):
self.translator = translator
self.accounts_file = 'cursor_accounts.txt'
def save_account_info(self, email, password, token, total_usage):
"""Save account information to file"""
try:
with open(self.accounts_file, 'a', encoding='utf-8') as f:
f.write(f"\n{'='*50}\n")
f.write(f"Email: {email}\n")
f.write(f"Password: {password}\n")
f.write(f"Token: {token}\n")
f.write(f"Usage Limit: {total_usage}\n")
f.write(f"{'='*50}\n")
print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('register.account_info_saved') if self.translator else 'Account information saved'}...{Style.RESET_ALL}")
return True
except Exception as e:
error_msg = self.translator.get('register.save_account_info_failed', error=str(e)) if self.translator else f'Failed to save account information: {str(e)}'
print(f"{Fore.RED}{EMOJI['ERROR']} {error_msg}{Style.RESET_ALL}")
return False
def get_last_email_domain(self):
"""Get the domain from the last used email"""
try:
if not os.path.exists(self.accounts_file):
return None
# Only read the last 1KB of data from the file
with open(self.accounts_file, 'rb') as f:
# Get file size
f.seek(0, os.SEEK_END)
file_size = f.tell()
if file_size == 0:
return None
# Determine the number of bytes to read, maximum 1KB
read_size = min(1024, file_size)
# Move to the appropriate position to start reading
f.seek(file_size - read_size)
# Read the end data
data = f.read(read_size).decode('utf-8', errors='ignore')
# Split by lines and search in reverse
lines = data.split('\n')
for line in reversed(lines):
if line.strip().startswith('Email:'):
email = line.split('Email:')[1].strip()
# Extract domain part (after @)
if '@' in email:
return email.split('@')[1]
return None
# If no email is found in the last 1KB
return None
except Exception as e:
error_msg = self.translator.get('account.get_last_email_domain_failed', error=str(e)) if self.translator else f'Failed to get the last used email domain: {str(e)}'
print(f"{Fore.RED}{EMOJI['ERROR']} {error_msg}{Style.RESET_ALL}")
return None
def suggest_email(self, first_name, last_name):
"""Generate a suggested email based on first and last name with the last used domain"""
try:
# Get the last used email domain
domain = self.get_last_email_domain()
if not domain:
return None
# Generate email prefix from first and last name (lowercase)
email_prefix = f"{first_name.lower()}.{last_name.lower()}"
# Combine prefix and domain
suggested_email = f"{email_prefix}@{domain}"
return suggested_email
except Exception as e:
error_msg = self.translator.get('account.suggest_email_failed', error=str(e)) if self.translator else f'Failed to suggest email: {str(e)}'
print(f"{Fore.RED}{EMOJI['ERROR']} {error_msg}{Style.RESET_ALL}")
return None

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -7,6 +7,7 @@ from cursor_auth import CursorAuth
from reset_machine_manual import MachineIDResetter
from get_user_token import get_token_from_cookie
from config import get_config
from account_manager import AccountManager
os.environ["PYTHONVERBOSE"] = "0"
os.environ["PYINSTALLER_VERBOSE"] = "0"
@ -67,11 +68,28 @@ class CursorRegistration:
def setup_email(self):
"""Setup Email"""
try:
# Try to get a suggested email
account_manager = AccountManager(self.translator)
suggested_email = account_manager.suggest_email(self.first_name, self.last_name)
if suggested_email:
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}'}")
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:'}")
user_input = input().strip()
if user_input.lower() == 'yes' or user_input.lower() == 'y':
self.email_address = suggested_email
else:
# User input is their own email address
self.email_address = user_input
else:
# If there's no suggested email
print(f"{Fore.CYAN}{EMOJI['START']} {self.translator.get('register.manual_email_input') if self.translator else 'Please enter your email address:'}")
self.email_address = input().strip()
# Validate if the email is valid
if '@' not in self.email_address:
print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.invalid_email') if self.translator else '无效的邮箱地址'}{Style.RESET_ALL}")
print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.invalid_email') if self.translator else 'Invalid email address'}{Style.RESET_ALL}")
return False
print(f"{Fore.CYAN}{EMOJI['MAIL']} {self.translator.get('register.email_address')}: {self.email_address}" + "\n" + f"{Style.RESET_ALL}")
@ -88,7 +106,7 @@ class CursorRegistration:
code = input().strip()
if not code.isdigit() or len(code) != 6:
print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.invalid_code') if self.translator else '无效的验证码'}{Style.RESET_ALL}")
print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.invalid_code') if self.translator else 'Invalid verification code'}{Style.RESET_ALL}")
return None
return code
@ -224,17 +242,12 @@ class CursorRegistration:
if not resetter.reset_machine_ids(): # Call reset_machine_ids method directly
raise Exception("Failed to reset machine ID")
# Save account information to file
with open('cursor_accounts.txt', 'a', encoding='utf-8') as f:
f.write(f"\n{'='*50}\n")
f.write(f"Email: {self.email_address}\n")
f.write(f"Password: {self.password}\n")
f.write(f"Token: {token}\n")
f.write(f"Usage Limit: {total_usage}\n")
f.write(f"{'='*50}\n")
print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('register.account_info_saved')}...{Style.RESET_ALL}")
# Save account information to file using AccountManager
account_manager = AccountManager(self.translator)
if account_manager.save_account_info(self.email_address, self.password, token, total_usage):
return True
else:
return False
except Exception as e:
print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('register.save_account_info_failed', error=str(e))}{Style.RESET_ALL}")

View File

@ -1,19 +1,23 @@
import requests
import re
import datetime
import time
from typing import Optional
from .email_tab_interface import EmailTabInterface
class TempMailPlusTab(EmailTabInterface):
"""Implementation of EmailTabInterface for tempmail.plus"""
def __init__(self, email: str, epin: str, translator=None):
def __init__(self, email: str, epin: str, translator=None,
polling_interval: int = 2, max_attempts: int = 10):
"""Initialize TempMailPlusTab
Args:
email: The email address to check
epin: The epin token for authentication
translator: Optional translator for internationalization
polling_interval: Time in seconds between polling attempts
max_attempts: Maximum number of polling attempts
"""
self.email = email
self.epin = epin
@ -35,8 +39,13 @@ class TempMailPlusTab(EmailTabInterface):
'x-requested-with': 'XMLHttpRequest'
}
self.cookies = {'email': email}
self._cached_mail_id = None # 缓存mail_id
self._cached_verification_code = None # 缓存验证码
self._cached_mail_id = None # Cache for mail_id
self._cached_verification_code = None # Cache for verification code
# Polling configuration
self.polling_interval = polling_interval
self.max_attempts = max_attempts
self.current_attempt = 0
def refresh_inbox(self) -> None:
"""Refresh the email inbox"""
@ -45,6 +54,42 @@ class TempMailPlusTab(EmailTabInterface):
def check_for_cursor_email(self) -> bool:
"""Check if there is a new email and immediately retrieve verification code
Returns:
bool: True if new email found and verification code retrieved, False otherwise
"""
# Reset attempt counter
self.current_attempt = 0
# Polling logic
while self.current_attempt < self.max_attempts:
found = self._check_email_once()
if found:
# Successfully found email and retrieved verification code
self.current_attempt = 0 # Reset counter for next use
return True
# Not found, continue polling
self.current_attempt += 1
if self.current_attempt < self.max_attempts:
# Print polling status information
if self.translator:
print(self.translator.get('tempmail.polling',
attempt=self.current_attempt,
max=self.max_attempts))
else:
print(f"Polling for email: attempt {self.current_attempt}/{self.max_attempts}")
time.sleep(self.polling_interval)
# Exceeded maximum attempts
if self.translator:
print(self.translator.get('tempmail.max_attempts_reached'))
else:
print(f"Max attempts ({self.max_attempts}) reached. No verification email found.")
return False
def _check_email_once(self) -> bool:
"""Single attempt to check for email
Returns:
bool: True if new email found and verification code retrieved, False otherwise
"""
@ -63,11 +108,11 @@ class TempMailPlusTab(EmailTabInterface):
data = response.json()
if data.get('result') and data.get('mail_list'):
# 检查邮件列表中的第一个邮件是否为新邮件
# Check if the first email in the list is a new email
if data['mail_list'][0].get('is_new') == True:
self._cached_mail_id = data['mail_list'][0].get('mail_id') # 缓存mail_id
self._cached_mail_id = data['mail_list'][0].get('mail_id') # Cache the mail_id
# 立即获取验证码
# Immediately retrieve verification code
verification_code = self._extract_verification_code()
if verification_code:
self._cached_verification_code = verification_code
@ -103,7 +148,7 @@ class TempMailPlusTab(EmailTabInterface):
if not data.get('result'):
return ""
# 验证发件人邮箱是否包含cursor字符串
# Verify if sender email contains cursor string
from_mail = data.get('from_mail', '')
if 'cursor' not in from_mail.lower():
return ""
@ -129,13 +174,12 @@ class TempMailPlusTab(EmailTabInterface):
if __name__ == "__main__":
import os
import time
import sys
import configparser
from config import get_config
# 尝试导入 translator
# Try to import translator
try:
from main import Translator
translator = Translator()
@ -150,15 +194,15 @@ if __name__ == "__main__":
print(f"{translator.get('tempmail.configured_email', email=email) if translator else f'Configured email: {email}'}")
# 初始化TempMailPlusTab传递 translator
# Initialize TempMailPlusTab, pass translator
mail_tab = TempMailPlusTab(email, epin, translator)
# 检查是否有Cursor的邮件
# Check if there is a Cursor email
print(f"{translator.get('tempmail.checking_email') if translator else 'Checking for Cursor verification email...'}")
if mail_tab.check_for_cursor_email():
print(f"{translator.get('tempmail.email_found') if translator else 'Found Cursor verification email'}")
# 获取验证码
# Get verification code
verification_code = mail_tab.get_verification_code()
if verification_code:
print(f"{translator.get('tempmail.verification_code', code=verification_code) if translator else f'Verification code: {verification_code}'}")

View File

@ -191,6 +191,8 @@
"setting_password": "Setting Password",
"manual_code_input": "Manual Code Input",
"manual_email_input": "Manual Email Input",
"suggest_email": "Suggested email: {suggested_email}",
"use_suggested_email_or_enter": "Type \"yes\" to use this email or enter your own email:",
"password": "Password",
"first_name": "First Name",
"last_name": "Last Name",

View File

@ -191,6 +191,8 @@
"setting_password": "设置密码",
"manual_code_input": "手动输入验证码",
"manual_email_input": "手动输入邮箱",
"suggest_email": "推荐邮箱地址: {suggested_email}",
"use_suggested_email_or_enter": "输入\"yes\"使用此邮箱或直接输入您想使用的邮箱地址:",
"password": "密码",
"first_name": "名字",
"last_name": "姓氏",

View File

@ -188,6 +188,8 @@
"setting_password": "設置密碼",
"manual_code_input": "手動輸入驗證碼",
"manual_email_input": "手動輸入郵箱地址",
"suggest_email": "推薦郵箱地址: {suggested_email}",
"use_suggested_email_or_enter": "輸入\"yes\"使用此郵箱或直接輸入您想使用的郵箱地址:",
"password": "密碼",
"first_name": "名字",
"last_name": "姓氏",

View File

@ -125,75 +125,61 @@ function Install-CursorFreeVIP {
Write-Styled "No existing installation file found, starting download..." -Color $Theme.Primary -Prefix "Download"
# Create WebClient and add progress event
$webClient = New-Object System.Net.WebClient
$webClient.Headers.Add("User-Agent", "PowerShell Script")
# Use HttpWebRequest for chunked download with real-time progress bar
$url = $asset.browser_download_url
$outputFile = $downloadPath
Write-Styled "Downloading from: $url" -Color $Theme.Info -Prefix "URL"
Write-Styled "Saving to: $outputFile" -Color $Theme.Info -Prefix "Path"
# Define progress variables
$Global:downloadedBytes = 0
$Global:totalBytes = 0
$Global:lastProgress = 0
$Global:lastBytes = 0
$Global:lastTime = Get-Date
# Download progress event
$eventId = [guid]::NewGuid()
Register-ObjectEvent -InputObject $webClient -EventName DownloadProgressChanged -Action {
$Global:downloadedBytes = $EventArgs.BytesReceived
$Global:totalBytes = $EventArgs.TotalBytesToReceive
$progress = [math]::Round(($Global:downloadedBytes / $Global:totalBytes) * 100, 1)
# Only update display when progress changes by more than 1%
if ($progress -gt $Global:lastProgress + 1) {
$Global:lastProgress = $progress
$downloadedMB = [math]::Round($Global:downloadedBytes / 1MB, 2)
$totalMB = [math]::Round($Global:totalBytes / 1MB, 2)
# Calculate download speed
$currentTime = Get-Date
$timeSpan = ($currentTime - $Global:lastTime).TotalSeconds
if ($timeSpan -gt 0) {
$bytesChange = $Global:downloadedBytes - $Global:lastBytes
$speed = $bytesChange / $timeSpan
# Choose appropriate unit based on speed
$request = [System.Net.HttpWebRequest]::Create($url)
$request.UserAgent = "PowerShell Script"
$response = $request.GetResponse()
$totalLength = $response.ContentLength
$responseStream = $response.GetResponseStream()
$fileStream = [System.IO.File]::OpenWrite($outputFile)
$buffer = New-Object byte[] 8192
$bytesRead = 0
$totalRead = 0
$lastProgress = -1
$startTime = Get-Date
try {
do {
$bytesRead = $responseStream.Read($buffer, 0, $buffer.Length)
if ($bytesRead -gt 0) {
$fileStream.Write($buffer, 0, $bytesRead)
$totalRead += $bytesRead
$progress = [math]::Round(($totalRead / $totalLength) * 100, 1)
if ($progress -ne $lastProgress) {
$elapsed = (Get-Date) - $startTime
$speed = if ($elapsed.TotalSeconds -gt 0) { $totalRead / $elapsed.TotalSeconds } else { 0 }
$speedDisplay = if ($speed -gt 1MB) {
"$([math]::Round($speed / 1MB, 2)) MB/s"
"{0:N2} MB/s" -f ($speed / 1MB)
} elseif ($speed -gt 1KB) {
"$([math]::Round($speed / 1KB, 2)) KB/s"
"{0:N2} KB/s" -f ($speed / 1KB)
} else {
"$([math]::Round($speed, 2)) B/s"
"{0:N2} B/s" -f $speed
}
Write-Host "`rDownloading: $downloadedMB MB / $totalMB MB ($progress%) - $speedDisplay" -NoNewline -ForegroundColor Cyan
# Update last data
$Global:lastBytes = $Global:downloadedBytes
$Global:lastTime = $currentTime
$downloadedMB = [math]::Round($totalRead / 1MB, 2)
$totalMB = [math]::Round($totalLength / 1MB, 2)
Write-Progress -Activity "Downloading CursorFreeVIP" -Status "$downloadedMB MB / $totalMB MB ($progress%) - $speedDisplay" -PercentComplete $progress
$lastProgress = $progress
}
}
} | Out-Null
# Download completed event
Register-ObjectEvent -InputObject $webClient -EventName DownloadFileCompleted -Action {
Write-Host "`r" -NoNewline
} while ($bytesRead -gt 0)
} finally {
$fileStream.Close()
$responseStream.Close()
$response.Close()
}
Write-Progress -Activity "Downloading CursorFreeVIP" -Completed
# Check file exists and is not zero size
if (!(Test-Path $outputFile) -or ((Get-Item $outputFile).Length -eq 0)) {
throw "Download failed or file is empty."
}
Write-Styled "Download completed!" -Color $Theme.Success -Prefix "Complete"
Unregister-Event -SourceIdentifier $eventId
} | Out-Null
# Start download
$webClient.DownloadFileAsync([Uri]$asset.browser_download_url, $downloadPath)
# Wait for download to complete
while ($webClient.IsBusy) {
Start-Sleep -Milliseconds 100
}
Write-Styled "File location: $downloadPath" -Color $Theme.Info -Prefix "Location"
Write-Styled "File location: $outputFile" -Color $Theme.Info -Prefix "Location"
Write-Styled "Starting program..." -Color $Theme.Primary -Prefix "Launch"
# Run program
Start-Process $downloadPath
Start-Process $outputFile
}
catch {
Write-Styled $_.Exception.Message -Color $Theme.Error -Prefix "Error"