sidepanel.js 88 KB

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