account-run-history.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. (function attachBackgroundAccountRunHistory(root, factory) {
  2. root.MultiPageBackgroundAccountRunHistory = factory();
  3. })(typeof self !== 'undefined' ? self : globalThis, function createBackgroundAccountRunHistoryModule() {
  4. function createAccountRunHistoryHelpers(deps = {}) {
  5. const {
  6. ACCOUNT_RUN_HISTORY_STORAGE_KEY = 'accountRunHistory',
  7. addLog,
  8. buildLocalHelperEndpoint,
  9. chrome,
  10. getErrorMessage,
  11. getState,
  12. normalizeAccountRunHistoryHelperBaseUrl,
  13. } = deps;
  14. function normalizeTimestamp(value) {
  15. const timestamp = Date.parse(String(value || ''));
  16. return Number.isFinite(timestamp) ? timestamp : 0;
  17. }
  18. function normalizeRetryCount(value) {
  19. const count = Math.floor(Number(value) || 0);
  20. return count > 0 ? count : 0;
  21. }
  22. function normalizeFinalStatus(status = '') {
  23. const normalized = String(status || '').trim().toLowerCase();
  24. if (!normalized) {
  25. return '';
  26. }
  27. if (normalized === 'success') {
  28. return 'success';
  29. }
  30. if (normalized === 'failed' || /_failed$/.test(normalized)) {
  31. return 'failed';
  32. }
  33. if (normalized === 'stopped' || /_stopped$/.test(normalized)) {
  34. return 'stopped';
  35. }
  36. return '';
  37. }
  38. function extractFailedStep(status = '', detail = '') {
  39. const normalizedStatus = String(status || '').trim().toLowerCase();
  40. const statusMatch = normalizedStatus.match(/^step(\d+)_failed$/);
  41. if (statusMatch) {
  42. const step = Number(statusMatch[1]);
  43. return Number.isInteger(step) && step > 0 ? step : null;
  44. }
  45. const text = String(detail || '').trim();
  46. const detailMatch = text.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/i);
  47. if (!detailMatch) {
  48. return null;
  49. }
  50. const step = Number(detailMatch[1] || detailMatch[2]);
  51. return Number.isInteger(step) && step > 0 ? step : null;
  52. }
  53. function isPhoneVerificationFailure(detail = '') {
  54. const text = String(detail || '').trim();
  55. if (!text) {
  56. return false;
  57. }
  58. return /add[_\s-]?phone/i.test(text)
  59. || /手机号(?:验证|页面|页)|手机(?:号)?页面|出现手机号验证/.test(text)
  60. || /进入了手机号页面/.test(text);
  61. }
  62. function buildFailureLabel(finalStatus, failedStep, failureDetail = '') {
  63. if (finalStatus === 'success') {
  64. return '流程完成';
  65. }
  66. if (finalStatus === 'stopped') {
  67. return '流程已停止';
  68. }
  69. if (finalStatus !== 'failed') {
  70. return '无';
  71. }
  72. if (isPhoneVerificationFailure(failureDetail)) {
  73. return '出现手机号验证';
  74. }
  75. if (Number.isInteger(failedStep) && failedStep > 0) {
  76. return `步骤 ${failedStep} 失败`;
  77. }
  78. return '流程失败';
  79. }
  80. function buildRecordId(email = '') {
  81. return String(email || '').trim().toLowerCase();
  82. }
  83. function normalizeSource(value = '') {
  84. return String(value || '').trim().toLowerCase() === 'auto' ? 'auto' : 'manual';
  85. }
  86. function normalizeAutoRunContext(context) {
  87. if (!context || typeof context !== 'object') {
  88. return null;
  89. }
  90. const currentRun = Math.max(0, Math.floor(Number(context.currentRun) || 0));
  91. const totalRuns = Math.max(0, Math.floor(Number(context.totalRuns) || 0));
  92. const attemptRun = Math.max(0, Math.floor(Number(context.attemptRun) || 0));
  93. if (!currentRun && !totalRuns && !attemptRun) {
  94. return null;
  95. }
  96. return {
  97. currentRun,
  98. totalRuns,
  99. attemptRun,
  100. };
  101. }
  102. function buildAutoRunContextFromState(state = {}) {
  103. return normalizeAutoRunContext({
  104. currentRun: state.autoRunCurrentRun,
  105. totalRuns: state.autoRunTotalRuns,
  106. attemptRun: state.autoRunAttemptRun,
  107. });
  108. }
  109. function getRetryCountFromState(state = {}) {
  110. if (!Boolean(state.autoRunning)) {
  111. return 0;
  112. }
  113. const attemptRun = Math.max(0, Math.floor(Number(state.autoRunAttemptRun) || 0));
  114. return attemptRun > 1 ? attemptRun - 1 : 0;
  115. }
  116. function normalizeAccountRunHistoryRecord(record) {
  117. if (!record || typeof record !== 'object') {
  118. return null;
  119. }
  120. const email = String(record.email || '').trim();
  121. const password = String(record.password || '').trim();
  122. const finalStatus = normalizeFinalStatus(record.finalStatus || record.status || '');
  123. if (!email || !password || !finalStatus) {
  124. return null;
  125. }
  126. const finishedAt = String(record.finishedAt || record.recordedAt || '').trim();
  127. const failureDetail = finalStatus === 'failed' || finalStatus === 'stopped'
  128. ? String(record.failureDetail || record.reason || '').trim()
  129. : '';
  130. const failedStepCandidate = Number(record.failedStep);
  131. const failedStep = Number.isInteger(failedStepCandidate) && failedStepCandidate > 0
  132. ? failedStepCandidate
  133. : extractFailedStep(record.finalStatus || record.status || '', failureDetail);
  134. const autoRunContext = normalizeAutoRunContext(record.autoRunContext);
  135. const retryCount = normalizeRetryCount(
  136. record.retryCount !== undefined
  137. ? record.retryCount
  138. : ((autoRunContext?.attemptRun || 0) > 1 ? autoRunContext.attemptRun - 1 : 0)
  139. );
  140. const source = normalizeSource(record.source || (autoRunContext ? 'auto' : 'manual'));
  141. return {
  142. recordId: String(record.recordId || '').trim() || buildRecordId(email),
  143. email,
  144. password,
  145. finalStatus,
  146. finishedAt,
  147. retryCount,
  148. failureLabel: String(record.failureLabel || '').trim() || buildFailureLabel(finalStatus, failedStep, failureDetail),
  149. failureDetail,
  150. failedStep: Number.isInteger(failedStep) && failedStep > 0 ? failedStep : null,
  151. source,
  152. autoRunContext: source === 'auto' ? autoRunContext : null,
  153. };
  154. }
  155. function normalizeAccountRunHistory(records) {
  156. if (!Array.isArray(records)) {
  157. return [];
  158. }
  159. return records
  160. .map((item) => normalizeAccountRunHistoryRecord(item))
  161. .filter(Boolean)
  162. .sort((left, right) => normalizeTimestamp(right.finishedAt) - normalizeTimestamp(left.finishedAt));
  163. }
  164. async function getPersistedAccountRunHistory() {
  165. try {
  166. const stored = await chrome.storage.local.get(ACCOUNT_RUN_HISTORY_STORAGE_KEY);
  167. return normalizeAccountRunHistory(stored[ACCOUNT_RUN_HISTORY_STORAGE_KEY]);
  168. } catch (err) {
  169. console.warn('[MultiPage:account-run-history] Failed to read account run history:', err?.message || err);
  170. return [];
  171. }
  172. }
  173. async function setPersistedAccountRunHistory(records) {
  174. const normalizedHistory = normalizeAccountRunHistory(records);
  175. await chrome.storage.local.set({
  176. [ACCOUNT_RUN_HISTORY_STORAGE_KEY]: normalizedHistory,
  177. });
  178. return normalizedHistory;
  179. }
  180. function buildAccountRunHistoryRecord(state = {}, status = '', reason = '') {
  181. const email = String(state.email || '').trim();
  182. const password = String(state.password || state.customPassword || '').trim() || '无';
  183. const finalStatus = normalizeFinalStatus(status);
  184. if (!email || !finalStatus) {
  185. return null;
  186. }
  187. const failureDetail = finalStatus === 'failed' || finalStatus === 'stopped' ? String(reason || '').trim() : '';
  188. const failedStep = finalStatus === 'failed' ? extractFailedStep(status, failureDetail) : null;
  189. const source = Boolean(state.autoRunning) ? 'auto' : 'manual';
  190. const autoRunContext = source === 'auto' ? buildAutoRunContextFromState(state) : null;
  191. const retryCount = source === 'auto' ? getRetryCountFromState(state) : 0;
  192. const finishedAt = new Date().toISOString();
  193. return {
  194. recordId: buildRecordId(email),
  195. email,
  196. password,
  197. finalStatus,
  198. finishedAt,
  199. retryCount,
  200. failureLabel: buildFailureLabel(finalStatus, failedStep, failureDetail),
  201. failureDetail,
  202. failedStep: Number.isInteger(failedStep) && failedStep > 0 ? failedStep : null,
  203. source,
  204. autoRunContext,
  205. };
  206. }
  207. function upsertAccountRunHistoryRecord(history, record) {
  208. const normalizedHistory = normalizeAccountRunHistory(history);
  209. if (!record) {
  210. return normalizedHistory;
  211. }
  212. const recordId = String(record.recordId || '').trim();
  213. const emailKey = String(record.email || '').trim().toLowerCase();
  214. const nextHistory = normalizedHistory.filter((item) => {
  215. const itemRecordId = String(item.recordId || '').trim();
  216. const itemEmailKey = String(item.email || '').trim().toLowerCase();
  217. return itemRecordId !== recordId && itemEmailKey !== emailKey;
  218. });
  219. nextHistory.unshift(record);
  220. return normalizeAccountRunHistory(nextHistory);
  221. }
  222. async function appendAccountRunHistoryRecord(status, stateOverride = null, reason = '') {
  223. const state = stateOverride || await getState();
  224. const record = buildAccountRunHistoryRecord(state, status, reason);
  225. if (!record) {
  226. return null;
  227. }
  228. const history = await getPersistedAccountRunHistory();
  229. const nextHistory = upsertAccountRunHistoryRecord(history, record);
  230. await setPersistedAccountRunHistory(nextHistory);
  231. return record;
  232. }
  233. function summarizeAccountRunHistory(records = []) {
  234. return normalizeAccountRunHistory(records).reduce((summary, record) => {
  235. summary.total += 1;
  236. if (record.finalStatus === 'success') {
  237. summary.success += 1;
  238. } else if (record.finalStatus === 'failed') {
  239. summary.failed += 1;
  240. } else if (record.finalStatus === 'stopped') {
  241. summary.stopped += 1;
  242. }
  243. summary.retryTotal += normalizeRetryCount(record.retryCount);
  244. return summary;
  245. }, {
  246. total: 0,
  247. success: 0,
  248. failed: 0,
  249. stopped: 0,
  250. retryTotal: 0,
  251. });
  252. }
  253. function buildAccountRunHistorySnapshotPayload(records = []) {
  254. const normalizedHistory = normalizeAccountRunHistory(records);
  255. return {
  256. generatedAt: new Date().toISOString(),
  257. summary: summarizeAccountRunHistory(normalizedHistory),
  258. records: normalizedHistory,
  259. };
  260. }
  261. function shouldSyncAccountRunHistorySnapshot(state = {}) {
  262. if (!Boolean(state.accountRunHistoryTextEnabled)) {
  263. return false;
  264. }
  265. const helperBaseUrl = normalizeAccountRunHistoryHelperBaseUrl(state.accountRunHistoryHelperBaseUrl);
  266. return Boolean(helperBaseUrl);
  267. }
  268. function shouldAppendAccountRunTextFile(state = {}) {
  269. return shouldSyncAccountRunHistorySnapshot(state);
  270. }
  271. async function syncAccountRunHistorySnapshot(records, stateOverride = null) {
  272. const state = stateOverride || await getState();
  273. if (!shouldSyncAccountRunHistorySnapshot(state)) {
  274. return '';
  275. }
  276. const helperBaseUrl = normalizeAccountRunHistoryHelperBaseUrl(state.accountRunHistoryHelperBaseUrl);
  277. let response;
  278. try {
  279. response = await fetch(buildLocalHelperEndpoint(helperBaseUrl, '/sync-account-run-records'), {
  280. method: 'POST',
  281. headers: {
  282. 'Content-Type': 'application/json',
  283. Accept: 'application/json',
  284. },
  285. body: JSON.stringify(buildAccountRunHistorySnapshotPayload(records)),
  286. });
  287. } catch (err) {
  288. throw new Error(`账号记录快照同步失败:无法连接本地 helper(${getErrorMessage(err)})`);
  289. }
  290. let payload = null;
  291. try {
  292. payload = await response.json();
  293. } catch (err) {
  294. throw new Error(`账号记录快照同步失败:本地 helper 返回了无法解析的响应(${getErrorMessage(err)})`);
  295. }
  296. if (!response.ok || payload?.ok === false) {
  297. throw new Error(`账号记录快照同步失败:${payload?.error || `HTTP ${response.status}`}`);
  298. }
  299. return payload?.filePath || '';
  300. }
  301. async function appendAccountRunRecord(status, stateOverride = null, reason = '') {
  302. const state = stateOverride || await getState();
  303. const record = await appendAccountRunHistoryRecord(status, state, reason);
  304. if (!record) {
  305. return null;
  306. }
  307. try {
  308. const history = await getPersistedAccountRunHistory();
  309. const filePath = await syncAccountRunHistorySnapshot(history, state);
  310. if (filePath) {
  311. await addLog(`账号记录快照已同步到本地:${filePath}`, 'info');
  312. }
  313. } catch (err) {
  314. await addLog(getErrorMessage(err), 'warn');
  315. }
  316. return record;
  317. }
  318. async function clearAccountRunHistory(stateOverride = null) {
  319. const state = stateOverride || await getState();
  320. const history = await getPersistedAccountRunHistory();
  321. await setPersistedAccountRunHistory([]);
  322. try {
  323. const filePath = await syncAccountRunHistorySnapshot([], state);
  324. if (filePath) {
  325. await addLog(`账号记录快照已同步到本地:${filePath}`, 'info');
  326. }
  327. } catch (err) {
  328. await addLog(getErrorMessage(err), 'warn');
  329. }
  330. return {
  331. clearedCount: history.length,
  332. };
  333. }
  334. return {
  335. appendAccountRunRecord,
  336. appendAccountRunHistoryRecord,
  337. buildAccountRunHistoryRecord,
  338. buildAccountRunHistorySnapshotPayload,
  339. clearAccountRunHistory,
  340. getPersistedAccountRunHistory,
  341. normalizeAccountRunHistory,
  342. normalizeAccountRunHistoryRecord,
  343. normalizeFinalStatus,
  344. setPersistedAccountRunHistory,
  345. shouldAppendAccountRunTextFile,
  346. shouldSyncAccountRunHistorySnapshot,
  347. summarizeAccountRunHistory,
  348. syncAccountRunHistorySnapshot,
  349. };
  350. }
  351. return {
  352. createAccountRunHistoryHelpers,
  353. };
  354. });