sidepanel.js 87 KB

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