AccountService.ts 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. // 记录关键 Cookie(用于调试)
  134. const keyNames = parsed.slice(0, 3).map((c: any) => c.name).join(', ');
  135. logger.info(`[AccountService] 关键 Cookie: ${keyNames}`);
  136. }
  137. } catch {
  138. logger.warn(`[AccountService] Cookie 不是 JSON 格式,可能是字符串格式`);
  139. }
  140. return decryptedCookies;
  141. }
  142. async addAccount(userId: number, data: AddPlatformAccountRequest & {
  143. accountInfo?: {
  144. accountId?: string;
  145. accountName?: string;
  146. avatarUrl?: string;
  147. fansCount?: number;
  148. worksCount?: number;
  149. };
  150. }): Promise<PlatformAccountType> {
  151. const platform = data.platform as PlatformType;
  152. // 解密 Cookie(如果是加密的)
  153. let cookieData = data.cookieData;
  154. let decryptedCookies: string;
  155. try {
  156. // 尝试解密(如果是通过浏览器登录获取的加密Cookie)
  157. decryptedCookies = CookieManager.decrypt(cookieData);
  158. } catch {
  159. // 如果解密失败,可能是直接粘贴的Cookie字符串
  160. decryptedCookies = cookieData;
  161. }
  162. // 检查客户端传入的 accountId 是否有效(不是纯时间戳)
  163. const clientAccountId = data.accountInfo?.accountId;
  164. const isValidClientAccountId = clientAccountId && !this.isTimestampBasedId(clientAccountId);
  165. // 从 Cookie 中提取账号 ID(部分平台的 Cookie 包含真实用户 ID)
  166. const accountIdFromCookie = this.extractAccountIdFromCookie(platform, decryptedCookies);
  167. // 某些平台应优先使用 API 返回的真实 ID,而不是 Cookie 中的值
  168. // - 抖音:使用抖音号(unique_id,如 Ethanfly9392),而不是 Cookie 中的 passport_uid
  169. // - 小红书:使用小红书号(red_num),而不是 Cookie 中的 userid
  170. // - 百家号:使用 new_uc_id,而不是 Cookie 中的 BDUSS
  171. // - 视频号/头条:使用 API 返回的真实账号 ID
  172. const platformsPreferApiId: PlatformType[] = ['douyin', 'xiaohongshu', 'baijiahao', 'weixin_video', 'toutiao'];
  173. const preferApiId = platformsPreferApiId.includes(platform);
  174. // 确定最终的 accountId
  175. let finalAccountId: string;
  176. if (preferApiId && isValidClientAccountId) {
  177. // 对于优先使用 API ID 的平台,先用客户端传入的有效 ID
  178. finalAccountId = this.normalizeAccountId(platform, clientAccountId);
  179. logger.info(`[addAccount] Using API-based accountId for ${platform}: ${finalAccountId}`);
  180. } else if (accountIdFromCookie) {
  181. // 其他平台优先使用 Cookie 中提取的 ID
  182. finalAccountId = accountIdFromCookie;
  183. logger.info(`[addAccount] Using accountId from cookie: ${finalAccountId}`);
  184. } else if (isValidClientAccountId) {
  185. // 再次尝试客户端 ID
  186. finalAccountId = this.normalizeAccountId(platform, clientAccountId);
  187. logger.info(`[addAccount] Using valid client accountId: ${finalAccountId}`);
  188. } else {
  189. finalAccountId = `${platform}_${Date.now()}`;
  190. logger.warn(`[addAccount] Using timestamp-based accountId as fallback: ${finalAccountId}`);
  191. }
  192. // 使用传入的账号信息(来自浏览器登录会话),或使用默认值
  193. const accountInfo = {
  194. accountId: finalAccountId,
  195. accountName: data.accountInfo?.accountName || `${platform}账号`,
  196. avatarUrl: data.accountInfo?.avatarUrl || null,
  197. fansCount: data.accountInfo?.fansCount || 0,
  198. worksCount: data.accountInfo?.worksCount || 0,
  199. };
  200. logger.info(`Adding account for ${platform}: ${accountInfo.accountId}, name: ${accountInfo.accountName}`);
  201. // 检查是否已存在相同账号
  202. const existing = await this.accountRepository.findOne({
  203. where: { userId, platform, accountId: accountInfo.accountId },
  204. });
  205. if (existing) {
  206. // 更新已存在的账号
  207. await this.accountRepository.update(existing.id, {
  208. cookieData: cookieData, // 存储原始数据(可能是加密的)
  209. accountName: accountInfo.accountName,
  210. avatarUrl: accountInfo.avatarUrl,
  211. fansCount: accountInfo.fansCount,
  212. worksCount: accountInfo.worksCount,
  213. status: 'active',
  214. groupId: data.groupId || existing.groupId,
  215. proxyConfig: data.proxyConfig || existing.proxyConfig,
  216. });
  217. const updated = await this.accountRepository.findOne({ where: { id: existing.id } });
  218. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  219. // 异步刷新账号信息(获取准确的粉丝数、作品数等)
  220. this.refreshAccountAsync(userId, existing.id, platform).catch(err => {
  221. logger.warn(`[addAccount] Background refresh failed for existing account ${existing.id}:`, err);
  222. });
  223. return this.formatAccount(updated!);
  224. }
  225. // 创建新账号
  226. const account = this.accountRepository.create({
  227. userId,
  228. platform,
  229. cookieData: cookieData,
  230. groupId: data.groupId || null,
  231. proxyConfig: data.proxyConfig || null,
  232. status: 'active',
  233. accountId: accountInfo.accountId,
  234. accountName: accountInfo.accountName,
  235. avatarUrl: accountInfo.avatarUrl,
  236. fansCount: accountInfo.fansCount,
  237. worksCount: accountInfo.worksCount,
  238. });
  239. await this.accountRepository.save(account);
  240. // 通知其他客户端
  241. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_ADDED, { account: this.formatAccount(account) });
  242. // 异步刷新账号信息(获取准确的粉丝数、作品数等)
  243. // 不阻塞返回,后台执行
  244. this.refreshAccountAsync(userId, account.id, platform).catch(err => {
  245. logger.warn(`[addAccount] Background refresh failed for account ${account.id}:`, err);
  246. });
  247. // 新增账号后,按平台触发一次“近30天数据同步”,用于初始化 user_day_statistics
  248. this.initStatisticsForNewAccountAsync(account).catch(err => {
  249. logger.warn(
  250. `[addAccount] Initial statistics sync failed for account ${account.id} (${platform}):`,
  251. err
  252. );
  253. });
  254. return this.formatAccount(account);
  255. }
  256. /**
  257. * 异步刷新账号信息(用于添加账号后获取准确数据)
  258. */
  259. private async refreshAccountAsync(userId: number, accountId: number, platform: PlatformType): Promise<void> {
  260. // 延迟 2 秒执行,等待前端处理完成
  261. await new Promise(resolve => setTimeout(resolve, 2000));
  262. logger.info(`[addAccount] Starting background refresh for account ${accountId} (${platform})`);
  263. try {
  264. await this.refreshAccount(userId, accountId);
  265. logger.info(`[addAccount] Background refresh completed for account ${accountId}`);
  266. } catch (error) {
  267. logger.warn(`[addAccount] Background refresh failed for account ${accountId}:`, error);
  268. }
  269. }
  270. /**
  271. * 新增账号后,按平台触发一次“近30天数据同步”,用于初始化 user_day_statistics
  272. * 仿照定时任务里跑的导入服务,但只针对当前账号
  273. */
  274. private async initStatisticsForNewAccountAsync(account: PlatformAccount): Promise<void> {
  275. const platform = account.platform as PlatformType;
  276. // 延迟几秒,避免和前端后续操作/账号刷新抢占浏览器资源
  277. await new Promise((resolve) => setTimeout(resolve, 3000));
  278. logger.info(
  279. `[addAccount] Starting initial statistics import for account ${account.id} (${platform})`
  280. );
  281. try {
  282. if (platform === 'xiaohongshu') {
  283. const svc = new XiaohongshuAccountOverviewImportService();
  284. await svc.importAccountLast30Days(account);
  285. } else if (platform === 'douyin') {
  286. const svc = new DouyinAccountOverviewImportService();
  287. await svc.importAccountLast30Days(account);
  288. } else if (platform === 'baijiahao') {
  289. const svc = new BaijiahaoContentOverviewImportService();
  290. await svc.importAccountLast30Days(account);
  291. } else if (platform === 'weixin_video') {
  292. const svc = new WeixinVideoDataCenterImportService();
  293. await svc.importAccountLast30Days(account);
  294. } else {
  295. logger.info(
  296. `[addAccount] Initial statistics import skipped for unsupported platform ${platform}`
  297. );
  298. return;
  299. }
  300. logger.info(
  301. `[addAccount] Initial statistics import completed for account ${account.id} (${platform})`
  302. );
  303. } catch (error) {
  304. logger.warn(
  305. `[addAccount] Initial statistics import encountered error for account ${account.id} (${platform}):`,
  306. error
  307. );
  308. // 出错时不抛出,让前端添加账号流程不受影响
  309. }
  310. }
  311. async updateAccount(
  312. userId: number,
  313. accountId: number,
  314. data: UpdatePlatformAccountRequest
  315. ): Promise<PlatformAccountType> {
  316. const account = await this.accountRepository.findOne({
  317. where: { id: accountId, userId },
  318. });
  319. if (!account) {
  320. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  321. }
  322. await this.accountRepository.update(accountId, {
  323. groupId: data.groupId !== undefined ? data.groupId : account.groupId,
  324. proxyConfig: data.proxyConfig !== undefined ? data.proxyConfig : account.proxyConfig,
  325. status: data.status ?? account.status,
  326. });
  327. const updated = await this.accountRepository.findOne({ where: { id: accountId } });
  328. // 通知其他客户端
  329. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  330. return this.formatAccount(updated!);
  331. }
  332. async deleteAccount(userId: number, accountId: number): Promise<void> {
  333. const account = await this.accountRepository.findOne({
  334. where: { id: accountId, userId },
  335. });
  336. if (!account) {
  337. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  338. }
  339. await this.accountRepository.delete(accountId);
  340. // 通知其他客户端
  341. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_DELETED, { accountId });
  342. }
  343. async refreshAccount(userId: number, accountId: number): Promise<PlatformAccountType & { needReLogin?: boolean }> {
  344. const account = await this.accountRepository.findOne({
  345. where: { id: accountId, userId },
  346. });
  347. if (!account) {
  348. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  349. }
  350. const platform = account.platform as PlatformType;
  351. const updateData: Partial<PlatformAccount> = {
  352. updatedAt: new Date(),
  353. };
  354. let needReLogin = false;
  355. let aiRefreshSuccess = false;
  356. // 尝试通过无头浏览器刷新账号信息
  357. if (account.cookieData) {
  358. try {
  359. // 解密 Cookie
  360. let decryptedCookies: string;
  361. try {
  362. decryptedCookies = CookieManager.decrypt(account.cookieData);
  363. } catch {
  364. decryptedCookies = account.cookieData;
  365. }
  366. // 解析 Cookie - 支持两种格式
  367. let cookieList: { name: string; value: string; domain: string; path: string }[];
  368. let cookieParseError = false;
  369. try {
  370. // 先尝试 JSON 格式
  371. cookieList = JSON.parse(decryptedCookies);
  372. } catch {
  373. // 如果 JSON 解析失败,尝试解析 "name=value; name2=value2" 格式
  374. cookieList = this.parseCookieString(decryptedCookies, platform);
  375. if (cookieList.length === 0) {
  376. logger.error(`Invalid cookie format for account ${accountId}`);
  377. cookieParseError = true;
  378. }
  379. }
  380. if (cookieList.length > 0 && !cookieParseError) {
  381. // 抖音、小红书、百家号直接使用 API 获取准确数据,不使用 AI(因为 AI 可能识别错误)
  382. // 但是如果 API 调用失败,作为备用方案仍会尝试 AI
  383. const platformsSkipAI: PlatformType[] = ['douyin', 'xiaohongshu', 'baijiahao'];
  384. const shouldUseAI = aiService.isAvailable() && !platformsSkipAI.includes(platform);
  385. logger.info(`[refreshAccount] Platform: ${platform}, shouldUseAI: ${shouldUseAI}, aiAvailable: ${aiService.isAvailable()}`);
  386. // ========== AI 辅助刷新(部分平台使用) ==========
  387. if (shouldUseAI) {
  388. try {
  389. logger.info(`[AI Refresh] Starting AI-assisted refresh for account ${accountId} (${platform})`);
  390. // 使用无头浏览器截图,然后 AI 分析
  391. const aiResult = await this.refreshAccountWithAI(platform, cookieList, accountId);
  392. if (aiResult.needReLogin) {
  393. // AI 检测到需要重新登录
  394. updateData.status = 'expired';
  395. needReLogin = true;
  396. aiRefreshSuccess = true;
  397. logger.warn(`[AI Refresh] Account ${accountId} needs re-login (detected by AI)`);
  398. } else if (aiResult.accountInfo) {
  399. // AI 成功获取到账号信息
  400. updateData.status = 'active';
  401. updateData.accountName = aiResult.accountInfo.accountName;
  402. if (aiResult.accountInfo.avatarUrl) {
  403. updateData.avatarUrl = aiResult.accountInfo.avatarUrl;
  404. }
  405. if (aiResult.accountInfo.fansCount !== undefined) {
  406. updateData.fansCount = aiResult.accountInfo.fansCount;
  407. }
  408. if (aiResult.accountInfo.worksCount !== undefined) {
  409. updateData.worksCount = aiResult.accountInfo.worksCount;
  410. }
  411. aiRefreshSuccess = true;
  412. logger.info(`[AI Refresh] Successfully refreshed account ${accountId}: ${aiResult.accountInfo.accountName}`);
  413. }
  414. } catch (aiError) {
  415. logger.warn(`[AI Refresh] AI-assisted refresh failed for account ${accountId}:`, aiError);
  416. // AI 刷新失败,继续使用原有逻辑
  417. }
  418. }
  419. // ========== 原有逻辑(AI 失败时的备用方案) ==========
  420. if (!aiRefreshSuccess) {
  421. // 第一步:通过浏览器检查 Cookie 是否有效
  422. const isValid = await headlessBrowserService.checkCookieValid(platform, cookieList);
  423. if (!isValid) {
  424. // Cookie 已过期,需要重新登录
  425. updateData.status = 'expired';
  426. needReLogin = true;
  427. logger.warn(`Account ${accountId} (${account.accountName}) cookie expired, need re-login`);
  428. } else {
  429. // Cookie 有效,尝试获取账号信息
  430. updateData.status = 'active';
  431. try {
  432. const profile = await headlessBrowserService.fetchAccountInfo(platform, cookieList);
  433. // 检查是否获取到有效信息(排除默认名称)
  434. const defaultNames = [
  435. `${platform}账号`, '未知账号', '抖音账号', '小红书账号',
  436. '快手账号', '视频号账号', 'B站账号', '头条账号', '百家号账号'
  437. ];
  438. const isValidProfile = profile.accountName && !defaultNames.includes(profile.accountName);
  439. if (isValidProfile) {
  440. updateData.accountName = profile.accountName;
  441. updateData.avatarUrl = profile.avatarUrl;
  442. // 仅在粉丝数有效时更新(避免因获取失败导致的归零)
  443. if (profile.fansCount !== undefined) {
  444. // 如果新粉丝数为 0,但原粉丝数 > 0,可能是获取失败,记录警告并跳过更新
  445. if (profile.fansCount === 0 && (account.fansCount || 0) > 0) {
  446. logger.warn(`[refreshAccount] Fans count dropped to 0 for ${accountId} (was ${account.fansCount}). Ignoring potential fetch error.`);
  447. } else {
  448. updateData.fansCount = profile.fansCount;
  449. }
  450. }
  451. if (profile.worksCount === 0 && (account.worksCount || 0) > 0) {
  452. logger.warn(`[refreshAccount] Works count dropped to 0 for ${accountId} (was ${account.worksCount}). Ignoring potential fetch error.`);
  453. } else {
  454. updateData.worksCount = profile.worksCount;
  455. }
  456. // 如果获取到了有效的 accountId(如抖音号),也更新它
  457. // 这样可以修正之前使用错误 ID(如 Cookie 值)保存的账号
  458. if (profile.accountId && !this.isTimestampBasedId(profile.accountId)) {
  459. const newAccountId = this.normalizeAccountId(platform, profile.accountId);
  460. // 只有当新 ID 与旧 ID 不同时才更新
  461. if (newAccountId !== account.accountId) {
  462. updateData.accountId = newAccountId;
  463. logger.info(`[refreshAccount] Updating accountId from ${account.accountId} to ${newAccountId}`);
  464. }
  465. }
  466. logger.info(`Refreshed account info for ${platform}: ${profile.accountName}, fans: ${profile.fansCount}, works: ${profile.worksCount}`);
  467. } else {
  468. // 获取的信息无效,但 Cookie 有效,保持 active 状态
  469. logger.warn(`Could not fetch valid account info for ${accountId}, but cookie is valid`);
  470. }
  471. } catch (infoError) {
  472. // 获取账号信息失败,但 Cookie 检查已通过,保持 active 状态
  473. logger.warn(`Failed to fetch account info for ${accountId}, but cookie is valid:`, infoError);
  474. // 对于百家号,如果是获取信息失败,可能是分散认证问题,不需要立即标记为失败
  475. if (platform === 'baijiahao') {
  476. logger.info(`[baijiahao] Account info fetch failed for ${accountId}, but this might be due to distributed auth. Keeping status active.`);
  477. }
  478. }
  479. }
  480. }
  481. }
  482. // Cookie 解析失败时,不改变状态
  483. } catch (error) {
  484. logger.error(`Failed to refresh account ${accountId}:`, error);
  485. // 不抛出错误,不改变状态,只更新时间戳
  486. }
  487. }
  488. // 没有 Cookie 数据时,不改变状态
  489. await this.accountRepository.update(accountId, updateData);
  490. const updated = await this.accountRepository.findOne({ where: { id: accountId } });
  491. // 保存账号每日统计数据(粉丝数、作品数)
  492. // 无论是否更新了粉丝数/作品数,都要保存当前值到统计表,确保每天都有记录
  493. if (updated) {
  494. try {
  495. const userDayStatisticsService = new UserDayStatisticsService();
  496. await userDayStatisticsService.saveStatistics({
  497. accountId,
  498. fansCount: updated.fansCount || 0,
  499. worksCount: updated.worksCount || 0,
  500. });
  501. logger.debug(`[AccountService] Saved account day statistics for account ${accountId} (fans: ${updated.fansCount || 0}, works: ${updated.worksCount || 0})`);
  502. } catch (error) {
  503. logger.error(`[AccountService] Failed to save account day statistics for account ${accountId}:`, error);
  504. // 不抛出错误,不影响主流程
  505. }
  506. }
  507. // 通知其他客户端
  508. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, { account: this.formatAccount(updated!) });
  509. return { ...this.formatAccount(updated!), needReLogin };
  510. }
  511. /**
  512. * 使用 AI 辅助刷新账号信息
  513. */
  514. private async refreshAccountWithAI(
  515. platform: PlatformType,
  516. cookieList: { name: string; value: string; domain: string; path: string }[],
  517. accountId: number
  518. ): Promise<{
  519. needReLogin: boolean;
  520. accountInfo?: {
  521. accountName: string;
  522. avatarUrl?: string;
  523. fansCount?: number;
  524. worksCount?: number;
  525. };
  526. }> {
  527. // 使用无头浏览器访问平台后台并截图
  528. const screenshot = await headlessBrowserService.capturePageScreenshot(platform, cookieList);
  529. if (!screenshot) {
  530. throw new Error('Failed to capture screenshot');
  531. }
  532. // 第一步:使用 AI 分析登录状态
  533. const loginStatus = await aiService.analyzeLoginStatus(screenshot, platform);
  534. logger.info(`[AI Refresh] Login status for account ${accountId}:`, {
  535. isLoggedIn: loginStatus.isLoggedIn,
  536. hasVerification: loginStatus.hasVerification,
  537. });
  538. // 如果 AI 检测到未登录或有验证码,说明需要重新登录
  539. if (!loginStatus.isLoggedIn || loginStatus.hasVerification) {
  540. return { needReLogin: true };
  541. }
  542. // 第二步:使用 AI 提取账号信息
  543. const accountInfo = await aiService.extractAccountInfo(screenshot, platform);
  544. logger.info(`[AI Refresh] Account info extraction for ${accountId}:`, {
  545. found: accountInfo.found,
  546. accountName: accountInfo.accountName,
  547. });
  548. if (accountInfo.found && accountInfo.accountName) {
  549. return {
  550. needReLogin: false,
  551. accountInfo: {
  552. accountName: accountInfo.accountName,
  553. fansCount: accountInfo.fansCount ? parseInt(String(accountInfo.fansCount)) : undefined,
  554. worksCount: accountInfo.worksCount ? parseInt(String(accountInfo.worksCount)) : undefined,
  555. },
  556. };
  557. }
  558. // AI 未能提取到账号信息,但登录状态正常
  559. // 返回空结果,让原有逻辑处理
  560. return { needReLogin: false };
  561. }
  562. /**
  563. * 检查账号 Cookie 是否有效
  564. */
  565. async checkAccountStatus(userId: number, accountId: number): Promise<{ isValid: boolean }> {
  566. const account = await this.accountRepository.findOne({
  567. where: { id: accountId, userId },
  568. });
  569. if (!account) {
  570. throw new AppError('账号不存在', HTTP_STATUS.NOT_FOUND, ERROR_CODES.ACCOUNT_NOT_FOUND);
  571. }
  572. if (!account.cookieData) {
  573. // 更新状态为过期
  574. await this.accountRepository.update(accountId, { status: 'expired' });
  575. return { isValid: false };
  576. }
  577. const platform = account.platform as PlatformType;
  578. try {
  579. // 解密 Cookie
  580. let decryptedCookies: string;
  581. try {
  582. decryptedCookies = CookieManager.decrypt(account.cookieData);
  583. } catch {
  584. decryptedCookies = account.cookieData;
  585. }
  586. // 解析 Cookie - 支持两种格式
  587. let cookieList: { name: string; value: string; domain: string; path: string }[];
  588. try {
  589. // 先尝试 JSON 格式
  590. cookieList = JSON.parse(decryptedCookies);
  591. } catch {
  592. // 如果 JSON 解析失败,尝试解析 "name=value; name2=value2" 格式
  593. cookieList = this.parseCookieString(decryptedCookies, platform);
  594. if (cookieList.length === 0) {
  595. await this.accountRepository.update(accountId, { status: 'expired' });
  596. return { isValid: false };
  597. }
  598. }
  599. // 使用 API 检查 Cookie 是否有效
  600. const isValid = await headlessBrowserService.checkCookieValid(platform, cookieList);
  601. // 更新账号状态
  602. if (!isValid) {
  603. await this.accountRepository.update(accountId, { status: 'expired' });
  604. wsManager.sendToUser(userId, WS_EVENTS.ACCOUNT_UPDATED, {
  605. account: { ...this.formatAccount(account), status: 'expired' }
  606. });
  607. } else if (account.status === 'expired') {
  608. // 如果之前是过期状态但现在有效了,更新为正常
  609. await this.accountRepository.update(accountId, { status: 'active' });
  610. }
  611. return { isValid };
  612. } catch (error) {
  613. logger.error(`Failed to check account status ${accountId}:`, error);
  614. return { isValid: false };
  615. }
  616. }
  617. /**
  618. * 批量刷新所有账号状态
  619. */
  620. async refreshAllAccounts(userId: number): Promise<{ refreshed: number; failed: number }> {
  621. const accounts = await this.accountRepository.find({
  622. where: { userId },
  623. });
  624. let refreshed = 0;
  625. let failed = 0;
  626. for (const account of accounts) {
  627. try {
  628. await this.refreshAccount(userId, account.id);
  629. refreshed++;
  630. } catch (error) {
  631. logger.error(`Failed to refresh account ${account.id}:`, error);
  632. failed++;
  633. }
  634. }
  635. logger.info(`Refreshed ${refreshed} accounts for user ${userId}, ${failed} failed`);
  636. return { refreshed, failed };
  637. }
  638. async getQRCode(platform: string): Promise<QRCodeInfo> {
  639. // TODO: 调用对应平台适配器获取二维码
  640. // 这里返回模拟数据
  641. return {
  642. qrcodeUrl: `https://example.com/qrcode/${platform}/${Date.now()}`,
  643. qrcodeKey: `qr_${platform}_${Date.now()}`,
  644. expireTime: Date.now() + 300000, // 5分钟后过期
  645. };
  646. }
  647. async checkQRCodeStatus(platform: string, qrcodeKey: string): Promise<LoginStatusResult> {
  648. // TODO: 调用对应平台适配器检查扫码状态
  649. // 这里返回模拟数据
  650. return {
  651. status: 'waiting',
  652. message: '等待扫码',
  653. };
  654. }
  655. /**
  656. * 验证 Cookie 并获取账号信息(用于 Electron 内嵌浏览器登录)
  657. */
  658. async verifyCookieAndGetInfo(platform: PlatformType, cookieData: string): Promise<{
  659. success: boolean;
  660. message?: string;
  661. accountInfo?: {
  662. accountId: string;
  663. accountName: string;
  664. avatarUrl: string;
  665. fansCount: number;
  666. worksCount: number;
  667. };
  668. }> {
  669. try {
  670. // 将 cookie 字符串转换为 cookie 列表格式
  671. const cookieList = this.parseCookieString(cookieData, platform);
  672. if (cookieList.length === 0) {
  673. return { success: false, message: 'Cookie 格式无效' };
  674. }
  675. // 先尝试获取账号信息(可以同时验证登录状态)
  676. // 如果能成功获取到有效信息,说明登录是有效的
  677. try {
  678. const profile = await headlessBrowserService.fetchAccountInfo(platform, cookieList);
  679. // 检查是否获取到有效信息(排除默认名称)
  680. const defaultNames = [
  681. `${platform}账号`, '未知账号', '抖音账号', '小红书账号',
  682. '快手账号', '视频号账号', 'B站账号', '头条账号', '百家号账号'
  683. ];
  684. const isValidProfile = profile.accountName && !defaultNames.includes(profile.accountName);
  685. if (isValidProfile) {
  686. return {
  687. success: true,
  688. accountInfo: {
  689. // 确保 accountId 带有平台前缀
  690. accountId: this.normalizeAccountId(platform, profile.accountId || ''),
  691. accountName: profile.accountName,
  692. avatarUrl: profile.avatarUrl || '',
  693. fansCount: profile.fansCount || 0,
  694. worksCount: profile.worksCount || 0,
  695. },
  696. };
  697. }
  698. // 未能获取有效信息,再验证 Cookie 是否有效
  699. logger.info(`[verifyCookieAndGetInfo] Could not get valid profile for ${platform}, checking cookie validity...`);
  700. } catch (infoError) {
  701. logger.warn(`Failed to fetch account info for ${platform}:`, infoError);
  702. }
  703. // 账号信息获取失败或无效,检查 Cookie 是否有效
  704. const isValid = await headlessBrowserService.checkCookieValid(platform, cookieList);
  705. if (isValid) {
  706. // Cookie 有效但未能获取账号信息,返回基本成功
  707. return {
  708. success: true,
  709. message: '登录成功,但无法获取详细信息',
  710. accountInfo: {
  711. accountId: `${platform}_${Date.now()}`,
  712. accountName: `${platform}账号`,
  713. avatarUrl: '',
  714. fansCount: 0,
  715. worksCount: 0,
  716. },
  717. };
  718. } else {
  719. // Cookie 无效
  720. return { success: false, message: '登录状态无效或已过期' };
  721. }
  722. } catch (error) {
  723. logger.error(`Failed to verify cookie for ${platform}:`, error);
  724. return {
  725. success: false,
  726. message: error instanceof Error ? error.message : '验证失败'
  727. };
  728. }
  729. }
  730. /**
  731. * 将 cookie 字符串解析为 cookie 列表
  732. */
  733. private parseCookieString(cookieString: string, platform: PlatformType): {
  734. name: string;
  735. value: string;
  736. domain: string;
  737. path: string;
  738. }[] {
  739. // 获取平台对应的域名
  740. const domainMap: Record<string, string> = {
  741. douyin: '.douyin.com',
  742. kuaishou: '.kuaishou.com',
  743. xiaohongshu: '.xiaohongshu.com',
  744. weixin_video: '.qq.com',
  745. bilibili: '.bilibili.com',
  746. toutiao: '.toutiao.com',
  747. baijiahao: '.baidu.com',
  748. qie: '.qq.com',
  749. dayuhao: '.alibaba.com',
  750. };
  751. const domain = domainMap[platform] || `.${platform}.com`;
  752. // 解析 "name=value; name2=value2" 格式的 cookie 字符串
  753. const cookies: { name: string; value: string; domain: string; path: string }[] = [];
  754. const pairs = cookieString.split(';');
  755. for (const pair of pairs) {
  756. const trimmed = pair.trim();
  757. if (!trimmed) continue;
  758. const eqIndex = trimmed.indexOf('=');
  759. if (eqIndex === -1) continue;
  760. const name = trimmed.substring(0, eqIndex).trim();
  761. const value = trimmed.substring(eqIndex + 1).trim();
  762. if (name && value) {
  763. cookies.push({
  764. name,
  765. value,
  766. domain,
  767. path: '/',
  768. });
  769. }
  770. }
  771. return cookies;
  772. }
  773. private formatGroup(group: AccountGroup): AccountGroupType {
  774. return {
  775. id: group.id,
  776. userId: group.userId,
  777. name: group.name,
  778. description: group.description,
  779. createdAt: group.createdAt.toISOString(),
  780. };
  781. }
  782. private formatAccount(account: PlatformAccount): PlatformAccountType {
  783. return {
  784. id: account.id,
  785. userId: account.userId,
  786. platform: account.platform,
  787. accountName: account.accountName || '',
  788. accountId: account.accountId || '',
  789. avatarUrl: account.avatarUrl,
  790. fansCount: account.fansCount,
  791. worksCount: account.worksCount,
  792. status: account.status,
  793. proxyConfig: account.proxyConfig,
  794. groupId: account.groupId,
  795. cookieExpireAt: account.cookieExpireAt?.toISOString() || null,
  796. createdAt: account.createdAt.toISOString(),
  797. updatedAt: account.updatedAt.toISOString(),
  798. };
  799. }
  800. /**
  801. * 从 Cookie 中提取账号 ID(最可靠的方式)
  802. * 不同平台使用不同的 Cookie 字段来标识用户
  803. */
  804. private extractAccountIdFromCookie(platform: PlatformType, cookieString: string): string | null {
  805. // 各平台用于标识用户的 Cookie 名称(按优先级排序)
  806. const platformCookieNames: Record<string, string[]> = {
  807. douyin: ['passport_uid', 'uid_tt', 'ttwid', 'sessionid_ss'],
  808. kuaishou: ['userId', 'passToken', 'did'],
  809. xiaohongshu: ['customerClientId', 'web_session', 'xsecappid'],
  810. weixin_video: ['wxuin', 'pass_ticket', 'uin'],
  811. bilibili: ['DedeUserID', 'SESSDATA', 'bili_jct'],
  812. toutiao: ['sso_uid', 'sessionid', 'passport_uid'],
  813. baijiahao: ['BDUSS', 'STOKEN', 'BAIDUID'],
  814. qie: ['uin', 'skey', 'p_uin'],
  815. dayuhao: ['login_aliyunid', 'cna', 'munb'],
  816. };
  817. const targetCookieNames = platformCookieNames[platform] || [];
  818. if (targetCookieNames.length === 0) {
  819. return null;
  820. }
  821. try {
  822. // 尝试解析 JSON 格式的 Cookie
  823. let cookieList: { name: string; value: string }[];
  824. try {
  825. cookieList = JSON.parse(cookieString);
  826. } catch {
  827. // 如果不是 JSON,尝试解析 "name=value; name2=value2" 格式
  828. cookieList = this.parseCookieString(cookieString, platform).map(c => ({
  829. name: c.name,
  830. value: c.value,
  831. }));
  832. }
  833. if (!Array.isArray(cookieList) || cookieList.length === 0) {
  834. return null;
  835. }
  836. // 按优先级查找 Cookie
  837. for (const cookieName of targetCookieNames) {
  838. const cookie = cookieList.find(c => c.name === cookieName);
  839. if (cookie?.value) {
  840. // 获取 Cookie 值,处理可能的编码
  841. let cookieValue = cookie.value;
  842. // 处理特殊格式的 Cookie(如 ttwid 可能包含分隔符)
  843. if (cookieValue.includes('|')) {
  844. cookieValue = cookieValue.split('|')[1] || cookieValue;
  845. }
  846. if (cookieValue.includes('%')) {
  847. try {
  848. cookieValue = decodeURIComponent(cookieValue);
  849. } catch {
  850. // 解码失败,使用原值
  851. }
  852. }
  853. // 截取合理长度(避免过长的 ID)
  854. if (cookieValue.length > 64) {
  855. cookieValue = cookieValue.slice(0, 64);
  856. }
  857. const accountId = `${platform}_${cookieValue}`;
  858. logger.info(`[extractAccountIdFromCookie] Found ${cookieName} for ${platform}: ${accountId}`);
  859. return accountId;
  860. }
  861. }
  862. return null;
  863. } catch (error) {
  864. logger.warn(`[extractAccountIdFromCookie] Failed to extract accountId from cookie for ${platform}:`, error);
  865. return null;
  866. }
  867. }
  868. /**
  869. * 平台短前缀映射(统一使用短前缀)
  870. */
  871. private static readonly SHORT_PREFIX_MAP: Record<PlatformType, string> = {
  872. 'douyin': 'dy_',
  873. 'xiaohongshu': 'xhs_',
  874. 'weixin_video': 'sph_',
  875. 'baijiahao': 'bjh_',
  876. 'kuaishou': 'ks_',
  877. 'bilibili': 'bili_',
  878. 'toutiao': 'tt_',
  879. 'qie': 'qie_',
  880. 'dayuhao': 'dyh_',
  881. };
  882. /**
  883. * 标准化 accountId 格式,统一使用短前缀
  884. * 例如:Ethanfly9392 -> dy_Ethanfly9392
  885. */
  886. private normalizeAccountId(platform: PlatformType, accountId: string): string {
  887. const shortPrefix = AccountService.SHORT_PREFIX_MAP[platform] || `${platform}_`;
  888. if (!accountId) {
  889. return `${shortPrefix}${Date.now()}`;
  890. }
  891. // 如果已经有正确的短前缀,直接返回
  892. if (accountId.startsWith(shortPrefix)) {
  893. return accountId;
  894. }
  895. // 移除任何已有的前缀(短前缀或完整前缀)
  896. const allShortPrefixes = Object.values(AccountService.SHORT_PREFIX_MAP);
  897. const allFullPrefixes = Object.keys(AccountService.SHORT_PREFIX_MAP).map(p => `${p}_`);
  898. const allPrefixes = [...allShortPrefixes, ...allFullPrefixes];
  899. let cleanId = accountId;
  900. for (const prefix of allPrefixes) {
  901. if (cleanId.startsWith(prefix)) {
  902. cleanId = cleanId.slice(prefix.length);
  903. break;
  904. }
  905. }
  906. // 添加正确的短前缀
  907. return `${shortPrefix}${cleanId}`;
  908. }
  909. /**
  910. * 检查 accountId 是否是基于时间戳生成的(不可靠的 ID)
  911. * 时间戳 ID 格式通常是:dy_1737619200000 或 douyin_1737619200000
  912. */
  913. private isTimestampBasedId(accountId: string): boolean {
  914. if (!accountId) return true;
  915. // 检查是否匹配 前缀_时间戳 格式(支持短前缀和完整前缀)
  916. const timestampPattern = /^[a-z_]+_(\d{13,})$/;
  917. const match = accountId.match(timestampPattern);
  918. if (!match) {
  919. return false;
  920. }
  921. // 提取数字部分,检查是否是合理的时间戳(2020年到2030年之间)
  922. if (match[1]) {
  923. const timestamp = parseInt(match[1]);
  924. const minTimestamp = new Date('2020-01-01').getTime(); // 1577836800000
  925. const maxTimestamp = new Date('2030-01-01').getTime(); // 1893456000000
  926. if (timestamp >= minTimestamp && timestamp <= maxTimestamp) {
  927. logger.info(`[isTimestampBasedId] Detected timestamp-based ID: ${accountId}`);
  928. return true;
  929. }
  930. }
  931. return false;
  932. }
  933. }