chendeben vor 1 Jahr
Ursprung
Commit
3205df5128
3 geänderte Dateien mit 116 neuen und 96 gelöschten Zeilen
  1. 13 27
      config.py
  2. 15 7
      cursor_pro_keep_alive.py
  3. 88 62
      get_email_code.py

+ 13 - 27
config.py

@@ -2,6 +2,7 @@ from dotenv import load_dotenv
 import os
 import sys
 from logger import logging
+import uuid
 
 
 class Config:
@@ -14,47 +15,32 @@ class Config:
             # 如果是开发环境
             application_path = os.path.dirname(os.path.abspath(__file__))
 
-        # 指定 .env 文件的路径
-        dotenv_path = os.path.join(application_path, ".env")
-
-        if not os.path.exists(dotenv_path):
-            raise FileNotFoundError(f"文件 {dotenv_path} 不存在")
-
-        # 加载 .env 文件
-        load_dotenv(dotenv_path)
-
-        self.temp_mail = os.getenv("TEMP_MAIL", "").strip().split("@")[0]
-        self.domain = os.getenv("DOMAIN", "").strip()
-
-        self.check_config()
+        self.auth_token = str(uuid.uuid4()).replace('-', '')
 
     def get_temp_mail(self):
+        # 返回临时邮箱地址
+        return getattr(self, 'temp_mail', None)
 
-        return self.temp_mail
-
-    def get_domain(self):
-        return self.domain
+    def set_temp_mail(self, mail):
+        self.temp_mail = mail
 
-    def check_config(self):
-        if not self.check_is_valid(self.temp_mail):
-            raise ValueError("临时邮箱未配置,请在 .env 文件中设置 TEMP_MAIL")
-        if not self.check_is_valid(self.domain):
-            raise ValueError("域名未配置,请在 .env 文件中设置 DOMAIN")
+    def get_auth_token(self):
+        return self.auth_token
 
     def check_is_valid(self, str):
         return len(str.strip()) > 0
 
     def print_config(self):
-        logging.info(f"\033[32m临时邮箱: {self.temp_mail}\033[0m")
-        logging.info(f"\033[32m域名: {self.domain}\033[0m")
+        temp_mail = self.get_temp_mail()
+        if temp_mail:
+            logging.info(f"\033[32m临时邮箱: {temp_mail}\033[0m")
 
 
 # 使用示例
 if __name__ == "__main__":
     try:
         config = Config()
-        print("环境变量加载成功!")
+        print("配置初始化成功!")
         config.get_temp_mail()
-        config.get_domain()
-    except ValueError as e:
+    except Exception as e:
         print(f"错误: {e}")

+ 15 - 7
cursor_pro_keep_alive.py

@@ -160,7 +160,7 @@ def sign_up_account(browser, tab):
                 break
             if tab.ele("@data-index=0"):
                 logging.info("正在获取邮箱验证码...")
-                code = email_handler.get_verification_code()
+                code = email_handler.get_verification_code(account)
                 if not code:
                     logging.error("获取验证码失败")
                     return False
@@ -196,6 +196,9 @@ def sign_up_account(browser, tab):
             usage_info = usage_ele.text
             total_usage = usage_info.split("/")[-1].strip()
             logging.info(f"账户可用额度上限: {total_usage}")
+        else:
+            logging.error("无法获取账户额度信息")
+            return False
     except Exception as e:
         logging.error(f"获取账户额度信息失败: {str(e)}")
 
@@ -218,7 +221,6 @@ class EmailGenerator:
     ):
         configInstance = Config()
         configInstance.print_config()
-        self.domain = configInstance.get_domain()
         self.default_password = password
         self.default_first_name = self.generate_random_name()
         self.default_last_name = self.generate_random_name()
@@ -232,10 +234,17 @@ class EmailGenerator:
         return first_letter + rest_letters
 
     def generate_email(self, length=8):
-        """生成随机邮箱地址"""
-        random_str = "".join(random.choices("abcdefghijklmnopqrstuvwxyz", k=length))
-        timestamp = str(int(time.time()))[-6:]  # 使用时间戳后6位
-        return f"{random_str}{timestamp}@{self.domain}"
+        """获取可用的邮箱地址"""
+        try:
+            email_handler = EmailVerificationHandler()
+            email_handler._create_mailbox()
+            email_list = email_handler._get_email_list()
+            if email_list and len(email_list) > 0:
+                return email_list[-1]  # 直接返回最后一个邮箱地址
+            raise Exception("无法获取可用的邮箱地址")
+        except Exception as e:
+            logging.error(f"获取邮箱地址失败: {str(e)}")
+            raise
 
     def get_account_info(self):
         """获取完整的账号信息"""
@@ -264,7 +273,6 @@ if __name__ == "__main__":
         login_url = "https://authenticator.cursor.sh"
         sign_up_url = "https://authenticator.cursor.sh/sign-up"
         settings_url = "https://www.cursor.com/settings"
-        mail_url = "https://tempmail.plus"
 
         logging.info("正在生成随机账号信息...")
         email_generator = EmailGenerator()

+ 88 - 62
get_email_code.py

@@ -6,81 +6,107 @@ import requests
 
 class EmailVerificationHandler:
     def __init__(self):
-        self.username = Config().get_temp_mail()
+        self.config = Config()
         self.session = requests.Session()
-        self.emailExtension = "@mailto.plus"
+        self.base_url = "https://tm.ss5.xyz"
+        self.headers = {
+            'accept': 'application/json, text/javascript, */*; q=0.01',
+            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
+            'cache-control': 'no-cache',
+            'dnt': '1',
+            'pragma': 'no-cache',
+            'priority': 'u=1, i',
+            'referer': 'https://tm.ss5.xyz/index.html',
+            'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
+            'sec-ch-ua-mobile': '?0',
+            'sec-ch-ua-platform': '"macOS"',
+            'sec-fetch-dest': 'empty',
+            'sec-fetch-mode': 'cors',
+            'sec-fetch-site': 'same-origin',
+            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
+            'x-requested-with': 'XMLHttpRequest'
+        }
+        self.auth_token = self.config.get_auth_token()
+        self.session.cookies.set('PHPSESSID', '967qb8iskkmkl2q56i554l5j3e')
+        self.session.cookies.set('ysmail', self.auth_token)
 
-    def get_verification_code(self):
+    def get_verification_code(self, email=None):
         code = None
 
         try:
             print("正在处理...")
-
-            # 等待并获取最新邮件
-            code, first_id = self._get_latest_mail_code()
-
-            # 清理邮件
-            self._cleanup_mail(first_id)
+            # 使用传入的邮箱地址或从配置获取
+            self.username = email if email else self.config.get_temp_mail()
+            print("当前邮箱:", self.username)
+            
+            if self.username:
+                # 使用邮箱地址获取验证码
+                code = self._get_latest_mail_code()
+            else:
+                print("错误:未提供有效的邮箱地址")
 
         except Exception as e:
             print(f"获取验证码失败: {str(e)}")
 
         return code
 
-    # 手动输入验证码
-    def _get_latest_mail_code(self):
-        # 获取邮件列表
-        mail_list_url = f"https://tempmail.plus/api/mails?email={self.username}{self.emailExtension}&limit=20&epin="
-        mail_list_response = self.session.get(mail_list_url)
-        mail_list_data = mail_list_response.json()
-        time.sleep(0.5)
-        if not mail_list_data.get("result"):
-            return None, None
-
-        # 获取最新邮件的ID
-        first_id = mail_list_data.get("first_id")
-        if not first_id:
-            return None, None
-
-        # 获取具体邮件内容
-        mail_detail_url = f"https://tempmail.plus/api/mails/{first_id}?email={self.username}{self.emailExtension}&epin="
-        mail_detail_response = self.session.get(mail_detail_url)
-        mail_detail_data = mail_detail_response.json()
-        time.sleep(0.5)
-        if not mail_detail_data.get("result"):
-            return None, None
-
-        # 从邮件文本中提取6位数字验证码
-        mail_text = mail_detail_data.get("text", "")
-        code_match = re.search(r"\b\d{6}\b", mail_text)
-
-        if code_match:
-            return code_match.group(), first_id
-        return None, None
-
-    def _cleanup_mail(self, first_id):
-        # 构造删除请求的URL和数据
-        delete_url = "https://tempmail.plus/api/mails/"
-        payload = {
-            "email": f"{self.username}{self.emailExtension}",
-            "first_id": first_id,
-            "epin": "",
-        }
-
-        # 最多尝试5次
-        for _ in range(5):
-            response = self.session.delete(delete_url, data=payload)
+    def _create_mailbox(self):
+        url = f"{self.base_url}/user/user?a={self.auth_token}"
+        response = self.session.get(url, headers=self.headers)
+        if response.status_code != 200:
+            raise Exception("创建邮箱失败")
+        return response.json()
+
+    def _get_email_list(self):
+        url = f"{self.base_url}/user/lists?a={self.auth_token}"
+        response = self.session.get(url, headers=self.headers)
+        if response.status_code != 200:
+            raise Exception("获取邮箱列表失败")
+        data = response.json()
+        return data.get('data', [])
+
+    def _get_latest_mail_code(self, max_attempts=10, retry_interval=3):
+        for attempt in range(max_attempts):
+            url = f"{self.base_url}/mail/lists?u={self.username}&a={self.auth_token}"
+            response = self.session.get(url, headers=self.headers)
+            if response.status_code != 200:
+                print(f"第 {attempt + 1} 次尝试获取邮件失败,{retry_interval} 秒后重试...")
+                time.sleep(retry_interval)
+                continue
+
+            response_data = response.json()
+            mail_list_data = response_data.get('data')
+            
+            # 检查返回的数据结构
+            if not isinstance(mail_list_data, list) or not mail_list_data or response_data.get('code') != 0:
+                print(f"第 {attempt + 1} 次尝试未收到邮件,{retry_interval} 秒后重试...")
+                time.sleep(retry_interval)
+                continue
+
+            # 获取最新邮件内容
             try:
-                result = response.json().get("result")
-                if result is True:
-                    return True
-            except:
-                pass
-
-            # 如果失败,等待0.5秒后重试
-            time.sleep(0.5)
-
-        return False
+                latest_mail = mail_list_data[0]
+                if not isinstance(latest_mail, dict):
+                    print(f"第 {attempt + 1} 次尝试邮件格式错误,{retry_interval} 秒后重试...")
+                    time.sleep(retry_interval)
+                    continue
+                    
+                mail_text = latest_mail.get('content', '')
+                
+                # 从邮件文本中提取指定格式的验证码
+                code_match = re.search(r">(\d{6})<", mail_text)
+                if code_match:
+                    return code_match.group(1)
+            except Exception as e:
+                print(f"处理邮件内容时出错: {str(e)}")
+                time.sleep(retry_interval)
+                continue
+            
+            print(f"第 {attempt + 1} 次尝试未找到验证码,{retry_interval} 秒后重试...")
+            time.sleep(retry_interval)
+
+        print(f"已达到最大尝试次数 ({max_attempts}),获取验证码失败")
+        return None
 
 
 if __name__ == "__main__":