HeadlessBrowserService.ts 197 KB

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