HeadlessBrowserService.ts 168 KB

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