HeadlessBrowserService.ts 210 KB

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