sidepanel.js 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const settingsCard = document.getElementById('settings-card');
  13. const displayOauthUrl = document.getElementById('display-oauth-url');
  14. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  15. const displayStatus = document.getElementById('display-status');
  16. const statusBar = document.getElementById('status-bar');
  17. const inputEmail = document.getElementById('input-email');
  18. const inputPassword = document.getElementById('input-password');
  19. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  20. const btnToggleVpsPassword = document.getElementById('btn-toggle-vps-password');
  21. const btnFetchEmail = document.getElementById('btn-fetch-email');
  22. const btnTogglePassword = document.getElementById('btn-toggle-password');
  23. const btnSaveSettings = document.getElementById('btn-save-settings');
  24. const btnStop = document.getElementById('btn-stop');
  25. const btnReset = document.getElementById('btn-reset');
  26. const stepsProgress = document.getElementById('steps-progress');
  27. const btnAutoRun = document.getElementById('btn-auto-run');
  28. const btnAutoContinue = document.getElementById('btn-auto-continue');
  29. const autoContinueBar = document.getElementById('auto-continue-bar');
  30. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  31. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  32. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  33. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  34. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  35. const btnClearLog = document.getElementById('btn-clear-log');
  36. const configMenuShell = document.getElementById('config-menu-shell');
  37. const btnConfigMenu = document.getElementById('btn-config-menu');
  38. const configMenu = document.getElementById('config-menu');
  39. const btnExportSettings = document.getElementById('btn-export-settings');
  40. const btnImportSettings = document.getElementById('btn-import-settings');
  41. const inputImportSettingsFile = document.getElementById('input-import-settings-file');
  42. const selectPanelMode = document.getElementById('select-panel-mode');
  43. const rowVpsUrl = document.getElementById('row-vps-url');
  44. const inputVpsUrl = document.getElementById('input-vps-url');
  45. const rowVpsPassword = document.getElementById('row-vps-password');
  46. const inputVpsPassword = document.getElementById('input-vps-password');
  47. const rowLocalCpaStep9Mode = document.getElementById('row-local-cpa-step9-mode');
  48. const localCpaStep9ModeButtons = Array.from(document.querySelectorAll('[data-local-cpa-step9-mode]'));
  49. const rowSub2ApiUrl = document.getElementById('row-sub2api-url');
  50. const inputSub2ApiUrl = document.getElementById('input-sub2api-url');
  51. const rowSub2ApiEmail = document.getElementById('row-sub2api-email');
  52. const inputSub2ApiEmail = document.getElementById('input-sub2api-email');
  53. const rowSub2ApiPassword = document.getElementById('row-sub2api-password');
  54. const inputSub2ApiPassword = document.getElementById('input-sub2api-password');
  55. const rowSub2ApiGroup = document.getElementById('row-sub2api-group');
  56. const inputSub2ApiGroup = document.getElementById('input-sub2api-group');
  57. const selectMailProvider = document.getElementById('select-mail-provider');
  58. const rowEmailGenerator = document.getElementById('row-email-generator');
  59. const selectEmailGenerator = document.getElementById('select-email-generator');
  60. const hotmailSection = document.getElementById('hotmail-section');
  61. const rowHotmailServiceMode = document.getElementById('row-hotmail-service-mode');
  62. const hotmailServiceModeButtons = Array.from(document.querySelectorAll('[data-hotmail-service-mode]'));
  63. const rowHotmailRemoteBaseUrl = document.getElementById('row-hotmail-remote-base-url');
  64. const inputHotmailRemoteBaseUrl = document.getElementById('input-hotmail-remote-base-url');
  65. const rowHotmailLocalBaseUrl = document.getElementById('row-hotmail-local-base-url');
  66. const inputHotmailLocalBaseUrl = document.getElementById('input-hotmail-local-base-url');
  67. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  68. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  69. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  70. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  71. const inputHotmailImport = document.getElementById('input-hotmail-import');
  72. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  73. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  74. const btnHotmailUsageGuide = document.getElementById('btn-hotmail-usage-guide');
  75. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  76. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  77. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  78. const hotmailListShell = document.getElementById('hotmail-list-shell');
  79. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  80. const rowInbucketHost = document.getElementById('row-inbucket-host');
  81. const inputInbucketHost = document.getElementById('input-inbucket-host');
  82. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  83. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  84. const rowCfDomain = document.getElementById('row-cf-domain');
  85. const selectCfDomain = document.getElementById('select-cf-domain');
  86. const inputCfDomain = document.getElementById('input-cf-domain');
  87. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  88. const inputRunCount = document.getElementById('input-run-count');
  89. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  90. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  91. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  92. const autoStartModal = document.getElementById('auto-start-modal');
  93. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  94. const autoStartMessage = document.getElementById('auto-start-message');
  95. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  96. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  97. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  98. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  99. const autoHintText = document.querySelector('.auto-hint');
  100. const STEP_DEFAULT_STATUSES = {
  101. 1: 'pending',
  102. 2: 'pending',
  103. 3: 'pending',
  104. 4: 'pending',
  105. 5: 'pending',
  106. 6: 'pending',
  107. 7: 'pending',
  108. 8: 'pending',
  109. 9: 'pending',
  110. };
  111. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  112. const AUTO_DELAY_MIN_MINUTES = 1;
  113. const AUTO_DELAY_MAX_MINUTES = 1440;
  114. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  115. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  116. const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
  117. const HOTMAIL_SERVICE_MODE_LOCAL = 'local';
  118. let latestState = null;
  119. let currentAutoRun = {
  120. autoRunning: false,
  121. phase: 'idle',
  122. currentRun: 0,
  123. totalRuns: 1,
  124. attemptRun: 0,
  125. scheduledAt: null,
  126. };
  127. let settingsDirty = false;
  128. let settingsSaveInFlight = false;
  129. let settingsAutoSaveTimer = null;
  130. let cloudflareDomainEditMode = false;
  131. let modalChoiceResolver = null;
  132. let currentModalActions = [];
  133. let scheduledCountdownTimer = null;
  134. let hotmailActionInFlight = false;
  135. let hotmailListExpanded = false;
  136. let configMenuOpen = false;
  137. let configActionInFlight = false;
  138. const EYE_OPEN_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>';
  139. const EYE_CLOSED_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19C5 19 1 12 1 12a21.77 21.77 0 0 1 5.06-6.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.86 21.86 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
  140. const COPY_ICON = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
  141. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  142. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  143. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  144. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  145. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  146. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  147. const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
  148. // ============================================================
  149. // Toast Notifications
  150. // ============================================================
  151. const toastContainer = document.getElementById('toast-container');
  152. const TOAST_ICONS = {
  153. error: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
  154. warn: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  155. success: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
  156. info: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  157. };
  158. const LOG_LEVEL_LABELS = {
  159. info: '信息',
  160. ok: '成功',
  161. warn: '警告',
  162. error: '错误',
  163. };
  164. function showToast(message, type = 'error', duration = 4000) {
  165. const toast = document.createElement('div');
  166. toast.className = `toast toast-${type}`;
  167. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  168. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  169. toastContainer.appendChild(toast);
  170. if (duration > 0) {
  171. setTimeout(() => dismissToast(toast), duration);
  172. }
  173. }
  174. function dismissToast(toast) {
  175. if (!toast.parentNode) return;
  176. toast.classList.add('toast-exit');
  177. toast.addEventListener('animationend', () => toast.remove());
  178. }
  179. function resetActionModalButtons() {
  180. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  181. buttons.forEach((button) => {
  182. if (!button) return;
  183. button.hidden = true;
  184. button.disabled = false;
  185. button.onclick = null;
  186. });
  187. currentModalActions = [];
  188. }
  189. function configureActionModalButton(button, action) {
  190. if (!button) return;
  191. if (!action) {
  192. button.hidden = true;
  193. button.onclick = null;
  194. return;
  195. }
  196. button.hidden = false;
  197. button.disabled = false;
  198. button.textContent = action.label;
  199. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  200. button.onclick = () => resolveModalChoice(action.id);
  201. }
  202. function resolveModalChoice(choice) {
  203. if (modalChoiceResolver) {
  204. modalChoiceResolver(choice);
  205. modalChoiceResolver = null;
  206. }
  207. resetActionModalButtons();
  208. if (autoStartModal) {
  209. autoStartModal.hidden = true;
  210. }
  211. }
  212. function openActionModal({ title, message, actions }) {
  213. if (!autoStartModal) {
  214. return Promise.resolve(null);
  215. }
  216. if (modalChoiceResolver) {
  217. resolveModalChoice(null);
  218. }
  219. autoStartTitle.textContent = title;
  220. autoStartMessage.textContent = message;
  221. currentModalActions = actions || [];
  222. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  223. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  224. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  225. autoStartModal.hidden = false;
  226. return new Promise((resolve) => {
  227. modalChoiceResolver = resolve;
  228. });
  229. }
  230. function openAutoStartChoiceDialog(startStep, options = {}) {
  231. const runningStep = Number.isInteger(options.runningStep) ? options.runningStep : null;
  232. const continueMessage = runningStep
  233. ? `继续当前会先等待步骤 ${runningStep} 完成,再按最新进度自动执行。`
  234. : `继续当前会从步骤 ${startStep} 开始自动执行。`;
  235. return openActionModal({
  236. title: '启动自动',
  237. message: `检测到当前已有流程进度。${continueMessage}重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  238. actions: [
  239. { id: null, label: '取消', variant: 'btn-ghost' },
  240. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  241. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  242. ],
  243. });
  244. }
  245. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  246. const choice = await openActionModal({
  247. title,
  248. message,
  249. actions: [
  250. { id: null, label: '取消', variant: 'btn-ghost' },
  251. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  252. ],
  253. });
  254. return choice === 'confirm';
  255. }
  256. function updateConfigMenuControls() {
  257. const disabled = configActionInFlight || settingsSaveInFlight;
  258. const importLocked = disabled
  259. || currentAutoRun.autoRunning
  260. || Object.values(getStepStatuses()).some((status) => status === 'running');
  261. if (btnConfigMenu) {
  262. btnConfigMenu.disabled = disabled;
  263. btnConfigMenu.setAttribute('aria-expanded', String(configMenuOpen));
  264. }
  265. if (configMenu) {
  266. configMenu.hidden = !configMenuOpen;
  267. }
  268. if (btnExportSettings) {
  269. btnExportSettings.disabled = disabled;
  270. }
  271. if (btnImportSettings) {
  272. btnImportSettings.disabled = importLocked;
  273. }
  274. }
  275. function closeConfigMenu() {
  276. configMenuOpen = false;
  277. updateConfigMenuControls();
  278. }
  279. function openConfigMenu() {
  280. configMenuOpen = true;
  281. updateConfigMenuControls();
  282. }
  283. function toggleConfigMenu() {
  284. configMenuOpen ? closeConfigMenu() : openConfigMenu();
  285. }
  286. async function waitForSettingsSaveIdle() {
  287. while (settingsSaveInFlight) {
  288. await new Promise((resolve) => setTimeout(resolve, 50));
  289. }
  290. }
  291. async function flushPendingSettingsBeforeExport() {
  292. clearTimeout(settingsAutoSaveTimer);
  293. await waitForSettingsSaveIdle();
  294. if (settingsDirty) {
  295. await saveSettings({ silent: true });
  296. }
  297. }
  298. async function settlePendingSettingsBeforeImport() {
  299. clearTimeout(settingsAutoSaveTimer);
  300. await waitForSettingsSaveIdle();
  301. }
  302. function downloadTextFile(content, fileName, mimeType = 'application/json;charset=utf-8') {
  303. const blob = new Blob([content], { type: mimeType });
  304. const objectUrl = URL.createObjectURL(blob);
  305. const anchor = document.createElement('a');
  306. anchor.href = objectUrl;
  307. anchor.download = fileName;
  308. document.body.appendChild(anchor);
  309. anchor.click();
  310. anchor.remove();
  311. setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
  312. }
  313. function isDoneStatus(status) {
  314. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  315. }
  316. function getStepStatuses(state = latestState) {
  317. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  318. }
  319. function getFirstUnfinishedStep(state = latestState) {
  320. const statuses = getStepStatuses(state);
  321. for (let step = 1; step <= 9; step++) {
  322. if (!isDoneStatus(statuses[step])) {
  323. return step;
  324. }
  325. }
  326. return null;
  327. }
  328. function getRunningSteps(state = latestState) {
  329. const statuses = getStepStatuses(state);
  330. return Object.entries(statuses)
  331. .filter(([, status]) => status === 'running')
  332. .map(([step]) => Number(step))
  333. .sort((a, b) => a - b);
  334. }
  335. function hasSavedProgress(state = latestState) {
  336. const statuses = getStepStatuses(state);
  337. return Object.values(statuses).some((status) => status !== 'pending');
  338. }
  339. function shouldOfferAutoModeChoice(state = latestState) {
  340. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  341. }
  342. function syncLatestState(nextState) {
  343. const mergedStepStatuses = nextState?.stepStatuses
  344. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  345. : getStepStatuses(latestState);
  346. latestState = {
  347. ...(latestState || {}),
  348. ...(nextState || {}),
  349. stepStatuses: mergedStepStatuses,
  350. };
  351. }
  352. function syncAutoRunState(source = {}) {
  353. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  354. const autoRunning = source.autoRunning !== undefined
  355. ? Boolean(source.autoRunning)
  356. : (source.autoRunPhase !== undefined || source.phase !== undefined
  357. ? ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(phase)
  358. : currentAutoRun.autoRunning);
  359. currentAutoRun = {
  360. autoRunning,
  361. phase,
  362. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  363. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  364. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  365. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  366. };
  367. }
  368. function isAutoRunLockedPhase() {
  369. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'waiting_step' || currentAutoRun.phase === 'retrying';
  370. }
  371. function isAutoRunPausedPhase() {
  372. return currentAutoRun.phase === 'waiting_email';
  373. }
  374. function isAutoRunWaitingStepPhase() {
  375. return currentAutoRun.phase === 'waiting_step';
  376. }
  377. function isAutoRunScheduledPhase() {
  378. return currentAutoRun.phase === 'scheduled';
  379. }
  380. function getAutoRunLabel(payload = currentAutoRun) {
  381. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  382. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  383. }
  384. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  385. if ((payload.totalRuns || 1) > 1) {
  386. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  387. }
  388. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  389. }
  390. function normalizeAutoDelayMinutes(value) {
  391. const numeric = Number(value);
  392. if (!Number.isFinite(numeric)) {
  393. return AUTO_DELAY_DEFAULT_MINUTES;
  394. }
  395. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  396. }
  397. function updateAutoDelayInputState() {
  398. const scheduled = isAutoRunScheduledPhase();
  399. inputAutoDelayEnabled.disabled = scheduled;
  400. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  401. }
  402. function formatCountdown(remainingMs) {
  403. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  404. const hours = Math.floor(totalSeconds / 3600);
  405. const minutes = Math.floor((totalSeconds % 3600) / 60);
  406. const seconds = totalSeconds % 60;
  407. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  408. }
  409. function formatScheduleTime(timestamp) {
  410. return new Date(timestamp).toLocaleString('zh-CN', {
  411. hour12: false,
  412. month: '2-digit',
  413. day: '2-digit',
  414. hour: '2-digit',
  415. minute: '2-digit',
  416. second: '2-digit',
  417. });
  418. }
  419. function stopScheduledCountdownTicker() {
  420. clearInterval(scheduledCountdownTimer);
  421. scheduledCountdownTimer = null;
  422. }
  423. function renderScheduledAutoRunInfo() {
  424. if (!autoScheduleBar) {
  425. return;
  426. }
  427. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  428. autoScheduleBar.style.display = 'none';
  429. return;
  430. }
  431. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  432. autoScheduleBar.style.display = 'flex';
  433. autoScheduleTitle.textContent = '已计划自动运行';
  434. autoScheduleMeta.textContent = remainingMs > 0
  435. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  436. : '倒计时即将结束,正在准备启动...';
  437. }
  438. function syncScheduledCountdownTicker() {
  439. renderScheduledAutoRunInfo();
  440. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  441. stopScheduledCountdownTicker();
  442. return;
  443. }
  444. if (scheduledCountdownTimer) {
  445. return;
  446. }
  447. scheduledCountdownTimer = setInterval(() => {
  448. renderScheduledAutoRunInfo();
  449. updateStatusDisplay(latestState);
  450. }, 1000);
  451. }
  452. function setDefaultAutoRunButton() {
  453. btnAutoRun.disabled = false;
  454. inputRunCount.disabled = false;
  455. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> 自动';
  456. }
  457. function normalizeCloudflareDomainValue(value = '') {
  458. let normalized = String(value || '').trim().toLowerCase();
  459. if (!normalized) return '';
  460. normalized = normalized.replace(/^@+/, '');
  461. normalized = normalized.replace(/^https?:\/\//, '');
  462. normalized = normalized.replace(/\/.*$/, '');
  463. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  464. return '';
  465. }
  466. return normalized;
  467. }
  468. function normalizeCloudflareDomains(values = []) {
  469. const seen = new Set();
  470. const domains = [];
  471. for (const value of Array.isArray(values) ? values : []) {
  472. const normalized = normalizeCloudflareDomainValue(value);
  473. if (!normalized || seen.has(normalized)) continue;
  474. seen.add(normalized);
  475. domains.push(normalized);
  476. }
  477. return domains;
  478. }
  479. function getCloudflareDomainsFromState() {
  480. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  481. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  482. if (activeDomain && !domains.includes(activeDomain)) {
  483. domains.unshift(activeDomain);
  484. }
  485. return { domains, activeDomain: activeDomain || domains[0] || '' };
  486. }
  487. function renderCloudflareDomainOptions(preferredDomain = '') {
  488. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  489. const { domains, activeDomain } = getCloudflareDomainsFromState();
  490. const selected = preferred || activeDomain;
  491. selectCfDomain.innerHTML = '';
  492. if (domains.length === 0) {
  493. const option = document.createElement('option');
  494. option.value = '';
  495. option.textContent = '请先添加域名';
  496. selectCfDomain.appendChild(option);
  497. selectCfDomain.disabled = true;
  498. selectCfDomain.value = '';
  499. return;
  500. }
  501. for (const domain of domains) {
  502. const option = document.createElement('option');
  503. option.value = domain;
  504. option.textContent = domain;
  505. selectCfDomain.appendChild(option);
  506. }
  507. selectCfDomain.disabled = false;
  508. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  509. }
  510. function setCloudflareDomainEditMode(editing, options = {}) {
  511. const { clearInput = false } = options;
  512. cloudflareDomainEditMode = Boolean(editing);
  513. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  514. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  515. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  516. if (cloudflareDomainEditMode) {
  517. if (clearInput) {
  518. inputCfDomain.value = '';
  519. }
  520. inputCfDomain.focus();
  521. } else if (clearInput) {
  522. inputCfDomain.value = '';
  523. }
  524. }
  525. function collectSettingsPayload() {
  526. const { domains, activeDomain } = getCloudflareDomainsFromState();
  527. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  528. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  529. ) || activeDomain;
  530. return {
  531. panelMode: selectPanelMode.value,
  532. vpsUrl: inputVpsUrl.value.trim(),
  533. vpsPassword: inputVpsPassword.value,
  534. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  535. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  536. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  537. sub2apiPassword: inputSub2ApiPassword.value,
  538. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  539. customPassword: inputPassword.value,
  540. mailProvider: selectMailProvider.value,
  541. emailGenerator: selectEmailGenerator.value,
  542. inbucketHost: inputInbucketHost.value.trim(),
  543. inbucketMailbox: inputInbucketMailbox.value.trim(),
  544. hotmailServiceMode: getSelectedHotmailServiceMode(),
  545. hotmailRemoteBaseUrl: inputHotmailRemoteBaseUrl.value.trim(),
  546. hotmailLocalBaseUrl: inputHotmailLocalBaseUrl.value.trim(),
  547. cloudflareDomain: selectedCloudflareDomain,
  548. cloudflareDomains: domains,
  549. autoRunSkipFailures: inputAutoSkipFailures.checked,
  550. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  551. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  552. };
  553. }
  554. function normalizeLocalCpaStep9Mode(value = '') {
  555. return String(value || '').trim().toLowerCase() === 'bypass'
  556. ? 'bypass'
  557. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  558. }
  559. function normalizeHotmailServiceMode(value = '') {
  560. return HOTMAIL_SERVICE_MODE_LOCAL;
  561. }
  562. function getSelectedLocalCpaStep9Mode() {
  563. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  564. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  565. }
  566. function setLocalCpaStep9Mode(mode) {
  567. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  568. localCpaStep9ModeButtons.forEach((button) => {
  569. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  570. button.classList.toggle('is-active', active);
  571. button.setAttribute('aria-pressed', String(active));
  572. });
  573. }
  574. function getSelectedHotmailServiceMode() {
  575. const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active'));
  576. return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode);
  577. }
  578. function setHotmailServiceMode(mode) {
  579. const resolvedMode = normalizeHotmailServiceMode(mode);
  580. hotmailServiceModeButtons.forEach((button) => {
  581. const isRemoteMode = button.dataset.hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE;
  582. const active = button.dataset.hotmailServiceMode === resolvedMode;
  583. button.disabled = isRemoteMode;
  584. button.setAttribute('aria-disabled', String(isRemoteMode));
  585. button.classList.toggle('is-active', active);
  586. button.setAttribute('aria-pressed', String(active));
  587. });
  588. }
  589. function setSettingsCardLocked(locked) {
  590. if (!settingsCard) {
  591. return;
  592. }
  593. settingsCard.classList.toggle('is-locked', locked);
  594. settingsCard.toggleAttribute('inert', locked);
  595. }
  596. async function setRuntimeEmailState(email) {
  597. const normalizedEmail = String(email || '').trim() || null;
  598. const response = await chrome.runtime.sendMessage({
  599. type: 'SET_EMAIL_STATE',
  600. source: 'sidepanel',
  601. payload: { email: normalizedEmail },
  602. });
  603. if (response?.error) {
  604. throw new Error(response.error);
  605. }
  606. return normalizedEmail;
  607. }
  608. async function clearRegistrationEmail(options = {}) {
  609. const { silent = false } = options;
  610. if (!inputEmail.value.trim() && !latestState?.email) {
  611. return;
  612. }
  613. inputEmail.value = '';
  614. syncLatestState({ email: null });
  615. try {
  616. await setRuntimeEmailState(null);
  617. } catch (err) {
  618. if (!silent) {
  619. showToast(`清空邮箱失败:${err.message}`, 'error');
  620. }
  621. throw err;
  622. }
  623. }
  624. function markSettingsDirty(isDirty = true) {
  625. settingsDirty = isDirty;
  626. updateSaveButtonState();
  627. }
  628. function updateSaveButtonState() {
  629. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  630. updateConfigMenuControls();
  631. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  632. }
  633. function scheduleSettingsAutoSave() {
  634. clearTimeout(settingsAutoSaveTimer);
  635. settingsAutoSaveTimer = setTimeout(() => {
  636. saveSettings({ silent: true }).catch(() => { });
  637. }, 500);
  638. }
  639. async function saveSettings(options = {}) {
  640. const { silent = false } = options;
  641. clearTimeout(settingsAutoSaveTimer);
  642. if (!settingsDirty && !settingsSaveInFlight && silent) {
  643. return;
  644. }
  645. const payload = collectSettingsPayload();
  646. settingsSaveInFlight = true;
  647. updateSaveButtonState();
  648. try {
  649. const response = await chrome.runtime.sendMessage({
  650. type: 'SAVE_SETTING',
  651. source: 'sidepanel',
  652. payload,
  653. });
  654. if (response?.error) {
  655. throw new Error(response.error);
  656. }
  657. if (response?.state) {
  658. applySettingsState(response.state);
  659. } else {
  660. syncLatestState(payload);
  661. markSettingsDirty(false);
  662. updatePanelModeUI();
  663. updateMailProviderUI();
  664. updateButtonStates();
  665. }
  666. if (!silent) {
  667. showToast('配置已保存', 'success', 1800);
  668. }
  669. } catch (err) {
  670. markSettingsDirty(true);
  671. if (!silent) {
  672. showToast(`保存失败:${err.message}`, 'error');
  673. }
  674. throw err;
  675. } finally {
  676. settingsSaveInFlight = false;
  677. updateSaveButtonState();
  678. }
  679. }
  680. function applyAutoRunStatus(payload = currentAutoRun) {
  681. syncAutoRunState(payload);
  682. const runLabel = getAutoRunLabel(currentAutoRun);
  683. const locked = isAutoRunLockedPhase();
  684. const paused = isAutoRunPausedPhase();
  685. const scheduled = isAutoRunScheduledPhase();
  686. const settingsCardLocked = scheduled || locked;
  687. setSettingsCardLocked(settingsCardLocked);
  688. inputRunCount.disabled = currentAutoRun.autoRunning;
  689. btnAutoRun.disabled = currentAutoRun.autoRunning;
  690. btnFetchEmail.disabled = locked;
  691. inputEmail.disabled = locked;
  692. inputAutoSkipFailures.disabled = scheduled;
  693. if (currentAutoRun.totalRuns > 0) {
  694. inputRunCount.value = String(currentAutoRun.totalRuns);
  695. }
  696. switch (currentAutoRun.phase) {
  697. case 'scheduled':
  698. autoContinueBar.style.display = 'none';
  699. btnAutoRun.innerHTML = `已计划${runLabel}`;
  700. break;
  701. case 'waiting_step':
  702. autoContinueBar.style.display = 'none';
  703. btnAutoRun.innerHTML = `等待中${runLabel}`;
  704. break;
  705. case 'waiting_email':
  706. autoContinueBar.style.display = 'flex';
  707. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  708. break;
  709. case 'running':
  710. autoContinueBar.style.display = 'none';
  711. btnAutoRun.innerHTML = `运行中${runLabel}`;
  712. break;
  713. case 'retrying':
  714. autoContinueBar.style.display = 'none';
  715. btnAutoRun.innerHTML = `重试中${runLabel}`;
  716. break;
  717. default:
  718. autoContinueBar.style.display = 'none';
  719. setDefaultAutoRunButton();
  720. inputEmail.disabled = false;
  721. if (!locked) {
  722. btnFetchEmail.disabled = false;
  723. }
  724. break;
  725. }
  726. updateAutoDelayInputState();
  727. syncScheduledCountdownTicker();
  728. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  729. updateConfigMenuControls();
  730. }
  731. function initializeManualStepActions() {
  732. document.querySelectorAll('.step-row').forEach((row) => {
  733. const step = Number(row.dataset.step);
  734. const statusEl = row.querySelector('.step-status');
  735. if (!statusEl) return;
  736. const actions = document.createElement('div');
  737. actions.className = 'step-actions';
  738. const manualBtn = document.createElement('button');
  739. manualBtn.type = 'button';
  740. manualBtn.className = 'step-manual-btn';
  741. manualBtn.dataset.step = String(step);
  742. manualBtn.title = '跳过此步';
  743. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  744. manualBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';
  745. manualBtn.addEventListener('click', async (event) => {
  746. event.stopPropagation();
  747. try {
  748. await handleSkipStep(step);
  749. } catch (err) {
  750. showToast(err.message, 'error');
  751. }
  752. });
  753. statusEl.parentNode.replaceChild(actions, statusEl);
  754. actions.appendChild(manualBtn);
  755. actions.appendChild(statusEl);
  756. });
  757. }
  758. // ============================================================
  759. // State Restore on load
  760. // ============================================================
  761. function applySettingsState(state) {
  762. syncLatestState(state);
  763. syncAutoRunState(state);
  764. inputEmail.value = state?.email || '';
  765. syncPasswordField(state || {});
  766. inputVpsUrl.value = state?.vpsUrl || '';
  767. inputVpsPassword.value = state?.vpsPassword || '';
  768. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  769. selectPanelMode.value = state?.panelMode || 'cpa';
  770. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  771. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  772. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  773. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  774. selectMailProvider.value = state?.mailProvider || '163';
  775. selectEmailGenerator.value = state?.emailGenerator || 'duck';
  776. inputInbucketHost.value = state?.inbucketHost || '';
  777. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  778. setHotmailServiceMode(state?.hotmailServiceMode);
  779. inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || '';
  780. inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || '';
  781. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  782. setCloudflareDomainEditMode(false, { clearInput: true });
  783. inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures);
  784. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  785. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  786. if (state?.autoRunTotalRuns) {
  787. inputRunCount.value = String(state.autoRunTotalRuns);
  788. }
  789. applyAutoRunStatus(state);
  790. markSettingsDirty(false);
  791. updateAutoDelayInputState();
  792. updatePanelModeUI();
  793. updateMailProviderUI();
  794. updateButtonStates();
  795. }
  796. async function restoreState() {
  797. try {
  798. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  799. applySettingsState(state);
  800. if (state.oauthUrl) {
  801. displayOauthUrl.textContent = state.oauthUrl;
  802. displayOauthUrl.classList.add('has-value');
  803. }
  804. if (state.localhostUrl) {
  805. displayLocalhostUrl.textContent = state.localhostUrl;
  806. displayLocalhostUrl.classList.add('has-value');
  807. }
  808. if (state.stepStatuses) {
  809. for (const [step, status] of Object.entries(state.stepStatuses)) {
  810. updateStepUI(Number(step), status);
  811. }
  812. }
  813. if (state.logs) {
  814. for (const entry of state.logs) {
  815. appendLog(entry);
  816. }
  817. }
  818. updateStatusDisplay(latestState);
  819. updateProgressCounter();
  820. } catch (err) {
  821. console.error('Failed to restore state:', err);
  822. }
  823. }
  824. function syncPasswordField(state) {
  825. inputPassword.value = state.customPassword || state.password || '';
  826. }
  827. function getSelectedEmailGenerator() {
  828. return selectEmailGenerator.value === 'cloudflare' ? 'cloudflare' : 'duck';
  829. }
  830. function getEmailGeneratorUiCopy() {
  831. if (getSelectedEmailGenerator() === 'cloudflare') {
  832. return {
  833. buttonLabel: '生成 Cloudflare',
  834. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  835. successVerb: '生成',
  836. label: 'Cloudflare 邮箱',
  837. };
  838. }
  839. return {
  840. buttonLabel: '获取 Duck',
  841. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  842. successVerb: '获取',
  843. label: 'Duck 邮箱',
  844. };
  845. }
  846. function getHotmailAccounts(state = latestState) {
  847. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  848. }
  849. function getCurrentHotmailAccount(state = latestState) {
  850. const currentId = state?.currentHotmailAccountId;
  851. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  852. }
  853. function getCurrentHotmailEmail(state = latestState) {
  854. return String(getCurrentHotmailAccount(state)?.email || '').trim();
  855. }
  856. function isCurrentEmailManagedByHotmail(state = latestState) {
  857. const hotmailEmail = getCurrentHotmailEmail(state);
  858. if (!hotmailEmail) {
  859. return false;
  860. }
  861. const inputEmailValue = String(inputEmail.value || '').trim();
  862. const stateEmailValue = String(state?.email || '').trim();
  863. return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
  864. }
  865. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  866. const accounts = getHotmailAccounts(state);
  867. if (typeof filterHotmailAccountsByUsage === 'function') {
  868. return filterHotmailAccountsByUsage(accounts, mode);
  869. }
  870. if (mode === 'used') {
  871. return accounts.filter((account) => Boolean(account?.used));
  872. }
  873. return accounts.slice();
  874. }
  875. function getHotmailBulkActionText(mode, count) {
  876. if (typeof getHotmailBulkActionLabel === 'function') {
  877. return getHotmailBulkActionLabel(mode, count);
  878. }
  879. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  880. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  881. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  882. return `${prefix}${suffix}`;
  883. }
  884. function getHotmailListToggleText(expanded, count) {
  885. if (typeof getHotmailListToggleLabel === 'function') {
  886. return getHotmailListToggleLabel(expanded, count);
  887. }
  888. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  889. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  890. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  891. }
  892. function updateHotmailListViewport() {
  893. const count = getHotmailAccounts().length;
  894. const usedCount = getHotmailAccountsByUsage('used').length;
  895. if (btnClearUsedHotmailAccounts) {
  896. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  897. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  898. }
  899. if (btnDeleteAllHotmailAccounts) {
  900. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  901. btnDeleteAllHotmailAccounts.disabled = count === 0;
  902. }
  903. if (btnToggleHotmailList) {
  904. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  905. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  906. btnToggleHotmailList.disabled = count === 0;
  907. }
  908. if (hotmailListShell) {
  909. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  910. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  911. }
  912. }
  913. function setHotmailListExpanded(expanded, options = {}) {
  914. const { persist = true } = options;
  915. hotmailListExpanded = Boolean(expanded);
  916. updateHotmailListViewport();
  917. if (persist) {
  918. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  919. }
  920. }
  921. function initHotmailListExpandedState() {
  922. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  923. setHotmailListExpanded(saved === '1', { persist: false });
  924. }
  925. function shouldClearCurrentHotmailSelectionLocally(account) {
  926. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  927. return shouldClearHotmailCurrentSelection(account);
  928. }
  929. return Boolean(account) && account.used === true;
  930. }
  931. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  932. if (typeof upsertHotmailAccountInList === 'function') {
  933. return upsertHotmailAccountInList(accounts, nextAccount);
  934. }
  935. const list = Array.isArray(accounts) ? accounts.slice() : [];
  936. if (!nextAccount?.id) return list;
  937. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  938. if (existingIndex === -1) {
  939. list.push(nextAccount);
  940. return list;
  941. }
  942. list[existingIndex] = nextAccount;
  943. return list;
  944. }
  945. function refreshHotmailSelectionUI() {
  946. renderHotmailAccounts();
  947. if (selectMailProvider.value === 'hotmail-api') {
  948. inputEmail.value = getCurrentHotmailEmail();
  949. }
  950. }
  951. function applyHotmailAccountMutation(account, options = {}) {
  952. if (!account?.id) return;
  953. const { preserveCurrentSelection = false } = options;
  954. const nextState = {
  955. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  956. };
  957. if (!preserveCurrentSelection
  958. && latestState?.currentHotmailAccountId === account.id
  959. && shouldClearCurrentHotmailSelectionLocally(account)) {
  960. nextState.currentHotmailAccountId = null;
  961. if (selectMailProvider.value === 'hotmail-api') {
  962. nextState.email = null;
  963. }
  964. }
  965. syncLatestState(nextState);
  966. refreshHotmailSelectionUI();
  967. }
  968. function formatDateTime(timestamp) {
  969. const value = Number(timestamp);
  970. if (!Number.isFinite(value) || value <= 0) {
  971. return '未使用';
  972. }
  973. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  974. }
  975. function getHotmailAvailabilityLabel(account) {
  976. if (account.used) return '已用';
  977. return '可分配';
  978. }
  979. function getHotmailStatusLabel(account) {
  980. if (account.used) return '已用';
  981. switch (account.status) {
  982. case 'authorized':
  983. return '可用';
  984. case 'error':
  985. return '异常';
  986. default:
  987. return '待校验';
  988. }
  989. }
  990. function getHotmailStatusClass(account) {
  991. if (account.used) return 'status-used';
  992. return `status-${account.status || 'pending'}`;
  993. }
  994. function clearHotmailForm() {
  995. inputHotmailEmail.value = '';
  996. inputHotmailClientId.value = '';
  997. inputHotmailPassword.value = '';
  998. inputHotmailRefreshToken.value = '';
  999. }
  1000. function renderHotmailAccounts() {
  1001. if (!hotmailAccountsList) return;
  1002. const accounts = getHotmailAccounts();
  1003. const currentId = latestState?.currentHotmailAccountId || '';
  1004. if (!accounts.length) {
  1005. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  1006. updateHotmailListViewport();
  1007. return;
  1008. }
  1009. hotmailAccountsList.innerHTML = accounts.map((account) => `
  1010. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  1011. <div class="hotmail-account-top">
  1012. <div class="hotmail-account-title-row">
  1013. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  1014. <button
  1015. class="hotmail-copy-btn"
  1016. type="button"
  1017. data-account-action="copy-email"
  1018. data-account-id="${escapeHtml(account.id)}"
  1019. title="复制邮箱"
  1020. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  1021. >${COPY_ICON}</button>
  1022. </div>
  1023. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  1024. </div>
  1025. <div class="hotmail-account-meta">
  1026. <span>客户端 ID:${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  1027. <span>刷新令牌:${account.refreshToken ? '已保存' : '未保存'}</span>
  1028. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  1029. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  1030. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  1031. </div>
  1032. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  1033. <div class="hotmail-account-actions">
  1034. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  1035. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  1036. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  1037. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  1038. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  1039. </div>
  1040. </div>
  1041. `).join('');
  1042. updateHotmailListViewport();
  1043. }
  1044. function updateMailProviderUI() {
  1045. const useInbucket = selectMailProvider.value === 'inbucket';
  1046. const useHotmail = selectMailProvider.value === 'hotmail-api';
  1047. const hotmailServiceMode = getSelectedHotmailServiceMode();
  1048. const useEmailGenerator = !useHotmail;
  1049. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  1050. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  1051. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  1052. const showCloudflareDomain = useEmailGenerator && useCloudflare;
  1053. if (rowEmailGenerator) {
  1054. rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none';
  1055. }
  1056. rowCfDomain.style.display = showCloudflareDomain ? '' : 'none';
  1057. const { domains } = getCloudflareDomainsFromState();
  1058. if (showCloudflareDomain) {
  1059. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  1060. } else {
  1061. setCloudflareDomainEditMode(false, { clearInput: false });
  1062. }
  1063. if (hotmailSection) {
  1064. hotmailSection.style.display = useHotmail ? '' : 'none';
  1065. }
  1066. if (rowHotmailServiceMode) {
  1067. rowHotmailServiceMode.style.display = useHotmail ? '' : 'none';
  1068. }
  1069. if (rowHotmailRemoteBaseUrl) {
  1070. rowHotmailRemoteBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE ? '' : 'none';
  1071. }
  1072. if (rowHotmailLocalBaseUrl) {
  1073. rowHotmailLocalBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_LOCAL ? '' : 'none';
  1074. }
  1075. selectEmailGenerator.disabled = useHotmail;
  1076. btnFetchEmail.hidden = useHotmail;
  1077. inputEmail.readOnly = useHotmail;
  1078. const uiCopy = getEmailGeneratorUiCopy();
  1079. inputEmail.placeholder = useHotmail ? '由 Hotmail 账号池自动分配' : uiCopy.placeholder;
  1080. if (!btnFetchEmail.disabled) {
  1081. btnFetchEmail.textContent = uiCopy.buttonLabel;
  1082. }
  1083. if (autoHintText) {
  1084. autoHintText.textContent = useHotmail
  1085. ? '请先校验并选择一个 Hotmail 账号'
  1086. : '先自动获取邮箱,或手动粘贴邮箱后再继续';
  1087. }
  1088. if (useHotmail) {
  1089. inputEmail.value = getCurrentHotmailEmail();
  1090. }
  1091. renderHotmailAccounts();
  1092. }
  1093. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  1094. const { silent = false } = options;
  1095. const normalizedDomains = normalizeCloudflareDomains(domains);
  1096. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  1097. const payload = {
  1098. cloudflareDomain: normalizedActiveDomain,
  1099. cloudflareDomains: normalizedDomains,
  1100. };
  1101. const response = await chrome.runtime.sendMessage({
  1102. type: 'SAVE_SETTING',
  1103. source: 'sidepanel',
  1104. payload,
  1105. });
  1106. if (response?.error) {
  1107. throw new Error(response.error);
  1108. }
  1109. syncLatestState({
  1110. ...payload,
  1111. });
  1112. renderCloudflareDomainOptions(normalizedActiveDomain);
  1113. setCloudflareDomainEditMode(false, { clearInput: true });
  1114. markSettingsDirty(false);
  1115. updateMailProviderUI();
  1116. if (!silent) {
  1117. showToast('Cloudflare 域名已保存', 'success', 1800);
  1118. }
  1119. }
  1120. function updatePanelModeUI() {
  1121. const useSub2Api = selectPanelMode.value === 'sub2api';
  1122. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  1123. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  1124. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  1125. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  1126. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  1127. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  1128. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  1129. const step9Btn = document.querySelector('.step-btn[data-step="9"]');
  1130. if (step9Btn) {
  1131. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  1132. }
  1133. }
  1134. // ============================================================
  1135. // UI Updates
  1136. // ============================================================
  1137. function updateStepUI(step, status) {
  1138. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  1139. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  1140. syncLatestState({
  1141. stepStatuses: {
  1142. ...getStepStatuses(),
  1143. [step]: status,
  1144. },
  1145. });
  1146. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  1147. if (row) {
  1148. row.className = `step-row ${status}`;
  1149. }
  1150. updateButtonStates();
  1151. updateProgressCounter();
  1152. updateConfigMenuControls();
  1153. }
  1154. function updateProgressCounter() {
  1155. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  1156. stepsProgress.textContent = `${completed} / 9`;
  1157. }
  1158. function updateButtonStates() {
  1159. const statuses = getStepStatuses();
  1160. const anyRunning = Object.values(statuses).some(s => s === 'running');
  1161. const autoLocked = isAutoRunLockedPhase();
  1162. const autoScheduled = isAutoRunScheduledPhase();
  1163. for (let step = 1; step <= 9; step++) {
  1164. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  1165. if (!btn) continue;
  1166. if (anyRunning || autoLocked || autoScheduled) {
  1167. btn.disabled = true;
  1168. } else if (step === 1) {
  1169. btn.disabled = false;
  1170. } else {
  1171. const prevStatus = statuses[step - 1];
  1172. const currentStatus = statuses[step];
  1173. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  1174. }
  1175. }
  1176. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  1177. const step = Number(btn.dataset.step);
  1178. const currentStatus = statuses[step];
  1179. const prevStatus = statuses[step - 1];
  1180. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  1181. btn.style.display = 'none';
  1182. btn.disabled = true;
  1183. btn.title = '当前不可跳过';
  1184. return;
  1185. }
  1186. if (step > 1 && !isDoneStatus(prevStatus)) {
  1187. btn.style.display = 'none';
  1188. btn.disabled = true;
  1189. btn.title = `请先完成步骤 ${step - 1}`;
  1190. return;
  1191. }
  1192. btn.style.display = '';
  1193. btn.disabled = false;
  1194. btn.title = `跳过步骤 ${step}`;
  1195. });
  1196. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  1197. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  1198. }
  1199. function updateStopButtonState(active) {
  1200. btnStop.disabled = !active;
  1201. }
  1202. function updateStatusDisplay(state) {
  1203. if (!state || !state.stepStatuses) return;
  1204. statusBar.className = 'status-bar';
  1205. if (isAutoRunScheduledPhase()) {
  1206. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  1207. ? currentAutoRun.scheduledAt - Date.now()
  1208. : 0;
  1209. displayStatus.textContent = remainingMs > 0
  1210. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  1211. : '倒计时即将结束,正在准备启动...';
  1212. statusBar.classList.add('scheduled');
  1213. return;
  1214. }
  1215. if (isAutoRunPausedPhase()) {
  1216. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  1217. statusBar.classList.add('paused');
  1218. return;
  1219. }
  1220. if (isAutoRunWaitingStepPhase()) {
  1221. const runningSteps = getRunningSteps(state);
  1222. displayStatus.textContent = runningSteps.length
  1223. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  1224. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  1225. statusBar.classList.add('running');
  1226. return;
  1227. }
  1228. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  1229. if (running) {
  1230. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  1231. statusBar.classList.add('running');
  1232. return;
  1233. }
  1234. if (isAutoRunLockedPhase()) {
  1235. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  1236. statusBar.classList.add('running');
  1237. return;
  1238. }
  1239. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  1240. if (failed) {
  1241. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  1242. statusBar.classList.add('failed');
  1243. return;
  1244. }
  1245. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  1246. if (stopped) {
  1247. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  1248. statusBar.classList.add('stopped');
  1249. return;
  1250. }
  1251. const lastCompleted = Object.entries(state.stepStatuses)
  1252. .filter(([, s]) => isDoneStatus(s))
  1253. .map(([k]) => Number(k))
  1254. .sort((a, b) => b - a)[0];
  1255. if (lastCompleted === 9) {
  1256. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  1257. statusBar.classList.add('completed');
  1258. } else if (lastCompleted) {
  1259. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  1260. ? `步骤 ${lastCompleted} 已跳过`
  1261. : `步骤 ${lastCompleted} 已完成`;
  1262. } else {
  1263. displayStatus.textContent = '就绪';
  1264. }
  1265. }
  1266. function appendLog(entry) {
  1267. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  1268. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  1269. const line = document.createElement('div');
  1270. line.className = `log-line log-${entry.level}`;
  1271. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  1272. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  1273. let html = `<span class="log-time">${time}</span> `;
  1274. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  1275. if (stepNum) {
  1276. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  1277. }
  1278. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  1279. line.innerHTML = html;
  1280. logArea.appendChild(line);
  1281. logArea.scrollTop = logArea.scrollHeight;
  1282. }
  1283. function escapeHtml(text) {
  1284. const div = document.createElement('div');
  1285. div.textContent = text;
  1286. return div.innerHTML;
  1287. }
  1288. async function fetchGeneratedEmail(options = {}) {
  1289. const { showFailureToast = true } = options;
  1290. const uiCopy = getEmailGeneratorUiCopy();
  1291. const defaultLabel = uiCopy.buttonLabel;
  1292. btnFetchEmail.disabled = true;
  1293. btnFetchEmail.textContent = '...';
  1294. try {
  1295. const response = await chrome.runtime.sendMessage({
  1296. type: 'FETCH_GENERATED_EMAIL',
  1297. source: 'sidepanel',
  1298. payload: {
  1299. generateNew: true,
  1300. generator: selectEmailGenerator.value,
  1301. },
  1302. });
  1303. if (response?.error) {
  1304. throw new Error(response.error);
  1305. }
  1306. if (!response?.email) {
  1307. throw new Error('未返回可用邮箱。');
  1308. }
  1309. inputEmail.value = response.email;
  1310. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  1311. return response.email;
  1312. } catch (err) {
  1313. if (showFailureToast) {
  1314. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  1315. }
  1316. throw err;
  1317. } finally {
  1318. btnFetchEmail.disabled = false;
  1319. btnFetchEmail.textContent = defaultLabel;
  1320. }
  1321. }
  1322. function syncToggleButtonLabel(button, input, labels) {
  1323. if (!button || !input) return;
  1324. const isHidden = input.type === 'password';
  1325. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  1326. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  1327. button.title = isHidden ? labels.show : labels.hide;
  1328. }
  1329. async function copyTextToClipboard(text) {
  1330. const value = String(text || '').trim();
  1331. if (!value) {
  1332. throw new Error('没有可复制的内容。');
  1333. }
  1334. if (!navigator.clipboard?.writeText) {
  1335. throw new Error('当前环境不支持剪贴板复制。');
  1336. }
  1337. await navigator.clipboard.writeText(value);
  1338. }
  1339. async function exportSettingsFile() {
  1340. closeConfigMenu();
  1341. configActionInFlight = true;
  1342. updateConfigMenuControls();
  1343. try {
  1344. await flushPendingSettingsBeforeExport();
  1345. const response = await chrome.runtime.sendMessage({
  1346. type: 'EXPORT_SETTINGS',
  1347. source: 'sidepanel',
  1348. payload: {},
  1349. });
  1350. if (response?.error) {
  1351. throw new Error(response.error);
  1352. }
  1353. if (!response?.fileContent || !response?.fileName) {
  1354. throw new Error('\u672a\u751f\u6210\u53ef\u4e0b\u8f7d\u7684\u914d\u7f6e\u6587\u4ef6\u3002');
  1355. }
  1356. downloadTextFile(response.fileContent, response.fileName);
  1357. showToast('\u914d\u7f6e\u5df2\u5bfc\u51fa\uff1a' + response.fileName, 'success', 2200);
  1358. } catch (err) {
  1359. showToast('\u5bfc\u51fa\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  1360. } finally {
  1361. configActionInFlight = false;
  1362. updateConfigMenuControls();
  1363. }
  1364. }
  1365. async function importSettingsFromFile(file) {
  1366. if (!file) return;
  1367. configActionInFlight = true;
  1368. closeConfigMenu();
  1369. updateConfigMenuControls();
  1370. try {
  1371. await settlePendingSettingsBeforeImport();
  1372. const rawText = await file.text();
  1373. let parsedConfig = null;
  1374. try {
  1375. parsedConfig = JSON.parse(rawText);
  1376. } catch {
  1377. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002');
  1378. }
  1379. const confirmed = await openConfirmModal({
  1380. title: '\u5bfc\u5165\u914d\u7f6e',
  1381. message: '\u786e\u8ba4\u5bfc\u5165\u914d\u7f6e\u6587\u4ef6 "' + file.name + '" \u5417\uff1f\u5bfc\u5165\u540e\u4f1a\u8986\u76d6\u5f53\u524d\u914d\u7f6e\u3002',
  1382. confirmLabel: '\u786e\u8ba4\u8986\u76d6\u5bfc\u5165',
  1383. confirmVariant: 'btn-danger',
  1384. });
  1385. if (!confirmed) {
  1386. return;
  1387. }
  1388. const response = await chrome.runtime.sendMessage({
  1389. type: 'IMPORT_SETTINGS',
  1390. source: 'sidepanel',
  1391. payload: {
  1392. config: parsedConfig,
  1393. },
  1394. });
  1395. if (response?.error) {
  1396. throw new Error(response.error);
  1397. }
  1398. if (!response?.state) {
  1399. throw new Error('\u5bfc\u5165\u540e\u672a\u8fd4\u56de\u6700\u65b0\u914d\u7f6e\u72b6\u6001\u3002');
  1400. }
  1401. applySettingsState(response.state);
  1402. updateStatusDisplay(latestState);
  1403. showToast('\u914d\u7f6e\u5df2\u5bfc\u5165\uff0c\u5f53\u524d\u914d\u7f6e\u5df2\u8986\u76d6\u3002', 'success', 2200);
  1404. } catch (err) {
  1405. showToast('\u5bfc\u5165\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  1406. } finally {
  1407. configActionInFlight = false;
  1408. updateConfigMenuControls();
  1409. if (inputImportSettingsFile) {
  1410. inputImportSettingsFile.value = '';
  1411. }
  1412. }
  1413. }
  1414. async function deleteHotmailAccountsByMode(mode) {
  1415. const isUsedMode = mode === 'used';
  1416. const targetAccounts = getHotmailAccountsByUsage(isUsedMode ? 'used' : 'all');
  1417. if (!targetAccounts.length) {
  1418. showToast(isUsedMode ? '没有已用账号可清空。' : '没有可删除的 Hotmail 账号。', 'warn');
  1419. return;
  1420. }
  1421. const confirmed = await openConfirmModal({
  1422. title: isUsedMode ? '清空已用账号' : '全部删除账号',
  1423. message: isUsedMode
  1424. ? `确认删除当前 ${targetAccounts.length} 个已用 Hotmail 账号吗?`
  1425. : `确认删除全部 ${targetAccounts.length} 个 Hotmail 账号吗?`,
  1426. confirmLabel: isUsedMode ? '确认清空已用' : '确认全部删除',
  1427. confirmVariant: isUsedMode ? 'btn-outline' : 'btn-danger',
  1428. });
  1429. if (!confirmed) {
  1430. return;
  1431. }
  1432. const response = await chrome.runtime.sendMessage({
  1433. type: 'DELETE_HOTMAIL_ACCOUNTS',
  1434. source: 'sidepanel',
  1435. payload: { mode: isUsedMode ? 'used' : 'all' },
  1436. });
  1437. if (response?.error) {
  1438. throw new Error(response.error);
  1439. }
  1440. const targetIds = new Set(targetAccounts.map((account) => account.id));
  1441. const nextAccounts = isUsedMode
  1442. ? getHotmailAccounts().filter((account) => !targetIds.has(account.id))
  1443. : [];
  1444. const nextState = { hotmailAccounts: nextAccounts };
  1445. if (latestState?.currentHotmailAccountId && targetIds.has(latestState.currentHotmailAccountId)) {
  1446. nextState.currentHotmailAccountId = null;
  1447. if (selectMailProvider.value === 'hotmail-api') {
  1448. nextState.email = null;
  1449. }
  1450. }
  1451. syncLatestState(nextState);
  1452. refreshHotmailSelectionUI();
  1453. showToast(
  1454. isUsedMode
  1455. ? `已清空 ${response.deletedCount || 0} 个已用 Hotmail 账号`
  1456. : `已删除全部 ${response.deletedCount || 0} 个 Hotmail 账号`,
  1457. 'success',
  1458. 2200
  1459. );
  1460. }
  1461. function syncPasswordToggleLabel() {
  1462. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  1463. show: '显示密码',
  1464. hide: '隐藏密码',
  1465. });
  1466. }
  1467. function syncVpsUrlToggleLabel() {
  1468. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  1469. show: '显示 CPA 地址',
  1470. hide: '隐藏 CPA 地址',
  1471. });
  1472. }
  1473. function syncVpsPasswordToggleLabel() {
  1474. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  1475. show: '显示管理密钥',
  1476. hide: '隐藏管理密钥',
  1477. });
  1478. }
  1479. async function maybeTakeoverAutoRun(actionLabel) {
  1480. if (!isAutoRunPausedPhase()) {
  1481. return true;
  1482. }
  1483. const confirmed = await openConfirmModal({
  1484. title: '接管自动',
  1485. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  1486. confirmLabel: '确认接管',
  1487. confirmVariant: 'btn-primary',
  1488. });
  1489. if (!confirmed) {
  1490. return false;
  1491. }
  1492. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  1493. return true;
  1494. }
  1495. async function handleSkipStep(step) {
  1496. if (isAutoRunPausedPhase()) {
  1497. const takeoverResponse = await chrome.runtime.sendMessage({
  1498. type: 'TAKEOVER_AUTO_RUN',
  1499. source: 'sidepanel',
  1500. payload: {},
  1501. });
  1502. if (takeoverResponse?.error) {
  1503. throw new Error(takeoverResponse.error);
  1504. }
  1505. }
  1506. const response = await chrome.runtime.sendMessage({
  1507. type: 'SKIP_STEP',
  1508. source: 'sidepanel',
  1509. payload: { step },
  1510. });
  1511. if (response?.error) {
  1512. throw new Error(response.error);
  1513. }
  1514. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  1515. }
  1516. // ============================================================
  1517. // Button Handlers
  1518. // ============================================================
  1519. document.querySelectorAll('.step-btn').forEach(btn => {
  1520. btn.addEventListener('click', async () => {
  1521. try {
  1522. const step = Number(btn.dataset.step);
  1523. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  1524. return;
  1525. }
  1526. if (step === 3) {
  1527. if (inputPassword.value !== (latestState?.customPassword || '')) {
  1528. await chrome.runtime.sendMessage({
  1529. type: 'SAVE_SETTING',
  1530. source: 'sidepanel',
  1531. payload: { customPassword: inputPassword.value },
  1532. });
  1533. syncLatestState({ customPassword: inputPassword.value });
  1534. }
  1535. let email = inputEmail.value.trim();
  1536. if (selectMailProvider.value === 'hotmail-api') {
  1537. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1538. if (response?.error) {
  1539. throw new Error(response.error);
  1540. }
  1541. } else {
  1542. let email = inputEmail.value.trim();
  1543. if (!email) {
  1544. try {
  1545. email = await fetchGeneratedEmail({ showFailureToast: false });
  1546. } catch (err) {
  1547. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  1548. return;
  1549. }
  1550. }
  1551. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  1552. if (response?.error) {
  1553. throw new Error(response.error);
  1554. }
  1555. }
  1556. } else {
  1557. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1558. if (response?.error) {
  1559. throw new Error(response.error);
  1560. }
  1561. }
  1562. } catch (err) {
  1563. showToast(err.message, 'error');
  1564. }
  1565. });
  1566. });
  1567. btnFetchEmail.addEventListener('click', async () => {
  1568. if (selectMailProvider.value === 'hotmail-api') {
  1569. return;
  1570. }
  1571. await fetchGeneratedEmail().catch(() => { });
  1572. });
  1573. btnToggleHotmailList?.addEventListener('click', () => {
  1574. setHotmailListExpanded(!hotmailListExpanded);
  1575. });
  1576. btnHotmailUsageGuide?.addEventListener('click', async () => {
  1577. await openConfirmModal({
  1578. title: '使用教程',
  1579. message: '由于第三方服务接口结构不同,所以暂时无法使用,如果您的token可以直连微软,请测试本地功能,详细功能请看项目根目录的readme文件',
  1580. confirmLabel: '确定',
  1581. confirmVariant: 'btn-primary',
  1582. });
  1583. });
  1584. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  1585. if (hotmailActionInFlight) return;
  1586. hotmailActionInFlight = true;
  1587. btnClearUsedHotmailAccounts.disabled = true;
  1588. try {
  1589. await deleteHotmailAccountsByMode('used');
  1590. } catch (err) {
  1591. showToast(err.message, 'error');
  1592. } finally {
  1593. hotmailActionInFlight = false;
  1594. updateHotmailListViewport();
  1595. }
  1596. });
  1597. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  1598. if (hotmailActionInFlight) return;
  1599. hotmailActionInFlight = true;
  1600. btnDeleteAllHotmailAccounts.disabled = true;
  1601. try {
  1602. await deleteHotmailAccountsByMode('all');
  1603. } catch (err) {
  1604. showToast(err.message, 'error');
  1605. } finally {
  1606. hotmailActionInFlight = false;
  1607. updateHotmailListViewport();
  1608. }
  1609. });
  1610. btnAddHotmailAccount?.addEventListener('click', async () => {
  1611. if (hotmailActionInFlight) return;
  1612. const email = inputHotmailEmail.value.trim();
  1613. const clientId = inputHotmailClientId.value.trim();
  1614. const refreshToken = inputHotmailRefreshToken.value.trim();
  1615. if (!email) {
  1616. showToast('请先填写 Hotmail 邮箱。', 'warn');
  1617. return;
  1618. }
  1619. if (!clientId) {
  1620. showToast('请先填写微软应用客户端 ID。', 'warn');
  1621. return;
  1622. }
  1623. if (!refreshToken) {
  1624. showToast('请先填写刷新令牌(refresh token)。', 'warn');
  1625. return;
  1626. }
  1627. hotmailActionInFlight = true;
  1628. btnAddHotmailAccount.disabled = true;
  1629. try {
  1630. const response = await chrome.runtime.sendMessage({
  1631. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1632. source: 'sidepanel',
  1633. payload: {
  1634. email,
  1635. clientId,
  1636. password: inputHotmailPassword.value,
  1637. refreshToken,
  1638. },
  1639. });
  1640. if (response?.error) {
  1641. throw new Error(response.error);
  1642. }
  1643. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  1644. clearHotmailForm();
  1645. } catch (err) {
  1646. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  1647. } finally {
  1648. hotmailActionInFlight = false;
  1649. btnAddHotmailAccount.disabled = false;
  1650. }
  1651. });
  1652. btnImportHotmailAccounts?.addEventListener('click', async () => {
  1653. if (hotmailActionInFlight) return;
  1654. if (typeof parseHotmailImportText !== 'function') {
  1655. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  1656. return;
  1657. }
  1658. const rawText = inputHotmailImport.value.trim();
  1659. if (!rawText) {
  1660. showToast('请先粘贴账号导入内容。', 'warn');
  1661. return;
  1662. }
  1663. const parsedAccounts = parseHotmailImportText(rawText);
  1664. if (!parsedAccounts.length) {
  1665. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  1666. return;
  1667. }
  1668. hotmailActionInFlight = true;
  1669. btnImportHotmailAccounts.disabled = true;
  1670. try {
  1671. for (const account of parsedAccounts) {
  1672. const response = await chrome.runtime.sendMessage({
  1673. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1674. source: 'sidepanel',
  1675. payload: account,
  1676. });
  1677. if (response?.error) {
  1678. throw new Error(response.error);
  1679. }
  1680. }
  1681. inputHotmailImport.value = '';
  1682. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  1683. } catch (err) {
  1684. showToast(`批量导入失败:${err.message}`, 'error');
  1685. } finally {
  1686. hotmailActionInFlight = false;
  1687. btnImportHotmailAccounts.disabled = false;
  1688. }
  1689. });
  1690. hotmailAccountsList?.addEventListener('click', async (event) => {
  1691. const actionButton = event.target.closest('[data-account-action]');
  1692. if (!actionButton || hotmailActionInFlight) {
  1693. return;
  1694. }
  1695. const accountId = actionButton.dataset.accountId;
  1696. const action = actionButton.dataset.accountAction;
  1697. if (!accountId || !action) {
  1698. return;
  1699. }
  1700. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  1701. hotmailActionInFlight = true;
  1702. actionButton.disabled = true;
  1703. try {
  1704. if (action === 'copy-email') {
  1705. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  1706. await copyTextToClipboard(targetAccount.email);
  1707. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  1708. } else if (action === 'select') {
  1709. const response = await chrome.runtime.sendMessage({
  1710. type: 'SELECT_HOTMAIL_ACCOUNT',
  1711. source: 'sidepanel',
  1712. payload: { accountId },
  1713. });
  1714. if (response?.error) throw new Error(response.error);
  1715. syncLatestState({ currentHotmailAccountId: response.account.id });
  1716. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1717. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  1718. } else if (action === 'toggle-used') {
  1719. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  1720. const response = await chrome.runtime.sendMessage({
  1721. type: 'PATCH_HOTMAIL_ACCOUNT',
  1722. source: 'sidepanel',
  1723. payload: {
  1724. accountId,
  1725. updates: { used: !targetAccount.used },
  1726. },
  1727. });
  1728. if (response?.error) throw new Error(response.error);
  1729. applyHotmailAccountMutation(response.account);
  1730. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  1731. } else if (action === 'verify') {
  1732. const response = await chrome.runtime.sendMessage({
  1733. type: 'VERIFY_HOTMAIL_ACCOUNT',
  1734. source: 'sidepanel',
  1735. payload: { accountId },
  1736. });
  1737. if (response?.error) throw new Error(response.error);
  1738. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1739. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  1740. } else if (action === 'test') {
  1741. const response = await chrome.runtime.sendMessage({
  1742. type: 'TEST_HOTMAIL_ACCOUNT',
  1743. source: 'sidepanel',
  1744. payload: { accountId },
  1745. });
  1746. if (response?.error) throw new Error(response.error);
  1747. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1748. if (response.latestCode) {
  1749. await copyTextToClipboard(response.latestCode);
  1750. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1751. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  1752. } else if (response.latestSubject) {
  1753. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1754. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  1755. } else {
  1756. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  1757. }
  1758. } else if (action === 'delete') {
  1759. const confirmed = await openConfirmModal({
  1760. title: '删除账号',
  1761. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  1762. confirmLabel: '确认删除',
  1763. confirmVariant: 'btn-danger',
  1764. });
  1765. if (!confirmed) {
  1766. return;
  1767. }
  1768. const response = await chrome.runtime.sendMessage({
  1769. type: 'DELETE_HOTMAIL_ACCOUNT',
  1770. source: 'sidepanel',
  1771. payload: { accountId },
  1772. });
  1773. if (response?.error) throw new Error(response.error);
  1774. showToast('Hotmail 账号已删除', 'success', 1800);
  1775. }
  1776. } catch (err) {
  1777. showToast(err.message, 'error');
  1778. } finally {
  1779. hotmailActionInFlight = false;
  1780. actionButton.disabled = false;
  1781. }
  1782. });
  1783. btnTogglePassword.addEventListener('click', () => {
  1784. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  1785. syncPasswordToggleLabel();
  1786. });
  1787. btnToggleVpsUrl.addEventListener('click', () => {
  1788. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  1789. syncVpsUrlToggleLabel();
  1790. });
  1791. btnToggleVpsPassword.addEventListener('click', () => {
  1792. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  1793. syncVpsPasswordToggleLabel();
  1794. });
  1795. localCpaStep9ModeButtons.forEach((button) => {
  1796. button.addEventListener('click', () => {
  1797. const nextMode = button.dataset.localCpaStep9Mode;
  1798. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  1799. return;
  1800. }
  1801. setLocalCpaStep9Mode(nextMode);
  1802. markSettingsDirty(true);
  1803. saveSettings({ silent: true }).catch(() => { });
  1804. });
  1805. });
  1806. hotmailServiceModeButtons.forEach((button) => {
  1807. button.addEventListener('click', () => {
  1808. if (button.disabled) {
  1809. return;
  1810. }
  1811. const nextMode = button.dataset.hotmailServiceMode;
  1812. if (getSelectedHotmailServiceMode() === normalizeHotmailServiceMode(nextMode)) {
  1813. return;
  1814. }
  1815. setHotmailServiceMode(nextMode);
  1816. updateMailProviderUI();
  1817. markSettingsDirty(true);
  1818. saveSettings({ silent: true }).catch(() => { });
  1819. });
  1820. });
  1821. btnSaveSettings.addEventListener('click', async () => {
  1822. if (!settingsDirty) {
  1823. showToast('配置已是最新', 'info', 1400);
  1824. return;
  1825. }
  1826. await saveSettings({ silent: false }).catch(() => { });
  1827. });
  1828. btnStop.addEventListener('click', async () => {
  1829. btnStop.disabled = true;
  1830. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  1831. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  1832. });
  1833. btnConfigMenu?.addEventListener('click', (event) => {
  1834. event.stopPropagation();
  1835. toggleConfigMenu();
  1836. });
  1837. configMenu?.addEventListener('click', (event) => {
  1838. event.stopPropagation();
  1839. });
  1840. btnExportSettings?.addEventListener('click', async () => {
  1841. if (configActionInFlight || settingsSaveInFlight) {
  1842. return;
  1843. }
  1844. await exportSettingsFile();
  1845. });
  1846. btnImportSettings?.addEventListener('click', async () => {
  1847. if (configActionInFlight || settingsSaveInFlight) {
  1848. return;
  1849. }
  1850. closeConfigMenu();
  1851. if (inputImportSettingsFile) {
  1852. inputImportSettingsFile.value = '';
  1853. inputImportSettingsFile.click();
  1854. }
  1855. });
  1856. inputImportSettingsFile?.addEventListener('change', async () => {
  1857. const file = inputImportSettingsFile.files?.[0] || null;
  1858. await importSettingsFromFile(file);
  1859. });
  1860. autoStartModal?.addEventListener('click', (event) => {
  1861. if (event.target === autoStartModal) {
  1862. resolveModalChoice(null);
  1863. }
  1864. });
  1865. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  1866. // Auto Run
  1867. btnAutoRun.addEventListener('click', async () => {
  1868. try {
  1869. const totalRuns = Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  1870. let mode = 'restart';
  1871. if (shouldOfferAutoModeChoice()) {
  1872. const startStep = getFirstUnfinishedStep();
  1873. const runningStep = getRunningSteps()[0] ?? null;
  1874. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  1875. if (!choice) {
  1876. return;
  1877. }
  1878. mode = choice;
  1879. }
  1880. btnAutoRun.disabled = true;
  1881. inputRunCount.disabled = true;
  1882. const delayEnabled = inputAutoDelayEnabled.checked;
  1883. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  1884. inputAutoDelayMinutes.value = String(delayMinutes);
  1885. btnAutoRun.innerHTML = delayEnabled
  1886. ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 计划中...'
  1887. : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 运行中...';
  1888. const response = await chrome.runtime.sendMessage({
  1889. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  1890. source: 'sidepanel',
  1891. payload: {
  1892. totalRuns,
  1893. delayMinutes,
  1894. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1895. mode,
  1896. },
  1897. });
  1898. if (response?.error) {
  1899. throw new Error(response.error);
  1900. }
  1901. } catch (err) {
  1902. setDefaultAutoRunButton();
  1903. inputRunCount.disabled = false;
  1904. showToast(err.message, 'error');
  1905. }
  1906. });
  1907. btnAutoContinue.addEventListener('click', async () => {
  1908. const email = inputEmail.value.trim();
  1909. if (!email) {
  1910. showToast('请先获取或粘贴邮箱。', 'warn');
  1911. return;
  1912. }
  1913. autoContinueBar.style.display = 'none';
  1914. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  1915. });
  1916. btnAutoRunNow?.addEventListener('click', async () => {
  1917. try {
  1918. btnAutoRunNow.disabled = true;
  1919. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  1920. } catch (err) {
  1921. showToast(err.message, 'error');
  1922. } finally {
  1923. btnAutoRunNow.disabled = false;
  1924. }
  1925. });
  1926. btnAutoCancelSchedule?.addEventListener('click', async () => {
  1927. try {
  1928. btnAutoCancelSchedule.disabled = true;
  1929. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  1930. showToast('已取消倒计时计划。', 'info', 1800);
  1931. } catch (err) {
  1932. showToast(err.message, 'error');
  1933. } finally {
  1934. btnAutoCancelSchedule.disabled = false;
  1935. }
  1936. });
  1937. // Reset
  1938. btnReset.addEventListener('click', async () => {
  1939. const confirmed = await openConfirmModal({
  1940. title: '重置流程',
  1941. message: '确认重置全部步骤和数据吗?',
  1942. confirmLabel: '确认重置',
  1943. confirmVariant: 'btn-danger',
  1944. });
  1945. if (!confirmed) {
  1946. return;
  1947. }
  1948. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  1949. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  1950. syncAutoRunState({
  1951. autoRunning: false,
  1952. autoRunPhase: 'idle',
  1953. autoRunCurrentRun: 0,
  1954. autoRunTotalRuns: 1,
  1955. autoRunAttemptRun: 0,
  1956. scheduledAutoRunAt: null,
  1957. });
  1958. displayOauthUrl.textContent = '等待中...';
  1959. displayOauthUrl.classList.remove('has-value');
  1960. displayLocalhostUrl.textContent = '等待中...';
  1961. displayLocalhostUrl.classList.remove('has-value');
  1962. inputEmail.value = '';
  1963. displayStatus.textContent = '就绪';
  1964. statusBar.className = 'status-bar';
  1965. logArea.innerHTML = '';
  1966. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1967. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1968. setDefaultAutoRunButton();
  1969. applyAutoRunStatus(currentAutoRun);
  1970. markSettingsDirty(false);
  1971. updateStopButtonState(false);
  1972. updateButtonStates();
  1973. updateProgressCounter();
  1974. renderHotmailAccounts();
  1975. });
  1976. // Clear log
  1977. btnClearLog.addEventListener('click', () => {
  1978. logArea.innerHTML = '';
  1979. });
  1980. // Save settings on change
  1981. inputEmail.addEventListener('change', async () => {
  1982. if (selectMailProvider.value === 'hotmail-api') {
  1983. return;
  1984. }
  1985. const email = inputEmail.value.trim();
  1986. inputEmail.value = email;
  1987. try {
  1988. if (email) {
  1989. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  1990. if (response?.error) {
  1991. throw new Error(response.error);
  1992. }
  1993. } else {
  1994. await setRuntimeEmailState(null);
  1995. }
  1996. } catch (err) {
  1997. showToast(err.message, 'error');
  1998. }
  1999. });
  2000. inputEmail.addEventListener('input', updateButtonStates);
  2001. inputVpsUrl.addEventListener('input', () => {
  2002. markSettingsDirty(true);
  2003. scheduleSettingsAutoSave();
  2004. });
  2005. inputVpsUrl.addEventListener('blur', () => {
  2006. saveSettings({ silent: true }).catch(() => { });
  2007. });
  2008. inputVpsPassword.addEventListener('input', () => {
  2009. markSettingsDirty(true);
  2010. scheduleSettingsAutoSave();
  2011. });
  2012. inputVpsPassword.addEventListener('blur', () => {
  2013. saveSettings({ silent: true }).catch(() => { });
  2014. });
  2015. [inputHotmailRemoteBaseUrl, inputHotmailLocalBaseUrl].forEach((input) => {
  2016. input?.addEventListener('input', () => {
  2017. markSettingsDirty(true);
  2018. scheduleSettingsAutoSave();
  2019. });
  2020. input?.addEventListener('blur', () => {
  2021. saveSettings({ silent: true }).catch(() => { });
  2022. });
  2023. });
  2024. inputPassword.addEventListener('input', () => {
  2025. markSettingsDirty(true);
  2026. updateButtonStates();
  2027. scheduleSettingsAutoSave();
  2028. });
  2029. inputPassword.addEventListener('blur', () => {
  2030. saveSettings({ silent: true }).catch(() => { });
  2031. });
  2032. selectMailProvider.addEventListener('change', async () => {
  2033. const previousProvider = latestState?.mailProvider || '';
  2034. const nextProvider = selectMailProvider.value;
  2035. updateMailProviderUI();
  2036. if (previousProvider === 'hotmail-api' && nextProvider !== 'hotmail-api' && isCurrentEmailManagedByHotmail()) {
  2037. await clearRegistrationEmail({ silent: true }).catch(() => { });
  2038. }
  2039. markSettingsDirty(true);
  2040. saveSettings({ silent: true }).catch(() => { });
  2041. });
  2042. selectEmailGenerator.addEventListener('change', () => {
  2043. updateMailProviderUI();
  2044. clearRegistrationEmail({ silent: true }).catch(() => { });
  2045. markSettingsDirty(true);
  2046. saveSettings({ silent: true }).catch(() => { });
  2047. });
  2048. selectPanelMode.addEventListener('change', () => {
  2049. updatePanelModeUI();
  2050. markSettingsDirty(true);
  2051. saveSettings({ silent: true }).catch(() => { });
  2052. });
  2053. selectCfDomain.addEventListener('change', () => {
  2054. if (selectCfDomain.disabled) {
  2055. return;
  2056. }
  2057. markSettingsDirty(true);
  2058. saveSettings({ silent: true }).catch(() => { });
  2059. });
  2060. btnCfDomainMode.addEventListener('click', async () => {
  2061. try {
  2062. if (!cloudflareDomainEditMode) {
  2063. setCloudflareDomainEditMode(true, { clearInput: true });
  2064. return;
  2065. }
  2066. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  2067. if (!newDomain) {
  2068. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  2069. inputCfDomain.focus();
  2070. return;
  2071. }
  2072. const { domains } = getCloudflareDomainsFromState();
  2073. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  2074. } catch (err) {
  2075. showToast(err.message, 'error');
  2076. }
  2077. });
  2078. inputCfDomain.addEventListener('keydown', (event) => {
  2079. if (event.key === 'Enter') {
  2080. event.preventDefault();
  2081. btnCfDomainMode.click();
  2082. }
  2083. });
  2084. inputSub2ApiUrl.addEventListener('input', () => {
  2085. markSettingsDirty(true);
  2086. scheduleSettingsAutoSave();
  2087. });
  2088. inputSub2ApiUrl.addEventListener('blur', () => {
  2089. saveSettings({ silent: true }).catch(() => { });
  2090. });
  2091. inputSub2ApiEmail.addEventListener('input', () => {
  2092. markSettingsDirty(true);
  2093. scheduleSettingsAutoSave();
  2094. });
  2095. inputSub2ApiEmail.addEventListener('blur', () => {
  2096. saveSettings({ silent: true }).catch(() => { });
  2097. });
  2098. inputSub2ApiPassword.addEventListener('input', () => {
  2099. markSettingsDirty(true);
  2100. scheduleSettingsAutoSave();
  2101. });
  2102. inputSub2ApiPassword.addEventListener('blur', () => {
  2103. saveSettings({ silent: true }).catch(() => { });
  2104. });
  2105. inputSub2ApiGroup.addEventListener('input', () => {
  2106. markSettingsDirty(true);
  2107. scheduleSettingsAutoSave();
  2108. });
  2109. inputSub2ApiGroup.addEventListener('blur', () => {
  2110. saveSettings({ silent: true }).catch(() => { });
  2111. });
  2112. inputInbucketMailbox.addEventListener('input', () => {
  2113. markSettingsDirty(true);
  2114. scheduleSettingsAutoSave();
  2115. });
  2116. inputInbucketMailbox.addEventListener('blur', () => {
  2117. saveSettings({ silent: true }).catch(() => { });
  2118. });
  2119. inputInbucketHost.addEventListener('input', () => {
  2120. markSettingsDirty(true);
  2121. scheduleSettingsAutoSave();
  2122. });
  2123. inputInbucketHost.addEventListener('blur', () => {
  2124. saveSettings({ silent: true }).catch(() => { });
  2125. });
  2126. inputAutoSkipFailures.addEventListener('change', () => {
  2127. markSettingsDirty(true);
  2128. saveSettings({ silent: true }).catch(() => { });
  2129. });
  2130. inputAutoDelayEnabled.addEventListener('change', () => {
  2131. updateAutoDelayInputState();
  2132. markSettingsDirty(true);
  2133. saveSettings({ silent: true }).catch(() => { });
  2134. });
  2135. inputAutoDelayMinutes.addEventListener('input', () => {
  2136. markSettingsDirty(true);
  2137. scheduleSettingsAutoSave();
  2138. });
  2139. inputAutoDelayMinutes.addEventListener('blur', () => {
  2140. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  2141. saveSettings({ silent: true }).catch(() => { });
  2142. });
  2143. // ============================================================
  2144. // Listen for Background broadcasts
  2145. // ============================================================
  2146. chrome.runtime.onMessage.addListener((message) => {
  2147. switch (message.type) {
  2148. case 'LOG_ENTRY':
  2149. appendLog(message.payload);
  2150. if (message.payload.level === 'error') {
  2151. showToast(message.payload.message, 'error');
  2152. }
  2153. break;
  2154. case 'STEP_STATUS_CHANGED': {
  2155. const { step, status } = message.payload;
  2156. updateStepUI(step, status);
  2157. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  2158. syncLatestState(state);
  2159. syncAutoRunState(state);
  2160. updateStatusDisplay(latestState);
  2161. updateButtonStates();
  2162. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  2163. syncPasswordField(state);
  2164. if (state.oauthUrl) {
  2165. displayOauthUrl.textContent = state.oauthUrl;
  2166. displayOauthUrl.classList.add('has-value');
  2167. }
  2168. if (state.localhostUrl) {
  2169. displayLocalhostUrl.textContent = state.localhostUrl;
  2170. displayLocalhostUrl.classList.add('has-value');
  2171. }
  2172. }
  2173. }
  2174. ).catch(() => { });
  2175. break;
  2176. }
  2177. case 'AUTO_RUN_RESET': {
  2178. // Full UI reset for next run
  2179. syncLatestState({
  2180. oauthUrl: null,
  2181. localhostUrl: null,
  2182. email: null,
  2183. password: null,
  2184. stepStatuses: STEP_DEFAULT_STATUSES,
  2185. logs: [],
  2186. scheduledAutoRunAt: null,
  2187. });
  2188. displayOauthUrl.textContent = '等待中...';
  2189. displayOauthUrl.classList.remove('has-value');
  2190. displayLocalhostUrl.textContent = '等待中...';
  2191. displayLocalhostUrl.classList.remove('has-value');
  2192. inputEmail.value = '';
  2193. displayStatus.textContent = '就绪';
  2194. statusBar.className = 'status-bar';
  2195. logArea.innerHTML = '';
  2196. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2197. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2198. applyAutoRunStatus(currentAutoRun);
  2199. updateProgressCounter();
  2200. updateButtonStates();
  2201. renderHotmailAccounts();
  2202. break;
  2203. }
  2204. case 'DATA_UPDATED': {
  2205. syncLatestState(message.payload);
  2206. if (message.payload.email !== undefined) {
  2207. inputEmail.value = message.payload.email || '';
  2208. }
  2209. if (message.payload.password !== undefined) {
  2210. inputPassword.value = message.payload.password || '';
  2211. }
  2212. if (message.payload.localCpaStep9Mode !== undefined) {
  2213. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  2214. }
  2215. if (message.payload.oauthUrl !== undefined) {
  2216. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  2217. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  2218. }
  2219. if (message.payload.localhostUrl !== undefined) {
  2220. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  2221. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  2222. }
  2223. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  2224. renderHotmailAccounts();
  2225. if (selectMailProvider.value === 'hotmail-api') {
  2226. inputEmail.value = getCurrentHotmailEmail();
  2227. }
  2228. }
  2229. if (message.payload.autoRunDelayEnabled !== undefined) {
  2230. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  2231. updateAutoDelayInputState();
  2232. }
  2233. if (message.payload.autoRunDelayMinutes !== undefined) {
  2234. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  2235. }
  2236. break;
  2237. }
  2238. case 'AUTO_RUN_STATUS': {
  2239. syncLatestState({
  2240. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(message.payload.phase),
  2241. autoRunPhase: message.payload.phase,
  2242. autoRunCurrentRun: message.payload.currentRun,
  2243. autoRunTotalRuns: message.payload.totalRuns,
  2244. autoRunAttemptRun: message.payload.attemptRun,
  2245. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  2246. });
  2247. applyAutoRunStatus(message.payload);
  2248. updateStatusDisplay(latestState);
  2249. updateButtonStates();
  2250. break;
  2251. }
  2252. }
  2253. });
  2254. // ============================================================
  2255. // Theme Toggle
  2256. // ============================================================
  2257. const btnTheme = document.getElementById('btn-theme');
  2258. function setTheme(theme) {
  2259. document.documentElement.setAttribute('data-theme', theme);
  2260. localStorage.setItem('multipage-theme', theme);
  2261. }
  2262. function initTheme() {
  2263. const saved = localStorage.getItem('multipage-theme');
  2264. if (saved) {
  2265. setTheme(saved);
  2266. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  2267. setTheme('dark');
  2268. }
  2269. }
  2270. btnTheme.addEventListener('click', () => {
  2271. const current = document.documentElement.getAttribute('data-theme');
  2272. setTheme(current === 'dark' ? 'light' : 'dark');
  2273. });
  2274. document.addEventListener('click', (event) => {
  2275. if (!configMenuOpen) {
  2276. return;
  2277. }
  2278. if (configMenuShell?.contains(event.target)) {
  2279. return;
  2280. }
  2281. closeConfigMenu();
  2282. });
  2283. document.addEventListener('keydown', (event) => {
  2284. if (event.key === 'Escape' && configMenuOpen) {
  2285. closeConfigMenu();
  2286. }
  2287. });
  2288. // ============================================================
  2289. // Init
  2290. // ============================================================
  2291. initializeManualStepActions();
  2292. initTheme();
  2293. initHotmailListExpandedState();
  2294. updateSaveButtonState();
  2295. updateConfigMenuControls();
  2296. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  2297. restoreState().then(() => {
  2298. syncPasswordToggleLabel();
  2299. syncVpsUrlToggleLabel();
  2300. syncVpsPasswordToggleLabel();
  2301. updatePanelModeUI();
  2302. updateButtonStates();
  2303. updateStatusDisplay(latestState);
  2304. });