| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481 |
- /// <reference lib="dom" />
- import { chromium, type BrowserContext, type Page } from 'playwright';
- import { logger } from '../utils/logger.js';
- import { extractDeclaredNotesCountFromPostedResponse } from '../utils/xiaohongshu.js';
- import type { PlatformType } from '@media-manager/shared';
- import { getPythonServiceBaseUrl } from './PythonServiceConfigService.js';
- // 抖音 API 接口配置
- const DOUYIN_API = {
- // 检查用户登录状态 - 返回 result: true 表示已登录(需要在浏览器上下文中调用)
- CHECK_USER: '/aweme/v1/creator/check/user/',
- // 获取作品列表(新接口,支持分页)
- WORK_LIST: 'https://creator.douyin.com/janus/douyin/creator/pc/work_list',
- // 获取评论列表
- COMMENT_LIST: 'https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/',
- // 创作者首页(用于触发登录检查)
- CREATOR_HOME: 'https://creator.douyin.com/creator-micro/home',
- };
- // 平台 API 配置(用于直接 HTTP 请求检查)
- const PLATFORM_API_CONFIG: Record<string, {
- checkUrl: string;
- isValidResponse: (data: unknown) => boolean;
- }> = {
- douyin: {
- // 使用账号基础信息接口检查 Cookie 有效性
- checkUrl: 'https://creator.douyin.com/web/api/creator/mcn/account_base_info?show_mcn_status=1',
- isValidResponse: (data: unknown) => {
- const resp = data as { status_code?: number; BaseResp?: { StatusCode?: number } };
- // status_code 为 0 表示 Cookie 有效
- return resp?.status_code === 0 || resp?.BaseResp?.StatusCode === 0;
- },
- },
- baijiahao: {
- // 使用 appinfo 接口检查 Cookie 有效性
- checkUrl: 'https://baijiahao.baidu.com/builder/app/appinfo',
- isValidResponse: (data: unknown) => {
- const resp = data as {
- errno?: number;
- errmsg?: string;
- data?: {
- user?: {
- name?: string;
- app_id?: string | number;
- userid?: number;
- status?: string;
- }
- }
- };
- 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}`);
- // errno 为 0 表示请求成功
- const isErrnoOk = resp?.errno === 0;
- // 必须有用户信息(name 或 app_id)
- const hasUserInfo = !!(resp?.data?.user?.name || resp?.data?.user?.app_id);
- // 用户状态不能是 'banned' 或其他异常状态(兼容 normal 等常见正常状态)
- const userStatus = resp?.data?.user?.status;
- const isStatusOk = !userStatus || ['audit', 'pass', 'active', 'normal'].includes(String(userStatus));
- const isValid = isErrnoOk && hasUserInfo && isStatusOk;
- if (!isValid) {
- logger.warn(`[Baijiahao] Cookie invalid: errno=${resp?.errno}, hasUserInfo=${hasUserInfo}, status=${userStatus}`);
- }
- return isValid;
- },
- },
- };
- export interface AccountInfo {
- accountId: string;
- accountName: string;
- avatarUrl: string;
- fansCount?: number;
- worksCount: number;
- worksList?: WorkItem[];
- worksListComplete?: boolean;
- source?: 'python' | 'playwright' | 'api';
- pythonAvailable?: boolean;
- }
- export interface WorkItem {
- videoId?: string;
- title: string;
- coverUrl: string;
- /** 作品播放/详情页 URL,同步到 works.video_url */
- videoUrl?: string;
- duration: string;
- publishTime: string;
- status: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- collectCount?: number;
- }
- export interface CommentItem {
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- parentCommentId?: string;
- videoId?: string;
- videoTitle?: string;
- videoCoverUrl?: string;
- }
- export interface WorkComments {
- videoId: string;
- videoTitle: string;
- videoCoverUrl: string;
- comments: CommentItem[];
- }
- export interface CookieData {
- name: string;
- value: string;
- domain: string;
- path: string;
- }
- export type CookieCheckSource = 'python' | 'api' | 'browser';
- export type CookieCheckReason =
- | 'valid'
- | 'need_login'
- | 'risk_control'
- | 'uncertain';
- export interface CookieCheckResult {
- isValid: boolean;
- needReLogin: boolean;
- uncertain: boolean;
- reason: CookieCheckReason;
- source: CookieCheckSource;
- message?: string;
- }
- /**
- * 无头浏览器服务 - 用于后台静默获取账号信息
- */
- class HeadlessBrowserService {
- /**
- * 检查 Cookie 是否有效
- * 优先使用 Python 服务(通过浏览器访问后台检测),回退到 API 检查
- */
- async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
- const status = await this.checkCookieStatus(platform, cookies);
- return status.isValid || status.uncertain;
- }
- /**
- * 检查 Cookie 状态(有效 / 需要重新登录 / 不确定)
- */
- async checkCookieStatus(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
- logger.info(`[checkCookieStatus] Checking cookie for ${platform}, cookie count: ${cookies.length}`);
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- try {
- const result = await this.checkLoginStatusViaPython(platform, cookies);
- logger.info(
- `[checkCookieStatus] Python result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
- );
- return result;
- } catch (error) {
- logger.warn(`[Python API] Check login failed, falling back:`, error);
- }
- } else {
- logger.info(`[checkCookieStatus] Python service not available`);
- }
- const apiConfig = PLATFORM_API_CONFIG[platform];
- if (apiConfig) {
- const result = await this.checkCookieStatusByApi(platform, cookies, apiConfig);
- logger.info(
- `[checkCookieStatus] API result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
- );
- return result;
- }
- const result = await this.checkCookieStatusByBrowser(platform, cookies);
- logger.info(
- `[checkCookieStatus] Browser result for ${platform}: isValid=${result.isValid}, needReLogin=${result.needReLogin}, uncertain=${result.uncertain}, reason=${result.reason}`
- );
- return result;
- }
- private containsRiskKeywords(text: string): boolean {
- if (!text) return false;
- const lowered = text.toLowerCase();
- const keywords = [
- '验证码',
- '安全验证',
- '人机验证',
- '滑块',
- '风控',
- '风险',
- '访问受限',
- '行为异常',
- '系统检测到异常',
- '安全校验',
- 'captcha',
- 'verify',
- 'challenge',
- 'risk',
- 'security',
- 'safe',
- 'protect',
- 'blocked',
- ];
- return keywords.some(k => lowered.includes(k.toLowerCase()));
- }
- private async getPageBodyTextSafe(page: Page): Promise<string> {
- try {
- const content = await page.textContent('body');
- return (content || '').slice(0, 8000);
- } catch {
- return '';
- }
- }
- /**
- * 通过 Python 服务检查登录状态(浏览器访问后台页面,检测是否需要登录)
- */
- private async checkLoginStatusViaPython(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- // 构建 Cookie 字符串
- const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
- logger.info(`[Python API] Checking login status for ${platform}`);
- const response = await fetch(`${pythonUrl}/check_login`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API returned ${response.status}`);
- }
- const result = await response.json() as {
- success: boolean;
- valid: boolean;
- need_login: boolean;
- message?: string;
- error?: string;
- };
- logger.info(`[Python API] Check login result for ${platform}: valid=${result.valid}, need_login=${result.need_login}`);
- if (!result.success) {
- throw new Error(result.error || 'Check login failed');
- }
- const message = result.message || result.error || '';
- if (!result.valid || result.need_login) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: this.containsRiskKeywords(message) ? 'risk_control' : 'need_login',
- source: 'python',
- message,
- };
- }
- if (this.containsRiskKeywords(message)) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'python',
- message,
- };
- }
- return {
- isValid: true,
- needReLogin: false,
- uncertain: false,
- reason: 'valid',
- source: 'python',
- message,
- };
- }
- /**
- * 通过 API 检查 Cookie 是否有效
- * 注意:API 返回不确定状态时会回退到浏览器检查,避免误判
- */
- private async checkCookieStatusByApi(
- platform: PlatformType,
- cookies: CookieData[],
- apiConfig: typeof PLATFORM_API_CONFIG[string]
- ): Promise<CookieCheckResult> {
- try {
- // 构建 Cookie 字符串(所有 Cookie 拼接)
- const cookieString = cookies
- .map(c => `${c.name}=${c.value}`)
- .join('; ');
- logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);
- // 发起 API 请求,模拟浏览器请求
- const response = await fetch(apiConfig.checkUrl, {
- method: 'GET',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Cache-Control': 'no-cache',
- 'Cookie': cookieString,
- 'Pragma': 'no-cache',
- 'Referer': this.getPlatformReferer(platform),
- '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',
- 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
- 'sec-ch-ua-mobile': '?0',
- 'sec-ch-ua-platform': '"Windows"',
- 'sec-fetch-dest': 'empty',
- 'sec-fetch-mode': 'cors',
- 'sec-fetch-site': 'same-origin',
- },
- });
- const data = await response.json();
- logger.info(`[API] Raw response for ${platform}:`, JSON.stringify(data).substring(0, 500));
- const isValid = apiConfig.isValidResponse(data);
- const statusCode = (data as { status_code?: number; errno?: number; ret?: { errno?: number } })?.status_code
- ?? (data as { errno?: number })?.errno
- ?? (data as { ret?: { errno?: number } })?.ret?.errno;
- logger.info(`API check cookie for ${platform}: valid=${isValid}, statusCode=${statusCode}`);
- // 如果 API 明确返回有效,直接返回 true
- if (isValid) {
- const rawText = JSON.stringify(data).slice(0, 2000);
- if (this.containsRiskKeywords(rawText)) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'api',
- message: 'API 返回疑似风控/验证页面',
- };
- }
- return {
- isValid: true,
- needReLogin: false,
- uncertain: false,
- reason: 'valid',
- source: 'api',
- };
- }
- // API 返回无效时,检查是否是明确的"未登录"状态
- // 抖音: status_code 为 2 或 8 通常表示未登录/登录过期
- // 百家号: errno 为非 0 可能表示未登录,但需要根据具体错误码判断
- const clearlyNotLoggedIn = statusCode === 2 || statusCode === 8;
- if (clearlyNotLoggedIn) {
- logger.info(`[API] Platform ${platform} clearly not logged in (statusCode=${statusCode})`);
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'need_login',
- source: 'api',
- };
- }
- // 百家号特殊处理:API 用 Node fetch 调用时可能因分散认证等返回 errno !== 0,但 Cookie 在浏览器内仍有效
- // 因此当 API 判为无效时,回退到浏览器检查,避免“能登录后台却显示过期”
- if (platform === 'baijiahao') {
- const errno = (data as { errno?: number })?.errno;
- if (errno === 0 && isValid) {
- return { isValid: true, needReLogin: false, uncertain: false, reason: 'valid', source: 'api' };
- }
- if (errno === 0 && !isValid) {
- logger.warn(`[API] Baijiahao errno=0 but no user info, falling back to browser check`);
- return this.checkCookieStatusByBrowser(platform, cookies);
- }
- // errno 110 通常表示未登录,可直接判无效;其他 errno(如 10001402 分散认证)可能只是接口限制,用浏览器再判一次
- if (errno === 110) {
- logger.warn(`[API] Baijiahao errno=110 (not logged in), cookie invalid`);
- return { isValid: false, needReLogin: true, uncertain: false, reason: 'need_login', source: 'api' };
- }
- logger.info(`[API] Baijiahao errno=${errno}, falling back to browser check (may be dispersed auth)`);
- return this.checkCookieStatusByBrowser(platform, cookies);
- }
- // 不确定的状态(如 status_code=7),回退到浏览器检查
- logger.info(`[API] Uncertain status for ${platform} (statusCode=${statusCode}), falling back to browser check`);
- return this.checkCookieStatusByBrowser(platform, cookies);
- } catch (error) {
- logger.error(`API check cookie error for ${platform}:`, error);
- // API 检查失败时,回退到浏览器检查
- return this.checkCookieStatusByBrowser(platform, cookies);
- }
- }
- /**
- * 获取平台 Referer
- */
- private getPlatformReferer(platform: PlatformType): string {
- const referers: Record<string, string> = {
- douyin: 'https://creator.douyin.com/',
- bilibili: 'https://member.bilibili.com/',
- kuaishou: 'https://cp.kuaishou.com/',
- baijiahao: 'https://baijiahao.baidu.com/',
- };
- return referers[platform] || '';
- }
- /**
- * 通过浏览器检查 Cookie 是否有效(检查是否被重定向到登录页)
- * 注意:网络错误或服务不可用时返回 true(保持原状态),避免误判为过期
- */
- private async checkCookieStatusByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<CookieCheckResult> {
- // 对于抖音平台,使用 check/user 接口检查
- if (platform === 'douyin') {
- return this.checkDouyinLoginStatusByApi(cookies);
- }
- const browser = await chromium.launch({ headless: true });
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- const config = this.getPlatformConfig(platform);
- // #6065: 视频号使用专门的平台登录页检查(登录后 URL 含特定路径,非登录时可能不重定向)
- if (platform === 'weixin_video') {
- return this.checkWeixinVideoLoginStatusByBrowser(page, context, cookies, browser);
- }
- // 访问平台主页
- await page.goto(config.homeUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- const url = page.url();
- logger.info(`Browser check cookie for ${platform}: URL=${url}`);
- // 检查是否被重定向到登录页
- const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));
- const bodyText = await this.getPageBodyTextSafe(page);
- const isRiskControl = this.containsRiskKeywords(url) || this.containsRiskKeywords(bodyText);
- await page.close();
- await context.close();
- await browser.close();
- if (isLoginPage) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'need_login',
- source: 'browser',
- };
- }
- if (isRiskControl) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'browser',
- message: '检测到风控/验证页面',
- };
- }
- return {
- isValid: true,
- needReLogin: false,
- uncertain: false,
- reason: 'valid',
- source: 'browser',
- };
- } catch (error) {
- logger.error(`Browser check cookie error for ${platform}:`, error);
- await browser.close();
- return {
- isValid: false,
- needReLogin: false,
- uncertain: true,
- reason: 'uncertain',
- source: 'browser',
- message: error instanceof Error ? error.message : 'Browser check error',
- };
- }
- }
- /**
- * 抖音登录状态检查 - 通过监听 check/user 接口
- * 访问创作者首页,监听 check/user 接口返回的 result 字段判断登录状态
- */
- private async checkDouyinLoginStatusByApi(cookies: CookieData[]): Promise<CookieCheckResult> {
- const browser = await chromium.launch({ headless: true });
- let isLoggedIn = false;
- let checkCompleted = false;
- let isRiskControl = false;
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- // 监听 check/user 接口响应
- page.on('response', async (response) => {
- const url = response.url();
- if (url.includes(DOUYIN_API.CHECK_USER)) {
- try {
- const data = await response.json();
- // result: true 表示已登录
- isLoggedIn = data?.result === true && data?.status_code === 0;
- checkCompleted = true;
- logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
- } catch {
- // 忽略解析错误
- }
- }
- });
- // 访问创作者首页,触发 check/user 接口
- await page.goto(DOUYIN_API.CREATOR_HOME, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待接口响应或超时
- const startTime = Date.now();
- while (!checkCompleted && Date.now() - startTime < 10000) {
- await page.waitForTimeout(500);
- }
- // 如果没有收到 check/user 响应,检查 URL 是否被重定向到登录页
- if (!checkCompleted) {
- const currentUrl = page.url();
- isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
- logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
- }
- const finalUrl = page.url();
- const bodyText = await this.getPageBodyTextSafe(page);
- isRiskControl = this.containsRiskKeywords(finalUrl) || this.containsRiskKeywords(bodyText);
- await page.close();
- await context.close();
- await browser.close();
- if (isRiskControl) {
- return {
- isValid: false,
- needReLogin: true,
- uncertain: false,
- reason: 'risk_control',
- source: 'browser',
- message: '检测到风控/验证页面',
- };
- }
- return {
- isValid: isLoggedIn,
- needReLogin: !isLoggedIn,
- uncertain: false,
- reason: isLoggedIn ? 'valid' : 'need_login',
- source: 'browser',
- };
- } catch (error) {
- logger.error('[Douyin] checkDouyinLoginByApi error:', error);
- try {
- await browser.close();
- } catch { }
- return {
- isValid: false,
- needReLogin: false,
- uncertain: true,
- reason: 'uncertain',
- source: 'browser',
- message: error instanceof Error ? error.message : 'Douyin check error',
- };
- }
- }
- /**
- * #6065: 视频号登录状态检测 - 通过检查平台页面是否展示账号信息
- * 视频号 Cookie 失效时可能不重定向到登录页(URL 不变),需要正向信号判断
- */
- private async checkWeixinVideoLoginStatusByBrowser(
- page: Page,
- context: BrowserContext,
- cookies: CookieData[],
- browser: import('playwright').Browser
- ): Promise<CookieCheckResult> {
- try {
- // 视频号创作者平台需要等待加载完成后检测页面内容
- await page.goto('https://channels.weixin.qq.com/platform', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(5000);
- // 尝试等待网络空闲,给页面足够时间加载
- try {
- await page.waitForLoadState('networkidle', { timeout: 15000 });
- } catch {
- // 超时继续
- }
- const url = page.url();
- const bodyText = await this.getPageBodyTextSafe(page);
- logger.info(`[Weixin Video] Browser check: URL=${url}, bodyLen=${bodyText.length}`);
- // 检测明确的登录页特征
- if (url.includes('login.html') || url.includes('/login?') || url.includes('passport')) {
- logger.info('[Weixin Video] Redirected to login page');
- await page.close();
- await context.close();
- await browser.close();
- return { isValid: false, needReLogin: true, uncertain: false, reason: 'need_login', source: 'browser' };
- }
- // 检测风控
- if (this.containsRiskKeywords(url) || this.containsRiskKeywords(bodyText)) {
- logger.info('[Weixin Video] Detected risk control keywords');
- await page.close();
- await context.close();
- await browser.close();
- return { isValid: false, needReLogin: true, uncertain: false, reason: 'risk_control', source: 'browser', message: '检测到风控/验证页面' };
- }
- // #6065: 正向信号检测 - 检查页面上是否存在已登录的账号信息元素
- // 视频号登录后首页会出现 nickname、头像等元素
- const positiveSignals = [
- '.finder-nickname', // 视频号昵称
- '.avatar img[src]', // 头像图片
- '[class*="video-count"]', // 视频数
- '[class*="follower"]', // 关注者
- 'div.title-name', // 账号名称
- ];
- let hasPositiveSignal = false;
- for (const selector of positiveSignals) {
- try {
- const count = await page.locator(selector).count();
- if (count > 0) {
- hasPositiveSignal = true;
- logger.info(`[Weixin Video] Found positive signal: ${selector}`);
- break;
- }
- } catch {
- // continue
- }
- }
- // 额外检查:页面正文是否包含视频号管理页面的特征文本
- const hasManagementText = bodyText.includes('发表视频') ||
- bodyText.includes('数据中心') ||
- bodyText.includes('互动管理') ||
- bodyText.includes('内容管理');
- if (hasPositiveSignal || hasManagementText) {
- logger.info(`[Weixin Video] Cookie valid (positive signal=${hasPositiveSignal}, managementText=${hasManagementText})`);
- await page.close();
- await context.close();
- await browser.close();
- return { isValid: true, needReLogin: false, uncertain: false, reason: 'valid', source: 'browser' };
- }
- // 没有正向信号也没有登录指标 → 不确定(可能是页面加载慢或网络问题)
- logger.warn(`[Weixin Video] No positive or negative signals detected, marking as uncertain`);
- await page.close();
- await context.close();
- await browser.close();
- return { isValid: false, needReLogin: false, uncertain: true, reason: 'uncertain', source: 'browser', message: '无法确定视频号登录状态' };
- } catch (error) {
- logger.error('[Weixin Video] checkLoginByBrowser error:', error);
- try {
- await browser.close();
- } catch { /* ignore */ }
- return { isValid: false, needReLogin: false, uncertain: true, reason: 'uncertain', source: 'browser', message: error instanceof Error ? error.message : 'Weixin video check error' };
- }
- }
- /**
- * 访问平台后台页面并截图(用于 AI 分析)
- * @param platform 平台类型
- * @param cookies Cookie 数据
- * @returns Base64 编码的截图,失败返回 null
- */
- async capturePageScreenshot(platform: PlatformType, cookies: CookieData[]): Promise<string | null> {
- const browser = await chromium.launch({ headless: true });
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- await context.addCookies(cookies);
- const page = await context.newPage();
- const config = this.getPlatformConfig(platform);
- logger.info(`[Screenshot] Navigating to ${platform} home page: ${config.homeUrl}`);
- // 访问平台主页
- await page.goto(config.homeUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- const url = page.url();
- logger.info(`[Screenshot] Current URL: ${url}`);
- // 截图
- const screenshotBuffer = await page.screenshot({
- type: 'jpeg',
- quality: 80,
- fullPage: false,
- });
- const base64Screenshot = screenshotBuffer.toString('base64');
- await page.close();
- await context.close();
- await browser.close();
- logger.info(`[Screenshot] Captured screenshot for ${platform}, size: ${Math.round(base64Screenshot.length / 1024)}KB`);
- return base64Screenshot;
- } catch (error) {
- logger.error(`[Screenshot] Failed to capture screenshot for ${platform}:`, error);
- try {
- await browser.close();
- } catch { /* ignore */ }
- return null;
- }
- }
- /**
- * 检查 Python 服务是否可用
- */
- private async checkPythonServiceAvailable(): Promise<boolean> {
- try {
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- const response = await fetch(`${pythonUrl}/health`, {
- method: 'GET',
- signal: AbortSignal.timeout(3000),
- });
- return response.ok;
- } catch {
- return false;
- }
- }
- /**
- * 通过 Python API 获取作品列表
- */
- private async fetchWorksViaPython(
- platform: PlatformType,
- cookies: CookieData[],
- onPage?: (info: {
- platform: PlatformType;
- page: string;
- pageSize: number;
- fetched: number;
- newCount: number;
- totalSoFar: number;
- declaredTotal?: number;
- hasMore: boolean;
- nextPage?: unknown;
- }) => void
- ): Promise<{
- works: WorkItem[];
- total?: number;
- }> {
- logger.info(`[Python API] Fetching works for ${platform} (auto pagination)...`);
- const cookieString = JSON.stringify(cookies);
- const pythonPlatform = platform === 'weixin_video' ? 'weixin' : platform;
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- // 抖音 work_list 接口 count 最大 20,需与创作者中心一致
- const pageSize =
- platform === 'xiaohongshu' || platform === 'douyin' || platform === 'baijiahao'
- ? 20
- : 50;
- let maxPages = 30;
- const allWorks: WorkItem[] = [];
- const seenIds = new Set<string>();
- const legacyToCanonical = new Map<string, string>();
- let declaredTotal: number | undefined;
- let cursor: string | number = 0;
- const seenCursors = new Set<string>();
- // 抖音、小红书使用 cursor 分页;视频号使用 currentPage 页码(pageIndex 0,1,2...)
- const useCursorPagination = platform === 'xiaohongshu' || platform === 'douyin';
- for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
- const pageParam: number | string = useCursorPagination ? cursor : pageIndex;
- logger.info(`[Python API] Fetching works page=${String(pageParam)}, page_size=${pageSize} for ${platform}`);
- logger.info(`[Python API] 调用 Python /works: platform=${platform} -> pythonPlatform=${pythonPlatform}, page=${String(pageParam)}, url=${pythonUrl}`);
- const response: Response = await fetch(`${pythonUrl}/works`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- platform: pythonPlatform,
- cookie: cookieString,
- page: pageParam,
- page_size: pageSize,
- auto_paging: (platform === 'xiaohongshu' || platform === 'baijiahao') && pageIndex === 0,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API returned ${response.status}`);
- }
- const result: any = await response.json();
- if (pageIndex === 0) {
- 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'}`);
- if (result.error) {
- logger.warn(`[Python API] Error from Python service: ${result.error}`);
- }
- }
- if (!result.success) {
- logger.error(`[Python API] Python service returned error: ${result.error || 'Unknown error'}, full response: ${JSON.stringify(result).substring(0, 500)}`);
- throw new Error(result.error || 'Failed to get works');
- }
- if (typeof result.total === 'number' && result.total > 0) {
- declaredTotal = declaredTotal ? Math.max(declaredTotal, result.total) : result.total;
- if (pageIndex === 0) {
- maxPages = Math.min(400, Math.ceil(result.total / pageSize) + 5);
- }
- }
- const pageWorks: WorkItem[] = (result.works || []).map((work: {
- work_id: string;
- title: string;
- cover_url: string;
- video_url?: string;
- duration: number;
- publish_time: string;
- status: string;
- play_count: number;
- like_count: number;
- comment_count: number;
- share_count: number;
- collect_count?: number;
- }) => ({
- videoId: work.work_id,
- title: work.title,
- coverUrl: work.cover_url,
- videoUrl: work.video_url || '',
- duration: String(work.duration || 0),
- publishTime: work.publish_time,
- status: work.status || 'published',
- playCount: work.play_count || 0,
- likeCount: work.like_count || 0,
- commentCount: work.comment_count || 0,
- shareCount: work.share_count || 0,
- collectCount: work.collect_count ?? 0,
- }));
- let newCount = 0;
- for (const w of pageWorks) {
- const titleForId = (w.title || '').trim();
- const publishTimeForId = (w.publishTime || '').trim();
- const legacyId = `${platform}_${titleForId}_${publishTimeForId}`.substring(0, 100);
- let canonicalId = (w.videoId || '').trim() || legacyId;
- if (platform === 'weixin_video') {
- const rawId = (w.videoId || '').trim();
- if (rawId) {
- legacyToCanonical.set(legacyId, rawId);
- canonicalId = rawId;
- } else {
- const mapped = legacyToCanonical.get(legacyId);
- if (mapped) canonicalId = mapped;
- }
- }
- if (!seenIds.has(canonicalId)) {
- seenIds.add(canonicalId);
- allWorks.push({
- ...w,
- videoId: canonicalId,
- });
- newCount++;
- }
- }
- logger.info(
- `[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 ?? '')}`
- );
- onPage?.({
- platform,
- page: String(pageParam),
- pageSize,
- fetched: pageWorks.length,
- newCount,
- totalSoFar: allWorks.length,
- declaredTotal,
- hasMore: !!result.has_more,
- nextPage: result.next_page,
- });
- if (useCursorPagination) {
- const next: any = result.next_page;
- const hasNextCursor = next !== undefined && next !== null && next !== '' && next !== -1 && next !== '-1';
- if (hasNextCursor) {
- const key = String(next);
- if (seenCursors.has(key)) break;
- seenCursors.add(key);
- cursor = next;
- } else {
- if (platform === 'douyin') break;
- cursor = (typeof cursor === 'number' ? cursor + 1 : pageIndex + 1);
- }
- // 抖音:仅当无下一页游标或本页 0 条时停止
- if (platform === 'douyin') {
- if (!hasNextCursor || pageWorks.length === 0) break;
- } else {
- const expectedMore = declaredTotal && declaredTotal > 0 ? allWorks.length < declaredTotal : !!result.has_more;
- if (!expectedMore || pageWorks.length === 0 || newCount === 0) break;
- }
- } else {
- if (!result.has_more || pageWorks.length === 0 || newCount === 0) break;
- }
- }
- logger.info(`[Python API] Total works fetched for ${platform}: ${allWorks.length}`);
- return { works: allWorks, total: declaredTotal };
- }
- /**
- * 获取账号信息(优先使用 Python API,回退到无头浏览器)
- */
- async fetchAccountInfo(
- platform: PlatformType,
- cookies: CookieData[],
- options?: {
- onWorksFetchProgress?: (info: {
- platform: PlatformType;
- page: string;
- pageSize: number;
- fetched: number;
- newCount: number;
- totalSoFar: number;
- declaredTotal?: number;
- hasMore: boolean;
- nextPage?: unknown;
- }) => void;
- }
- ): Promise<AccountInfo> {
- logger.info(`[fetchAccountInfo] Starting for platform: ${platform}`);
- let pythonAvailable = false;
- // 百家号:优先走 Python 的 /account_info(包含粉丝数、作品数),避免 Node 直连分散认证问题
- if (platform === 'baijiahao') {
- pythonAvailable = await this.checkPythonServiceAvailable();
- let info: AccountInfo;
- if (pythonAvailable) {
- logger.info(`[Python API] Service available, fetching account_info for baijiahao`);
- try {
- info = await this.fetchAccountInfoViaPython(platform, cookies);
- info.source = 'python';
- info.pythonAvailable = true;
- } catch (error) {
- logger.warn(`[Python API] Failed to fetch account_info for baijiahao, will still try /works:`, error);
- info = this.getDefaultAccountInfo(platform);
- info.source = 'python';
- info.pythonAvailable = true;
- }
- } else {
- logger.info(`[Python API] Service not available for baijiahao, falling back to direct API`);
- // #6085: Python 不可用时回退到 Node 直连 API,需捕获分散认证等 errno 异常
- try {
- info = await this.fetchBaijiahaoAccountInfoDirectApi(cookies);
- } catch (apiError) {
- logger.warn(`[Baijiahao] Direct API failed: ${apiError instanceof Error ? apiError.message : apiError}`);
- // 分散认证等 errno 非 0 错误不一定是 cookie 失效,返回默认信息而非抛出异常
- info = this.getDefaultAccountInfo(platform);
- }
- info.source = 'api';
- info.pythonAvailable = false;
- }
- // 百家号同步作品需要全量:优先通过 Python /works 自动分页拉取
- if (pythonAvailable) {
- try {
- const { works: worksList, total: worksTotal } = await this.fetchWorksViaPython(
- platform,
- cookies,
- options?.onWorksFetchProgress
- );
- info.worksList = worksList;
- if (worksTotal && worksTotal > 0) {
- info.worksCount = worksTotal;
- info.worksListComplete = worksList.length >= worksTotal;
- } else if (worksList.length > 0) {
- info.worksCount = Math.max(info.worksCount || 0, worksList.length);
- info.worksListComplete = undefined;
- }
- info.source = 'python';
- info.pythonAvailable = true;
- } catch (error) {
- logger.warn(`[Python API] Failed to fetch works for baijiahao:`, error);
- // 将 Python 侧错误抛出,让任务显示失败原因(如未登录、token 失效),而不是“共同步 0 个作品”
- const msg = error instanceof Error ? error.message : String(error);
- throw new Error(msg || '百家号拉取作品列表失败,请检查登录状态后重试');
- }
- }
- return info;
- }
- // 对于支持的平台,尝试使用 Python API 获取作品列表和账号信息
- // 同步作品需要全量:这里会通过 Python /works 自动分页拉取
- const supportedPlatforms: PlatformType[] = ['douyin', 'xiaohongshu', 'kuaishou', 'weixin_video', 'baijiahao'];
- if (supportedPlatforms.includes(platform)) {
- pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info(`[Python API] Service available, trying to fetch works for ${platform}`);
- try {
- const { works: worksList, total: worksTotal } = await this.fetchWorksViaPython(
- platform,
- cookies,
- options?.onWorksFetchProgress
- );
- // 如果成功获取到作品,使用 Playwright 获取账号基本信息
- if (worksList.length > 0) {
- logger.info(`[Python API] Successfully fetched ${worksList.length} works for ${platform}`);
- try {
- let accountInfo: AccountInfo;
- // 对于小红书,优先使用 Python API 获取账号信息(因为 Node 端 Playwright 可能无法捕获到 API)
- if (platform === 'xiaohongshu') {
- try {
- accountInfo = await this.fetchAccountInfoViaPython(platform, cookies);
- } catch (e) {
- logger.warn(`[Python API] Failed to fetch account info for ${platform}, falling back to Playwright:`, e);
- accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- }
- } else {
- accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- }
- accountInfo.worksList = worksList;
- // 账号展示的作品数优先用 Python 返回的 total(更接近创作者中心“全部笔记”),否则回退到抓到的列表长度
- accountInfo.worksCount = worksTotal && worksTotal > 0 ? worksTotal : worksList.length;
- accountInfo.worksListComplete = worksTotal && worksTotal > 0 ? worksList.length >= worksTotal : undefined;
- accountInfo.source = 'python';
- accountInfo.pythonAvailable = true;
- logger.info(`[fetchAccountInfo] Using Python API works count for ${platform}: ${accountInfo.worksCount}`);
- return accountInfo;
- } catch (playwrightError) {
- logger.warn(`[Playwright] Failed to get account info for ${platform}:`, playwrightError);
- const accountInfo = this.getDefaultAccountInfo(platform);
- accountInfo.worksList = worksList;
- accountInfo.worksCount = worksTotal && worksTotal > 0 ? worksTotal : worksList.length;
- accountInfo.worksListComplete = worksTotal && worksTotal > 0 ? worksList.length >= worksTotal : undefined;
- accountInfo.source = 'python';
- accountInfo.pythonAvailable = true;
- return accountInfo;
- }
- }
- // 作品列表为空,尝试用 Playwright 获取账号信息
- if (worksTotal > 0 && worksList.length === 0) {
- logger.warn(`[Python API] Warning: API reported ${worksTotal} works but returned empty list for ${platform}`);
- logger.warn(`[Python API] This may indicate a bug in Python API or API format change`);
- } else {
- logger.info(`[Python API] Got empty works list for ${platform} (total=${worksTotal}), trying Playwright`);
- }
- } catch (pythonError) {
- logger.warn(`[Python API] Failed to fetch works for ${platform}:`, pythonError);
- logger.warn(`[Python API] Error details:`, pythonError instanceof Error ? pythonError.message : String(pythonError));
- }
- } else {
- logger.info(`[Python API] Service not available for ${platform}`);
- }
- }
- // 使用 Playwright 获取账号信息
- logger.info(`[Playwright] Fetching account info for ${platform}`);
- const info = await this.fetchAccountInfoWithPlaywright(platform, cookies);
- info.source = 'playwright';
- info.pythonAvailable = pythonAvailable;
- return info;
- }
- /**
- * 使用 Playwright 获取账号信息(原方法)
- */
- private async fetchAccountInfoWithPlaywright(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
- const browser = await chromium.launch({ headless: true });
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- locale: 'zh-CN',
- timezoneId: 'Asia/Shanghai',
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 规范化 cookies 的 sameSite 值,Playwright 只接受 Strict/Lax/None
- const validSameSiteValues = ["Strict", "Lax", "None"];
- const normalizedCookies = cookies.map(cookie => {
- const sameSite = cookie.sameSite as string | undefined;
- let normalizedSameSite: "Strict" | "Lax" | "None" | undefined = "Lax";
-
- if (sameSite && validSameSiteValues.includes(sameSite)) {
- normalizedSameSite = sameSite as "Strict" | "Lax" | "None";
- } else if (sameSite) {
- // 尝试大小写不敏感匹配
- const lowerSameSite = sameSite.toLowerCase();
- if (lowerSameSite === "strict") normalizedSameSite = "Strict";
- else if (lowerSameSite === "lax") normalizedSameSite = "Lax";
- else if (lowerSameSite === "none") normalizedSameSite = "None";
- else {
- // 无效值,使用默认 Lax
- logger.warn("[Cookie] Invalid sameSite value: " + sameSite + ", defaulting to Lax");
- normalizedSameSite = "Lax";
- }
- }
-
- return {
- ...cookie,
- sameSite: normalizedSameSite
- };
- });
-
- await context.addCookies(normalizedCookies);
- const page = await context.newPage();
- let accountInfo: AccountInfo;
- switch (platform) {
- case 'douyin':
- accountInfo = await this.fetchDouyinAccountInfo(page, context, cookies);
- break;
- case 'bilibili':
- accountInfo = await this.fetchBilibiliAccountInfo(page, context, cookies);
- break;
- case 'kuaishou':
- accountInfo = await this.fetchKuaishouAccountInfo(page, context, cookies);
- break;
- case 'xiaohongshu':
- accountInfo = await this.fetchXiaohongshuAccountInfo(page, context, cookies);
- break;
- case 'weixin_video':
- accountInfo = await this.fetchWeixinVideoAccountInfo(page, context, cookies);
- break;
- default:
- accountInfo = this.getDefaultAccountInfo(platform);
- }
- await page.close();
- await context.close();
- await browser.close();
- return accountInfo;
- } catch (error) {
- logger.error('HeadlessBrowser fetchAccountInfo error:', error);
- await browser.close();
- return this.getDefaultAccountInfo(platform);
- }
- }
- /**
- * 获取抖音账号信息 - 通过 API 方式获取
- * 1. 监听 check/user 接口验证登录状态
- * 2. 通过 work_list API 获取作品数和作品列表
- */
- private async fetchDouyinAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `douyin_${Date.now()}`;
- let accountName = '抖音账号';
- let avatarUrl = '';
- let fansCount: number | undefined;
- let worksCount = 0;
- let worksList: WorkItem[] = [];
- let isLoggedIn = false;
- // 用于存储从 API 捕获的数据
- const capturedData: {
- userInfo?: {
- nickname?: string;
- avatar?: string;
- uid?: string;
- sec_uid?: string;
- unique_id?: string; // 抖音号(如 Ethanfly9392)
- short_id?: string; // 短ID
- follower_count?: number;
- };
- dataOverview?: {
- fans_count?: number;
- total_works?: number;
- total_play?: number;
- };
- worksList?: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- duration: number;
- createTime: number;
- statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number; collect_count: number };
- }>;
- total?: number;
- } = {};
- try {
- // 从 Cookie 获取用户 ID
- const uidCookie = cookies.find(c =>
- ['passport_uid', 'uid', 'ssid'].includes(c.name)
- );
- if (uidCookie?.value) {
- accountId = `douyin_${uidCookie.value}`;
- }
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听 check/user 接口 - 验证登录状态
- if (url.includes(DOUYIN_API.CHECK_USER)) {
- const data = await response.json();
- isLoggedIn = data?.result === true && data?.status_code === 0;
- logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
- }
- // 监听 work_list 接口 - 获取作品列表
- if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
- const data = await response.json();
- if (data?.aweme_list && data.aweme_list.length > 0) {
- // 优先从 author.aweme_count 获取真实的作品数(最准确)
- const firstAweme = data.aweme_list[0];
- const authorAwemeCount = firstAweme?.author?.aweme_count;
- if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
- capturedData.total = authorAwemeCount;
- logger.info(`[Douyin API] Using author.aweme_count as works count: ${authorAwemeCount}`);
- } else {
- // 备用方案:使用 items 数组长度
- const itemsCount = data?.items?.length || 0;
- if (itemsCount > 0) {
- capturedData.total = (capturedData.total || 0) + itemsCount;
- } else {
- // 如果没有 items,使用 aweme_list 长度
- capturedData.total = (capturedData.total || 0) + data.aweme_list.length;
- }
- }
- // 解析作品列表;video_url 使用 video.play_addr.url_list 的第一项
- capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
- const statistics = aweme.statistics as Record<string, unknown> || {};
- const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
- const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';
- const video = aweme.video as { play_addr?: { url_list?: string[] } } | undefined;
- const videoUrl = video?.play_addr?.url_list?.[0] || '';
- return {
- awemeId: String(aweme.aweme_id || ''),
- title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
- coverUrl,
- videoUrl,
- duration: Number(aweme.duration || 0),
- createTime: Number(aweme.create_time || 0),
- statistics: {
- play_count: Number(statistics.play_count || 0),
- digg_count: Number(statistics.digg_count || 0),
- comment_count: Number(statistics.comment_count || 0),
- share_count: Number(statistics.share_count || 0),
- collect_count: Number((statistics as any).collect_count || 0),
- },
- };
- });
- logger.info(`[Douyin API] work_list: itemsCount=${capturedData.total}, aweme_list_length=${capturedData.worksList?.length}`);
- }
- }
- // 监听账号信息接口 - 增加更多可能的接口
- if (url.includes('/account_base_info') ||
- url.includes('/user/info') ||
- url.includes('/creator/user') ||
- url.includes('/data/overview') ||
- url.includes('/creator-micro/data') ||
- url.includes('/home_data')) {
- const data = await response.json();
- logger.info(`[Douyin API] Captured response from: ${url.split('?')[0]}`);
- // 处理 data/overview API - 获取总作品数
- if (url.includes('/data/overview') || url.includes('/creator-micro/data')) {
- if (data?.data) {
- capturedData.dataOverview = {
- fans_count: data.data.fans_count || data.data.follower_count,
- total_works: data.data.total_item_cnt || data.data.works_count || data.data.video_count,
- total_play: data.data.total_play_cnt,
- };
- logger.info(`[Douyin API] Captured data overview: total_works=${capturedData.dataOverview.total_works}, fans_count=${capturedData.dataOverview.fans_count}`);
- }
- }
-
- // 尝试多种数据结构
- const user = data?.user || data?.data?.user || data?.data || data;
- if (user) {
- const nickname = user.nickname || user.name || user.nick_name || user.user_name;
- const avatar = user.avatar_url || user.avatar_thumb?.url_list?.[0] || user.avatar || user.avatar_larger?.url_list?.[0];
- const uid = user.uid || user.user_id || user.id;
- const fans = user.follower_count || user.fans_count || user.mplatform_followers_count;
- // 获取抖音号(unique_id 或 short_id)
- const uniqueId = user.unique_id || user.short_id || user.douyin_id;
- if (nickname || uid || uniqueId) {
- capturedData.userInfo = {
- nickname: nickname,
- avatar: avatar,
- uid: uid,
- sec_uid: user.sec_uid,
- unique_id: uniqueId,
- short_id: user.short_id,
- follower_count: fans,
- };
- logger.info(`[Douyin API] user info captured: nickname=${capturedData.userInfo.nickname}, uid=${capturedData.userInfo.uid}, unique_id=${capturedData.userInfo.unique_id}`);
- }
- }
- }
- } catch (e) {
- // 忽略非 JSON 响应
- }
- });
- // 访问主页获取基本信息并触发 check/user 接口
- logger.info('[Douyin] Navigating to creator home...');
- await page.goto(DOUYIN_API.CREATOR_HOME, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待页面加载完成
- await page.waitForTimeout(3000);
- // 尝试等待网络空闲
- try {
- await page.waitForLoadState('networkidle', { timeout: 10000 });
- } catch {
- // 超时继续
- }
- // 额外等待确保 API 响应被捕获
- await page.waitForTimeout(2000);
- // 访问数据中心页面,触发 data/overview API
- logger.info('[Douyin] Navigating to data center to trigger data/overview API...');
- try {
- await page.goto('https://creator.douyin.com/creator-micro/data-center/operation', {
- waitUntil: 'domcontentloaded',
- timeout: 15000,
- });
- await page.waitForTimeout(3000);
-
- // 检查是否获取到 dataOverview
- if (capturedData.dataOverview?.total_works) {
- logger.info(`[Douyin] Captured dataOverview from data center: total_works=${capturedData.dataOverview.total_works}`);
- } else {
- logger.warn('[Douyin] Failed to capture dataOverview from data center');
- }
- } catch (error) {
- logger.warn('[Douyin] Failed to navigate to data center:', error);
- }
- // #6088: 如果还没有获取到作品列表,主动访问内容管理页面触发 work_list API
- if (!capturedData.worksList || capturedData.worksList.length === 0) {
- logger.info('[Douyin] No works captured yet, navigating to content manage page to trigger work_list API...');
- try {
- await page.goto('https://creator.douyin.com/creator-micro/content/manage', {
- waitUntil: 'domcontentloaded',
- timeout: 15000,
- });
- await page.waitForTimeout(5000);
- if (capturedData.worksList && capturedData.worksList.length > 0) {
- logger.info(`[Douyin] Captured ${capturedData.worksList.length} works from content manage page`);
- } else {
- logger.warn('[Douyin] Still no works captured from content manage page');
- }
- } catch (error) {
- logger.warn('[Douyin] Failed to navigate to content manage page:', error);
- }
- }
- // 检查登录状态 - 如果没有从 API 获取到,通过 URL 判断
- if (!isLoggedIn) {
- const currentUrl = page.url();
- isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
- }
- if (!isLoggedIn) {
- logger.warn('[Douyin] Not logged in, returning default account info');
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- }
- // 从页面提取基本账号信息(作为 API 数据的补充)
- const accountData = await page.evaluate(() => {
- const result: { name?: string; avatar?: string; fans?: number; douyinId?: string } = {};
- // 提取抖音号 - 多种方式
- // 方式1:通过选择器查找包含抖音号的元素
- const uniqueIdSelectors = [
- 'div[class*="unique"]',
- 'span[class*="unique"]',
- 'div[class*="douyin-id"]',
- 'span[class*="douyin-id"]',
- '[class*="account-id"]',
- '[class*="shortId"]',
- '[class*="short-id"]',
- ];
- for (const selector of uniqueIdSelectors) {
- const el = document.querySelector(selector);
- if (el) {
- const text = el.textContent?.trim() || '';
- const match = text.match(/抖音号[::]\s*(\S+)/) || text.match(/ID[::]\s*(\S+)/);
- if (match) {
- result.douyinId = match[1];
- break;
- }
- // 如果元素文本本身就是抖音号(无前缀)
- if (text && !text.includes('抖音号') && /^[a-zA-Z0-9_]+$/.test(text)) {
- result.douyinId = text;
- break;
- }
- }
- }
- // 方式2:全局搜索包含"抖音号"的文本
- if (!result.douyinId) {
- const allElements = Array.from(document.querySelectorAll('span, div, p'));
- for (const el of allElements) {
- const text = el.textContent?.trim() || '';
- // 匹配 "抖音号:xxx" 或 "抖音号: xxx"
- const match = text.match(/抖音号[::]\s*([a-zA-Z0-9_]+)/);
- if (match && match[1]) {
- result.douyinId = match[1];
- break;
- }
- }
- }
- // 查找头像 - 优先使用头像容器
- const avatarSelectors = [
- '[class*="avatar"] img',
- '[class*="user-avatar"] img',
- '[class*="profile"] img',
- 'img[class*="avatar"]',
- ];
- for (const selector of avatarSelectors) {
- const img = document.querySelector(selector) as HTMLImageElement;
- if (img?.src && (img.src.includes('aweme') || img.src.includes('douyinpic') || img.src.includes('bytedance'))) {
- result.avatar = img.src;
- break;
- }
- }
- // 备用方案:查找所有图片
- if (!result.avatar) {
- const avatarImgs = Array.from(document.querySelectorAll('img'));
- for (const img of avatarImgs) {
- const src = img.src || img.getAttribute('src') || '';
- if (src && (src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance'))) {
- const rect = img.getBoundingClientRect();
- if (rect.width > 30 && rect.width < 150 && rect.top < 300) {
- result.avatar = src;
- break;
- }
- }
- }
- }
- // 获取粉丝数 - 多种选择器
- const fansSelectors = [
- '#guide_home_fans',
- '[class*="fans"]',
- '[class*="follower"]',
- '[class*="data-item"]',
- ];
- for (const selector of fansSelectors) {
- const el = document.querySelector(selector);
- if (el) {
- const text = el.textContent?.trim() || '';
- // 匹配 "123" 或 "1.2万" 或 "粉丝 123"
- const match = text.match(/(\d+(?:\.\d+)?)\s*([万wW])?/);
- if (match) {
- let num = parseFloat(match[1]);
- if (match[2]) num *= 10000;
- result.fans = Math.floor(num);
- break;
- }
- }
- }
- // 查找用户名 - 更精确的选择器
- const nameSelectors = [
- '[class*="user-name"]',
- '[class*="nickname"]',
- '[class*="author-name"]',
- '[class*="profile-name"]',
- 'h1[class*="name"]',
- 'h2[class*="name"]',
- ];
- for (const selector of nameSelectors) {
- const el = document.querySelector(selector);
- if (el) {
- const text = el.textContent?.trim() || '';
- if (text && text.length >= 2 && text.length <= 30) {
- result.name = text;
- break;
- }
- }
- }
- // 备用方案:查找包含名字的容器
- if (!result.name) {
- const nameContainers = Array.from(document.querySelectorAll('[class*="name"], [class*="nick"], [class*="user"]'));
- for (const container of nameContainers) {
- const text = container.textContent?.trim() || '';
- if (text &&
- text.length >= 2 &&
- text.length <= 20 &&
- !text.includes('关注') &&
- !text.includes('粉丝') &&
- !text.includes('获赞') &&
- !text.includes('加载') &&
- !text.includes('创作') &&
- !text.includes('发布') &&
- !text.includes('抖音号') &&
- !text.match(/^\d+$/)) {
- const rect = container.getBoundingClientRect();
- if (rect.top < 400 && rect.left < 500) {
- result.name = text;
- break;
- }
- }
- }
- }
- return result;
- });
- // 优先使用抖音号作为 ID(unique_id),其次是页面提取的抖音号,最后是 uid
- if (capturedData.userInfo?.unique_id) {
- // 优先使用抖音号(如 Ethanfly9392)
- accountId = `douyin_${capturedData.userInfo.unique_id}`;
- logger.info(`[Douyin] Using unique_id as accountId: ${accountId}`);
- } else if (capturedData.userInfo?.short_id) {
- // 其次使用短ID
- accountId = `douyin_${capturedData.userInfo.short_id}`;
- logger.info(`[Douyin] Using short_id as accountId: ${accountId}`);
- } else if (accountData.douyinId) {
- // 使用页面提取的抖音号
- accountId = `douyin_${accountData.douyinId}`;
- logger.info(`[Douyin] Using page douyinId as accountId: ${accountId}`);
- } else if (capturedData.userInfo?.uid) {
- // 最后使用内部uid
- accountId = `douyin_${capturedData.userInfo.uid}`;
- logger.info(`[Douyin] Using uid as accountId: ${accountId}`);
- }
- accountName = capturedData.userInfo?.nickname || accountData.name || accountName;
- avatarUrl = capturedData.userInfo?.avatar || accountData.avatar || avatarUrl;
- fansCount = capturedData.userInfo?.follower_count || accountData.fans || fansCount;
- // 优先从 dataOverview 获取作品数(最准确)
- if (capturedData.dataOverview?.total_works && capturedData.dataOverview.total_works > 0) {
- worksCount = capturedData.dataOverview.total_works;
- logger.info(`[Douyin] Using dataOverview.total_works as works count: ${worksCount}`);
- }
-
- // 通过 API 获取作品列表
- logger.info('[Douyin] Fetching works via API...');
- const apiResult = await this.fetchWorksDirectApi(page);
- logger.info(`[Douyin] fetchWorksDirectApi returned: works.length=${apiResult.works.length}, total=${apiResult.total}`);
-
- if (apiResult.works.length > 0) {
- // 如果之前从 dataOverview 获取到了作品数,优先使用它
- if (worksCount === 0) {
- // 使用 API 返回的总数,如果为 0 则使用实际获取到的作品列表长度
- worksCount = apiResult.total > 0 ? apiResult.total : apiResult.works.length;
- logger.info(`[Douyin] Using API result as works count: ${worksCount} (total=${apiResult.total}, works.length=${apiResult.works.length})`);
- } else {
- logger.info(`[Douyin] Already have works count from dataOverview: ${worksCount}, skipping API result`);
- }
- worksList = apiResult.works.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- videoUrl: (w as { videoUrl?: string }).videoUrl || (w.awemeId ? `https://www.douyin.com/video/${w.awemeId}` : ''),
- duration: '00:00',
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: w.playCount,
- likeCount: w.likeCount,
- commentCount: w.commentCount,
- shareCount: w.shareCount,
- collectCount: w.collectCount,
- }));
- logger.info(`[Douyin] Got ${apiResult.works.length} works from API, total count: ${worksCount}`);
- } else {
- logger.warn(`[Douyin] fetchWorksDirectApi returned 0 works`);
- if (capturedData.worksList && capturedData.worksList.length > 0) {
- // 如果之前从 dataOverview 获取到了作品数,优先使用它
- if (worksCount === 0) {
- // 如果直接 API 调用失败,使用监听到的数据
- logger.info(`[Douyin] Falling back to intercepted API data: ${capturedData.worksList.length} works`);
- worksCount = capturedData.total || capturedData.worksList.length;
- } else {
- logger.info(`[Douyin] Already have works count from dataOverview: ${worksCount}, skipping intercepted data`);
- }
- worksList = capturedData.worksList.map(w => ({
- videoId: w.awemeId,
- title: w.title,
- coverUrl: w.coverUrl,
- videoUrl: (w as { videoUrl?: string }).videoUrl || (w.awemeId ? `https://www.douyin.com/video/${w.awemeId}` : ''),
- duration: this.formatDuration(w.duration),
- publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
- status: 'published',
- playCount: w.statistics.play_count,
- likeCount: w.statistics.digg_count,
- commentCount: w.statistics.comment_count,
- shareCount: w.statistics.share_count,
- collectCount: w.statistics.collect_count,
- }));
- logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
- } else {
- logger.warn(`[Douyin] No works found: fetchWorksDirectApi returned 0, intercepted data also empty`);
- logger.warn(`[Douyin] This may indicate: cookie expired, API error, or account has no works`);
- }
- }
- } catch (error) {
- logger.error('Failed to fetch Douyin account info:', error);
- logger.error('Error details:', error instanceof Error ? error.stack : String(error));
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
- }
- /**
- * 格式化视频时长
- */
- private formatDuration(ms: number): string {
- if (!ms) return '00:00';
- const seconds = Math.floor(ms / 1000);
- const minutes = Math.floor(seconds / 60);
- const remainingSeconds = seconds % 60;
- return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
- }
- /**
- * 获取B站账号信息
- */
- private async fetchBilibiliAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `bilibili_${Date.now()}`;
- let accountName = 'B站账号';
- let avatarUrl = '';
- let fansCount: number | undefined;
- let worksCount = 0;
- try {
- const uidCookie = cookies.find(c => c.name === 'DedeUserID');
- if (uidCookie?.value) {
- accountId = `bilibili_${uidCookie.value}`;
- }
- await page.goto('https://member.bilibili.com/platform/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 获取用户名
- const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
- if (nameEl) {
- const text = await nameEl.textContent();
- if (text?.trim()) {
- accountName = text.trim();
- }
- }
- // 获取头像
- const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
- if (avatarEl) {
- const src = await avatarEl.getAttribute('src');
- if (src) {
- avatarUrl = src;
- }
- }
- } catch (error) {
- logger.warn('Failed to fetch Bilibili account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取快手账号信息
- */
- private async fetchKuaishouAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `kuaishou_${Date.now()}`;
- let accountName = '快手账号';
- let avatarUrl = '';
- let fansCount: number | undefined;
- let worksCount = 0;
- try {
- const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
- if (uidCookie?.value) {
- accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
- }
- await page.goto('https://cp.kuaishou.com/profile', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 获取用户名
- const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
- if (nameEl) {
- const text = await nameEl.textContent();
- if (text?.trim()) {
- accountName = text.trim();
- }
- }
- // 获取头像
- const avatarEl = await page.$('[class*="avatar"] img');
- if (avatarEl) {
- const src = await avatarEl.getAttribute('src');
- if (src) {
- avatarUrl = src;
- }
- }
- } catch (error) {
- logger.warn('Failed to fetch Kuaishou account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取微信视频号账号信息
- */
- private async fetchWeixinVideoAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `weixin_video_${Date.now()}`;
- let accountName = '视频号账号';
- let avatarUrl = '';
- let fansCount: number | undefined;
- let worksCount = 0;
- let finderId = '';
- try {
- // 从 Cookie 中提取用户标识
- // 优先使用 finder_username(视频号唯一标识)
- const finderUsernameCookie = cookies.find(c => c.name === 'finder_username');
- if (finderUsernameCookie?.value) {
- finderId = finderUsernameCookie.value;
- accountId = `weixin_video_${finderId}`;
- logger.info(`[WeixinVideo] Found finder_username from cookie: ${finderId}`);
- }
- // 备选:使用 wxuin 或 uin
- if (!finderId) {
- const uinCookie = cookies.find(c => c.name === 'wxuin' || c.name === 'uin');
- if (uinCookie?.value) {
- // 仍然保持时间戳格式,后续会尝试从页面获取真实 ID
- accountId = `weixin_video_${uinCookie.value}`;
- logger.info(`[WeixinVideo] Using uin from cookie: ${uinCookie.value}`);
- }
- }
- // 访问视频号创作者平台首页
- await page.goto('https://channels.weixin.qq.com/platform/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[WeixinVideo] Cookie expired, needs login');
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- // 从页面提取账号信息
- const accountData = await page.evaluate(() => {
- const result: { name?: string; avatar?: string; fans?: number; works?: number; finderId?: string } = {};
- try {
- // ===== 1. 优先使用精确选择器获取视频号 ID =====
- // 方法1: 通过 #finder-uid-copy 的 data-clipboard-text 属性获取
- const finderIdCopyEl = document.querySelector('#finder-uid-copy');
- if (finderIdCopyEl) {
- const clipboardText = finderIdCopyEl.getAttribute('data-clipboard-text');
- if (clipboardText && clipboardText.length >= 10) {
- result.finderId = clipboardText;
- console.log('[WeixinVideo] Found finder ID from data-clipboard-text:', result.finderId);
- } else {
- // 备选:获取元素文本内容
- const text = finderIdCopyEl.textContent?.trim();
- if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
- result.finderId = text;
- console.log('[WeixinVideo] Found finder ID from #finder-uid-copy text:', result.finderId);
- }
- }
- }
- // 方法2: 通过 .finder-uniq-id 选择器获取
- if (!result.finderId) {
- const finderUniqIdEl = document.querySelector('.finder-uniq-id');
- if (finderUniqIdEl) {
- const clipboardText = finderUniqIdEl.getAttribute('data-clipboard-text');
- if (clipboardText && clipboardText.length >= 10) {
- result.finderId = clipboardText;
- console.log('[WeixinVideo] Found finder ID from .finder-uniq-id data-clipboard-text:', result.finderId);
- } else {
- const text = finderUniqIdEl.textContent?.trim();
- if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
- result.finderId = text;
- console.log('[WeixinVideo] Found finder ID from .finder-uniq-id text:', result.finderId);
- }
- }
- }
- }
- // 方法3: 从页面文本中正则匹配
- if (!result.finderId) {
- const bodyText = document.body.innerText || '';
- const finderIdPatterns = [
- /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
- /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
- ];
- for (const pattern of finderIdPatterns) {
- const match = bodyText.match(pattern);
- if (match && match[1] && match[1].length >= 10) {
- result.finderId = match[1];
- console.log('[WeixinVideo] Found finder ID from regex:', result.finderId);
- break;
- }
- }
- }
- // ===== 2. 获取账号名称 =====
- // 优先使用 h2.finder-nickname
- const nicknameEl = document.querySelector('h2.finder-nickname') ||
- document.querySelector('.finder-nickname');
- if (nicknameEl) {
- const text = nicknameEl.textContent?.trim();
- if (text && text.length >= 2 && text.length <= 30) {
- result.name = text;
- console.log('[WeixinVideo] Found name from .finder-nickname:', result.name);
- }
- }
- // 备选选择器
- if (!result.name) {
- const nameSelectors = [
- '.account-name',
- '[class*="nickname"]',
- '[class*="userName"]',
- ];
- for (const selector of nameSelectors) {
- const el = document.querySelector(selector);
- const text = el?.textContent?.trim();
- if (text && text.length >= 2 && text.length <= 30) {
- result.name = text;
- console.log('[WeixinVideo] Found name from selector:', selector, result.name);
- break;
- }
- }
- }
- // ===== 3. 获取头像 =====
- // 优先使用 img.avatar
- const avatarEl = document.querySelector('img.avatar') as HTMLImageElement;
- if (avatarEl?.src && avatarEl.src.startsWith('http')) {
- result.avatar = avatarEl.src;
- console.log('[WeixinVideo] Found avatar from img.avatar:', result.avatar);
- }
- // 备选选择器
- if (!result.avatar) {
- const avatarSelectors = [
- '.finder-info-container img.avatar',
- 'img[alt="视频号头像"]',
- 'img[src*="wx.qlogo.cn/finderhead"]',
- 'img[src*="wx.qlogo"]',
- ];
- for (const selector of avatarSelectors) {
- const el = document.querySelector(selector) as HTMLImageElement;
- if (el?.src && el.src.startsWith('http')) {
- result.avatar = el.src;
- console.log('[WeixinVideo] Found avatar from selector:', selector);
- break;
- }
- }
- }
- // ===== 4. 获取视频数和关注者数 =====
- // 使用 .finder-content-info 中的 .finder-info-num
- const contentInfo = document.querySelector('.finder-content-info');
- if (contentInfo) {
- const infoDivs = contentInfo.querySelectorAll('div');
- infoDivs.forEach(div => {
- const text = div.textContent || '';
- const numEl = div.querySelector('.finder-info-num');
- if (numEl) {
- const num = parseInt(numEl.textContent?.trim() || '0', 10);
- if (text.includes('视频') || text.includes('作品')) {
- result.works = num;
- console.log('[WeixinVideo] Found works from .finder-info-num:', result.works);
- } else if (text.includes('关注者') || text.includes('粉丝')) {
- result.fans = num;
- console.log('[WeixinVideo] Found fans from .finder-info-num:', result.fans);
- }
- }
- });
- }
- // 备选:从页面整体文本中匹配
- if (result.fans === undefined || result.works === undefined) {
- const bodyText = document.body.innerText || '';
- if (result.fans === undefined) {
- const fansMatch = bodyText.match(/关注者\s*(\d+(?:\.\d+)?[万wW]?)/) ||
- bodyText.match(/粉丝\s*(\d+(?:\.\d+)?[万wW]?)/);
- if (fansMatch) {
- let count = parseFloat(fansMatch[1]);
- if (fansMatch[1].includes('万') || fansMatch[1].toLowerCase().includes('w')) {
- count = count * 10000;
- }
- result.fans = Math.floor(count);
- console.log('[WeixinVideo] Found fans from text:', result.fans);
- }
- }
- if (result.works === undefined) {
- const worksMatch = bodyText.match(/视频\s*(\d+)/) ||
- bodyText.match(/作品\s*(\d+)/);
- if (worksMatch) {
- result.works = parseInt(worksMatch[1], 10);
- console.log('[WeixinVideo] Found works from text:', result.works);
- }
- }
- }
- } catch (e) {
- console.error('[WeixinVideo] Extract error:', e);
- }
- return result;
- });
- logger.info(`[WeixinVideo] Extracted account data from home page:`, accountData);
- // 更新账号信息
- if (accountData.name) {
- accountName = accountData.name;
- }
- if (accountData.avatar) {
- avatarUrl = accountData.avatar;
- }
- if (accountData.fans !== undefined) {
- fansCount = accountData.fans;
- }
- if (accountData.works !== undefined) {
- worksCount = accountData.works;
- }
- if (accountData.finderId) {
- finderId = accountData.finderId;
- accountId = `weixin_video_${accountData.finderId}`;
- }
- // 如果首页没有获取到视频号 ID,尝试访问账号设置页面
- if (!finderId || finderId.length < 10) {
- logger.info('[WeixinVideo] Finder ID not found on home page, trying account settings page...');
- try {
- // 访问账号设置页面
- await page.goto('https://channels.weixin.qq.com/platform/account', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
- // 从账号设置页面提取视频号 ID
- const settingsData = await page.evaluate(() => {
- const result: { finderId?: string; name?: string } = {};
- const bodyText = document.body.innerText || '';
- // 尝试多种匹配模式
- const patterns = [
- /视频号ID[::\s]*([a-zA-Z0-9_]+)/,
- /视频号[::\s]*ID[::\s]*([a-zA-Z0-9_]+)/,
- /视频号[::\s]+([a-zA-Z0-9_]{10,})/,
- /Finder\s*ID[::\s]*([a-zA-Z0-9_]+)/i,
- /finder_username[::\s]*([a-zA-Z0-9_]+)/i,
- /唯一标识[::\s]*([a-zA-Z0-9_]+)/,
- ];
- for (const pattern of patterns) {
- const match = bodyText.match(pattern);
- if (match && match[1]) {
- result.finderId = match[1];
- console.log('[WeixinVideo] Found finder ID from settings page:', result.finderId);
- break;
- }
- }
- // 从元素中查找
- if (!result.finderId) {
- const idSelectors = [
- '[class*="finder-id"]',
- '[class*="account-id"]',
- '[class*="unique-id"]',
- '.finder-uniq-id',
- 'span.finder-uniq-id',
- '[class*="copy-id"]',
- ];
- for (const selector of idSelectors) {
- const el = document.querySelector(selector);
- const text = el?.textContent?.trim();
- if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10 && text.length <= 30) {
- result.finderId = text;
- console.log('[WeixinVideo] Found ID from settings selector:', result.finderId);
- break;
- }
- }
- }
- return result;
- });
- logger.info(`[WeixinVideo] Extracted data from settings page:`, settingsData);
- if (settingsData.finderId) {
- finderId = settingsData.finderId;
- accountId = `weixin_video_${settingsData.finderId}`;
- }
- } catch (settingsError) {
- logger.warn('[WeixinVideo] Failed to fetch from settings page:', settingsError);
- }
- }
- logger.info(`[WeixinVideo] Final account info: id=${accountId}, name=${accountName}, avatar=${avatarUrl ? 'yes' : 'no'}, fans=${fansCount}`);
- } catch (error) {
- logger.warn('Failed to fetch WeixinVideo account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 获取小红书账号信息 - 通过 API 方式获取
- */
- private async fetchXiaohongshuAccountInfo(
- page: Page,
- _context: BrowserContext,
- cookies: CookieData[]
- ): Promise<AccountInfo> {
- let accountId = `xiaohongshu_${Date.now()}`;
- let accountName = '小红书账号';
- let avatarUrl = '';
- let fansCount: number | undefined;
- let worksCount = 0;
- // 用于存储捕获的数据
- const capturedData: {
- userInfo?: {
- nickname?: string;
- avatar?: string;
- userId?: string;
- redId?: string;
- fans?: number;
- notes?: number;
- };
- } = {};
- try {
- // 从 Cookie 获取用户 ID
- const userIdCookie = cookies.find(c =>
- c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
- );
- if (userIdCookie?.value) {
- accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
- }
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听用户信息 API
- if (url.includes('/api/galaxy/creator/home/personal_info') ||
- url.includes('/api/sns/web/v1/user/selfinfo') ||
- url.includes('/user/selfinfo')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));
- // 解析用户信息
- const userInfo = data?.data?.user_info || data?.data || data;
- if (userInfo) {
- capturedData.userInfo = {
- nickname: userInfo.nickname || userInfo.name || userInfo.userName,
- avatar: userInfo.image || userInfo.avatar || userInfo.images,
- userId: userInfo.user_id || userInfo.userId,
- redId: userInfo.red_id || userInfo.redId,
- fans: userInfo.fans ?? userInfo.fansCount,
- notes: userInfo.notes ?? userInfo.noteCount,
- };
- logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
- }
- }
- // 监听创作者主页数据
- if (url.includes('/api/galaxy/creator/home/home_page') ||
- url.includes('/api/galaxy/creator/data')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));
- if (data?.data) {
- const homeData = data.data;
- // 获取粉丝数和笔记数
- if (homeData.fans_count !== undefined) {
- capturedData.userInfo = capturedData.userInfo || {};
- capturedData.userInfo.fans = homeData.fans_count;
- }
- if (homeData.note_count !== undefined) {
- capturedData.userInfo = capturedData.userInfo || {};
- capturedData.userInfo.notes = homeData.note_count;
- }
- }
- }
- } catch {
- // 忽略非 JSON 响应
- }
- });
- // 导航到小红书创作者中心
- logger.info('[Xiaohongshu] Navigating to creator center...');
- await page.goto('https://creator.xiaohongshu.com/creator/home', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Xiaohongshu] Cookie expired, needs login');
- // 返回空信息,fansCount 为 undefined,避免重置为 0
- return { accountId, accountName, avatarUrl, fansCount: undefined, worksCount: 0 };
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 如果 API 没有捕获到数据,尝试从页面提取
- if (!capturedData.userInfo?.nickname) {
- logger.info('[Xiaohongshu] API did not return data, extracting from page...');
- // 尝试获取用户名
- const nameSelectors = [
- '[class*="nickname"]',
- '[class*="user-name"]',
- '[class*="userName"]',
- '.user-info .name',
- '[class*="creator"] [class*="name"]',
- ];
- for (const selector of nameSelectors) {
- const el = await page.$(selector);
- if (el) {
- const text = await el.textContent();
- if (text?.trim() && text.trim().length < 50) {
- accountName = text.trim();
- logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
- break;
- }
- }
- }
- // 尝试获取头像
- const avatarSelectors = [
- '[class*="avatar"] img',
- '[class*="user-avatar"] img',
- '.user-info img',
- '[class*="creator"] img[src*="sns"]',
- ];
- for (const selector of avatarSelectors) {
- const el = await page.$(selector);
- if (el) {
- const src = await el.getAttribute('src');
- if (src && src.startsWith('http')) {
- avatarUrl = src;
- logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
- break;
- }
- }
- }
- // 尝试获取粉丝数
- const statsText = await page.textContent('body');
- const fansMatch = statsText?.match(/粉丝[::\s]*(\d+(?:\.\d+)?[万亿]?)/);
- if (fansMatch) {
- fansCount = this.parseChineseNumber(fansMatch[1]);
- logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
- }
- const notesMatch = statsText?.match(/笔记[::\s]*(\d+)/);
- if (notesMatch) {
- worksCount = parseInt(notesMatch[1], 10);
- logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
- }
- }
- // 使用捕获的数据
- if (capturedData.userInfo) {
- if (capturedData.userInfo.nickname) {
- accountName = capturedData.userInfo.nickname;
- }
- if (capturedData.userInfo.avatar) {
- avatarUrl = capturedData.userInfo.avatar;
- }
- // 优先使用小红书号(redId)作为 accountId
- if (capturedData.userInfo.redId) {
- accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
- logger.info(`[Xiaohongshu] Using redId as accountId: ${accountId}`);
- } else if (capturedData.userInfo.userId) {
- accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
- }
- if (capturedData.userInfo.fans !== undefined) {
- fansCount = capturedData.userInfo.fans;
- }
- if (capturedData.userInfo.notes !== undefined) {
- worksCount = capturedData.userInfo.notes;
- }
- }
- // 如果还没获取到小红书号,尝试从页面文本中提取
- if (!accountId.match(/xiaohongshu_[a-zA-Z0-9_]+/) || accountId.includes('_' + Date.now().toString().slice(0, 8))) {
- const bodyText = await page.textContent('body');
- // 匹配小红书号格式:小红书号:xxxxxxx
- const xhsIdMatch = bodyText?.match(/小红书号[::]\s*([a-zA-Z0-9_]+)/) ||
- bodyText?.match(/红书号[::]\s*([a-zA-Z0-9_]+)/);
- if (xhsIdMatch) {
- accountId = `xiaohongshu_${xhsIdMatch[1]}`;
- logger.info(`[Xiaohongshu] Found 小红书号 from page text: ${accountId}`);
- }
- }
- logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
- // 获取作品列表 - 通过监听 API 接口
- const worksList: WorkItem[] = [];
- let worksListComplete: boolean | undefined;
- try {
- logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');
- // 存储所有捕获的笔记数据
- const allNotesData: Array<{
- noteId: string;
- title: string;
- coverUrl: string;
- status: number;
- publishTime: string;
- type: string;
- duration: number;
- likeCount: number;
- commentCount: number;
- collectCount: number;
- viewCount: number;
- shareCount: number;
- }> = [];
- let maxPages = 120;
- // 设置 API 响应监听器 - 在导航之前绑定
- let apiResponseReceived = false;
- let totalNotesCount = 0; // 从 tags 中获取的总作品数
- let stoppedByMaxPages = false;
- const seenNoteIds = new Set<string>();
- const upsertNotesFromPayload = (payload: any) => {
- if (!payload) return;
- const declaredTotal = extractDeclaredNotesCountFromPostedResponse(payload);
- if (declaredTotal > 0) {
- totalNotesCount = Math.max(totalNotesCount, declaredTotal);
- }
- if (totalNotesCount > 0) {
- const estimatedPages = Math.ceil(totalNotesCount / 20) + 5;
- maxPages = Math.max(maxPages, Math.min(500, estimatedPages));
- }
- const notes = payload.notes || [];
- for (const note of notes) {
- const noteId = note.id || '';
- if (!noteId || seenNoteIds.has(noteId)) continue;
- seenNoteIds.add(noteId);
- let coverUrl = note.images_list?.[0]?.url || '';
- if (coverUrl.startsWith('http://')) {
- coverUrl = coverUrl.replace('http://', 'https://');
- }
- const duration = note.video_info?.duration || 0;
- allNotesData.push({
- noteId,
- title: note.display_title || '',
- coverUrl,
- status: note.tab_status || 1,
- publishTime: note.time || '',
- type: note.type || 'normal',
- duration,
- likeCount: note.likes || 0,
- commentCount: note.comments_count || 0,
- collectCount: note.collected_count || 0,
- viewCount: note.view_count || 0,
- shareCount: note.shared_count || 0,
- });
- }
- };
- const fetchNotesPage = async (pageNum: number) => {
- return await page.evaluate(async (p) => {
- // #6071: 添加 page_size=20 确保每页返回足够多的笔记(默认可能只有10条)
- const response = await fetch(
- `https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}&page_size=20`,
- {
- method: 'GET',
- credentials: 'include',
- headers: {
- Accept: 'application/json',
- },
- }
- );
- return await response.json();
- }, pageNum);
- };
- const notesApiHandler = async (response: import('playwright').Response) => {
- const url = response.url();
- try {
- // 监听小红书笔记列表 API
- // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
- if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
- url.includes('/api/sns/v5/creator/note/user/posted') ||
- url.includes('creator/note/user/posted')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);
- if ((data?.success || data?.code === 0) && data?.data) {
- apiResponseReceived = true;
- upsertNotesFromPayload(data.data);
- } else {
- }
- }
- } catch (e) {
- // 只在有相关 URL 时打印警告
- if (url.includes('creator/note')) {
- logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
- }
- }
- };
- // 先绑定监听器
- page.on('response', notesApiHandler);
- logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');
- // 导航到笔记管理页面 - 使用 domcontentloaded 加快加载,避免 networkidle 超时
- try {
- await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- } catch (navError) {
- // 导航超时不影响已捕获的 API 数据
- logger.warn('[Xiaohongshu] Navigation timeout, but API data may have been captured');
- }
- // 等待 API 响应
- await page.waitForTimeout(5000);
- logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);
- // 如果监听器没有捕获到数据,尝试直接调用 API
- if (allNotesData.length === 0) {
- logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');
- try {
- const apiResponse = await fetchNotesPage(0);
- logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);
- if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
- upsertNotesFromPayload(apiResponse.data);
- }
- } catch (apiError) {
- logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
- }
- }
- if (allNotesData.length > 0) {
- let pageNum = 1;
- while (pageNum < maxPages) {
- if (totalNotesCount > 0 && seenNoteIds.size >= totalNotesCount) break;
- let nextResponse: any;
- try {
- nextResponse = await fetchNotesPage(pageNum);
- } catch (e) {
- logger.warn(`[Xiaohongshu] Page fetch failed: page=${pageNum}`, e);
- break;
- }
- if (!(nextResponse?.success || nextResponse?.code === 0) || !nextResponse?.data) break;
- const before = seenNoteIds.size;
- upsertNotesFromPayload(nextResponse.data);
- const after = seenNoteIds.size;
- if (after === before) break;
- pageNum++;
- await page.waitForTimeout(600);
- }
- if (pageNum >= maxPages) stoppedByMaxPages = true;
- }
- // 移除监听器
- page.off('response', notesApiHandler);
- logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);
- // 转换为 WorkItem 格式
- for (const note of allNotesData) {
- // 转换时长为 mm:ss 格式
- const minutes = Math.floor(note.duration / 60);
- const seconds = note.duration % 60;
- const durationStr = note.duration > 0
- ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
- : '';
- // 转换状态
- let statusStr = 'published';
- if (note.status === 0) statusStr = 'draft';
- else if (note.status === 2) statusStr = 'reviewing';
- else if (note.status === 3) statusStr = 'rejected';
- worksList.push({
- videoId: note.noteId,
- title: note.title || '无标题',
- coverUrl: note.coverUrl,
- videoUrl: note.noteId ? `https://www.xiaohongshu.com/explore/${note.noteId}` : '',
- duration: durationStr,
- publishTime: note.publishTime,
- status: statusStr,
- playCount: note.viewCount,
- likeCount: note.likeCount,
- commentCount: note.commentCount,
- shareCount: note.shareCount,
- });
- }
- logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);
- if (totalNotesCount > 0) {
- worksListComplete = worksList.length >= totalNotesCount;
- worksCount = totalNotesCount;
- } else if (worksList.length > 0) {
- worksListComplete = !stoppedByMaxPages;
- worksCount = worksList.length;
- }
- } catch (worksError) {
- logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
- }
- logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
- return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList, worksListComplete };
- } catch (error) {
- logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
- }
- return { accountId, accountName, avatarUrl, fansCount, worksCount };
- }
- /**
- * 解析中文数字(如 1.2万 -> 12000)
- */
- private parseChineseNumber(str: string): number {
- if (!str) return 0;
- let num = parseFloat(str);
- if (str.includes('万')) {
- num *= 10000;
- } else if (str.includes('亿')) {
- num *= 100000000;
- }
- return Math.floor(num);
- }
- /**
- * 获取平台配置
- */
- private getPlatformConfig(platform: PlatformType) {
- const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
- douyin: {
- homeUrl: 'https://creator.douyin.com/creator-micro/home',
- loginIndicators: ['login', 'passport', 'sso'],
- },
- bilibili: {
- homeUrl: 'https://member.bilibili.com/platform/home',
- loginIndicators: ['passport.bilibili.com', 'login'],
- },
- kuaishou: {
- homeUrl: 'https://cp.kuaishou.com/profile',
- loginIndicators: ['passport.kuaishou.com', 'login'],
- },
- xiaohongshu: {
- homeUrl: 'https://creator.xiaohongshu.com/',
- loginIndicators: ['login', 'passport'],
- },
- weixin_video: {
- homeUrl: 'https://channels.weixin.qq.com/platform',
- loginIndicators: ['login.html', '/login', 'passport'],
- },
- baijiahao: {
- homeUrl: 'https://baijiahao.baidu.com/builder/rc/home',
- loginIndicators: ['login', 'passport'],
- },
- toutiao: {
- homeUrl: 'https://mp.toutiao.com/profile_v4/index',
- loginIndicators: ['login', 'passport', 'sso'],
- },
- weibo: {
- homeUrl: 'https://weibo.com/u/',
- loginIndicators: ['login', 'passport'],
- },
- dayu: {
- homeUrl: 'https://mp.dayu.com/',
- loginIndicators: ['login', 'passport'],
- },
- };
- return configs[platform] || { homeUrl: '', loginIndicators: ['login'] };
- }
- /**
- * 百家号 - 直接通过 API 获取账号信息和作品列表
- */
- private async fetchBaijiahaoAccountInfoDirectApi(cookies: CookieData[]): Promise<AccountInfo> {
- logger.info(`[Baijiahao API] Fetching account info via direct API...`);
- // 构建 Cookie 字符串,确保格式正确
- const cookieString = cookies
- .map(c => `${c.name.trim()}=${c.value.trim()}`)
- .filter(c => c.includes('=')) // 过滤掉无效的 cookie
- .join('; ');
- logger.debug(`[Baijiahao API] Cookie string length: ${cookieString.length}, cookie count: ${cookies.length}`);
- const headers: Record<string, string> = {
- 'Accept': '*/*',
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Accept-Encoding': 'gzip, deflate, br',
- 'Connection': 'keep-alive',
- 'Cookie': cookieString,
- // 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
- // 'Origin': 'https://baijiahao.baidu.com',
- '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',
- // 'Sec-Fetch-Dest': 'empty',
- // 'Sec-Fetch-Mode': 'cors',
- // 'Sec-Fetch-Site': 'same-origin',
- };
- let accountInfo: AccountInfo = this.getDefaultAccountInfo('baijiahao');
- // 标记哪些字段已成功获取
- let fansCountFetched = false;
- let worksCountFetched = false;
- try {
- // 1. 获取账号基本信息 (appinfo API)
- logger.info(`[Baijiahao API] Step 1: Fetching appinfo...`);
- const appInfoResponse = await fetch('https://baijiahao.baidu.com/builder/app/appinfo', {
- method: 'GET',
- headers,
- });
- if (!appInfoResponse.ok) {
- logger.error(`[Baijiahao API] appinfo request failed: ${appInfoResponse.status}`);
- throw new Error(`appinfo request failed: ${appInfoResponse.status}`);
- }
- const appInfoData = await appInfoResponse.json() as {
- errno?: number;
- errmsg?: string;
- data?: {
- user?: {
- name?: string;
- avatar?: string;
- app_id?: string | number;
- userid?: number;
- status?: string;
- };
- };
- };
- logger.info(`[Baijiahao API] appinfo response: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
- if (appInfoData.errno !== 0) {
- // #6085: errno 非 0 不一定是 cookie 失效(如 errno=10001402 分散认证),
- // 只有 errno=110 才明确表示未登录,其他 errno 返回默认信息避免同步中断
- if (appInfoData.errno === 110) {
- logger.error(`[Baijiahao API] Not logged in (errno=110)`);
- throw new Error(`appinfo API error: errno=110, cookie expired`);
- }
- logger.warn(`[Baijiahao API] appinfo returned errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}, returning default info`);
- return accountInfo;
- }
- if (!appInfoData.data?.user) {
- logger.error(`[Baijiahao API] No user data in appinfo response`);
- throw new Error('No user data in appinfo response');
- }
- const user = appInfoData.data.user;
- accountInfo.accountId = user.app_id ? `bjh_${user.app_id}` : accountInfo.accountId;
- accountInfo.accountName = user.name || accountInfo.accountName;
- // 处理头像 URL(可能是相对路径)
- if (user.avatar) {
- accountInfo.avatarUrl = user.avatar.startsWith('http')
- ? user.avatar
- : `https:${user.avatar}`;
- }
- logger.info(`[Baijiahao API] Got account info: name=${accountInfo.accountName}, id=${accountInfo.accountId}, avatar=${accountInfo.avatarUrl}`);
- // 2. 获取粉丝数 (growthInfo API)
- logger.info(`[Baijiahao API] Step 2: Fetching growth info...`);
- try {
- const growthInfoResponse = await fetch('https://baijiahao.baidu.com/cms-ui/rights/growth/get_info', {
- method: 'GET',
- headers,
- });
- if (growthInfoResponse.ok) {
- const growthData = await growthInfoResponse.json() as {
- errno?: number;
- errmsg?: string;
- data?: {
- total_fans?: number;
- };
- };
- logger.info(`[Baijiahao API] growth info response: errno=${growthData.errno}`);
- if (growthData.errno === 0 && growthData.data) {
- const fansCount = growthData.data.total_fans;
- if (fansCount !== undefined && fansCount !== null) {
- accountInfo.fansCount = fansCount;
- fansCountFetched = true;
- logger.info(`[Baijiahao API] Got fans count: ${accountInfo.fansCount}`);
- } else {
- logger.warn(`[Baijiahao API] growth info API returned no fans count`);
- }
- } else {
- logger.warn(`[Baijiahao API] growth info API error: errno=${growthData.errno}, errmsg=${growthData.errmsg}`);
- }
- } else {
- logger.warn(`[Baijiahao API] growth info request failed: ${growthInfoResponse.status}`);
- }
- } catch (growthError) {
- logger.warn(`[Baijiahao API] Failed to fetch growth info (non-critical):`, growthError);
- // 粉丝数获取失败不影响整体流程
- }
- // 3. 获取作品列表 (分页获取所有作品)
- logger.info(`[Baijiahao API] Step 3: Fetching works list...`);
- setTimeout(() => {
- console.log('1000ms');
- }, 1000);
- const worksList: WorkItem[] = [];
- let currentPage = 1;
- const pageSize = 20;
- let hasMore = true;
- let totalWorks = 0;
- let worksListError = false;
- while (hasMore && !worksListError) {
- try {
- const listUrl = `https://baijiahao.baidu.com/pcui/article/lists?currentPage=${currentPage}&pageSize=${pageSize}&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0`;
- logger.info(`[Baijiahao API] Fetching works page ${currentPage}...`);
- logger.debug(`[Baijiahao API] Request headers include Cookie: ${!!headers.Cookie}, Cookie length: ${headers.Cookie?.length || 0}`);
- const listResponse = await fetch(listUrl, {
- method: 'GET',
- headers,
- });
- if (!listResponse.ok) {
- const errorText = await listResponse.text();
- logger.warn(`[Baijiahao API] Failed to fetch works list page ${currentPage}: ${listResponse.status}`);
- logger.warn(`[Baijiahao API] Error response body: ${errorText}`);
- break;
- }
- const responseText = await listResponse.text();
- logger.info(`[Baijiahao API] ========== Works API Response (Page ${currentPage}) ==========`);
- logger.info(`[Baijiahao API] Full response: ${responseText}`);
- logger.info(`[Baijiahao API] ============================================================`);
- const listData = JSON.parse(responseText) as {
- errno?: number;
- errmsg?: string;
- data?: {
- list?: Array<{
- id?: string;
- article_id?: string;
- title?: string;
- cover_images?: string | string[];
- created_at?: string;
- create_time?: string;
- status?: string;
- read_amount?: number;
- read_count?: number;
- like_amount?: number;
- like_count?: number;
- comment_amount?: number;
- comment_count?: number;
- share_amount?: number;
- share_count?: number;
- }>;
- page?: {
- currentPage?: number;
- pageSize?: number;
- totalCount?: number;
- totalPage?: number;
- };
- total?: number; // 兼容旧格式
- };
- };
- // 处理分散认证问题 (errno=10001402),重试一次
- if (listData.errno === 10001402) {
- logger.warn(`[Baijiahao API] Dispersed authentication issue (errno=10001402) on page ${currentPage}, retrying after 3 seconds...`);
- logger.debug(`[Baijiahao API] Request URL: ${listUrl}`);
- logger.debug(`[Baijiahao API] Cookie header present: ${!!headers.Cookie}, length: ${headers.Cookie?.length || 0}`);
- await new Promise(resolve => setTimeout(resolve, 3000));
- // 重试一次,确保 headers 包含 Cookie
- const retryResponse = await fetch(listUrl, {
- method: 'GET',
- headers: {
- ...headers,
- 'Cookie': cookieString, // 确保 Cookie 被正确传递
- },
- });
- if (retryResponse.ok) {
- const retryResponseText = await retryResponse.text();
- logger.info(`[Baijiahao API] ========== Works API Retry Response (Page ${currentPage}) ==========`);
- logger.info(`[Baijiahao API] Full retry response: ${retryResponseText}`);
- logger.info(`[Baijiahao API] ============================================================`);
- const retryData = JSON.parse(retryResponseText) as typeof listData;
- if (retryData.errno === 0) {
- logger.info(`[Baijiahao API] Retry successful for page ${currentPage}`);
- Object.assign(listData, retryData);
- } else if (retryData.errno === 10001402) {
- logger.error(`[Baijiahao API] Retry still failed with errno=10001402, cookie may be invalid or expired`);
- logger.error(`[Baijiahao API] Retry response data: ${JSON.stringify(retryData, null, 2)}`);
- // 如果重试仍然失败,可能是 Cookie 问题,记录详细信息
- logger.error(`[Baijiahao API] Cookie info: ${cookieString.substring(0, 200)}...`);
- // 标记错误,但不完全失败,继续返回已获取的账号信息
- worksListError = true;
- logger.warn(`[Baijiahao API] Works list fetch failed, but will return other account info (name, fans count)`);
- break;
- } else {
- logger.warn(`[Baijiahao API] Retry still failed: errno=${retryData.errno}, errmsg=${retryData.errmsg}`);
- break;
- }
- } else {
- logger.warn(`[Baijiahao API] Retry request failed: ${retryResponse.status}`);
- break;
- }
- }
- if (listData.errno !== 0) {
- logger.warn(`[Baijiahao API] API returned error on page ${currentPage}: errno=${listData.errno}, errmsg=${listData.errmsg}`);
- logger.warn(`[Baijiahao API] Error response data: ${JSON.stringify(listData, null, 2)}`);
- // 如果不是 10001402 错误,标记为错误但继续返回其他信息
- if (listData.errno !== 10001402) {
- worksListError = true;
- logger.warn(`[Baijiahao API] Works list fetch failed with errno=${listData.errno}, but will return other account info`);
- }
- break;
- }
- const list = listData.data?.list || [];
- // 优先使用 data.page.totalCount,如果没有则使用 data.total(兼容旧格式)
- totalWorks = listData.data?.page?.totalCount || listData.data?.total || 0;
- logger.info(`[Baijiahao API] Got ${list.length} works on page ${currentPage}, total: ${totalWorks}`);
- for (const item of list) {
- // 处理 cover_images 可能是字符串(JSON)或数组
- let coverUrl = '';
- if (item.cover_images) {
- if (Array.isArray(item.cover_images)) {
- coverUrl = item.cover_images[0] || '';
- } else if (typeof item.cover_images === 'string') {
- try {
- const coverArray = JSON.parse(item.cover_images);
- if (Array.isArray(coverArray) && coverArray.length > 0) {
- coverUrl = typeof coverArray[0] === 'string' ? coverArray[0] : coverArray[0]?.src || coverArray[0]?.ori_src || '';
- }
- } catch {
- coverUrl = item.cover_images;
- }
- }
- }
- worksList.push({
- videoId: item.id || item.article_id || `bjh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
- title: item.title || '',
- coverUrl: coverUrl,
- videoUrl: item.url || item.article_url || '',
- duration: '00:00',
- publishTime: item.created_at || item.create_time || new Date().toISOString(),
- status: item.status || 'published',
- playCount: item.read_amount || item.read_count || 0,
- likeCount: item.like_amount || item.like_count || 0,
- commentCount: item.comment_amount || item.comment_count || 0,
- shareCount: item.share_amount || item.share_count || 0,
- });
- }
- // 检查是否还有更多
- if (list.length < pageSize) {
- hasMore = false;
- logger.info(`[Baijiahao API] No more works, stopping at page ${currentPage}`);
- } else {
- currentPage++;
- // 防止无限循环,最多获取 10 页(200 个作品)
- if (currentPage > 10) {
- logger.warn(`[Baijiahao API] Reached max pages (10), stopping. Total fetched: ${worksList.length}, API total: ${totalWorks}`);
- hasMore = false;
- }
- }
- } catch (pageError) {
- logger.error(`[Baijiahao API] Error fetching page ${currentPage}:`, pageError);
- break;
- }
- }
- accountInfo.worksList = worksList;
- // 使用 API 返回的 total 字段作为作品总数,而不是已获取的作品列表长度
- // 因为可能只获取了部分作品(最多 10 页),但 total 是真实的总数
- if (totalWorks > 0) {
- accountInfo.worksCount = totalWorks;
- worksCountFetched = true;
- } else if (worksList.length > 0) {
- // 如果 API 没有返回 total,但获取到了作品列表,使用列表长度
- accountInfo.worksCount = worksList.length;
- worksCountFetched = true;
- }
- if (worksListError) {
- logger.warn(`[Baijiahao API] Works list fetch encountered errors, but returning partial account info`);
- logger.info(`[Baijiahao API] Account info (partial): name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched})`);
- } else {
- 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})`);
- }
- return accountInfo;
- } catch (error) {
- logger.error(`[Baijiahao API] Failed to fetch account info:`, error);
- // 返回默认信息,但保留已获取的部分数据
- return accountInfo;
- }
- }
- /**
- * 通过 Python API 获取账号信息
- */
- private async fetchAccountInfoViaPython(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
- logger.info(`[Python API] Fetching account info for ${platform}...`);
- try {
- // 检查 Python 服务是否可用
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (!pythonAvailable) {
- logger.warn(`[Python API] Service not available, returning default info`);
- return this.getDefaultAccountInfo(platform);
- }
- // 构建 Cookie 字符串
- const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
- // 调用 Python API
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- const response = await fetch(`${pythonUrl}/account_info`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- logger.warn(`[Python API] account_info returned ${response.status}`);
- return this.getDefaultAccountInfo(platform);
- }
- const result = await response.json() as {
- success: boolean;
- account_id?: string;
- account_name?: string;
- avatar_url?: string;
- fans_count?: number;
- works_count?: number;
- error?: string;
- need_login?: boolean;
- };
- logger.info(`[Python API] account_info result: success=${result.success}, name=${result.account_name}`);
- if (result.success && result.account_name) {
- return {
- accountId: result.account_id || `${platform}_${Date.now()}`,
- accountName: result.account_name,
- avatarUrl: result.avatar_url || '',
- fansCount: result.fans_count,
- worksCount: result.works_count ?? 0,
- };
- }
- if (result.need_login) {
- logger.warn(`[Python API] Account needs re-login`);
- }
- logger.warn(`[Python API] Failed to get account info: ${result.error}`);
- return this.getDefaultAccountInfo(platform);
- } catch (error) {
- logger.error(`[Python API] Failed to fetch account info for ${platform}:`, error);
- return this.getDefaultAccountInfo(platform);
- }
- }
- /**
- * 获取默认账号信息
- */
- private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
- // 平台友好名称映射
- const platformNames: Record<string, string> = {
- douyin: '抖音',
- xiaohongshu: '小红书',
- kuaishou: '快手',
- weixin_video: '视频号',
- bilibili: 'B站',
- toutiao: '头条',
- baijiahao: '百家号',
- };
- const name = platformNames[platform] || platform;
- return {
- accountId: `${platform}_${Date.now()}`,
- accountName: `${name}账号`,
- avatarUrl: '',
- fansCount: undefined,
- worksCount: 0,
- };
- }
- /**
- * 获取抖音评论 - 逐个选择作品获取评论
- */
- async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
- const browser = await chromium.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- const page = await context.newPage();
- // 导航到评论管理页面
- logger.info('Navigating to Douyin comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(3000);
- // 点击"选择作品"按钮
- logger.info('Looking for "选择作品" button...');
- const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');
- if (selectWorkBtn) {
- await selectWorkBtn.click();
- await page.waitForTimeout(2000);
- logger.info('Clicked "选择作品" button');
- } else {
- // 如果没有选择作品按钮,可能已经有作品被选中,直接获取当前评论
- logger.info('No "选择作品" button found, fetching current comments...');
- const currentComments = await this.extractCommentsFromPage(page);
- if (currentComments.length > 0) {
- allWorkComments.push({
- videoId: 'current',
- videoTitle: '当前作品',
- videoCoverUrl: '',
- comments: currentComments,
- });
- }
- await page.close();
- await context.close();
- await browser.close();
- return allWorkComments;
- }
- // 获取作品列表
- const worksList = await page.evaluate(() => {
- const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];
- // 查找作品列表容器(弹窗中的作品选择列表)
- const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');
- workItems.forEach((item, index) => {
- const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
- const coverEl = item.querySelector('img, [class*="cover"]');
- const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
- let coverUrl = '';
- if (coverEl) {
- coverUrl = (coverEl as HTMLImageElement).src ||
- coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
- }
- // 获取 video ID(从数据属性或其他方式)
- const videoId = item.getAttribute('data-video-id') ||
- item.getAttribute('data-id') ||
- `video_${index}`;
- works.push({ videoId, title, coverUrl });
- });
- return works;
- });
- logger.info(`Found ${worksList.length} works in the selector`);
- // 如果有作品列表,逐个选择并获取评论
- if (worksList.length > 0) {
- for (let i = 0; i < worksList.length; i++) {
- try {
- logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);
- // 点击选择该作品
- const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
- if (workItem) {
- await workItem.click();
- await page.waitForTimeout(2000);
- // 点击确认按钮(如果有)
- const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
- if (confirmBtn) {
- await confirmBtn.click();
- await page.waitForTimeout(2000);
- }
- }
- // 等待评论加载
- await page.waitForTimeout(2000);
- // 提取评论
- const comments = await this.extractCommentsFromPage(page);
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: worksList[i].videoId,
- videoTitle: worksList[i].title,
- videoCoverUrl: worksList[i].coverUrl,
- comments,
- });
- logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
- }
- // 重新打开选择作品弹窗(如果需要继续选择其他作品)
- if (i < worksList.length - 1) {
- const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
- if (selectBtn) {
- await selectBtn.click();
- await page.waitForTimeout(2000);
- }
- }
- } catch (workError) {
- logger.warn(`Failed to process work ${i + 1}:`, workError);
- }
- }
- } else {
- // 没有找到作品列表,尝试直接从页面获取评论
- const comments = await this.extractCommentsFromPage(page);
- if (comments.length > 0) {
- // 获取当前显示的作品信息
- const currentWork = await page.evaluate(() => {
- const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
- const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');
- return {
- title: titleEl?.textContent?.trim() || '当前作品',
- coverUrl: (coverEl as HTMLImageElement)?.src || '',
- };
- });
- allWorkComments.push({
- videoId: 'current',
- videoTitle: currentWork.title,
- videoCoverUrl: currentWork.coverUrl,
- comments,
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('Error fetching Douyin comments:', error);
- await browser.close();
- return allWorkComments;
- }
- }
- /**
- * 从页面提取评论列表
- * 使用抖音创作者中心的精确选择器
- * 根据实际 HTML 结构:
- * - 评论容器: container-sXKyMs (或类似 container-xxx)
- * - 用户名: username-aLgaNB (或类似 username-xxx)
- * - 时间: time-NRtTXO (或类似 time-xxx)
- * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
- * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
- */
- private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
- return page.evaluate(() => {
- const comments: Array<{
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const seenContents = new Set<string>();
- // 方法1: 直接查找所有评论容器 (container-xxx 类名)
- // 评论容器通常包含 checkbox、avatar、content 等子元素
- const allContainers = document.querySelectorAll('[class*="container-"]');
- const commentContainers: Element[] = [];
- allContainers.forEach(container => {
- // 检查是否是评论容器:包含用户名和评论内容
- const hasUsername = container.querySelector('[class*="username-"]');
- const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
- if (hasUsername && hasCommentContent) {
- commentContainers.push(container);
- }
- });
- console.log(`Found ${commentContainers.length} comment containers`);
- // 如果方法1没找到,尝试方法2:通过评论内容元素向上查找
- if (commentContainers.length === 0) {
- const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
- console.log(`Found ${contentElements.length} content elements, searching parents...`);
- contentElements.forEach(contentEl => {
- let parent = contentEl.parentElement;
- // 向上查找最多 10 层
- for (let i = 0; i < 10 && parent; i++) {
- const className = parent.className || '';
- // 查找包含 container- 的父元素
- if (className.includes('container-')) {
- if (!commentContainers.includes(parent)) {
- commentContainers.push(parent);
- }
- break;
- }
- parent = parent.parentElement;
- }
- });
- }
- console.log(`Total comment containers: ${commentContainers.length}`);
- commentContainers.forEach((container, index) => {
- try {
- // 提取用户名 - 使用 username-xxx 选择器
- let authorName = '';
- const usernameEl = container.querySelector('[class*="username-"]');
- if (usernameEl && usernameEl.textContent) {
- authorName = usernameEl.textContent.trim();
- }
- if (!authorName) authorName = '未知用户';
- // 提取头像 - 从 avatar-xxx 容器内的 img 提取
- let authorAvatar = '';
- const avatarContainer = container.querySelector('[class*="avatar-"]');
- if (avatarContainer) {
- const avatarImg = avatarContainer.querySelector('img');
- if (avatarImg) {
- authorAvatar = avatarImg.src || '';
- }
- }
- // 提取时间 - 使用 time-xxx 选择器
- let commentTime = '';
- const timeEl = container.querySelector('[class*="time-"]');
- if (timeEl && timeEl.textContent) {
- commentTime = timeEl.textContent.trim();
- }
- // 提取评论内容 - 使用 comment-content-text-xxx 选择器
- let content = '';
- const contentEl = container.querySelector('[class*="comment-content-text-"]');
- if (contentEl && contentEl.textContent) {
- content = contentEl.textContent.trim();
- }
- // 跳过空内容
- if (!content || content.length < 1) {
- console.log(`[${index}] Skipping empty content`);
- return;
- }
- // 去重 (基于用户名+内容)
- const contentKey = `${authorName}||${content}`;
- if (seenContents.has(contentKey)) {
- console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
- return;
- }
- seenContents.add(contentKey);
- // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
- let likeCount = 0;
- const operationsEl = container.querySelector('[class*="operations-"]');
- if (operationsEl) {
- // 查找第一个 item-xxx,通常是点赞数
- const firstItem = operationsEl.querySelector('[class*="item-"]');
- if (firstItem) {
- const text = firstItem.textContent || '';
- const match = text.match(/(\d+)/);
- if (match) {
- likeCount = parseInt(match[1], 10);
- }
- }
- }
- // 生成唯一 ID
- const contentHash = content.slice(0, 30) + authorName + commentTime;
- const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;
- comments.push({
- commentId,
- authorId: authorName,
- authorName,
- authorAvatar,
- content,
- likeCount,
- commentTime,
- });
- console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
- } catch (err) {
- console.error(`[${index}] Error extracting comment:`, err);
- }
- });
- console.log(`Successfully extracted ${comments.length} comments`);
- return comments;
- });
- }
- /**
- * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
- * 使用无头浏览器,通过拦截网络请求直接获取 API 数据
- * 更稳定、更高效
- */
- async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
- const browser = await chromium.launch({
- headless: true, // 无头模式
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- // 存储捕获的 API 数据
- const capturedWorks: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- commentCount: number;
- }> = [];
- const capturedComments: Map<string, CommentItem[]> = new Map();
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 监听网络响应
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听作品列表 API - 支持新旧两种接口
- // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
- // 旧接口: /creator/item/list (item_info_list 字段)
- if (url.includes('/work_list') || url.includes('/creator/item/list')) {
- const data = await response.json();
- // 新接口: aweme_list
- if (data?.aweme_list && data.aweme_list.length > 0) {
- for (const aweme of data.aweme_list) {
- const awemeId = String(aweme.aweme_id || '');
- if (!awemeId) continue;
- const statistics = aweme.statistics || {};
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- let title = aweme.item_title || '';
- if (!title) {
- const desc = aweme.desc || aweme.caption || '';
- title = desc.split('\n')[0].slice(0, 50) || '无标题';
- }
- let coverUrl = '';
- if (aweme.Cover?.url_list?.length > 0) {
- coverUrl = aweme.Cover.url_list[0];
- } else if (aweme.video?.cover?.url_list?.length > 0) {
- coverUrl = aweme.video.cover.url_list[0];
- }
- capturedWorks.push({
- awemeId,
- title,
- coverUrl,
- commentCount,
- });
- }
- logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
- }
- // 旧接口: item_info_list
- const itemList = data?.item_info_list || data?.item_list || [];
- if (itemList.length > 0) {
- for (const item of itemList) {
- capturedWorks.push({
- awemeId: item.item_id_plain || item.aweme_id || '',
- title: item.title || '无标题',
- coverUrl: item.cover_image_url || '',
- commentCount: item.comment_count || 0,
- });
- }
- logger.info(`[API] Captured ${itemList.length} works from item/list API`);
- }
- }
- // 监听评论列表 API(两种格式)
- // 格式1: /comment/list/select/ - 初始加载,返回 { comments: [...] }
- // 格式2: /creator/comment/list/ - 切换作品后,返回 { comment_info_list: [...] }
- if (url.includes('/comment/list') || url.includes('/comment/read')) {
- const data = await response.json();
- // 从 URL 中提取 aweme_id
- const awemeIdMatch = url.match(/aweme_id=(\d+)/);
- const awemeId = awemeIdMatch?.[1] || '';
- let comments: CommentItem[] = [];
- // 格式1: 初始加载的评论 API (comment/list/select)
- if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
- comments = data.comments.map((c: Record<string, unknown>) => {
- const user = c.user as Record<string, unknown> | undefined;
- const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
- const avatarUrls = avatarThumb?.url_list as string[] | undefined;
- return {
- commentId: String(c.cid || ''),
- authorId: String(user?.uid || ''),
- authorName: String(user?.nickname || '匿名'),
- authorAvatar: avatarUrls?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- };
- });
- logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
- }
- // 格式2: 切换作品后的评论 API (creator/comment/list)
- if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
- comments = data.comment_info_list.map((c: Record<string, unknown>) => {
- const userInfo = c.user_info as Record<string, unknown> | undefined;
- return {
- commentId: String(c.comment_id || ''),
- authorId: String(userInfo?.user_id || ''),
- authorName: String(userInfo?.screen_name || '匿名'),
- authorAvatar: String(userInfo?.avatar_url || ''),
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: awemeId, // 这种格式没有直接返回 aweme_id
- };
- });
- logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
- }
- if (comments.length > 0) {
- const videoId = comments[0]?.videoId || awemeId;
- if (videoId) {
- const existing = capturedComments.get(videoId) || [];
- capturedComments.set(videoId, [...existing, ...comments]);
- logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
- }
- }
- }
- } catch {
- // 忽略非 JSON 响应
- }
- });
- // 导航到创作者中心页面(设置好 Cookie 后)
- logger.info('[API Interception] Navigating to creator page...');
- await page.goto('https://creator.douyin.com/creator-micro/home', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面加载
- await page.waitForTimeout(3000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[API Interception] Cookie expired');
- return [];
- }
- // 方式1:直接调用 API 获取作品列表(优先)
- logger.info('[API Interception] Fetching works via direct API...');
- const apiResult = await this.fetchWorksDirectApi(page);
- let works = apiResult.works;
- // 方式2:如果直接调用失败,尝试通过页面触发 API
- if (works.length === 0) {
- logger.info('[API Interception] Direct API failed, trying page navigation...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'networkidle',
- timeout: 60000,
- });
- await page.waitForTimeout(3000);
- // 点击"选择作品"按钮触发作品列表 API
- const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
- if (selectBtn) {
- await selectBtn.click();
- await page.waitForTimeout(3000);
- }
- // 使用监听到的数据
- works = capturedWorks;
- }
- logger.info(`[API Interception] Total works: ${works.length}`);
- // 获取有评论的作品
- const worksWithComments = works.filter(w => w.commentCount > 0);
- logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);
- // 如果有评论的作品,需要导航到评论管理页面并逐个切换获取
- if (worksWithComments.length > 0) {
- // 先尝试直接调用 API 获取评论
- for (const work of worksWithComments) {
- logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);
- let comments = capturedComments.get(work.awemeId) || [];
- if (comments.length === 0) {
- comments = await this.fetchCommentsDirectApi(page, work.awemeId);
- }
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
- }
- }
- // 如果直接 API 没有获取到足够的评论,使用页面交互方式
- const worksNeedingPageMethod = worksWithComments.filter(w => {
- const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
- return !found || found.comments.length === 0;
- });
- if (worksNeedingPageMethod.length > 0) {
- logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);
- // works 是所有作品的列表(包括没有评论的),弹窗中的顺序应该和这个一致
- // worksWithComments 是有评论的作品列表
- logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
- logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);
- // 构建作品索引映射:在所有作品列表中,每个有评论的作品的索引是多少
- const workIndexMap = new Map<string, number>();
- works.forEach((w, idx) => {
- if (w.commentCount > 0) {
- workIndexMap.set(w.awemeId, idx);
- }
- });
- logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);
- // 导航到评论管理页面
- logger.info('[Page Method] Navigating to comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面加载
- await page.waitForTimeout(5000);
- // 用于存储最新捕获的评论和 aweme_id
- const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };
- // 设置监听器 - 捕获评论 API 响应
- page.on('response', async (response) => {
- const url = response.url();
- if (url.includes('/comment/list') || url.includes('/comment/read')) {
- try {
- const jsonData = await response.json();
- let parsedComments: CommentItem[] = [];
- let capturedAwemeId = '';
- // 从 URL 中提取 aweme_id(格式1有)
- const awemeIdMatch = url.match(/aweme_id=(\d+)/);
- capturedAwemeId = awemeIdMatch?.[1] || '';
- // 格式1: { comments: [...] }
- if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
- // 从评论中提取 aweme_id
- const firstComment = jsonData.comments[0] as Record<string, unknown>;
- if (!capturedAwemeId && firstComment.aweme_id) {
- capturedAwemeId = String(firstComment.aweme_id);
- }
- parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
- commentId: String((c as { cid?: string }).cid || ''),
- authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
- authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
- authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
- content: String((c as { text?: string }).text || ''),
- likeCount: Number((c as { digg_count?: number }).digg_count || 0),
- commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
- videoId: capturedAwemeId,
- }));
- logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
- }
- // 格式2: { comment_info_list: [...] }
- if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
- parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
- const userInfo = c.user_info as Record<string, unknown> | undefined;
- return {
- commentId: String(c.comment_id || ''),
- authorId: String(userInfo?.user_id || ''),
- authorName: String(userInfo?.screen_name || '匿名'),
- authorAvatar: String(userInfo?.avatar_url || ''),
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: '', // 格式2没有aweme_id,稍后填充
- };
- });
- logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
- }
- if (parsedComments.length > 0) {
- latestHolder.comments = parsedComments;
- latestHolder.awemeId = capturedAwemeId;
- }
- } catch {
- // 忽略
- }
- }
- });
- // 等待第一个作品的评论加载(格式1,有 aweme_id)
- await page.waitForTimeout(4000);
- // 处理第一个作品(页面加载时自动显示,格式1有aweme_id可以直接匹配)
- if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
- const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
- if (matchedWork) {
- allWorkComments.push({
- videoId: matchedWork.awemeId,
- videoTitle: matchedWork.title,
- videoCoverUrl: matchedWork.coverUrl,
- comments: latestHolder.comments,
- });
- logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
- }
- }
- // 遍历其他有评论的作品
- for (const work of worksWithComments) {
- // 检查是否已获取
- const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
- if (existing) {
- logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
- continue;
- }
- // 获取该作品在所有作品列表中的索引
- const workIndex = workIndexMap.get(work.awemeId);
- if (workIndex === undefined) {
- logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
- continue;
- }
- logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);
- try {
- // 清空之前的数据
- latestHolder.comments = [];
- latestHolder.awemeId = '';
- // 点击"选择作品"按钮
- await page.click('button:has-text("选择作品")');
- await page.waitForTimeout(2000);
- // 找到弹窗中的作品图片列表
- const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
- logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);
- if (workIndex < workImages.length) {
- // 点击对应索引的作品
- await workImages[workIndex].click();
- logger.info(`[Page Method] Clicked work image at index ${workIndex}`);
- // 等待评论 API 响应
- await page.waitForTimeout(4000);
- // 获取评论
- if (latestHolder.comments.length > 0) {
- // 使用当前 work 的 awemeId
- const comments = latestHolder.comments.map(c => ({
- ...c,
- videoId: work.awemeId,
- }));
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
- } else {
- // 尝试从页面提取
- const pageComments = await this.extractCommentsFromPage(page);
- if (pageComments.length > 0) {
- const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
- allWorkComments.push({
- videoId: work.awemeId,
- videoTitle: work.title,
- videoCoverUrl: work.coverUrl,
- comments,
- });
- logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
- } else {
- logger.warn(`[Page Method] No comments for ${work.awemeId}`);
- }
- }
- } else {
- logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
- await page.keyboard.press('Escape');
- }
- await page.waitForTimeout(1000);
- } catch (e) {
- logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
- await page.keyboard.press('Escape').catch(() => { });
- await page.waitForTimeout(500);
- }
- }
- }
- }
- logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
- await context.close();
- } catch (error) {
- logger.error('[API Interception] Error:', error);
- } finally {
- await browser.close();
- }
- return allWorkComments;
- }
- /**
- * 直接调用评论 API 获取数据(支持分页获取所有评论)
- * 优先使用视频页面 API(获取全部评论),失败时才使用创作者 API
- */
- private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- // 优先尝试视频页面 API(获取全部评论)
- logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
- let comments = await this.fetchVideoPageCommentsApi(page, awemeId);
- if (comments.length > 0) {
- logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
- return comments;
- }
- // 如果视频页面 API 失败,尝试创作者评论 API(可能只返回部分评论)
- logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
- comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);
- return comments;
- }
- /**
- * 通过视频页面获取全部评论(主要方案)
- * 这个 API 能获取视频的所有评论,不仅仅是创作者回复过的
- */
- private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- const comments: CommentItem[] = [];
- const maxPages = 50;
- let cursor = 0;
- let hasMore = true;
- let pageCount = 0;
- try {
- // 导航到视频页面
- logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
- await page.goto(`https://www.douyin.com/video/${awemeId}`, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- const data = await page.evaluate(async ({ videoId, cursorValue }) => {
- try {
- 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=`;
- const resp = await fetch(url, {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'Referer': `https://www.douyin.com/video/${videoId}`,
- },
- });
- if (!resp.ok) {
- return { error: `HTTP ${resp.status}`, comments: [] };
- }
- return resp.json();
- } catch (e) {
- return { error: String(e), comments: [] };
- }
- }, { videoId: awemeId, cursorValue: cursor });
- if (data?.error) {
- logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
- }
- if (data?.comments && Array.isArray(data.comments)) {
- for (const c of data.comments) {
- comments.push({
- commentId: String(c.cid || ''),
- authorId: String(c.user?.uid || c.user?.sec_uid || ''),
- authorName: String(c.user?.nickname || '匿名'),
- authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- });
- }
- logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
- }
- hasMore = data?.has_more === true || data?.has_more === 1;
- cursor = data?.cursor || cursor + 50;
- if (!data?.comments || data.comments.length === 0) {
- hasMore = false;
- }
- }
- logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
- } catch (e) {
- logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
- }
- return comments;
- }
- /**
- * 创作者评论管理 API(备用方案)
- * 获取的是需要回复的评论
- */
- private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
- const comments: CommentItem[] = [];
- const maxPages = 50;
- let cursor = 0;
- let hasMore = true;
- let pageCount = 0;
- try {
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- const data = await page.evaluate(async ({ videoId, cursorValue }) => {
- 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`;
- const resp = await fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return resp.json();
- }, { videoId: awemeId, cursorValue: cursor });
- if (data?.comments && Array.isArray(data.comments)) {
- for (const c of data.comments) {
- comments.push({
- commentId: String(c.cid || ''),
- authorId: String(c.user?.uid || ''),
- authorName: String(c.user?.nickname || '匿名'),
- authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
- content: String(c.text || ''),
- likeCount: Number(c.digg_count || 0),
- commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
- videoId: String(c.aweme_id || awemeId),
- });
- }
- logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
- }
- hasMore = data?.has_more === true || data?.has_more === 1;
- cursor = data?.cursor || cursor + 50;
- if (!data?.comments || data.comments.length === 0) {
- hasMore = false;
- }
- }
- logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
- } catch (e) {
- logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
- }
- return comments;
- }
- /**
- * 直接调用抖音 API 获取作品列表
- * 使用新的 work_list 接口,支持分页加载
- * 返回作品列表和总作品数
- *
- * 注意:需要先导航到作品管理页面才能正确调用 API
- */
- private async fetchWorksDirectApi(page: Page): Promise<{
- works: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- videoUrl?: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- collectCount: number;
- createTime?: number;
- }>;
- total: number;
- }> {
- const works: Array<{
- awemeId: string;
- title: string;
- coverUrl: string;
- videoUrl?: string;
- playCount: number;
- likeCount: number;
- commentCount: number;
- shareCount: number;
- collectCount: number;
- createTime?: number;
- }> = [];
- let totalCount = 0; // 从 API 获取的总作品数
- try {
- // 首先导航到作品管理页面,确保 API 有正确的上下文和权限
- const contentManageUrl = 'https://creator.douyin.com/creator-micro/content/manage';
- const currentUrl = page.url();
- if (!currentUrl.includes('/content/manage')) {
- logger.info(`[DirectAPI] Navigating to content manage page...`);
- await page.goto(contentManageUrl, {
- waitUntil: 'domcontentloaded',
- timeout: 30000,
- });
- await page.waitForTimeout(2000);
- // 检查是否需要登录
- const newUrl = page.url();
- if (newUrl.includes('login') || newUrl.includes('passport')) {
- logger.warn('[DirectAPI] Not logged in, cannot fetch works');
- return { works, total: 0 };
- }
- }
- let hasMore = true;
- let maxCursor = 0;
- let pageCount = 0;
- const maxPages = 20; // 最多加载20页,防止无限循环
- while (hasMore && pageCount < maxPages) {
- pageCount++;
- logger.info(`[DirectAPI] Fetching works page ${pageCount}, cursor: ${maxCursor}`);
- const data = await page.evaluate(async (cursor: number) => {
- // 使用新的 work_list API 接口
- // status: 0 表示获取全部已发布的作品
- // count: 每页获取数量
- 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`;
- const resp = await fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json',
- },
- });
- return resp.json();
- }, maxCursor);
- // 获取作品数
- const awemeList = data?.aweme_list || [];
-
- // 记录完整的API响应数据,用于调试
- if (pageCount === 1) {
- logger.info(`[DirectAPI] First page API response: ${JSON.stringify(data).substring(0, 1000)}`);
- }
-
- 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}`);
- // 检查 API 返回状态
- if (data?.status_code !== 0 && data?.status_code !== undefined) {
- logger.warn(`[DirectAPI] API returned error status_code: ${data.status_code}`);
- logger.warn(`[DirectAPI] Error message: ${data?.err_msg || data?.errMsg || 'unknown'}`);
- // status_code: 8 表示未授权,可能需要重新登录
- if (data.status_code === 8) {
- logger.warn('[DirectAPI] status_code 8: Not authorized, may need re-login');
- }
- // 如果是第一页就出错,记录更详细的错误信息
- if (pageCount === 1) {
- logger.error(`[DirectAPI] First page failed with status_code ${data.status_code}, cannot fetch works`);
- logger.error(`[DirectAPI] Response data: ${JSON.stringify(data).substring(0, 500)}`);
- }
- break;
- }
-
- // 如果 status_code 是 0 但 aweme_list 为空,记录警告
- if (data?.status_code === 0 && awemeList.length === 0 && pageCount === 1) {
- logger.warn(`[DirectAPI] API returned success but aweme_list is empty on first page`);
- logger.warn(`[DirectAPI] Response data: ${JSON.stringify(data).substring(0, 500)}`);
- }
- // 优先从第一个作品的 author.aweme_count 获取真实作品数(只在第一页获取)
- if (pageCount === 1) {
- const firstAweme = awemeList[0];
-
- // 方案1: 从 author.aweme_count 获取(最准确)
- if (awemeList.length > 0 && firstAweme?.author?.aweme_count !== undefined && firstAweme.author.aweme_count > 0) {
- totalCount = firstAweme.author.aweme_count;
- logger.info(`[DirectAPI] Using author.aweme_count as total works: ${totalCount}`);
- }
-
- // 方案2: 如果 author.aweme_count 不存在,尝试从 API 响应的 total 字段获取
- if (totalCount === 0 && data?.total !== undefined && data.total > 0) {
- totalCount = data.total;
- logger.info(`[DirectAPI] Using API response total field: ${totalCount}`);
- }
-
- // 方案3: 如果前两个都没有,尝试从 author 字段的其他属性获取
- if (totalCount === 0 && awemeList.length > 0 && firstAweme?.author) {
- const author = firstAweme.author;
- const possibleCountFields = ['aweme_count', 'work_count', 'video_count', 'item_count'];
- for (const field of possibleCountFields) {
- if (author[field] !== undefined && author[field] > 0) {
- totalCount = author[field];
- logger.info(`[DirectAPI] Using author.${field} as total works: ${totalCount}`);
- break;
- }
- }
- }
-
- // 方案4: 如果以上都没有,记录完整的 author 对象以便调试
- if (totalCount === 0 && awemeList.length > 0 && firstAweme?.author) {
- logger.warn(`[DirectAPI] Could not find total works count. Author object: ${JSON.stringify(firstAweme.author).substring(0, 300)}`);
- }
-
- // 方案5: 如果第一页没有数据,也记录完整响应以便调试
- if (totalCount === 0 && awemeList.length === 0) {
- logger.warn(`[DirectAPI] First page returned 0 works. Full response: ${JSON.stringify(data).substring(0, 500)}`);
- }
- }
- // 解析 aweme_list 中的作品数据
- logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);
- for (const aweme of awemeList) {
- const awemeId = String(aweme.aweme_id || '');
- if (!awemeId) continue;
- // 从 statistics 中获取所有统计字段
- const statistics = aweme.statistics || {};
- const playCount = parseInt(String(statistics.play_count || '0'), 10);
- const likeCount = parseInt(String(statistics.digg_count || '0'), 10); // 抖音用 digg_count 表示点赞
- const commentCount = parseInt(String(statistics.comment_count || '0'), 10);
- const shareCount = parseInt(String(statistics.share_count || '0'), 10);
- const collectCount = parseInt(String(statistics.collect_count || '0'), 10);
- // 获取标题:优先使用 item_title,其次使用 desc(描述)
- let title = aweme.item_title || '';
- if (!title) {
- // 从 desc 中提取标题(取第一行或前50个字符)
- const desc = aweme.desc || aweme.caption || '';
- title = desc.split('\n')[0].slice(0, 50) || '无标题';
- }
- // 获取封面 URL:从 Cover.url_list 或 video.cover.url_list 中获取
- let coverUrl = '';
- if (aweme.Cover?.url_list?.length > 0) {
- coverUrl = aweme.Cover.url_list[0];
- } else if (aweme.video?.cover?.url_list?.length > 0) {
- coverUrl = aweme.video.cover.url_list[0];
- }
- // 入库 video_url 使用 play_addr.url_list 的第一项
- const videoUrl = aweme.video?.play_addr?.url_list?.[0] || '';
- works.push({
- awemeId,
- title,
- coverUrl,
- videoUrl,
- playCount,
- likeCount,
- commentCount,
- shareCount,
- collectCount,
- createTime: aweme.create_time,
- });
- }
- // 检查是否有更多数据
- // 注意: 抖音 API 返回的 has_more 可能不准确,我们额外判断
- const apiHasMore = data?.has_more === true || data?.has_more === 1;
- // 更新游标:使用返回的 max_cursor
- if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
- // 只有当 max_cursor 有变化时才继续
- if (data.max_cursor !== maxCursor) {
- maxCursor = data.max_cursor;
- hasMore = apiHasMore && awemeList.length > 0;
- } else {
- // max_cursor 没变化,说明到底了
- hasMore = false;
- }
- } else if (awemeList.length > 0) {
- // 如果没有 max_cursor,使用最后一个作品的 create_time 作为游标
- const lastAweme = awemeList[awemeList.length - 1];
- if (lastAweme.create_time) {
- const newCursor = lastAweme.create_time;
- if (newCursor !== maxCursor) {
- maxCursor = newCursor;
- hasMore = apiHasMore;
- } else {
- hasMore = false;
- }
- } else {
- hasMore = false;
- }
- } else {
- // 没有获取到数据,停止循环
- hasMore = false;
- }
- logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);
- // 稍微延迟,避免请求过快
- if (hasMore) {
- await new Promise(resolve => setTimeout(resolve, 500));
- }
- }
- logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages, items count: ${totalCount}`);
-
- // 如果总作品数 > 0 但实际获取到的作品数为 0,记录警告
- if (totalCount > 0 && works.length === 0) {
- logger.warn(`[DirectAPI] Warning: API reported ${totalCount} works but fetched 0 works`);
- logger.warn(`[DirectAPI] This may indicate: API error, cookie expired, or permission issue`);
- }
- } catch (e) {
- logger.error('[DirectAPI] Failed to fetch works:', e);
- logger.error('[DirectAPI] Error details:', e instanceof Error ? e.stack : String(e));
- }
- return { works, total: totalCount };
- }
- /**
- * 通过 Python API 获取评论 - 分作品逐个获取
- */
- private async fetchCommentsViaPythonApi(platform: 'douyin' | 'xiaohongshu' | 'weixin' | 'baijiahao', cookies: CookieData[]): Promise<WorkComments[]> {
- const allWorkComments: WorkComments[] = [];
- const cookieString = JSON.stringify(cookies);
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- // 1. 先获取作品列表(小红书使用 auto_paging 获取全部,避免只取第一页)
- const useAutoPaging = platform === 'xiaohongshu';
- logger.info(`[${platform} Comments Python] Fetching works list (auto_paging=${useAutoPaging})...`);
- const worksResponse = await fetch(`${pythonUrl}/works`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- page: 0,
- page_size: 50,
- auto_paging: useAutoPaging,
- }),
- });
- if (!worksResponse.ok) {
- throw new Error(`Python API works returned ${worksResponse.status}`);
- }
- const worksResult = await worksResponse.json();
- if (!worksResult.success) {
- throw new Error(worksResult.error || 'Failed to get works');
- }
- const works = worksResult.works || [];
- logger.info(`[${platform} Comments Python] Got ${works.length} works`);
- // 2. 遍历作品获取评论
- for (const work of works) {
- const workId = work.work_id;
- if (!workId) continue;
- try {
- logger.info(`[${platform} Comments Python] Fetching comments for work ${workId}...`);
- const commentsResponse = await fetch(`${pythonUrl}/comments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform,
- cookie: cookieString,
- work_id: workId,
- }),
- });
- if (!commentsResponse.ok) {
- logger.warn(`[${platform} Comments Python] Comments API returned ${commentsResponse.status} for work ${workId}`);
- continue;
- }
- const commentsResult = await commentsResponse.json();
- if (!commentsResult.success) {
- logger.warn(`[${platform} Comments Python] Failed to get comments for work ${workId}: ${commentsResult.error}`);
- continue;
- }
- const comments: CommentItem[] = (commentsResult.comments || []).map((c: {
- comment_id: string;
- parent_comment_id: string;
- author_id: string;
- author_name: string;
- author_avatar: string;
- content: string;
- like_count: number;
- create_time: string;
- reply_count?: number;
- }) => ({
- commentId: c.comment_id,
- parentCommentId: c.parent_comment_id,
- authorId: c.author_id,
- authorName: c.author_name,
- authorAvatar: c.author_avatar,
- content: c.content,
- likeCount: c.like_count,
- commentTime: c.create_time,
- replyCount: c.reply_count || 0,
- }));
- if (comments.length > 0) {
- allWorkComments.push({
- videoId: workId,
- videoTitle: work.title || '',
- videoCoverUrl: work.cover_url || '',
- comments,
- });
- logger.info(`[${platform} Comments Python] Got ${comments.length} comments for work ${workId}`);
- }
- } catch (commentError) {
- logger.warn(`[${platform} Comments Python] Error fetching comments for work ${workId}:`, commentError);
- }
- }
- logger.info(`[${platform} Comments Python] Total: ${allWorkComments.length} works with comments`);
- return allWorkComments;
- }
- /**
- * 通过 Python API 获取抖音评论 - 一次性获取所有作品的评论(备用)
- */
- private async fetchDouyinCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
- const cookieString = JSON.stringify(cookies);
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- logger.info('[Douyin Comments Python] Fetching all comments...');
- const response = await fetch(`${pythonUrl}/all_comments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform: 'douyin',
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API all_comments returned ${response.status}`);
- }
- const result = await response.json();
- if (!result.success) {
- throw new Error(result.error || 'Failed to get all comments');
- }
- const workComments = result.work_comments || [];
- logger.info(`[Douyin Comments Python] Got ${workComments.length} works with comments`);
- // 转换数据格式
- const allWorkComments: WorkComments[] = workComments.map((wc: {
- work_id: string;
- title: string;
- cover_url: string;
- comments: Array<{
- comment_id: string;
- author_id: string;
- author_name: string;
- author_avatar: string;
- content: string;
- like_count: number;
- create_time: string;
- is_author?: boolean;
- }>;
- }) => ({
- videoId: wc.work_id,
- videoTitle: wc.title || '',
- videoCoverUrl: wc.cover_url || '',
- comments: (wc.comments || []).map(c => ({
- commentId: c.comment_id,
- authorId: c.author_id,
- authorName: c.author_name,
- authorAvatar: c.author_avatar,
- content: c.content,
- likeCount: c.like_count,
- commentTime: c.create_time,
- })),
- }));
- logger.info(`[Douyin Comments Python] Total: ${allWorkComments.length} works with comments`);
- return allWorkComments;
- }
- /**
- * 获取抖音评论 - 优先使用 Python API
- */
- async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 Python API(分作品获取)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Douyin Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('douyin', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Douyin Comments] Python API returned empty, falling back to Playwright...');
- } catch (pythonError) {
- logger.warn('[Douyin Comments] Python API failed:', pythonError);
- }
- }
- // 回退到 Playwright API 拦截方式
- const result = await this.fetchDouyinCommentsByApiInterception(cookies);
- if (result.length > 0) {
- return result;
- }
- // 如果 API 方式失败,使用旧的 DOM 解析方式作为备用
- logger.info('[Fallback] Using DOM parsing method...');
- const browser = await chromium.launch({
- headless: true, // 改为无头模式
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.douyin.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 导航到评论管理页面
- logger.info('Navigating to Douyin comment management page...');
- await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- // 等待页面完全加载
- logger.info('Waiting for page to fully load...');
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- logger.info(`Current URL: ${currentUrl}`);
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('Cookie expired, need re-login');
- await browser.close();
- return allWorkComments;
- }
- logger.info('Page loaded successfully');
- // 等待评论列表加载
- logger.info('Waiting for comments to load...');
- try {
- await page.waitForSelector('[class*="comment-content-text-"]', { timeout: 10000 });
- logger.info('Comments loaded');
- } catch {
- logger.warn('No comments found on initial load, will try to select works');
- }
- // 辅助函数:从当前页面提取评论
- const extractCommentsFromCurrentPage = async (): Promise<CommentItem[]> => {
- logger.info('Extracting comments from current page...');
- // 滚动页面加载所有评论
- await page.evaluate(async () => {
- // 滚动多次加载更多评论
- for (let i = 0; i < 10; i++) {
- window.scrollBy(0, 500);
- await new Promise(r => setTimeout(r, 800));
- }
- window.scrollTo(0, 0);
- });
- await page.waitForTimeout(2000);
- // 使用精确选择器提取评论
- const comments = await page.evaluate(() => {
- const result: Array<{
- commentId: string;
- authorId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const seenContents = new Set<string>();
- // 查找所有评论容器:包含 username 和 comment-content-text 的 container
- const allContainers = document.querySelectorAll('[class*="container-"]');
- const commentContainers: Element[] = [];
- allContainers.forEach(container => {
- const hasUsername = container.querySelector('[class*="username-"]');
- const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
- if (hasUsername && hasCommentContent) {
- commentContainers.push(container);
- }
- });
- console.log(`Found ${commentContainers.length} comment containers`);
- commentContainers.forEach((container, index) => {
- try {
- // 用户名
- const usernameEl = container.querySelector('[class*="username-"]');
- const authorName = usernameEl?.textContent?.trim() || '未知用户';
- // 时间
- const timeEl = container.querySelector('[class*="time-"]');
- const commentTime = timeEl?.textContent?.trim() || '';
- // 评论内容
- const contentEl = container.querySelector('[class*="comment-content-text-"]');
- const content = contentEl?.textContent?.trim() || '';
- if (!content) return;
- // 头像
- const avatarContainer = container.querySelector('[class*="avatar-"]');
- const avatarImg = avatarContainer?.querySelector('img');
- const authorAvatar = avatarImg?.src || '';
- // 去重
- const key = `${authorName}||${content}`;
- if (seenContents.has(key)) return;
- seenContents.add(key);
- // 点赞数
- let likeCount = 0;
- const opsEl = container.querySelector('[class*="operations-"]');
- if (opsEl) {
- const itemEl = opsEl.querySelector('[class*="item-"]');
- if (itemEl) {
- const match = itemEl.textContent?.match(/(\d+)/);
- if (match) likeCount = parseInt(match[1], 10);
- }
- }
- // 生成 ID
- const hash = content.slice(0, 30) + authorName + commentTime;
- const commentId = `dy_${btoa(encodeURIComponent(hash)).slice(0, 20)}`;
- result.push({
- commentId,
- authorId: authorName,
- authorName,
- authorAvatar,
- content,
- likeCount,
- commentTime,
- });
- console.log(`[${index}] ${authorName}: ${content.slice(0, 30)}`);
- } catch (e) {
- console.error(`Error at ${index}:`, e);
- }
- });
- return result;
- });
- logger.info(`Extracted ${comments.length} comments`);
- return comments;
- };
- // 辅助函数:获取当前显示的作品标题
- const getCurrentWorkTitle = async (): Promise<string> => {
- return page.evaluate(() => {
- // 查找作品标题 - 通常在页面顶部区域
- // 排除筛选器和按钮中的文本
- const excludeTexts = ['全部评论', '最新发布', '全部人群', '搜索', '选择作品', '评论管理'];
- // 方法1: 查找视频信息区域
- const videoInfoSelectors = [
- '[class*="video-info"] [class*="title"]',
- '[class*="work-info"] [class*="title"]',
- '[class*="content-info"] [class*="title"]',
- ];
- for (const selector of videoInfoSelectors) {
- const el = document.querySelector(selector);
- if (el?.textContent) {
- const text = el.textContent.trim();
- if (text.length > 5 && !excludeTexts.some(e => text.includes(e))) {
- return text;
- }
- }
- }
- // 方法2: 查找页面上较长的标题文本
- const allTexts = document.querySelectorAll('div, span, p');
- for (const el of Array.from(allTexts)) {
- const text = el.textContent?.trim() || '';
- if (text.length > 20 &&
- text.length < 200 &&
- !excludeTexts.some(e => text.includes(e)) &&
- !el.closest('button') &&
- !el.closest('[class*="select"]') &&
- !el.closest('[class*="filter"]')) {
- // 检查是否可能是作品标题(通常包含特定字符或格式)
- if (text.includes('#') || text.match(/[,。!?、]/)) {
- return text;
- }
- }
- }
- return '';
- });
- };
- // 步骤1: 先获取当前页面显示的评论(默认显示的第一个作品)
- logger.info('Step 1: Getting comments from default view...');
- const defaultTitle = await getCurrentWorkTitle();
- const defaultComments = await extractCommentsFromCurrentPage();
- if (defaultComments.length > 0) {
- allWorkComments.push({
- videoId: `video_${Date.now()}`,
- videoTitle: defaultTitle || '默认作品',
- videoCoverUrl: '',
- comments: defaultComments,
- });
- logger.info(`Got ${defaultComments.length} comments from default view, title: "${defaultTitle.slice(0, 50)}"`);
- }
- // 步骤2: 尝试点击"选择作品"按钮获取更多作品的评论
- logger.info('Step 2: Looking for "选择作品" button...');
- // 使用 locator 查找按钮
- const selectBtn = page.locator('text=选择作品').first();
- const btnCount = await selectBtn.count();
- logger.info(`Found ${btnCount} "选择作品" button(s)`);
- if (btnCount > 0) {
- logger.info('Clicking "选择作品" button...');
- await selectBtn.click();
- // 等待更长时间,确保弹窗完全加载
- logger.info('Waiting for work list modal to appear...');
- await page.waitForTimeout(5000);
- // 打印当前页面状态,帮助调试
- const modalInfo = await page.evaluate(() => {
- // 查找所有可能的弹窗元素
- const modals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="drawer"], [class*="dialog"], [role="dialog"]');
- const modalClasses = Array.from(modals).map(m => m.className).slice(0, 5);
- // 查找所有图片(作品封面)
- const images = document.querySelectorAll('img[src*="douyinpic"]');
- // 查找所有可能的卡片元素
- const cards = document.querySelectorAll('[class*="card"], [class*="item"]');
- const cardClasses = Array.from(cards).map(c => c.className).slice(0, 10);
- return {
- modalCount: modals.length,
- modalClasses,
- imageCount: images.length,
- cardCount: cards.length,
- cardClasses,
- };
- });
- logger.info(`Modal debug: ${JSON.stringify(modalInfo)}`);
- // 尝试多种选择器查找作品列表
- const workSelectors = [
- '[class*="video-card"]',
- '[class*="work-item"]',
- '[class*="content-item"]',
- '[class*="modal"] [class*="card"]',
- '[class*="modal"] img',
- '[class*="drawer"] [class*="card"]',
- '[class*="drawer"] img',
- '[role="dialog"] [class*="card"]',
- '[role="dialog"] img',
- '[class*="popup"] img',
- 'img[src*="douyinpic"]', // 直接找抖音图片
- ];
- let workElements: Awaited<ReturnType<typeof page.$$>> = [];
- let usedSelector = '';
- for (const selector of workSelectors) {
- const elements = await page.$$(selector);
- logger.info(`Selector "${selector}" found ${elements.length} elements`);
- if (elements.length > 0 && elements.length < 50) { // 避免选中太多无关元素
- workElements = elements;
- usedSelector = selector;
- break;
- }
- }
- logger.info(`Using selector "${usedSelector}", found ${workElements.length} work items`);
- if (workElements.length > 0) {
- // 首先获取所有作品的评论数信息
- // 根据 HTML 结构:
- // - 作品项容器: div.container-Lkxos9 (类名可能变化,使用 [class*="container-"])
- // - 标题: div.title-LUOP3b (类名可能变化,使用 [class*="title-"])
- // - 评论数: div.right-os7ZB9 > div (类名可能变化,使用 [class*="right-"] > div)
- const workInfoList = await page.evaluate(() => {
- const works: Array<{ index: number; title: string; commentCount: number }> = [];
- // 查找作品列表容器中的所有作品项
- // 根据用户提供的 HTML,作品项的类名是 container-Lkxos9
- const workContainers = document.querySelectorAll('[role="dialog"] [class*="container-"]');
- console.log(`Found ${workContainers.length} work containers`);
- workContainers.forEach((container, index) => {
- // 检查是否包含图片(确认是作品项而不是其他容器)
- const img = container.querySelector('img[src*="douyinpic"]');
- if (!img) {
- console.log(`Container ${index} has no douyinpic image, skipping`);
- return;
- }
- // 提取标题
- const titleEl = container.querySelector('[class*="title-"]');
- const title = titleEl?.textContent?.trim() || `作品 ${works.length + 1}`;
- // 提取评论数 - 在 right- 容器的最后一个 div 中
- let commentCount = 0;
- const rightContainer = container.querySelector('[class*="right-"]');
- if (rightContainer) {
- // 获取 right 容器下的所有直接 div 子元素
- const divs = rightContainer.querySelectorAll(':scope > div');
- if (divs.length > 0) {
- // 最后一个 div 包含评论数
- const lastDiv = divs[divs.length - 1];
- const text = lastDiv.textContent?.trim() || '0';
- const num = parseInt(text, 10);
- if (!isNaN(num)) {
- commentCount = num;
- }
- }
- }
- console.log(`Work ${works.length}: title="${title.slice(0, 30)}...", commentCount=${commentCount}`);
- works.push({
- index: works.length,
- title: title.slice(0, 100),
- commentCount
- });
- });
- // 如果上面的选择器没找到,尝试备用方法
- if (works.length === 0) {
- console.log('Primary selector failed, trying fallback...');
- // 直接查找包含 douyinpic 图片的元素的父容器
- const images = document.querySelectorAll('[role="dialog"] img[src*="douyinpic"]');
- images.forEach((img, index) => {
- // 向上查找到作品项容器
- let container = img.parentElement;
- while (container && !container.classList.toString().includes('container-')) {
- container = container.parentElement;
- }
- if (container) {
- const titleEl = container.querySelector('[class*="title-"]');
- const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
- // 查找评论数
- let commentCount = 0;
- const rightEl = container.querySelector('[class*="right-"]');
- if (rightEl) {
- const text = rightEl.textContent?.trim() || '';
- // 提取最后出现的数字
- const matches = text.match(/\d+/g);
- if (matches && matches.length > 0) {
- commentCount = parseInt(matches[matches.length - 1], 10);
- }
- }
- works.push({ index, title: title.slice(0, 100), commentCount });
- }
- });
- }
- return works;
- });
- logger.info(`Work info list (${workInfoList.length} items): ${JSON.stringify(workInfoList)}`);
- // 过滤出评论数 > 0 的作品,或者评论数未知(-1)的作品
- const worksWithComments = workInfoList.filter(w => w.commentCount > 0 || w.commentCount === -1);
- logger.info(`Found ${worksWithComments.length} works with comments > 0 or unknown (out of ${workInfoList.length})`);
- // 如果所有作品评论数都是0,则不处理任何作品
- const allZero = workInfoList.every(w => w.commentCount === 0);
- if (allZero) {
- logger.info('All works have 0 comments, skipping all');
- }
- // 如果没有找到评论数信息或有未知的,处理这些作品
- const indicesToProcess = allZero
- ? []
- : (worksWithComments.length > 0
- ? worksWithComments.map(w => w.index)
- : Array.from({ length: Math.min(workElements.length, 10) }, (_, i) => i));
- logger.info(`Will process work indices: ${indicesToProcess.join(', ')}`);
- // 遍历每个有评论的作品
- for (let idx = 0; idx < indicesToProcess.length; idx++) {
- const i = indicesToProcess[idx];
- try {
- const workInfo = workInfoList.find(w => w.index === i);
- logger.info(`Processing work ${idx + 1}/${indicesToProcess.length} (index=${i}, title="${workInfo?.title}", expectedComments=${workInfo?.commentCount})...`);
- // 重新打开选择作品弹窗
- if (idx > 0) {
- await selectBtn.click();
- await page.waitForTimeout(3000);
- }
- // 重新获取元素列表(因为 DOM 可能已变化)
- const currentItems = await page.$$(usedSelector);
- if (i < currentItems.length) {
- // 滚动到元素可见
- await currentItems[i].scrollIntoViewIfNeeded();
- await page.waitForTimeout(500);
- // 点击元素
- await currentItems[i].click();
- await page.waitForTimeout(4000);
- // 获取评论
- const title = await getCurrentWorkTitle();
- const comments = await extractCommentsFromCurrentPage();
- logger.info(`Work index=${i}: title="${title.slice(0, 50)}", comments=${comments.length}`);
- // 检查是否已经获取过这个作品的评论
- const exists = allWorkComments.some(w =>
- w.videoTitle === title ||
- (w.comments.length > 0 && comments.length > 0 &&
- w.comments[0].content === comments[0].content)
- );
- if (!exists && (comments.length > 0 || title)) {
- allWorkComments.push({
- videoId: `video_${Date.now()}_${i}`,
- videoTitle: title || workInfo?.title || `作品 ${i + 1}`,
- videoCoverUrl: '',
- comments,
- });
- logger.info(`Work index=${i}: Saved ${comments.length} comments`);
- } else {
- logger.info(`Work index=${i}: Skipped (duplicate or empty)`);
- }
- }
- } catch (err) {
- logger.warn(`Error processing work index=${i}:`, err);
- }
- }
- } else {
- logger.warn('No work items found in modal');
- }
- // 按 Escape 关闭弹窗
- try {
- await page.keyboard.press('Escape');
- await page.waitForTimeout(500);
- } catch { }
- } else {
- logger.warn('"选择作品" button not found, only default comments will be returned');
- }
- await page.close();
- await context.close();
- await browser.close();
- const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
- logger.info(`Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('Error fetching Douyin comments:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- /**
- * 通过 Python API 获取小红书评论 - 一次性获取所有作品的评论
- */
- private async fetchXiaohongshuCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
- const cookieString = JSON.stringify(cookies);
- const pythonUrl = (await getPythonServiceBaseUrl()).replace(/\/$/, '');
- logger.info('[Xiaohongshu Comments Python] Fetching all comments...');
- const response = await fetch(`${pythonUrl}/all_comments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- platform: 'xiaohongshu',
- cookie: cookieString,
- }),
- });
- if (!response.ok) {
- throw new Error(`Python API all_comments returned ${response.status}`);
- }
- const result = await response.json();
- if (!result.success) {
- throw new Error(result.error || 'Failed to get all comments');
- }
- const workComments = result.work_comments || [];
- logger.info(`[Xiaohongshu Comments Python] Got ${workComments.length} works with comments`);
- // 转换数据格式
- const allWorkComments: WorkComments[] = workComments.map((wc: {
- work_id: string;
- title: string;
- cover_url: string;
- comments: Array<{
- comment_id: string;
- author_id: string;
- author_name: string;
- author_avatar: string;
- content: string;
- like_count: number;
- create_time: string;
- }>;
- }) => ({
- videoId: wc.work_id,
- videoTitle: wc.title || '',
- videoCoverUrl: wc.cover_url || '',
- comments: (wc.comments || []).map(c => ({
- commentId: c.comment_id,
- authorId: c.author_id,
- authorName: c.author_name,
- authorAvatar: c.author_avatar,
- content: c.content,
- likeCount: c.like_count,
- commentTime: c.create_time,
- })),
- }));
- logger.info(`[Xiaohongshu Comments Python] Total: ${allWorkComments.length} works with comments`);
- return allWorkComments;
- }
- /**
- * 获取小红书评论 - 优先使用 Python API
- */
- async fetchXiaohongshuCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 Python API(分作品获取)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Xiaohongshu Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('xiaohongshu', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Xiaohongshu Comments] Python API returned empty, falling back to Playwright...');
- } catch (pythonError) {
- logger.warn('[Xiaohongshu Comments] Python API failed:', pythonError);
- }
- }
- // 回退到 Playwright 方式
- const browser = await chromium.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.xiaohongshu.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 用于捕获评论数据
- const capturedComments: Map<string, CommentItem[]> = new Map();
- const capturedNotes: Array<{
- noteId: string;
- title: string;
- coverUrl: string;
- }> = [];
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听笔记列表 API
- if (url.includes('/api/galaxy/creator/content/note_list') ||
- url.includes('/api/galaxy/creator/notes')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
- const notes = data?.data?.notes || data?.data?.list || [];
- for (const note of notes) {
- capturedNotes.push({
- noteId: note.note_id || note.id || '',
- title: note.title || note.desc || '',
- coverUrl: note.cover?.url || note.cover || '',
- });
- }
- }
- // 监听评论列表 API
- if (url.includes('/api/sns/web/v2/comment/page') ||
- url.includes('/api/galaxy/creator/comment') ||
- url.includes('/api/sns/v1/note/comment')) {
- const data = await response.json();
- logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
- const comments: CommentItem[] = [];
- const commentList = data?.data?.comments || data?.comments || [];
- for (const comment of commentList) {
- comments.push({
- commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
- authorId: comment.user_info?.user_id || comment.user_id || '',
- authorName: comment.user_info?.nickname || comment.nickname || '',
- authorAvatar: comment.user_info?.image || comment.avatar || '',
- content: comment.content || '',
- likeCount: comment.like_count || 0,
- commentTime: comment.create_time || comment.time || '',
- parentCommentId: comment.target_comment_id || undefined,
- });
- // 处理子评论
- const subComments = comment.sub_comments || comment.replies || [];
- for (const sub of subComments) {
- comments.push({
- commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
- authorId: sub.user_info?.user_id || sub.user_id || '',
- authorName: sub.user_info?.nickname || sub.nickname || '',
- authorAvatar: sub.user_info?.image || sub.avatar || '',
- content: sub.content || '',
- likeCount: sub.like_count || 0,
- commentTime: sub.create_time || sub.time || '',
- parentCommentId: comment.id || comment.comment_id || undefined,
- });
- }
- }
- // 尝试从 URL 获取笔记 ID
- const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
- const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;
- if (comments.length > 0) {
- const existing = capturedComments.get(noteId) || [];
- capturedComments.set(noteId, [...existing, ...comments]);
- }
- }
- } catch { }
- });
- // 导航到评论管理页面
- logger.info('[Xiaohongshu Comments] Navigating to comment management...');
- await page.goto('https://creator.xiaohongshu.com/creator/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
- await browser.close();
- return allWorkComments;
- }
- // 尝试加载更多评论
- for (let i = 0; i < 5; i++) {
- await page.evaluate(() => {
- window.scrollBy(0, 500);
- });
- await page.waitForTimeout(1000);
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 将捕获的评论转换为 WorkComments 格式
- for (const [noteId, comments] of capturedComments) {
- const noteInfo = capturedNotes.find(n => n.noteId === noteId);
- allWorkComments.push({
- videoId: noteId,
- videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
- videoCoverUrl: noteInfo?.coverUrl || '',
- comments,
- });
- }
- // 如果没有从 API 获取到评论,尝试从页面提取
- if (allWorkComments.length === 0) {
- logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');
- const pageComments = await page.evaluate(() => {
- const result: Array<{
- commentId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
- commentItems.forEach((item, index) => {
- try {
- const authorEl = item.querySelector('[class*="author"], [class*="name"]');
- const avatarEl = item.querySelector('img');
- const contentEl = item.querySelector('[class*="content"]');
- const timeEl = item.querySelector('[class*="time"]');
- const likeEl = item.querySelector('[class*="like"] span');
- result.push({
- commentId: `xhs_page_${index}`,
- authorName: authorEl?.textContent?.trim() || '',
- authorAvatar: avatarEl?.src || '',
- content: contentEl?.textContent?.trim() || '',
- likeCount: parseInt(likeEl?.textContent || '0') || 0,
- commentTime: timeEl?.textContent?.trim() || '',
- });
- } catch { }
- });
- return result;
- });
- if (pageComments.length > 0) {
- allWorkComments.push({
- videoId: 'page_comments',
- videoTitle: '页面评论',
- videoCoverUrl: '',
- comments: pageComments.map(c => ({
- ...c,
- authorId: '',
- })),
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
- logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('[Xiaohongshu Comments] Error:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- /**
- * #6073: 获取百家号评论 - 优先使用 Python API
- * 注: CommentService 调用了此方法但之前未实现,导致运行时 TypeError
- */
- async fetchBaijiahaoCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Baijiahao Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('baijiahao', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Baijiahao Comments] Python API returned empty');
- } catch (pythonError) {
- logger.warn('[Baijiahao Comments] Python API failed:', pythonError);
- }
- }
- // 百家号暂无 Playwright 评论抓取方案,返回空数组
- logger.warn('[Baijiahao Comments] No fallback available, returning empty');
- return [];
- }
- /**
- * 获取微信视频号评论 - 优先使用 Python API
- */
- async fetchWeixinVideoCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
- // 优先使用 Python API(分作品获取)
- const pythonAvailable = await this.checkPythonServiceAvailable();
- if (pythonAvailable) {
- logger.info('[Weixin Video Comments] Using Python API...');
- try {
- const result = await this.fetchCommentsViaPythonApi('weixin', cookies);
- if (result.length > 0) {
- return result;
- }
- logger.info('[Weixin Video Comments] Python API returned empty, falling back to Playwright...');
- } catch (pythonError) {
- logger.warn('[Weixin Video Comments] Python API failed:', pythonError);
- }
- }
- // 回退到 Playwright 方式
- const browser = await chromium.launch({
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- });
- const allWorkComments: WorkComments[] = [];
- try {
- const context = await browser.newContext({
- viewport: { width: 1920, height: 1080 },
- userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- });
- // 设置 Cookie
- const playwrightCookies = cookies.map(c => ({
- name: c.name,
- value: c.value,
- domain: c.domain || '.weixin.qq.com',
- path: c.path || '/',
- }));
- await context.addCookies(playwrightCookies);
- logger.info(`[Weixin Video Comments] Set ${playwrightCookies.length} cookies`);
- const page = await context.newPage();
- // 用于捕获评论数据
- const capturedComments: Map<string, CommentItem[]> = new Map();
- const capturedWorks: Array<{
- workId: string;
- title: string;
- coverUrl: string;
- }> = [];
- // 设置 API 响应监听器
- page.on('response', async (response) => {
- const url = response.url();
- try {
- // 监听作品列表 API
- if (url.includes('/mmfinderassistant-bin/post/post_list')) {
- const data = await response.json();
- logger.info(`[Weixin Video API] Works list: ${JSON.stringify(data).slice(0, 500)}`);
- const posts = data?.data?.list || [];
- for (const post of posts) {
- capturedWorks.push({
- workId: post.objectNonce || post.id || '',
- title: post.title || post.desc || '',
- coverUrl: post.cover?.url || post.cover || '',
- });
- }
- }
- // 监听评论列表 API
- if (url.includes('/mmfinderassistant-bin/comment/comment_list')) {
- const data = await response.json();
- logger.info(`[Weixin Video API] Comments: ${JSON.stringify(data).slice(0, 500)}`);
- const comments: CommentItem[] = [];
- const commentList = data?.data?.commentList || data?.comments || [];
- for (const comment of commentList) {
- comments.push({
- commentId: comment.commentId || comment.id || `weixin_${Date.now()}`,
- authorId: comment.commenterInfo?.identifier || comment.authorId || '',
- authorName: comment.commenterInfo?.nickName || comment.nickname || comment.nick_name || '',
- authorAvatar: comment.commenterInfo?.headUrl || comment.avatar || '',
- content: comment.content || '',
- likeCount: comment.likeCnt || comment.like_count || 0,
- commentTime: comment.createTime || comment.create_time || '',
- parentCommentId: comment.parentCommentId || undefined,
- });
- // 处理子评论
- const subComments = comment.subCommentList || comment.sub_comments || [];
- for (const sub of subComments) {
- comments.push({
- commentId: sub.commentId || sub.id || `weixin_sub_${Date.now()}`,
- authorId: sub.commenterInfo?.identifier || sub.authorId || '',
- authorName: sub.commenterInfo?.nickName || sub.nickname || sub.nick_name || '',
- authorAvatar: sub.commenterInfo?.headUrl || sub.avatar || '',
- content: sub.content || '',
- likeCount: sub.likeCnt || sub.like_count || 0,
- commentTime: sub.createTime || sub.create_time || '',
- parentCommentId: comment.commentId || comment.id || undefined,
- });
- }
- }
- // 尝试从 URL 获取作品 ID
- const workIdMatch = url.match(/objectNonce=([^&]+)/) || url.match(/workId=([^&]+)/);
- const workId = workIdMatch?.[1] || `work_${Date.now()}`;
- if (comments.length > 0) {
- const existing = capturedComments.get(workId) || [];
- capturedComments.set(workId, [...existing, ...comments]);
- }
- }
- } catch { }
- });
- // 导航到评论管理页面
- logger.info('[Weixin Video Comments] Navigating to comment management...');
- await page.goto('https://channels.weixin.qq.com/platform/interaction/comment', {
- waitUntil: 'domcontentloaded',
- timeout: 60000,
- });
- await page.waitForTimeout(5000);
- // 检查是否需要登录
- const currentUrl = page.url();
- if (currentUrl.includes('login') || currentUrl.includes('passport')) {
- logger.warn('[Weixin Video Comments] Cookie expired, need re-login');
- await browser.close();
- return allWorkComments;
- }
- // 尝试加载更多评论
- for (let i = 0; i < 5; i++) {
- await page.evaluate(() => {
- window.scrollBy(0, 500);
- });
- await page.waitForTimeout(1000);
- }
- // 等待 API 响应
- await page.waitForTimeout(3000);
- // 将捕获的评论转换为 WorkComments 格式
- for (const [workId, comments] of capturedComments) {
- const workInfo = capturedWorks.find(w => w.workId === workId);
- allWorkComments.push({
- videoId: workId,
- videoTitle: workInfo?.title || `作品 ${workId.slice(0, 10)}`,
- videoCoverUrl: workInfo?.coverUrl || '',
- comments,
- });
- }
- // 如果没有从 API 获取到评论,尝试从页面提取
- if (allWorkComments.length === 0) {
- logger.info('[Weixin Video Comments] No comments from API, extracting from page...');
- const pageComments = await page.evaluate(() => {
- const result: Array<{
- commentId: string;
- authorName: string;
- authorAvatar: string;
- content: string;
- likeCount: number;
- commentTime: string;
- }> = [];
- const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
- commentItems.forEach((item, index) => {
- try {
- const authorEl = item.querySelector('[class*="author"], [class*="name"]');
- const avatarEl = item.querySelector('img');
- const contentEl = item.querySelector('[class*="content"]');
- const timeEl = item.querySelector('[class*="time"]');
- const likeEl = item.querySelector('[class*="like"] span');
- result.push({
- commentId: `weixin_page_${index}`,
- authorName: authorEl?.textContent?.trim() || '',
- authorAvatar: avatarEl?.src || '',
- content: contentEl?.textContent?.trim() || '',
- likeCount: parseInt(likeEl?.textContent || '0') || 0,
- commentTime: timeEl?.textContent?.trim() || '',
- });
- } catch { }
- });
- return result;
- });
- if (pageComments.length > 0) {
- allWorkComments.push({
- videoId: 'page_comments',
- videoTitle: '页面评论',
- videoCoverUrl: '',
- comments: pageComments.map(c => ({
- ...c,
- authorId: '',
- })),
- });
- }
- }
- await page.close();
- await context.close();
- await browser.close();
- const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
- logger.info(`[Weixin Video Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);
- return allWorkComments;
- } catch (error) {
- logger.error('[Weixin Video Comments] Error:', error);
- try {
- await browser.close();
- } catch { }
- return allWorkComments;
- }
- }
- }
- export const headlessBrowserService = new HeadlessBrowserService();
|