HeadlessBrowserService.ts 210 KB

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