sidepanel.js 88 KB

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