Claude Session Key 管理器

Claude Session Key 管理工具,支持拖拽、测活、批量导入导出、WebDAV云备份等功能

目前为 2025-03-09 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Claude Session Key 管理器
  3. // @name:zh-CN Claude Session Key 管理器
  4. // @name:en Claude Session Key Manager
  5. // @version 1.0.1
  6. // @description Claude Session Key 管理工具,支持拖拽、测活、导入导出、WebDAV云备份等功能
  7. // @description:zh-CN Claude Session Key 管理工具,支持拖拽、测活、批量导入导出、WebDAV云备份等功能
  8. // @description:en Claude Session Key Manager with drag-and-drop, token validation, import/export, WebDAV backup and more
  9. // @author xiaoye6688
  10. // @namespace https://gf.qytechs.cn/users/1317128-xiaoye6688
  11. // @homepage https://gf.qytechs.cn/zh-CN/users/1317128-xiaoye6688
  12. // @supportURL https://gf.qytechs.cn/zh-CN/users/1317128-xiaoye6688
  13. // @license MIT
  14. // @date 2025-03-09
  15. // @modified 2025-03-09
  16.  
  17. // @match https://claude.ai/*
  18. // @match https://claude.asia/*
  19. // @match https://demo.fuclaude.com/*
  20. // @include https://*fuclaude*/*
  21. //
  22. // @icon https://claude.ai/favicon.ico
  23. // @run-at document-end
  24.  
  25. // @grant GM_xmlhttpRequest
  26. // @grant GM_setValue
  27. // @grant GM_getValue
  28. // @grant GM_deleteValue
  29. // @grant GM_addStyle
  30. // @grant GM_registerMenuCommand
  31. // @grant GM_unregisterMenuCommand
  32. // @grant GM_info
  33.  
  34. // @connect ipapi.co
  35. // @connect api.claude.ai
  36. // @connect *
  37. // ==/UserScript==
  38.  
  39. (function () {
  40. "use strict";
  41.  
  42. const config = {
  43. storageKey: "claudeTokens",
  44. ipApiUrl: "https://ipapi.co/country_code",
  45. defaultToken: {
  46. name: "Token00",
  47. key: "sk-key",
  48. },
  49. currentTokenKey: "currentClaudeToken",
  50. testResultsKey: "claudeTokenTestResults",
  51. testResultExpiry: 1800000, // 30分钟过期
  52. };
  53.  
  54. const theme = {
  55. light: {
  56. bgColor: "#fcfaf5",
  57. textColor: "#333",
  58. borderColor: "#ccc",
  59. buttonBg: "#f5f1e9",
  60. buttonHoverBg: "#e5e1d9",
  61. modalBg: "rgba(0, 0, 0, 0.5)",
  62. },
  63. dark: {
  64. bgColor: "#2c2b28",
  65. textColor: "#f5f4ef",
  66. borderColor: "#3f3f3c",
  67. buttonBg: "#3f3f3c",
  68. buttonHoverBg: "#4a4a47",
  69. modalBg: "rgba(0, 0, 0, 0.7)",
  70. },
  71. };
  72.  
  73. const getStyles = (isDarkMode) => `
  74. :root {
  75. --bg-color: ${isDarkMode ? theme.dark.bgColor : theme.light.bgColor};
  76. --text-color: ${isDarkMode ? theme.dark.textColor : theme.light.textColor};
  77. --border-color: ${isDarkMode ? theme.dark.borderColor : theme.light.borderColor};
  78. --button-bg: ${isDarkMode ? theme.dark.buttonBg : theme.light.buttonBg};
  79. --button-hover-bg: ${isDarkMode ? theme.dark.buttonHoverBg : theme.light.buttonHoverBg};
  80. --modal-bg: ${isDarkMode ? theme.dark.modalBg : theme.light.modalBg};
  81. }
  82. /* 浮动按钮样式 */
  83. #claude-toggle-button {
  84. width: 40px;
  85. height: 40px;
  86. border-radius: 50%;
  87. background-color: var(--bg-color);
  88. color: #b3462f;
  89. cursor: move;
  90. position: fixed;
  91. z-index: 10000;
  92. display: flex;
  93. align-items: center;
  94. justify-content: center;
  95. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  96. transition: background-color 0.3s ease, transform 0.2s ease;
  97. outline: none;
  98. padding: 0;
  99. user-select: none;
  100. touch-action: none;
  101. border: 1px solid var(--border-color);
  102. font-size: 18px;
  103. }
  104. #claude-toggle-button:hover {
  105. transform: scale(1.1);
  106. box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
  107. }
  108. /* 下拉容器样式 */
  109. .claude-dropdown-container {
  110. position: fixed;
  111. background-color: var(--bg-color);
  112. padding: 20px;
  113. border-radius: 12px;
  114. box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  115. display: none;
  116. flex-direction: column;
  117. gap: 0; /* 移除flex布局产生的空隙 */
  118. width: 600px;
  119. max-height: 80vh;
  120. overflow-y: auto;
  121. z-index: 9999;
  122. border: 1px solid var(--border-color);
  123. opacity: 0;
  124. transform: scale(0.95);
  125. transition: opacity 0.3s ease, transform 0.3s ease;
  126. scrollbar-gutter: stable; /* 保持滚动条空间稳定 */
  127. scrollbar-width: thin; /* Firefox滚动条样式 */
  128. scrollbar-color: ${isDarkMode ? "rgba(255, 255, 255, 0.2) transparent" : "rgba(0, 0, 0, 0.2) transparent"};
  129. }
  130. /* 标题容器 */
  131. .claude-title-container {
  132. display: flex;
  133. justify-content: space-between;
  134. align-items: center;
  135. padding-bottom: 10px;
  136. }
  137. .claude-title-container h2 {
  138. margin: 0;
  139. color: var(--text-color);
  140. font-size: 18px;
  141. font-weight: 600;
  142. }
  143. .claude-ip-display {
  144. font-size: 14px;
  145. color: var(--text-color);
  146. padding: 4px 10px;
  147. background-color: var(--button-bg);
  148. border-radius: 12px;
  149. }
  150. /* Token 网格容器 */
  151. .claude-token-grid {
  152. display: grid;
  153. grid-template-columns: repeat(2, 1fr);
  154. gap: 12px;
  155. max-height: calc(2 * (90px + 12px) + 24px); /* 两行token的高度加上间隙和padding */
  156. overflow-y: auto;
  157. padding: 12px 0 12px 12px;
  158. scrollbar-gutter: stable; /* 保持滚动条空间稳定,防止出现时推动内容 */
  159. border: 1px solid var(--border-color);
  160. border-radius: 8px;
  161. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.03)" : "rgba(0, 0, 0, 0.02)"};
  162. /* Firefox滚动条样式支持 */
  163. scrollbar-width: thin;
  164. scrollbar-color: ${isDarkMode ? "rgba(255, 255, 255, 0.2) transparent" : "rgba(0, 0, 0, 0.2) transparent"};
  165. }
  166. /* Token 卡片样式 */
  167. .claude-token-item {
  168. padding: 15px;
  169. border-radius: 8px;
  170. background-color: var(--bg-color);
  171. border: 1px solid var(--border-color);
  172. cursor: pointer;
  173. transition: all 0.3s ease;
  174. position: relative;
  175. height: 90px; /* 固定高度 */
  176. box-sizing: border-box; /* 确保padding不会增加总高度 */
  177. display: flex;
  178. flex-direction: column;
  179. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  180. }
  181. .claude-token-item:hover {
  182. transform: translateY(-2px);
  183. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  184. border-color: ${isDarkMode ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.2)"};
  185. }
  186. .claude-token-item.current-token {
  187. border: 2px solid #b3462f;
  188. background-color: ${isDarkMode ? "rgba(179, 70, 47, 0.1)" : "rgba(179, 70, 47, 0.05)"};
  189. position: relative;
  190. }
  191. .current-token-badge {
  192. position: absolute;
  193. top: -8px;
  194. left: 8px;
  195. background-color: #b3462f;
  196. width: 20px;
  197. height: 20px;
  198. border-radius: 50%;
  199. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  200. display: flex;
  201. align-items: center;
  202. justify-content: center;
  203. }
  204. .current-token-badge::after {
  205. content: "";
  206. display: block;
  207. width: 10px;
  208. height: 10px;
  209. border-radius: 50%;
  210. background-color: white;
  211. }
  212. /* Token 内容样式 */
  213. .token-info {
  214. display: flex;
  215. flex-direction: column;
  216. gap: 8px;
  217. flex: 1; /* 填充可用空间 */
  218. justify-content: space-between; /* 顶部行和底部行分别位于容器顶部和底部 */
  219. }
  220. .token-top-row {
  221. display: flex;
  222. align-items: center;
  223. justify-content: space-between;
  224. }
  225. .token-name-container {
  226. display: flex;
  227. align-items: center;
  228. gap: 8px;
  229. }
  230. .token-number {
  231. padding: 2px 8px;
  232. border-radius: 12px;
  233. font-size: 12px;
  234. background-color: var(--button-bg);
  235. }
  236. .token-name {
  237. font-weight: 500;
  238. font-size: 14px;
  239. }
  240. .token-actions {
  241. display: flex;
  242. gap: 8px;
  243. }
  244. .token-action-btn {
  245. background: transparent;
  246. border: none;
  247. cursor: pointer;
  248. padding: 4px;
  249. border-radius: 4px;
  250. display: flex;
  251. align-items: center;
  252. justify-content: center;
  253. color: var(--text-color);
  254. transition: all 0.2s ease;
  255. }
  256. .token-action-btn:hover {
  257. background-color: var(--button-hover-bg);
  258. transform: scale(1.1);
  259. }
  260. .token-action-btn.delete-btn {
  261. color: #e24a4a;
  262. }
  263. .token-bottom-row {
  264. display: flex;
  265. align-items: center;
  266. justify-content: space-between;
  267. }
  268. .token-status {
  269. display: flex;
  270. align-items: center;
  271. gap: 6px;
  272. margin-left: auto;
  273. }
  274. .status-indicator {
  275. width: 10px;
  276. height: 10px;
  277. border-radius: 50%;
  278. background-color: #888;
  279. }
  280. .status-indicator.success {
  281. background-color: #48bb78;
  282. }
  283. .status-indicator.error {
  284. background-color: #e53e3e;
  285. }
  286. .status-indicator.loading {
  287. background-color: #888;
  288. animation: pulse 1.5s infinite;
  289. }
  290. @keyframes pulse {
  291. 0% { opacity: 0.4; }
  292. 50% { opacity: 1; }
  293. 100% { opacity: 0.4; }
  294. }
  295. .token-time {
  296. font-size: 12px;
  297. color: var(--text-color);
  298. opacity: 0.7;
  299. }
  300. /* 按钮容器 */
  301. .claude-button-container {
  302. display: grid;
  303. grid-template-columns: repeat(3, 1fr);
  304. gap: 8px;
  305. padding-top: 12px;
  306. }
  307. .claude-button {
  308. padding: 8px 10px;
  309. border: none;
  310. border-radius: 6px;
  311. cursor: pointer;
  312. transition: all 0.2s ease;
  313. font-size: 13px;
  314. font-weight: 500;
  315. display: flex;
  316. align-items: center;
  317. justify-content: center;
  318. gap: 4px;
  319. white-space: nowrap;
  320. overflow: hidden;
  321. text-overflow: ellipsis;
  322. position: relative;
  323. }
  324. .claude-button:hover {
  325. transform: translateY(-2px);
  326. }
  327. .claude-button.primary {
  328. background-color: #b3462f;
  329. color: white;
  330. }
  331. .claude-button.primary:hover {
  332. background-color: #a03d2a;
  333. }
  334. .claude-button.secondary {
  335. background-color: var(--button-bg);
  336. color: var(--text-color);
  337. }
  338. .claude-button.secondary:hover {
  339. background-color: var(--button-hover-bg);
  340. }
  341. /* 工具提示样式 */
  342. .claude-button[data-tooltip]:hover::after {
  343. content: attr(data-tooltip);
  344. position: absolute;
  345. bottom: 100%;
  346. left: 50%;
  347. transform: translateX(-50%);
  348. background-color: rgba(0, 0, 0, 0.8);
  349. color: white;
  350. padding: 5px 10px;
  351. border-radius: 4px;
  352. font-size: 12px;
  353. white-space: nowrap;
  354. z-index: 10001;
  355. margin-bottom: 5px;
  356. pointer-events: none;
  357. opacity: 0;
  358. animation: tooltip-fade-in 0.2s ease forwards;
  359. }
  360. @keyframes tooltip-fade-in {
  361. from { opacity: 0; transform: translate(-50%, 5px); }
  362. to { opacity: 1; transform: translate(-50%, 0); }
  363. }
  364. /* 模态框样式 */
  365. .claude-modal {
  366. position: fixed;
  367. top: 0;
  368. left: 0;
  369. width: 100%;
  370. height: 100%;
  371. background-color: var(--modal-bg);
  372. display: flex;
  373. justify-content: center;
  374. align-items: center;
  375. z-index: 10001;
  376. }
  377. .claude-modal-content {
  378. background-color: var(--bg-color);
  379. padding: 20px;
  380. padding-right: 14px; /* 右侧padding稍微增加,为滚动条预留空间但不过多 */
  381. border-radius: 8px;
  382. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  383. width: 500px;
  384. max-width: 90%;
  385. overflow-y: auto;
  386. position: relative;
  387. scrollbar-gutter: stable; /* 保持滚动条空间稳定 */
  388. scrollbar-width: thin; /* Firefox滚动条样式 */
  389. scrollbar-color: ${isDarkMode ? "rgba(255, 255, 255, 0.2) transparent" : "rgba(0, 0, 0, 0.2) transparent"};
  390. }
  391. .claude-modal-content.narrow-modal {
  392. width: 400px;
  393. max-width: 80%;
  394. }
  395. .claude-modal h2 {
  396. margin-top: 0;
  397. margin-bottom: 15px;
  398. color: var(--text-color);
  399. font-size: 18px;
  400. font-weight: 600;
  401. }
  402. .claude-modal input, .claude-modal textarea {
  403. width: 100%;
  404. padding: 10px;
  405. margin-bottom: 15px;
  406. border: 1px solid var(--border-color);
  407. border-radius: 4px;
  408. font-size: 14px;
  409. background-color: var(--bg-color);
  410. color: var(--text-color);
  411. }
  412. .claude-modal-buttons {
  413. display: flex;
  414. justify-content: flex-end;
  415. gap: 10px;
  416. margin-top: 15px;
  417. }
  418. .claude-close-button {
  419. position: absolute;
  420. top: 10px;
  421. right: 10px;
  422. background: none;
  423. border: none;
  424. font-size: 20px;
  425. cursor: pointer;
  426. color: var(--text-color);
  427. padding: 5px;
  428. line-height: 1;
  429. }
  430. /* 自定义滚动条样式 */
  431. .claude-token-grid::-webkit-scrollbar {
  432. width: 6px;
  433. /* 初始状态下滚动条透明 */
  434. background-color: transparent;
  435. }
  436. .claude-token-grid::-webkit-scrollbar-track {
  437. background: transparent;
  438. margin: 4px 0;
  439. }
  440. .claude-token-grid::-webkit-scrollbar-thumb {
  441. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.15)"};
  442. border-radius: 6px;
  443. transition: background-color 0.3s ease;
  444. /* 初始状态下滚动条半透明 */
  445. opacity: 0.6;
  446. }
  447. .claude-token-grid::-webkit-scrollbar-thumb:hover {
  448. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)"};
  449. opacity: 1;
  450. }
  451. .claude-token-grid:hover::-webkit-scrollbar-thumb {
  452. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)"};
  453. opacity: 1;
  454. }
  455. /* 滚动条样式 */
  456. .claude-dropdown-container::-webkit-scrollbar,
  457. .claude-modal-content::-webkit-scrollbar {
  458. width: 6px;
  459. background-color: transparent;
  460. }
  461. .claude-dropdown-container::-webkit-scrollbar-track,
  462. .claude-modal-content::-webkit-scrollbar-track {
  463. background: transparent;
  464. margin: 4px 0;
  465. }
  466. .claude-dropdown-container::-webkit-scrollbar-thumb,
  467. .claude-modal-content::-webkit-scrollbar-thumb {
  468. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.15)" : "rgba(0, 0, 0, 0.15)"};
  469. border-radius: 6px;
  470. transition: background-color 0.3s ease;
  471. opacity: 0.6;
  472. }
  473. .claude-dropdown-container::-webkit-scrollbar-thumb:hover,
  474. .claude-modal-content::-webkit-scrollbar-thumb:hover {
  475. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)"};
  476. opacity: 1;
  477. }
  478. .claude-dropdown-container:hover::-webkit-scrollbar-thumb,
  479. .claude-modal-content:hover::-webkit-scrollbar-thumb {
  480. opacity: 1;
  481. }
  482. /* 预览容器 */
  483. .claude-preview-container {
  484. margin-top: 15px;
  485. max-height: 200px;
  486. overflow-y: auto;
  487. border: 1px solid var(--border-color);
  488. border-radius: 8px;
  489. padding: 15px;
  490. }
  491. .claude-preview-title {
  492. font-size: 16px;
  493. margin-bottom: 10px;
  494. color: var(--text-color);
  495. border-bottom: 1px solid var(--border-color);
  496. padding-bottom: 5px;
  497. }
  498. .claude-preview-item {
  499. margin-bottom: 8px;
  500. font-size: 14px;
  501. padding: 8px;
  502. border-radius: 4px;
  503. background-color: var(--button-bg);
  504. }
  505.  
  506. /* 滚动提示样式 */
  507. .scroll-indicator {
  508. grid-column: 1 / -1; /* 横跨所有列 */
  509. display: flex;
  510. align-items: center;
  511. justify-content: center;
  512. padding: 8px;
  513. margin-top: 5px;
  514. color: ${isDarkMode ? "rgba(255, 255, 255, 0.6)" : "rgba(0, 0, 0, 0.5)"};
  515. font-size: 12px;
  516. background-color: ${isDarkMode ? "rgba(255, 255, 255, 0.05)" : "rgba(0, 0, 0, 0.03)"};
  517. border-radius: 6px;
  518. gap: 8px;
  519. }
  520.  
  521. .scroll-arrow {
  522. animation: bounce 1.5s infinite;
  523. }
  524.  
  525. @keyframes bounce {
  526. 0%, 100% { transform: translateY(0); }
  527. 50% { transform: translateY(3px); }
  528. }
  529. `;
  530.  
  531. const UI = {
  532. createElem(tag, className = "", styles = {}) {
  533. const elem = document.createElement(tag);
  534. if (className) elem.className = className;
  535. Object.assign(elem.style, styles);
  536. return elem;
  537. },
  538.  
  539. createButton(text, className, icon = "") {
  540. const button = this.createElem("button", className);
  541. if (icon) {
  542. button.innerHTML = `${icon} ${text}`;
  543. } else {
  544. button.textContent = text;
  545. }
  546. return button;
  547. },
  548.  
  549. createModal(title, content, includeCloseButton = true) {
  550. const modal = this.createElem("div", "claude-modal");
  551. modal.setAttribute("aria-modal", "true");
  552. modal.setAttribute("role", "dialog");
  553.  
  554. const modalContent = this.createElem("div", "claude-modal-content");
  555.  
  556. const titleElem = this.createElem("h2");
  557. titleElem.textContent = title;
  558. modalContent.appendChild(titleElem);
  559.  
  560. if (includeCloseButton) {
  561. const closeButton = this.createElem("button", "claude-close-button");
  562. closeButton.textContent = "×";
  563. closeButton.addEventListener("click", () => document.body.removeChild(modal));
  564. modalContent.appendChild(closeButton);
  565. }
  566.  
  567. modalContent.appendChild(content);
  568.  
  569. const buttonContainer = this.createElem("div", "claude-modal-buttons");
  570. modalContent.appendChild(buttonContainer);
  571.  
  572. modal.appendChild(modalContent);
  573. document.body.appendChild(modal);
  574.  
  575. return {
  576. modal,
  577. buttonContainer,
  578. close: () => document.body.removeChild(modal),
  579. };
  580. },
  581. };
  582.  
  583. const App = {
  584. init() {
  585. this.isDarkMode = document.documentElement.getAttribute("data-mode") === "dark";
  586. this.injectStyles();
  587. this.tokens = this.loadTokens();
  588. this.createUI();
  589. this.setupEventListeners();
  590. this.observeThemeChanges();
  591.  
  592. // 获取保存的位置或使用默认值
  593. const savedPosition = {
  594. left: GM_getValue("buttonLeft", 10),
  595. bottom: GM_getValue("buttonBottom", 10)
  596. };
  597.  
  598. // 设置按钮位置
  599. this.toggleButton.style.left = `${savedPosition.left}px`;
  600. this.toggleButton.style.bottom = `${savedPosition.bottom}px`;
  601.  
  602. // 初始化拖拽状态
  603. this.isDragging = false;
  604. this.buttonLeft = savedPosition.left;
  605. this.buttonBottom = savedPosition.bottom;
  606.  
  607. // 获取IP信息
  608. this.fetchIPCountryCode();
  609. },
  610.  
  611. injectStyles() {
  612. this.styleElem = document.createElement("style");
  613. this.styleElem.textContent = getStyles(this.isDarkMode);
  614. document.head.appendChild(this.styleElem);
  615. },
  616.  
  617. updateStyles() {
  618. this.styleElem.textContent = getStyles(this.isDarkMode);
  619. },
  620.  
  621. loadTokens() {
  622. try {
  623. const savedTokens = GM_getValue(config.storageKey);
  624. let tokens = savedTokens && savedTokens.length > 0
  625. ? savedTokens
  626. : [config.defaultToken];
  627.  
  628. // 为没有创建时间的token添加默认值
  629. tokens = tokens.map(token => {
  630. if (!token.createdAt) {
  631. const now = new Date();
  632. return {
  633. ...token,
  634. createdAt: now.toLocaleString("zh-CN", {
  635. month: "2-digit",
  636. day: "2-digit",
  637. hour: "2-digit",
  638. minute: "2-digit",
  639. }),
  640. timestamp: now.getTime()
  641. };
  642. }
  643. return token;
  644. });
  645.  
  646. return tokens;
  647. } catch (error) {
  648. console.error("加载 tokens 失败:", error);
  649. return [config.defaultToken];
  650. }
  651. },
  652.  
  653. saveTokens() {
  654. try {
  655. GM_setValue(config.storageKey, this.tokens);
  656. } catch (error) {
  657. console.error("保存 tokens 失败:", error);
  658. alert("保存 tokens 失败,请重试。");
  659. }
  660. },
  661.  
  662. createUI() {
  663. // 创建浮动按钮
  664. this.toggleButton = UI.createElem("button", "claude-toggle-button", {
  665. left: "10px",
  666. bottom: "10px"
  667. });
  668. this.toggleButton.id = "claude-toggle-button";
  669. this.toggleButton.innerHTML = `
  670. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" pointer-events="none">
  671. <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" pointer-events="none"></path>
  672. </svg>
  673. `;
  674. document.body.appendChild(this.toggleButton);
  675.  
  676. // 创建下拉容器
  677. this.dropdownContainer = UI.createElem("div", "claude-dropdown-container");
  678. document.body.appendChild(this.dropdownContainer);
  679.  
  680. // 创建标题容器
  681. const titleContainer = UI.createElem("div", "claude-title-container");
  682.  
  683. const title = UI.createElem("h2");
  684. title.textContent = "Claude Session Key 管理器";
  685.  
  686. this.ipDisplay = UI.createElem("div", "claude-ip-display");
  687. this.ipDisplay.textContent = "IP: 加载中...";
  688.  
  689. titleContainer.appendChild(title);
  690. titleContainer.appendChild(this.ipDisplay);
  691. this.dropdownContainer.appendChild(titleContainer);
  692.  
  693. // 创建 Token 网格
  694. this.tokenGrid = UI.createElem("div", "claude-token-grid");
  695. this.dropdownContainer.appendChild(this.tokenGrid);
  696.  
  697. // 更新 Token 网格
  698. this.updateTokenGrid();
  699.  
  700. // 创建按钮容器
  701. const buttonContainer = UI.createElem("div", "claude-button-container");
  702.  
  703. // 测试所有按钮
  704. const testAllButton = UI.createButton("测活", "claude-button primary", "🔍");
  705. testAllButton.setAttribute("data-tooltip", "测试所有Token是否有效");
  706. testAllButton.addEventListener("click", () => this.testAllTokens());
  707. buttonContainer.appendChild(testAllButton);
  708.  
  709. // 清理无效按钮
  710. const cleanInvalidButton = UI.createButton("清理", "claude-button secondary", "🗑️");
  711. cleanInvalidButton.setAttribute("data-tooltip", "清理所有无效的Token");
  712. cleanInvalidButton.addEventListener("click", () => this.removeInvalidTokens());
  713. buttonContainer.appendChild(cleanInvalidButton);
  714.  
  715. // 添加 Token 按钮
  716. const addTokenButton = UI.createButton("添加", "claude-button secondary", "➕");
  717. addTokenButton.setAttribute("data-tooltip", "添加新的Token");
  718. addTokenButton.addEventListener("click", () => this.showAddTokenModal());
  719. buttonContainer.appendChild(addTokenButton);
  720.  
  721. // 批量导入按钮
  722. const importButton = UI.createButton("导入", "claude-button secondary", "📥");
  723. importButton.setAttribute("data-tooltip", "批量导入多个Token");
  724. importButton.addEventListener("click", () => this.showBulkImportModal());
  725. buttonContainer.appendChild(importButton);
  726.  
  727. // 批量导出按钮
  728. const exportButton = UI.createButton("导出", "claude-button secondary", "📤");
  729. exportButton.setAttribute("data-tooltip", "导出所有Token");
  730. exportButton.addEventListener("click", () => this.exportTokens());
  731. buttonContainer.appendChild(exportButton);
  732.  
  733. // WebDAV备份按钮
  734. const webdavButton = UI.createButton("云备份", "claude-button secondary", "☁️");
  735. webdavButton.setAttribute("data-tooltip", "WebDAV云备份与恢复");
  736. webdavButton.addEventListener("click", () => this.showWebDAVModal());
  737. buttonContainer.appendChild(webdavButton);
  738.  
  739. this.dropdownContainer.appendChild(buttonContainer);
  740.  
  741. // 添加信息提示
  742. const infoSection = UI.createElem("div", "claude-info-section", {
  743. marginTop: "10px",
  744. padding: "8px",
  745. backgroundColor: "#f8f9fa",
  746. borderRadius: "6px",
  747. fontSize: "11px",
  748. color: "#666",
  749. textAlign: "center"
  750. });
  751. infoSection.innerHTML = '悬停显示面板 • 拖拽按钮调整位置 • 支持WebDAV云备份';
  752. this.dropdownContainer.appendChild(infoSection);
  753. },
  754.  
  755. updateTokenGrid() {
  756. this.tokenGrid.innerHTML = "";
  757.  
  758. // 获取当前使用的 token
  759. const currentTokenName = GM_getValue(config.currentTokenKey);
  760.  
  761. // 加载测试结果
  762. const testResults = this.loadTestResults();
  763.  
  764. this.tokens.forEach((token, index) => {
  765. const tokenItem = UI.createElem("div", "claude-token-item");
  766. if (token.name === currentTokenName) {
  767. tokenItem.classList.add("current-token");
  768.  
  769. // 添加选中标记
  770. const currentBadge = UI.createElem("div", "current-token-badge");
  771. tokenItem.appendChild(currentBadge);
  772. }
  773.  
  774. // Token 信息容器
  775. const tokenInfo = UI.createElem("div", "token-info");
  776.  
  777. // 顶部行:名称和操作按钮
  778. const topRow = UI.createElem("div", "token-top-row");
  779.  
  780. // 名称容器
  781. const nameContainer = UI.createElem("div", "token-name-container");
  782.  
  783. const numberBadge = UI.createElem("span", "token-number");
  784. numberBadge.textContent = `#${(index + 1).toString().padStart(2, "0")}`;
  785.  
  786. const nameSpan = UI.createElem("span", "token-name");
  787. nameSpan.textContent = token.name;
  788.  
  789. nameContainer.appendChild(numberBadge);
  790. nameContainer.appendChild(nameSpan);
  791.  
  792. // 操作按钮
  793. const actions = UI.createElem("div", "token-actions");
  794.  
  795. // 编辑按钮
  796. const editButton = UI.createElem("button", "token-action-btn edit-btn");
  797. editButton.innerHTML = `
  798. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  799. <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>
  800. </svg>
  801. `;
  802. editButton.dataset.index = index;
  803. editButton.addEventListener("click", (e) => {
  804. e.stopPropagation();
  805. this.showEditTokenModal(index);
  806. });
  807.  
  808. // 删除按钮
  809. const deleteButton = UI.createElem("button", "token-action-btn delete-btn");
  810. deleteButton.innerHTML = `
  811. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  812. <path d="M3 6h18"></path>
  813. <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"></path>
  814. <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
  815. </svg>
  816. `;
  817. deleteButton.dataset.index = index;
  818. deleteButton.addEventListener("click", (e) => {
  819. e.stopPropagation();
  820. this.confirmDeleteToken(index);
  821. });
  822.  
  823. actions.appendChild(editButton);
  824. actions.appendChild(deleteButton);
  825.  
  826. topRow.appendChild(nameContainer);
  827. topRow.appendChild(actions);
  828.  
  829. // 底部行:状态和时间
  830. const bottomRow = UI.createElem("div", "token-bottom-row");
  831.  
  832. // 添加时间戳(使用token的创建时间)
  833. const timeSpan = UI.createElem("span", "token-time");
  834. timeSpan.textContent = token.createdAt || "";
  835. bottomRow.appendChild(timeSpan);
  836.  
  837. // 状态指示器
  838. const status = UI.createElem("div", "token-status");
  839. const statusIndicator = UI.createElem("div", "status-indicator");
  840.  
  841. // 检查缓存的测试结果
  842. const testResult = testResults[token.key];
  843. if (testResult) {
  844. statusIndicator.classList.add(testResult.status);
  845. }
  846.  
  847. status.appendChild(statusIndicator);
  848. status.addEventListener("click", async (e) => {
  849. e.stopPropagation();
  850. await this.testSingleToken(token, statusIndicator, bottomRow);
  851. });
  852.  
  853. bottomRow.appendChild(status);
  854.  
  855. // 将行添加到信息容器
  856. tokenInfo.appendChild(topRow);
  857. tokenInfo.appendChild(bottomRow);
  858.  
  859. // 将信息容器添加到 token 项
  860. tokenItem.appendChild(tokenInfo);
  861.  
  862. // 点击切换 token
  863. tokenItem.addEventListener("click", () => this.switchToToken(token));
  864.  
  865. // 将 token 项添加到网格
  866. this.tokenGrid.appendChild(tokenItem);
  867. });
  868.  
  869. // 如果token数量超过4个(两行),添加滚动提示
  870. if (this.tokens.length > 4) {
  871. const scrollIndicator = UI.createElem("div", "scroll-indicator");
  872. scrollIndicator.innerHTML = `
  873. <div class="scroll-text">向下滚动查看更多 (${this.tokens.length - 4})</div>
  874. <div class="scroll-arrow">
  875. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  876. <path d="M7 13l5 5 5-5"></path>
  877. <path d="M7 6l5 5 5-5"></path>
  878. </svg>
  879. </div>
  880. `;
  881. this.tokenGrid.appendChild(scrollIndicator);
  882. }
  883. },
  884.  
  885. async switchToToken(token) {
  886. // 检查是否有缓存的测试结果
  887. const cachedResult = this.getTestResult(token.key);
  888.  
  889. // 如果有缓存的测试结果且为无效,提示用户并询问是否继续
  890. if (cachedResult && cachedResult.status === "error") {
  891. const confirmResult = await this.showConfirmDialog(
  892. "警告",
  893. `该 Token "${token.name}" 已被标记为无效,是否仍要切换到该 Token?`
  894. );
  895.  
  896. if (!confirmResult) {
  897. return;
  898. }
  899. }
  900.  
  901. // 应用 token
  902. this.applyToken(token.key);
  903. GM_setValue(config.currentTokenKey, token.name);
  904.  
  905. // 隐藏下拉菜单
  906. this.hideDropdown();
  907. },
  908.  
  909. applyToken(token) {
  910. const currentURL = window.location.href;
  911.  
  912. if (currentURL.startsWith("https://claude.ai/")) {
  913. document.cookie = `sessionKey=${token}; path=/; domain=.claude.ai`;
  914. window.location.reload();
  915. } else {
  916. let loginUrl;
  917. const hostname = new URL(currentURL).hostname;
  918. if (hostname !== "claude.ai") {
  919. loginUrl = `https://${hostname}/login_token?session_key=${token}`;
  920. }
  921.  
  922. if (loginUrl) {
  923. window.location.href = loginUrl;
  924. }
  925. }
  926. },
  927.  
  928. async testSingleToken(token, statusIndicator, bottomRow) {
  929. // 显示加载状态
  930. statusIndicator.className = "status-indicator loading";
  931.  
  932. // 测试 token
  933. const result = await this.testToken(token.key);
  934.  
  935. // 保存测试结果
  936. this.saveTestResult(token.key, result);
  937.  
  938. // 更新状态指示器
  939. statusIndicator.className = `status-indicator ${result.status}`;
  940.  
  941. // 不再更新时间戳,保持显示token的创建时间
  942. },
  943.  
  944. async testAllTokens() {
  945. // 获取所有 token 项
  946. const tokenItems = this.tokenGrid.querySelectorAll(".claude-token-item");
  947.  
  948. // 禁用测试按钮
  949. const testButton = this.dropdownContainer.querySelector(".claude-button.primary");
  950. testButton.disabled = true;
  951. testButton.textContent = "测试中...";
  952.  
  953. // 清除所有缓存的测试结果
  954. GM_setValue(config.testResultsKey, {});
  955.  
  956. const tokens = Array.from(tokenItems);
  957.  
  958. // 按4个一组处理所有tokens
  959. for (let i = 0; i < tokens.length; i += 4) {
  960. // 取出当前4个(或更少)token
  961. const currentChunk = tokens.slice(i, Math.min(i + 4, tokens.length));
  962.  
  963. // 并行处理这最多4个token
  964. await Promise.all(
  965. currentChunk.map(async (tokenItem) => {
  966. const index = Array.from(tokenItems).indexOf(tokenItem);
  967. const token = this.tokens[index];
  968. const statusIndicator = tokenItem.querySelector(".status-indicator");
  969. const bottomRow = tokenItem.querySelector(".token-bottom-row");
  970.  
  971. await this.testSingleToken(token, statusIndicator, bottomRow);
  972. })
  973. );
  974. }
  975.  
  976. // 恢复测试按钮
  977. testButton.disabled = false;
  978. testButton.innerHTML = "🔍 测活";
  979. },
  980.  
  981. async testToken(key) {
  982. return new Promise((resolve) => {
  983. GM_xmlhttpRequest({
  984. method: "GET",
  985. url: "https://api.claude.ai/api/organizations",
  986. headers: {
  987. accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
  988. "accept-language": "en-US,en;q=0.9",
  989. "cache-control": "max-age=0",
  990. cookie: `sessionKey=${key}`,
  991. "user-agent": "Mozilla/5.0 (X11; Linux x86_64)",
  992. "sec-fetch-mode": "navigate",
  993. "sec-fetch-site": "none",
  994. },
  995. onload: (response) => {
  996. try {
  997. if (response.status !== 200) {
  998. resolve({ status: "error", message: "无效" });
  999. return;
  1000. }
  1001.  
  1002. const responseText = response.responseText;
  1003.  
  1004. if (responseText.toLowerCase().includes("unauthorized")) {
  1005. resolve({ status: "error", message: "无效" });
  1006. return;
  1007. }
  1008.  
  1009. if (responseText.trim() === "") {
  1010. resolve({ status: "error", message: "无响应" });
  1011. return;
  1012. }
  1013.  
  1014. try {
  1015. const objects = JSON.parse(responseText);
  1016. if (objects && objects.length > 0) {
  1017. resolve({ status: "success", message: "有效" });
  1018. return;
  1019. }
  1020. } catch (e) {
  1021. resolve({ status: "error", message: "解析失败" });
  1022. return;
  1023. }
  1024.  
  1025. resolve({ status: "error", message: "无效数据" });
  1026. } catch (error) {
  1027. console.error("解析响应时发生错误:", error);
  1028. resolve({ status: "error", message: "测试失败" });
  1029. }
  1030. },
  1031. onerror: (error) => {
  1032. console.error("请求发生错误:", error);
  1033. resolve({ status: "error", message: "网络错误" });
  1034. },
  1035. ontimeout: () => {
  1036. resolve({ status: "error", message: "超时" });
  1037. },
  1038. });
  1039. });
  1040. },
  1041.  
  1042. loadTestResults() {
  1043. try {
  1044. const cached = GM_getValue(config.testResultsKey, {});
  1045. const now = Date.now();
  1046. // 清理过期的测试结果
  1047. const filtered = Object.entries(cached).reduce((acc, [key, value]) => {
  1048. if (now - value.timestamp < config.testResultExpiry) {
  1049. acc[key] = value;
  1050. }
  1051. return acc;
  1052. }, {});
  1053. return filtered;
  1054. } catch (error) {
  1055. console.error("加载测试结果缓存失败:", error);
  1056. return {};
  1057. }
  1058. },
  1059.  
  1060. saveTestResult(key, result) {
  1061. try {
  1062. const testResults = this.loadTestResults();
  1063. const now = new Date();
  1064. // 统一使用简短时间格式
  1065. const formattedTime = now.toLocaleString("zh-CN", {
  1066. month: "2-digit",
  1067. day: "2-digit",
  1068. hour: "2-digit",
  1069. minute: "2-digit",
  1070. });
  1071.  
  1072. testResults[key] = {
  1073. status: result.status,
  1074. message: result.message,
  1075. timestamp: now.getTime(),
  1076. testTime: formattedTime, // 保存简短格式的时间
  1077. };
  1078. GM_setValue(config.testResultsKey, testResults);
  1079. } catch (error) {
  1080. console.error("保存测试结果失败:", error);
  1081. }
  1082. },
  1083.  
  1084. getTestResult(key) {
  1085. const testResults = this.loadTestResults();
  1086. return testResults[key];
  1087. },
  1088.  
  1089. async removeInvalidTokens() {
  1090. const confirmResult = await this.showConfirmDialog(
  1091. "确认清理",
  1092. "是否删除所有无效的 Tokens?此操作不可撤销。"
  1093. );
  1094.  
  1095. if (!confirmResult) return;
  1096.  
  1097. const testResults = this.loadTestResults();
  1098. const validTokens = this.tokens.filter((token) => {
  1099. const result = testResults[token.key];
  1100. return !result || result.status === "success";
  1101. });
  1102.  
  1103. if (validTokens.length === this.tokens.length) {
  1104. alert("没有发现无效的 Tokens");
  1105. return;
  1106. }
  1107.  
  1108. this.tokens = validTokens;
  1109. this.saveTokens();
  1110. this.updateTokenGrid();
  1111. },
  1112.  
  1113. showAddTokenModal() {
  1114. const content = UI.createElem("div", "claude-add-token-form");
  1115.  
  1116. const nameInput = UI.createElem("input");
  1117. nameInput.placeholder = "Token 名称";
  1118. nameInput.setAttribute("aria-label", "Token 名称");
  1119.  
  1120. const keyInput = UI.createElem("input");
  1121. keyInput.placeholder = "Token 密钥";
  1122. keyInput.setAttribute("aria-label", "Token 密钥");
  1123.  
  1124. content.appendChild(nameInput);
  1125. content.appendChild(keyInput);
  1126.  
  1127. const { modal, buttonContainer, close } = UI.createModal("添加 Token", content);
  1128. modal.querySelector(".claude-modal-content").classList.add("narrow-modal");
  1129.  
  1130. const addButton = UI.createButton("添加", "claude-button primary");
  1131. addButton.addEventListener("click", () => {
  1132. if (this.validateInput(nameInput.value, keyInput.value)) {
  1133. // 获取当前时间并格式化
  1134. const now = new Date();
  1135. const formattedTime = now.toLocaleString("zh-CN", {
  1136. month: "2-digit",
  1137. day: "2-digit",
  1138. hour: "2-digit",
  1139. minute: "2-digit",
  1140. });
  1141.  
  1142. this.tokens.push({
  1143. name: nameInput.value,
  1144. key: keyInput.value,
  1145. createdAt: formattedTime, // 添加创建时间
  1146. timestamp: now.getTime() // 添加时间戳用于排序
  1147. });
  1148.  
  1149. this.saveTokens();
  1150. this.updateTokenGrid();
  1151. close();
  1152. }
  1153. });
  1154.  
  1155. const cancelButton = UI.createButton("取消", "claude-button secondary");
  1156. cancelButton.addEventListener("click", close);
  1157.  
  1158. buttonContainer.appendChild(cancelButton);
  1159. buttonContainer.appendChild(addButton);
  1160. },
  1161.  
  1162. showEditTokenModal(index) {
  1163. const token = this.tokens[index];
  1164. const content = UI.createElem("div", "claude-edit-token-form");
  1165.  
  1166. const nameInput = UI.createElem("input");
  1167. nameInput.value = token.name;
  1168. nameInput.placeholder = "Token 名称";
  1169.  
  1170. const keyInput = UI.createElem("input");
  1171. keyInput.value = token.key;
  1172. keyInput.placeholder = "Token 密钥";
  1173.  
  1174. content.appendChild(nameInput);
  1175. content.appendChild(keyInput);
  1176.  
  1177. const { modal, buttonContainer, close } = UI.createModal("编辑 Token", content);
  1178. modal.querySelector(".claude-modal-content").classList.add("narrow-modal");
  1179.  
  1180. const saveButton = UI.createButton("保存", "claude-button primary");
  1181. saveButton.addEventListener("click", () => {
  1182. if (this.validateInput(nameInput.value, keyInput.value)) {
  1183. // 保留原有的创建时间和时间戳
  1184. this.tokens[index] = {
  1185. name: nameInput.value,
  1186. key: keyInput.value,
  1187. createdAt: token.createdAt || "", // 保留原有的创建时间
  1188. timestamp: token.timestamp || Date.now() // 保留原有的时间戳
  1189. };
  1190.  
  1191. this.saveTokens();
  1192. this.updateTokenGrid();
  1193. close();
  1194. }
  1195. });
  1196.  
  1197. const cancelButton = UI.createButton("取消", "claude-button secondary");
  1198. cancelButton.addEventListener("click", close);
  1199.  
  1200. buttonContainer.appendChild(cancelButton);
  1201. buttonContainer.appendChild(saveButton);
  1202. },
  1203.  
  1204. confirmDeleteToken(index) {
  1205. const token = this.tokens[index];
  1206. const content = UI.createElem("div", "claude-delete-confirm");
  1207.  
  1208. content.innerHTML = `
  1209. <div style="font-size: 48px; text-align: center; margin-bottom: 16px;">⚠️</div>
  1210. <div style="font-size: 18px; font-weight: 600; text-align: center; margin-bottom: 12px;">删除确认</div>
  1211. <div style="text-align: center; margin-bottom: 24px;">
  1212. 您确定要删除 Token "${token.name}" 吗?<br>
  1213. 此操作无法撤销。
  1214. </div>
  1215. `;
  1216.  
  1217. const { modal, buttonContainer, close } = UI.createModal("", content);
  1218. modal.querySelector(".claude-modal-content").classList.add("narrow-modal");
  1219.  
  1220. const deleteButton = UI.createButton("删除", "claude-button primary");
  1221. deleteButton.style.backgroundColor = "#e53e3e";
  1222. deleteButton.addEventListener("click", () => {
  1223. this.deleteToken(index);
  1224. close();
  1225. });
  1226.  
  1227. const cancelButton = UI.createButton("取消", "claude-button secondary");
  1228. cancelButton.addEventListener("click", close);
  1229.  
  1230. buttonContainer.appendChild(cancelButton);
  1231. buttonContainer.appendChild(deleteButton);
  1232. },
  1233.  
  1234. deleteToken(index) {
  1235. this.tokens.splice(index, 1);
  1236. this.saveTokens();
  1237. this.updateTokenGrid();
  1238. },
  1239.  
  1240. showBulkImportModal() {
  1241. const content = UI.createElem("div", "claude-bulk-import-form");
  1242.  
  1243. // 文本区域标签
  1244. const textareaLabel = UI.createElem("label");
  1245. textareaLabel.innerHTML = "<strong>1️⃣ Tokens 粘贴区:</strong><br>在这里粘贴您需要导入的 Tokens,每行一个!";
  1246. content.appendChild(textareaLabel);
  1247.  
  1248. // 文本区域
  1249. const textarea = UI.createElem("textarea");
  1250. textarea.rows = 10;
  1251. content.appendChild(textarea);
  1252.  
  1253. // 命名规则容器
  1254. const namingRuleContainer = UI.createElem("div", "claude-naming-rule");
  1255.  
  1256. // 命名规则标签
  1257. const namingRuleLabel = UI.createElem("label");
  1258. namingRuleLabel.innerHTML = "<strong>2️⃣ Tokens 命名规则:</strong>";
  1259. namingRuleContainer.appendChild(namingRuleLabel);
  1260.  
  1261. // 名称前缀
  1262. const prefixLabel = UI.createElem("label");
  1263. prefixLabel.textContent = "名称前缀:";
  1264. namingRuleContainer.appendChild(prefixLabel);
  1265.  
  1266. const prefixInput = UI.createElem("input");
  1267. prefixInput.value = "token";
  1268. namingRuleContainer.appendChild(prefixInput);
  1269.  
  1270. // 起始编号
  1271. const startNumberLabel = UI.createElem("label");
  1272. startNumberLabel.textContent = "名称起始编号:";
  1273. namingRuleContainer.appendChild(startNumberLabel);
  1274.  
  1275. const startNumberInput = UI.createElem("input");
  1276. startNumberInput.type = "number";
  1277. startNumberInput.value = "1";
  1278. namingRuleContainer.appendChild(startNumberInput);
  1279.  
  1280. content.appendChild(namingRuleContainer);
  1281.  
  1282. // 预览容器
  1283. const previewLabel = UI.createElem("label");
  1284. previewLabel.innerHTML = "<strong>3️⃣ Tokens 导入结果预览:</strong>";
  1285. content.appendChild(previewLabel);
  1286.  
  1287. const previewContainer = UI.createElem("div", "claude-preview-container");
  1288. content.appendChild(previewContainer);
  1289.  
  1290. const { modal, buttonContainer, close } = UI.createModal("批量导入 Tokens", content);
  1291.  
  1292. const importButton = UI.createButton("导入", "claude-button primary");
  1293. importButton.addEventListener("click", () => {
  1294. this.performBulkImport(
  1295. textarea.value,
  1296. prefixInput.value,
  1297. startNumberInput.value
  1298. );
  1299. close();
  1300. });
  1301.  
  1302. const cancelButton = UI.createButton("取消", "claude-button secondary");
  1303. cancelButton.addEventListener("click", close);
  1304.  
  1305. buttonContainer.appendChild(cancelButton);
  1306. buttonContainer.appendChild(importButton);
  1307.  
  1308. // 更新预览
  1309. const updatePreview = () => {
  1310. this.previewBulkImport(
  1311. textarea.value,
  1312. prefixInput.value,
  1313. startNumberInput.value,
  1314. previewContainer
  1315. );
  1316. };
  1317.  
  1318. [textarea, prefixInput, startNumberInput].forEach((elem) => {
  1319. elem.addEventListener("input", updatePreview);
  1320. });
  1321.  
  1322. // 初始化预览
  1323. updatePreview();
  1324. },
  1325.  
  1326. previewBulkImport(input, namePrefix, startNumber, previewContainer) {
  1327. previewContainer.innerHTML = "";
  1328.  
  1329. const tokens = this.parseTokens(input);
  1330. const namedTokens = this.applyNamingRule(
  1331. tokens,
  1332. namePrefix,
  1333. parseInt(startNumber)
  1334. );
  1335.  
  1336. const previewTitle = UI.createElem("div", "claude-preview-title");
  1337. previewTitle.textContent = "请核对下方导入结果:";
  1338. previewContainer.appendChild(previewTitle);
  1339.  
  1340. if (namedTokens.length === 0) {
  1341. const emptyMessage = UI.createElem("div", "claude-preview-item");
  1342. emptyMessage.textContent = "等待输入...";
  1343. previewContainer.appendChild(emptyMessage);
  1344. return;
  1345. }
  1346.  
  1347. namedTokens.forEach((token) => {
  1348. const previewItem = UI.createElem("div", "claude-preview-item");
  1349. previewItem.innerHTML = `
  1350. <strong>${token.name}:</strong>
  1351. <span style="font-family: monospace; word-break: break-all;">${token.key}</span>
  1352. `;
  1353. previewContainer.appendChild(previewItem);
  1354. });
  1355. },
  1356.  
  1357. performBulkImport(input, namePrefix, startNumber) {
  1358. const tokens = this.parseTokens(input);
  1359. const namedTokens = this.applyNamingRule(
  1360. tokens,
  1361. namePrefix,
  1362. parseInt(startNumber)
  1363. );
  1364.  
  1365. if (namedTokens.length === 0) {
  1366. alert("没有有效的 Tokens 可导入");
  1367. return;
  1368. }
  1369.  
  1370. this.tokens = [...this.tokens, ...namedTokens];
  1371. this.saveTokens();
  1372. this.updateTokenGrid();
  1373. },
  1374.  
  1375. parseTokens(input) {
  1376. return input
  1377. .split("\n")
  1378. .map((line) => line.trim())
  1379. .filter((line) => this.validateTokenKey(line))
  1380. .map((key) => ({ key }));
  1381. },
  1382.  
  1383. applyNamingRule(tokens, namePrefix, startNumber) {
  1384. return tokens.map((token, index) => {
  1385. const number = startNumber + index;
  1386. const name = `${namePrefix}${number.toString().padStart(2, "0")}`;
  1387. return { ...token, name };
  1388. });
  1389. },
  1390.  
  1391. exportTokens() {
  1392. const testResults = this.loadTestResults();
  1393. const exportData = this.tokens.map((token) => {
  1394. const testResult = testResults[token.key] || {};
  1395. return {
  1396. name: token.name,
  1397. sessionKey: token.key,
  1398. isValid: testResult.status === "success" ? true : testResult.status === "error" ? false : null,
  1399. testTime: testResult.testTime || null,
  1400. testMessage: testResult.message || null,
  1401. };
  1402. });
  1403.  
  1404. // 创建并下载 JSON 文件
  1405. const blob = new Blob([JSON.stringify(exportData, null, 2)], {
  1406. type: "application/json",
  1407. });
  1408. const url = URL.createObjectURL(blob);
  1409. const a = document.createElement("a");
  1410. a.href = url;
  1411. a.download = `claude_tokens_${new Date().toISOString().split("T")[0]}.json`;
  1412. document.body.appendChild(a);
  1413. a.click();
  1414. document.body.removeChild(a);
  1415. },
  1416.  
  1417. showWebDAVModal() {
  1418. const content = UI.createElem("div", "claude-webdav-form");
  1419. content.style.cssText = "width: 100%; max-width: 600px;";
  1420.  
  1421. // 添加帮助信息
  1422. const helpInfo = UI.createElem("div", "claude-webdav-help");
  1423. helpInfo.style.cssText = `
  1424. margin-bottom: 10px;
  1425. padding: 12px;
  1426. background-color: var(--bg-color);
  1427. border: 1px solid var(--border-color);
  1428. border-radius: 8px;
  1429. font-size: 13px;
  1430. color: var(--text-color);
  1431. box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  1432. `;
  1433. helpInfo.innerHTML = `
  1434. <p style="margin: 0 0 10px 0; font-weight: 600; color: var(--text-color);">📝 WebDAV服务器设置说明:</p>
  1435. <ul style="margin: 0; padding-left: 20px; line-height: 1.6;">
  1436. <li>URL必须是完整的WebDAV路径,例如:https://dav.jianguoyun.com/dav/Claude/</li>
  1437. <li>确保路径末尾有斜杠"/"</li>
  1438. <li>如果遇到404错误,请确认路径是否存在</li>
  1439. <li>坚果云用户请使用应用专用密码</li>
  1440. </ul>
  1441. `;
  1442. content.appendChild(helpInfo);
  1443.  
  1444. // 创建表单容器
  1445. const formContainer = UI.createElem("div", "claude-webdav-form-container");
  1446. formContainer.style.cssText = `
  1447. display: grid;
  1448. gap: 8px;
  1449. margin-bottom: 15px;
  1450. `;
  1451.  
  1452. // WebDAV服务器URL输入
  1453. const urlGroup = UI.createElem("div", "input-group");
  1454. urlGroup.style.cssText = "display: flex; align-items: center; gap: 10px;";
  1455.  
  1456. const urlLabel = UI.createElem("label");
  1457. urlLabel.textContent = "WebDAV URL:";
  1458. urlLabel.style.cssText = "font-weight: 500; color: var(--text-color); min-width: 120px; text-align: right;";
  1459.  
  1460. const urlInput = UI.createElem("input");
  1461. urlInput.type = "text";
  1462. urlInput.placeholder = "https://dav.jianguoyun.com/dav/Claude/";
  1463. urlInput.value = GM_getValue("webdav_url", "");
  1464. urlInput.style.cssText = `
  1465. flex: 1;
  1466. padding: 10px;
  1467. border: 1px solid var(--border-color);
  1468. border-radius: 6px;
  1469. font-size: 14px;
  1470. background-color: var(--bg-color);
  1471. color: var(--text-color);
  1472. transition: all 0.3s ease;
  1473. `;
  1474.  
  1475. urlGroup.appendChild(urlLabel);
  1476. urlGroup.appendChild(urlInput);
  1477. formContainer.appendChild(urlGroup);
  1478.  
  1479. // 用户名输入
  1480. const usernameGroup = UI.createElem("div", "input-group");
  1481. usernameGroup.style.cssText = "display: flex; align-items: center; gap: 10px;";
  1482.  
  1483. const usernameLabel = UI.createElem("label");
  1484. usernameLabel.textContent = "用户名:";
  1485. usernameLabel.style.cssText = "font-weight: 500; color: var(--text-color); min-width: 120px; text-align: right;";
  1486.  
  1487. const usernameInput = UI.createElem("input");
  1488. usernameInput.type = "text";
  1489. usernameInput.placeholder = "用户名";
  1490. usernameInput.value = GM_getValue("webdav_username", "");
  1491. usernameInput.style.cssText = `
  1492. flex: 1;
  1493. padding: 10px;
  1494. border: 1px solid var(--border-color);
  1495. border-radius: 6px;
  1496. font-size: 14px;
  1497. background-color: var(--bg-color);
  1498. color: var(--text-color);
  1499. transition: all 0.3s ease;
  1500. `;
  1501.  
  1502. usernameGroup.appendChild(usernameLabel);
  1503. usernameGroup.appendChild(usernameInput);
  1504. formContainer.appendChild(usernameGroup);
  1505.  
  1506. // 密码输入
  1507. const passwordGroup = UI.createElem("div", "input-group");
  1508. passwordGroup.style.cssText = "display: flex; align-items: center; gap: 10px;";
  1509.  
  1510. const passwordLabel = UI.createElem("label");
  1511. passwordLabel.textContent = "密码:";
  1512. passwordLabel.style.cssText = "font-weight: 500; color: var(--text-color); min-width: 120px; text-align: right;";
  1513.  
  1514. const passwordInput = UI.createElem("input");
  1515. passwordInput.type = "password";
  1516. passwordInput.placeholder = "密码";
  1517. passwordInput.value = GM_getValue("webdav_password", "");
  1518. passwordInput.style.cssText = `
  1519. flex: 1;
  1520. padding: 10px;
  1521. border: 1px solid var(--border-color);
  1522. border-radius: 6px;
  1523. font-size: 14px;
  1524. background-color: var(--bg-color);
  1525. color: var(--text-color);
  1526. transition: all 0.3s ease;
  1527. `;
  1528.  
  1529. passwordGroup.appendChild(passwordLabel);
  1530. passwordGroup.appendChild(passwordInput);
  1531. formContainer.appendChild(passwordGroup);
  1532.  
  1533. // 文件名输入
  1534. const filenameGroup = UI.createElem("div", "input-group");
  1535. filenameGroup.style.cssText = "display: flex; align-items: center; gap: 10px;";
  1536.  
  1537. const filenameLabel = UI.createElem("label");
  1538. filenameLabel.textContent = "文件名:";
  1539. filenameLabel.style.cssText = "font-weight: 500; color: var(--text-color); min-width: 120px; text-align: right;";
  1540.  
  1541. const filenameInput = UI.createElem("input");
  1542. filenameInput.type = "text";
  1543. filenameInput.placeholder = "claude_tokens.json";
  1544. filenameInput.value = GM_getValue("webdav_filename", "claude_tokens.json");
  1545. filenameInput.style.cssText = `
  1546. flex: 1;
  1547. padding: 10px;
  1548. border: 1px solid var(--border-color);
  1549. border-radius: 6px;
  1550. font-size: 14px;
  1551. background-color: var(--bg-color);
  1552. color: var(--text-color);
  1553. transition: all 0.3s ease;
  1554. `;
  1555.  
  1556. filenameGroup.appendChild(filenameLabel);
  1557. filenameGroup.appendChild(filenameInput);
  1558. formContainer.appendChild(filenameGroup);
  1559.  
  1560. content.appendChild(formContainer);
  1561.  
  1562. // 测试连接按钮
  1563. const testConnectionButton = UI.createButton("测试连接", "claude-button secondary");
  1564. testConnectionButton.style.cssText = `
  1565. width: 100%;
  1566. margin: 10px 0;
  1567. padding: 10px;
  1568. font-size: 14px;
  1569. font-weight: 500;
  1570. border-radius: 6px;
  1571. background-color: var(--button-bg);
  1572. color: var(--text-color);
  1573. border: 1px solid var(--border-color);
  1574. cursor: pointer;
  1575. transition: all 0.3s ease;
  1576. `;
  1577. testConnectionButton.addEventListener("click", async () => {
  1578. this.saveWebDAVSettings(urlInput.value, usernameInput.value, passwordInput.value, filenameInput.value);
  1579.  
  1580. statusDisplay.style.display = "block";
  1581. statusDisplay.textContent = "正在测试连接...";
  1582. statusDisplay.style.backgroundColor = "var(--bg-color)";
  1583.  
  1584. try {
  1585. await this.checkWebDAVDirectory(urlInput.value, usernameInput.value, passwordInput.value);
  1586. statusDisplay.textContent = "✅ 连接成功!目录存在且可访问。";
  1587. statusDisplay.style.backgroundColor = "#d4edda";
  1588. } catch (error) {
  1589. statusDisplay.textContent = `❌ 连接失败: ${error.message}`;
  1590. statusDisplay.style.backgroundColor = "#f8d7da";
  1591. }
  1592. });
  1593. content.appendChild(testConnectionButton);
  1594.  
  1595. // 状态显示
  1596. const statusDisplay = UI.createElem("div", "claude-webdav-status");
  1597. statusDisplay.style.cssText = `
  1598. margin: 10px 0;
  1599. padding: 10px;
  1600. border-radius: 6px;
  1601. font-size: 14px;
  1602. text-align: center;
  1603. display: none;
  1604. transition: all 0.3s ease;
  1605. `;
  1606. content.appendChild(statusDisplay);
  1607.  
  1608. // 操作按钮容器
  1609. const actionsContainer = UI.createElem("div", "claude-webdav-actions");
  1610. actionsContainer.style.cssText = `
  1611. display: grid;
  1612. grid-template-columns: repeat(3, 1fr);
  1613. gap: 10px;
  1614. margin-top: 15px;
  1615. `;
  1616.  
  1617. // 备份按钮
  1618. const backupButton = UI.createButton("备份到WebDAV", "claude-button primary");
  1619. backupButton.style.cssText = `
  1620. padding: 12px;
  1621. font-size: 14px;
  1622. font-weight: 500;
  1623. border-radius: 6px;
  1624. background-color: #b3462f;
  1625. color: white;
  1626. border: none;
  1627. cursor: pointer;
  1628. transition: all 0.3s ease;
  1629. `;
  1630. backupButton.addEventListener("click", async () => {
  1631. this.saveWebDAVSettings(urlInput.value, usernameInput.value, passwordInput.value, filenameInput.value);
  1632.  
  1633. statusDisplay.style.display = "block";
  1634. statusDisplay.textContent = "正在备份...";
  1635. statusDisplay.style.backgroundColor = "var(--bg-color)";
  1636.  
  1637. try {
  1638. await this.backupToWebDAV(urlInput.value, usernameInput.value, passwordInput.value, filenameInput.value);
  1639. statusDisplay.textContent = "✅ 备份成功!";
  1640. statusDisplay.style.backgroundColor = "#d4edda";
  1641. } catch (error) {
  1642. statusDisplay.textContent = `❌ 备份失败: ${error.message}`;
  1643. statusDisplay.style.backgroundColor = "#f8d7da";
  1644. }
  1645. });
  1646.  
  1647. // 恢复按钮
  1648. const restoreButton = UI.createButton("从WebDAV恢复", "claude-button secondary");
  1649. restoreButton.style.cssText = `
  1650. padding: 12px;
  1651. font-size: 14px;
  1652. font-weight: 500;
  1653. border-radius: 6px;
  1654. background-color: var(--button-bg);
  1655. color: var(--text-color);
  1656. border: 1px solid var(--border-color);
  1657. cursor: pointer;
  1658. transition: all 0.3s ease;
  1659. `;
  1660. restoreButton.addEventListener("click", async () => {
  1661. this.saveWebDAVSettings(urlInput.value, usernameInput.value, passwordInput.value, filenameInput.value);
  1662.  
  1663. statusDisplay.style.display = "block";
  1664. statusDisplay.textContent = "正在恢复...";
  1665. statusDisplay.style.backgroundColor = "var(--bg-color)";
  1666.  
  1667. try {
  1668. await this.restoreFromWebDAV(urlInput.value, usernameInput.value, passwordInput.value, filenameInput.value);
  1669. statusDisplay.textContent = "✅ 恢复成功!";
  1670. statusDisplay.style.backgroundColor = "#d4edda";
  1671. this.updateTokenGrid();
  1672. } catch (error) {
  1673. statusDisplay.textContent = `❌ 恢复失败: ${error.message}`;
  1674. statusDisplay.style.backgroundColor = "#f8d7da";
  1675. }
  1676. });
  1677.  
  1678. // 关闭按钮
  1679. const closeButton = UI.createButton("关闭", "claude-button secondary");
  1680. closeButton.style.cssText = `
  1681. padding: 12px;
  1682. font-size: 14px;
  1683. font-weight: 500;
  1684. border-radius: 6px;
  1685. background-color: var(--button-bg);
  1686. color: var(--text-color);
  1687. border: 1px solid var(--border-color);
  1688. cursor: pointer;
  1689. transition: all 0.3s ease;
  1690. `;
  1691. closeButton.addEventListener("click", () => {
  1692. modal.remove();
  1693. });
  1694.  
  1695. actionsContainer.appendChild(backupButton);
  1696. actionsContainer.appendChild(restoreButton);
  1697. actionsContainer.appendChild(closeButton);
  1698. content.appendChild(actionsContainer);
  1699.  
  1700. // 创建模态框
  1701. const { modal, buttonContainer } = UI.createModal("☁️ WebDAV备份与恢复", content, true);
  1702. document.body.appendChild(modal);
  1703.  
  1704. // 添加关闭按钮事件监听
  1705. const closeBtn = modal.querySelector(".claude-close-button");
  1706. if (closeBtn) {
  1707. closeBtn.addEventListener("click", () => {
  1708. document.body.removeChild(modal);
  1709. });
  1710. }
  1711. },
  1712.  
  1713. saveWebDAVSettings(url, username, password, filename) {
  1714. GM_setValue("webdav_url", url);
  1715. GM_setValue("webdav_username", username);
  1716. GM_setValue("webdav_password", password);
  1717. GM_setValue("webdav_filename", filename);
  1718. },
  1719.  
  1720. async backupToWebDAV(url, username, password, filename) {
  1721. // 准备备份数据
  1722. const testResults = this.loadTestResults();
  1723. const exportData = this.tokens.map((token) => {
  1724. const testResult = testResults[token.key] || {};
  1725. return {
  1726. name: token.name,
  1727. sessionKey: token.key,
  1728. isValid: testResult.status === "success" ? true : testResult.status === "error" ? false : null,
  1729. testTime: testResult.testTime || null,
  1730. testMessage: testResult.message || null,
  1731. };
  1732. });
  1733.  
  1734. const jsonData = JSON.stringify(exportData, null, 2);
  1735.  
  1736. // 确保URL以/结尾
  1737. if (!url.endsWith('/')) {
  1738. url += '/';
  1739. }
  1740.  
  1741. // 先检查目录是否存在
  1742. try {
  1743. await this.checkWebDAVDirectory(url, username, password);
  1744. } catch (error) {
  1745. // 如果是404错误,尝试创建目录
  1746. if (error.message.includes("404")) {
  1747. try {
  1748. // 尝试创建父目录
  1749. const parentUrl = url.substring(0, url.lastIndexOf('/', url.length - 2) + 1);
  1750. if (parentUrl !== url) {
  1751. await this.createWebDAVDirectory(parentUrl, username, password, url.substring(parentUrl.length, url.length - 1));
  1752. } else {
  1753. throw new Error("无法确定父目录");
  1754. }
  1755. } catch (createError) {
  1756. throw new Error(`目录不存在且无法创建: ${createError.message}`);
  1757. }
  1758. } else {
  1759. throw error;
  1760. }
  1761. }
  1762.  
  1763. // 发送到WebDAV服务器
  1764. return new Promise((resolve, reject) => {
  1765. GM_xmlhttpRequest({
  1766. method: "PUT",
  1767. url: url + filename,
  1768. headers: {
  1769. "Content-Type": "application/json",
  1770. "Authorization": "Basic " + btoa(username + ":" + password)
  1771. },
  1772. data: jsonData,
  1773. onload: function (response) {
  1774. if (response.status >= 200 && response.status < 300) {
  1775. resolve();
  1776. } else {
  1777. console.error("WebDAV备份失败:", response);
  1778. reject(new Error(`HTTP错误: ${response.status} ${response.statusText || ''}\n响应: ${response.responseText || '无响应内容'}`));
  1779. }
  1780. },
  1781. onerror: function (error) {
  1782. console.error("WebDAV备份网络错误:", error);
  1783. reject(new Error(`网络错误: ${error.statusText || '连接失败'}`));
  1784. }
  1785. });
  1786. });
  1787. },
  1788.  
  1789. // 检查WebDAV目录是否存在
  1790. checkWebDAVDirectory(url, username, password) {
  1791. return new Promise((resolve, reject) => {
  1792. GM_xmlhttpRequest({
  1793. method: "PROPFIND",
  1794. url: url,
  1795. headers: {
  1796. "Depth": "0",
  1797. "Authorization": "Basic " + btoa(username + ":" + password)
  1798. },
  1799. onload: function (response) {
  1800. if (response.status >= 200 && response.status < 300) {
  1801. resolve();
  1802. } else {
  1803. reject(new Error(`HTTP错误: ${response.status} ${response.statusText || ''}`));
  1804. }
  1805. },
  1806. onerror: function (error) {
  1807. reject(new Error(`网络错误: ${error.statusText || '连接失败'}`));
  1808. }
  1809. });
  1810. });
  1811. },
  1812.  
  1813. // 创建WebDAV目录
  1814. createWebDAVDirectory(parentUrl, username, password, dirName) {
  1815. return new Promise((resolve, reject) => {
  1816. GM_xmlhttpRequest({
  1817. method: "MKCOL",
  1818. url: parentUrl + dirName,
  1819. headers: {
  1820. "Authorization": "Basic " + btoa(username + ":" + password)
  1821. },
  1822. onload: function (response) {
  1823. if (response.status >= 200 && response.status < 300) {
  1824. resolve();
  1825. } else {
  1826. reject(new Error(`无法创建目录: HTTP错误 ${response.status} ${response.statusText || ''}`));
  1827. }
  1828. },
  1829. onerror: function (error) {
  1830. reject(new Error(`网络错误: ${error.statusText || '连接失败'}`));
  1831. }
  1832. });
  1833. });
  1834. },
  1835.  
  1836. async restoreFromWebDAV(url, username, password, filename) {
  1837. // 确保URL以/结尾
  1838. if (!url.endsWith('/')) {
  1839. url += '/';
  1840. }
  1841.  
  1842. // 从WebDAV服务器获取数据
  1843. return new Promise((resolve, reject) => {
  1844. GM_xmlhttpRequest({
  1845. method: "GET",
  1846. url: url + filename,
  1847. headers: {
  1848. "Authorization": "Basic " + btoa(username + ":" + password)
  1849. },
  1850. onload: (response) => {
  1851. if (response.status >= 200 && response.status < 300) {
  1852. try {
  1853. const data = JSON.parse(response.responseText);
  1854.  
  1855. // 转换数据格式
  1856. const tokens = data.map(item => ({
  1857. name: item.name,
  1858. key: item.sessionKey,
  1859. createdAt: new Date().toLocaleString("zh-CN", {
  1860. month: "2-digit",
  1861. day: "2-digit",
  1862. hour: "2-digit",
  1863. minute: "2-digit",
  1864. }),
  1865. timestamp: Date.now()
  1866. }));
  1867.  
  1868. // 更新tokens
  1869. this.tokens = tokens;
  1870. this.saveTokens();
  1871.  
  1872. resolve();
  1873. } catch (error) {
  1874. console.error("解析WebDAV数据失败:", error, response.responseText);
  1875. reject(new Error(`解析数据失败: ${error.message}`));
  1876. }
  1877. } else {
  1878. console.error("WebDAV恢复失败:", response);
  1879. reject(new Error(`HTTP错误: ${response.status} ${response.statusText || ''}\n响应: ${response.responseText || '无响应内容'}`));
  1880. }
  1881. },
  1882. onerror: function (error) {
  1883. console.error("WebDAV恢复网络错误:", error);
  1884. reject(new Error(`网络错误: ${error.statusText || '连接失败'}`));
  1885. }
  1886. });
  1887. });
  1888. },
  1889.  
  1890. validateInput(name, key) {
  1891. if (!name || !key) {
  1892. alert("Token 名称和密钥都要填写!");
  1893. return false;
  1894. }
  1895. // 移除对token名称的严格限制,允许更多字符,包括@和.
  1896. // if (!/^[a-zA-Z0-9-_]+$/.test(name)) {
  1897. // alert("Token 名称只能包含字母、数字、下划线和连字符!");
  1898. // return false;
  1899. // }
  1900. if (!this.validateTokenKey(key)) {
  1901. alert("无效的 Token 密钥格式!");
  1902. return false;
  1903. }
  1904. return true;
  1905. },
  1906.  
  1907. validateTokenKey(key) {
  1908. return /^sk-ant-sid\d{2}-[A-Za-z0-9_-]*$/.test(key);
  1909. },
  1910.  
  1911. showConfirmDialog(title, message) {
  1912. return new Promise((resolve) => {
  1913. const content = UI.createElem("div", "claude-confirm-dialog");
  1914.  
  1915. content.innerHTML = `
  1916. <div style="font-size: 48px; text-align: center; margin-bottom: 16px;">⚠️</div>
  1917. <div style="font-size: 18px; font-weight: 600; text-align: center; margin-bottom: 12px;">${title}</div>
  1918. <div style="text-align: center; margin-bottom: 24px;">${message}</div>
  1919. `;
  1920.  
  1921. const { modal, buttonContainer, close } = UI.createModal("", content);
  1922. modal.querySelector(".claude-modal-content").classList.add("narrow-modal");
  1923.  
  1924. const confirmButton = UI.createButton("确认", "claude-button primary");
  1925. confirmButton.addEventListener("click", () => {
  1926. close();
  1927. resolve(true);
  1928. });
  1929.  
  1930. const cancelButton = UI.createButton("取消", "claude-button secondary");
  1931. cancelButton.addEventListener("click", () => {
  1932. close();
  1933. resolve(false);
  1934. });
  1935.  
  1936. buttonContainer.appendChild(cancelButton);
  1937. buttonContainer.appendChild(confirmButton);
  1938. });
  1939. },
  1940.  
  1941. fetchIPCountryCode() {
  1942. this.ipDisplay.textContent = "IP: 加载中...";
  1943.  
  1944. GM_xmlhttpRequest({
  1945. method: "GET",
  1946. url: config.ipApiUrl,
  1947. onload: (response) => {
  1948. if (response.status === 200) {
  1949. this.ipDisplay.textContent = "IP: " + response.responseText.trim();
  1950. } else {
  1951. this.ipDisplay.textContent = "IP: 获取失败";
  1952. }
  1953. },
  1954. onerror: () => {
  1955. this.ipDisplay.textContent = "IP: 获取失败";
  1956. },
  1957. });
  1958. },
  1959.  
  1960. setupEventListeners() {
  1961. // 拖拽相关事件
  1962. this.toggleButton.addEventListener("mousedown", this.onMouseDown.bind(this));
  1963. document.addEventListener("mousemove", this.onMouseMove.bind(this));
  1964. document.addEventListener("mouseup", this.onMouseUp.bind(this));
  1965.  
  1966. // 状态管理对象
  1967. this.state = {
  1968. isButtonHovered: false,
  1969. isDropdownHovered: false,
  1970. isDropdownVisible: false,
  1971. isDragging: false,
  1972. isProcessingClick: false, // 新增:处理点击状态
  1973. isClosing: false, // 新增:窗口正在关闭的状态
  1974.  
  1975. // 检查当前是否应该保持弹窗显示
  1976. shouldKeepOpen() {
  1977. // 修改逻辑,即使在拖动过程中,也要考虑鼠标悬停状态
  1978. return this.isButtonHovered || this.isDropdownHovered;
  1979. }
  1980. };
  1981.  
  1982. // 定时器
  1983. this.hoverTimeout = null;
  1984. this.closeTimeout = null;
  1985.  
  1986. // 鼠标进入按钮
  1987. this.toggleButton.addEventListener("mouseenter", (e) => {
  1988. if (this.state.isProcessingClick) return; // 如果正在处理点击,忽略hover
  1989.  
  1990. this.state.isButtonHovered = true;
  1991. clearTimeout(this.closeTimeout);
  1992. clearTimeout(this.hoverTimeout); // 确保清除之前的hover定时器
  1993.  
  1994. // 如果下拉窗口未显示或正在关闭中,则显示窗口
  1995. if (!this.state.isDropdownVisible || this.state.isClosing) {
  1996. // 如果窗口正在关闭,立即显示
  1997. if (this.state.isClosing) {
  1998. this.state.isClosing = false;
  1999. this.showDropdown();
  2000. } else {
  2001. this.hoverTimeout = setTimeout(() => {
  2002. this.showDropdown();
  2003. }, 300);
  2004. }
  2005. }
  2006. });
  2007.  
  2008. // 鼠标离开按钮
  2009. this.toggleButton.addEventListener("mouseleave", (e) => {
  2010. if (this.state.isProcessingClick) return; // 如果正在处理点击,忽略hover
  2011.  
  2012. this.state.isButtonHovered = false;
  2013. clearTimeout(this.hoverTimeout);
  2014.  
  2015. // 检查是否应该关闭弹窗
  2016. if (!this.state.shouldKeepOpen()) {
  2017. this.scheduleHideDropdown();
  2018. }
  2019. });
  2020.  
  2021. // 按钮点击事件
  2022. this.toggleButton.addEventListener("click", (e) => {
  2023. if (this.state.isDragging) return; // 如果正在拖拽,忽略点击
  2024.  
  2025. this.state.isProcessingClick = true;
  2026. clearTimeout(this.hoverTimeout);
  2027. clearTimeout(this.closeTimeout);
  2028.  
  2029. if (this.state.isDropdownVisible) {
  2030. this.hideDropdown();
  2031. } else {
  2032. this.showDropdown();
  2033. }
  2034.  
  2035. setTimeout(() => {
  2036. this.state.isProcessingClick = false;
  2037. }, 100);
  2038. });
  2039.  
  2040. // 鼠标进入弹窗
  2041. this.dropdownContainer.addEventListener("mouseenter", () => {
  2042. if (this.state.isProcessingClick) return;
  2043.  
  2044. this.state.isDropdownHovered = true;
  2045. clearTimeout(this.closeTimeout);
  2046.  
  2047. // 如果弹窗在淡出过程中,恢复显示
  2048. if (this.state.isDropdownVisible && this.dropdownContainer.style.opacity !== "1") {
  2049. this.dropdownContainer.style.opacity = "1";
  2050. this.dropdownContainer.style.transform = "scale(1)";
  2051. }
  2052. });
  2053.  
  2054. // 鼠标离开弹窗
  2055. this.dropdownContainer.addEventListener("mouseleave", () => {
  2056. if (this.state.isProcessingClick) return;
  2057.  
  2058. this.state.isDropdownHovered = false;
  2059.  
  2060. // 检查是否应该关闭弹窗
  2061. if (!this.state.shouldKeepOpen()) {
  2062. this.scheduleHideDropdown();
  2063. }
  2064. });
  2065.  
  2066. // 点击其他区域关闭下拉菜单
  2067. document.addEventListener("click", (e) => {
  2068. if (
  2069. this.dropdownContainer.style.display === "flex" &&
  2070. !this.dropdownContainer.contains(e.target) &&
  2071. e.target !== this.toggleButton
  2072. ) {
  2073. this.state.isDropdownHovered = false;
  2074. this.state.isButtonHovered = false;
  2075. this.hideDropdown();
  2076. }
  2077. });
  2078. },
  2079.  
  2080. onMouseDown(e) {
  2081. if (e.button !== 0) return; // 只处理左键点击
  2082.  
  2083. this.isDragging = true;
  2084. this.state.isDragging = true;
  2085. this.startX = e.clientX;
  2086. this.startY = e.clientY;
  2087.  
  2088. const rect = this.toggleButton.getBoundingClientRect();
  2089. this.offsetX = this.startX - rect.left;
  2090. this.offsetY = this.startY - rect.top;
  2091.  
  2092. this.toggleButton.style.cursor = "grabbing";
  2093.  
  2094. // 不再清除悬停定时器,允许在拖动过程中显示窗口
  2095. // clearTimeout(this.hoverTimeout);
  2096. clearTimeout(this.closeTimeout);
  2097.  
  2098. // 如果鼠标在按钮上,立即显示下拉窗口
  2099. if (this.state.isButtonHovered && !this.state.isDropdownVisible) {
  2100. this.showDropdown();
  2101. }
  2102.  
  2103. // 阻止默认行为和事件冒泡
  2104. e.preventDefault();
  2105. e.stopPropagation();
  2106. },
  2107.  
  2108. onMouseMove(e) {
  2109. // 检查鼠标是否在按钮上,用于处理拖动过程中的悬停
  2110. const buttonRect = this.toggleButton.getBoundingClientRect();
  2111. const isOverButton =
  2112. e.clientX >= buttonRect.left &&
  2113. e.clientX <= buttonRect.right &&
  2114. e.clientY >= buttonRect.top &&
  2115. e.clientY <= buttonRect.bottom;
  2116.  
  2117. // 更新悬停状态
  2118. if (isOverButton && !this.state.isButtonHovered) {
  2119. this.state.isButtonHovered = true;
  2120. // 如果下拉窗口未显示或正在关闭中,则显示窗口
  2121. if (!this.state.isDropdownVisible || this.state.isClosing) {
  2122. clearTimeout(this.hoverTimeout);
  2123. // 如果窗口正在关闭或正在拖动,立即显示
  2124. if (this.state.isClosing || this.isDragging) {
  2125. this.state.isClosing = false;
  2126. this.showDropdown();
  2127. } else {
  2128. this.hoverTimeout = setTimeout(() => {
  2129. this.showDropdown();
  2130. }, 300);
  2131. }
  2132. }
  2133. } else if (!isOverButton && this.state.isButtonHovered) {
  2134. this.state.isButtonHovered = false;
  2135. clearTimeout(this.hoverTimeout);
  2136. if (!this.state.shouldKeepOpen()) {
  2137. this.scheduleHideDropdown();
  2138. }
  2139. }
  2140.  
  2141. if (!this.isDragging) return;
  2142.  
  2143. const x = e.clientX - this.offsetX;
  2144. const y = e.clientY - this.offsetY;
  2145.  
  2146. // 计算底部位置
  2147. const bottom = window.innerHeight - y - this.toggleButton.offsetHeight;
  2148.  
  2149. // 确保按钮在窗口范围内
  2150. const maxX = window.innerWidth - this.toggleButton.offsetWidth;
  2151. const maxBottom = window.innerHeight - this.toggleButton.offsetHeight;
  2152.  
  2153. this.buttonLeft = Math.max(0, Math.min(x, maxX));
  2154. this.buttonBottom = Math.max(0, Math.min(bottom, maxBottom));
  2155.  
  2156. // 更新按钮位置
  2157. this.toggleButton.style.left = `${this.buttonLeft}px`;
  2158. this.toggleButton.style.bottom = `${this.buttonBottom}px`;
  2159. this.toggleButton.style.top = "auto";
  2160.  
  2161. // 如果下拉窗口可见,更新其位置
  2162. if (this.state.isDropdownVisible) {
  2163. this.updateDropdownPosition();
  2164. }
  2165.  
  2166. e.preventDefault();
  2167. },
  2168.  
  2169. // 添加新方法用于更新下拉窗口位置
  2170. updateDropdownPosition() {
  2171. const buttonRect = this.toggleButton.getBoundingClientRect();
  2172. const dropdownWidth = 600; // 下拉窗口宽度
  2173.  
  2174. // 计算下拉窗口位置
  2175. let left = buttonRect.right + 10;
  2176. let top = buttonRect.top;
  2177.  
  2178. // 检查是否超出右边界
  2179. if (left + dropdownWidth > window.innerWidth) {
  2180. // 如果右边放不下,则放到左边
  2181. left = buttonRect.left - dropdownWidth - 10;
  2182. }
  2183.  
  2184. // 如果左边也放不下,则居中显示
  2185. if (left < 0) {
  2186. left = Math.max(0, (window.innerWidth - dropdownWidth) / 2);
  2187. }
  2188.  
  2189. // 检查是否超出底部边界
  2190. const dropdownHeight = Math.min(this.dropdownContainer.scrollHeight, window.innerHeight * 0.8);
  2191. if (top + dropdownHeight > window.innerHeight) {
  2192. // 如果超出底部,则向上显示,确保完全可见
  2193. top = Math.max(0, window.innerHeight - dropdownHeight - 10);
  2194. }
  2195.  
  2196. // 应用新位置
  2197. this.dropdownContainer.style.left = `${left}px`;
  2198. this.dropdownContainer.style.top = `${top}px`;
  2199. },
  2200.  
  2201. onMouseUp(e) {
  2202. if (!this.isDragging) return;
  2203.  
  2204. this.isDragging = false;
  2205. this.state.isDragging = false;
  2206. this.toggleButton.style.cursor = "move";
  2207.  
  2208. // 保存位置
  2209. GM_setValue("buttonLeft", this.buttonLeft);
  2210. GM_setValue("buttonBottom", this.buttonBottom);
  2211.  
  2212. // 检查鼠标是否在按钮上
  2213. const buttonRect = this.toggleButton.getBoundingClientRect();
  2214. const isOverButton =
  2215. e.clientX >= buttonRect.left &&
  2216. e.clientX <= buttonRect.right &&
  2217. e.clientY >= buttonRect.top &&
  2218. e.clientY <= buttonRect.bottom;
  2219.  
  2220. // 更新悬停状态
  2221. this.state.isButtonHovered = isOverButton;
  2222.  
  2223. // 添加短暂延迟,避免与点击事件冲突
  2224. setTimeout(() => {
  2225. // 如果鼠标在按钮上且下拉窗口未显示,则显示下拉窗口
  2226. if (isOverButton && !this.state.isDropdownVisible) {
  2227. this.showDropdown();
  2228. }
  2229. // 否则检查是否应该关闭弹窗
  2230. else if (!this.state.shouldKeepOpen()) {
  2231. this.scheduleHideDropdown();
  2232. }
  2233. }, 100);
  2234.  
  2235. e.preventDefault();
  2236. },
  2237.  
  2238. scheduleHideDropdown() {
  2239. if (this.state.isProcessingClick) return;
  2240.  
  2241. clearTimeout(this.closeTimeout);
  2242. this.closeTimeout = setTimeout(() => {
  2243. if (!this.state.shouldKeepOpen()) {
  2244. this.hideDropdown();
  2245. }
  2246. }, 300);
  2247. },
  2248.  
  2249. showDropdown() {
  2250. // 立即更新状态
  2251. this.state.isDropdownVisible = true;
  2252. this.state.isClosing = false;
  2253.  
  2254. // 计算下拉菜单位置
  2255. const buttonRect = this.toggleButton.getBoundingClientRect();
  2256. const dropdownWidth = 600;
  2257.  
  2258. // 先显示容器但设为透明,以便获取实际高度
  2259. this.dropdownContainer.style.opacity = "0";
  2260. this.dropdownContainer.style.display = "flex";
  2261.  
  2262. // 更新下拉窗口位置
  2263. this.updateDropdownPosition();
  2264.  
  2265. // 淡入效果
  2266. setTimeout(() => {
  2267. this.dropdownContainer.style.opacity = "1";
  2268. this.dropdownContainer.style.transform = "scale(1)";
  2269. this.toggleButton.style.transform = "scale(1.1)";
  2270. }, 10);
  2271. },
  2272.  
  2273. hideDropdown() {
  2274. // 设置正在关闭状态
  2275. this.state.isClosing = true;
  2276.  
  2277. // 添加动画
  2278. this.dropdownContainer.style.opacity = "0";
  2279. this.dropdownContainer.style.transform = "scale(0.95)";
  2280. this.toggleButton.style.transform = "scale(1)";
  2281.  
  2282. // 等待动画完成后隐藏
  2283. this.closeTimeout = setTimeout(() => {
  2284. if (!this.state.shouldKeepOpen()) {
  2285. this.dropdownContainer.style.display = "none";
  2286. this.state.isDropdownVisible = false;
  2287. this.state.isClosing = false; // 重置关闭状态
  2288. } else {
  2289. // 如果此时应该保持打开,则恢复显示
  2290. this.state.isClosing = false; // 重置关闭状态
  2291. this.dropdownContainer.style.opacity = "1";
  2292. this.dropdownContainer.style.transform = "scale(1)";
  2293. }
  2294. }, 300);
  2295. },
  2296.  
  2297. observeThemeChanges() {
  2298. const observer = new MutationObserver((mutations) => {
  2299. mutations.forEach((mutation) => {
  2300. if (
  2301. mutation.type === "attributes" &&
  2302. mutation.attributeName === "data-mode"
  2303. ) {
  2304. this.isDarkMode =
  2305. document.documentElement.getAttribute("data-mode") === "dark";
  2306. this.updateStyles();
  2307. }
  2308. });
  2309. });
  2310.  
  2311. observer.observe(document.documentElement, {
  2312. attributes: true,
  2313. attributeFilter: ["data-mode"],
  2314. });
  2315. },
  2316. };
  2317.  
  2318. // 初始化应用
  2319. App.init();
  2320. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址