HeadlessBrowserService.ts 196 KB

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