sidepanel.js 86 KB

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