Merge pull request #823 from cjahv/main

🚀 更新 TempMailPlus 的 Cursor 邮件识别逻辑
This commit is contained in:
Pin Studios 2025-04-30 17:10:20 +08:00 committed by GitHub
commit f8499708c9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 266 additions and 22 deletions

View File

@ -112,7 +112,7 @@ class CursorRegistration:
epin = config.get('TempMailPlus', 'epin') epin = config.get('TempMailPlus', 'epin')
if email and epin: if email and epin:
from email_tabs.tempmail_plus_tab import TempMailPlusTab from email_tabs.tempmail_plus_tab import TempMailPlusTab
email_tab = TempMailPlusTab(email, epin) email_tab = TempMailPlusTab(email, epin, self.translator)
print(f"{Fore.CYAN}{EMOJI['MAIL']} {self.translator.get('register.using_tempmail_plus')}{Style.RESET_ALL}") print(f"{Fore.CYAN}{EMOJI['MAIL']} {self.translator.get('register.using_tempmail_plus')}{Style.RESET_ALL}")
# Use new_signup.py directly for registration # Use new_signup.py directly for registration

View File

@ -1,7 +1,7 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
class EmailTabInterface(ABC): class EmailTabInterface(ABC):
"""Email tab interface for handling email verification""" """Interface for email tab implementations"""
@abstractmethod @abstractmethod
def refresh_inbox(self) -> None: def refresh_inbox(self) -> None:
@ -10,10 +10,10 @@ class EmailTabInterface(ABC):
@abstractmethod @abstractmethod
def check_for_cursor_email(self) -> bool: def check_for_cursor_email(self) -> bool:
"""Check if there is a verification email from Cursor """Check if there is a new email from Cursor
Returns: Returns:
bool: True if verification email exists, False otherwise bool: True if new email found, False otherwise
""" """
pass pass
@ -22,6 +22,6 @@ class EmailTabInterface(ABC):
"""Get the verification code from the email """Get the verification code from the email
Returns: Returns:
str: The verification code if found, empty string otherwise str: The verification code if available, empty string otherwise
""" """
pass pass

View File

@ -1,20 +1,23 @@
import requests import requests
import re import re
import datetime
from typing import Optional from typing import Optional
from .email_tab_interface import EmailTabInterface from .email_tab_interface import EmailTabInterface
class TempMailPlusTab(EmailTabInterface): class TempMailPlusTab(EmailTabInterface):
"""Implementation of EmailTabInterface for tempmail.plus""" """Implementation of EmailTabInterface for tempmail.plus"""
def __init__(self, email: str, epin: str): def __init__(self, email: str, epin: str, translator=None):
"""Initialize TempMailPlusTab """Initialize TempMailPlusTab
Args: Args:
email: The email address to check email: The email address to check
epin: The epin token for authentication epin: The epin token for authentication
translator: Optional translator for internationalization
""" """
self.email = email self.email = email
self.epin = epin self.epin = epin
self.translator = translator
self.base_url = "https://tempmail.plus/api" self.base_url = "https://tempmail.plus/api"
self.headers = { self.headers = {
'accept': 'application/json', 'accept': 'application/json',
@ -33,16 +36,17 @@ class TempMailPlusTab(EmailTabInterface):
} }
self.cookies = {'email': email} self.cookies = {'email': email}
self._cached_mail_id = None # 缓存mail_id self._cached_mail_id = None # 缓存mail_id
self._cached_verification_code = None # 缓存验证码
def refresh_inbox(self) -> None: def refresh_inbox(self) -> None:
"""Refresh the email inbox""" """Refresh the email inbox"""
pass pass
def check_for_cursor_email(self) -> bool: def check_for_cursor_email(self) -> bool:
"""Check if there is a verification email from Cursor """Check if there is a new email and immediately retrieve verification code
Returns: Returns:
bool: True if verification email exists, False otherwise bool: True if new email found and verification code retrieved, False otherwise
""" """
try: try:
params = { params = {
@ -59,28 +63,30 @@ class TempMailPlusTab(EmailTabInterface):
data = response.json() data = response.json()
if data.get('result') and data.get('mail_list'): if data.get('result') and data.get('mail_list'):
for mail in data['mail_list']: # 检查邮件列表中的第一个邮件是否为新邮件
if 'cursor.sh' in mail.get('from_mail', '') and mail.get('is_new') == True: if data['mail_list'][0].get('is_new') == True:
self._cached_mail_id = mail.get('mail_id') # 缓存mail_id self._cached_mail_id = data['mail_list'][0].get('mail_id') # 缓存mail_id
# 立即获取验证码
verification_code = self._extract_verification_code()
if verification_code:
self._cached_verification_code = verification_code
return True return True
return False return False
except Exception as e: except Exception as e:
print(f"检查Cursor邮件失败: {str(e)}") print(f"{self.translator.get('tempmail.check_email_failed', error=str(e)) if self.translator else f'Check email failed: {str(e)}'}")
return False return False
def get_verification_code(self) -> str: def _extract_verification_code(self) -> str:
"""Get the verification code from the email """Extract verification code from email content
Returns: Returns:
str: The verification code if found, empty string otherwise str: The verification code if found, empty string otherwise
""" """
try: try:
# 如果没有缓存的mail_id先检查是否有新邮件
if not self._cached_mail_id: if not self._cached_mail_id:
if not self.check_for_cursor_email(): return ""
return ""
# 使用缓存的mail_id获取邮件内容
params = { params = {
'email': self.email, 'email': self.email,
'epin': self.epin 'epin': self.epin
@ -97,6 +103,11 @@ class TempMailPlusTab(EmailTabInterface):
if not data.get('result'): if not data.get('result'):
return "" return ""
# 验证发件人邮箱是否包含cursor字符串
from_mail = data.get('from_mail', '')
if 'cursor' not in from_mail.lower():
return ""
# Extract verification code from text content using regex # Extract verification code from text content using regex
text = data.get('text', '') text = data.get('text', '')
match = re.search(r'\n\n(\d{6})\n\n', text) match = re.search(r'\n\n(\d{6})\n\n', text)
@ -105,5 +116,58 @@ class TempMailPlusTab(EmailTabInterface):
return "" return ""
except Exception as e: except Exception as e:
print(f"获取验证码失败: {str(e)}") print(f"{self.translator.get('tempmail.extract_code_failed', error=str(e)) if self.translator else f'Extract verification code failed: {str(e)}'}")
return "" return ""
def get_verification_code(self) -> str:
"""Get the verification code from cache
Returns:
str: The cached verification code if available, empty string otherwise
"""
return self._cached_verification_code or ""
if __name__ == "__main__":
import os
import time
import sys
import configparser
from config import get_config
# 尝试导入 translator
try:
from main import Translator
translator = Translator()
except ImportError:
translator = None
config = get_config(translator)
try:
email = config.get('TempMailPlus', 'email')
epin = config.get('TempMailPlus', 'epin')
print(f"{translator.get('tempmail.configured_email', email=email) if translator else f'Configured email: {email}'}")
# 初始化TempMailPlusTab传递 translator
mail_tab = TempMailPlusTab(email, epin, translator)
# 检查是否有Cursor的邮件
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'}")
# 获取验证码
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}'}")
else:
print(f"{translator.get('tempmail.no_code') if translator else 'Could not get verification code'}")
else:
print(f"{translator.get('tempmail.no_email') if translator else 'No Cursor verification email found'}")
except configparser.Error as e:
print(f"{translator.get('tempmail.config_error', error=str(e)) if translator else f'Config file error: {str(e)}'}")
except Exception as e:
print(f"{translator.get('tempmail.general_error', error=str(e)) if translator else f'An error occurred: {str(e)}'}")

View File

@ -850,5 +850,17 @@
"updating_database": "تحديث قاعدة بيانات مصادقة المؤشر ...", "updating_database": "تحديث قاعدة بيانات مصادقة المؤشر ...",
"title": "مصادقة المؤشر اليدوي", "title": "مصادقة المؤشر اليدوي",
"auth_update_failed": "فشل في تحديث معلومات المصادقة" "auth_update_failed": "فشل في تحديث معلومات المصادقة"
},
"tempmail": {
"config_error": "خطأ في ملف التكوين: {error}",
"no_email": "لم يتم العثور على بريد إلكتروني للتحقق من المؤشر",
"general_error": "حدث خطأ: {error}",
"checking_email": "التحقق من البريد الإلكتروني للتحقق من المؤشر ...",
"extract_code_failed": "فشل استخراج رمز التحقق: {error}",
"configured_email": "البريد الإلكتروني المكون: {البريد الإلكتروني}",
"check_email_failed": "فشل التحقق من البريد الإلكتروني: {error}",
"no_code": "لا يمكن الحصول على رمز التحقق",
"email_found": "تم العثور على البريد الإلكتروني للتحقق من المؤشر",
"verification_code": "رمز التحقق: {code}"
} }
} }

View File

@ -863,5 +863,17 @@
"auth_update_failed": "Неуспешно актуализиране на информацията за удостоверяване", "auth_update_failed": "Неуспешно актуализиране на информацията за удостоверяване",
"title": "Ръчно удостоверяване на курсора", "title": "Ръчно удостоверяване на курсора",
"updating_database": "Актуализиране на базата данни за удостоверяване на курсора ..." "updating_database": "Актуализиране на базата данни за удостоверяване на курсора ..."
},
"tempmail": {
"no_email": "Не е намерен имейл за проверка на курсора",
"config_error": "Грешка в конфигурацията на файла: {грешка}",
"general_error": "Възникна грешка: {грешка}",
"configured_email": "Конфигуриран имейл: {имейл}",
"extract_code_failed": "Кодът за проверка на екстракт не успя: {Грешка}",
"checking_email": "Проверка за имейл за проверка на курсора ...",
"no_code": "Не можа да получи код за проверка",
"email_found": "Намерен имейл за проверка на курсора",
"check_email_failed": "Проверете имейла не е успешен: {Грешка}",
"verification_code": "Код за проверка: {код}"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Dieses Tool modifiziert die Datei workbench.desktop.main.js, um die Token -Grenze zu umgehen", "description": "Dieses Tool modifiziert die Datei workbench.desktop.main.js, um die Token -Grenze zu umgehen",
"press_enter": "Drücken Sie die Eingabetaste, um fortzufahren ...", "press_enter": "Drücken Sie die Eingabetaste, um fortzufahren ...",
"title": "Bypass Token Limit Tool" "title": "Bypass Token Limit Tool"
},
"tempmail": {
"no_email": "Keine Cursorüberprüfungs -E -Mail gefunden",
"general_error": "Es ist ein Fehler aufgetreten: {Fehler}",
"config_error": "Konfigurationsdateifehler: {Fehler}",
"checking_email": "Überprüfung nach Cursor -Überprüfungs -E -Mail ...",
"extract_code_failed": "Verifizierungscode extrahieren fehlgeschlagen: {Fehler}",
"configured_email": "Konfigurierte E -Mail: {E -Mail}",
"no_code": "Konnte keinen Bestätigungscode erhalten",
"check_email_failed": "Überprüfen Sie die E -Mail fehlgeschlagen: {Fehler}",
"email_found": "Gefundene Cursor -Überprüfungs -E -Mail gefunden",
"verification_code": "Überprüfungscode: {Code}"
} }
} }

View File

@ -850,5 +850,17 @@
"auth_updated_successfully": "Authentication information updated successfully!", "auth_updated_successfully": "Authentication information updated successfully!",
"auth_update_failed": "Failed to update authentication information", "auth_update_failed": "Failed to update authentication information",
"error": "Error: {error}" "error": "Error: {error}"
},
"tempmail": {
"check_email_failed": "Check email failed: {error}",
"extract_code_failed": "Extract verification code failed: {error}",
"configured_email": "Configured email: {email}",
"checking_email": "Checking for Cursor verification email...",
"email_found": "Found Cursor verification email",
"verification_code": "Verification code: {code}",
"no_code": "Could not get verification code",
"no_email": "No Cursor verification email found",
"config_error": "Config file error: {error}",
"general_error": "An error occurred: {error}"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Esta herramienta modifica el archivo workbench.desktop.main.js para evitar el límite del token", "description": "Esta herramienta modifica el archivo workbench.desktop.main.js para evitar el límite del token",
"press_enter": "Presione Entrar para continuar ...", "press_enter": "Presione Entrar para continuar ...",
"title": "Herramienta de límite de token de derivación" "title": "Herramienta de límite de token de derivación"
},
"tempmail": {
"general_error": "Se produjo un error: {error}",
"config_error": "Error de archivo de configuración: {error}",
"no_email": "No se encuentra el correo electrónico de verificación del cursor",
"checking_email": "Comprobación del correo electrónico de verificación del cursor ...",
"configured_email": "Correo electrónico configurado: {correo electrónico}",
"extract_code_failed": "Extraer el código de verificación fallido: {error}",
"no_code": "No pudo obtener el código de verificación",
"check_email_failed": "Verifique el correo electrónico fallido: {error}",
"email_found": "Correo electrónico de verificación del cursor encontrado",
"verification_code": "Código de verificación: {código}"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Cet outil modifie le fichier workbench.desktop.main.js pour contourner la limite de jeton", "description": "Cet outil modifie le fichier workbench.desktop.main.js pour contourner la limite de jeton",
"press_enter": "Appuyez sur Entrée pour continuer ...", "press_enter": "Appuyez sur Entrée pour continuer ...",
"title": "Outil de limite de jeton de contournement" "title": "Outil de limite de jeton de contournement"
},
"tempmail": {
"no_email": "Aucun e-mail de vérification du curseur trouvé",
"general_error": "Une erreur s'est produite: {erreur}",
"config_error": "Erreur de fichier de configuration: {erreur}",
"configured_email": "Email configuré: {e-mail}",
"extract_code_failed": "Extraire le code de vérification a échoué: {error}",
"checking_email": "Vérification du courrier électronique de vérification du curseur ...",
"email_found": "Email de vérification du curseur trouvé",
"no_code": "Impossible d'obtenir le code de vérification",
"check_email_failed": "Vérifier l'échec de l'e-mail: {Erreur}",
"verification_code": "Code de vérification: {code}"
} }
} }

View File

@ -850,5 +850,17 @@
"description": "Questo strumento modifica il file workbench.desktop.main.js per bypassare il limite token", "description": "Questo strumento modifica il file workbench.desktop.main.js per bypassare il limite token",
"press_enter": "Premere Invio per continuare ...", "press_enter": "Premere Invio per continuare ...",
"title": "Strumento di limite di bypass token" "title": "Strumento di limite di bypass token"
},
"tempmail": {
"config_error": "Errore del file di configurazione: {errore}",
"no_email": "Nessuna e -mail di verifica del cursore trovato",
"general_error": "Si è verificato un errore: {errore}",
"extract_code_failed": "Extract Verifica Codice non riuscito: {errore}",
"configured_email": "Email configurata: {email}",
"no_code": "Impossibile ottenere il codice di verifica",
"checking_email": "Verificare la verifica della verifica del cursore ...",
"check_email_failed": "Controlla l'e -mail non riuscita: {errore}",
"email_found": "Email di verifica del cursore trovato",
"verification_code": "Codice di verifica: {codice}"
} }
} }

View File

@ -850,5 +850,17 @@
"title": "手動カーソル認証", "title": "手動カーソル認証",
"updating_database": "カーソル認証データベースの更新...", "updating_database": "カーソル認証データベースの更新...",
"auth_update_failed": "認証情報の更新に失敗しました" "auth_update_failed": "認証情報の更新に失敗しました"
},
"tempmail": {
"general_error": "エラーが発生しました:{エラー}",
"no_email": "カーソル検証メールは見つかりません",
"config_error": "構成ファイルエラー:{エラー}",
"checking_email": "カーソル検証メールの確認...",
"extract_code_failed": "検証コードが失敗した抽出:{エラー}",
"configured_email": "構成された電子メール:{電子メール}",
"email_found": "カーソル検証メールが見つかりました",
"no_code": "確認コードを取得できませんでした",
"check_email_failed": "電子メールの失敗を確認する:{エラー}",
"verification_code": "検証コード:{code}"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Deze tool wijzigt het bestand Workbench.desktop.main.js om de tokenlimiet te omzeilen", "description": "Deze tool wijzigt het bestand Workbench.desktop.main.js om de tokenlimiet te omzeilen",
"press_enter": "Druk op Enter om door te gaan ...", "press_enter": "Druk op Enter om door te gaan ...",
"title": "Omzeilen token limiet tool" "title": "Omzeilen token limiet tool"
},
"tempmail": {
"no_email": "Geen cursorverificatie -e -mail gevonden",
"general_error": "Er is een fout opgetreden: {error}",
"config_error": "Config -bestandsfout: {error}",
"checking_email": "Controleren op cursorverificatie -e -mail ...",
"extract_code_failed": "Extract Verificatiecode mislukt: {error}",
"configured_email": "Geconfigureerd e -mail: {e -mail}",
"no_code": "Kon geen verificatiecode krijgen",
"email_found": "Cursor Verificatie -e -mail gevonden",
"check_email_failed": "Controleer e -mail mislukt: {error}",
"verification_code": "Verificatiecode: {code}"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Esta ferramenta modifica o arquivo workbench.desktop.main.js para ignorar o limite do token", "description": "Esta ferramenta modifica o arquivo workbench.desktop.main.js para ignorar o limite do token",
"press_enter": "Pressione Enter para continuar ...", "press_enter": "Pressione Enter para continuar ...",
"title": "Ipassue Token Limit Tool" "title": "Ipassue Token Limit Tool"
},
"tempmail": {
"config_error": "Erro de arquivo de configuração: {erro}",
"general_error": "Ocorreu um erro: {erro}",
"no_email": "Nenhum e -mail de verificação do cursor encontrado",
"extract_code_failed": "Código de verificação de extração falhou: {erro}",
"checking_email": "Verificando o e -mail de verificação do cursor ...",
"configured_email": "Email configurado: {email}",
"no_code": "Não foi possível obter o código de verificação",
"check_email_failed": "Verifique o e -mail falhado: {erro}",
"verification_code": "Código de verificação: {code}",
"email_found": "E -mail de verificação do cursor encontrado"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Этот инструмент изменяет файл workbench.desktop.main.js, чтобы обойти предел токена", "description": "Этот инструмент изменяет файл workbench.desktop.main.js, чтобы обойти предел токена",
"press_enter": "Нажмите Enter, чтобы продолжить ...", "press_enter": "Нажмите Enter, чтобы продолжить ...",
"title": "Инструмент ограничения обхода токена" "title": "Инструмент ограничения обхода токена"
},
"tempmail": {
"no_email": "Электронное письмо с проверкой курсора не найдено",
"config_error": "Ошибка файла конфигурации: {ошибка}",
"extract_code_failed": "Установка кода извлечения проверки: {ошибка}",
"general_error": "Произошла ошибка: {ошибка}",
"no_code": "Не удалось получить код проверки",
"checking_email": "Проверка на проверку курсора по электронной почте ...",
"configured_email": "Настройка электронной почты: {электронная почта}",
"check_email_failed": "Проверка по электронной почте не удастся: {ошибка}",
"verification_code": "Код проверки: {код}",
"email_found": "Найдено электронное письмо с проверкой курсора"
} }
} }

View File

@ -862,5 +862,17 @@
"description": "Bu araç, jeton sınırını atlamak için workbench.desktop.main.js dosyasını değiştirir", "description": "Bu araç, jeton sınırını atlamak için workbench.desktop.main.js dosyasını değiştirir",
"press_enter": "Devam etmek için Enter tuşuna basın ...", "press_enter": "Devam etmek için Enter tuşuna basın ...",
"title": "Baypas Token Limit Aracı" "title": "Baypas Token Limit Aracı"
},
"tempmail": {
"general_error": "Bir hata oluştu: {hata}",
"no_email": "İmleç doğrulama e -postası bulunamadı",
"config_error": "Yapılandırma dosya hatası: {error}",
"extract_code_failed": ıkarma Doğrulama Kodu Başarısız: {Hata}",
"configured_email": "Yapılandırılmış e -posta: {e -posta}",
"checking_email": "İmleç doğrulama e -postasını kontrol etmek ...",
"check_email_failed": "E -postanın başarısız olduğunu kontrol edin: {hata}",
"no_code": "Doğrulama kodu alamadı",
"email_found": "İmleç doğrulama e -postası bulundu",
"verification_code": "Doğrulama kodu: {kod}"
} }
} }

View File

@ -863,5 +863,17 @@
"profile": "Hồ sơ {Number}", "profile": "Hồ sơ {Number}",
"profile_list": "Có sẵn {trình duyệt} Hồ sơ:", "profile_list": "Có sẵn {trình duyệt} Hồ sơ:",
"invalid_selection": "Lựa chọn không hợp lệ. Hãy thử lại." "invalid_selection": "Lựa chọn không hợp lệ. Hãy thử lại."
},
"tempmail": {
"config_error": "Lỗi tệp cấu hình: {error}",
"general_error": "Đã xảy ra lỗi: {lỗi}",
"no_email": "Không tìm thấy email xác minh con trỏ",
"checking_email": "Kiểm tra email xác minh con trỏ ...",
"configured_email": "Email được định cấu hình: {email}",
"extract_code_failed": "Trích xuất mã xác minh không thành công: {error}",
"no_code": "Không thể nhận mã xác minh",
"check_email_failed": "Kiểm tra email không thành công: {lỗi}",
"email_found": "Tìm thấy email xác minh con trỏ",
"verification_code": "Mã xác minh: {code}"
} }
} }

View File

@ -854,5 +854,17 @@
"title": "手动Cursor身份验证", "title": "手动Cursor身份验证",
"token_verified": "令牌成功验证了!", "token_verified": "令牌成功验证了!",
"updating_database": "更新Cursor身份验证数据库..." "updating_database": "更新Cursor身份验证数据库..."
},
"tempmail": {
"general_error": "发生错误:{error}",
"no_email": "找不到Cursor验证电子邮件",
"configured_email": "配置的电子邮件:{email}",
"config_error": "配置文件错误:{error}",
"extract_code_failed": "提取验证代码失败:{error}",
"no_code": "无法获得验证代码",
"check_email_failed": "检查电子邮件失败:{error}",
"checking_email": "检查Cursor验证电子邮件...",
"email_found": "找到Cursor验证电子邮件",
"verification_code": "验证代码:{code}"
} }
} }

View File

@ -869,5 +869,17 @@
"title": "手動Cursor身份驗證", "title": "手動Cursor身份驗證",
"updating_database": "更新Cursor身份驗證數據庫...", "updating_database": "更新Cursor身份驗證數據庫...",
"auth_update_failed": "無法更新身份驗證信息" "auth_update_failed": "無法更新身份驗證信息"
},
"tempmail": {
"general_error": "發生錯誤:{error}",
"config_error": "配置文件錯誤:{error}",
"no_email": "找不到Cursor驗證電子郵件",
"checking_email": "檢查Cursor驗證電子郵件...",
"extract_code_failed": "提取驗證代碼失敗:{error}",
"configured_email": "配置的電子郵件:{email}",
"no_code": "無法獲得驗證代碼",
"check_email_failed": "檢查電子郵件失敗:{error}",
"email_found": "找到Cursor驗證電子郵件",
"verification_code": "驗證代碼:{code}"
} }
} }