HeadlessBrowserService.ts 196 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191
  1. /// <reference lib="dom" />
  2. import { chromium, type BrowserContext, type Page } from 'playwright';
  3. import { logger } from '../utils/logger.js';
  4. import { extractDeclaredNotesCountFromPostedResponse } from '../utils/xiaohongshu.js';
  5. import type { PlatformType } from '@media-manager/shared';
  6. // Python 服务配置
  7. const PYTHON_SERVICE_URL = process.env.PYTHON_PUBLISH_SERVICE_URL || process.env.XHS_SERVICE_URL || 'http://localhost:5005';
  8. // 抖音 API 接口配置
  9. const DOUYIN_API = {
  10. // 检查用户登录状态 - 返回 result: true 表示已登录(需要在浏览器上下文中调用)
  11. CHECK_USER: '/aweme/v1/creator/check/user/',
  12. // 获取作品列表(新接口,支持分页)
  13. WORK_LIST: 'https://creator.douyin.com/janus/douyin/creator/pc/work_list',
  14. // 获取评论列表
  15. COMMENT_LIST: 'https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/',
  16. // 创作者首页(用于触发登录检查)
  17. CREATOR_HOME: 'https://creator.douyin.com/creator-micro/home',
  18. };
  19. // 平台 API 配置(用于直接 HTTP 请求检查)
  20. const PLATFORM_API_CONFIG: Record<string, {
  21. checkUrl: string;
  22. isValidResponse: (data: unknown) => boolean;
  23. }> = {
  24. douyin: {
  25. // 使用账号基础信息接口检查 Cookie 有效性
  26. checkUrl: 'https://creator.douyin.com/web/api/creator/mcn/account_base_info?show_mcn_status=1',
  27. isValidResponse: (data: unknown) => {
  28. const resp = data as { status_code?: number; BaseResp?: { StatusCode?: number } };
  29. // status_code 为 0 表示 Cookie 有效
  30. return resp?.status_code === 0 || resp?.BaseResp?.StatusCode === 0;
  31. },
  32. },
  33. baijiahao: {
  34. // 使用 appinfo 接口检查 Cookie 有效性
  35. checkUrl: 'https://baijiahao.baidu.com/builder/app/appinfo',
  36. isValidResponse: (data: unknown) => {
  37. const resp = data as {
  38. errno?: number;
  39. errmsg?: string;
  40. data?: {
  41. user?: {
  42. name?: string;
  43. app_id?: string | number;
  44. userid?: number;
  45. status?: string;
  46. }
  47. }
  48. };
  49. logger.info(`[Baijiahao] API response: errno=${resp?.errno}, errmsg=${resp?.errmsg}, user.name=${resp?.data?.user?.name}, user.app_id=${resp?.data?.user?.app_id}, user.status=${resp?.data?.user?.status}`);
  50. // errno 为 0 表示请求成功
  51. const isErrnoOk = resp?.errno === 0;
  52. // 必须有用户信息(name 或 app_id)
  53. const hasUserInfo = !!(resp?.data?.user?.name || resp?.data?.user?.app_id);
  54. // 用户状态不能是 'banned' 或其他异常状态(兼容 normal 等常见正常状态)
  55. const userStatus = resp?.data?.user?.status;
  56. const isStatusOk = !userStatus || ['audit', 'pass', 'active', 'normal'].includes(String(userStatus));
  57. const isValid = isErrnoOk && hasUserInfo && isStatusOk;
  58. if (!isValid) {
  59. logger.warn(`[Baijiahao] Cookie invalid: errno=${resp?.errno}, hasUserInfo=${hasUserInfo}, status=${userStatus}`);
  60. }
  61. return isValid;
  62. },
  63. },
  64. };
  65. export interface AccountInfo {
  66. accountId: string;
  67. accountName: string;
  68. avatarUrl: string;
  69. fansCount?: number;
  70. worksCount: number;
  71. worksList?: WorkItem[];
  72. worksListComplete?: boolean;
  73. source?: 'python' | 'playwright' | 'api';
  74. pythonAvailable?: boolean;
  75. }
  76. export interface WorkItem {
  77. videoId?: string;
  78. title: string;
  79. coverUrl: string;
  80. /** 作品播放/详情页 URL,同步到 works.video_url */
  81. videoUrl?: string;
  82. duration: string;
  83. publishTime: string;
  84. status: string;
  85. playCount: number;
  86. likeCount: number;
  87. commentCount: number;
  88. shareCount: number;
  89. collectCount?: number;
  90. }
  91. export interface CommentItem {
  92. commentId: string;
  93. authorId: string;
  94. authorName: string;
  95. authorAvatar: string;
  96. content: string;
  97. likeCount: number;
  98. commentTime: string;
  99. parentCommentId?: string;
  100. videoId?: string;
  101. videoTitle?: string;
  102. videoCoverUrl?: string;
  103. }
  104. export interface WorkComments {
  105. videoId: string;
  106. videoTitle: string;
  107. videoCoverUrl: string;
  108. comments: CommentItem[];
  109. }
  110. export interface CookieData {
  111. name: string;
  112. value: string;
  113. domain: string;
  114. path: string;
  115. }
  116. export type CookieCheckSource = 'python' | 'api' | 'browser';
  117. export type CookieCheckReason =
  118. | 'valid'
  119. | 'need_login'
  120. | 'risk_control'
  121. | 'uncertain';
  122. export interface CookieCheckResult {
  123. isValid: boolean;
  124. needReLogin: boolean;
  125. uncertain: boolean;
  126. reason: CookieCheckReason;
  127. source: CookieCheckSource;
  128. message?: string;
  129. }
  130. /**
  131. * 无头浏览器服务 - 用于后台静默获取账号信息
  132. */
  133. class HeadlessBrowserService {
  134. /**
  135. * 检查 Cookie 是否有效
  136. * 优先使用 Python 服务(通过浏览器访问后台检测),回退到 API 检查
  137. */
  138. async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
  139. const status = await this.checkCookieStatus(platform, cookies);
  140. return status.isValid || status.uncertain;
  141. }
  142. /**
  143. * 检查 Cookie 状态(有效 / 需要重新登录 / 不确定)
  144. */
  145. async checkCookieStatus(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
  146. logger.info(`[checkCookieStatus] Checking cookie for ${platform}, cookie count: ${cookies.length}`);
  147. const pythonAvailable = await this.checkPythonServiceAvailable();
  148. if (pythonAvailable) {
  149. try {
  150. const result = await this.checkLoginStatusViaPython(platform, cookies);
  151. logger.info(
  152. `[checkCookieStatus] Python result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
  153. );
  154. return result;
  155. } catch (error) {
  156. logger.warn(`[Python API] Check login failed, falling back:`, error);
  157. }
  158. } else {
  159. logger.info(`[checkCookieStatus] Python service not available`);
  160. }
  161. const apiConfig = PLATFORM_API_CONFIG[platform];
  162. if (apiConfig) {
  163. const result = await this.checkCookieStatusByApi(platform, cookies, apiConfig);
  164. logger.info(
  165. `[checkCookieStatus] API result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
  166. );
  167. return result;
  168. }
  169. const result = await this.checkCookieStatusByBrowser(platform, cookies);
  170. logger.info(
  171. `[checkCookieStatus] Browser result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
  172. );
  173. return result;
  174. }
  175. private containsRiskKeywords(text: string): boolean {
  176. if (!text) return false;
  177. const lowered = text.toLowerCase();
  178. const keywords = [
  179. '验证码',
  180. '安全验证',
  181. '人机验证',
  182. '滑块',
  183. '风控',
  184. '风险',
  185. '访问受限',
  186. '行为异常',
  187. '系统检测到异常',
  188. '安全校验',
  189. 'captcha',
  190. 'verify',
  191. 'challenge',
  192. 'risk',
  193. 'security',
  194. 'safe',
  195. 'protect',
  196. 'blocked',
  197. ];
  198. return keywords.some(k => lowered.includes(k.toLowerCase()));
  199. }
  200. private async getPageBodyTextSafe(page: Page): Promise<string> {
  201. try {
  202. const content = await page.textContent('body');
  203. return (content || '').slice(0, 8000);
  204. } catch {
  205. return '';
  206. }
  207. }
  208. /**
  209. * 通过 Python 服务检查登录状态(浏览器访问后台页面,检测是否需要登录)
  210. */
  211. private async checkLoginStatusViaPython(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
  212. const pythonUrl = PYTHON_SERVICE_URL;
  213. // 构建 Cookie 字符串
  214. const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
  215. logger.info(`[Python API] Checking login status for ${platform}`);
  216. const response = await fetch(`${pythonUrl}/check_login`, {
  217. method: 'POST',
  218. headers: { 'Content-Type': 'application/json' },
  219. body: JSON.stringify({
  220. platform,
  221. cookie: cookieString,
  222. }),
  223. });
  224. if (!response.ok) {
  225. throw new Error(`Python API returned ${response.status}`);
  226. }
  227. const result = await response.json() as {
  228. success: boolean;
  229. valid: boolean;
  230. need_login: boolean;
  231. message?: string;
  232. error?: string;
  233. };
  234. logger.info(`[Python API] Check login result for ${platform}: valid=${result.valid}, need_login=${result.need_login}`);
  235. if (!result.success) {
  236. throw new Error(result.error || 'Check login failed');
  237. }
  238. const message = result.message || result.error || '';
  239. if (!result.valid || result.need_login) {
  240. return {
  241. isValid: false,
  242. needReLogin: true,
  243. uncertain: false,
  244. reason: this.containsRiskKeywords(message) ? 'risk_control' : 'need_login',
  245. source: 'python',
  246. message,
  247. };
  248. }
  249. if (this.containsRiskKeywords(message)) {
  250. return {
  251. isValid: false,
  252. needReLogin: true,
  253. uncertain: false,
  254. reason: 'risk_control',
  255. source: 'python',
  256. message,
  257. };
  258. }
  259. return {
  260. isValid: true,
  261. needReLogin: false,
  262. uncertain: false,
  263. reason: 'valid',
  264. source: 'python',
  265. message,
  266. };
  267. }
  268. /**
  269. * 通过 API 检查 Cookie 是否有效
  270. * 注意:API 返回不确定状态时会回退到浏览器检查,避免误判
  271. */
  272. private async checkCookieStatusByApi(
  273. platform: PlatformType,
  274. cookies: CookieData[],
  275. apiConfig: typeof PLATFORM_API_CONFIG[string]
  276. ): Promise<CookieCheckResult> {
  277. try {
  278. // 构建 Cookie 字符串(所有 Cookie 拼接)
  279. const cookieString = cookies
  280. .map(c => `${c.name}=${c.value}`)
  281. .join('; ');
  282. logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);
  283. // 发起 API 请求,模拟浏览器请求
  284. const response = await fetch(apiConfig.checkUrl, {
  285. method: 'GET',
  286. headers: {
  287. 'Accept': 'application/json, text/plain, */*',
  288. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  289. 'Cache-Control': 'no-cache',
  290. 'Cookie': cookieString,
  291. 'Pragma': 'no-cache',
  292. 'Referer': this.getPlatformReferer(platform),
  293. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  294. 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
  295. 'sec-ch-ua-mobile': '?0',
  296. 'sec-ch-ua-platform': '"Windows"',
  297. 'sec-fetch-dest': 'empty',
  298. 'sec-fetch-mode': 'cors',
  299. 'sec-fetch-site': 'same-origin',
  300. },
  301. });
  302. const data = await response.json();
  303. logger.info(`[API] Raw response for ${platform}:`, JSON.stringify(data).substring(0, 500));
  304. const isValid = apiConfig.isValidResponse(data);
  305. const statusCode = (data as { status_code?: number; errno?: number; ret?: { errno?: number } })?.status_code
  306. ?? (data as { errno?: number })?.errno
  307. ?? (data as { ret?: { errno?: number } })?.ret?.errno;
  308. logger.info(`API check cookie for ${platform}: valid=${isValid}, statusCode=${statusCode}`);
  309. // 如果 API 明确返回有效,直接返回 true
  310. if (isValid) {
  311. const rawText = JSON.stringify(data).slice(0, 2000);
  312. if (this.containsRiskKeywords(rawText)) {
  313. return {
  314. isValid: false,
  315. needReLogin: true,
  316. uncertain: false,
  317. reason: 'risk_control',
  318. source: 'api',
  319. message: 'API 返回疑似风控/验证页面',
  320. };
  321. }
  322. return {
  323. isValid: true,
  324. needReLogin: false,
  325. uncertain: false,
  326. reason: 'valid',
  327. source: 'api',
  328. };
  329. }
  330. // API 返回无效时,检查是否是明确的"未登录"状态
  331. // 抖音: status_code 为 2 或 8 通常表示未登录/登录过期
  332. // 百家号: errno 为非 0 可能表示未登录,但需要根据具体错误码判断
  333. const clearlyNotLoggedIn = statusCode === 2 || statusCode === 8;
  334. if (clearlyNotLoggedIn) {
  335. logger.info(`[API] Platform ${platform} clearly not logged in (statusCode=${statusCode})`);
  336. return {
  337. isValid: false,
  338. needReLogin: true,
  339. uncertain: false,
  340. reason: 'need_login',
  341. source: 'api',
  342. };
  343. }
  344. // 百家号特殊处理:API 用 Node fetch 调用时可能因分散认证等返回 errno !== 0,但 Cookie 在浏览器内仍有效
  345. // 因此当 API 判为无效时,回退到浏览器检查,避免“能登录后台却显示过期”
  346. if (platform === 'baijiahao') {
  347. const errno = (data as { errno?: number })?.errno;
  348. if (errno === 0 && isValid) {
  349. return { isValid: true, needReLogin: false, uncertain: false, reason: 'valid', source: 'api' };
  350. }
  351. if (errno === 0 && !isValid) {
  352. logger.warn(`[API] Baijiahao errno=0 but no user info, falling back to browser check`);
  353. return this.checkCookieStatusByBrowser(platform, cookies);
  354. }
  355. // errno 110 通常表示未登录,可直接判无效;其他 errno(如 10001402 分散认证)可能只是接口限制,用浏览器再判一次
  356. if (errno === 110) {
  357. logger.warn(`[API] Baijiahao errno=110 (not logged in), cookie invalid`);
  358. return { isValid: false, needReLogin: true, uncertain: false, reason: 'need_login', source: 'api' };
  359. }
  360. logger.info(`[API] Baijiahao errno=${errno}, falling back to browser check (may be dispersed auth)`);
  361. return this.checkCookieStatusByBrowser(platform, cookies);
  362. }
  363. // 不确定的状态(如 status_code=7),回退到浏览器检查
  364. logger.info(`[API] Uncertain status for ${platform} (statusCode=${statusCode}), falling back to browser check`);
  365. return this.checkCookieStatusByBrowser(platform, cookies);
  366. } catch (error) {
  367. logger.error(`API check cookie error for ${platform}:`, error);
  368. // API 检查失败时,回退到浏览器检查
  369. return this.checkCookieStatusByBrowser(platform, cookies);
  370. }
  371. }
  372. /**
  373. * 获取平台 Referer
  374. */
  375. private getPlatformReferer(platform: PlatformType): string {
  376. const referers: Record<string, string> = {
  377. douyin: 'https://creator.douyin.com/',
  378. bilibili: 'https://member.bilibili.com/',
  379. kuaishou: 'https://cp.kuaishou.com/',
  380. baijiahao: 'https://baijiahao.baidu.com/',
  381. };
  382. return referers[platform] || '';
  383. }
  384. /**
  385. * 通过浏览器检查 Cookie 是否有效(检查是否被重定向到登录页)
  386. * 注意:网络错误或服务不可用时返回 true(保持原状态),避免误判为过期
  387. */
  388. private async checkCookieStatusByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
  389. // 对于抖音平台,使用 check/user 接口检查
  390. if (platform === 'douyin') {
  391. return this.checkDouyinLoginStatusByApi(cookies);
  392. }
  393. const browser = await chromium.launch({ headless: true });
  394. try {
  395. const context = await browser.newContext({
  396. viewport: { width: 1920, height: 1080 },
  397. locale: 'zh-CN',
  398. timezoneId: 'Asia/Shanghai',
  399. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  400. });
  401. await context.addCookies(cookies);
  402. const page = await context.newPage();
  403. const config = this.getPlatformConfig(platform);
  404. // 访问平台主页
  405. await page.goto(config.homeUrl, {
  406. waitUntil: 'domcontentloaded',
  407. timeout: 30000,
  408. });
  409. await page.waitForTimeout(3000);
  410. const url = page.url();
  411. logger.info(`Browser check cookie for ${platform}: URL=${url}`);
  412. // 检查是否被重定向到登录页
  413. const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));
  414. const bodyText = await this.getPageBodyTextSafe(page);
  415. const isRiskControl = this.containsRiskKeywords(url) || this.containsRiskKeywords(bodyText);
  416. await page.close();
  417. await context.close();
  418. await browser.close();
  419. if (isLoginPage) {
  420. return {
  421. isValid: false,
  422. needReLogin: true,
  423. uncertain: false,
  424. reason: 'need_login',
  425. source: 'browser',
  426. };
  427. }
  428. if (isRiskControl) {
  429. return {
  430. isValid: false,
  431. needReLogin: true,
  432. uncertain: false,
  433. reason: 'risk_control',
  434. source: 'browser',
  435. message: '检测到风控/验证页面',
  436. };
  437. }
  438. return {
  439. isValid: true,
  440. needReLogin: false,
  441. uncertain: false,
  442. reason: 'valid',
  443. source: 'browser',
  444. };
  445. } catch (error) {
  446. logger.error(`Browser check cookie error for ${platform}:`, error);
  447. await browser.close();
  448. return {
  449. isValid: false,
  450. needReLogin: false,
  451. uncertain: true,
  452. reason: 'uncertain',
  453. source: 'browser',
  454. message: error instanceof Error ? error.message : 'Browser check error',
  455. };
  456. }
  457. }
  458. /**
  459. * 抖音登录状态检查 - 通过监听 check/user 接口
  460. * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
  461. */
  462. private async checkDouyinLoginStatusByApi(cookies: CookieData[]): Promise<CookieCheckResult> {
  463. const browser = await chromium.launch({ headless: true });
  464. let isLoggedIn = false;
  465. let checkCompleted = false;
  466. let isRiskControl = false;
  467. try {
  468. const context = await browser.newContext({
  469. viewport: { width: 1920, height: 1080 },
  470. locale: 'zh-CN',
  471. timezoneId: 'Asia/Shanghai',
  472. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  473. });
  474. await context.addCookies(cookies);
  475. const page = await context.newPage();
  476. // 监听 check/user 接口响应
  477. page.on('response', async (response) => {
  478. const url = response.url();
  479. if (url.includes(DOUYIN_API.CHECK_USER)) {
  480. try {
  481. const data = await response.json();
  482. // result: true 表示已登录
  483. isLoggedIn = data?.result === true && data?.status_code === 0;
  484. checkCompleted = true;
  485. logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
  486. } catch {
  487. // 忽略解析错误
  488. }
  489. }
  490. });
  491. // 访问创作者首页,触发 check/user 接口
  492. await page.goto(DOUYIN_API.CREATOR_HOME, {
  493. waitUntil: 'domcontentloaded',
  494. timeout: 30000,
  495. });
  496. // 等待接口响应或超时
  497. const startTime = Date.now();
  498. while (!checkCompleted && Date.now() - startTime < 10000) {
  499. await page.waitForTimeout(500);
  500. }
  501. // 如果没有收到 check/user 响应,检查 URL 是否被重定向到登录页
  502. if (!checkCompleted) {
  503. const currentUrl = page.url();
  504. isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
  505. logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
  506. }
  507. const finalUrl = page.url();
  508. const bodyText = await this.getPageBodyTextSafe(page);
  509. isRiskControl = this.containsRiskKeywords(finalUrl) || this.containsRiskKeywords(bodyText);
  510. await page.close();
  511. await context.close();
  512. await browser.close();
  513. if (isRiskControl) {
  514. return {
  515. isValid: false,
  516. needReLogin: true,
  517. uncertain: false,
  518. reason: 'risk_control',
  519. source: 'browser',
  520. message: '检测到风控/验证页面',
  521. };
  522. }
  523. return {
  524. isValid: isLoggedIn,
  525. needReLogin: !isLoggedIn,
  526. uncertain: false,
  527. reason: isLoggedIn ? 'valid' : 'need_login',
  528. source: 'browser',
  529. };
  530. } catch (error) {
  531. logger.error('[Douyin] checkDouyinLoginByApi error:', error);
  532. try {
  533. await browser.close();
  534. } catch { }
  535. return {
  536. isValid: false,
  537. needReLogin: false,
  538. uncertain: true,
  539. reason: 'uncertain',
  540. source: 'browser',
  541. message: error instanceof Error ? error.message : 'Douyin check error',
  542. };
  543. }
  544. }
  545. /**
  546. * 访问平台后台页面并截图(用于 AI 分析)
  547. * @param platform 平台类型
  548. * @param cookies Cookie 数据
  549. * @returns Base64 编码的截图,失败返回 null
  550. */
  551. async capturePageScreenshot(platform: PlatformType, cookies: CookieData[]): Promise<string | null> {
  552. const browser = await chromium.launch({ headless: true });
  553. try {
  554. const context = await browser.newContext({
  555. viewport: { width: 1920, height: 1080 },
  556. locale: 'zh-CN',
  557. timezoneId: 'Asia/Shanghai',
  558. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  559. });
  560. await context.addCookies(cookies);
  561. const page = await context.newPage();
  562. const config = this.getPlatformConfig(platform);
  563. logger.info(`[Screenshot] Navigating to ${platform} home page: ${config.homeUrl}`);
  564. // 访问平台主页
  565. await page.goto(config.homeUrl, {
  566. waitUntil: 'domcontentloaded',
  567. timeout: 30000,
  568. });
  569. // 等待页面加载
  570. await page.waitForTimeout(3000);
  571. const url = page.url();
  572. logger.info(`[Screenshot] Current URL: ${url}`);
  573. // 截图
  574. const screenshotBuffer = await page.screenshot({
  575. type: 'jpeg',
  576. quality: 80,
  577. fullPage: false,
  578. });
  579. const base64Screenshot = screenshotBuffer.toString('base64');
  580. await page.close();
  581. await context.close();
  582. await browser.close();
  583. logger.info(`[Screenshot] Captured screenshot for ${platform}, size: ${Math.round(base64Screenshot.length / 1024)}KB`);
  584. return base64Screenshot;
  585. } catch (error) {
  586. logger.error(`[Screenshot] Failed to capture screenshot for ${platform}:`, error);
  587. try {
  588. await browser.close();
  589. } catch { /* ignore */ }
  590. return null;
  591. }
  592. }
  593. /**
  594. * 检查 Python 服务是否可用
  595. */
  596. private async checkPythonServiceAvailable(): Promise<boolean> {
  597. try {
  598. const response = await fetch(`${PYTHON_SERVICE_URL}/health`, {
  599. method: 'GET',
  600. signal: AbortSignal.timeout(3000),
  601. });
  602. return response.ok;
  603. } catch {
  604. return false;
  605. }
  606. }
  607. /**
  608. * 通过 Python API 获取作品列表
  609. */
  610. private async fetchWorksViaPython(
  611. platform: PlatformType,
  612. cookies: CookieData[],
  613. onPage?: (info: {
  614. platform: PlatformType;
  615. page: string;
  616. pageSize: number;
  617. fetched: number;
  618. newCount: number;
  619. totalSoFar: number;
  620. declaredTotal?: number;
  621. hasMore: boolean;
  622. nextPage?: unknown;
  623. }) => void
  624. ): Promise<{
  625. works: WorkItem[];
  626. total?: number;
  627. }> {
  628. logger.info(`[Python API] Fetching works for ${platform} (auto pagination)...`);
  629. const cookieString = JSON.stringify(cookies);
  630. const pythonPlatform = platform === 'weixin_video' ? 'weixin' : platform;
  631. // 抖音 work_list 接口 count 最大 20,需与创作者中心一致
  632. const pageSize = platform === 'xiaohongshu' ? 20 : platform === 'douyin' ? 20 : 50;
  633. let maxPages = 30;
  634. const allWorks: WorkItem[] = [];
  635. const seenIds = new Set<string>();
  636. const legacyToCanonical = new Map<string, string>();
  637. let declaredTotal: number | undefined;
  638. let cursor: string | number = 0;
  639. const seenCursors = new Set<string>();
  640. // 抖音、小红书使用 cursor 分页;视频号使用 currentPage 页码(pageIndex 0,1,2...)
  641. const useCursorPagination = platform === 'xiaohongshu' || platform === 'douyin';
  642. for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
  643. const pageParam: number | string = useCursorPagination ? cursor : pageIndex;
  644. logger.info(`[Python API] Fetching works page=${String(pageParam)}, page_size=${pageSize} for ${platform}`);
  645. logger.info(`[Python API] 调用 Python /works: platform=${platform} -> pythonPlatform=${pythonPlatform}, page=${String(pageParam)}, url=${PYTHON_SERVICE_URL}`);
  646. const response: Response = await fetch(`${PYTHON_SERVICE_URL}/works`, {
  647. method: 'POST',
  648. headers: {
  649. 'Content-Type': 'application/json',
  650. },
  651. body: JSON.stringify({
  652. platform: pythonPlatform,
  653. cookie: cookieString,
  654. page: pageParam,
  655. page_size: pageSize,
  656. auto_paging: platform === 'xiaohongshu' && pageIndex === 0,
  657. }),
  658. });
  659. if (!response.ok) {
  660. throw new Error(`Python API returned ${response.status}`);
  661. }
  662. const result: any = await response.json();
  663. if (pageIndex === 0) {
  664. logger.info(`[Python API] Response for ${platform}: success=${result.success}, works_count=${result.works?.length || 0}, total=${result.total || 0}, has_more=${result.has_more}, error=${result.error || 'none'}`);
  665. if (result.error) {
  666. logger.warn(`[Python API] Error from Python service: ${result.error}`);
  667. }
  668. }
  669. if (!result.success) {
  670. logger.error(`[Python API] Python service returned error: ${result.error || 'Unknown error'}, full response: ${JSON.stringify(result).substring(0, 500)}`);
  671. throw new Error(result.error || 'Failed to get works');
  672. }
  673. if (typeof result.total === 'number' && result.total > 0) {
  674. declaredTotal = declaredTotal ? Math.max(declaredTotal, result.total) : result.total;
  675. if (pageIndex === 0) {
  676. maxPages = Math.min(400, Math.ceil(result.total / pageSize) + 5);
  677. }
  678. }
  679. const pageWorks: WorkItem[] = (result.works || []).map((work: {
  680. work_id: string;
  681. title: string;
  682. cover_url: string;
  683. video_url?: string;
  684. duration: number;
  685. publish_time: string;
  686. status: string;
  687. play_count: number;
  688. like_count: number;
  689. comment_count: number;
  690. share_count: number;
  691. collect_count?: number;
  692. }) => ({
  693. videoId: work.work_id,
  694. title: work.title,
  695. coverUrl: work.cover_url,
  696. videoUrl: work.video_url || '',
  697. duration: String(work.duration || 0),
  698. publishTime: work.publish_time,
  699. status: work.status || 'published',
  700. playCount: work.play_count || 0,
  701. likeCount: work.like_count || 0,
  702. commentCount: work.comment_count || 0,
  703. shareCount: work.share_count || 0,
  704. collectCount: work.collect_count ?? 0,
  705. }));
  706. let newCount = 0;
  707. for (const w of pageWorks) {
  708. const titleForId = (w.title || '').trim();
  709. const publishTimeForId = (w.publishTime || '').trim();
  710. const legacyId = `${platform}_${titleForId}_${publishTimeForId}`.substring(0, 100);
  711. let canonicalId = (w.videoId || '').trim() || legacyId;
  712. if (platform === 'weixin_video') {
  713. const rawId = (w.videoId || '').trim();
  714. if (rawId) {
  715. legacyToCanonical.set(legacyId, rawId);
  716. canonicalId = rawId;
  717. } else {
  718. const mapped = legacyToCanonical.get(legacyId);
  719. if (mapped) canonicalId = mapped;
  720. }
  721. }
  722. if (!seenIds.has(canonicalId)) {
  723. seenIds.add(canonicalId);
  724. allWorks.push({
  725. ...w,
  726. videoId: canonicalId,
  727. });
  728. newCount++;
  729. }
  730. }
  731. logger.info(
  732. `[Python API] Page ${String(pageParam)} fetched=${pageWorks.length}, new=${newCount}, total=${allWorks.length}, has_more=${!!result.has_more}, declared_total=${declaredTotal || 0}, next_page=${String(result.next_page ?? '')}`
  733. );
  734. onPage?.({
  735. platform,
  736. page: String(pageParam),
  737. pageSize,
  738. fetched: pageWorks.length,
  739. newCount,
  740. totalSoFar: allWorks.length,
  741. declaredTotal,
  742. hasMore: !!result.has_more,
  743. nextPage: result.next_page,
  744. });
  745. if (useCursorPagination) {
  746. const next: any = result.next_page;
  747. const hasNextCursor = next !== undefined && next !== null && next !== '' && next !== -1 && next !== '-1';
  748. if (hasNextCursor) {
  749. const key = String(next);
  750. if (seenCursors.has(key)) break;
  751. seenCursors.add(key);
  752. cursor = next;
  753. } else {
  754. if (platform === 'douyin') break;
  755. cursor = (typeof cursor === 'number' ? cursor + 1 : pageIndex + 1);
  756. }
  757. // 抖音:仅当无下一页游标或本页 0 条时停止
  758. if (platform === 'douyin') {
  759. if (!hasNextCursor || pageWorks.length === 0) break;
  760. } else {
  761. const expectedMore = declaredTotal && declaredTotal > 0 ? allWorks.length < declaredTotal : !!result.has_more;
  762. if (!expectedMore || pageWorks.length === 0 || newCount === 0) break;
  763. }
  764. } else {
  765. if (!result.has_more || pageWorks.length === 0 || newCount === 0) break;
  766. }
  767. }
  768. logger.info(`[Python API] Total works fetched for ${platform}: ${allWorks.length}`);
  769. return { works: allWorks, total: declaredTotal };
  770. }
  771. /**
  772. * 获取账号信息(优先使用 Python API,回退到无头浏览器)
  773. */
  774. async fetchAccountInfo(
  775. platform: PlatformType,
  776. cookies: CookieData[],
  777. options?: {
  778. onWorksFetchProgress?: (info: {
  779. platform: PlatformType;
  780. page: string;
  781. pageSize: number;
  782. fetched: number;
  783. newCount: number;
  784. totalSoFar: number;
  785. declaredTotal?: number;
  786. hasMore: boolean;
  787. nextPage?: unknown;
  788. }) => void;
  789. }
  790. ): Promise<AccountInfo> {
  791. logger.info(`[fetchAccountInfo] Starting for platform: ${platform}`);
  792. let pythonAvailable = false;
  793. // 百家号:优先走 Python 的 /account_info(包含粉丝数、作品数),避免 Node 直连分散认证问题
  794. if (platform === 'baijiahao') {
  795. pythonAvailable = await this.checkPythonServiceAvailable();
  796. let info: AccountInfo;
  797. if (pythonAvailable) {
  798. logger.info(`[Python API] Service available, fetching account_info for baijiahao`);
  799. try {
  800. info = await this.fetchAccountInfoViaPython(platform, cookies);
  801. info.source = 'python';
  802. info.pythonAvailable = true;
  803. } catch (error) {
  804. logger.warn(`[Python API] Failed to fetch account_info for baijiahao, will still try /works:`, error);
  805. info = this.getDefaultAccountInfo(platform);
  806. info.source = 'python';
  807. info.pythonAvailable = true;
  808. }
  809. } else {
  810. logger.info(`[Python API] Service not available for baijiahao, falling back to direct API`);
  811. // Python 不可用时,回退到 Node 直连 API(可能仍会遇到分散认证问题)
  812. info = await this.fetchBaijiahaoAccountInfoDirectApi(cookies);
  813. info.source = 'api';
  814. info.pythonAvailable = false;
  815. }
  816. // 百家号同步作品需要全量:优先通过 Python /works 自动分页拉取
  817. if (pythonAvailable) {
  818. try {
  819. const { works: worksList, total: worksTotal } = await this.fetchWorksViaPython(
  820. platform,
  821. cookies,
  822. options?.onWorksFetchProgress
  823. );
  824. info.worksList = worksList;
  825. if (worksTotal && worksTotal > 0) {
  826. info.worksCount = worksTotal;
  827. info.worksListComplete = worksList.length >= worksTotal;
  828. } else if (worksList.length > 0) {
  829. info.worksCount = Math.max(info.worksCount || 0, worksList.length);
  830. info.worksListComplete = undefined;
  831. }
  832. info.source = 'python';
  833. info.pythonAvailable = true;
  834. } catch (error) {
  835. logger.warn(`[Python API] Failed to fetch works for baijiahao:`, error);
  836. }
  837. }
  838. return info;
  839. }
  840. // 对于支持的平台,尝试使用 Python API 获取作品列表和账号信息
  841. // 同步作品需要全量:这里会通过 Python /works 自动分页拉取
  842. const supportedPlatforms: PlatformType[] = ['douyin', 'xiaohongshu', 'kuaishou', 'weixin_video', 'baijiahao'];
  843. if (supportedPlatforms.includes(platform)) {
  844. pythonAvailable = await this.checkPythonServiceAvailable();
  845. if (pythonAvailable) {
  846. logger.info(`[Python API] Service available, trying to fetch works for ${platform}`);
  847. try {
  848. const { works: worksList, total: worksTotal } = await this.fetchWorksViaPython(
  849. platform,
  850. cookies,
  851. options?.onWorksFetchProgress
  852. );
  853. // 如果成功获取到作品,使用 Playwright 获取账号基本信息
  854. if (worksList.length > 0) {
  855. logger.info(`[Python API] Successfully fetched ${worksList.length} works for ${platform}`);
  856. try {
  857. let accountInfo: AccountInfo;
  858. // 对于小红书,优先使用 Python API 获取账号信息(因为 Node 端 Playwright 可能无法捕获到 API)
  859. if (platform === 'xiaohongshu') {
  860. try {
  861. accountInfo = await this.fetchAccountInfoViaPython(platform, cookies);
  862. } catch (e) {
  863. logger.warn(`[Python API] Failed to fetch account info for ${platform}, falling back to Playwright:`, e);
  864. accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
  865. }
  866. } else {
  867. accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
  868. }
  869. accountInfo.worksList = worksList;
  870. // 账号展示的作品数优先用 Python 返回的 total(更接近创作者中心“全部笔记”),否则回退到抓到的列表长度
  871. accountInfo.worksCount = worksTotal && worksTotal > 0 ? worksTotal : worksList.length;
  872. accountInfo.worksListComplete = worksTotal && worksTotal > 0 ? worksList.length >= worksTotal : undefined;
  873. accountInfo.source = 'python';
  874. accountInfo.pythonAvailable = true;
  875. logger.info(`[fetchAccountInfo] Using Python API works count for ${platform}: ${accountInfo.worksCount}`);
  876. return accountInfo;
  877. } catch (playwrightError) {
  878. logger.warn(`[Playwright] Failed to get account info for ${platform}:`, playwrightError);
  879. const accountInfo = this.getDefaultAccountInfo(platform);
  880. accountInfo.worksList = worksList;
  881. accountInfo.worksCount = worksTotal && worksTotal > 0 ? worksTotal : worksList.length;
  882. accountInfo.worksListComplete = worksTotal && worksTotal > 0 ? worksList.length >= worksTotal : undefined;
  883. accountInfo.source = 'python';
  884. accountInfo.pythonAvailable = true;
  885. return accountInfo;
  886. }
  887. }
  888. // 作品列表为空,尝试用 Playwright 获取账号信息
  889. if (worksTotal > 0 && worksList.length === 0) {
  890. logger.warn(`[Python API] Warning: API reported ${worksTotal} works but returned empty list for ${platform}`);
  891. logger.warn(`[Python API] This may indicate a bug in Python API or API format change`);
  892. } else {
  893. logger.info(`[Python API] Got empty works list for ${platform} (total=${worksTotal}), trying Playwright`);
  894. }
  895. } catch (pythonError) {
  896. logger.warn(`[Python API] Failed to fetch works for ${platform}:`, pythonError);
  897. logger.warn(`[Python API] Error details:`, pythonError instanceof Error ? pythonError.message : String(pythonError));
  898. }
  899. } else {
  900. logger.info(`[Python API] Service not available for ${platform}`);
  901. }
  902. }
  903. // 使用 Playwright 获取账号信息
  904. logger.info(`[Playwright] Fetching account info for ${platform}`);
  905. const info = await this.fetchAccountInfoWithPlaywright(platform, cookies);
  906. info.source = 'playwright';
  907. info.pythonAvailable = pythonAvailable;
  908. return info;
  909. }
  910. /**
  911. * 使用 Playwright 获取账号信息(原方法)
  912. */
  913. private async fetchAccountInfoWithPlaywright(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
  914. const browser = await chromium.launch({ headless: true });
  915. try {
  916. const context = await browser.newContext({
  917. viewport: { width: 1920, height: 1080 },
  918. locale: 'zh-CN',
  919. timezoneId: 'Asia/Shanghai',
  920. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  921. });
  922. await context.addCookies(cookies);
  923. const page = await context.newPage();
  924. let accountInfo: AccountInfo;
  925. switch (platform) {
  926. case 'douyin':
  927. accountInfo = await this.fetchDouyinAccountInfo(page, context, cookies);
  928. break;
  929. case 'bilibili':
  930. accountInfo = await this.fetchBilibiliAccountInfo(page, context, cookies);
  931. break;
  932. case 'kuaishou':
  933. accountInfo = await this.fetchKuaishouAccountInfo(page, context, cookies);
  934. break;
  935. case 'xiaohongshu':
  936. accountInfo = await this.fetchXiaohongshuAccountInfo(page, context, cookies);
  937. break;
  938. case 'weixin_video':
  939. accountInfo = await this.fetchWeixinVideoAccountInfo(page, context, cookies);
  940. break;
  941. default:
  942. accountInfo = this.getDefaultAccountInfo(platform);
  943. }
  944. await page.close();
  945. await context.close();
  946. await browser.close();
  947. return accountInfo;
  948. } catch (error) {
  949. logger.error('HeadlessBrowser fetchAccountInfo error:', error);
  950. await browser.close();
  951. return this.getDefaultAccountInfo(platform);
  952. }
  953. }
  954. /**
  955. * 获取抖音账号信息 - 通过 API 方式获取
  956. * 1. 监听 check/user 接口验证登录状态
  957. * 2. 通过 work_list API 获取作品数和作品列表
  958. */
  959. private async fetchDouyinAccountInfo(
  960. page: Page,
  961. _context: BrowserContext,
  962. cookies: CookieData[]
  963. ): Promise<AccountInfo> {
  964. let accountId = `douyin_${Date.now()}`;
  965. let accountName = '抖音账号';
  966. let avatarUrl = '';
  967. let fansCount: number | undefined;
  968. let worksCount = 0;
  969. let worksList: WorkItem[] = [];
  970. let isLoggedIn = false;
  971. // 用于存储从 API 捕获的数据
  972. const capturedData: {
  973. userInfo?: {
  974. nickname?: string;
  975. avatar?: string;
  976. uid?: string;
  977. sec_uid?: string;
  978. unique_id?: string; // 抖音号(如 Ethanfly9392)
  979. short_id?: string; // 短ID
  980. follower_count?: number;
  981. };
  982. worksList?: Array<{
  983. awemeId: string;
  984. title: string;
  985. coverUrl: string;
  986. duration: number;
  987. createTime: number;
  988. statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number; collect_count: number };
  989. }>;
  990. total?: number;
  991. } = {};
  992. try {
  993. // 从 Cookie 获取用户 ID
  994. const uidCookie = cookies.find(c =>
  995. ['passport_uid', 'uid', 'ssid'].includes(c.name)
  996. );
  997. if (uidCookie?.value) {
  998. accountId = `douyin_${uidCookie.value}`;
  999. }
  1000. // 设置 API 响应监听器
  1001. page.on('response', async (response) => {
  1002. const url = response.url();
  1003. try {
  1004. // 监听 check/user 接口 - 验证登录状态
  1005. if (url.includes(DOUYIN_API.CHECK_USER)) {
  1006. const data = await response.json();
  1007. isLoggedIn = data?.result === true && data?.status_code === 0;
  1008. logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
  1009. }
  1010. // 监听 work_list 接口 - 获取作品列表
  1011. if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
  1012. const data = await response.json();
  1013. if (data?.aweme_list && data.aweme_list.length > 0) {
  1014. // 优先从 author.aweme_count 获取真实的作品数(最准确)
  1015. const firstAweme = data.aweme_list[0];
  1016. const authorAwemeCount = firstAweme?.author?.aweme_count;
  1017. if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
  1018. capturedData.total = authorAwemeCount;
  1019. logger.info(`[Douyin API] Using author.aweme_count as works count: ${authorAwemeCount}`);
  1020. } else {
  1021. // 备用方案:使用 items 数组长度
  1022. const itemsCount = data?.items?.length || 0;
  1023. if (itemsCount > 0) {
  1024. capturedData.total = (capturedData.total || 0) + itemsCount;
  1025. } else {
  1026. // 如果没有 items,使用 aweme_list 长度
  1027. capturedData.total = (capturedData.total || 0) + data.aweme_list.length;
  1028. }
  1029. }
  1030. // 解析作品列表;video_url 使用 video.play_addr.url_list 的第一项
  1031. capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
  1032. const statistics = aweme.statistics as Record<string, unknown> || {};
  1033. const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
  1034. const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';
  1035. const video = aweme.video as { play_addr?: { url_list?: string[] } } | undefined;
  1036. const videoUrl = video?.play_addr?.url_list?.[0] || '';
  1037. return {
  1038. awemeId: String(aweme.aweme_id || ''),
  1039. title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
  1040. coverUrl,
  1041. videoUrl,
  1042. duration: Number(aweme.duration || 0),
  1043. createTime: Number(aweme.create_time || 0),
  1044. statistics: {
  1045. play_count: Number(statistics.play_count || 0),
  1046. digg_count: Number(statistics.digg_count || 0),
  1047. comment_count: Number(statistics.comment_count || 0),
  1048. share_count: Number(statistics.share_count || 0),
  1049. collect_count: Number((statistics as any).collect_count || 0),
  1050. },
  1051. };
  1052. });
  1053. logger.info(`[Douyin API] work_list: itemsCount=${capturedData.total}, aweme_list_length=${capturedData.worksList?.length}`);
  1054. }
  1055. }
  1056. // 监听账号信息接口 - 增加更多可能的接口
  1057. if (url.includes('/account_base_info') ||
  1058. url.includes('/user/info') ||
  1059. url.includes('/creator/user') ||
  1060. url.includes('/data/overview') ||
  1061. url.includes('/creator-micro/data') ||
  1062. url.includes('/home_data')) {
  1063. const data = await response.json();
  1064. logger.info(`[Douyin API] Captured response from: ${url.split('?')[0]}`);
  1065. // 尝试多种数据结构
  1066. const user = data?.user || data?.data?.user || data?.data || data;
  1067. if (user) {
  1068. const nickname = user.nickname || user.name || user.nick_name || user.user_name;
  1069. const avatar = user.avatar_url || user.avatar_thumb?.url_list?.[0] || user.avatar || user.avatar_larger?.url_list?.[0];
  1070. const uid = user.uid || user.user_id || user.id;
  1071. const fans = user.follower_count || user.fans_count || user.mplatform_followers_count;
  1072. // 获取抖音号(unique_id 或 short_id)
  1073. const uniqueId = user.unique_id || user.short_id || user.douyin_id;
  1074. if (nickname || uid || uniqueId) {
  1075. capturedData.userInfo = {
  1076. nickname: nickname,
  1077. avatar: avatar,
  1078. uid: uid,
  1079. sec_uid: user.sec_uid,
  1080. unique_id: uniqueId,
  1081. short_id: user.short_id,
  1082. follower_count: fans,
  1083. };
  1084. logger.info(`[Douyin API] user info captured: nickname=${capturedData.userInfo.nickname}, uid=${capturedData.userInfo.uid}, unique_id=${capturedData.userInfo.unique_id}`);
  1085. }
  1086. }
  1087. }
  1088. } catch (e) {
  1089. // 忽略非 JSON 响应
  1090. }
  1091. });
  1092. // 访问主页获取基本信息并触发 check/user 接口
  1093. logger.info('[Douyin] Navigating to creator home...');
  1094. await page.goto(DOUYIN_API.CREATOR_HOME, {
  1095. waitUntil: 'domcontentloaded',
  1096. timeout: 30000,
  1097. });
  1098. // 等待页面加载完成
  1099. await page.waitForTimeout(3000);
  1100. // 尝试等待网络空闲
  1101. try {
  1102. await page.waitForLoadState('networkidle', { timeout: 10000 });
  1103. } catch {
  1104. // 超时继续
  1105. }
  1106. // 额外等待确保 API 响应被捕获
  1107. await page.waitForTimeout(2000);
  1108. // 检查登录状态 - 如果没有从 API 获取到,通过 URL 判断
  1109. if (!isLoggedIn) {
  1110. const currentUrl = page.url();
  1111. isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
  1112. }
  1113. if (!isLoggedIn) {
  1114. logger.warn('[Douyin] Not logged in, returning default account info');
  1115. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  1116. }
  1117. // 从页面提取基本账号信息(作为 API 数据的补充)
  1118. const accountData = await page.evaluate(() => {
  1119. const result: { name?: string; avatar?: string; fans?: number; douyinId?: string } = {};
  1120. // 提取抖音号 - 多种方式
  1121. // 方式1:通过选择器查找包含抖音号的元素
  1122. const uniqueIdSelectors = [
  1123. 'div[class*="unique"]',
  1124. 'span[class*="unique"]',
  1125. 'div[class*="douyin-id"]',
  1126. 'span[class*="douyin-id"]',
  1127. '[class*="account-id"]',
  1128. '[class*="shortId"]',
  1129. '[class*="short-id"]',
  1130. ];
  1131. for (const selector of uniqueIdSelectors) {
  1132. const el = document.querySelector(selector);
  1133. if (el) {
  1134. const text = el.textContent?.trim() || '';
  1135. const match = text.match(/抖音号[::]\s*(\S+)/) || text.match(/ID[::]\s*(\S+)/);
  1136. if (match) {
  1137. result.douyinId = match[1];
  1138. break;
  1139. }
  1140. // 如果元素文本本身就是抖音号(无前缀)
  1141. if (text && !text.includes('抖音号') && /^[a-zA-Z0-9_]+$/.test(text)) {
  1142. result.douyinId = text;
  1143. break;
  1144. }
  1145. }
  1146. }
  1147. // 方式2:全局搜索包含"抖音号"的文本
  1148. if (!result.douyinId) {
  1149. const allElements = Array.from(document.querySelectorAll('span, div, p'));
  1150. for (const el of allElements) {
  1151. const text = el.textContent?.trim() || '';
  1152. // 匹配 "抖音号:xxx" 或 "抖音号: xxx"
  1153. const match = text.match(/抖音号[::]\s*([a-zA-Z0-9_]+)/);
  1154. if (match && match[1]) {
  1155. result.douyinId = match[1];
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. // 查找头像 - 优先使用头像容器
  1161. const avatarSelectors = [
  1162. '[class*="avatar"] img',
  1163. '[class*="user-avatar"] img',
  1164. '[class*="profile"] img',
  1165. 'img[class*="avatar"]',
  1166. ];
  1167. for (const selector of avatarSelectors) {
  1168. const img = document.querySelector(selector) as HTMLImageElement;
  1169. if (img?.src && (img.src.includes('aweme') || img.src.includes('douyinpic') || img.src.includes('bytedance'))) {
  1170. result.avatar = img.src;
  1171. break;
  1172. }
  1173. }
  1174. // 备用方案:查找所有图片
  1175. if (!result.avatar) {
  1176. const avatarImgs = Array.from(document.querySelectorAll('img'));
  1177. for (const img of avatarImgs) {
  1178. const src = img.src || img.getAttribute('src') || '';
  1179. if (src && (src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance'))) {
  1180. const rect = img.getBoundingClientRect();
  1181. if (rect.width > 30 && rect.width < 150 && rect.top < 300) {
  1182. result.avatar = src;
  1183. break;
  1184. }
  1185. }
  1186. }
  1187. }
  1188. // 获取粉丝数 - 多种选择器
  1189. const fansSelectors = [
  1190. '#guide_home_fans',
  1191. '[class*="fans"]',
  1192. '[class*="follower"]',
  1193. '[class*="data-item"]',
  1194. ];
  1195. for (const selector of fansSelectors) {
  1196. const el = document.querySelector(selector);
  1197. if (el) {
  1198. const text = el.textContent?.trim() || '';
  1199. // 匹配 "123" 或 "1.2万" 或 "粉丝 123"
  1200. const match = text.match(/(\d+(?:\.\d+)?)\s*([万wW])?/);
  1201. if (match) {
  1202. let num = parseFloat(match[1]);
  1203. if (match[2]) num *= 10000;
  1204. result.fans = Math.floor(num);
  1205. break;
  1206. }
  1207. }
  1208. }
  1209. // 查找用户名 - 更精确的选择器
  1210. const nameSelectors = [
  1211. '[class*="user-name"]',
  1212. '[class*="nickname"]',
  1213. '[class*="author-name"]',
  1214. '[class*="profile-name"]',
  1215. 'h1[class*="name"]',
  1216. 'h2[class*="name"]',
  1217. ];
  1218. for (const selector of nameSelectors) {
  1219. const el = document.querySelector(selector);
  1220. if (el) {
  1221. const text = el.textContent?.trim() || '';
  1222. if (text && text.length >= 2 && text.length <= 30) {
  1223. result.name = text;
  1224. break;
  1225. }
  1226. }
  1227. }
  1228. // 备用方案:查找包含名字的容器
  1229. if (!result.name) {
  1230. const nameContainers = Array.from(document.querySelectorAll('[class*="name"], [class*="nick"], [class*="user"]'));
  1231. for (const container of nameContainers) {
  1232. const text = container.textContent?.trim() || '';
  1233. if (text &&
  1234. text.length >= 2 &&
  1235. text.length <= 20 &&
  1236. !text.includes('关注') &&
  1237. !text.includes('粉丝') &&
  1238. !text.includes('获赞') &&
  1239. !text.includes('加载') &&
  1240. !text.includes('创作') &&
  1241. !text.includes('发布') &&
  1242. !text.includes('抖音号') &&
  1243. !text.match(/^\d+$/)) {
  1244. const rect = container.getBoundingClientRect();
  1245. if (rect.top < 400 && rect.left < 500) {
  1246. result.name = text;
  1247. break;
  1248. }
  1249. }
  1250. }
  1251. }
  1252. return result;
  1253. });
  1254. // 优先使用抖音号作为 ID(unique_id),其次是页面提取的抖音号,最后是 uid
  1255. if (capturedData.userInfo?.unique_id) {
  1256. // 优先使用抖音号(如 Ethanfly9392)
  1257. accountId = `douyin_${capturedData.userInfo.unique_id}`;
  1258. logger.info(`[Douyin] Using unique_id as accountId: ${accountId}`);
  1259. } else if (capturedData.userInfo?.short_id) {
  1260. // 其次使用短ID
  1261. accountId = `douyin_${capturedData.userInfo.short_id}`;
  1262. logger.info(`[Douyin] Using short_id as accountId: ${accountId}`);
  1263. } else if (accountData.douyinId) {
  1264. // 使用页面提取的抖音号
  1265. accountId = `douyin_${accountData.douyinId}`;
  1266. logger.info(`[Douyin] Using page douyinId as accountId: ${accountId}`);
  1267. } else if (capturedData.userInfo?.uid) {
  1268. // 最后使用内部uid
  1269. accountId = `douyin_${capturedData.userInfo.uid}`;
  1270. logger.info(`[Douyin] Using uid as accountId: ${accountId}`);
  1271. }
  1272. accountName = capturedData.userInfo?.nickname || accountData.name || accountName;
  1273. avatarUrl = capturedData.userInfo?.avatar || accountData.avatar || avatarUrl;
  1274. fansCount = capturedData.userInfo?.follower_count || accountData.fans || fansCount;
  1275. // 通过 API 获取作品列表
  1276. logger.info('[Douyin] Fetching works via API...');
  1277. const apiResult = await this.fetchWorksDirectApi(page);
  1278. logger.info(`[Douyin] fetchWorksDirectApi returned: works.length=${apiResult.works.length}, total=${apiResult.total}`);
  1279. if (apiResult.works.length > 0) {
  1280. // 使用 items 累计数量作为作品数(apiResult.total 现在是累计的 items.length)
  1281. // 如果 total 为 0,则使用 works 列表长度
  1282. worksCount = apiResult.total > 0 ? apiResult.total : apiResult.works.length;
  1283. worksList = apiResult.works.map(w => ({
  1284. videoId: w.awemeId,
  1285. title: w.title,
  1286. coverUrl: w.coverUrl,
  1287. videoUrl: (w as { videoUrl?: string }).videoUrl || (w.awemeId ? `https://www.douyin.com/video/${w.awemeId}` : ''),
  1288. duration: '00:00',
  1289. publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
  1290. status: 'published',
  1291. playCount: w.playCount,
  1292. likeCount: w.likeCount,
  1293. commentCount: w.commentCount,
  1294. shareCount: w.shareCount,
  1295. collectCount: w.collectCount,
  1296. }));
  1297. logger.info(`[Douyin] Got ${apiResult.works.length} works from API, total count: ${worksCount}`);
  1298. } else {
  1299. logger.warn(`[Douyin] fetchWorksDirectApi returned 0 works`);
  1300. if (capturedData.worksList && capturedData.worksList.length > 0) {
  1301. // 如果直接 API 调用失败,使用监听到的数据
  1302. logger.info(`[Douyin] Falling back to intercepted API data: ${capturedData.worksList.length} works`);
  1303. worksCount = capturedData.total || capturedData.worksList.length;
  1304. worksList = capturedData.worksList.map(w => ({
  1305. videoId: w.awemeId,
  1306. title: w.title,
  1307. coverUrl: w.coverUrl,
  1308. videoUrl: (w as { videoUrl?: string }).videoUrl || (w.awemeId ? `https://www.douyin.com/video/${w.awemeId}` : ''),
  1309. duration: this.formatDuration(w.duration),
  1310. publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
  1311. status: 'published',
  1312. playCount: w.statistics.play_count,
  1313. likeCount: w.statistics.digg_count,
  1314. commentCount: w.statistics.comment_count,
  1315. shareCount: w.statistics.share_count,
  1316. collectCount: w.statistics.collect_count,
  1317. }));
  1318. logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
  1319. } else {
  1320. logger.warn(`[Douyin] No works found: fetchWorksDirectApi returned 0, intercepted data also empty`);
  1321. logger.warn(`[Douyin] This may indicate: cookie expired, API error, or account has no works`);
  1322. }
  1323. }
  1324. } catch (error) {
  1325. logger.error('Failed to fetch Douyin account info:', error);
  1326. logger.error('Error details:', error instanceof Error ? error.stack : String(error));
  1327. }
  1328. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  1329. }
  1330. /**
  1331. * 格式化视频时长
  1332. */
  1333. private formatDuration(ms: number): string {
  1334. if (!ms) return '00:00';
  1335. const seconds = Math.floor(ms / 1000);
  1336. const minutes = Math.floor(seconds / 60);
  1337. const remainingSeconds = seconds % 60;
  1338. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  1339. }
  1340. /**
  1341. * 获取B站账号信息
  1342. */
  1343. private async fetchBilibiliAccountInfo(
  1344. page: Page,
  1345. _context: BrowserContext,
  1346. cookies: CookieData[]
  1347. ): Promise<AccountInfo> {
  1348. let accountId = `bilibili_${Date.now()}`;
  1349. let accountName = 'B站账号';
  1350. let avatarUrl = '';
  1351. let fansCount: number | undefined;
  1352. let worksCount = 0;
  1353. try {
  1354. const uidCookie = cookies.find(c => c.name === 'DedeUserID');
  1355. if (uidCookie?.value) {
  1356. accountId = `bilibili_${uidCookie.value}`;
  1357. }
  1358. await page.goto('https://member.bilibili.com/platform/home', {
  1359. waitUntil: 'domcontentloaded',
  1360. timeout: 30000,
  1361. });
  1362. await page.waitForTimeout(3000);
  1363. // 获取用户名
  1364. const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
  1365. if (nameEl) {
  1366. const text = await nameEl.textContent();
  1367. if (text?.trim()) {
  1368. accountName = text.trim();
  1369. }
  1370. }
  1371. // 获取头像
  1372. const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
  1373. if (avatarEl) {
  1374. const src = await avatarEl.getAttribute('src');
  1375. if (src) {
  1376. avatarUrl = src;
  1377. }
  1378. }
  1379. } catch (error) {
  1380. logger.warn('Failed to fetch Bilibili account info:', error);
  1381. }
  1382. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1383. }
  1384. /**
  1385. * 获取快手账号信息
  1386. */
  1387. private async fetchKuaishouAccountInfo(
  1388. page: Page,
  1389. _context: BrowserContext,
  1390. cookies: CookieData[]
  1391. ): Promise<AccountInfo> {
  1392. let accountId = `kuaishou_${Date.now()}`;
  1393. let accountName = '快手账号';
  1394. let avatarUrl = '';
  1395. let fansCount: number | undefined;
  1396. let worksCount = 0;
  1397. try {
  1398. const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
  1399. if (uidCookie?.value) {
  1400. accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
  1401. }
  1402. await page.goto('https://cp.kuaishou.com/profile', {
  1403. waitUntil: 'domcontentloaded',
  1404. timeout: 30000,
  1405. });
  1406. await page.waitForTimeout(3000);
  1407. // 获取用户名
  1408. const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
  1409. if (nameEl) {
  1410. const text = await nameEl.textContent();
  1411. if (text?.trim()) {
  1412. accountName = text.trim();
  1413. }
  1414. }
  1415. // 获取头像
  1416. const avatarEl = await page.$('[class*="avatar"] img');
  1417. if (avatarEl) {
  1418. const src = await avatarEl.getAttribute('src');
  1419. if (src) {
  1420. avatarUrl = src;
  1421. }
  1422. }
  1423. } catch (error) {
  1424. logger.warn('Failed to fetch Kuaishou account info:', error);
  1425. }
  1426. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1427. }
  1428. /**
  1429. * 获取微信视频号账号信息
  1430. */
  1431. private async fetchWeixinVideoAccountInfo(
  1432. page: Page,
  1433. _context: BrowserContext,
  1434. cookies: CookieData[]
  1435. ): Promise<AccountInfo> {
  1436. let accountId = `weixin_video_${Date.now()}`;
  1437. let accountName = '视频号账号';
  1438. let avatarUrl = '';
  1439. let fansCount: number | undefined;
  1440. let worksCount = 0;
  1441. let finderId = '';
  1442. try {
  1443. // 从 Cookie 中提取用户标识
  1444. // 优先使用 finder_username(视频号唯一标识)
  1445. const finderUsernameCookie = cookies.find(c => c.name === 'finder_username');
  1446. if (finderUsernameCookie?.value) {
  1447. finderId = finderUsernameCookie.value;
  1448. accountId = `weixin_video_${finderId}`;
  1449. logger.info(`[WeixinVideo] Found finder_username from cookie: ${finderId}`);
  1450. }
  1451. // 备选:使用 wxuin 或 uin
  1452. if (!finderId) {
  1453. const uinCookie = cookies.find(c => c.name === 'wxuin' || c.name === 'uin');
  1454. if (uinCookie?.value) {
  1455. // 仍然保持时间戳格式,后续会尝试从页面获取真实 ID
  1456. accountId = `weixin_video_${uinCookie.value}`;
  1457. logger.info(`[WeixinVideo] Using uin from cookie: ${uinCookie.value}`);
  1458. }
  1459. }
  1460. // 访问视频号创作者平台首页
  1461. await page.goto('https://channels.weixin.qq.com/platform/home', {
  1462. waitUntil: 'domcontentloaded',
  1463. timeout: 30000,
  1464. });
  1465. await page.waitForTimeout(3000);
  1466. // 检查是否需要登录
  1467. const currentUrl = page.url();
  1468. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  1469. logger.warn('[WeixinVideo] Cookie expired, needs login');
  1470. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1471. }
  1472. // 从页面提取账号信息
  1473. const accountData = await page.evaluate(() => {
  1474. const result: { name?: string; avatar?: string; fans?: number; works?: number; finderId?: string } = {};
  1475. try {
  1476. // ===== 1. 优先使用精确选择器获取视频号 ID =====
  1477. // 方法1: 通过 #finder-uid-copy 的 data-clipboard-text 属性获取
  1478. const finderIdCopyEl = document.querySelector('#finder-uid-copy');
  1479. if (finderIdCopyEl) {
  1480. const clipboardText = finderIdCopyEl.getAttribute('data-clipboard-text');
  1481. if (clipboardText && clipboardText.length >= 10) {
  1482. result.finderId = clipboardText;
  1483. console.log('[WeixinVideo] Found finder ID from data-clipboard-text:', result.finderId);
  1484. } else {
  1485. // 备选:获取元素文本内容
  1486. const text = finderIdCopyEl.textContent?.trim();
  1487. if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
  1488. result.finderId = text;
  1489. console.log('[WeixinVideo] Found finder ID from #finder-uid-copy text:', result.finderId);
  1490. }
  1491. }
  1492. }
  1493. // 方法2: 通过 .finder-uniq-id 选择器获取
  1494. if (!result.finderId) {
  1495. const finderUniqIdEl = document.querySelector('.finder-uniq-id');
  1496. if (finderUniqIdEl) {
  1497. const clipboardText = finderUniqIdEl.getAttribute('data-clipboard-text');
  1498. if (clipboardText && clipboardText.length >= 10) {
  1499. result.finderId = clipboardText;
  1500. console.log('[WeixinVideo] Found finder ID from .finder-uniq-id data-clipboard-text:', result.finderId);
  1501. } else {
  1502. const text = finderUniqIdEl.textContent?.trim();
  1503. if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
  1504. result.finderId = text;
  1505. console.log('[WeixinVideo] Found finder ID from .finder-uniq-id text:', result.finderId);
  1506. }
  1507. }
  1508. }
  1509. }
  1510. // 方法3: 从页面文本中正则匹配
  1511. if (!result.finderId) {
  1512. const bodyText = document.body.innerText || '';
  1513. const finderIdPatterns = [
  1514. /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
  1515. /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
  1516. ];
  1517. for (const pattern of finderIdPatterns) {
  1518. const match = bodyText.match(pattern);
  1519. if (match && match[1] && match[1].length >= 10) {
  1520. result.finderId = match[1];
  1521. console.log('[WeixinVideo] Found finder ID from regex:', result.finderId);
  1522. break;
  1523. }
  1524. }
  1525. }
  1526. // ===== 2. 获取账号名称 =====
  1527. // 优先使用 h2.finder-nickname
  1528. const nicknameEl = document.querySelector('h2.finder-nickname') ||
  1529. document.querySelector('.finder-nickname');
  1530. if (nicknameEl) {
  1531. const text = nicknameEl.textContent?.trim();
  1532. if (text && text.length >= 2 && text.length <= 30) {
  1533. result.name = text;
  1534. console.log('[WeixinVideo] Found name from .finder-nickname:', result.name);
  1535. }
  1536. }
  1537. // 备选选择器
  1538. if (!result.name) {
  1539. const nameSelectors = [
  1540. '.account-name',
  1541. '[class*="nickname"]',
  1542. '[class*="userName"]',
  1543. ];
  1544. for (const selector of nameSelectors) {
  1545. const el = document.querySelector(selector);
  1546. const text = el?.textContent?.trim();
  1547. if (text && text.length >= 2 && text.length <= 30) {
  1548. result.name = text;
  1549. console.log('[WeixinVideo] Found name from selector:', selector, result.name);
  1550. break;
  1551. }
  1552. }
  1553. }
  1554. // ===== 3. 获取头像 =====
  1555. // 优先使用 img.avatar
  1556. const avatarEl = document.querySelector('img.avatar') as HTMLImageElement;
  1557. if (avatarEl?.src && avatarEl.src.startsWith('http')) {
  1558. result.avatar = avatarEl.src;
  1559. console.log('[WeixinVideo] Found avatar from img.avatar:', result.avatar);
  1560. }
  1561. // 备选选择器
  1562. if (!result.avatar) {
  1563. const avatarSelectors = [
  1564. '.finder-info-container img.avatar',
  1565. 'img[alt="视频号头像"]',
  1566. 'img[src*="wx.qlogo.cn/finderhead"]',
  1567. 'img[src*="wx.qlogo"]',
  1568. ];
  1569. for (const selector of avatarSelectors) {
  1570. const el = document.querySelector(selector) as HTMLImageElement;
  1571. if (el?.src && el.src.startsWith('http')) {
  1572. result.avatar = el.src;
  1573. console.log('[WeixinVideo] Found avatar from selector:', selector);
  1574. break;
  1575. }
  1576. }
  1577. }
  1578. // ===== 4. 获取视频数和关注者数 =====
  1579. // 使用 .finder-content-info 中的 .finder-info-num
  1580. const contentInfo = document.querySelector('.finder-content-info');
  1581. if (contentInfo) {
  1582. const infoDivs = contentInfo.querySelectorAll('div');
  1583. infoDivs.forEach(div => {
  1584. const text = div.textContent || '';
  1585. const numEl = div.querySelector('.finder-info-num');
  1586. if (numEl) {
  1587. const num = parseInt(numEl.textContent?.trim() || '0', 10);
  1588. if (text.includes('视频') || text.includes('作品')) {
  1589. result.works = num;
  1590. console.log('[WeixinVideo] Found works from .finder-info-num:', result.works);
  1591. } else if (text.includes('关注者') || text.includes('粉丝')) {
  1592. result.fans = num;
  1593. console.log('[WeixinVideo] Found fans from .finder-info-num:', result.fans);
  1594. }
  1595. }
  1596. });
  1597. }
  1598. // 备选:从页面整体文本中匹配
  1599. if (result.fans === undefined || result.works === undefined) {
  1600. const bodyText = document.body.innerText || '';
  1601. if (result.fans === undefined) {
  1602. const fansMatch = bodyText.match(/关注者\s*(\d+(?:\.\d+)?[万wW]?)/) ||
  1603. bodyText.match(/粉丝\s*(\d+(?:\.\d+)?[万wW]?)/);
  1604. if (fansMatch) {
  1605. let count = parseFloat(fansMatch[1]);
  1606. if (fansMatch[1].includes('万') || fansMatch[1].toLowerCase().includes('w')) {
  1607. count = count * 10000;
  1608. }
  1609. result.fans = Math.floor(count);
  1610. console.log('[WeixinVideo] Found fans from text:', result.fans);
  1611. }
  1612. }
  1613. if (result.works === undefined) {
  1614. const worksMatch = bodyText.match(/视频\s*(\d+)/) ||
  1615. bodyText.match(/作品\s*(\d+)/);
  1616. if (worksMatch) {
  1617. result.works = parseInt(worksMatch[1], 10);
  1618. console.log('[WeixinVideo] Found works from text:', result.works);
  1619. }
  1620. }
  1621. }
  1622. } catch (e) {
  1623. console.error('[WeixinVideo] Extract error:', e);
  1624. }
  1625. return result;
  1626. });
  1627. logger.info(`[WeixinVideo] Extracted account data from home page:`, accountData);
  1628. // 更新账号信息
  1629. if (accountData.name) {
  1630. accountName = accountData.name;
  1631. }
  1632. if (accountData.avatar) {
  1633. avatarUrl = accountData.avatar;
  1634. }
  1635. if (accountData.fans !== undefined) {
  1636. fansCount = accountData.fans;
  1637. }
  1638. if (accountData.works !== undefined) {
  1639. worksCount = accountData.works;
  1640. }
  1641. if (accountData.finderId) {
  1642. finderId = accountData.finderId;
  1643. accountId = `weixin_video_${accountData.finderId}`;
  1644. }
  1645. // 如果首页没有获取到视频号 ID,尝试访问账号设置页面
  1646. if (!finderId || finderId.length < 10) {
  1647. logger.info('[WeixinVideo] Finder ID not found on home page, trying account settings page...');
  1648. try {
  1649. // 访问账号设置页面
  1650. await page.goto('https://channels.weixin.qq.com/platform/account', {
  1651. waitUntil: 'domcontentloaded',
  1652. timeout: 30000,
  1653. });
  1654. await page.waitForTimeout(2000);
  1655. // 从账号设置页面提取视频号 ID
  1656. const settingsData = await page.evaluate(() => {
  1657. const result: { finderId?: string; name?: string } = {};
  1658. const bodyText = document.body.innerText || '';
  1659. // 尝试多种匹配模式
  1660. const patterns = [
  1661. /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
  1662. /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
  1663. /视频号[::\s]+([a-zA-Z0-9_]{10,})/,
  1664. /Finder\s*ID[::\s]*([a-zA-Z0-9_]+)/i,
  1665. /finder_username[::\s]*([a-zA-Z0-9_]+)/i,
  1666. /唯一标识[::\s]*([a-zA-Z0-9_]+)/,
  1667. ];
  1668. for (const pattern of patterns) {
  1669. const match = bodyText.match(pattern);
  1670. if (match && match[1]) {
  1671. result.finderId = match[1];
  1672. console.log('[WeixinVideo] Found finder ID from settings page:', result.finderId);
  1673. break;
  1674. }
  1675. }
  1676. // 从元素中查找
  1677. if (!result.finderId) {
  1678. const idSelectors = [
  1679. '[class*="finder-id"]',
  1680. '[class*="account-id"]',
  1681. '[class*="unique-id"]',
  1682. '.finder-uniq-id',
  1683. 'span.finder-uniq-id',
  1684. '[class*="copy-id"]',
  1685. ];
  1686. for (const selector of idSelectors) {
  1687. const el = document.querySelector(selector);
  1688. const text = el?.textContent?.trim();
  1689. if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10 && text.length <= 30) {
  1690. result.finderId = text;
  1691. console.log('[WeixinVideo] Found ID from settings selector:', result.finderId);
  1692. break;
  1693. }
  1694. }
  1695. }
  1696. return result;
  1697. });
  1698. logger.info(`[WeixinVideo] Extracted data from settings page:`, settingsData);
  1699. if (settingsData.finderId) {
  1700. finderId = settingsData.finderId;
  1701. accountId = `weixin_video_${settingsData.finderId}`;
  1702. }
  1703. } catch (settingsError) {
  1704. logger.warn('[WeixinVideo] Failed to fetch from settings page:', settingsError);
  1705. }
  1706. }
  1707. logger.info(`[WeixinVideo] Final account info: id=${accountId}, name=${accountName}, avatar=${avatarUrl ? 'yes' : 'no'}, fans=${fansCount}`);
  1708. } catch (error) {
  1709. logger.warn('Failed to fetch WeixinVideo account info:', error);
  1710. }
  1711. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  1712. }
  1713. /**
  1714. * 获取小红书账号信息 - 通过 API 方式获取
  1715. */
  1716. private async fetchXiaohongshuAccountInfo(
  1717. page: Page,
  1718. _context: BrowserContext,
  1719. cookies: CookieData[]
  1720. ): Promise<AccountInfo> {
  1721. let accountId = `xiaohongshu_${Date.now()}`;
  1722. let accountName = '小红书账号';
  1723. let avatarUrl = '';
  1724. let fansCount: number | undefined;
  1725. let worksCount = 0;
  1726. // 用于存储捕获的数据
  1727. const capturedData: {
  1728. userInfo?: {
  1729. nickname?: string;
  1730. avatar?: string;
  1731. userId?: string;
  1732. redId?: string;
  1733. fans?: number;
  1734. notes?: number;
  1735. };
  1736. } = {};
  1737. try {
  1738. // 从 Cookie 获取用户 ID
  1739. const userIdCookie = cookies.find(c =>
  1740. c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
  1741. );
  1742. if (userIdCookie?.value) {
  1743. accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
  1744. }
  1745. // 设置 API 响应监听器
  1746. page.on('response', async (response) => {
  1747. const url = response.url();
  1748. try {
  1749. // 监听用户信息 API
  1750. if (url.includes('/api/galaxy/creator/home/personal_info') ||
  1751. url.includes('/api/sns/web/v1/user/selfinfo') ||
  1752. url.includes('/user/selfinfo')) {
  1753. const data = await response.json();
  1754. logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));
  1755. // 解析用户信息
  1756. const userInfo = data?.data?.user_info || data?.data || data;
  1757. if (userInfo) {
  1758. capturedData.userInfo = {
  1759. nickname: userInfo.nickname || userInfo.name || userInfo.userName,
  1760. avatar: userInfo.image || userInfo.avatar || userInfo.images,
  1761. userId: userInfo.user_id || userInfo.userId,
  1762. redId: userInfo.red_id || userInfo.redId,
  1763. fans: userInfo.fans ?? userInfo.fansCount,
  1764. notes: userInfo.notes ?? userInfo.noteCount,
  1765. };
  1766. logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
  1767. }
  1768. }
  1769. // 监听创作者主页数据
  1770. if (url.includes('/api/galaxy/creator/home/home_page') ||
  1771. url.includes('/api/galaxy/creator/data')) {
  1772. const data = await response.json();
  1773. logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));
  1774. if (data?.data) {
  1775. const homeData = data.data;
  1776. // 获取粉丝数和笔记数
  1777. if (homeData.fans_count !== undefined) {
  1778. capturedData.userInfo = capturedData.userInfo || {};
  1779. capturedData.userInfo.fans = homeData.fans_count;
  1780. }
  1781. if (homeData.note_count !== undefined) {
  1782. capturedData.userInfo = capturedData.userInfo || {};
  1783. capturedData.userInfo.notes = homeData.note_count;
  1784. }
  1785. }
  1786. }
  1787. } catch {
  1788. // 忽略非 JSON 响应
  1789. }
  1790. });
  1791. // 导航到小红书创作者中心
  1792. logger.info('[Xiaohongshu] Navigating to creator center...');
  1793. await page.goto('https://creator.xiaohongshu.com/creator/home', {
  1794. waitUntil: 'domcontentloaded',
  1795. timeout: 30000,
  1796. });
  1797. // 等待页面加载
  1798. await page.waitForTimeout(3000);
  1799. // 检查是否需要登录
  1800. const currentUrl = page.url();
  1801. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  1802. logger.warn('[Xiaohongshu] Cookie expired, needs login');
  1803. // 返回空信息,fansCount 为 undefined,避免重置为 0
  1804. return { accountId, accountName, avatarUrl, fansCount: undefined, worksCount: 0 };
  1805. }
  1806. // 等待 API 响应
  1807. await page.waitForTimeout(3000);
  1808. // 如果 API 没有捕获到数据,尝试从页面提取
  1809. if (!capturedData.userInfo?.nickname) {
  1810. logger.info('[Xiaohongshu] API did not return data, extracting from page...');
  1811. // 尝试获取用户名
  1812. const nameSelectors = [
  1813. '[class*="nickname"]',
  1814. '[class*="user-name"]',
  1815. '[class*="userName"]',
  1816. '.user-info .name',
  1817. '[class*="creator"] [class*="name"]',
  1818. ];
  1819. for (const selector of nameSelectors) {
  1820. const el = await page.$(selector);
  1821. if (el) {
  1822. const text = await el.textContent();
  1823. if (text?.trim() && text.trim().length < 50) {
  1824. accountName = text.trim();
  1825. logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
  1826. break;
  1827. }
  1828. }
  1829. }
  1830. // 尝试获取头像
  1831. const avatarSelectors = [
  1832. '[class*="avatar"] img',
  1833. '[class*="user-avatar"] img',
  1834. '.user-info img',
  1835. '[class*="creator"] img[src*="sns"]',
  1836. ];
  1837. for (const selector of avatarSelectors) {
  1838. const el = await page.$(selector);
  1839. if (el) {
  1840. const src = await el.getAttribute('src');
  1841. if (src && src.startsWith('http')) {
  1842. avatarUrl = src;
  1843. logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
  1844. break;
  1845. }
  1846. }
  1847. }
  1848. // 尝试获取粉丝数
  1849. const statsText = await page.textContent('body');
  1850. const fansMatch = statsText?.match(/粉丝[::\s]*(\d+(?:\.\d+)?[万亿]?)/);
  1851. if (fansMatch) {
  1852. fansCount = this.parseChineseNumber(fansMatch[1]);
  1853. logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
  1854. }
  1855. const notesMatch = statsText?.match(/笔记[::\s]*(\d+)/);
  1856. if (notesMatch) {
  1857. worksCount = parseInt(notesMatch[1], 10);
  1858. logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
  1859. }
  1860. }
  1861. // 使用捕获的数据
  1862. if (capturedData.userInfo) {
  1863. if (capturedData.userInfo.nickname) {
  1864. accountName = capturedData.userInfo.nickname;
  1865. }
  1866. if (capturedData.userInfo.avatar) {
  1867. avatarUrl = capturedData.userInfo.avatar;
  1868. }
  1869. // 优先使用小红书号(redId)作为 accountId
  1870. if (capturedData.userInfo.redId) {
  1871. accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
  1872. logger.info(`[Xiaohongshu] Using redId as accountId: ${accountId}`);
  1873. } else if (capturedData.userInfo.userId) {
  1874. accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
  1875. }
  1876. if (capturedData.userInfo.fans !== undefined) {
  1877. fansCount = capturedData.userInfo.fans;
  1878. }
  1879. if (capturedData.userInfo.notes !== undefined) {
  1880. worksCount = capturedData.userInfo.notes;
  1881. }
  1882. }
  1883. // 如果还没获取到小红书号,尝试从页面文本中提取
  1884. if (!accountId.match(/xiaohongshu_[a-zA-Z0-9_]+/) || accountId.includes('_' + Date.now().toString().slice(0, 8))) {
  1885. const bodyText = await page.textContent('body');
  1886. // 匹配小红书号格式:小红书号:xxxxxxx
  1887. const xhsIdMatch = bodyText?.match(/小红书号[::]\s*([a-zA-Z0-9_]+)/) ||
  1888. bodyText?.match(/红书号[::]\s*([a-zA-Z0-9_]+)/);
  1889. if (xhsIdMatch) {
  1890. accountId = `xiaohongshu_${xhsIdMatch[1]}`;
  1891. logger.info(`[Xiaohongshu] Found 小红书号 from page text: ${accountId}`);
  1892. }
  1893. }
  1894. logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
  1895. // 获取作品列表 - 通过监听 API 接口
  1896. const worksList: WorkItem[] = [];
  1897. let worksListComplete: boolean | undefined;
  1898. try {
  1899. logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');
  1900. // 存储所有捕获的笔记数据
  1901. const allNotesData: Array<{
  1902. noteId: string;
  1903. title: string;
  1904. coverUrl: string;
  1905. status: number;
  1906. publishTime: string;
  1907. type: string;
  1908. duration: number;
  1909. likeCount: number;
  1910. commentCount: number;
  1911. collectCount: number;
  1912. viewCount: number;
  1913. shareCount: number;
  1914. }> = [];
  1915. let maxPages = 120;
  1916. // 设置 API 响应监听器 - 在导航之前绑定
  1917. let apiResponseReceived = false;
  1918. let totalNotesCount = 0; // 从 tags 中获取的总作品数
  1919. let stoppedByMaxPages = false;
  1920. const seenNoteIds = new Set<string>();
  1921. const upsertNotesFromPayload = (payload: any) => {
  1922. if (!payload) return;
  1923. const declaredTotal = extractDeclaredNotesCountFromPostedResponse(payload);
  1924. if (declaredTotal > 0) {
  1925. totalNotesCount = Math.max(totalNotesCount, declaredTotal);
  1926. }
  1927. if (totalNotesCount > 0) {
  1928. const estimatedPages = Math.ceil(totalNotesCount / 20) + 5;
  1929. maxPages = Math.max(maxPages, Math.min(500, estimatedPages));
  1930. }
  1931. const notes = payload.notes || [];
  1932. for (const note of notes) {
  1933. const noteId = note.id || '';
  1934. if (!noteId || seenNoteIds.has(noteId)) continue;
  1935. seenNoteIds.add(noteId);
  1936. let coverUrl = note.images_list?.[0]?.url || '';
  1937. if (coverUrl.startsWith('http://')) {
  1938. coverUrl = coverUrl.replace('http://', 'https://');
  1939. }
  1940. const duration = note.video_info?.duration || 0;
  1941. allNotesData.push({
  1942. noteId,
  1943. title: note.display_title || '',
  1944. coverUrl,
  1945. status: note.tab_status || 1,
  1946. publishTime: note.time || '',
  1947. type: note.type || 'normal',
  1948. duration,
  1949. likeCount: note.likes || 0,
  1950. commentCount: note.comments_count || 0,
  1951. collectCount: note.collected_count || 0,
  1952. viewCount: note.view_count || 0,
  1953. shareCount: note.shared_count || 0,
  1954. });
  1955. }
  1956. };
  1957. const fetchNotesPage = async (pageNum: number) => {
  1958. return await page.evaluate(async (p) => {
  1959. const response = await fetch(
  1960. `https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}`,
  1961. {
  1962. method: 'GET',
  1963. credentials: 'include',
  1964. headers: {
  1965. Accept: 'application/json',
  1966. },
  1967. }
  1968. );
  1969. return await response.json();
  1970. }, pageNum);
  1971. };
  1972. const notesApiHandler = async (response: import('playwright').Response) => {
  1973. const url = response.url();
  1974. try {
  1975. // 监听小红书笔记列表 API
  1976. // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
  1977. if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
  1978. url.includes('/api/sns/v5/creator/note/user/posted') ||
  1979. url.includes('creator/note/user/posted')) {
  1980. const data = await response.json();
  1981. logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);
  1982. if ((data?.success || data?.code === 0) && data?.data) {
  1983. apiResponseReceived = true;
  1984. upsertNotesFromPayload(data.data);
  1985. } else {
  1986. }
  1987. }
  1988. } catch (e) {
  1989. // 只在有相关 URL 时打印警告
  1990. if (url.includes('creator/note')) {
  1991. logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
  1992. }
  1993. }
  1994. };
  1995. // 先绑定监听器
  1996. page.on('response', notesApiHandler);
  1997. logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');
  1998. // 导航到笔记管理页面 - 使用 domcontentloaded 加快加载,避免 networkidle 超时
  1999. try {
  2000. await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
  2001. waitUntil: 'domcontentloaded',
  2002. timeout: 30000,
  2003. });
  2004. } catch (navError) {
  2005. // 导航超时不影响已捕获的 API 数据
  2006. logger.warn('[Xiaohongshu] Navigation timeout, but API data may have been captured');
  2007. }
  2008. // 等待 API 响应
  2009. await page.waitForTimeout(5000);
  2010. logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);
  2011. // 如果监听器没有捕获到数据,尝试直接调用 API
  2012. if (allNotesData.length === 0) {
  2013. logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');
  2014. try {
  2015. const apiResponse = await fetchNotesPage(0);
  2016. logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
  2017. if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
  2018. upsertNotesFromPayload(apiResponse.data);
  2019. }
  2020. } catch (apiError) {
  2021. logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
  2022. }
  2023. }
  2024. if (allNotesData.length > 0) {
  2025. let pageNum = 1;
  2026. while (pageNum < maxPages) {
  2027. if (totalNotesCount > 0 && seenNoteIds.size >= totalNotesCount) break;
  2028. let nextResponse: any;
  2029. try {
  2030. nextResponse = await fetchNotesPage(pageNum);
  2031. } catch (e) {
  2032. logger.warn(`[Xiaohongshu] Page fetch failed: page=${pageNum}`, e);
  2033. break;
  2034. }
  2035. if (!(nextResponse?.success || nextResponse?.code === 0) || !nextResponse?.data) break;
  2036. const before = seenNoteIds.size;
  2037. upsertNotesFromPayload(nextResponse.data);
  2038. const after = seenNoteIds.size;
  2039. if (after === before) break;
  2040. pageNum++;
  2041. await page.waitForTimeout(600);
  2042. }
  2043. if (pageNum >= maxPages) stoppedByMaxPages = true;
  2044. }
  2045. // 移除监听器
  2046. page.off('response', notesApiHandler);
  2047. logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);
  2048. // 转换为 WorkItem 格式
  2049. for (const note of allNotesData) {
  2050. // 转换时长为 mm:ss 格式
  2051. const minutes = Math.floor(note.duration / 60);
  2052. const seconds = note.duration % 60;
  2053. const durationStr = note.duration > 0
  2054. ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  2055. : '';
  2056. // 转换状态
  2057. let statusStr = 'published';
  2058. if (note.status === 0) statusStr = 'draft';
  2059. else if (note.status === 2) statusStr = 'reviewing';
  2060. else if (note.status === 3) statusStr = 'rejected';
  2061. worksList.push({
  2062. videoId: note.noteId,
  2063. title: note.title || '无标题',
  2064. coverUrl: note.coverUrl,
  2065. videoUrl: note.noteId ? `https://www.xiaohongshu.com/explore/${note.noteId}` : '',
  2066. duration: durationStr,
  2067. publishTime: note.publishTime,
  2068. status: statusStr,
  2069. playCount: note.viewCount,
  2070. likeCount: note.likeCount,
  2071. commentCount: note.commentCount,
  2072. shareCount: note.shareCount,
  2073. });
  2074. }
  2075. logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);
  2076. if (totalNotesCount > 0) {
  2077. worksListComplete = worksList.length >= totalNotesCount;
  2078. worksCount = totalNotesCount;
  2079. } else if (worksList.length > 0) {
  2080. worksListComplete = !stoppedByMaxPages;
  2081. worksCount = worksList.length;
  2082. }
  2083. } catch (worksError) {
  2084. logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
  2085. }
  2086. logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
  2087. return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList, worksListComplete };
  2088. } catch (error) {
  2089. logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
  2090. }
  2091. return { accountId, accountName, avatarUrl, fansCount, worksCount };
  2092. }
  2093. /**
  2094. * 解析中文数字(如 1.2万 -> 12000)
  2095. */
  2096. private parseChineseNumber(str: string): number {
  2097. if (!str) return 0;
  2098. let num = parseFloat(str);
  2099. if (str.includes('万')) {
  2100. num *= 10000;
  2101. } else if (str.includes('亿')) {
  2102. num *= 100000000;
  2103. }
  2104. return Math.floor(num);
  2105. }
  2106. /**
  2107. * 获取平台配置
  2108. */
  2109. private getPlatformConfig(platform: PlatformType) {
  2110. const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
  2111. douyin: {
  2112. homeUrl: 'https://creator.douyin.com/creator-micro/home',
  2113. loginIndicators: ['login', 'passport', 'sso'],
  2114. },
  2115. bilibili: {
  2116. homeUrl: 'https://member.bilibili.com/platform/home',
  2117. loginIndicators: ['passport.bilibili.com', 'login'],
  2118. },
  2119. kuaishou: {
  2120. homeUrl: 'https://cp.kuaishou.com/profile',
  2121. loginIndicators: ['passport.kuaishou.com', 'login'],
  2122. },
  2123. xiaohongshu: {
  2124. homeUrl: 'https://creator.xiaohongshu.com/',
  2125. loginIndicators: ['login', 'passport'],
  2126. },
  2127. weixin_video: {
  2128. homeUrl: 'https://channels.weixin.qq.com/platform',
  2129. loginIndicators: ['login.html', '/login', 'passport'],
  2130. },
  2131. baijiahao: {
  2132. homeUrl: 'https://baijiahao.baidu.com/builder/rc/home',
  2133. loginIndicators: ['login', 'passport'],
  2134. },
  2135. toutiao: {
  2136. homeUrl: 'https://mp.toutiao.com/profile_v4/index',
  2137. loginIndicators: ['login', 'passport', 'sso'],
  2138. },
  2139. weibo: {
  2140. homeUrl: 'https://weibo.com/u/',
  2141. loginIndicators: ['login', 'passport'],
  2142. },
  2143. dayu: {
  2144. homeUrl: 'https://mp.dayu.com/',
  2145. loginIndicators: ['login', 'passport'],
  2146. },
  2147. };
  2148. return configs[platform] || { homeUrl: '', loginIndicators: ['login'] };
  2149. }
  2150. /**
  2151. * 百家号 - 直接通过 API 获取账号信息和作品列表
  2152. */
  2153. private async fetchBaijiahaoAccountInfoDirectApi(cookies: CookieData[]): Promise<AccountInfo> {
  2154. logger.info(`[Baijiahao API] Fetching account info via direct API...`);
  2155. // 构建 Cookie 字符串,确保格式正确
  2156. const cookieString = cookies
  2157. .map(c => `${c.name.trim()}=${c.value.trim()}`)
  2158. .filter(c => c.includes('=')) // 过滤掉无效的 cookie
  2159. .join('; ');
  2160. logger.debug(`[Baijiahao API] Cookie string length: ${cookieString.length}, cookie count: ${cookies.length}`);
  2161. const headers: Record<string, string> = {
  2162. 'Accept': '*/*',
  2163. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  2164. 'Accept-Encoding': 'gzip, deflate, br',
  2165. 'Connection': 'keep-alive',
  2166. 'Cookie': cookieString,
  2167. // 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
  2168. // 'Origin': 'https://baijiahao.baidu.com',
  2169. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2170. // 'Sec-Fetch-Dest': 'empty',
  2171. // 'Sec-Fetch-Mode': 'cors',
  2172. // 'Sec-Fetch-Site': 'same-origin',
  2173. };
  2174. let accountInfo: AccountInfo = this.getDefaultAccountInfo('baijiahao');
  2175. // 标记哪些字段已成功获取
  2176. let fansCountFetched = false;
  2177. let worksCountFetched = false;
  2178. try {
  2179. // 1. 获取账号基本信息 (appinfo API)
  2180. logger.info(`[Baijiahao API] Step 1: Fetching appinfo...`);
  2181. const appInfoResponse = await fetch('https://baijiahao.baidu.com/builder/app/appinfo', {
  2182. method: 'GET',
  2183. headers,
  2184. });
  2185. if (!appInfoResponse.ok) {
  2186. logger.error(`[Baijiahao API] appinfo request failed: ${appInfoResponse.status}`);
  2187. throw new Error(`appinfo request failed: ${appInfoResponse.status}`);
  2188. }
  2189. const appInfoData = await appInfoResponse.json() as {
  2190. errno?: number;
  2191. errmsg?: string;
  2192. data?: {
  2193. user?: {
  2194. name?: string;
  2195. avatar?: string;
  2196. app_id?: string | number;
  2197. userid?: number;
  2198. status?: string;
  2199. };
  2200. };
  2201. };
  2202. logger.info(`[Baijiahao API] appinfo response: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
  2203. if (appInfoData.errno !== 0) {
  2204. logger.error(`[Baijiahao API] appinfo API error: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
  2205. throw new Error(`appinfo API error: ${appInfoData.errmsg || 'Unknown error'}`);
  2206. }
  2207. if (!appInfoData.data?.user) {
  2208. logger.error(`[Baijiahao API] No user data in appinfo response`);
  2209. throw new Error('No user data in appinfo response');
  2210. }
  2211. const user = appInfoData.data.user;
  2212. accountInfo.accountId = user.app_id ? `bjh_${user.app_id}` : accountInfo.accountId;
  2213. accountInfo.accountName = user.name || accountInfo.accountName;
  2214. // 处理头像 URL(可能是相对路径)
  2215. if (user.avatar) {
  2216. accountInfo.avatarUrl = user.avatar.startsWith('http')
  2217. ? user.avatar
  2218. : `https:${user.avatar}`;
  2219. }
  2220. logger.info(`[Baijiahao API] Got account info: name=${accountInfo.accountName}, id=${accountInfo.accountId}, avatar=${accountInfo.avatarUrl}`);
  2221. // 2. 获取粉丝数 (growthInfo API)
  2222. logger.info(`[Baijiahao API] Step 2: Fetching growth info...`);
  2223. try {
  2224. const growthInfoResponse = await fetch('https://baijiahao.baidu.com/cms-ui/rights/growth/get_info', {
  2225. method: 'GET',
  2226. headers,
  2227. });
  2228. if (growthInfoResponse.ok) {
  2229. const growthData = await growthInfoResponse.json() as {
  2230. errno?: number;
  2231. errmsg?: string;
  2232. data?: {
  2233. total_fans?: number;
  2234. };
  2235. };
  2236. logger.info(`[Baijiahao API] growth info response: errno=${growthData.errno}`);
  2237. if (growthData.errno === 0 && growthData.data) {
  2238. const fansCount = growthData.data.total_fans;
  2239. if (fansCount !== undefined && fansCount !== null) {
  2240. accountInfo.fansCount = fansCount;
  2241. fansCountFetched = true;
  2242. logger.info(`[Baijiahao API] Got fans count: ${accountInfo.fansCount}`);
  2243. } else {
  2244. logger.warn(`[Baijiahao API] growth info API returned no fans count`);
  2245. }
  2246. } else {
  2247. logger.warn(`[Baijiahao API] growth info API error: errno=${growthData.errno}, errmsg=${growthData.errmsg}`);
  2248. }
  2249. } else {
  2250. logger.warn(`[Baijiahao API] growth info request failed: ${growthInfoResponse.status}`);
  2251. }
  2252. } catch (growthError) {
  2253. logger.warn(`[Baijiahao API] Failed to fetch growth info (non-critical):`, growthError);
  2254. // 粉丝数获取失败不影响整体流程
  2255. }
  2256. // 3. 获取作品列表 (分页获取所有作品)
  2257. logger.info(`[Baijiahao API] Step 3: Fetching works list...`);
  2258. setTimeout(() => {
  2259. console.log('1000ms');
  2260. }, 1000);
  2261. const worksList: WorkItem[] = [];
  2262. let currentPage = 1;
  2263. const pageSize = 20;
  2264. let hasMore = true;
  2265. let totalWorks = 0;
  2266. let worksListError = false;
  2267. while (hasMore && !worksListError) {
  2268. try {
  2269. const listUrl = `https://baijiahao.baidu.com/pcui/article/lists?currentPage=${currentPage}&pageSize=${pageSize}&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0`;
  2270. logger.info(`[Baijiahao API] Fetching works page ${currentPage}...`);
  2271. logger.debug(`[Baijiahao API] Request headers include Cookie: ${!!headers.Cookie}, Cookie length: ${headers.Cookie?.length || 0}`);
  2272. const listResponse = await fetch(listUrl, {
  2273. method: 'GET',
  2274. headers,
  2275. });
  2276. if (!listResponse.ok) {
  2277. const errorText = await listResponse.text();
  2278. logger.warn(`[Baijiahao API] Failed to fetch works list page ${currentPage}: ${listResponse.status}`);
  2279. logger.warn(`[Baijiahao API] Error response body: ${errorText}`);
  2280. break;
  2281. }
  2282. const responseText = await listResponse.text();
  2283. logger.info(`[Baijiahao API] ========== Works API Response (Page ${currentPage}) ==========`);
  2284. logger.info(`[Baijiahao API] Full response: ${responseText}`);
  2285. logger.info(`[Baijiahao API] ============================================================`);
  2286. const listData = JSON.parse(responseText) as {
  2287. errno?: number;
  2288. errmsg?: string;
  2289. data?: {
  2290. list?: Array<{
  2291. id?: string;
  2292. article_id?: string;
  2293. title?: string;
  2294. cover_images?: string | string[];
  2295. created_at?: string;
  2296. create_time?: string;
  2297. status?: string;
  2298. read_amount?: number;
  2299. read_count?: number;
  2300. like_amount?: number;
  2301. like_count?: number;
  2302. comment_amount?: number;
  2303. comment_count?: number;
  2304. share_amount?: number;
  2305. share_count?: number;
  2306. }>;
  2307. page?: {
  2308. currentPage?: number;
  2309. pageSize?: number;
  2310. totalCount?: number;
  2311. totalPage?: number;
  2312. };
  2313. total?: number; // 兼容旧格式
  2314. };
  2315. };
  2316. // 处理分散认证问题 (errno=10001402),重试一次
  2317. if (listData.errno === 10001402) {
  2318. logger.warn(`[Baijiahao API] Dispersed authentication issue (errno=10001402) on page ${currentPage}, retrying after 3 seconds...`);
  2319. logger.debug(`[Baijiahao API] Request URL: ${listUrl}`);
  2320. logger.debug(`[Baijiahao API] Cookie header present: ${!!headers.Cookie}, length: ${headers.Cookie?.length || 0}`);
  2321. await new Promise(resolve => setTimeout(resolve, 3000));
  2322. // 重试一次,确保 headers 包含 Cookie
  2323. const retryResponse = await fetch(listUrl, {
  2324. method: 'GET',
  2325. headers: {
  2326. ...headers,
  2327. 'Cookie': cookieString, // 确保 Cookie 被正确传递
  2328. },
  2329. });
  2330. if (retryResponse.ok) {
  2331. const retryResponseText = await retryResponse.text();
  2332. logger.info(`[Baijiahao API] ========== Works API Retry Response (Page ${currentPage}) ==========`);
  2333. logger.info(`[Baijiahao API] Full retry response: ${retryResponseText}`);
  2334. logger.info(`[Baijiahao API] ============================================================`);
  2335. const retryData = JSON.parse(retryResponseText) as typeof listData;
  2336. if (retryData.errno === 0) {
  2337. logger.info(`[Baijiahao API] Retry successful for page ${currentPage}`);
  2338. Object.assign(listData, retryData);
  2339. } else if (retryData.errno === 10001402) {
  2340. logger.error(`[Baijiahao API] Retry still failed with errno=10001402, cookie may be invalid or expired`);
  2341. logger.error(`[Baijiahao API] Retry response data: ${JSON.stringify(retryData, null, 2)}`);
  2342. // 如果重试仍然失败,可能是 Cookie 问题,记录详细信息
  2343. logger.error(`[Baijiahao API] Cookie info: ${cookieString.substring(0, 200)}...`);
  2344. // 标记错误,但不完全失败,继续返回已获取的账号信息
  2345. worksListError = true;
  2346. logger.warn(`[Baijiahao API] Works list fetch failed, but will return other account info (name, fans count)`);
  2347. break;
  2348. } else {
  2349. logger.warn(`[Baijiahao API] Retry still failed: errno=${retryData.errno}, errmsg=${retryData.errmsg}`);
  2350. break;
  2351. }
  2352. } else {
  2353. logger.warn(`[Baijiahao API] Retry request failed: ${retryResponse.status}`);
  2354. break;
  2355. }
  2356. }
  2357. if (listData.errno !== 0) {
  2358. logger.warn(`[Baijiahao API] API returned error on page ${currentPage}: errno=${listData.errno}, errmsg=${listData.errmsg}`);
  2359. logger.warn(`[Baijiahao API] Error response data: ${JSON.stringify(listData, null, 2)}`);
  2360. // 如果不是 10001402 错误,标记为错误但继续返回其他信息
  2361. if (listData.errno !== 10001402) {
  2362. worksListError = true;
  2363. logger.warn(`[Baijiahao API] Works list fetch failed with errno=${listData.errno}, but will return other account info`);
  2364. }
  2365. break;
  2366. }
  2367. const list = listData.data?.list || [];
  2368. // 优先使用 data.page.totalCount,如果没有则使用 data.total(兼容旧格式)
  2369. totalWorks = listData.data?.page?.totalCount || listData.data?.total || 0;
  2370. logger.info(`[Baijiahao API] Got ${list.length} works on page ${currentPage}, total: ${totalWorks}`);
  2371. for (const item of list) {
  2372. // 处理 cover_images 可能是字符串(JSON)或数组
  2373. let coverUrl = '';
  2374. if (item.cover_images) {
  2375. if (Array.isArray(item.cover_images)) {
  2376. coverUrl = item.cover_images[0] || '';
  2377. } else if (typeof item.cover_images === 'string') {
  2378. try {
  2379. const coverArray = JSON.parse(item.cover_images);
  2380. if (Array.isArray(coverArray) && coverArray.length > 0) {
  2381. coverUrl = typeof coverArray[0] === 'string' ? coverArray[0] : coverArray[0]?.src || coverArray[0]?.ori_src || '';
  2382. }
  2383. } catch {
  2384. coverUrl = item.cover_images;
  2385. }
  2386. }
  2387. }
  2388. worksList.push({
  2389. videoId: item.id || item.article_id || `bjh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
  2390. title: item.title || '',
  2391. coverUrl: coverUrl,
  2392. videoUrl: item.url || item.article_url || '',
  2393. duration: '00:00',
  2394. publishTime: item.created_at || item.create_time || new Date().toISOString(),
  2395. status: item.status || 'published',
  2396. playCount: item.read_amount || item.read_count || 0,
  2397. likeCount: item.like_amount || item.like_count || 0,
  2398. commentCount: item.comment_amount || item.comment_count || 0,
  2399. shareCount: item.share_amount || item.share_count || 0,
  2400. });
  2401. }
  2402. // 检查是否还有更多
  2403. if (list.length < pageSize) {
  2404. hasMore = false;
  2405. logger.info(`[Baijiahao API] No more works, stopping at page ${currentPage}`);
  2406. } else {
  2407. currentPage++;
  2408. // 防止无限循环,最多获取 10 页(200 个作品)
  2409. if (currentPage > 10) {
  2410. logger.warn(`[Baijiahao API] Reached max pages (10), stopping. Total fetched: ${worksList.length}, API total: ${totalWorks}`);
  2411. hasMore = false;
  2412. }
  2413. }
  2414. } catch (pageError) {
  2415. logger.error(`[Baijiahao API] Error fetching page ${currentPage}:`, pageError);
  2416. break;
  2417. }
  2418. }
  2419. accountInfo.worksList = worksList;
  2420. // 使用 API 返回的 total 字段作为作品总数,而不是已获取的作品列表长度
  2421. // 因为可能只获取了部分作品(最多 10 页),但 total 是真实的总数
  2422. if (totalWorks > 0) {
  2423. accountInfo.worksCount = totalWorks;
  2424. worksCountFetched = true;
  2425. } else if (worksList.length > 0) {
  2426. // 如果 API 没有返回 total,但获取到了作品列表,使用列表长度
  2427. accountInfo.worksCount = worksList.length;
  2428. worksCountFetched = true;
  2429. }
  2430. if (worksListError) {
  2431. logger.warn(`[Baijiahao API] Works list fetch encountered errors, but returning partial account info`);
  2432. logger.info(`[Baijiahao API] Account info (partial): name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched})`);
  2433. } else {
  2434. logger.info(`[Baijiahao API] Successfully fetched account info: name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched}, API total: ${totalWorks}, fetched list: ${worksList.length})`);
  2435. }
  2436. return accountInfo;
  2437. } catch (error) {
  2438. logger.error(`[Baijiahao API] Failed to fetch account info:`, error);
  2439. // 返回默认信息,但保留已获取的部分数据
  2440. return accountInfo;
  2441. }
  2442. }
  2443. /**
  2444. * 通过 Python API 获取账号信息
  2445. */
  2446. private async fetchAccountInfoViaPython(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
  2447. logger.info(`[Python API] Fetching account info for ${platform}...`);
  2448. try {
  2449. // 检查 Python 服务是否可用
  2450. const pythonAvailable = await this.checkPythonServiceAvailable();
  2451. if (!pythonAvailable) {
  2452. logger.warn(`[Python API] Service not available, returning default info`);
  2453. return this.getDefaultAccountInfo(platform);
  2454. }
  2455. // 构建 Cookie 字符串
  2456. const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
  2457. // 调用 Python API
  2458. const response = await fetch(`${PYTHON_SERVICE_URL}/account_info`, {
  2459. method: 'POST',
  2460. headers: {
  2461. 'Content-Type': 'application/json',
  2462. },
  2463. body: JSON.stringify({
  2464. platform,
  2465. cookie: cookieString,
  2466. }),
  2467. });
  2468. if (!response.ok) {
  2469. logger.warn(`[Python API] account_info returned ${response.status}`);
  2470. return this.getDefaultAccountInfo(platform);
  2471. }
  2472. const result = await response.json() as {
  2473. success: boolean;
  2474. account_id?: string;
  2475. account_name?: string;
  2476. avatar_url?: string;
  2477. fans_count?: number;
  2478. works_count?: number;
  2479. error?: string;
  2480. need_login?: boolean;
  2481. };
  2482. logger.info(`[Python API] account_info result: success=${result.success}, name=${result.account_name}`);
  2483. if (result.success && result.account_name) {
  2484. return {
  2485. accountId: result.account_id || `${platform}_${Date.now()}`,
  2486. accountName: result.account_name,
  2487. avatarUrl: result.avatar_url || '',
  2488. fansCount: result.fans_count,
  2489. worksCount: result.works_count ?? 0,
  2490. };
  2491. }
  2492. if (result.need_login) {
  2493. logger.warn(`[Python API] Account needs re-login`);
  2494. }
  2495. logger.warn(`[Python API] Failed to get account info: ${result.error}`);
  2496. return this.getDefaultAccountInfo(platform);
  2497. } catch (error) {
  2498. logger.error(`[Python API] Failed to fetch account info for ${platform}:`, error);
  2499. return this.getDefaultAccountInfo(platform);
  2500. }
  2501. }
  2502. /**
  2503. * 获取默认账号信息
  2504. */
  2505. private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
  2506. // 平台友好名称映射
  2507. const platformNames: Record<string, string> = {
  2508. douyin: '抖音',
  2509. xiaohongshu: '小红书',
  2510. kuaishou: '快手',
  2511. weixin_video: '视频号',
  2512. bilibili: 'B站',
  2513. toutiao: '头条',
  2514. baijiahao: '百家号',
  2515. };
  2516. const name = platformNames[platform] || platform;
  2517. return {
  2518. accountId: `${platform}_${Date.now()}`,
  2519. accountName: `${name}账号`,
  2520. avatarUrl: '',
  2521. fansCount: undefined,
  2522. worksCount: 0,
  2523. };
  2524. }
  2525. /**
  2526. * 获取抖音评论 - 逐个选择作品获取评论
  2527. */
  2528. async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
  2529. const browser = await chromium.launch({
  2530. headless: true,
  2531. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  2532. });
  2533. const allWorkComments: WorkComments[] = [];
  2534. try {
  2535. const context = await browser.newContext({
  2536. viewport: { width: 1920, height: 1080 },
  2537. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2538. });
  2539. // 设置 Cookie
  2540. const playwrightCookies = cookies.map(c => ({
  2541. name: c.name,
  2542. value: c.value,
  2543. domain: c.domain || '.douyin.com',
  2544. path: c.path || '/',
  2545. }));
  2546. await context.addCookies(playwrightCookies);
  2547. const page = await context.newPage();
  2548. // 导航到评论管理页面
  2549. logger.info('Navigating to Douyin comment management page...');
  2550. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  2551. waitUntil: 'domcontentloaded',
  2552. timeout: 30000,
  2553. });
  2554. await page.waitForTimeout(3000);
  2555. // 点击"选择作品"按钮
  2556. logger.info('Looking for "选择作品" button...');
  2557. const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');
  2558. if (selectWorkBtn) {
  2559. await selectWorkBtn.click();
  2560. await page.waitForTimeout(2000);
  2561. logger.info('Clicked "选择作品" button');
  2562. } else {
  2563. // 如果没有选择作品按钮,可能已经有作品被选中,直接获取当前评论
  2564. logger.info('No "选择作品" button found, fetching current comments...');
  2565. const currentComments = await this.extractCommentsFromPage(page);
  2566. if (currentComments.length > 0) {
  2567. allWorkComments.push({
  2568. videoId: 'current',
  2569. videoTitle: '当前作品',
  2570. videoCoverUrl: '',
  2571. comments: currentComments,
  2572. });
  2573. }
  2574. await page.close();
  2575. await context.close();
  2576. await browser.close();
  2577. return allWorkComments;
  2578. }
  2579. // 获取作品列表
  2580. const worksList = await page.evaluate(() => {
  2581. const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];
  2582. // 查找作品列表容器(弹窗中的作品选择列表)
  2583. const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');
  2584. workItems.forEach((item, index) => {
  2585. const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
  2586. const coverEl = item.querySelector('img, [class*="cover"]');
  2587. const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
  2588. let coverUrl = '';
  2589. if (coverEl) {
  2590. coverUrl = (coverEl as HTMLImageElement).src ||
  2591. coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
  2592. }
  2593. // 获取 video ID(从数据属性或其他方式)
  2594. const videoId = item.getAttribute('data-video-id') ||
  2595. item.getAttribute('data-id') ||
  2596. `video_${index}`;
  2597. works.push({ videoId, title, coverUrl });
  2598. });
  2599. return works;
  2600. });
  2601. logger.info(`Found ${worksList.length} works in the selector`);
  2602. // 如果有作品列表,逐个选择并获取评论
  2603. if (worksList.length > 0) {
  2604. for (let i = 0; i < worksList.length; i++) {
  2605. try {
  2606. logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);
  2607. // 点击选择该作品
  2608. const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
  2609. if (workItem) {
  2610. await workItem.click();
  2611. await page.waitForTimeout(2000);
  2612. // 点击确认按钮(如果有)
  2613. const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
  2614. if (confirmBtn) {
  2615. await confirmBtn.click();
  2616. await page.waitForTimeout(2000);
  2617. }
  2618. }
  2619. // 等待评论加载
  2620. await page.waitForTimeout(2000);
  2621. // 提取评论
  2622. const comments = await this.extractCommentsFromPage(page);
  2623. if (comments.length > 0) {
  2624. allWorkComments.push({
  2625. videoId: worksList[i].videoId,
  2626. videoTitle: worksList[i].title,
  2627. videoCoverUrl: worksList[i].coverUrl,
  2628. comments,
  2629. });
  2630. logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
  2631. }
  2632. // 重新打开选择作品弹窗(如果需要继续选择其他作品)
  2633. if (i < worksList.length - 1) {
  2634. const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
  2635. if (selectBtn) {
  2636. await selectBtn.click();
  2637. await page.waitForTimeout(2000);
  2638. }
  2639. }
  2640. } catch (workError) {
  2641. logger.warn(`Failed to process work ${i + 1}:`, workError);
  2642. }
  2643. }
  2644. } else {
  2645. // 没有找到作品列表,尝试直接从页面获取评论
  2646. const comments = await this.extractCommentsFromPage(page);
  2647. if (comments.length > 0) {
  2648. // 获取当前显示的作品信息
  2649. const currentWork = await page.evaluate(() => {
  2650. const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
  2651. const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');
  2652. return {
  2653. title: titleEl?.textContent?.trim() || '当前作品',
  2654. coverUrl: (coverEl as HTMLImageElement)?.src || '',
  2655. };
  2656. });
  2657. allWorkComments.push({
  2658. videoId: 'current',
  2659. videoTitle: currentWork.title,
  2660. videoCoverUrl: currentWork.coverUrl,
  2661. comments,
  2662. });
  2663. }
  2664. }
  2665. await page.close();
  2666. await context.close();
  2667. await browser.close();
  2668. logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
  2669. return allWorkComments;
  2670. } catch (error) {
  2671. logger.error('Error fetching Douyin comments:', error);
  2672. await browser.close();
  2673. return allWorkComments;
  2674. }
  2675. }
  2676. /**
  2677. * 从页面提取评论列表
  2678. * 使用抖音创作者中心的精确选择器
  2679. * 根据实际 HTML 结构:
  2680. * - 评论容器: container-sXKyMs (或类似 container-xxx)
  2681. * - 用户名: username-aLgaNB (或类似 username-xxx)
  2682. * - 时间: time-NRtTXO (或类似 time-xxx)
  2683. * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
  2684. * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
  2685. */
  2686. private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
  2687. return page.evaluate(() => {
  2688. const comments: Array<{
  2689. commentId: string;
  2690. authorId: string;
  2691. authorName: string;
  2692. authorAvatar: string;
  2693. content: string;
  2694. likeCount: number;
  2695. commentTime: string;
  2696. }> = [];
  2697. const seenContents = new Set<string>();
  2698. // 方法1: 直接查找所有评论容器 (container-xxx 类名)
  2699. // 评论容器通常包含 checkbox、avatar、content 等子元素
  2700. const allContainers = document.querySelectorAll('[class*="container-"]');
  2701. const commentContainers: Element[] = [];
  2702. allContainers.forEach(container => {
  2703. // 检查是否是评论容器:包含用户名和评论内容
  2704. const hasUsername = container.querySelector('[class*="username-"]');
  2705. const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
  2706. if (hasUsername && hasCommentContent) {
  2707. commentContainers.push(container);
  2708. }
  2709. });
  2710. console.log(`Found ${commentContainers.length} comment containers`);
  2711. // 如果方法1没找到,尝试方法2:通过评论内容元素向上查找
  2712. if (commentContainers.length === 0) {
  2713. const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
  2714. console.log(`Found ${contentElements.length} content elements, searching parents...`);
  2715. contentElements.forEach(contentEl => {
  2716. let parent = contentEl.parentElement;
  2717. // 向上查找最多 10 层
  2718. for (let i = 0; i < 10 && parent; i++) {
  2719. const className = parent.className || '';
  2720. // 查找包含 container- 的父元素
  2721. if (className.includes('container-')) {
  2722. if (!commentContainers.includes(parent)) {
  2723. commentContainers.push(parent);
  2724. }
  2725. break;
  2726. }
  2727. parent = parent.parentElement;
  2728. }
  2729. });
  2730. }
  2731. console.log(`Total comment containers: ${commentContainers.length}`);
  2732. commentContainers.forEach((container, index) => {
  2733. try {
  2734. // 提取用户名 - 使用 username-xxx 选择器
  2735. let authorName = '';
  2736. const usernameEl = container.querySelector('[class*="username-"]');
  2737. if (usernameEl && usernameEl.textContent) {
  2738. authorName = usernameEl.textContent.trim();
  2739. }
  2740. if (!authorName) authorName = '未知用户';
  2741. // 提取头像 - 从 avatar-xxx 容器内的 img 提取
  2742. let authorAvatar = '';
  2743. const avatarContainer = container.querySelector('[class*="avatar-"]');
  2744. if (avatarContainer) {
  2745. const avatarImg = avatarContainer.querySelector('img');
  2746. if (avatarImg) {
  2747. authorAvatar = avatarImg.src || '';
  2748. }
  2749. }
  2750. // 提取时间 - 使用 time-xxx 选择器
  2751. let commentTime = '';
  2752. const timeEl = container.querySelector('[class*="time-"]');
  2753. if (timeEl && timeEl.textContent) {
  2754. commentTime = timeEl.textContent.trim();
  2755. }
  2756. // 提取评论内容 - 使用 comment-content-text-xxx 选择器
  2757. let content = '';
  2758. const contentEl = container.querySelector('[class*="comment-content-text-"]');
  2759. if (contentEl && contentEl.textContent) {
  2760. content = contentEl.textContent.trim();
  2761. }
  2762. // 跳过空内容
  2763. if (!content || content.length < 1) {
  2764. console.log(`[${index}] Skipping empty content`);
  2765. return;
  2766. }
  2767. // 去重 (基于用户名+内容)
  2768. const contentKey = `${authorName}||${content}`;
  2769. if (seenContents.has(contentKey)) {
  2770. console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
  2771. return;
  2772. }
  2773. seenContents.add(contentKey);
  2774. // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
  2775. let likeCount = 0;
  2776. const operationsEl = container.querySelector('[class*="operations-"]');
  2777. if (operationsEl) {
  2778. // 查找第一个 item-xxx,通常是点赞数
  2779. const firstItem = operationsEl.querySelector('[class*="item-"]');
  2780. if (firstItem) {
  2781. const text = firstItem.textContent || '';
  2782. const match = text.match(/(\d+)/);
  2783. if (match) {
  2784. likeCount = parseInt(match[1], 10);
  2785. }
  2786. }
  2787. }
  2788. // 生成唯一 ID
  2789. const contentHash = content.slice(0, 30) + authorName + commentTime;
  2790. const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;
  2791. comments.push({
  2792. commentId,
  2793. authorId: authorName,
  2794. authorName,
  2795. authorAvatar,
  2796. content,
  2797. likeCount,
  2798. commentTime,
  2799. });
  2800. console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
  2801. } catch (err) {
  2802. console.error(`[${index}] Error extracting comment:`, err);
  2803. }
  2804. });
  2805. console.log(`Successfully extracted ${comments.length} comments`);
  2806. return comments;
  2807. });
  2808. }
  2809. /**
  2810. * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
  2811. * 使用无头浏览器,通过拦截网络请求直接获取 API 数据
  2812. * 更稳定、更高效
  2813. */
  2814. async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
  2815. const browser = await chromium.launch({
  2816. headless: true, // 无头模式
  2817. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  2818. });
  2819. const allWorkComments: WorkComments[] = [];
  2820. // 存储捕获的 API 数据
  2821. const capturedWorks: Array<{
  2822. awemeId: string;
  2823. title: string;
  2824. coverUrl: string;
  2825. commentCount: number;
  2826. }> = [];
  2827. const capturedComments: Map<string, CommentItem[]> = new Map();
  2828. try {
  2829. const context = await browser.newContext({
  2830. viewport: { width: 1920, height: 1080 },
  2831. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  2832. });
  2833. // 设置 Cookie
  2834. const playwrightCookies = cookies.map(c => ({
  2835. name: c.name,
  2836. value: c.value,
  2837. domain: c.domain || '.douyin.com',
  2838. path: c.path || '/',
  2839. }));
  2840. await context.addCookies(playwrightCookies);
  2841. logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);
  2842. const page = await context.newPage();
  2843. // 监听网络响应
  2844. page.on('response', async (response) => {
  2845. const url = response.url();
  2846. try {
  2847. // 监听作品列表 API - 支持新旧两种接口
  2848. // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
  2849. // 旧接口: /creator/item/list (item_info_list 字段)
  2850. if (url.includes('/work_list') || url.includes('/creator/item/list')) {
  2851. const data = await response.json();
  2852. // 新接口: aweme_list
  2853. if (data?.aweme_list && data.aweme_list.length > 0) {
  2854. for (const aweme of data.aweme_list) {
  2855. const awemeId = String(aweme.aweme_id || '');
  2856. if (!awemeId) continue;
  2857. const statistics = aweme.statistics || {};
  2858. const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
  2859. let title = aweme.item_title || '';
  2860. if (!title) {
  2861. const desc = aweme.desc || aweme.caption || '';
  2862. title = desc.split('\n')[0].slice(0, 50) || '无标题';
  2863. }
  2864. let coverUrl = '';
  2865. if (aweme.Cover?.url_list?.length > 0) {
  2866. coverUrl = aweme.Cover.url_list[0];
  2867. } else if (aweme.video?.cover?.url_list?.length > 0) {
  2868. coverUrl = aweme.video.cover.url_list[0];
  2869. }
  2870. capturedWorks.push({
  2871. awemeId,
  2872. title,
  2873. coverUrl,
  2874. commentCount,
  2875. });
  2876. }
  2877. logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
  2878. }
  2879. // 旧接口: item_info_list
  2880. const itemList = data?.item_info_list || data?.item_list || [];
  2881. if (itemList.length > 0) {
  2882. for (const item of itemList) {
  2883. capturedWorks.push({
  2884. awemeId: item.item_id_plain || item.aweme_id || '',
  2885. title: item.title || '无标题',
  2886. coverUrl: item.cover_image_url || '',
  2887. commentCount: item.comment_count || 0,
  2888. });
  2889. }
  2890. logger.info(`[API] Captured ${itemList.length} works from item/list API`);
  2891. }
  2892. }
  2893. // 监听评论列表 API(两种格式)
  2894. // 格式1: /comment/list/select/ - 初始加载,返回 { comments: [...] }
  2895. // 格式2: /creator/comment/list/ - 切换作品后,返回 { comment_info_list: [...] }
  2896. if (url.includes('/comment/list') || url.includes('/comment/read')) {
  2897. const data = await response.json();
  2898. // 从 URL 中提取 aweme_id
  2899. const awemeIdMatch = url.match(/aweme_id=(\d+)/);
  2900. const awemeId = awemeIdMatch?.[1] || '';
  2901. let comments: CommentItem[] = [];
  2902. // 格式1: 初始加载的评论 API (comment/list/select)
  2903. if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
  2904. comments = data.comments.map((c: Record<string, unknown>) => {
  2905. const user = c.user as Record<string, unknown> | undefined;
  2906. const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
  2907. const avatarUrls = avatarThumb?.url_list as string[] | undefined;
  2908. return {
  2909. commentId: String(c.cid || ''),
  2910. authorId: String(user?.uid || ''),
  2911. authorName: String(user?.nickname || '匿名'),
  2912. authorAvatar: avatarUrls?.[0] || '',
  2913. content: String(c.text || ''),
  2914. likeCount: Number(c.digg_count || 0),
  2915. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2916. videoId: String(c.aweme_id || awemeId),
  2917. };
  2918. });
  2919. logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
  2920. }
  2921. // 格式2: 切换作品后的评论 API (creator/comment/list)
  2922. if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
  2923. comments = data.comment_info_list.map((c: Record<string, unknown>) => {
  2924. const userInfo = c.user_info as Record<string, unknown> | undefined;
  2925. return {
  2926. commentId: String(c.comment_id || ''),
  2927. authorId: String(userInfo?.user_id || ''),
  2928. authorName: String(userInfo?.screen_name || '匿名'),
  2929. authorAvatar: String(userInfo?.avatar_url || ''),
  2930. content: String(c.text || ''),
  2931. likeCount: Number(c.digg_count || 0),
  2932. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  2933. videoId: awemeId, // 这种格式没有直接返回 aweme_id
  2934. };
  2935. });
  2936. logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
  2937. }
  2938. if (comments.length > 0) {
  2939. const videoId = comments[0]?.videoId || awemeId;
  2940. if (videoId) {
  2941. const existing = capturedComments.get(videoId) || [];
  2942. capturedComments.set(videoId, [...existing, ...comments]);
  2943. logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
  2944. }
  2945. }
  2946. }
  2947. } catch {
  2948. // 忽略非 JSON 响应
  2949. }
  2950. });
  2951. // 导航到创作者中心页面(设置好 Cookie 后)
  2952. logger.info('[API Interception] Navigating to creator page...');
  2953. await page.goto('https://creator.douyin.com/creator-micro/home', {
  2954. waitUntil: 'domcontentloaded',
  2955. timeout: 60000,
  2956. });
  2957. // 等待页面加载
  2958. await page.waitForTimeout(3000);
  2959. // 检查是否需要登录
  2960. const currentUrl = page.url();
  2961. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  2962. logger.warn('[API Interception] Cookie expired');
  2963. return [];
  2964. }
  2965. // 方式1:直接调用 API 获取作品列表(优先)
  2966. logger.info('[API Interception] Fetching works via direct API...');
  2967. const apiResult = await this.fetchWorksDirectApi(page);
  2968. let works = apiResult.works;
  2969. // 方式2:如果直接调用失败,尝试通过页面触发 API
  2970. if (works.length === 0) {
  2971. logger.info('[API Interception] Direct API failed, trying page navigation...');
  2972. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  2973. waitUntil: 'networkidle',
  2974. timeout: 60000,
  2975. });
  2976. await page.waitForTimeout(3000);
  2977. // 点击"选择作品"按钮触发作品列表 API
  2978. const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
  2979. if (selectBtn) {
  2980. await selectBtn.click();
  2981. await page.waitForTimeout(3000);
  2982. }
  2983. // 使用监听到的数据
  2984. works = capturedWorks;
  2985. }
  2986. logger.info(`[API Interception] Total works: ${works.length}`);
  2987. // 获取有评论的作品
  2988. const worksWithComments = works.filter(w => w.commentCount > 0);
  2989. logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);
  2990. // 如果有评论的作品,需要导航到评论管理页面并逐个切换获取
  2991. if (worksWithComments.length > 0) {
  2992. // 先尝试直接调用 API 获取评论
  2993. for (const work of worksWithComments) {
  2994. logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);
  2995. let comments = capturedComments.get(work.awemeId) || [];
  2996. if (comments.length === 0) {
  2997. comments = await this.fetchCommentsDirectApi(page, work.awemeId);
  2998. }
  2999. if (comments.length > 0) {
  3000. allWorkComments.push({
  3001. videoId: work.awemeId,
  3002. videoTitle: work.title,
  3003. videoCoverUrl: work.coverUrl,
  3004. comments,
  3005. });
  3006. logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
  3007. }
  3008. }
  3009. // 如果直接 API 没有获取到足够的评论,使用页面交互方式
  3010. const worksNeedingPageMethod = worksWithComments.filter(w => {
  3011. const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
  3012. return !found || found.comments.length === 0;
  3013. });
  3014. if (worksNeedingPageMethod.length > 0) {
  3015. logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);
  3016. // works 是所有作品的列表(包括没有评论的),弹窗中的顺序应该和这个一致
  3017. // worksWithComments 是有评论的作品列表
  3018. logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
  3019. logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);
  3020. // 构建作品索引映射:在所有作品列表中,每个有评论的作品的索引是多少
  3021. const workIndexMap = new Map<string, number>();
  3022. works.forEach((w, idx) => {
  3023. if (w.commentCount > 0) {
  3024. workIndexMap.set(w.awemeId, idx);
  3025. }
  3026. });
  3027. logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);
  3028. // 导航到评论管理页面
  3029. logger.info('[Page Method] Navigating to comment management page...');
  3030. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  3031. waitUntil: 'domcontentloaded',
  3032. timeout: 60000,
  3033. });
  3034. // 等待页面加载
  3035. await page.waitForTimeout(5000);
  3036. // 用于存储最新捕获的评论和 aweme_id
  3037. const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };
  3038. // 设置监听器 - 捕获评论 API 响应
  3039. page.on('response', async (response) => {
  3040. const url = response.url();
  3041. if (url.includes('/comment/list') || url.includes('/comment/read')) {
  3042. try {
  3043. const jsonData = await response.json();
  3044. let parsedComments: CommentItem[] = [];
  3045. let capturedAwemeId = '';
  3046. // 从 URL 中提取 aweme_id(格式1有)
  3047. const awemeIdMatch = url.match(/aweme_id=(\d+)/);
  3048. capturedAwemeId = awemeIdMatch?.[1] || '';
  3049. // 格式1: { comments: [...] }
  3050. if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
  3051. // 从评论中提取 aweme_id
  3052. const firstComment = jsonData.comments[0] as Record<string, unknown>;
  3053. if (!capturedAwemeId && firstComment.aweme_id) {
  3054. capturedAwemeId = String(firstComment.aweme_id);
  3055. }
  3056. parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
  3057. commentId: String((c as { cid?: string }).cid || ''),
  3058. authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
  3059. authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
  3060. authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
  3061. content: String((c as { text?: string }).text || ''),
  3062. likeCount: Number((c as { digg_count?: number }).digg_count || 0),
  3063. commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
  3064. videoId: capturedAwemeId,
  3065. }));
  3066. logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
  3067. }
  3068. // 格式2: { comment_info_list: [...] }
  3069. if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
  3070. parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
  3071. const userInfo = c.user_info as Record<string, unknown> | undefined;
  3072. return {
  3073. commentId: String(c.comment_id || ''),
  3074. authorId: String(userInfo?.user_id || ''),
  3075. authorName: String(userInfo?.screen_name || '匿名'),
  3076. authorAvatar: String(userInfo?.avatar_url || ''),
  3077. content: String(c.text || ''),
  3078. likeCount: Number(c.digg_count || 0),
  3079. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  3080. videoId: '', // 格式2没有aweme_id,稍后填充
  3081. };
  3082. });
  3083. logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
  3084. }
  3085. if (parsedComments.length > 0) {
  3086. latestHolder.comments = parsedComments;
  3087. latestHolder.awemeId = capturedAwemeId;
  3088. }
  3089. } catch {
  3090. // 忽略
  3091. }
  3092. }
  3093. });
  3094. // 等待第一个作品的评论加载(格式1,有 aweme_id)
  3095. await page.waitForTimeout(4000);
  3096. // 处理第一个作品(页面加载时自动显示,格式1有aweme_id可以直接匹配)
  3097. if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
  3098. const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
  3099. if (matchedWork) {
  3100. allWorkComments.push({
  3101. videoId: matchedWork.awemeId,
  3102. videoTitle: matchedWork.title,
  3103. videoCoverUrl: matchedWork.coverUrl,
  3104. comments: latestHolder.comments,
  3105. });
  3106. logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
  3107. }
  3108. }
  3109. // 遍历其他有评论的作品
  3110. for (const work of worksWithComments) {
  3111. // 检查是否已获取
  3112. const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
  3113. if (existing) {
  3114. logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
  3115. continue;
  3116. }
  3117. // 获取该作品在所有作品列表中的索引
  3118. const workIndex = workIndexMap.get(work.awemeId);
  3119. if (workIndex === undefined) {
  3120. logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
  3121. continue;
  3122. }
  3123. logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);
  3124. try {
  3125. // 清空之前的数据
  3126. latestHolder.comments = [];
  3127. latestHolder.awemeId = '';
  3128. // 点击"选择作品"按钮
  3129. await page.click('button:has-text("选择作品")');
  3130. await page.waitForTimeout(2000);
  3131. // 找到弹窗中的作品图片列表
  3132. const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
  3133. logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);
  3134. if (workIndex < workImages.length) {
  3135. // 点击对应索引的作品
  3136. await workImages[workIndex].click();
  3137. logger.info(`[Page Method] Clicked work image at index ${workIndex}`);
  3138. // 等待评论 API 响应
  3139. await page.waitForTimeout(4000);
  3140. // 获取评论
  3141. if (latestHolder.comments.length > 0) {
  3142. // 使用当前 work 的 awemeId
  3143. const comments = latestHolder.comments.map(c => ({
  3144. ...c,
  3145. videoId: work.awemeId,
  3146. }));
  3147. allWorkComments.push({
  3148. videoId: work.awemeId,
  3149. videoTitle: work.title,
  3150. videoCoverUrl: work.coverUrl,
  3151. comments,
  3152. });
  3153. logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
  3154. } else {
  3155. // 尝试从页面提取
  3156. const pageComments = await this.extractCommentsFromPage(page);
  3157. if (pageComments.length > 0) {
  3158. const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
  3159. allWorkComments.push({
  3160. videoId: work.awemeId,
  3161. videoTitle: work.title,
  3162. videoCoverUrl: work.coverUrl,
  3163. comments,
  3164. });
  3165. logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
  3166. } else {
  3167. logger.warn(`[Page Method] No comments for ${work.awemeId}`);
  3168. }
  3169. }
  3170. } else {
  3171. logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
  3172. await page.keyboard.press('Escape');
  3173. }
  3174. await page.waitForTimeout(1000);
  3175. } catch (e) {
  3176. logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
  3177. await page.keyboard.press('Escape').catch(() => { });
  3178. await page.waitForTimeout(500);
  3179. }
  3180. }
  3181. }
  3182. }
  3183. logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
  3184. await context.close();
  3185. } catch (error) {
  3186. logger.error('[API Interception] Error:', error);
  3187. } finally {
  3188. await browser.close();
  3189. }
  3190. return allWorkComments;
  3191. }
  3192. /**
  3193. * 直接调用评论 API 获取数据(支持分页获取所有评论)
  3194. * 优先使用视频页面 API(获取全部评论),失败时才使用创作者 API
  3195. */
  3196. private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  3197. // 优先尝试视频页面 API(获取全部评论)
  3198. logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
  3199. let comments = await this.fetchVideoPageCommentsApi(page, awemeId);
  3200. if (comments.length > 0) {
  3201. logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
  3202. return comments;
  3203. }
  3204. // 如果视频页面 API 失败,尝试创作者评论 API(可能只返回部分评论)
  3205. logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
  3206. comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);
  3207. return comments;
  3208. }
  3209. /**
  3210. * 通过视频页面获取全部评论(主要方案)
  3211. * 这个 API 能获取视频的所有评论,不仅仅是创作者回复过的
  3212. */
  3213. private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  3214. const comments: CommentItem[] = [];
  3215. const maxPages = 50;
  3216. let cursor = 0;
  3217. let hasMore = true;
  3218. let pageCount = 0;
  3219. try {
  3220. // 导航到视频页面
  3221. logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
  3222. await page.goto(`https://www.douyin.com/video/${awemeId}`, {
  3223. waitUntil: 'domcontentloaded',
  3224. timeout: 30000,
  3225. });
  3226. await page.waitForTimeout(2000);
  3227. while (hasMore && pageCount < maxPages) {
  3228. pageCount++;
  3229. const data = await page.evaluate(async ({ videoId, cursorValue }) => {
  3230. try {
  3231. const url = `https://www.douyin.com/aweme/v1/web/comment/list/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&item_type=0&insert_ids=&whale_cut_token=&cut_version=1&rcFT=&aid=6383&device_platform=web_pc&verifyFp=&fp=&msToken=`;
  3232. const resp = await fetch(url, {
  3233. method: 'GET',
  3234. credentials: 'include',
  3235. headers: {
  3236. 'Accept': 'application/json, text/plain, */*',
  3237. 'Referer': `https://www.douyin.com/video/${videoId}`,
  3238. },
  3239. });
  3240. if (!resp.ok) {
  3241. return { error: `HTTP ${resp.status}`, comments: [] };
  3242. }
  3243. return resp.json();
  3244. } catch (e) {
  3245. return { error: String(e), comments: [] };
  3246. }
  3247. }, { videoId: awemeId, cursorValue: cursor });
  3248. if (data?.error) {
  3249. logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
  3250. }
  3251. if (data?.comments && Array.isArray(data.comments)) {
  3252. for (const c of data.comments) {
  3253. comments.push({
  3254. commentId: String(c.cid || ''),
  3255. authorId: String(c.user?.uid || c.user?.sec_uid || ''),
  3256. authorName: String(c.user?.nickname || '匿名'),
  3257. authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
  3258. content: String(c.text || ''),
  3259. likeCount: Number(c.digg_count || 0),
  3260. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  3261. videoId: String(c.aweme_id || awemeId),
  3262. });
  3263. }
  3264. logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
  3265. }
  3266. hasMore = data?.has_more === true || data?.has_more === 1;
  3267. cursor = data?.cursor || cursor + 50;
  3268. if (!data?.comments || data.comments.length === 0) {
  3269. hasMore = false;
  3270. }
  3271. }
  3272. logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
  3273. } catch (e) {
  3274. logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
  3275. }
  3276. return comments;
  3277. }
  3278. /**
  3279. * 创作者评论管理 API(备用方案)
  3280. * 获取的是需要回复的评论
  3281. */
  3282. private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
  3283. const comments: CommentItem[] = [];
  3284. const maxPages = 50;
  3285. let cursor = 0;
  3286. let hasMore = true;
  3287. let pageCount = 0;
  3288. try {
  3289. while (hasMore && pageCount < maxPages) {
  3290. pageCount++;
  3291. const data = await page.evaluate(async ({ videoId, cursorValue }) => {
  3292. const url = `https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&comment_select_options=0&sort_options=0&channel_id=618&app_id=2906&aid=2906&device_platform=webapp`;
  3293. const resp = await fetch(url, {
  3294. credentials: 'include',
  3295. headers: {
  3296. 'Accept': 'application/json',
  3297. },
  3298. });
  3299. return resp.json();
  3300. }, { videoId: awemeId, cursorValue: cursor });
  3301. if (data?.comments && Array.isArray(data.comments)) {
  3302. for (const c of data.comments) {
  3303. comments.push({
  3304. commentId: String(c.cid || ''),
  3305. authorId: String(c.user?.uid || ''),
  3306. authorName: String(c.user?.nickname || '匿名'),
  3307. authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
  3308. content: String(c.text || ''),
  3309. likeCount: Number(c.digg_count || 0),
  3310. commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
  3311. videoId: String(c.aweme_id || awemeId),
  3312. });
  3313. }
  3314. logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
  3315. }
  3316. hasMore = data?.has_more === true || data?.has_more === 1;
  3317. cursor = data?.cursor || cursor + 50;
  3318. if (!data?.comments || data.comments.length === 0) {
  3319. hasMore = false;
  3320. }
  3321. }
  3322. logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
  3323. } catch (e) {
  3324. logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
  3325. }
  3326. return comments;
  3327. }
  3328. /**
  3329. * 直接调用抖音 API 获取作品列表
  3330. * 使用新的 work_list 接口,支持分页加载
  3331. * 返回作品列表和总作品数
  3332. *
  3333. * 注意:需要先导航到作品管理页面才能正确调用 API
  3334. */
  3335. private async fetchWorksDirectApi(page: Page): Promise<{
  3336. works: Array<{
  3337. awemeId: string;
  3338. title: string;
  3339. coverUrl: string;
  3340. videoUrl?: string;
  3341. playCount: number;
  3342. likeCount: number;
  3343. commentCount: number;
  3344. shareCount: number;
  3345. collectCount: number;
  3346. createTime?: number;
  3347. }>;
  3348. total: number;
  3349. }> {
  3350. const works: Array<{
  3351. awemeId: string;
  3352. title: string;
  3353. coverUrl: string;
  3354. videoUrl?: string;
  3355. playCount: number;
  3356. likeCount: number;
  3357. commentCount: number;
  3358. shareCount: number;
  3359. collectCount: number;
  3360. createTime?: number;
  3361. }> = [];
  3362. let totalCount = 0; // 从 API 获取的总作品数
  3363. try {
  3364. // 首先导航到作品管理页面,确保 API 有正确的上下文和权限
  3365. const contentManageUrl = 'https://creator.douyin.com/creator-micro/content/manage';
  3366. const currentUrl = page.url();
  3367. if (!currentUrl.includes('/content/manage')) {
  3368. logger.info(`[DirectAPI] Navigating to content manage page...`);
  3369. await page.goto(contentManageUrl, {
  3370. waitUntil: 'domcontentloaded',
  3371. timeout: 30000,
  3372. });
  3373. await page.waitForTimeout(2000);
  3374. // 检查是否需要登录
  3375. const newUrl = page.url();
  3376. if (newUrl.includes('login') || newUrl.includes('passport')) {
  3377. logger.warn('[DirectAPI] Not logged in, cannot fetch works');
  3378. return { works, total: 0 };
  3379. }
  3380. }
  3381. let hasMore = true;
  3382. let maxCursor = 0;
  3383. let pageCount = 0;
  3384. const maxPages = 20; // 最多加载20页,防止无限循环
  3385. while (hasMore && pageCount < maxPages) {
  3386. pageCount++;
  3387. logger.info(`[DirectAPI] Fetching works page ${pageCount}, cursor: ${maxCursor}`);
  3388. const data = await page.evaluate(async (cursor: number) => {
  3389. // 使用新的 work_list API 接口
  3390. // status: 0 表示获取全部已发布的作品
  3391. // count: 每页获取数量
  3392. const url = `https://creator.douyin.com/janus/douyin/creator/pc/work_list?status=0&scene=star_atlas&device_platform=android&count=20&max_cursor=${cursor}&cookie_enabled=true&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_online=true&timezone_name=Asia%2FShanghai&aid=1128`;
  3393. const resp = await fetch(url, {
  3394. credentials: 'include',
  3395. headers: {
  3396. 'Accept': 'application/json',
  3397. },
  3398. });
  3399. return resp.json();
  3400. }, maxCursor);
  3401. // 获取作品数
  3402. const awemeList = data?.aweme_list || [];
  3403. logger.info(`[DirectAPI] API response: status_code=${data?.status_code}, has_more=${data?.has_more}, max_cursor=${data?.max_cursor}, aweme_list_length=${awemeList.length}`);
  3404. // 检查 API 返回状态
  3405. if (data?.status_code !== 0 && data?.status_code !== undefined) {
  3406. logger.warn(`[DirectAPI] API returned error status_code: ${data.status_code}`);
  3407. logger.warn(`[DirectAPI] Error message: ${data?.err_msg || data?.errMsg || 'unknown'}`);
  3408. // status_code: 8 表示未授权,可能需要重新登录
  3409. if (data.status_code === 8) {
  3410. logger.warn('[DirectAPI] status_code 8: Not authorized, may need re-login');
  3411. }
  3412. // 如果是第一页就出错,记录更详细的错误信息
  3413. if (pageCount === 1) {
  3414. logger.error(`[DirectAPI] First page failed with status_code ${data.status_code}, cannot fetch works`);
  3415. logger.error(`[DirectAPI] Response data: ${JSON.stringify(data).substring(0, 500)}`);
  3416. }
  3417. break;
  3418. }
  3419. // 如果 status_code 是 0 但 aweme_list 为空,记录警告
  3420. if (data?.status_code === 0 && awemeList.length === 0 && pageCount === 1) {
  3421. logger.warn(`[DirectAPI] API returned success but aweme_list is empty on first page`);
  3422. logger.warn(`[DirectAPI] Response data: ${JSON.stringify(data).substring(0, 500)}`);
  3423. }
  3424. // 优先从第一个作品的 author.aweme_count 获取真实作品数(只在第一页获取)
  3425. if (pageCount === 1 && awemeList.length > 0) {
  3426. const firstAweme = awemeList[0];
  3427. const authorAwemeCount = firstAweme?.author?.aweme_count;
  3428. if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
  3429. totalCount = authorAwemeCount;
  3430. logger.info(`[DirectAPI] Using author.aweme_count as total works: ${totalCount}`);
  3431. }
  3432. }
  3433. // 解析 aweme_list 中的作品数据
  3434. logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);
  3435. for (const aweme of awemeList) {
  3436. const awemeId = String(aweme.aweme_id || '');
  3437. if (!awemeId) continue;
  3438. // 从 statistics 中获取所有统计字段
  3439. const statistics = aweme.statistics || {};
  3440. const playCount = parseInt(String(statistics.play_count || '0'), 10);
  3441. const likeCount = parseInt(String(statistics.digg_count || '0'), 10); // 抖音用 digg_count 表示点赞
  3442. const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
  3443. const shareCount = parseInt(String(statistics.share_count || '0'), 10);
  3444. const collectCount = parseInt(String(statistics.collect_count || '0'), 10);
  3445. // 获取标题:优先使用 item_title,其次使用 desc(描述)
  3446. let title = aweme.item_title || '';
  3447. if (!title) {
  3448. // 从 desc 中提取标题(取第一行或前50个字符)
  3449. const desc = aweme.desc || aweme.caption || '';
  3450. title = desc.split('\n')[0].slice(0, 50) || '无标题';
  3451. }
  3452. // 获取封面 URL:从 Cover.url_list 或 video.cover.url_list 中获取
  3453. let coverUrl = '';
  3454. if (aweme.Cover?.url_list?.length > 0) {
  3455. coverUrl = aweme.Cover.url_list[0];
  3456. } else if (aweme.video?.cover?.url_list?.length > 0) {
  3457. coverUrl = aweme.video.cover.url_list[0];
  3458. }
  3459. // 入库 video_url 使用 play_addr.url_list 的第一项
  3460. const videoUrl = aweme.video?.play_addr?.url_list?.[0] || '';
  3461. works.push({
  3462. awemeId,
  3463. title,
  3464. coverUrl,
  3465. videoUrl,
  3466. playCount,
  3467. likeCount,
  3468. commentCount,
  3469. shareCount,
  3470. collectCount,
  3471. createTime: aweme.create_time,
  3472. });
  3473. }
  3474. // 检查是否有更多数据
  3475. // 注意: 抖音 API 返回的 has_more 可能不准确,我们额外判断
  3476. const apiHasMore = data?.has_more === true || data?.has_more === 1;
  3477. // 更新游标:使用返回的 max_cursor
  3478. if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
  3479. // 只有当 max_cursor 有变化时才继续
  3480. if (data.max_cursor !== maxCursor) {
  3481. maxCursor = data.max_cursor;
  3482. hasMore = apiHasMore && awemeList.length > 0;
  3483. } else {
  3484. // max_cursor 没变化,说明到底了
  3485. hasMore = false;
  3486. }
  3487. } else if (awemeList.length > 0) {
  3488. // 如果没有 max_cursor,使用最后一个作品的 create_time 作为游标
  3489. const lastAweme = awemeList[awemeList.length - 1];
  3490. if (lastAweme.create_time) {
  3491. const newCursor = lastAweme.create_time;
  3492. if (newCursor !== maxCursor) {
  3493. maxCursor = newCursor;
  3494. hasMore = apiHasMore;
  3495. } else {
  3496. hasMore = false;
  3497. }
  3498. } else {
  3499. hasMore = false;
  3500. }
  3501. } else {
  3502. // 没有获取到数据,停止循环
  3503. hasMore = false;
  3504. }
  3505. logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);
  3506. // 稍微延迟,避免请求过快
  3507. if (hasMore) {
  3508. await new Promise(resolve => setTimeout(resolve, 500));
  3509. }
  3510. }
  3511. logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages, items count: ${totalCount}`);
  3512. // 如果总作品数 > 0 但实际获取到的作品数为 0,记录警告
  3513. if (totalCount > 0 && works.length === 0) {
  3514. logger.warn(`[DirectAPI] Warning: API reported ${totalCount} works but fetched 0 works`);
  3515. logger.warn(`[DirectAPI] This may indicate: API error, cookie expired, or permission issue`);
  3516. }
  3517. } catch (e) {
  3518. logger.error('[DirectAPI] Failed to fetch works:', e);
  3519. logger.error('[DirectAPI] Error details:', e instanceof Error ? e.stack : String(e));
  3520. }
  3521. return { works, total: totalCount };
  3522. }
  3523. /**
  3524. * 通过 Python API 获取评论 - 分作品逐个获取
  3525. */
  3526. private async fetchCommentsViaPythonApi(platform: 'douyin' | 'xiaohongshu' | 'weixin', cookies: CookieData[]): Promise<WorkComments[]> {
  3527. const allWorkComments: WorkComments[] = [];
  3528. const cookieString = JSON.stringify(cookies);
  3529. // 1. 先获取作品列表
  3530. logger.info(`[${platform} Comments Python] Fetching works list...`);
  3531. const worksResponse = await fetch(`${PYTHON_SERVICE_URL}/works`, {
  3532. method: 'POST',
  3533. headers: { 'Content-Type': 'application/json' },
  3534. body: JSON.stringify({
  3535. platform,
  3536. cookie: cookieString,
  3537. page: 0,
  3538. page_size: 50,
  3539. }),
  3540. });
  3541. if (!worksResponse.ok) {
  3542. throw new Error(`Python API works returned ${worksResponse.status}`);
  3543. }
  3544. const worksResult = await worksResponse.json();
  3545. if (!worksResult.success) {
  3546. throw new Error(worksResult.error || 'Failed to get works');
  3547. }
  3548. const works = worksResult.works || [];
  3549. logger.info(`[${platform} Comments Python] Got ${works.length} works`);
  3550. // 2. 遍历作品获取评论
  3551. for (const work of works) {
  3552. const workId = work.work_id;
  3553. if (!workId) continue;
  3554. try {
  3555. logger.info(`[${platform} Comments Python] Fetching comments for work ${workId}...`);
  3556. const commentsResponse = await fetch(`${PYTHON_SERVICE_URL}/comments`, {
  3557. method: 'POST',
  3558. headers: { 'Content-Type': 'application/json' },
  3559. body: JSON.stringify({
  3560. platform,
  3561. cookie: cookieString,
  3562. work_id: workId,
  3563. }),
  3564. });
  3565. if (!commentsResponse.ok) {
  3566. logger.warn(`[${platform} Comments Python] Comments API returned ${commentsResponse.status} for work ${workId}`);
  3567. continue;
  3568. }
  3569. const commentsResult = await commentsResponse.json();
  3570. if (!commentsResult.success) {
  3571. logger.warn(`[${platform} Comments Python] Failed to get comments for work ${workId}: ${commentsResult.error}`);
  3572. continue;
  3573. }
  3574. const comments: CommentItem[] = (commentsResult.comments || []).map((c: {
  3575. comment_id: string;
  3576. parent_comment_id: string;
  3577. author_id: string;
  3578. author_name: string;
  3579. author_avatar: string;
  3580. content: string;
  3581. like_count: number;
  3582. create_time: string;
  3583. reply_count?: number;
  3584. }) => ({
  3585. commentId: c.comment_id,
  3586. parentCommentId: c.parent_comment_id,
  3587. authorId: c.author_id,
  3588. authorName: c.author_name,
  3589. authorAvatar: c.author_avatar,
  3590. content: c.content,
  3591. likeCount: c.like_count,
  3592. commentTime: c.create_time,
  3593. replyCount: c.reply_count || 0,
  3594. }));
  3595. if (comments.length > 0) {
  3596. allWorkComments.push({
  3597. videoId: workId,
  3598. videoTitle: work.title || '',
  3599. videoCoverUrl: work.cover_url || '',
  3600. comments,
  3601. });
  3602. logger.info(`[${platform} Comments Python] Got ${comments.length} comments for work ${workId}`);
  3603. }
  3604. } catch (commentError) {
  3605. logger.warn(`[${platform} Comments Python] Error fetching comments for work ${workId}:`, commentError);
  3606. }
  3607. }
  3608. logger.info(`[${platform} Comments Python] Total: ${allWorkComments.length} works with comments`);
  3609. return allWorkComments;
  3610. }
  3611. /**
  3612. * 通过 Python API 获取抖音评论 - 一次性获取所有作品的评论(备用)
  3613. */
  3614. private async fetchDouyinCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
  3615. const cookieString = JSON.stringify(cookies);
  3616. logger.info('[Douyin Comments Python] Fetching all comments...');
  3617. const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
  3618. method: 'POST',
  3619. headers: { 'Content-Type': 'application/json' },
  3620. body: JSON.stringify({
  3621. platform: 'douyin',
  3622. cookie: cookieString,
  3623. }),
  3624. });
  3625. if (!response.ok) {
  3626. throw new Error(`Python API all_comments returned ${response.status}`);
  3627. }
  3628. const result = await response.json();
  3629. if (!result.success) {
  3630. throw new Error(result.error || 'Failed to get all comments');
  3631. }
  3632. const workComments = result.work_comments || [];
  3633. logger.info(`[Douyin Comments Python] Got ${workComments.length} works with comments`);
  3634. // 转换数据格式
  3635. const allWorkComments: WorkComments[] = workComments.map((wc: {
  3636. work_id: string;
  3637. title: string;
  3638. cover_url: string;
  3639. comments: Array<{
  3640. comment_id: string;
  3641. author_id: string;
  3642. author_name: string;
  3643. author_avatar: string;
  3644. content: string;
  3645. like_count: number;
  3646. create_time: string;
  3647. is_author?: boolean;
  3648. }>;
  3649. }) => ({
  3650. videoId: wc.work_id,
  3651. videoTitle: wc.title || '',
  3652. videoCoverUrl: wc.cover_url || '',
  3653. comments: (wc.comments || []).map(c => ({
  3654. commentId: c.comment_id,
  3655. authorId: c.author_id,
  3656. authorName: c.author_name,
  3657. authorAvatar: c.author_avatar,
  3658. content: c.content,
  3659. likeCount: c.like_count,
  3660. commentTime: c.create_time,
  3661. })),
  3662. }));
  3663. logger.info(`[Douyin Comments Python] Total: ${allWorkComments.length} works with comments`);
  3664. return allWorkComments;
  3665. }
  3666. /**
  3667. * 获取抖音评论 - 优先使用 Python API
  3668. */
  3669. async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  3670. // 优先使用 Python API(分作品获取)
  3671. const pythonAvailable = await this.checkPythonServiceAvailable();
  3672. if (pythonAvailable) {
  3673. logger.info('[Douyin Comments] Using Python API...');
  3674. try {
  3675. const result = await this.fetchCommentsViaPythonApi('douyin', cookies);
  3676. if (result.length > 0) {
  3677. return result;
  3678. }
  3679. logger.info('[Douyin Comments] Python API returned empty, falling back to Playwright...');
  3680. } catch (pythonError) {
  3681. logger.warn('[Douyin Comments] Python API failed:', pythonError);
  3682. }
  3683. }
  3684. // 回退到 Playwright API 拦截方式
  3685. const result = await this.fetchDouyinCommentsByApiInterception(cookies);
  3686. if (result.length > 0) {
  3687. return result;
  3688. }
  3689. // 如果 API 方式失败,使用旧的 DOM 解析方式作为备用
  3690. logger.info('[Fallback] Using DOM parsing method...');
  3691. const browser = await chromium.launch({
  3692. headless: true, // 改为无头模式
  3693. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  3694. });
  3695. const allWorkComments: WorkComments[] = [];
  3696. try {
  3697. const context = await browser.newContext({
  3698. viewport: { width: 1920, height: 1080 },
  3699. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  3700. });
  3701. // 设置 Cookie
  3702. const playwrightCookies = cookies.map(c => ({
  3703. name: c.name,
  3704. value: c.value,
  3705. domain: c.domain || '.douyin.com',
  3706. path: c.path || '/',
  3707. }));
  3708. await context.addCookies(playwrightCookies);
  3709. logger.info(`Set ${playwrightCookies.length} cookies`);
  3710. const page = await context.newPage();
  3711. // 导航到评论管理页面
  3712. logger.info('Navigating to Douyin comment management page...');
  3713. await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
  3714. waitUntil: 'domcontentloaded',
  3715. timeout: 60000,
  3716. });
  3717. // 等待页面完全加载
  3718. logger.info('Waiting for page to fully load...');
  3719. await page.waitForTimeout(5000);
  3720. // 检查是否需要登录
  3721. const currentUrl = page.url();
  3722. logger.info(`Current URL: ${currentUrl}`);
  3723. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  3724. logger.warn('Cookie expired, need re-login');
  3725. await browser.close();
  3726. return allWorkComments;
  3727. }
  3728. logger.info('Page loaded successfully');
  3729. // 等待评论列表加载
  3730. logger.info('Waiting for comments to load...');
  3731. try {
  3732. await page.waitForSelector('[class*="comment-content-text-"]', { timeout: 10000 });
  3733. logger.info('Comments loaded');
  3734. } catch {
  3735. logger.warn('No comments found on initial load, will try to select works');
  3736. }
  3737. // 辅助函数:从当前页面提取评论
  3738. const extractCommentsFromCurrentPage = async (): Promise<CommentItem[]> => {
  3739. logger.info('Extracting comments from current page...');
  3740. // 滚动页面加载所有评论
  3741. await page.evaluate(async () => {
  3742. // 滚动多次加载更多评论
  3743. for (let i = 0; i < 10; i++) {
  3744. window.scrollBy(0, 500);
  3745. await new Promise(r => setTimeout(r, 800));
  3746. }
  3747. window.scrollTo(0, 0);
  3748. });
  3749. await page.waitForTimeout(2000);
  3750. // 使用精确选择器提取评论
  3751. const comments = await page.evaluate(() => {
  3752. const result: Array<{
  3753. commentId: string;
  3754. authorId: string;
  3755. authorName: string;
  3756. authorAvatar: string;
  3757. content: string;
  3758. likeCount: number;
  3759. commentTime: string;
  3760. }> = [];
  3761. const seenContents = new Set<string>();
  3762. // 查找所有评论容器:包含 username 和 comment-content-text 的 container
  3763. const allContainers = document.querySelectorAll('[class*="container-"]');
  3764. const commentContainers: Element[] = [];
  3765. allContainers.forEach(container => {
  3766. const hasUsername = container.querySelector('[class*="username-"]');
  3767. const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
  3768. if (hasUsername && hasCommentContent) {
  3769. commentContainers.push(container);
  3770. }
  3771. });
  3772. console.log(`Found ${commentContainers.length} comment containers`);
  3773. commentContainers.forEach((container, index) => {
  3774. try {
  3775. // 用户名
  3776. const usernameEl = container.querySelector('[class*="username-"]');
  3777. const authorName = usernameEl?.textContent?.trim() || '未知用户';
  3778. // 时间
  3779. const timeEl = container.querySelector('[class*="time-"]');
  3780. const commentTime = timeEl?.textContent?.trim() || '';
  3781. // 评论内容
  3782. const contentEl = container.querySelector('[class*="comment-content-text-"]');
  3783. const content = contentEl?.textContent?.trim() || '';
  3784. if (!content) return;
  3785. // 头像
  3786. const avatarContainer = container.querySelector('[class*="avatar-"]');
  3787. const avatarImg = avatarContainer?.querySelector('img');
  3788. const authorAvatar = avatarImg?.src || '';
  3789. // 去重
  3790. const key = `${authorName}||${content}`;
  3791. if (seenContents.has(key)) return;
  3792. seenContents.add(key);
  3793. // 点赞数
  3794. let likeCount = 0;
  3795. const opsEl = container.querySelector('[class*="operations-"]');
  3796. if (opsEl) {
  3797. const itemEl = opsEl.querySelector('[class*="item-"]');
  3798. if (itemEl) {
  3799. const match = itemEl.textContent?.match(/(\d+)/);
  3800. if (match) likeCount = parseInt(match[1], 10);
  3801. }
  3802. }
  3803. // 生成 ID
  3804. const hash = content.slice(0, 30) + authorName + commentTime;
  3805. const commentId = `dy_${btoa(encodeURIComponent(hash)).slice(0, 20)}`;
  3806. result.push({
  3807. commentId,
  3808. authorId: authorName,
  3809. authorName,
  3810. authorAvatar,
  3811. content,
  3812. likeCount,
  3813. commentTime,
  3814. });
  3815. console.log(`[${index}] ${authorName}: ${content.slice(0, 30)}`);
  3816. } catch (e) {
  3817. console.error(`Error at ${index}:`, e);
  3818. }
  3819. });
  3820. return result;
  3821. });
  3822. logger.info(`Extracted ${comments.length} comments`);
  3823. return comments;
  3824. };
  3825. // 辅助函数:获取当前显示的作品标题
  3826. const getCurrentWorkTitle = async (): Promise<string> => {
  3827. return page.evaluate(() => {
  3828. // 查找作品标题 - 通常在页面顶部区域
  3829. // 排除筛选器和按钮中的文本
  3830. const excludeTexts = ['全部评论', '最新发布', '全部人群', '搜索', '选择作品', '评论管理'];
  3831. // 方法1: 查找视频信息区域
  3832. const videoInfoSelectors = [
  3833. '[class*="video-info"] [class*="title"]',
  3834. '[class*="work-info"] [class*="title"]',
  3835. '[class*="content-info"] [class*="title"]',
  3836. ];
  3837. for (const selector of videoInfoSelectors) {
  3838. const el = document.querySelector(selector);
  3839. if (el?.textContent) {
  3840. const text = el.textContent.trim();
  3841. if (text.length > 5 && !excludeTexts.some(e => text.includes(e))) {
  3842. return text;
  3843. }
  3844. }
  3845. }
  3846. // 方法2: 查找页面上较长的标题文本
  3847. const allTexts = document.querySelectorAll('div, span, p');
  3848. for (const el of Array.from(allTexts)) {
  3849. const text = el.textContent?.trim() || '';
  3850. if (text.length > 20 &&
  3851. text.length < 200 &&
  3852. !excludeTexts.some(e => text.includes(e)) &&
  3853. !el.closest('button') &&
  3854. !el.closest('[class*="select"]') &&
  3855. !el.closest('[class*="filter"]')) {
  3856. // 检查是否可能是作品标题(通常包含特定字符或格式)
  3857. if (text.includes('#') || text.match(/[,。!?、]/)) {
  3858. return text;
  3859. }
  3860. }
  3861. }
  3862. return '';
  3863. });
  3864. };
  3865. // 步骤1: 先获取当前页面显示的评论(默认显示的第一个作品)
  3866. logger.info('Step 1: Getting comments from default view...');
  3867. const defaultTitle = await getCurrentWorkTitle();
  3868. const defaultComments = await extractCommentsFromCurrentPage();
  3869. if (defaultComments.length > 0) {
  3870. allWorkComments.push({
  3871. videoId: `video_${Date.now()}`,
  3872. videoTitle: defaultTitle || '默认作品',
  3873. videoCoverUrl: '',
  3874. comments: defaultComments,
  3875. });
  3876. logger.info(`Got ${defaultComments.length} comments from default view, title: "${defaultTitle.slice(0, 50)}"`);
  3877. }
  3878. // 步骤2: 尝试点击"选择作品"按钮获取更多作品的评论
  3879. logger.info('Step 2: Looking for "选择作品" button...');
  3880. // 使用 locator 查找按钮
  3881. const selectBtn = page.locator('text=选择作品').first();
  3882. const btnCount = await selectBtn.count();
  3883. logger.info(`Found ${btnCount} "选择作品" button(s)`);
  3884. if (btnCount > 0) {
  3885. logger.info('Clicking "选择作品" button...');
  3886. await selectBtn.click();
  3887. // 等待更长时间,确保弹窗完全加载
  3888. logger.info('Waiting for work list modal to appear...');
  3889. await page.waitForTimeout(5000);
  3890. // 打印当前页面状态,帮助调试
  3891. const modalInfo = await page.evaluate(() => {
  3892. // 查找所有可能的弹窗元素
  3893. const modals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="drawer"], [class*="dialog"], [role="dialog"]');
  3894. const modalClasses = Array.from(modals).map(m => m.className).slice(0, 5);
  3895. // 查找所有图片(作品封面)
  3896. const images = document.querySelectorAll('img[src*="douyinpic"]');
  3897. // 查找所有可能的卡片元素
  3898. const cards = document.querySelectorAll('[class*="card"], [class*="item"]');
  3899. const cardClasses = Array.from(cards).map(c => c.className).slice(0, 10);
  3900. return {
  3901. modalCount: modals.length,
  3902. modalClasses,
  3903. imageCount: images.length,
  3904. cardCount: cards.length,
  3905. cardClasses,
  3906. };
  3907. });
  3908. logger.info(`Modal debug: ${JSON.stringify(modalInfo)}`);
  3909. // 尝试多种选择器查找作品列表
  3910. const workSelectors = [
  3911. '[class*="video-card"]',
  3912. '[class*="work-item"]',
  3913. '[class*="content-item"]',
  3914. '[class*="modal"] [class*="card"]',
  3915. '[class*="modal"] img',
  3916. '[class*="drawer"] [class*="card"]',
  3917. '[class*="drawer"] img',
  3918. '[role="dialog"] [class*="card"]',
  3919. '[role="dialog"] img',
  3920. '[class*="popup"] img',
  3921. 'img[src*="douyinpic"]', // 直接找抖音图片
  3922. ];
  3923. let workElements: Awaited<ReturnType<typeof page.$$>> = [];
  3924. let usedSelector = '';
  3925. for (const selector of workSelectors) {
  3926. const elements = await page.$$(selector);
  3927. logger.info(`Selector "${selector}" found ${elements.length} elements`);
  3928. if (elements.length > 0 && elements.length < 50) { // 避免选中太多无关元素
  3929. workElements = elements;
  3930. usedSelector = selector;
  3931. break;
  3932. }
  3933. }
  3934. logger.info(`Using selector "${usedSelector}", found ${workElements.length} work items`);
  3935. if (workElements.length > 0) {
  3936. // 首先获取所有作品的评论数信息
  3937. // 根据 HTML 结构:
  3938. // - 作品项容器: div.container-Lkxos9 (类名可能变化,使用 [class*="container-"])
  3939. // - 标题: div.title-LUOP3b (类名可能变化,使用 [class*="title-"])
  3940. // - 评论数: div.right-os7ZB9 > div (类名可能变化,使用 [class*="right-"] > div)
  3941. const workInfoList = await page.evaluate(() => {
  3942. const works: Array<{ index: number; title: string; commentCount: number }> = [];
  3943. // 查找作品列表容器中的所有作品项
  3944. // 根据用户提供的 HTML,作品项的类名是 container-Lkxos9
  3945. const workContainers = document.querySelectorAll('[role="dialog"] [class*="container-"]');
  3946. console.log(`Found ${workContainers.length} work containers`);
  3947. workContainers.forEach((container, index) => {
  3948. // 检查是否包含图片(确认是作品项而不是其他容器)
  3949. const img = container.querySelector('img[src*="douyinpic"]');
  3950. if (!img) {
  3951. console.log(`Container ${index} has no douyinpic image, skipping`);
  3952. return;
  3953. }
  3954. // 提取标题
  3955. const titleEl = container.querySelector('[class*="title-"]');
  3956. const title = titleEl?.textContent?.trim() || `作品 ${works.length + 1}`;
  3957. // 提取评论数 - 在 right- 容器的最后一个 div 中
  3958. let commentCount = 0;
  3959. const rightContainer = container.querySelector('[class*="right-"]');
  3960. if (rightContainer) {
  3961. // 获取 right 容器下的所有直接 div 子元素
  3962. const divs = rightContainer.querySelectorAll(':scope > div');
  3963. if (divs.length > 0) {
  3964. // 最后一个 div 包含评论数
  3965. const lastDiv = divs[divs.length - 1];
  3966. const text = lastDiv.textContent?.trim() || '0';
  3967. const num = parseInt(text, 10);
  3968. if (!isNaN(num)) {
  3969. commentCount = num;
  3970. }
  3971. }
  3972. }
  3973. console.log(`Work ${works.length}: title="${title.slice(0, 30)}...", commentCount=${commentCount}`);
  3974. works.push({
  3975. index: works.length,
  3976. title: title.slice(0, 100),
  3977. commentCount
  3978. });
  3979. });
  3980. // 如果上面的选择器没找到,尝试备用方法
  3981. if (works.length === 0) {
  3982. console.log('Primary selector failed, trying fallback...');
  3983. // 直接查找包含 douyinpic 图片的元素的父容器
  3984. const images = document.querySelectorAll('[role="dialog"] img[src*="douyinpic"]');
  3985. images.forEach((img, index) => {
  3986. // 向上查找到作品项容器
  3987. let container = img.parentElement;
  3988. while (container && !container.classList.toString().includes('container-')) {
  3989. container = container.parentElement;
  3990. }
  3991. if (container) {
  3992. const titleEl = container.querySelector('[class*="title-"]');
  3993. const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
  3994. // 查找评论数
  3995. let commentCount = 0;
  3996. const rightEl = container.querySelector('[class*="right-"]');
  3997. if (rightEl) {
  3998. const text = rightEl.textContent?.trim() || '';
  3999. // 提取最后出现的数字
  4000. const matches = text.match(/\d+/g);
  4001. if (matches && matches.length > 0) {
  4002. commentCount = parseInt(matches[matches.length - 1], 10);
  4003. }
  4004. }
  4005. works.push({ index, title: title.slice(0, 100), commentCount });
  4006. }
  4007. });
  4008. }
  4009. return works;
  4010. });
  4011. logger.info(`Work info list (${workInfoList.length} items): ${JSON.stringify(workInfoList)}`);
  4012. // 过滤出评论数 > 0 的作品,或者评论数未知(-1)的作品
  4013. const worksWithComments = workInfoList.filter(w => w.commentCount > 0 || w.commentCount === -1);
  4014. logger.info(`Found ${worksWithComments.length} works with comments > 0 or unknown (out of ${workInfoList.length})`);
  4015. // 如果所有作品评论数都是0,则不处理任何作品
  4016. const allZero = workInfoList.every(w => w.commentCount === 0);
  4017. if (allZero) {
  4018. logger.info('All works have 0 comments, skipping all');
  4019. }
  4020. // 如果没有找到评论数信息或有未知的,处理这些作品
  4021. const indicesToProcess = allZero
  4022. ? []
  4023. : (worksWithComments.length > 0
  4024. ? worksWithComments.map(w => w.index)
  4025. : Array.from({ length: Math.min(workElements.length, 10) }, (_, i) => i));
  4026. logger.info(`Will process work indices: ${indicesToProcess.join(', ')}`);
  4027. // 遍历每个有评论的作品
  4028. for (let idx = 0; idx < indicesToProcess.length; idx++) {
  4029. const i = indicesToProcess[idx];
  4030. try {
  4031. const workInfo = workInfoList.find(w => w.index === i);
  4032. logger.info(`Processing work ${idx + 1}/${indicesToProcess.length} (index=${i}, title="${workInfo?.title}", expectedComments=${workInfo?.commentCount})...`);
  4033. // 重新打开选择作品弹窗
  4034. if (idx > 0) {
  4035. await selectBtn.click();
  4036. await page.waitForTimeout(3000);
  4037. }
  4038. // 重新获取元素列表(因为 DOM 可能已变化)
  4039. const currentItems = await page.$$(usedSelector);
  4040. if (i < currentItems.length) {
  4041. // 滚动到元素可见
  4042. await currentItems[i].scrollIntoViewIfNeeded();
  4043. await page.waitForTimeout(500);
  4044. // 点击元素
  4045. await currentItems[i].click();
  4046. await page.waitForTimeout(4000);
  4047. // 获取评论
  4048. const title = await getCurrentWorkTitle();
  4049. const comments = await extractCommentsFromCurrentPage();
  4050. logger.info(`Work index=${i}: title="${title.slice(0, 50)}", comments=${comments.length}`);
  4051. // 检查是否已经获取过这个作品的评论
  4052. const exists = allWorkComments.some(w =>
  4053. w.videoTitle === title ||
  4054. (w.comments.length > 0 && comments.length > 0 &&
  4055. w.comments[0].content === comments[0].content)
  4056. );
  4057. if (!exists && (comments.length > 0 || title)) {
  4058. allWorkComments.push({
  4059. videoId: `video_${Date.now()}_${i}`,
  4060. videoTitle: title || workInfo?.title || `作品 ${i + 1}`,
  4061. videoCoverUrl: '',
  4062. comments,
  4063. });
  4064. logger.info(`Work index=${i}: Saved ${comments.length} comments`);
  4065. } else {
  4066. logger.info(`Work index=${i}: Skipped (duplicate or empty)`);
  4067. }
  4068. }
  4069. } catch (err) {
  4070. logger.warn(`Error processing work index=${i}:`, err);
  4071. }
  4072. }
  4073. } else {
  4074. logger.warn('No work items found in modal');
  4075. }
  4076. // 按 Escape 关闭弹窗
  4077. try {
  4078. await page.keyboard.press('Escape');
  4079. await page.waitForTimeout(500);
  4080. } catch { }
  4081. } else {
  4082. logger.warn('"选择作品" button not found, only default comments will be returned');
  4083. }
  4084. await page.close();
  4085. await context.close();
  4086. await browser.close();
  4087. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  4088. logger.info(`Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  4089. return allWorkComments;
  4090. } catch (error) {
  4091. logger.error('Error fetching Douyin comments:', error);
  4092. try {
  4093. await browser.close();
  4094. } catch { }
  4095. return allWorkComments;
  4096. }
  4097. }
  4098. /**
  4099. * 通过 Python API 获取小红书评论 - 一次性获取所有作品的评论
  4100. */
  4101. private async fetchXiaohongshuCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
  4102. const cookieString = JSON.stringify(cookies);
  4103. logger.info('[Xiaohongshu Comments Python] Fetching all comments...');
  4104. const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
  4105. method: 'POST',
  4106. headers: { 'Content-Type': 'application/json' },
  4107. body: JSON.stringify({
  4108. platform: 'xiaohongshu',
  4109. cookie: cookieString,
  4110. }),
  4111. });
  4112. if (!response.ok) {
  4113. throw new Error(`Python API all_comments returned ${response.status}`);
  4114. }
  4115. const result = await response.json();
  4116. if (!result.success) {
  4117. throw new Error(result.error || 'Failed to get all comments');
  4118. }
  4119. const workComments = result.work_comments || [];
  4120. logger.info(`[Xiaohongshu Comments Python] Got ${workComments.length} works with comments`);
  4121. // 转换数据格式
  4122. const allWorkComments: WorkComments[] = workComments.map((wc: {
  4123. work_id: string;
  4124. title: string;
  4125. cover_url: string;
  4126. comments: Array<{
  4127. comment_id: string;
  4128. author_id: string;
  4129. author_name: string;
  4130. author_avatar: string;
  4131. content: string;
  4132. like_count: number;
  4133. create_time: string;
  4134. }>;
  4135. }) => ({
  4136. videoId: wc.work_id,
  4137. videoTitle: wc.title || '',
  4138. videoCoverUrl: wc.cover_url || '',
  4139. comments: (wc.comments || []).map(c => ({
  4140. commentId: c.comment_id,
  4141. authorId: c.author_id,
  4142. authorName: c.author_name,
  4143. authorAvatar: c.author_avatar,
  4144. content: c.content,
  4145. likeCount: c.like_count,
  4146. commentTime: c.create_time,
  4147. })),
  4148. }));
  4149. logger.info(`[Xiaohongshu Comments Python] Total: ${allWorkComments.length} works with comments`);
  4150. return allWorkComments;
  4151. }
  4152. /**
  4153. * 获取小红书评论 - 优先使用 Python API
  4154. */
  4155. async fetchXiaohongshuCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  4156. // 优先使用 Python API(分作品获取)
  4157. const pythonAvailable = await this.checkPythonServiceAvailable();
  4158. if (pythonAvailable) {
  4159. logger.info('[Xiaohongshu Comments] Using Python API...');
  4160. try {
  4161. const result = await this.fetchCommentsViaPythonApi('xiaohongshu', cookies);
  4162. if (result.length > 0) {
  4163. return result;
  4164. }
  4165. logger.info('[Xiaohongshu Comments] Python API returned empty, falling back to Playwright...');
  4166. } catch (pythonError) {
  4167. logger.warn('[Xiaohongshu Comments] Python API failed:', pythonError);
  4168. }
  4169. }
  4170. // 回退到 Playwright 方式
  4171. const browser = await chromium.launch({
  4172. headless: true,
  4173. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  4174. });
  4175. const allWorkComments: WorkComments[] = [];
  4176. try {
  4177. const context = await browser.newContext({
  4178. viewport: { width: 1920, height: 1080 },
  4179. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  4180. });
  4181. // 设置 Cookie
  4182. const playwrightCookies = cookies.map(c => ({
  4183. name: c.name,
  4184. value: c.value,
  4185. domain: c.domain || '.xiaohongshu.com',
  4186. path: c.path || '/',
  4187. }));
  4188. await context.addCookies(playwrightCookies);
  4189. logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);
  4190. const page = await context.newPage();
  4191. // 用于捕获评论数据
  4192. const capturedComments: Map<string, CommentItem[]> = new Map();
  4193. const capturedNotes: Array<{
  4194. noteId: string;
  4195. title: string;
  4196. coverUrl: string;
  4197. }> = [];
  4198. // 设置 API 响应监听器
  4199. page.on('response', async (response) => {
  4200. const url = response.url();
  4201. try {
  4202. // 监听笔记列表 API
  4203. if (url.includes('/api/galaxy/creator/content/note_list') ||
  4204. url.includes('/api/galaxy/creator/notes')) {
  4205. const data = await response.json();
  4206. logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
  4207. const notes = data?.data?.notes || data?.data?.list || [];
  4208. for (const note of notes) {
  4209. capturedNotes.push({
  4210. noteId: note.note_id || note.id || '',
  4211. title: note.title || note.desc || '',
  4212. coverUrl: note.cover?.url || note.cover || '',
  4213. });
  4214. }
  4215. }
  4216. // 监听评论列表 API
  4217. if (url.includes('/api/sns/web/v2/comment/page') ||
  4218. url.includes('/api/galaxy/creator/comment') ||
  4219. url.includes('/api/sns/v1/note/comment')) {
  4220. const data = await response.json();
  4221. logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
  4222. const comments: CommentItem[] = [];
  4223. const commentList = data?.data?.comments || data?.comments || [];
  4224. for (const comment of commentList) {
  4225. comments.push({
  4226. commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
  4227. authorId: comment.user_info?.user_id || comment.user_id || '',
  4228. authorName: comment.user_info?.nickname || comment.nickname || '',
  4229. authorAvatar: comment.user_info?.image || comment.avatar || '',
  4230. content: comment.content || '',
  4231. likeCount: comment.like_count || 0,
  4232. commentTime: comment.create_time || comment.time || '',
  4233. parentCommentId: comment.target_comment_id || undefined,
  4234. });
  4235. // 处理子评论
  4236. const subComments = comment.sub_comments || comment.replies || [];
  4237. for (const sub of subComments) {
  4238. comments.push({
  4239. commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
  4240. authorId: sub.user_info?.user_id || sub.user_id || '',
  4241. authorName: sub.user_info?.nickname || sub.nickname || '',
  4242. authorAvatar: sub.user_info?.image || sub.avatar || '',
  4243. content: sub.content || '',
  4244. likeCount: sub.like_count || 0,
  4245. commentTime: sub.create_time || sub.time || '',
  4246. parentCommentId: comment.id || comment.comment_id || undefined,
  4247. });
  4248. }
  4249. }
  4250. // 尝试从 URL 获取笔记 ID
  4251. const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
  4252. const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;
  4253. if (comments.length > 0) {
  4254. const existing = capturedComments.get(noteId) || [];
  4255. capturedComments.set(noteId, [...existing, ...comments]);
  4256. }
  4257. }
  4258. } catch { }
  4259. });
  4260. // 导航到评论管理页面
  4261. logger.info('[Xiaohongshu Comments] Navigating to comment management...');
  4262. await page.goto('https://creator.xiaohongshu.com/creator/comment', {
  4263. waitUntil: 'domcontentloaded',
  4264. timeout: 60000,
  4265. });
  4266. await page.waitForTimeout(5000);
  4267. // 检查是否需要登录
  4268. const currentUrl = page.url();
  4269. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  4270. logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
  4271. await browser.close();
  4272. return allWorkComments;
  4273. }
  4274. // 尝试加载更多评论
  4275. for (let i = 0; i < 5; i++) {
  4276. await page.evaluate(() => {
  4277. window.scrollBy(0, 500);
  4278. });
  4279. await page.waitForTimeout(1000);
  4280. }
  4281. // 等待 API 响应
  4282. await page.waitForTimeout(3000);
  4283. // 将捕获的评论转换为 WorkComments 格式
  4284. for (const [noteId, comments] of capturedComments) {
  4285. const noteInfo = capturedNotes.find(n => n.noteId === noteId);
  4286. allWorkComments.push({
  4287. videoId: noteId,
  4288. videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
  4289. videoCoverUrl: noteInfo?.coverUrl || '',
  4290. comments,
  4291. });
  4292. }
  4293. // 如果没有从 API 获取到评论,尝试从页面提取
  4294. if (allWorkComments.length === 0) {
  4295. logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');
  4296. const pageComments = await page.evaluate(() => {
  4297. const result: Array<{
  4298. commentId: string;
  4299. authorName: string;
  4300. authorAvatar: string;
  4301. content: string;
  4302. likeCount: number;
  4303. commentTime: string;
  4304. }> = [];
  4305. const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
  4306. commentItems.forEach((item, index) => {
  4307. try {
  4308. const authorEl = item.querySelector('[class*="author"], [class*="name"]');
  4309. const avatarEl = item.querySelector('img');
  4310. const contentEl = item.querySelector('[class*="content"]');
  4311. const timeEl = item.querySelector('[class*="time"]');
  4312. const likeEl = item.querySelector('[class*="like"] span');
  4313. result.push({
  4314. commentId: `xhs_page_${index}`,
  4315. authorName: authorEl?.textContent?.trim() || '',
  4316. authorAvatar: avatarEl?.src || '',
  4317. content: contentEl?.textContent?.trim() || '',
  4318. likeCount: parseInt(likeEl?.textContent || '0') || 0,
  4319. commentTime: timeEl?.textContent?.trim() || '',
  4320. });
  4321. } catch { }
  4322. });
  4323. return result;
  4324. });
  4325. if (pageComments.length > 0) {
  4326. allWorkComments.push({
  4327. videoId: 'page_comments',
  4328. videoTitle: '页面评论',
  4329. videoCoverUrl: '',
  4330. comments: pageComments.map(c => ({
  4331. ...c,
  4332. authorId: '',
  4333. })),
  4334. });
  4335. }
  4336. }
  4337. await page.close();
  4338. await context.close();
  4339. await browser.close();
  4340. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  4341. logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  4342. return allWorkComments;
  4343. } catch (error) {
  4344. logger.error('[Xiaohongshu Comments] Error:', error);
  4345. try {
  4346. await browser.close();
  4347. } catch { }
  4348. return allWorkComments;
  4349. }
  4350. }
  4351. /**
  4352. * 获取微信视频号评论 - 优先使用 Python API
  4353. */
  4354. async fetchWeixinVideoCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
  4355. // 优先使用 Python API(分作品获取)
  4356. const pythonAvailable = await this.checkPythonServiceAvailable();
  4357. if (pythonAvailable) {
  4358. logger.info('[Weixin Video Comments] Using Python API...');
  4359. try {
  4360. const result = await this.fetchCommentsViaPythonApi('weixin', cookies);
  4361. if (result.length > 0) {
  4362. return result;
  4363. }
  4364. logger.info('[Weixin Video Comments] Python API returned empty, falling back to Playwright...');
  4365. } catch (pythonError) {
  4366. logger.warn('[Weixin Video Comments] Python API failed:', pythonError);
  4367. }
  4368. }
  4369. // 回退到 Playwright 方式
  4370. const browser = await chromium.launch({
  4371. headless: true,
  4372. args: ['--no-sandbox', '--disable-setuid-sandbox'],
  4373. });
  4374. const allWorkComments: WorkComments[] = [];
  4375. try {
  4376. const context = await browser.newContext({
  4377. viewport: { width: 1920, height: 1080 },
  4378. userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  4379. });
  4380. // 设置 Cookie
  4381. const playwrightCookies = cookies.map(c => ({
  4382. name: c.name,
  4383. value: c.value,
  4384. domain: c.domain || '.weixin.qq.com',
  4385. path: c.path || '/',
  4386. }));
  4387. await context.addCookies(playwrightCookies);
  4388. logger.info(`[Weixin Video Comments] Set ${playwrightCookies.length} cookies`);
  4389. const page = await context.newPage();
  4390. // 用于捕获评论数据
  4391. const capturedComments: Map<string, CommentItem[]> = new Map();
  4392. const capturedWorks: Array<{
  4393. workId: string;
  4394. title: string;
  4395. coverUrl: string;
  4396. }> = [];
  4397. // 设置 API 响应监听器
  4398. page.on('response', async (response) => {
  4399. const url = response.url();
  4400. try {
  4401. // 监听作品列表 API
  4402. if (url.includes('/mmfinderassistant-bin/post/post_list')) {
  4403. const data = await response.json();
  4404. logger.info(`[Weixin Video API] Works list: ${JSON.stringify(data).slice(0, 500)}`);
  4405. const posts = data?.data?.list || [];
  4406. for (const post of posts) {
  4407. capturedWorks.push({
  4408. workId: post.objectNonce || post.id || '',
  4409. title: post.title || post.desc || '',
  4410. coverUrl: post.cover?.url || post.cover || '',
  4411. });
  4412. }
  4413. }
  4414. // 监听评论列表 API
  4415. if (url.includes('/mmfinderassistant-bin/comment/comment_list')) {
  4416. const data = await response.json();
  4417. logger.info(`[Weixin Video API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
  4418. const comments: CommentItem[] = [];
  4419. const commentList = data?.data?.commentList || data?.comments || [];
  4420. for (const comment of commentList) {
  4421. comments.push({
  4422. commentId: comment.commentId || comment.id || `weixin_${Date.now()}`,
  4423. authorId: comment.commenterInfo?.identifier || comment.authorId || '',
  4424. authorName: comment.commenterInfo?.nickName || comment.nickname || comment.nick_name || '',
  4425. authorAvatar: comment.commenterInfo?.headUrl || comment.avatar || '',
  4426. content: comment.content || '',
  4427. likeCount: comment.likeCnt || comment.like_count || 0,
  4428. commentTime: comment.createTime || comment.create_time || '',
  4429. parentCommentId: comment.parentCommentId || undefined,
  4430. });
  4431. // 处理子评论
  4432. const subComments = comment.subCommentList || comment.sub_comments || [];
  4433. for (const sub of subComments) {
  4434. comments.push({
  4435. commentId: sub.commentId || sub.id || `weixin_sub_${Date.now()}`,
  4436. authorId: sub.commenterInfo?.identifier || sub.authorId || '',
  4437. authorName: sub.commenterInfo?.nickName || sub.nickname || sub.nick_name || '',
  4438. authorAvatar: sub.commenterInfo?.headUrl || sub.avatar || '',
  4439. content: sub.content || '',
  4440. likeCount: sub.likeCnt || sub.like_count || 0,
  4441. commentTime: sub.createTime || sub.create_time || '',
  4442. parentCommentId: comment.commentId || comment.id || undefined,
  4443. });
  4444. }
  4445. }
  4446. // 尝试从 URL 获取作品 ID
  4447. const workIdMatch = url.match(/objectNonce=([^&]+)/) || url.match(/workId=([^&]+)/);
  4448. const workId = workIdMatch?.[1] || `work_${Date.now()}`;
  4449. if (comments.length > 0) {
  4450. const existing = capturedComments.get(workId) || [];
  4451. capturedComments.set(workId, [...existing, ...comments]);
  4452. }
  4453. }
  4454. } catch { }
  4455. });
  4456. // 导航到评论管理页面
  4457. logger.info('[Weixin Video Comments] Navigating to comment management...');
  4458. await page.goto('https://channels.weixin.qq.com/platform/interaction/comment', {
  4459. waitUntil: 'domcontentloaded',
  4460. timeout: 60000,
  4461. });
  4462. await page.waitForTimeout(5000);
  4463. // 检查是否需要登录
  4464. const currentUrl = page.url();
  4465. if (currentUrl.includes('login') || currentUrl.includes('passport')) {
  4466. logger.warn('[Weixin Video Comments] Cookie expired, need re-login');
  4467. await browser.close();
  4468. return allWorkComments;
  4469. }
  4470. // 尝试加载更多评论
  4471. for (let i = 0; i < 5; i++) {
  4472. await page.evaluate(() => {
  4473. window.scrollBy(0, 500);
  4474. });
  4475. await page.waitForTimeout(1000);
  4476. }
  4477. // 等待 API 响应
  4478. await page.waitForTimeout(3000);
  4479. // 将捕获的评论转换为 WorkComments 格式
  4480. for (const [workId, comments] of capturedComments) {
  4481. const workInfo = capturedWorks.find(w => w.workId === workId);
  4482. allWorkComments.push({
  4483. videoId: workId,
  4484. videoTitle: workInfo?.title || `作品 ${workId.slice(0, 10)}`,
  4485. videoCoverUrl: workInfo?.coverUrl || '',
  4486. comments,
  4487. });
  4488. }
  4489. // 如果没有从 API 获取到评论,尝试从页面提取
  4490. if (allWorkComments.length === 0) {
  4491. logger.info('[Weixin Video Comments] No comments from API, extracting from page...');
  4492. const pageComments = await page.evaluate(() => {
  4493. const result: Array<{
  4494. commentId: string;
  4495. authorName: string;
  4496. authorAvatar: string;
  4497. content: string;
  4498. likeCount: number;
  4499. commentTime: string;
  4500. }> = [];
  4501. const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
  4502. commentItems.forEach((item, index) => {
  4503. try {
  4504. const authorEl = item.querySelector('[class*="author"], [class*="name"]');
  4505. const avatarEl = item.querySelector('img');
  4506. const contentEl = item.querySelector('[class*="content"]');
  4507. const timeEl = item.querySelector('[class*="time"]');
  4508. const likeEl = item.querySelector('[class*="like"] span');
  4509. result.push({
  4510. commentId: `weixin_page_${index}`,
  4511. authorName: authorEl?.textContent?.trim() || '',
  4512. authorAvatar: avatarEl?.src || '',
  4513. content: contentEl?.textContent?.trim() || '',
  4514. likeCount: parseInt(likeEl?.textContent || '0') || 0,
  4515. commentTime: timeEl?.textContent?.trim() || '',
  4516. });
  4517. } catch { }
  4518. });
  4519. return result;
  4520. });
  4521. if (pageComments.length > 0) {
  4522. allWorkComments.push({
  4523. videoId: 'page_comments',
  4524. videoTitle: '页面评论',
  4525. videoCoverUrl: '',
  4526. comments: pageComments.map(c => ({
  4527. ...c,
  4528. authorId: '',
  4529. })),
  4530. });
  4531. }
  4532. }
  4533. await page.close();
  4534. await context.close();
  4535. await browser.close();
  4536. const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
  4537. logger.info(`[Weixin Video Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
  4538. return allWorkComments;
  4539. } catch (error) {
  4540. logger.error('[Weixin Video Comments] Error:', error);
  4541. try {
  4542. await browser.close();
  4543. } catch { }
  4544. return allWorkComments;
  4545. }
  4546. }
  4547. }
  4548. export const headlessBrowserService = new HeadlessBrowserService();