package com.dsapi.deepseek; import com.dsapi.config.DeepSeekProperties; import com.dsapi.constant.ErrorCodes; import com.dsapi.dto.SwitchState; import com.dsapi.exception.BusinessException; import com.dsapi.exception.SystemException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.BrowserType; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import com.microsoft.playwright.options.Cookie; import com.microsoft.playwright.options.LoadState; import com.microsoft.playwright.options.WaitForSelectorState; import jakarta.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** * Playwright DeepSeek 网关:方案1 精准表单 + 有头验证;方案2 有头窗口自动捕获。 */ @Component public class PlaywrightDeepSeekGateway implements DeepSeekGateway { private static final Logger log = LoggerFactory.getLogger(PlaywrightDeepSeekGateway.class); private static final String[] SIGN_IN_ROOT = { ".ds-sign-in-form__main", ".ds-sign-in-form-wrapper", ".ds-auth-form-wrapper", ".ds-sign-up-form__main" }; private final DeepSeekProperties properties; private final ObjectMapper objectMapper; private final Object lock = new Object(); private Playwright playwright; private Browser browser; private Boolean browserHeadless; private BrowserContext context; private Page page; private volatile boolean ready; private final Map pendingCaptchaPages = new ConcurrentHashMap<>(); private final Map scheme2Jobs = new ConcurrentHashMap<>(); public PlaywrightDeepSeekGateway(DeepSeekProperties properties, ObjectMapper objectMapper) { this.properties = properties; this.objectMapper = objectMapper; } @Override public LoginResult loginScheme1(String account, String password, boolean headed) { if (account == null || account.isBlank() || password == null || password.isBlank()) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "DeepSeek 账号密码不能为空"); } synchronized (lock) { String stage = DeepSeekLoginStages.OPEN_PAGE; String pageUrl = ""; try { ensureBrowser(!headed); page.navigate(properties.getSignInUrl()); page.waitForLoadState(LoadState.DOMCONTENTLOADED); page.waitForTimeout(800); pageUrl = safeUrl(); if (pageContentBlocked()) { return fail(DeepSeekLoginStages.BLOCKED, pageUrl, "页面被风控拦截(403/CloudFront)", "请改用方案2有头窗口,或检查网络环境"); } waitSignInForm(12000); stage = DeepSeekLoginStages.SWITCH_PASSWORD; boolean switched = switchToPasswordLogin(); if (!switched && page.locator("input[type='password']").count() == 0) { return fail(DeepSeekLoginStages.SWITCH_PASSWORD, safeUrl(), "未能切换到密码登录", "页面可能默认扫码/验证码登录,请改用方案2"); } stage = DeepSeekLoginStages.FILL_FORM; Locator form = resolveFormRoot(); fillAccount(form, account); fillPassword(form, password); stage = DeepSeekLoginStages.SUBMIT; clickLogin(form); page.waitForTimeout(1800); pageUrl = safeUrl(); if (isLoggedIn()) { ready = true; return ok(dumpCookies(), DeepSeekLoginStages.DONE, pageUrl, "登录成功"); } if (looksLikeCaptcha()) { stage = DeepSeekLoginStages.CAPTCHA; String token = UUID.randomUUID().toString(); pendingCaptchaPages.put(token, page); return new LoginResult( "NEED_CAPTCHA", "请在弹出的浏览器窗口中完成人机验证,完成后点击「我已完成验证」", null, token, null, stage, pageUrl, "不要关闭弹出的 Chromium 窗口" ); } return fail(DeepSeekLoginStages.FAILED, pageUrl, "登录未成功,请检查账号密码或改用方案2", "可查看诊断日志中的 stage/pageUrl"); } catch (BusinessException e) { throw e; } catch (Exception e) { log.error("Scheme1 login failed at {}", stage, e); if (pageContentBlocked()) { return fail(DeepSeekLoginStages.BLOCKED, safeUrl(), "访问被拦截: " + e.getMessage(), "建议方案2有头登录"); } throw new SystemException(ErrorCodes.SYSTEM_ERROR, "方案1登录异常(" + stage + "): " + e.getMessage(), e); } } } @Override public LoginResult waitScheme1Login(String sessionToken, long timeoutMs) { synchronized (lock) { Page captchaPage = pendingCaptchaPages.get(sessionToken); if (captchaPage == null && page != null) { captchaPage = page; } if (captchaPage == null) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "验证会话无效,请重新发起方案1登录"); } long deadline = System.currentTimeMillis() + Math.max(5000, timeoutMs); try { while (System.currentTimeMillis() < deadline) { if (isLoggedIn(captchaPage)) { pendingCaptchaPages.remove(sessionToken); this.page = captchaPage; ready = true; return ok(dumpCookies(), DeepSeekLoginStages.DONE, safeUrl(captchaPage), "登录成功"); } captchaPage.waitForTimeout(1000); } return new LoginResult( "NEED_CAPTCHA", "仍未检测到登录成功,请继续在浏览器完成验证后重试", null, sessionToken, null, DeepSeekLoginStages.CAPTCHA, safeUrl(captchaPage), "确认窗口内已进入聊天页后再点「我已完成验证」" ); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "等待验证失败: " + e.getMessage(), e); } } } @Override public LoginResult submitCaptcha(String sessionToken, int clickX, int clickY) { // 推荐路径为有头窗口手动验证;坐标点击仅作降级 return waitScheme1Login(sessionToken, 3000); } public String startScheme2Job() { synchronized (lock) { try { ensurePlaywright(); ensureHeadedBrowser(); BrowserContext jobContext = browser.newContext( new Browser.NewContextOptions() .setLocale("zh-CN") .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36") ); Page jobPage = jobContext.newPage(); jobPage.setDefaultTimeout(properties.getTimeoutMs()); jobPage.navigate(properties.getSignInUrl()); String jobId = UUID.randomUUID().toString().replace("-", ""); Scheme2LoginJob job = new Scheme2LoginJob(jobId, jobContext, jobPage); scheme2Jobs.put(jobId, job); return jobId; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "打开方案2登录窗口失败: " + e.getMessage(), e); } } } public Scheme2LoginJob getScheme2Job(String jobId) { Scheme2LoginJob job = scheme2Jobs.get(jobId); if (job == null) { throw new BusinessException(ErrorCodes.NOT_FOUND, "登录任务不存在或已结束"); } refreshScheme2Status(job); return job; } public LoginResult confirmScheme2Job(String jobId) { synchronized (lock) { Scheme2LoginJob job = getScheme2Job(jobId); try { Page jobPage = job.getPage(); if (jobPage.isClosed()) { job.setStatus(Scheme2LoginJob.CLOSED); throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "登录窗口已关闭,请重新打开"); } if (!isLoggedIn(jobPage)) { job.setStatus(Scheme2LoginJob.WAITING_USER); throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "尚未检测到登录成功,请先在弹出窗口完成登录后再确认"); } // 推荐策略:将登录 Context/Page 提升为主会话,避免只拷 Cookie 丢失 localStorage promoteScheme2Context(job); if (!ChatReadyProbe.isChatReady(page)) { try { page.navigate(properties.getChatUrl()); page.waitForLoadState(LoadState.DOMCONTENTLOADED); } catch (Exception e) { log.warn("navigate chat after promote failed: {}", e.getMessage()); } } if (!waitUntilChatReady(20000)) { ready = false; String url = safeUrl(); return fail(DeepSeekLoginStages.MIGRATE_FAILED, url, "登录窗已登录,但主聊天页未就绪(未找到输入框)", "请重试「我已登录」,或重新打开方案2窗口完成登录"); } ready = true; String payload = dumpCookies(); job.setSessionPayload(payload); job.setStatus(Scheme2LoginJob.SUCCESS); job.setMessage("登录成功,会话已保存"); return ok(payload, DeepSeekLoginStages.DONE, safeUrl(), "方案2登录成功:已提升登录窗口为聊天会话(chatReady=true)"); } catch (BusinessException e) { throw e; } catch (Exception e) { ready = false; throw new SystemException(ErrorCodes.SYSTEM_ERROR, "确认方案2登录失败: " + e.getMessage(), e); } } } /** * 将方案2的 BrowserContext/Page 提升为主会话;不关闭该 Context。 */ private void promoteScheme2Context(Scheme2LoginJob job) { BrowserContext promoted = job.getContext(); Page promotedPage = job.getPage(); BrowserContext oldContext = this.context; this.context = promoted; this.page = promotedPage; // 从 job 表移除,但不要 close context scheme2Jobs.remove(job.getJobId()); if (oldContext != null && oldContext != promoted) { try { oldContext.close(); } catch (Exception e) { log.debug("close old main context: {}", e.getMessage()); } } browserHeadless = false; } private void refreshScheme2Status(Scheme2LoginJob job) { try { if (job.getPage() == null || job.getPage().isClosed()) { job.setStatus(Scheme2LoginJob.CLOSED); job.setMessage("登录窗口已关闭"); return; } if (isLoggedIn(job.getPage())) { job.setStatus("LOGGED_IN_DETECTED"); job.setMessage("已检测到登录,请点击「我已登录」保存会话"); } else { job.setStatus(Scheme2LoginJob.WAITING_USER); job.setMessage("请在弹出的浏览器窗口中完成 DeepSeek 登录"); } } catch (Exception e) { job.setMessage("状态检测中: " + e.getMessage()); } } private void closeScheme2JobQuietly(String jobId) { Scheme2LoginJob job = scheme2Jobs.remove(jobId); if (job == null) { return; } // 若已提升为主 context,禁止关闭 if (job.getContext() == this.context) { return; } try { job.getContext().close(); } catch (Exception ignored) { } } public boolean isChatReady() { synchronized (lock) { return ready && ChatReadyProbe.isChatReady(page); } } public boolean isAuthExpired() { synchronized (lock) { return ChatReadyProbe.isAuthExpired(page); } } /** * 等待聊天输入框就绪。 */ public boolean waitUntilChatReady(long timeoutMs) { synchronized (lock) { if (page == null || page.isClosed()) { return false; } long deadline = System.currentTimeMillis() + Math.max(3000, timeoutMs); while (System.currentTimeMillis() < deadline) { if (ChatReadyProbe.isAuthExpired(page)) { return false; } if (ChatReadyProbe.isChatReady(page)) { return true; } try { page.waitForTimeout(500); } catch (Exception e) { return false; } } return ChatReadyProbe.isChatReady(page); } } @Override public void activateSessionPayload(String sessionPayload, int scheme) { if (sessionPayload == null || sessionPayload.isBlank()) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "sessionPayload 不能为空"); } synchronized (lock) { try { ensureBrowser(properties.isHeadless()); List> raw = objectMapper.readValue(sessionPayload, new TypeReference<>() { }); List cookies = new ArrayList<>(); for (Map item : raw) { Cookie c = new Cookie(String.valueOf(item.get("name")), String.valueOf(item.get("value"))); Object domain = item.get("domain"); c.domain = domain == null ? ".deepseek.com" : String.valueOf(domain); Object path = item.get("path"); c.path = path == null ? "/" : String.valueOf(path); cookies.add(c); } context.clearCookies(); context.addCookies(cookies); page.navigate(properties.getChatUrl()); page.waitForLoadState(LoadState.DOMCONTENTLOADED); page.waitForTimeout(1200); if (ChatReadyProbe.isAuthExpired(page) && !waitUntilChatReady(12000)) { ready = false; throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "注入会话后仍未登录,请重新登录"); } if (!waitUntilChatReady(15000)) { // Cookie 备份恢复可能缺 localStorage:标记未就绪但不伪造 ready ready = false; throw new BusinessException(ErrorCodes.CHAT_NOT_READY, "会话 Cookie 已注入但聊天页未就绪,请使用方案2重新登录(推荐)"); } ready = true; } catch (BusinessException e) { throw e; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "激活会话失败: " + e.getMessage(), e); } } } @Override public boolean isReady() { return ready; } @Override public SendResult sendMessage(String deepseekChatId, String content, boolean deepThinking, boolean smartSearch, Consumer onDelta) { synchronized (lock) { ensureReadyInternal(); ReplyCapture capture = null; try { if (deepseekChatId != null && !deepseekChatId.isBlank() && !deepseekChatId.startsWith("local-")) { page.navigate(properties.getChatUrl() + "a/chat/s/" + deepseekChatId); } else { page.navigate(properties.getChatUrl()); } page.waitForLoadState(LoadState.DOMCONTENTLOADED); if (!waitUntilChatReady(15000)) { if (ChatReadyProbe.isAuthExpired(page)) { ready = false; throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "登录已失效,请到接口设置重新登录"); } throw new BusinessException(ErrorCodes.CHAT_INPUT_NOT_FOUND, "未找到聊天输入框,请稍后重试或重新方案2登录"); } syncSwitchesInternal(deepThinking, smartSearch); capture = new ReplyCapture(page); capture.start(); String before = capture.readDomAssistantText(); fillChatInput(content); clickSend(); GenerationWatchdog watchdog = new GenerationWatchdog(page); watchdog.setNoiseHints(capture.readChatTitle(), content); StringBuilder accumulated = new StringBuilder(); String lastEmittedSnapshot = before == null ? "" : before; long deadline = System.currentTimeMillis() + properties.getTimeoutMs(); boolean emitDelta = onDelta != null && properties.isStreamDeltaEnabled(); while (System.currentTimeMillis() < deadline) { page.waitForTimeout(400); // 首条后标题可能刚出现,持续刷新 hint watchdog.setNoiseHints(capture.readChatTitle(), content); String currentDom = capture.readDomAssistantText(); String snapshot = currentDom == null ? "" : currentDom; watchdog.observe(snapshot); if (emitDelta && !snapshot.isEmpty() && !snapshot.equals(lastEmittedSnapshot)) { String delta; if (snapshot.startsWith(lastEmittedSnapshot)) { delta = snapshot.substring(lastEmittedSnapshot.length()); } else if (before != null && snapshot.startsWith(before)) { delta = snapshot.substring(before.length()); accumulated.setLength(0); } else { delta = ""; accumulated.setLength(0); accumulated.append(ReplyCapture.extractNewAssistant(before, snapshot)); } if (!delta.isEmpty()) { accumulated.append(delta); onDelta.accept(delta); } lastEmittedSnapshot = snapshot; } else if (!snapshot.isEmpty() && !snapshot.equals(lastEmittedSnapshot)) { lastEmittedSnapshot = snapshot; String body = ReplyCapture.extractNewAssistant(before, snapshot); body = ReplyCapture.stripTitlePrefix(body, capture.readChatTitle(), content); if (!body.isBlank() && body.length() >= accumulated.length()) { accumulated.setLength(0); accumulated.append(body); } } if (!watchdog.isSettled(before)) { continue; } // 首次判定结束后稍候再读,避免截断末段;不可信则继续等到超时 page.waitForTimeout(500); String settledCandidate = capture.resolveFinalText(before, accumulated.toString(), content); String titleNow = capture.readChatTitle(); if (ReplyCapture.isReliableFinal(settledCandidate, titleNow, content, true)) { accumulated.setLength(0); accumulated.append(settledCandidate); break; } // 已 settle 但仍像残片:再给网络/DOM 时间,避免每轮重复长等 page.waitForTimeout(800); } String finalText = capture.resolveFinalText(before, accumulated.toString(), content); // 定稿失败时短延迟重采,降低偶发误杀 for (int retry = 0; retry < 2 && !ReplyCapture.isReliableFinal(finalText, capture.readChatTitle(), content, true); retry++) { page.waitForTimeout(1000); String again = capture.resolveFinalText(before, accumulated.toString(), content); if (again != null && again.length() >= (finalText == null ? 0 : finalText.length())) { finalText = again; } } if (!ReplyCapture.isReliableFinal(finalText, capture.readChatTitle(), content, true)) { throw new BusinessException(ErrorCodes.REPLY_CAPTURE_EMPTY, "回复采集失败:内容像对话标题或未完成残片,请重试(登录态通常仍保留)"); } String chatId = extractChatIdFromUrl(); return new SendResult(chatId == null ? deepseekChatId : chatId, finalText.trim()); } catch (BusinessException e) { if (ErrorCodes.DEEPSEEK_NOT_READY.equals(e.getCode()) || ChatReadyProbe.isAuthExpired(page)) { ready = false; } throw e; } catch (Exception e) { if (ChatReadyProbe.isAuthExpired(page)) { ready = false; } throw new SystemException(ErrorCodes.SYSTEM_ERROR, "发送消息失败: " + e.getMessage(), e); } finally { if (capture != null) { capture.stop(); } } } } /** * 登录成功后导出 storageState 并切到无头;失败则保留有头并返回回退模式。 */ public int switchToHeadlessChatAfterLogin() { synchronized (lock) { if (!properties.isChatHeadlessAfterLogin()) { return DeepSeekLoginStages.BROWSER_HEADED_CHAT; } if (context == null || page == null || page.isClosed()) { log.warn("No session for headless switch, keep headed"); return DeepSeekLoginStages.BROWSER_HEADED_CHAT; } Path statePath = Path.of(properties.getStorageStatePath()); Browser oldBrowser = this.browser; BrowserContext oldContext = this.context; try { Path parent = statePath.getParent(); if (parent != null) { Files.createDirectories(parent); } context.storageState(new BrowserContext.StorageStateOptions().setPath(statePath)); ensurePlaywright(); Browser newBrowser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true)); BrowserContext newContext = newBrowser.newContext(new Browser.NewContextOptions() .setStorageStatePath(statePath) .setLocale("zh-CN") .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")); Page newPage = newContext.newPage(); newPage.setDefaultTimeout(properties.getTimeoutMs()); newPage.navigate(properties.getChatUrl()); newPage.waitForLoadState(LoadState.DOMCONTENTLOADED); this.browser = newBrowser; this.context = newContext; this.page = newPage; this.browserHeadless = true; if (!waitUntilChatReady(20000)) { log.warn("Headless chatReady failed, fallback to headed"); safeClose(newContext); safeClose(newBrowser); this.browser = oldBrowser; this.context = oldContext; this.page = oldContext.pages().isEmpty() ? oldContext.newPage() : oldContext.pages().get(0); this.browserHeadless = false; this.page.navigate(properties.getChatUrl()); waitUntilChatReady(15000); ready = ChatReadyProbe.isChatReady(page); return DeepSeekLoginStages.BROWSER_HEADED_CHAT; } ready = true; safeClose(oldContext); if (oldBrowser != null && oldBrowser != newBrowser) { safeClose(oldBrowser); } log.info("Switched to headless chat session, state={}", statePath.toAbsolutePath()); return DeepSeekLoginStages.BROWSER_HEADLESS_CHAT; } catch (Exception e) { log.error("switchToHeadlessChatAfterLogin failed, keep headed: {}", e.getMessage()); this.browser = oldBrowser; this.context = oldContext; if (oldContext != null && !oldContext.pages().isEmpty()) { this.page = oldContext.pages().get(0); } this.browserHeadless = false; ready = page != null && ChatReadyProbe.isChatReady(page); return DeepSeekLoginStages.BROWSER_HEADED_CHAT; } } } /** * 使用落盘 storageState 恢复聊天会话(优先于纯 Cookie)。 */ public boolean restoreFromStorageState(String storageStatePath, boolean preferHeadless) { synchronized (lock) { if (storageStatePath == null || storageStatePath.isBlank()) { return false; } Path statePath = Path.of(storageStatePath); if (!Files.exists(statePath)) { return false; } try { ensurePlaywright(); boolean headless = preferHeadless && properties.isChatHeadlessAfterLogin(); if (browser != null) { safeClose(context); safeClose(browser); browser = null; context = null; page = null; } browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(headless)); browserHeadless = headless; context = browser.newContext(new Browser.NewContextOptions() .setStorageStatePath(statePath) .setLocale("zh-CN") .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")); page = context.newPage(); page.setDefaultTimeout(properties.getTimeoutMs()); page.navigate(properties.getChatUrl()); page.waitForLoadState(LoadState.DOMCONTENTLOADED); if (!waitUntilChatReady(20000)) { ready = false; return false; } ready = true; return true; } catch (Exception e) { log.warn("restoreFromStorageState failed: {}", e.getMessage()); ready = false; return false; } } } public String currentStorageStatePath() { return properties.getStorageStatePath(); } public Boolean currentBrowserHeadless() { return browserHeadless; } /** * 粘贴导入 Playwright storageState JSON:校验 → 落盘配置路径 → 无头优先恢复会话。 * * @param storageStateJson deepseek-storage.json 全文 * @return Cookie JSON 备份(写入 biz_deepseek_session.session_payload) */ public String importStorageStateJson(String storageStateJson) { if (storageStateJson == null || storageStateJson.isBlank()) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "storageStateJson 不能为空"); } String trimmed = storageStateJson.trim(); if (trimmed.length() > 5 * 1024 * 1024) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "storageStateJson 过大(超过 5MB)"); } String normalized; try { JsonNode root = objectMapper.readTree(trimmed); if (root.isArray()) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "这是 Cookie 数组,请用「高级:粘贴 Cookie JSON」;本入口需要 deepseek-storage.json(含 cookies/origins)"); } if (!root.isObject() || (!root.has("cookies") && !root.has("origins"))) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "不是 Playwright storageState 格式,需含 cookies 或 origins 字段"); } normalized = objectMapper.writeValueAsString(root); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "storageStateJson 不是合法 JSON: " + e.getMessage()); } synchronized (lock) { try { Path statePath = Path.of(properties.getStorageStatePath()); Path parent = statePath.getParent(); if (parent != null) { Files.createDirectories(parent); } Files.writeString(statePath, normalized, StandardCharsets.UTF_8); // Linux / 无 GUI:优先无头;与登录后切无头策略一致 boolean preferHeadless = properties.isHeadless() || properties.isChatHeadlessAfterLogin(); if (!restoreFromStorageState(statePath.toString(), preferHeadless)) { ready = false; if (ChatReadyProbe.isAuthExpired(page)) { throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "已写入 storageState 但仍未登录,请确认文件来自本系统成功登录后的导出且未过期"); } throw new BusinessException(ErrorCodes.CHAT_NOT_READY, "已写入 storageState 但聊天页未就绪,请重新在有 GUI 环境登录后再导入"); } return dumpCookies(); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "导入 storageState 失败: " + e.getMessage(), e); } } } /** * 当前页面 URL(诊断用)。 */ public String currentPageUrl() { synchronized (lock) { try { return page == null || page.isClosed() ? null : page.url(); } catch (Exception e) { return null; } } } private void safeClose(AutoCloseable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (Exception ignored) { } } @Override public String openNewChat() { synchronized (lock) { ensureReadyInternal(); try { page.navigate(properties.getChatUrl()); page.waitForLoadState(LoadState.DOMCONTENTLOADED); if (!waitUntilChatReady(15000)) { if (ChatReadyProbe.isAuthExpired(page)) { ready = false; throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "登录已失效,请到接口设置重新登录"); } throw new BusinessException(ErrorCodes.CHAT_NOT_READY, "聊天页未就绪,无法开启新对话"); } clickIfPresent("text=开启新对话"); clickIfPresent("text=新对话"); clickIfPresent("button:has-text('新对话')"); clickIfPresent("button:has-text('New chat')"); page.waitForTimeout(800); String chatId = extractChatIdFromUrl(); return chatId == null ? "local-" + UUID.randomUUID() : chatId; } catch (BusinessException e) { throw e; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "开启新对话失败: " + e.getMessage(), e); } } } @Override public void syncSwitches(String deepseekChatId, boolean deepThinking, boolean smartSearch) { synchronized (lock) { ensureReadyInternal(); try { if (deepseekChatId != null && !deepseekChatId.isBlank() && !deepseekChatId.startsWith("local-")) { page.navigate(properties.getChatUrl() + "a/chat/s/" + deepseekChatId); page.waitForLoadState(LoadState.DOMCONTENTLOADED); } if (!waitUntilChatReady(12000)) { throw new BusinessException(ErrorCodes.CHAT_NOT_READY, "切换失败"); } page.waitForTimeout(400); Exception last = null; for (int attempt = 1; attempt <= 3; attempt++) { try { syncSwitchesInternal(deepThinking, smartSearch); return; } catch (BusinessException e) { last = e; log.warn("syncSwitches attempt {} failed: {}", attempt, e.getMessage()); page.waitForTimeout(600L * attempt); waitUntilChatReady(5000); } } if (last instanceof BusinessException be) { throw be; } throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "切换失败"); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "同步开关失败: " + e.getMessage(), e); } } } @Override public SwitchState readSwitches() { synchronized (lock) { try { ensureReadyInternal(); if (!waitUntilChatReady(12000)) { log.warn("readSwitches: chat not ready"); return SwitchState.unreadable(); } page.waitForTimeout(300); Boolean think = readSwitchStateByLabels("深度思考", "DeepThink", "深度思考模式"); Boolean search = readSwitchStateByLabels( "智能搜索", "联网搜索", "Search the web", "Web Search", "联网"); SwitchState state = new SwitchState(); state.setDeepThinking(think); state.setSmartSearch(search); // 智能搜索为必读项;深度思考可读则一并带回 state.setReadable(search != null); return state; } catch (BusinessException e) { log.warn("readSwitches business: {}", e.getMessage()); return SwitchState.unreadable(); } catch (Exception e) { log.warn("readSwitches failed: {}", e.getMessage()); return SwitchState.unreadable(); } } } private void syncSwitchesInternal(boolean deepThinking, boolean smartSearch) { // 深度思考:完整文案优先 boolean thinkOk = ensureSwitchTo(deepThinking, "深度思考", "DeepThink", "深度思考模式"); // 智能搜索:禁止单独用「Search」「搜索」宽泛匹配 boolean searchOk = ensureSwitchTo(smartSearch, "智能搜索", "联网搜索", "Search the web", "Web Search", "联网"); if (!thinkOk && !searchOk) { throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "切换失败"); } if (!searchOk) { log.warn("Smart search switch sync failed (deepThinkingOk={})", thinkOk); throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "切换失败"); } if (!thinkOk) { log.warn("Deep thinking switch sync failed (smartSearchOk={})", searchOk); throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "切换失败"); } } /** * 先读网页默认/当前态,仅当与目标不一致时点击,再读回校验。 */ private boolean ensureSwitchTo(boolean enable, String... labels) { for (int attempt = 1; attempt <= 3; attempt++) { SwitchHit hit = findSwitchHit(labels); if (hit == null) { log.debug("switch not found attempt {} labels={}", attempt, String.join(",", labels)); page.waitForTimeout(400L * attempt); continue; } if (hit.state != null && hit.state == enable) { log.debug("switch already at target enable={} label={}", enable, hit.label); return true; } if (hit.state == null) { log.debug("switch state unknown for {}, click and verify, target={}", hit.label, enable); } clickSwitch(hit); page.waitForTimeout(400); Boolean after = readSwitchStateByLabel(hit.label); if (after == null) { after = readSwitchStateByLabels(labels); } if (after != null && after == enable) { return true; } clickSwitch(hit); page.waitForTimeout(400); after = readSwitchStateByLabels(labels); if (after != null && after == enable) { return true; } // 状态仍不可读:短暂再探,不立刻判死 if (after == null) { page.waitForTimeout(500); after = readSwitchStateByLabels(labels); if (after != null && after == enable) { return true; } if (after == null && attempt < 3) { continue; } } } return false; } private SwitchHit findSwitchHit(String... labels) { for (String label : labels) { if (label == null || label.isBlank()) { continue; } // 拒绝过短宽泛词单独定位 if (label.length() <= 2) { continue; } Boolean state = readSwitchStateByLabel(label); boolean exists = switchElementExists(label); if (exists) { return new SwitchHit(label, state); } } return null; } private boolean switchElementExists(String name) { try { Object result = page.evaluate(""" (name) => { const nodes = Array.from(document.querySelectorAll( 'button,[role="switch"],[role="button"],label,[class*="switch"],[class*="toggle"]' )); return nodes.some(n => { const t = (n.innerText || n.textContent || '').replace(/\\s+/g, ' ').trim(); return t === name || t.startsWith(name + ' ') || t.startsWith(name); }); } """, name); return Boolean.TRUE.equals(result) || "true".equalsIgnoreCase(String.valueOf(result)); } catch (Exception e) { return false; } } private Boolean readSwitchStateByLabels(String... labels) { for (String label : labels) { Boolean s = readSwitchStateByLabel(label); if (s != null) { return s; } } return null; } private Boolean readSwitchStateByLabel(String name) { try { Object result = page.evaluate(""" (name) => { const nodes = Array.from(document.querySelectorAll( 'button,[role="switch"],[role="button"],label,[class*="switch"],[class*="toggle"]' )); const hit = nodes.find(n => { const t = (n.innerText || n.textContent || '').replace(/\\s+/g, ' ').trim(); return t === name || t.startsWith(name + ' ') || t.startsWith(name); }); if (!hit) return null; const el = hit.closest('button,[role="switch"],[role="button"],[class*="switch"],[class*="toggle"]') || hit; const pressed = el.getAttribute('aria-pressed') || el.getAttribute('aria-checked'); if (pressed === 'true') return true; if (pressed === 'false') return false; const ds = el.getAttribute('data-state') || el.getAttribute('data-checked'); if (ds === 'on' || ds === 'checked' || ds === 'true') return true; if (ds === 'off' || ds === 'unchecked' || ds === 'false') return false; const cls = String(el.className || ''); // 同时含 on/off 时以更明确的 token 为准 const onLike = /(?:^|[\\s_-])(active|selected|checked|on|enabled|open)(?:[\\s_-]|$)/i.test(cls); const offLike = /(?:^|[\\s_-])(inactive|unchecked|off|disabled|closed)(?:[\\s_-]|$)/i.test(cls); if (onLike && !offLike) return true; if (offLike && !onLike) return false; // 无法判断:返回 null,禁止当成 false return null; } """, name); if (result == null || "null".equals(String.valueOf(result))) { return null; } if (result instanceof Boolean b) { return b; } return Boolean.parseBoolean(String.valueOf(result)); } catch (Exception e) { return null; } } private void clickSwitch(SwitchHit hit) { try { page.evaluate(""" (name) => { const nodes = Array.from(document.querySelectorAll( 'button,[role="switch"],[role="button"],label,[class*="switch"],[class*="toggle"]' )); const hit = nodes.find(n => { const t = (n.innerText || n.textContent || '').replace(/\\s+/g, ' ').trim(); return t === name || t.startsWith(name + ' ') || t.startsWith(name); }); if (!hit) return false; const el = hit.closest('button,[role="switch"],[role="button"]') || hit; el.click(); return true; } """, hit.label); } catch (Exception e) { log.debug("click switch {} failed: {}", hit.label, e.getMessage()); } } private static final class SwitchHit { final String label; final Boolean state; SwitchHit(String label, Boolean state) { this.label = label; this.state = state; } } /** * 调试:显示或隐藏浏览器窗口(storageState 切换 headed/headless)。 * * @return browser_mode 常量 */ public int setBrowserVisible(boolean visible) { synchronized (lock) { if (!ready || context == null || page == null || page.isClosed()) { throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "请先完成 DeepSeek 登录"); } boolean wantHeadless = !visible; if (browserHeadless != null && browserHeadless == wantHeadless) { return visible ? DeepSeekLoginStages.BROWSER_HEADED_CHAT : DeepSeekLoginStages.BROWSER_HEADLESS_CHAT; } Path statePath = Path.of(properties.getStorageStatePath()); Browser oldBrowser = this.browser; BrowserContext oldContext = this.context; try { Path parent = statePath.getParent(); if (parent != null) { Files.createDirectories(parent); } context.storageState(new BrowserContext.StorageStateOptions().setPath(statePath)); ensurePlaywright(); Browser newBrowser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(wantHeadless)); BrowserContext newContext = newBrowser.newContext(new Browser.NewContextOptions() .setStorageStatePath(statePath) .setLocale("zh-CN") .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")); Page newPage = newContext.newPage(); newPage.setDefaultTimeout(properties.getTimeoutMs()); newPage.navigate(properties.getChatUrl()); newPage.waitForLoadState(LoadState.DOMCONTENTLOADED); this.browser = newBrowser; this.context = newContext; this.page = newPage; this.browserHeadless = wantHeadless; if (!waitUntilChatReady(25000)) { log.warn("setBrowserVisible chatReady failed, rollback"); safeClose(newContext); safeClose(newBrowser); this.browser = oldBrowser; this.context = oldContext; this.page = oldContext.pages().isEmpty() ? oldContext.newPage() : oldContext.pages().get(0); this.browserHeadless = !wantHeadless; ready = ChatReadyProbe.isChatReady(page); throw new BusinessException(ErrorCodes.HEADLESS_SWITCH_FAILED, "切换浏览器显示失败,已保持原状态"); } // 额外稳定等待,避免紧接着发送/切开关必失败 page.waitForTimeout(1200); if (!waitUntilChatReady(8000)) { log.warn("setBrowserVisible post-stabilize chatReady weak"); } ready = ChatReadyProbe.isChatReady(page); if (!ready) { safeClose(newContext); safeClose(newBrowser); this.browser = oldBrowser; this.context = oldContext; this.page = oldContext.pages().isEmpty() ? oldContext.newPage() : oldContext.pages().get(0); this.browserHeadless = !wantHeadless; ready = ChatReadyProbe.isChatReady(page); throw new BusinessException(ErrorCodes.HEADLESS_SWITCH_FAILED, "切换浏览器显示失败,已保持原状态"); } safeClose(oldContext); if (oldBrowser != null && oldBrowser != newBrowser) { safeClose(oldBrowser); } return visible ? DeepSeekLoginStages.BROWSER_HEADED_CHAT : DeepSeekLoginStages.BROWSER_HEADLESS_CHAT; } catch (BusinessException e) { throw e; } catch (Exception e) { this.browser = oldBrowser; this.context = oldContext; if (oldContext != null && !oldContext.pages().isEmpty()) { this.page = oldContext.pages().get(0); } throw new BusinessException(ErrorCodes.HEADLESS_SWITCH_FAILED, "切换浏览器显示失败: " + e.getMessage()); } } } private void waitSignInForm(int timeoutMs) { long deadline = System.currentTimeMillis() + timeoutMs; while (System.currentTimeMillis() < deadline) { for (String sel : SIGN_IN_ROOT) { if (page.locator(sel).count() > 0) { return; } } if (page.locator("input[type='password']").count() > 0 || page.locator("text=密码登录").count() > 0 || page.locator("text=Password").count() > 0) { return; } page.waitForTimeout(300); } } private boolean switchToPasswordLogin() { String[] selectors = { "text=密码登录", "a:has-text('密码登录')", "button:has-text('密码登录')", "div:has-text('密码登录')", "text=邮箱登录", "text=Password", "text=Log in with password", "text=账号密码登录" }; for (String sel : selectors) { try { if (page.locator(sel).count() > 0) { page.locator(sel).first().click(new Locator.ClickOptions().setTimeout(2500)); page.waitForTimeout(600); if (page.locator("input[type='password']").count() > 0) { return true; } } } catch (Exception e) { log.debug("switch password via {} failed: {}", sel, e.getMessage()); } } return page.locator("input[type='password']").count() > 0; } private Locator resolveFormRoot() { for (String sel : SIGN_IN_ROOT) { if (page.locator(sel).count() > 0) { return page.locator(sel).first(); } } return page.locator("body"); } private void fillAccount(Locator form, String account) { String[] sels = { "input[autocomplete='username']", "input[type='email']", "input[placeholder*='邮箱']", "input[placeholder*='手机']", "input[placeholder*='Email']", "input[placeholder*='email']", "input[placeholder*='Phone']", "input[type='text']" }; for (String sel : sels) { try { Locator loc = form.locator(sel); if (loc.count() > 0) { loc.first().waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.VISIBLE).setTimeout(4000)); loc.first().fill(account); return; } } catch (Exception e) { log.debug("fill account {} skip: {}", sel, e.getMessage()); } } throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "未找到账号输入框,可改用方案2"); } private void fillPassword(Locator form, String password) { Locator loc = form.locator("input[autocomplete='current-password'], input[type='password']"); if (loc.count() == 0) { loc = page.locator("input[type='password']"); } if (loc.count() == 0) { throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "未找到密码输入框,请确认已切换密码登录"); } loc.first().fill(password); } private void clickLogin(Locator form) { String[] sels = { "button.ds-basic-button--primary", "button:has-text('登录')", "button:has-text('Log in')", "button:has-text('Sign in')", "button[type='submit']" }; for (String sel : sels) { try { Locator loc = form.locator(sel); if (loc.count() == 0) { loc = page.locator(sel); } if (loc.count() > 0) { loc.first().click(new Locator.ClickOptions().setTimeout(3000)); return; } } catch (Exception e) { log.debug("click login {} skip: {}", sel, e.getMessage()); } } page.keyboard().press("Enter"); } private void ensurePlaywright() { if (playwright == null) { playwright = Playwright.create(); } } private void ensureHeadedBrowser() { ensurePlaywright(); // 方案2「打开登录窗口」必须有头;配置无头时明确拒绝,避免在无 DISPLAY 的 Linux 上静默失败 if (properties.isHeadless()) { throw new BusinessException(ErrorCodes.PARAM_INVALID, "当前 dsapi.deepseek.headless=true,无法打开可视登录窗口。" + "无 GUI 服务器请用「高级:粘贴 Cookie JSON」;" + "若要弹窗登录请设 headless=false,并准备 DISPLAY 或 xvfb-run。"); } if (browser != null && Boolean.FALSE.equals(browserHeadless)) { return; } if (browser != null) { try { browser.close(); } catch (Exception ignored) { } browser = null; context = null; page = null; ready = false; } try { browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false)); browserHeadless = false; } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "启动有头浏览器失败(常见于无桌面 Linux)。请改用 Cookie 粘贴,或安装 Xvfb 后用 " + "xvfb-run java -jar ... 启动。详情: " + e.getMessage(), e); } } private void ensureBrowser(boolean headless) { try { ensurePlaywright(); if (browser != null && browserHeadless != null && browserHeadless != headless) { try { browser.close(); } catch (Exception ignored) { } browser = null; context = null; page = null; ready = false; } if (browser == null) { browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(headless)); browserHeadless = headless; } if (context == null) { context = browser.newContext(new Browser.NewContextOptions() .setLocale("zh-CN") .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")); } if (page == null || page.isClosed()) { page = context.newPage(); page.setDefaultTimeout(properties.getTimeoutMs()); } } catch (Exception e) { throw new SystemException(ErrorCodes.SYSTEM_ERROR, "启动 Playwright 失败,请执行: mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args=\"install chromium\". 详情: " + e.getMessage(), e); } } private void ensureReadyInternal() { if (!ready || page == null || page.isClosed()) { throw new BusinessException(ErrorCodes.DEEPSEEK_NOT_READY, "DeepSeek 未登录或会话失效,请到接口设置重新登录"); } } private boolean pageContentBlocked() { try { String content = page.content(); String title = page.title(); return (content != null && (content.contains("403 ERROR") || content.contains("Request blocked") || content.contains("CloudFront"))) || (title != null && title.contains("403")); } catch (Exception e) { return false; } } private boolean looksLikeCaptcha() { try { return page.locator("iframe[src*='captcha']").count() > 0 || page.locator("iframe[src*='geetest']").count() > 0 || page.locator("[class*='captcha']").count() > 0 || page.locator("[class*='Captcha']").count() > 0 || page.locator("text=验证").count() > 0 || page.locator("text=滑块").count() > 0 || page.locator("canvas").count() > 0; } catch (Exception e) { return false; } } private boolean isLoggedIn() { return isLoggedIn(page); } private boolean isLoggedIn(Page p) { try { if (p == null || p.isClosed()) { return false; } String url = p.url(); if (url != null && url.contains("chat.deepseek.com") && !url.contains("sign_in") && !url.contains("sign-in")) { if (p.locator("textarea").count() > 0 || p.locator("[contenteditable='true']").count() > 0) { return true; } // 已离开登录页也视为接近成功 if (!url.contains("/sign")) { return p.locator("textarea").count() > 0; } } return p.locator("textarea[placeholder*='Message']").count() > 0 || p.locator("textarea").count() > 0; } catch (Exception e) { return false; } } private String dumpCookies() throws Exception { return cookiesToJson(context.cookies()); } private String cookiesToJson(List cookies) throws Exception { List> list = new ArrayList<>(); for (Cookie c : cookies) { list.add(Map.of( "name", c.name, "value", c.value, "domain", c.domain == null ? ".deepseek.com" : c.domain, "path", c.path == null ? "/" : c.path )); } return objectMapper.writeValueAsString(list); } private void fillChatInput(String content) { Locator input = ChatReadyProbe.findChatInput(page); if (input == null) { // 再等一会,SPA 可能晚渲染 if (waitUntilChatReady(8000)) { input = ChatReadyProbe.findChatInput(page); } } if (input == null) { throw new BusinessException(ErrorCodes.CHAT_INPUT_NOT_FOUND, "未找到聊天输入框"); } try { input.click(new Locator.ClickOptions().setTimeout(3000)); input.fill(content); } catch (Exception e) { try { input.click(); page.keyboard().type(content); } catch (Exception e2) { throw new BusinessException(ErrorCodes.CHAT_INPUT_NOT_FOUND, "无法向输入框填入内容: " + e.getMessage()); } } } private void clickSend() { clickIfPresent("button:has-text('发送')"); try { page.keyboard().press("Enter"); } catch (Exception ignored) { } } private String readLastAssistantText() { try { Object result = page.evaluate(""" () => { const nodes = Array.from(document.querySelectorAll('[class*="message"],[class*="markdown"],.ds-markdown')); if (!nodes.length) return null; return (nodes[nodes.length - 1].innerText || '').trim(); } """); return result == null ? null : String.valueOf(result); } catch (Exception e) { return null; } } private boolean isGenerationSettled() { try { return page.locator("button:has-text('停止')").count() == 0; } catch (Exception e) { return true; } } private String extractChatIdFromUrl() { String url = page.url(); int idx = url.indexOf("/a/chat/s/"); if (idx < 0) { return null; } String rest = url.substring(idx + "/a/chat/s/".length()); int end = rest.length(); for (int i = 0; i < rest.length(); i++) { char ch = rest.charAt(i); if (ch == '/' || ch == '?') { end = i; break; } } return rest.substring(0, end); } private void clickIfPresent(String selector) { try { if (page.locator(selector).count() > 0) { page.locator(selector).first().click(new Locator.ClickOptions().setTimeout(2000)); } } catch (Exception e) { log.debug("clickIfPresent {} skipped", selector); } } private LoginResult ok(String payload, String stage, String pageUrl, String message) { return new LoginResult("SUCCESS", message, null, null, payload, stage, pageUrl, null); } private LoginResult fail(String stage, String pageUrl, String message, String hint) { String status = DeepSeekLoginStages.BLOCKED.equals(stage) ? "BLOCKED" : "FAILED"; return new LoginResult(status, message, null, null, null, stage, pageUrl, hint); } private String safeUrl() { return safeUrl(page); } private String safeUrl(Page p) { try { return p == null ? "" : p.url(); } catch (Exception e) { return ""; } } public void markNotReady() { this.ready = false; } public String currentSessionPayload() { synchronized (lock) { try { if (context == null) { return null; } return dumpCookies(); } catch (Exception e) { return null; } } } @PreDestroy public void destroy() { synchronized (lock) { for (String id : new ArrayList<>(scheme2Jobs.keySet())) { closeScheme2JobQuietly(id); } try { if (context != null) { context.close(); } } catch (Exception ignored) { } try { if (browser != null) { browser.close(); } } catch (Exception ignored) { } try { if (playwright != null) { playwright.close(); } } catch (Exception ignored) { } } } }