account-run-history.js 14 KB

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