AccountService.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. import { AppDataSource, PlatformAccount, AccountGroup } from '../models/index.js';
  2. import { AppError } from '../middleware/error.js';
  3. import { ERROR_CODES, HTTP_STATUS } from '@media-manager/shared';
  4. import type {
  5. PlatformType,
  6. PlatformAccount as PlatformAccountType,
  7. AccountGroup as AccountGroupType,
  8. AddPlatformAccountRequest,
  9. UpdatePlatformAccountRequest,
  10. CreateAccountGroupRequest,
  11. QRCodeInfo,
  12. LoginStatusResult,
  13. } from '@media-manager/shared';
  14. import { wsManager } from '../websocket/index.js';
  15. import { WS_EVENTS } from '@media-manager/shared';
  16. import { CookieManager } from '../automation/cookie.js';
  17. import { logger } from '../utils/logger.js';
  18. import { headlessBrowserService } from './HeadlessBrowserService.js';
  19. import { aiService } from '../ai/index.js';
  20. import { UserDayStatisticsService } from './UserDayStatisticsService.js';
  21. import { XiaohongshuAccountOverviewImportService } from './XiaohongshuAccountOverviewImportService.js';
  22. import { DouyinAccountOverviewImportService } from './DouyinAccountOverviewImportService.js';
  23. import { BaijiahaoContentOverviewImportService } from './BaijiahaoContentOverviewImportService.js';
  24. import { WeixinVideoDataCenterImportService } from './WeixinVideoDataCenterImportService.js';
  25. interface GetAccountsParams {
  26. platform?: string;
  27. groupId?: number;
  28. status?: string;
  29. }
  30. export class AccountService {
  31. private accountRepository = AppDataSource.getRepository(PlatformAccount);
  32. private groupRepository = AppDataSource.getRepository(AccountGroup);
  33. // ============ 账号分组 ============
  34. async getGroups(userId: number): Promise<AccountGroupType[]> {
  35. const groups = await this.groupRepository.find({
  36. where: { userId },
  37. order: { createdAt: 'ASC' },
  38. });
  39. return groups.map(this.formatGroup);
  40. }
  41. async createGroup(userId: number, data: CreateAccountGroupRequest): Promise<AccountGroupType> {
  42. const group = this.groupRepository.create({
  43. userId,
  44. name: data.name,
  45. description: data.description || null,
  46. });
  47. await this.groupRepository.save(group);
  48. return this.formatGroup(group);
  49. }
  50. async updateGroup(
  51. userId: number,
  52. groupId: number,
  53. data: Partial<CreateAccountGroupRequest>
  54. ): Promise<AccountGroupType> {
  55. const group = await this.groupRepository.findOne({
  56. where: { id: groupId, userId },
  57. });
  58. if (!group) {
  59. throw new AppError('分组不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.NOT_FOUND);
  60. }
  61. await this.groupRepository.update(groupId, {
  62. name: data.name ?? group.name,
  63. description: data.description ?? group.description,
  64. });
  65. const updated = await this.groupRepository.findOne({ where: { id: groupId } });
  66. return this.formatGroup(updated!);
  67. }
  68. async deleteGroup(userId: number, groupId: number): Promise<void> {
  69. const group = await this.groupRepository.findOne({
  70. where: { id: groupId, userId },
  71. });
  72. if (!group) {
  73. throw new AppError('分组不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.NOT_FOUND);
  74. }
  75. await this.groupRepository.delete(groupId);
  76. }
  77. // ============ 平台账号 ============
  78. async getAccounts(userId: number, params: GetAccountsParams): Promise<PlatformAccountType[]> {
  79. const queryBuilder = this.accountRepository
  80. .createQueryBuilder('account')
  81. .where('account.userId = :userId', { userId });
  82. if (params.platform) {
  83. queryBuilder.andWhere('account.platform = :platform', { platform: params.platform });
  84. }
  85. if (params.groupId) {
  86. queryBuilder.andWhere('account.groupId = :groupId', { groupId: params.groupId });
  87. }
  88. if (params.status) {
  89. queryBuilder.andWhere('account.status = :status', { status: params.status });
  90. }
  91. const accounts = await queryBuilder
  92. .orderBy('account.createdAt', 'DESC')
  93. .getMany();
  94. return accounts.map(this.formatAccount);
  95. }
  96. async getAccountById(userId: number, accountId: number): Promise<PlatformAccountType> {
  97. const account = await this.accountRepository.findOne({
  98. where: { id: accountId, userId },
  99. });
  100. if (!account) {
  101. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  102. }
  103. return this.formatAccount(account);
  104. }
  105. /**
  106. * 获取账号的 Cookie 数据(用于客户端打开后台)
  107. */
  108. async getAccountCookie(userId: number, accountId: number): Promise<string> {
  109. const account = await this.accountRepository.findOne({
  110. where: { id: accountId, userId },
  111. });
  112. if (!account) {
  113. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  114. }
  115. if (!account.cookieData) {
  116. throw new AppError('账号没有 Cookie 数据', HTTP_STATUS.BAD_REQUEST, ERROR_CODES.VALIDATION_ERROR);
  117. }
  118. // 尝试解密 Cookie
  119. let decryptedCookies: string;
  120. try {
  121. decryptedCookies = CookieManager.decrypt(account.cookieData);
  122. logger.info(`[AccountService] Cookie 解密成功,账号: ${account.accountName}`);
  123. } catch (error) {
  124. // 如果解密失败,返回原始数据
  125. logger.warn(`[AccountService] Cookie 解密失败,使用原始数据,账号: ${account.accountName}`);
  126. decryptedCookies = account.cookieData;
  127. }
  128. // 验证 Cookie 格式
  129. try {
  130. const parsed = JSON.parse(decryptedCookies);
  131. if (Array.isArray(parsed) && parsed.length > 0) {
  132. logger.info(`[AccountService] Cookie 格式验证通过,共 ${parsed.length} 个 Cookie`);
  133. const cookieNames = parsed.map((c: any) => c?.name).filter(Boolean);
  134. // 记录关键 Cookie(用于调试)
  135. const keyNames = cookieNames.slice(0, 5).join(', ');
  136. logger.info(`[AccountService] 关键 Cookie: ${keyNames}`);
  137. if (account.platform === 'baijiahao') {
  138. const required = ['BDUSS', 'STOKEN', 'bjhStoken', 'devStoken', 'BAIDUID'];
  139. const present = required.filter(name => cookieNames.includes(name));
  140. logger.info(
  141. `[AccountService] 百家号关键 Cookie 命中: ${present.length}/${required.length} -> ${present.join(', ') || '无'}`
  142. );
  143. }
  144. }
  145. } catch {
  146. logger.warn(`[AccountService] Cookie 不是 JSON 格式,可能是字符串格式`);
  147. }
  148. return decryptedCookies;
  149. }
  150. async addAccount(userId: number, data: AddPlatformAccountRequest & {
  151. accountInfo?: {
  152. accountId?: string;
  153. accountName?: string;
  154. avatarUrl?: string;
  155. fansCount?: number;
  156. worksCount?: number;
  157. };
  158. }): Promise<PlatformAccountType> {
  159. const platform = data.platform as PlatformType;
  160. // 解密 Cookie(如果是加密的)
  161. let cookieData = data.cookieData;
  162. let decryptedCookies: string;
  163. try {
  164. // 尝试解密(如果是通过浏览器登录获取的加密Cookie)
  165. decryptedCookies = CookieManager.decrypt(cookieData);
  166. } catch {
  167. // 如果解密失败,可能是直接粘贴的Cookie字符串
  168. decryptedCookies = cookieData;
  169. }
  170. // 检查客户端传入的 accountId 是否有效(不是纯时间戳)
  171. const clientAccountId = data.accountInfo?.accountId;
  172. const isValidClientAccountId = clientAccountId && !this.isTimestampBasedId(clientAccountId);
  173. // 从 Cookie 中提取账号 ID(部分平台的 Cookie 包含真实用户 ID)
  174. const accountIdFromCookie = this.extractAccountIdFromCookie(platform, decryptedCookies);
  175. // 某些平台应优先使用 API 返回的真实 ID,而不是 Cookie 中的值
  176. // - 抖音:使用抖音号(unique_id,如 Ethanfly9392),而不是 Cookie 中的 passport_uid
  177. // - 小红书:使用小红书号(red_num),而不是 Cookie 中的 userid
  178. // - 百家号:使用 new_uc_id,而不是 Cookie 中的 BDUSS
  179. // - 视频号/头条:使用 API 返回的真实账号 ID
  180. const platformsPreferApiId: PlatformType[] = ['douyin', 'xiaohongshu', 'baijiahao', 'weixin_video', 'toutiao'];
  181. const preferApiId = platformsPreferApiId.includes(platform);
  182. // 确定最终的 accountId
  183. let finalAccountId: string;
  184. if (preferApiId && isValidClientAccountId) {
  185. // 对于优先使用 API ID 的平台,先用客户端传入的有效 ID
  186. finalAccountId = this.normalizeAccountId(platform, clientAccountId);
  187. logger.info(`[addAccount] Using API-based accountId for ${platform}: ${finalAccountId}`);
  188. } else if (accountIdFromCookie) {
  189. // 其他平台优先使用 Cookie 中提取的 ID
  190. finalAccountId = accountIdFromCookie;
  191. logger.info(`[addAccount] Using accountId from cookie: ${finalAccountId}`);
  192. } else if (isValidClientAccountId) {
  193. // 再次尝试客户端 ID
  194. finalAccountId = this.normalizeAccountId(platform, clientAccountId);
  195. logger.info(`[addAccount] Using valid client accountId: ${finalAccountId}`);
  196. } else {
  197. finalAccountId = `${platform}_${Date.now()}`;
  198. logger.warn(`[addAccount] Using timestamp-based accountId as fallback: ${finalAccountId}`);
  199. }
  200. // 使用传入的账号信息(来自浏览器登录会话),或使用默认值
  201. const accountInfo = {
  202. accountId: finalAccountId,
  203. accountName: data.accountInfo?.accountName || `${platform}账号`,
  204. avatarUrl: data.accountInfo?.avatarUrl || null,
  205. fansCount: data.accountInfo?.fansCount || 0,
  206. worksCount: data.accountInfo?.worksCount || 0,
  207. };
  208. logger.info(`Adding account for ${platform}: ${accountInfo.accountId}, name: ${accountInfo.accountName}`);
  209. // 检查是否已存在相同账号
  210. const existing = await this.accountRepository.findOne({
  211. where: { userId, platform, accountId: accountInfo.accountId },
  212. });
  213. if (existing) {
  214. // 更新已存在的账号
  215. const wasExpired = existing.status === 'expired';
  216. await this.accountRepository.update(existing.id, {
  217. cookieData: cookieData, // 存储原始数据(可能是加密的)
  218. accountName: accountInfo.accountName,
  219. avatarUrl: accountInfo.avatarUrl,
  220. fansCount: accountInfo.fansCount,
  221. worksCount: accountInfo.worksCount,
  222. status: 'active',
  223. groupId: data.groupId || existing.groupId,
  224. proxyConfig: data.proxyConfig || existing.proxyConfig,
  225. });
  226. const updated = await this.accountRepository.findOne({ where: { id: existing.id } });
  227. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  228. // Bug #6070: 通知前端账号数据已变更,触发其他模块(如首页数据看板)刷新
  229. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_DATA_CHANGED, { accountId: existing.id });
  230. // 异步刷新账号信息(获取准确的粉丝数、作品数等)
  231. this.refreshAccountAsync(userId, existing.id, platform).catch(err => {
  232. logger.warn(`[addAccount] Background refresh failed for existing account ${existing.id}:`, err);
  233. });
  234. // 账号从 expired 恢复为 active:异步补齐最近 30 天用户每日数据
  235. if (wasExpired && updated && updated.status === 'active') {
  236. this.backfillDailyStatisticsForReactivatedAccountAsync(updated).catch(err => {
  237. logger.warn(
  238. `[addAccount] Daily statistics backfill failed for reactivated account ${updated.id}:`,
  239. err
  240. );
  241. });
  242. }
  243. return this.formatAccount(updated!);
  244. }
  245. // 创建新账号
  246. const account = this.accountRepository.create({
  247. userId,
  248. platform,
  249. cookieData: cookieData,
  250. groupId: data.groupId || null,
  251. proxyConfig: data.proxyConfig || null,
  252. status: 'active',
  253. accountId: accountInfo.accountId,
  254. accountName: accountInfo.accountName,
  255. avatarUrl: accountInfo.avatarUrl,
  256. fansCount: accountInfo.fansCount,
  257. worksCount: accountInfo.worksCount,
  258. });
  259. await this.accountRepository.save(account);
  260. // 通知其他客户端
  261. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_ADDED, { account: this.formatAccount(account) });
  262. // Bug #6070: 通知前端账号数据已变更,触发其他模块(如首页数据看板)刷新
  263. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_DATA_CHANGED, { accountId: account.id });
  264. // 异步刷新账号信息(获取准确的粉丝数、作品数等)
  265. // 不阻塞返回,后台执行
  266. this.refreshAccountAsync(userId, account.id, platform).catch(err => {
  267. logger.warn(`[addAccount] Background refresh failed for account ${account.id}:`, err);
  268. });
  269. // 新增账号后,按平台触发一次“近30天数据同步”,用于初始化 user_day_statistics
  270. this.initStatisticsForNewAccountAsync(account).catch(err => {
  271. logger.warn(
  272. `[addAccount] Initial statistics sync failed for account ${account.id} (${platform}):`,
  273. err
  274. );
  275. });
  276. return this.formatAccount(account);
  277. }
  278. /**
  279. * 异步刷新账号信息(用于添加账号后获取准确数据)
  280. */
  281. private async refreshAccountAsync(userId: number, accountId: number, platform: PlatformType): Promise<void> {
  282. // 延迟 2 秒执行,等待前端处理完成
  283. await new Promise(resolve => setTimeout(resolve, 2000));
  284. logger.info(`[addAccount] Starting background refresh for account ${accountId} (${platform})`);
  285. try {
  286. await this.refreshAccount(userId, accountId);
  287. logger.info(`[addAccount] Background refresh completed for account ${accountId}`);
  288. } catch (error) {
  289. logger.warn(`[addAccount] Background refresh failed for account ${accountId}:`, error);
  290. }
  291. }
  292. /**
  293. * 新增账号后,按平台触发一次“近30天数据同步”,用于初始化 user_day_statistics
  294. * 仿照定时任务里跑的导入服务,但只针对当前账号
  295. */
  296. private async initStatisticsForNewAccountAsync(account: PlatformAccount): Promise<void> {
  297. const platform = account.platform as PlatformType;
  298. // 延迟几秒,避免和前端后续操作/账号刷新抢占浏览器资源
  299. await new Promise((resolve) => setTimeout(resolve, 3000));
  300. logger.info(
  301. `[addAccount] Starting initial statistics import for account ${account.id} (${platform})`
  302. );
  303. try {
  304. if (platform === 'xiaohongshu') {
  305. await XiaohongshuAccountOverviewImportService.runDailyImport();
  306. } else if (platform === 'douyin') {
  307. await DouyinAccountOverviewImportService.runDailyImport();
  308. } else if (platform === 'baijiahao') {
  309. await BaijiahaoContentOverviewImportService.runDailyImport();
  310. } else if (platform === 'weixin_video') {
  311. await WeixinVideoDataCenterImportService.runDailyImport();
  312. } else {
  313. logger.info(
  314. `[addAccount] Initial statistics import skipped for unsupported platform ${platform}`
  315. );
  316. return;
  317. }
  318. logger.info(
  319. `[addAccount] Initial statistics import completed for account ${account.id} (${platform})`
  320. );
  321. } catch (error) {
  322. logger.warn(
  323. `[addAccount] Initial statistics import encountered error for account ${account.id} (${platform}):`,
  324. error
  325. );
  326. // 出错时不抛出,让前端添加账号流程不受影响
  327. }
  328. }
  329. /**
  330. * 账号从失效(expired)恢复为 active 时,为该账号补齐最近 30 天的用户每日数据(user_day_statistics)
  331. * 注意:仅在状态从 expired → active 的切换时触发,且按平台调用对应的单账号导入入口
  332. */
  333. private async backfillDailyStatisticsForReactivatedAccountAsync(
  334. account: PlatformAccount
  335. ): Promise<void> {
  336. const platform = account.platform as PlatformType;
  337. // 延迟几秒,避免与前端后续操作/其他浏览器任务抢占资源
  338. await new Promise((resolve) => setTimeout(resolve, 3000));
  339. try {
  340. if (platform === 'xiaohongshu') {
  341. await XiaohongshuAccountOverviewImportService.runDailyImportForAccount(account.id);
  342. } else if (platform === 'douyin') {
  343. await DouyinAccountOverviewImportService.runDailyImportForAccount(account.id);
  344. } else if (platform === 'baijiahao') {
  345. await BaijiahaoContentOverviewImportService.runDailyImportForAccount(account.id);
  346. } else if (platform === 'weixin_video') {
  347. await WeixinVideoDataCenterImportService.runDailyImportForAccount(account.id);
  348. } else {
  349. logger.info(
  350. `[AccountService] Skip daily statistics backfill for unsupported platform ${platform} (accountId=${account.id})`
  351. );
  352. return;
  353. }
  354. logger.info(
  355. `[AccountService] Completed daily statistics backfill for reactivated account ${account.id} (${platform})`
  356. );
  357. } catch (error) {
  358. logger.warn(
  359. `[AccountService] Daily statistics backfill failed for reactivated account ${account.id} (${platform}):`,
  360. error
  361. );
  362. // 出错不影响账号激活本身
  363. }
  364. }
  365. async updateAccount(
  366. userId: number,
  367. accountId: number,
  368. data: UpdatePlatformAccountRequest
  369. ): Promise<PlatformAccountType> {
  370. const account = await this.accountRepository.findOne({
  371. where: { id: accountId, userId },
  372. });
  373. if (!account) {
  374. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  375. }
  376. await this.accountRepository.update(accountId, {
  377. groupId: data.groupId !== undefined ? data.groupId : account.groupId,
  378. proxyConfig: data.proxyConfig !== undefined ? data.proxyConfig : account.proxyConfig,
  379. status: data.status ?? account.status,
  380. });
  381. const updated = await this.accountRepository.findOne({ where: { id: accountId } });
  382. // 通知其他客户端
  383. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  384. return this.formatAccount(updated!);
  385. }
  386. async deleteAccount(userId: number, accountId: number): Promise<void> {
  387. const account = await this.accountRepository.findOne({
  388. where: { id: accountId, userId },
  389. });
  390. if (!account) {
  391. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  392. }
  393. await this.accountRepository.delete(accountId);
  394. // 通知其他客户端
  395. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_DELETED, { accountId });
  396. }
  397. async refreshAccount(userId: number, accountId: number): Promise<PlatformAccountType & { needReLogin?: boolean }> {
  398. const account = await this.accountRepository.findOne({
  399. where: { id: accountId, userId },
  400. });
  401. if (!account) {
  402. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  403. }
  404. const platform = account.platform as PlatformType;
  405. const wasExpired = account.status === 'expired';
  406. const updateData: Partial<PlatformAccount> = {
  407. updatedAt: new Date(),
  408. };
  409. let needReLogin = false;
  410. let aiRefreshSuccess = false;
  411. // Bug #6084: cookie 为空的账号直接标记为 expired
  412. if (!account.cookieData) {
  413. updateData.status = 'expired';
  414. needReLogin = true;
  415. logger.warn(`[refreshAccount] Account ${accountId} has empty cookieData, marking as expired`);
  416. await this.accountRepository.update(accountId, updateData);
  417. const updated = await this.accountRepository.findOne({ where: { id: accountId } });
  418. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  419. return { ...this.formatAccount(updated!), needReLogin };
  420. }
  421. // 尝试通过无头浏览器刷新账号信息
  422. if (account.cookieData) {
  423. try {
  424. // 解密 Cookie
  425. let decryptedCookies: string;
  426. try {
  427. decryptedCookies = CookieManager.decrypt(account.cookieData);
  428. } catch {
  429. decryptedCookies = account.cookieData;
  430. }
  431. // 解析 Cookie - 支持两种格式
  432. let cookieList: { name: string; value: string; domain: string; path: string }[];
  433. let cookieParseError = false;
  434. try {
  435. // 先尝试 JSON 格式
  436. cookieList = JSON.parse(decryptedCookies);
  437. } catch {
  438. // 如果 JSON 解析失败,尝试解析 "name=value; name2=value2" 格式
  439. cookieList = this.parseCookieString(decryptedCookies, platform);
  440. if (cookieList.length === 0) {
  441. logger.error(`Invalid cookie format for account ${accountId}`);
  442. cookieParseError = true;
  443. }
  444. }
  445. if (cookieList.length > 0 && !cookieParseError) {
  446. // 抖音、小红书、百家号直接使用 API 获取准确数据,不使用 AI(因为 AI 可能识别错误)
  447. // 但是如果 API 调用失败,作为备用方案仍会尝试 AI
  448. const platformsSkipAI: PlatformType[] = ['douyin', 'xiaohongshu', 'baijiahao'];
  449. const shouldUseAI = aiService.isAvailable() && !platformsSkipAI.includes(platform);
  450. logger.info(`[refreshAccount] Platform: ${platform}, shouldUseAI: ${shouldUseAI}, aiAvailable: ${aiService.isAvailable()}`);
  451. // ========== AI 辅助刷新(部分平台使用) ==========
  452. if (shouldUseAI) {
  453. try {
  454. logger.info(`[AI Refresh] Starting AI-assisted refresh for account ${accountId} (${platform})`);
  455. // 使用无头浏览器截图,然后 AI 分析
  456. const aiResult = await this.refreshAccountWithAI(platform, cookieList, accountId);
  457. if (aiResult.needReLogin) {
  458. // AI 检测到需要重新登录
  459. updateData.status = 'expired';
  460. needReLogin = true;
  461. aiRefreshSuccess = true;
  462. logger.warn(`[AI Refresh] Account ${accountId} needs re-login (detected by AI)`);
  463. } else if (aiResult.accountInfo) {
  464. // AI 成功获取到账号信息
  465. updateData.status = 'active';
  466. updateData.accountName = aiResult.accountInfo.accountName;
  467. if (aiResult.accountInfo.avatarUrl) {
  468. updateData.avatarUrl = aiResult.accountInfo.avatarUrl;
  469. }
  470. if (aiResult.accountInfo.fansCount !== undefined) {
  471. updateData.fansCount = aiResult.accountInfo.fansCount;
  472. }
  473. if (aiResult.accountInfo.worksCount !== undefined) {
  474. updateData.worksCount = aiResult.accountInfo.worksCount;
  475. }
  476. aiRefreshSuccess = true;
  477. logger.info(`[AI Refresh] Successfully refreshed account ${accountId}: ${aiResult.accountInfo.accountName}`);
  478. }
  479. } catch (aiError) {
  480. logger.warn(`[AI Refresh] AI-assisted refresh failed for account ${accountId}:`, aiError);
  481. // AI 刷新失败,继续使用原有逻辑
  482. }
  483. }
  484. // ========== 原有逻辑(AI 失败时的备用方案) ==========
  485. if (!aiRefreshSuccess) {
  486. const cookieStatus = await headlessBrowserService.checkCookieStatus(platform, cookieList);
  487. if (cookieStatus.needReLogin) {
  488. updateData.status = 'expired';
  489. needReLogin = true;
  490. logger.warn(
  491. `Account ${accountId} (${account.accountName}) needs re-login: reason=${cookieStatus.reason}, source=${cookieStatus.source}, msg=${cookieStatus.message || ''}`
  492. );
  493. } else if (cookieStatus.uncertain) {
  494. logger.warn(
  495. `Account ${accountId} (${account.accountName}) cookie status uncertain: source=${cookieStatus.source}, msg=${cookieStatus.message || ''}`
  496. );
  497. } else if (cookieStatus.isValid) {
  498. updateData.status = 'active';
  499. try {
  500. const profile = await headlessBrowserService.fetchAccountInfo(platform, cookieList);
  501. // 检查是否获取到有效信息(排除默认名称)
  502. const defaultNames = [
  503. `${platform}账号`, '未知账号', '抖音账号', '小红书账号',
  504. '快手账号', '视频号账号', 'B站账号', '头条账号', '百家号账号'
  505. ];
  506. const isValidProfile = profile.accountName && !defaultNames.includes(profile.accountName);
  507. if (isValidProfile) {
  508. updateData.accountName = profile.accountName;
  509. updateData.avatarUrl = profile.avatarUrl;
  510. // 仅在粉丝数有效时更新(避免因获取失败导致的归零)
  511. if (profile.fansCount !== undefined) {
  512. // 如果新粉丝数为 0,但原粉丝数 > 0,可能是获取失败,记录警告并跳过更新
  513. if (profile.fansCount === 0 && (account.fansCount || 0) > 0) {
  514. logger.warn(`[refreshAccount] Fans count dropped to 0 for ${accountId} (was ${account.fansCount}). Ignoring potential fetch error.`);
  515. } else {
  516. updateData.fansCount = profile.fansCount;
  517. }
  518. }
  519. if (profile.worksCount === 0 && (account.worksCount || 0) > 0) {
  520. logger.warn(`[refreshAccount] Works count dropped to 0 for ${accountId} (was ${account.worksCount}). Ignoring potential fetch error.`);
  521. } else {
  522. updateData.worksCount = profile.worksCount;
  523. }
  524. // 如果获取到了有效的 accountId(如抖音号),也更新它
  525. // 这样可以修正之前使用错误 ID(如 Cookie 值)保存的账号
  526. if (profile.accountId && !this.isTimestampBasedId(profile.accountId)) {
  527. const newAccountId = this.normalizeAccountId(platform, profile.accountId);
  528. // 只有当新 ID 与旧 ID 不同时才更新
  529. if (newAccountId !== account.accountId) {
  530. updateData.accountId = newAccountId;
  531. logger.info(`[refreshAccount] Updating accountId from ${account.accountId} to ${newAccountId}`);
  532. }
  533. }
  534. logger.info(`Refreshed account info for ${platform}: ${profile.accountName}, fans: ${profile.fansCount}, works: ${profile.worksCount}`);
  535. } else {
  536. // 获取的信息无效,但 Cookie 有效,保持 active 状态
  537. logger.warn(`Could not fetch valid account info for ${accountId}, but cookie is valid`);
  538. // Bug #6075: 即使 profile 名称无效,仍然强制更新 avatarUrl(用户可能只改了头像没改昵称)
  539. if (profile.avatarUrl) {
  540. updateData.avatarUrl = profile.avatarUrl;
  541. logger.info(`[refreshAccount] Force updating avatarUrl for ${accountId} (profile name invalid but avatar changed)`);
  542. }
  543. }
  544. // 无论 profile 是否有效,都尝试更新粉丝数和作品数(来自 Python API 的数据是可靠的)
  545. // 仅在粉丝数有效时更新(避免因获取失败导致的归零)
  546. if (profile.fansCount !== undefined) {
  547. if (profile.fansCount === 0 && (account.fansCount || 0) > 0) {
  548. logger.warn(`[refreshAccount] Fans count dropped to 0 for ${accountId} (was ${account.fansCount}). Ignoring potential fetch error.`);
  549. } else {
  550. updateData.fansCount = profile.fansCount;
  551. }
  552. }
  553. // 作品数更新:Python API 返回的数据是可靠的
  554. if (profile.worksCount !== undefined && profile.worksCount > 0) {
  555. updateData.worksCount = profile.worksCount;
  556. logger.info(`[refreshAccount] Updated works count for ${accountId}: ${profile.worksCount}`);
  557. } else if (profile.worksCount === 0 && (account.worksCount || 0) > 0) {
  558. logger.warn(`[refreshAccount] Works count dropped to 0 for ${accountId} (was ${account.worksCount}). Ignoring potential fetch error.`);
  559. }
  560. } catch (infoError) {
  561. // 获取账号信息失败,但 Cookie 检查已通过,保持 active 状态
  562. logger.warn(`Failed to fetch account info for ${accountId}, but cookie is valid:`, infoError);
  563. // 对于百家号,如果是获取信息失败,可能是分散认证问题,不需要立即标记为失败
  564. if (platform === 'baijiahao') {
  565. logger.info(`[baijiahao] Account info fetch failed for ${accountId}, but this might be due to distributed auth. Keeping status active.`);
  566. }
  567. }
  568. } else {
  569. logger.warn(
  570. `Account ${accountId} (${account.accountName}) cookie invalid without explicit re-login: source=${cookieStatus.source}, reason=${cookieStatus.reason}`
  571. );
  572. }
  573. }
  574. }
  575. // Cookie 解析失败时,不改变状态
  576. } catch (error) {
  577. logger.error(`Failed to refresh account ${accountId}:`, error);
  578. // 不抛出错误,不改变状态,只更新时间戳
  579. }
  580. }
  581. // 没有 Cookie 数据时,不改变状态
  582. await this.accountRepository.update(accountId, updateData);
  583. const updated = await this.accountRepository.findOne({ where: { id: accountId } });
  584. // 账号从 expired 恢复为 active:异步补齐最近 30 天用户每日数据
  585. const newStatus = updated?.status ?? account.status;
  586. if (wasExpired && newStatus === 'active' && updated) {
  587. this.backfillDailyStatisticsForReactivatedAccountAsync(updated).catch((error) => {
  588. logger.warn(
  589. `[AccountService] Daily statistics backfill failed after refresh for reactivated account ${updated.id}:`,
  590. error
  591. );
  592. });
  593. }
  594. // 刷新账号时不再写入 user_day_statistics,仅保留:每天定时任务 + 添加账号时的 initStatisticsForNewAccountAsync
  595. // if (updated) {
  596. // try {
  597. // const userDayStatisticsService = new UserDayStatisticsService();
  598. // await userDayStatisticsService.saveStatistics({
  599. // accountId,
  600. // fansCount: updated.fansCount || 0,
  601. // worksCount: updated.worksCount || 0,
  602. // });
  603. // logger.debug(`[AccountService] Saved account day statistics for account ${accountId} (fans: ${updated.fansCount || 0}, works: ${updated.worksCount || 0})`);
  604. // } catch (error) {
  605. // logger.error(`[AccountService] Failed to save account day statistics for account ${accountId}:`, error);
  606. // }
  607. // }
  608. // 通知其他客户端
  609. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  610. // Bug #6075: 检测 avatarUrl 或 accountName 是否发生变化,通知前端刷新数据
  611. if (updated) {
  612. const avatarChanged = updateData.avatarUrl !== undefined && updateData.avatarUrl !== account.avatarUrl;
  613. const nameChanged = updateData.accountName !== undefined && updateData.accountName !== account.accountName;
  614. if (avatarChanged || nameChanged) {
  615. logger.info(`[refreshAccount] Account ${accountId} data changed: avatarChanged=${avatarChanged}, nameChanged=${nameChanged}`);
  616. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_DATA_CHANGED, {
  617. accountId,
  618. accountName: updated.accountName,
  619. avatarUrl: updated.avatarUrl,
  620. });
  621. }
  622. }
  623. return { ...this.formatAccount(updated!), needReLogin };
  624. }
  625. /**
  626. * 使用 AI 辅助刷新账号信息
  627. */
  628. private async refreshAccountWithAI(
  629. platform: PlatformType,
  630. cookieList: { name: string; value: string; domain: string; path: string }[],
  631. accountId: number
  632. ): Promise<{
  633. needReLogin: boolean;
  634. accountInfo?: {
  635. accountName: string;
  636. avatarUrl?: string;
  637. fansCount?: number;
  638. worksCount?: number;
  639. };
  640. }> {
  641. // 使用无头浏览器访问平台后台并截图
  642. const screenshot = await headlessBrowserService.capturePageScreenshot(platform, cookieList);
  643. if (!screenshot) {
  644. throw new Error('Failed to capture screenshot');
  645. }
  646. // 第一步:使用 AI 分析登录状态
  647. const loginStatus = await aiService.analyzeLoginStatus(screenshot, platform);
  648. logger.info(`[AI Refresh] Login status for account ${accountId}:`, {
  649. isLoggedIn: loginStatus.isLoggedIn,
  650. hasVerification: loginStatus.hasVerification,
  651. });
  652. // 如果 AI 检测到未登录或有验证码,说明需要重新登录
  653. if (!loginStatus.isLoggedIn || loginStatus.hasVerification) {
  654. return { needReLogin: true };
  655. }
  656. // 第二步:使用 AI 提取账号信息
  657. const accountInfo = await aiService.extractAccountInfo(screenshot, platform);
  658. logger.info(`[AI Refresh] Account info extraction for ${accountId}:`, {
  659. found: accountInfo.found,
  660. accountName: accountInfo.accountName,
  661. });
  662. if (accountInfo.found && accountInfo.accountName) {
  663. return {
  664. needReLogin: false,
  665. accountInfo: {
  666. accountName: accountInfo.accountName,
  667. fansCount: accountInfo.fansCount ? parseInt(String(accountInfo.fansCount)) : undefined,
  668. worksCount: accountInfo.worksCount ? parseInt(String(accountInfo.worksCount)) : undefined,
  669. },
  670. };
  671. }
  672. // AI 未能提取到账号信息,但登录状态正常
  673. // 返回空结果,让原有逻辑处理
  674. return { needReLogin: false };
  675. }
  676. /**
  677. * 检查账号 Cookie 是否有效
  678. */
  679. async checkAccountStatus(
  680. userId: number,
  681. accountId: number
  682. ): Promise<{ isValid: boolean; needReLogin: boolean; uncertain: boolean }> {
  683. const account = await this.accountRepository.findOne({
  684. where: { id: accountId, userId },
  685. });
  686. if (!account) {
  687. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  688. }
  689. if (!account.cookieData) {
  690. // 更新状态为过期
  691. await this.accountRepository.update(accountId, { status: 'expired' });
  692. return { isValid: false, needReLogin: true, uncertain: false };
  693. }
  694. const platform = account.platform as PlatformType;
  695. try {
  696. // 解密 Cookie
  697. let decryptedCookies: string;
  698. try {
  699. decryptedCookies = CookieManager.decrypt(account.cookieData);
  700. } catch {
  701. decryptedCookies = account.cookieData;
  702. }
  703. // 解析 Cookie - 支持两种格式
  704. let cookieList: { name: string; value: string; domain: string; path: string }[];
  705. try {
  706. // 先尝试 JSON 格式
  707. cookieList = JSON.parse(decryptedCookies);
  708. } catch {
  709. // 如果 JSON 解析失败,尝试解析 "name=value; name2=value2" 格式
  710. cookieList = this.parseCookieString(decryptedCookies, platform);
  711. if (cookieList.length === 0) {
  712. await this.accountRepository.update(accountId, { status: 'expired' });
  713. return { isValid: false, needReLogin: true, uncertain: false };
  714. }
  715. }
  716. const cookieStatus = await headlessBrowserService.checkCookieStatus(platform, cookieList);
  717. // 更新账号状态
  718. if (cookieStatus.needReLogin) {
  719. await this.accountRepository.update(accountId, { status: 'expired' });
  720. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, {
  721. account: { ...this.formatAccount(account), status: 'expired' }
  722. });
  723. return { isValid: false, needReLogin: true, uncertain: false };
  724. }
  725. if (cookieStatus.uncertain) {
  726. return { isValid: true, needReLogin: false, uncertain: true };
  727. }
  728. if (cookieStatus.isValid && account.status === 'expired') {
  729. // 如果之前是过期状态但现在有效了,更新为正常
  730. await this.accountRepository.update(accountId, { status: 'active' });
  731. }
  732. return { isValid: cookieStatus.isValid, needReLogin: false, uncertain: false };
  733. } catch (error) {
  734. logger.error(`Failed to check account status ${accountId}:`, error);
  735. return { isValid: true, needReLogin: false, uncertain: true };
  736. }
  737. }
  738. /**
  739. * 批量刷新所有账号状态
  740. */
  741. async refreshAllAccounts(userId: number): Promise<{ refreshed: number; failed: number }> {
  742. const accounts = await this.accountRepository.find({
  743. where: { userId },
  744. });
  745. let refreshed = 0;
  746. let failed = 0;
  747. for (const account of accounts) {
  748. try {
  749. await this.refreshAccount(userId, account.id);
  750. refreshed++;
  751. } catch (error) {
  752. logger.error(`Failed to refresh account ${account.id}:`, error);
  753. failed++;
  754. }
  755. }
  756. logger.info(`Refreshed ${refreshed} accounts for user ${userId}, ${failed} failed`);
  757. return { refreshed, failed };
  758. }
  759. async getQRCode(platform: string): Promise<QRCodeInfo> {
  760. // TODO: 调用对应平台适配器获取二维码
  761. // 这里返回模拟数据
  762. return {
  763. qrcodeUrl: `https://example.com/qrcode/${platform}/${Date.now()}`,
  764. qrcodeKey: `qr_${platform}_${Date.now()}`,
  765. expireTime: Date.now() + 300000, // 5分钟后过期
  766. };
  767. }
  768. async checkQRCodeStatus(platform: string, qrcodeKey: string): Promise<LoginStatusResult> {
  769. // TODO: 调用对应平台适配器检查扫码状态
  770. // 这里返回模拟数据
  771. return {
  772. status: 'waiting',
  773. message: '等待扫码',
  774. };
  775. }
  776. /**
  777. * 验证 Cookie 并获取账号信息(用于 Electron 内嵌浏览器登录)
  778. */
  779. async verifyCookieAndGetInfo(platform: PlatformType, cookieData: string): Promise<{
  780. success: boolean;
  781. message?: string;
  782. accountInfo?: {
  783. accountId: string;
  784. accountName: string;
  785. avatarUrl: string;
  786. fansCount: number;
  787. worksCount: number;
  788. };
  789. }> {
  790. try {
  791. const domainMap: Record<string, string> = {
  792. douyin: '.douyin.com',
  793. kuaishou: '.kuaishou.com',
  794. xiaohongshu: '.xiaohongshu.com',
  795. weixin_video: '.qq.com',
  796. bilibili: '.bilibili.com',
  797. toutiao: '.toutiao.com',
  798. baijiahao: '.baidu.com',
  799. qie: '.qq.com',
  800. dayuhao: '.alibaba.com',
  801. };
  802. let cookieList: { name: string; value: string; domain: string; path: string }[] = [];
  803. try {
  804. const parsed = JSON.parse(cookieData) as Array<{
  805. name?: string;
  806. value?: string;
  807. domain?: string;
  808. path?: string;
  809. }>;
  810. if (Array.isArray(parsed) && parsed.length > 0) {
  811. const domain = domainMap[platform] || `.${platform}.com`;
  812. cookieList = parsed
  813. .filter(c => c?.name && c?.value)
  814. .map(c => ({
  815. name: String(c.name),
  816. value: String(c.value),
  817. domain: c.domain ? String(c.domain) : domain,
  818. path: c.path ? String(c.path) : '/',
  819. }));
  820. }
  821. } catch {
  822. cookieList = this.parseCookieString(cookieData, platform);
  823. }
  824. if (cookieList.length === 0) {
  825. return { success: false, message: 'Cookie 格式无效' };
  826. }
  827. // 先尝试获取账号信息(可以同时验证登录状态)
  828. // 如果能成功获取到有效信息,说明登录是有效的
  829. try {
  830. const profile = await headlessBrowserService.fetchAccountInfo(platform, cookieList);
  831. // 检查是否获取到有效信息(排除默认名称)
  832. const defaultNames = [
  833. `${platform}账号`, '未知账号', '抖音账号', '小红书账号',
  834. '快手账号', '视频号账号', 'B站账号', '头条账号', '百家号账号'
  835. ];
  836. const isValidProfile = profile.accountName && !defaultNames.includes(profile.accountName);
  837. if (isValidProfile) {
  838. return {
  839. success: true,
  840. accountInfo: {
  841. // 确保 accountId 带有平台前缀
  842. accountId: this.normalizeAccountId(platform, profile.accountId || ''),
  843. accountName: profile.accountName,
  844. avatarUrl: profile.avatarUrl || '',
  845. fansCount: profile.fansCount || 0,
  846. worksCount: profile.worksCount || 0,
  847. },
  848. };
  849. }
  850. // 未能获取有效信息,再验证 Cookie 是否有效
  851. logger.info(`[verifyCookieAndGetInfo] Could not get valid profile for ${platform}, checking cookie validity...`);
  852. } catch (infoError) {
  853. logger.warn(`Failed to fetch account info for ${platform}:`, infoError);
  854. }
  855. // 账号信息获取失败或无效,检查 Cookie 是否有效
  856. const cookieStatus = await headlessBrowserService.checkCookieStatus(platform, cookieList);
  857. if (cookieStatus.isValid) {
  858. // Cookie 有效但未能获取账号信息,返回基本成功
  859. return {
  860. success: true,
  861. message: '登录成功,但无法获取详细信息',
  862. accountInfo: {
  863. accountId: `${platform}_${Date.now()}`,
  864. accountName: `${platform}账号`,
  865. avatarUrl: '',
  866. fansCount: 0,
  867. worksCount: 0,
  868. },
  869. };
  870. }
  871. if (cookieStatus.needReLogin) {
  872. // Cookie 无效
  873. return { success: false, message: '登录状态无效或已过期' };
  874. }
  875. return { success: false, message: '无法验证登录状态,请稍后重试' };
  876. } catch (error) {
  877. logger.error(`Failed to verify cookie for ${platform}:`, error);
  878. return {
  879. success: false,
  880. message: error instanceof Error ? error.message : '验证失败'
  881. };
  882. }
  883. }
  884. /**
  885. * 将 cookie 字符串解析为 cookie 列表
  886. */
  887. private parseCookieString(cookieString: string, platform: PlatformType): {
  888. name: string;
  889. value: string;
  890. domain: string;
  891. path: string;
  892. }[] {
  893. // 获取平台对应的域名
  894. const domainMap: Record<string, string> = {
  895. douyin: '.douyin.com',
  896. kuaishou: '.kuaishou.com',
  897. xiaohongshu: '.xiaohongshu.com',
  898. weixin_video: '.qq.com',
  899. bilibili: '.bilibili.com',
  900. toutiao: '.toutiao.com',
  901. baijiahao: '.baidu.com',
  902. qie: '.qq.com',
  903. dayuhao: '.alibaba.com',
  904. };
  905. const domain = domainMap[platform] || `.${platform}.com`;
  906. // 解析 "name=value; name2=value2" 格式的 cookie 字符串
  907. const cookies: { name: string; value: string; domain: string; path: string }[] = [];
  908. const pairs = cookieString.split(';');
  909. for (const pair of pairs) {
  910. const trimmed = pair.trim();
  911. if (!trimmed) continue;
  912. const eqIndex = trimmed.indexOf('=');
  913. if (eqIndex === -1) continue;
  914. const name = trimmed.substring(0, eqIndex).trim();
  915. const value = trimmed.substring(eqIndex + 1).trim();
  916. if (name && value) {
  917. cookies.push({
  918. name,
  919. value,
  920. domain,
  921. path: '/',
  922. });
  923. }
  924. }
  925. return cookies;
  926. }
  927. private formatGroup(group: AccountGroup): AccountGroupType {
  928. return {
  929. id: group.id,
  930. userId: group.userId,
  931. name: group.name,
  932. description: group.description,
  933. createdAt: group.createdAt.toISOString(),
  934. };
  935. }
  936. private formatAccount(account: PlatformAccount): PlatformAccountType {
  937. return {
  938. id: account.id,
  939. userId: account.userId,
  940. platform: account.platform,
  941. accountName: account.accountName || '',
  942. accountId: account.accountId || '',
  943. avatarUrl: account.avatarUrl,
  944. fansCount: account.fansCount,
  945. worksCount: account.worksCount,
  946. status: account.status,
  947. proxyConfig: account.proxyConfig,
  948. groupId: account.groupId,
  949. cookieExpireAt: account.cookieExpireAt?.toISOString() || null,
  950. createdAt: account.createdAt.toISOString(),
  951. updatedAt: account.updatedAt.toISOString(),
  952. };
  953. }
  954. /**
  955. * 从 Cookie 中提取账号 ID(最可靠的方式)
  956. * 不同平台使用不同的 Cookie 字段来标识用户
  957. */
  958. private extractAccountIdFromCookie(platform: PlatformType, cookieString: string): string | null {
  959. // 各平台用于标识用户的 Cookie 名称(按优先级排序)
  960. const platformCookieNames: Record<string, string[]> = {
  961. douyin: ['passport_uid', 'uid_tt', 'ttwid', 'sessionid_ss'],
  962. kuaishou: ['userId', 'passToken', 'did'],
  963. xiaohongshu: ['customerClientId', 'web_session', 'xsecappid'],
  964. weixin_video: ['wxuin', 'pass_ticket', 'uin'],
  965. bilibili: ['DedeUserID', 'SESSDATA', 'bili_jct'],
  966. toutiao: ['sso_uid', 'sessionid', 'passport_uid'],
  967. baijiahao: ['BDUSS', 'STOKEN', 'BAIDUID'],
  968. qie: ['uin', 'skey', 'p_uin'],
  969. dayuhao: ['login_aliyunid', 'cna', 'munb'],
  970. };
  971. const targetCookieNames = platformCookieNames[platform] || [];
  972. if (targetCookieNames.length === 0) {
  973. return null;
  974. }
  975. try {
  976. // 尝试解析 JSON 格式的 Cookie
  977. let cookieList: { name: string; value: string }[];
  978. try {
  979. cookieList = JSON.parse(cookieString);
  980. } catch {
  981. // 如果不是 JSON,尝试解析 "name=value; name2=value2" 格式
  982. cookieList = this.parseCookieString(cookieString, platform).map(c => ({
  983. name: c.name,
  984. value: c.value,
  985. }));
  986. }
  987. if (!Array.isArray(cookieList) || cookieList.length === 0) {
  988. return null;
  989. }
  990. // 按优先级查找 Cookie
  991. for (const cookieName of targetCookieNames) {
  992. const cookie = cookieList.find(c => c.name === cookieName);
  993. if (cookie?.value) {
  994. // 获取 Cookie 值,处理可能的编码
  995. let cookieValue = cookie.value;
  996. // 处理特殊格式的 Cookie(如 ttwid 可能包含分隔符)
  997. if (cookieValue.includes('|')) {
  998. cookieValue = cookieValue.split('|')[1] || cookieValue;
  999. }
  1000. if (cookieValue.includes('%')) {
  1001. try {
  1002. cookieValue = decodeURIComponent(cookieValue);
  1003. } catch {
  1004. // 解码失败,使用原值
  1005. }
  1006. }
  1007. // 截取合理长度(避免过长的 ID)
  1008. if (cookieValue.length > 64) {
  1009. cookieValue = cookieValue.slice(0, 64);
  1010. }
  1011. const accountId = `${platform}_${cookieValue}`;
  1012. logger.info(`[extractAccountIdFromCookie] Found ${cookieName} for ${platform}: ${accountId}`);
  1013. return accountId;
  1014. }
  1015. }
  1016. return null;
  1017. } catch (error) {
  1018. logger.warn(`[extractAccountIdFromCookie] Failed to extract accountId from cookie for ${platform}:`, error);
  1019. return null;
  1020. }
  1021. }
  1022. /**
  1023. * 平台短前缀映射(统一使用短前缀)
  1024. */
  1025. private static readonly SHORT_PREFIX_MAP: Record<PlatformType, string> = {
  1026. 'douyin': 'dy_',
  1027. 'xiaohongshu': 'xhs_',
  1028. 'weixin_video': 'sph_',
  1029. 'baijiahao': 'bjh_',
  1030. 'kuaishou': 'ks_',
  1031. 'bilibili': 'bili_',
  1032. 'toutiao': 'tt_',
  1033. 'qie': 'qie_',
  1034. 'dayuhao': 'dyh_',
  1035. };
  1036. /**
  1037. * 标准化 accountId 格式,统一使用短前缀
  1038. * 例如:Ethanfly9392 -> dy_Ethanfly9392
  1039. */
  1040. private normalizeAccountId(platform: PlatformType, accountId: string): string {
  1041. const shortPrefix = AccountService.SHORT_PREFIX_MAP[platform] || `${platform}_`;
  1042. if (!accountId) {
  1043. return `${shortPrefix}${Date.now()}`;
  1044. }
  1045. // 如果已经有正确的短前缀,直接返回
  1046. if (accountId.startsWith(shortPrefix)) {
  1047. return accountId;
  1048. }
  1049. // 移除任何已有的前缀(短前缀或完整前缀)
  1050. const allShortPrefixes = Object.values(AccountService.SHORT_PREFIX_MAP);
  1051. const allFullPrefixes = Object.keys(AccountService.SHORT_PREFIX_MAP).map(p => `${p}_`);
  1052. const allPrefixes = [...allShortPrefixes, ...allFullPrefixes];
  1053. let cleanId = accountId;
  1054. for (const prefix of allPrefixes) {
  1055. if (cleanId.startsWith(prefix)) {
  1056. cleanId = cleanId.slice(prefix.length);
  1057. break;
  1058. }
  1059. }
  1060. // 添加正确的短前缀
  1061. return `${shortPrefix}${cleanId}`;
  1062. }
  1063. /**
  1064. * 检查 accountId 是否是基于时间戳生成的(不可靠的 ID)
  1065. * 时间戳 ID 格式通常是:dy_1737619200000 或 douyin_1737619200000
  1066. */
  1067. private isTimestampBasedId(accountId: string): boolean {
  1068. if (!accountId) return true;
  1069. // 检查是否匹配 前缀_时间戳 格式(支持短前缀和完整前缀)
  1070. const timestampPattern = /^[a-z_]+_(\d{13,})$/;
  1071. const match = accountId.match(timestampPattern);
  1072. if (!match) {
  1073. return false;
  1074. }
  1075. // 提取数字部分,检查是否是合理的时间戳(2020年到2030年之间)
  1076. if (match[1]) {
  1077. const timestamp = parseInt(match[1]);
  1078. const minTimestamp = new Date('2020-01-01').getTime(); // 1577836800000
  1079. const maxTimestamp = new Date('2030-01-01').getTime(); // 1893456000000
  1080. if (timestamp >= minTimestamp && timestamp <= maxTimestamp) {
  1081. logger.info(`[isTimestampBasedId] Detected timestamp-based ID: ${accountId}`);
  1082. return true;
  1083. }
  1084. }
  1085. return false;
  1086. }
  1087. }