main.py 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623
  1. # coding=utf-8
  2. import json
  3. import os
  4. import random
  5. import re
  6. import time
  7. import webbrowser
  8. import smtplib
  9. from email.mime.text import MIMEText
  10. from email.mime.multipart import MIMEMultipart
  11. from email.header import Header
  12. from email.utils import formataddr, formatdate, make_msgid
  13. from datetime import datetime
  14. from pathlib import Path
  15. from typing import Dict, List, Tuple, Optional, Union
  16. import pytz
  17. import requests
  18. import yaml
  19. VERSION = "3.1.0"
  20. # === SMTP邮件配置 ===
  21. SMTP_CONFIGS = {
  22. # Gmail(使用 STARTTLS)
  23. "gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"},
  24. # QQ邮箱(使用 SSL,更稳定)
  25. "qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"},
  26. # Outlook(使用 STARTTLS)
  27. "outlook.com": {
  28. "server": "smtp-mail.outlook.com",
  29. "port": 587,
  30. "encryption": "TLS",
  31. },
  32. "hotmail.com": {
  33. "server": "smtp-mail.outlook.com",
  34. "port": 587,
  35. "encryption": "TLS",
  36. },
  37. "live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  38. # 网易邮箱(使用 SSL,更稳定)
  39. "163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"},
  40. "126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"},
  41. # 新浪邮箱(使用 SSL)
  42. "sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"},
  43. # 搜狐邮箱(使用 SSL)
  44. "sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"},
  45. # 天翼邮箱(使用 SSL)
  46. "189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"},
  47. }
  48. # === 配置管理 ===
  49. def load_config():
  50. """加载配置文件"""
  51. config_path = os.environ.get("CONFIG_PATH", "config/config.yaml")
  52. if not Path(config_path).exists():
  53. raise FileNotFoundError(f"配置文件 {config_path} 不存在")
  54. with open(config_path, "r", encoding="utf-8") as f:
  55. config_data = yaml.safe_load(f)
  56. print(f"配置文件加载成功: {config_path}")
  57. # 构建配置
  58. config = {
  59. "VERSION_CHECK_URL": config_data["app"]["version_check_url"],
  60. "SHOW_VERSION_UPDATE": config_data["app"]["show_version_update"],
  61. "REQUEST_INTERVAL": config_data["crawler"]["request_interval"],
  62. "REPORT_MODE": os.environ.get("REPORT_MODE", "").strip()
  63. or config_data["report"]["mode"],
  64. "RANK_THRESHOLD": config_data["report"]["rank_threshold"],
  65. "USE_PROXY": config_data["crawler"]["use_proxy"],
  66. "DEFAULT_PROXY": config_data["crawler"]["default_proxy"],
  67. "ENABLE_CRAWLER": os.environ.get("ENABLE_CRAWLER", "").strip().lower()
  68. in ("true", "1")
  69. if os.environ.get("ENABLE_CRAWLER", "").strip()
  70. else config_data["crawler"]["enable_crawler"],
  71. "ENABLE_NOTIFICATION": os.environ.get("ENABLE_NOTIFICATION", "").strip().lower()
  72. in ("true", "1")
  73. if os.environ.get("ENABLE_NOTIFICATION", "").strip()
  74. else config_data["notification"]["enable_notification"],
  75. "MESSAGE_BATCH_SIZE": config_data["notification"]["message_batch_size"],
  76. "DINGTALK_BATCH_SIZE": config_data["notification"].get(
  77. "dingtalk_batch_size", 20000
  78. ),
  79. "FEISHU_BATCH_SIZE": config_data["notification"].get("feishu_batch_size", 29000),
  80. "BATCH_SEND_INTERVAL": config_data["notification"]["batch_send_interval"],
  81. "FEISHU_MESSAGE_SEPARATOR": config_data["notification"][
  82. "feishu_message_separator"
  83. ],
  84. "PUSH_WINDOW": {
  85. "ENABLED": os.environ.get("PUSH_WINDOW_ENABLED", "").strip().lower()
  86. in ("true", "1")
  87. if os.environ.get("PUSH_WINDOW_ENABLED", "").strip()
  88. else config_data["notification"]
  89. .get("push_window", {})
  90. .get("enabled", False),
  91. "TIME_RANGE": {
  92. "START": os.environ.get("PUSH_WINDOW_START", "").strip()
  93. or config_data["notification"]
  94. .get("push_window", {})
  95. .get("time_range", {})
  96. .get("start", "08:00"),
  97. "END": os.environ.get("PUSH_WINDOW_END", "").strip()
  98. or config_data["notification"]
  99. .get("push_window", {})
  100. .get("time_range", {})
  101. .get("end", "22:00"),
  102. },
  103. "ONCE_PER_DAY": os.environ.get("PUSH_WINDOW_ONCE_PER_DAY", "").strip().lower()
  104. in ("true", "1")
  105. if os.environ.get("PUSH_WINDOW_ONCE_PER_DAY", "").strip()
  106. else config_data["notification"]
  107. .get("push_window", {})
  108. .get("once_per_day", True),
  109. "RECORD_RETENTION_DAYS": int(
  110. os.environ.get("PUSH_WINDOW_RETENTION_DAYS", "").strip() or "0"
  111. )
  112. or config_data["notification"]
  113. .get("push_window", {})
  114. .get("push_record_retention_days", 7),
  115. },
  116. "WEIGHT_CONFIG": {
  117. "RANK_WEIGHT": config_data["weight"]["rank_weight"],
  118. "FREQUENCY_WEIGHT": config_data["weight"]["frequency_weight"],
  119. "HOTNESS_WEIGHT": config_data["weight"]["hotness_weight"],
  120. },
  121. "PLATFORMS": config_data["platforms"],
  122. }
  123. # 通知渠道配置(环境变量优先)
  124. notification = config_data.get("notification", {})
  125. webhooks = notification.get("webhooks", {})
  126. config["FEISHU_WEBHOOK_URL"] = os.environ.get(
  127. "FEISHU_WEBHOOK_URL", ""
  128. ).strip() or webhooks.get("feishu_url", "")
  129. config["DINGTALK_WEBHOOK_URL"] = os.environ.get(
  130. "DINGTALK_WEBHOOK_URL", ""
  131. ).strip() or webhooks.get("dingtalk_url", "")
  132. config["WEWORK_WEBHOOK_URL"] = os.environ.get(
  133. "WEWORK_WEBHOOK_URL", ""
  134. ).strip() or webhooks.get("wework_url", "")
  135. config["WEWORK_MSG_TYPE"] = os.environ.get(
  136. "WEWORK_MSG_TYPE", ""
  137. ).strip() or webhooks.get("wework_msg_type", "markdown")
  138. config["TELEGRAM_BOT_TOKEN"] = os.environ.get(
  139. "TELEGRAM_BOT_TOKEN", ""
  140. ).strip() or webhooks.get("telegram_bot_token", "")
  141. config["TELEGRAM_CHAT_ID"] = os.environ.get(
  142. "TELEGRAM_CHAT_ID", ""
  143. ).strip() or webhooks.get("telegram_chat_id", "")
  144. # 邮件配置
  145. config["EMAIL_FROM"] = os.environ.get("EMAIL_FROM", "").strip() or webhooks.get(
  146. "email_from", ""
  147. )
  148. config["EMAIL_PASSWORD"] = os.environ.get(
  149. "EMAIL_PASSWORD", ""
  150. ).strip() or webhooks.get("email_password", "")
  151. config["EMAIL_TO"] = os.environ.get("EMAIL_TO", "").strip() or webhooks.get(
  152. "email_to", ""
  153. )
  154. config["EMAIL_SMTP_SERVER"] = os.environ.get(
  155. "EMAIL_SMTP_SERVER", ""
  156. ).strip() or webhooks.get("email_smtp_server", "")
  157. config["EMAIL_SMTP_PORT"] = os.environ.get(
  158. "EMAIL_SMTP_PORT", ""
  159. ).strip() or webhooks.get("email_smtp_port", "")
  160. # ntfy配置
  161. config["NTFY_SERVER_URL"] = os.environ.get(
  162. "NTFY_SERVER_URL", "https://ntfy.sh"
  163. ).strip() or webhooks.get("ntfy_server_url", "https://ntfy.sh")
  164. config["NTFY_TOPIC"] = os.environ.get("NTFY_TOPIC", "").strip() or webhooks.get(
  165. "ntfy_topic", ""
  166. )
  167. config["NTFY_TOKEN"] = os.environ.get("NTFY_TOKEN", "").strip() or webhooks.get(
  168. "ntfy_token", ""
  169. )
  170. # 输出配置来源信息
  171. notification_sources = []
  172. if config["FEISHU_WEBHOOK_URL"]:
  173. source = "环境变量" if os.environ.get("FEISHU_WEBHOOK_URL") else "配置文件"
  174. notification_sources.append(f"飞书({source})")
  175. if config["DINGTALK_WEBHOOK_URL"]:
  176. source = "环境变量" if os.environ.get("DINGTALK_WEBHOOK_URL") else "配置文件"
  177. notification_sources.append(f"钉钉({source})")
  178. if config["WEWORK_WEBHOOK_URL"]:
  179. source = "环境变量" if os.environ.get("WEWORK_WEBHOOK_URL") else "配置文件"
  180. notification_sources.append(f"企业微信({source})")
  181. if config["TELEGRAM_BOT_TOKEN"] and config["TELEGRAM_CHAT_ID"]:
  182. token_source = (
  183. "环境变量" if os.environ.get("TELEGRAM_BOT_TOKEN") else "配置文件"
  184. )
  185. chat_source = "环境变量" if os.environ.get("TELEGRAM_CHAT_ID") else "配置文件"
  186. notification_sources.append(f"Telegram({token_source}/{chat_source})")
  187. if config["EMAIL_FROM"] and config["EMAIL_PASSWORD"] and config["EMAIL_TO"]:
  188. from_source = "环境变量" if os.environ.get("EMAIL_FROM") else "配置文件"
  189. notification_sources.append(f"邮件({from_source})")
  190. if config["NTFY_SERVER_URL"] and config["NTFY_TOPIC"]:
  191. server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件"
  192. notification_sources.append(f"ntfy({server_source})")
  193. if notification_sources:
  194. print(f"通知渠道配置来源: {', '.join(notification_sources)}")
  195. else:
  196. print("未配置任何通知渠道")
  197. return config
  198. print("正在加载配置...")
  199. CONFIG = load_config()
  200. print(f"TrendRadar v{VERSION} 配置加载完成")
  201. print(f"监控平台数量: {len(CONFIG['PLATFORMS'])}")
  202. # === 工具函数 ===
  203. def get_beijing_time():
  204. """获取北京时间"""
  205. return datetime.now(pytz.timezone("Asia/Shanghai"))
  206. def format_date_folder():
  207. """格式化日期文件夹"""
  208. return get_beijing_time().strftime("%Y年%m月%d日")
  209. def format_time_filename():
  210. """格式化时间文件名"""
  211. return get_beijing_time().strftime("%H时%M分")
  212. def clean_title(title: str) -> str:
  213. """清理标题中的特殊字符"""
  214. if not isinstance(title, str):
  215. title = str(title)
  216. cleaned_title = title.replace("\n", " ").replace("\r", " ")
  217. cleaned_title = re.sub(r"\s+", " ", cleaned_title)
  218. cleaned_title = cleaned_title.strip()
  219. return cleaned_title
  220. def ensure_directory_exists(directory: str):
  221. """确保目录存在"""
  222. Path(directory).mkdir(parents=True, exist_ok=True)
  223. def get_output_path(subfolder: str, filename: str) -> str:
  224. """获取输出路径"""
  225. date_folder = format_date_folder()
  226. output_dir = Path("output") / date_folder / subfolder
  227. ensure_directory_exists(str(output_dir))
  228. return str(output_dir / filename)
  229. def check_version_update(
  230. current_version: str, version_url: str, proxy_url: Optional[str] = None
  231. ) -> Tuple[bool, Optional[str]]:
  232. """检查版本更新"""
  233. try:
  234. proxies = None
  235. if proxy_url:
  236. proxies = {"http": proxy_url, "https": proxy_url}
  237. headers = {
  238. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  239. "Accept": "text/plain, */*",
  240. "Cache-Control": "no-cache",
  241. }
  242. response = requests.get(
  243. version_url, proxies=proxies, headers=headers, timeout=10
  244. )
  245. response.raise_for_status()
  246. remote_version = response.text.strip()
  247. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  248. # 比较版本
  249. def parse_version(version_str):
  250. try:
  251. parts = version_str.strip().split(".")
  252. if len(parts) != 3:
  253. raise ValueError("版本号格式不正确")
  254. return int(parts[0]), int(parts[1]), int(parts[2])
  255. except:
  256. return 0, 0, 0
  257. current_tuple = parse_version(current_version)
  258. remote_tuple = parse_version(remote_version)
  259. need_update = current_tuple < remote_tuple
  260. return need_update, remote_version if need_update else None
  261. except Exception as e:
  262. print(f"版本检查失败: {e}")
  263. return False, None
  264. def is_first_crawl_today() -> bool:
  265. """检测是否是当天第一次爬取"""
  266. date_folder = format_date_folder()
  267. txt_dir = Path("output") / date_folder / "txt"
  268. if not txt_dir.exists():
  269. return True
  270. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  271. return len(files) <= 1
  272. def html_escape(text: str) -> str:
  273. """HTML转义"""
  274. if not isinstance(text, str):
  275. text = str(text)
  276. return (
  277. text.replace("&", "&amp;")
  278. .replace("<", "&lt;")
  279. .replace(">", "&gt;")
  280. .replace('"', "&quot;")
  281. .replace("'", "&#x27;")
  282. )
  283. # === 推送记录管理 ===
  284. class PushRecordManager:
  285. """推送记录管理器"""
  286. def __init__(self):
  287. self.record_dir = Path("output") / ".push_records"
  288. self.ensure_record_dir()
  289. self.cleanup_old_records()
  290. def ensure_record_dir(self):
  291. """确保记录目录存在"""
  292. self.record_dir.mkdir(parents=True, exist_ok=True)
  293. def get_today_record_file(self) -> Path:
  294. """获取今天的记录文件路径"""
  295. today = get_beijing_time().strftime("%Y%m%d")
  296. return self.record_dir / f"push_record_{today}.json"
  297. def cleanup_old_records(self):
  298. """清理过期的推送记录"""
  299. retention_days = CONFIG["PUSH_WINDOW"]["RECORD_RETENTION_DAYS"]
  300. current_time = get_beijing_time()
  301. for record_file in self.record_dir.glob("push_record_*.json"):
  302. try:
  303. date_str = record_file.stem.replace("push_record_", "")
  304. file_date = datetime.strptime(date_str, "%Y%m%d")
  305. file_date = pytz.timezone("Asia/Shanghai").localize(file_date)
  306. if (current_time - file_date).days > retention_days:
  307. record_file.unlink()
  308. print(f"清理过期推送记录: {record_file.name}")
  309. except Exception as e:
  310. print(f"清理记录文件失败 {record_file}: {e}")
  311. def has_pushed_today(self) -> bool:
  312. """检查今天是否已经推送过"""
  313. record_file = self.get_today_record_file()
  314. if not record_file.exists():
  315. return False
  316. try:
  317. with open(record_file, "r", encoding="utf-8") as f:
  318. record = json.load(f)
  319. return record.get("pushed", False)
  320. except Exception as e:
  321. print(f"读取推送记录失败: {e}")
  322. return False
  323. def record_push(self, report_type: str):
  324. """记录推送"""
  325. record_file = self.get_today_record_file()
  326. now = get_beijing_time()
  327. record = {
  328. "pushed": True,
  329. "push_time": now.strftime("%Y-%m-%d %H:%M:%S"),
  330. "report_type": report_type,
  331. }
  332. try:
  333. with open(record_file, "w", encoding="utf-8") as f:
  334. json.dump(record, f, ensure_ascii=False, indent=2)
  335. print(f"推送记录已保存: {report_type} at {now.strftime('%H:%M:%S')}")
  336. except Exception as e:
  337. print(f"保存推送记录失败: {e}")
  338. def is_in_time_range(self, start_time: str, end_time: str) -> bool:
  339. """检查当前时间是否在指定时间范围内"""
  340. now = get_beijing_time()
  341. current_time = now.strftime("%H:%M")
  342. def normalize_time(time_str: str) -> str:
  343. """将时间字符串标准化为 HH:MM 格式"""
  344. try:
  345. parts = time_str.strip().split(":")
  346. if len(parts) != 2:
  347. raise ValueError(f"时间格式错误: {time_str}")
  348. hour = int(parts[0])
  349. minute = int(parts[1])
  350. if not (0 <= hour <= 23 and 0 <= minute <= 59):
  351. raise ValueError(f"时间范围错误: {time_str}")
  352. return f"{hour:02d}:{minute:02d}"
  353. except Exception as e:
  354. print(f"时间格式化错误 '{time_str}': {e}")
  355. return time_str
  356. normalized_start = normalize_time(start_time)
  357. normalized_end = normalize_time(end_time)
  358. normalized_current = normalize_time(current_time)
  359. result = normalized_start <= normalized_current <= normalized_end
  360. if not result:
  361. print(f"时间窗口判断:当前 {normalized_current},窗口 {normalized_start}-{normalized_end}")
  362. return result
  363. # === 数据获取 ===
  364. class DataFetcher:
  365. """数据获取器"""
  366. def __init__(self, proxy_url: Optional[str] = None):
  367. self.proxy_url = proxy_url
  368. def fetch_data(
  369. self,
  370. id_info: Union[str, Tuple[str, str]],
  371. max_retries: int = 2,
  372. min_retry_wait: int = 3,
  373. max_retry_wait: int = 5,
  374. ) -> Tuple[Optional[str], str, str]:
  375. """获取指定ID数据,支持重试"""
  376. if isinstance(id_info, tuple):
  377. id_value, alias = id_info
  378. else:
  379. id_value = id_info
  380. alias = id_value
  381. url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
  382. proxies = None
  383. if self.proxy_url:
  384. proxies = {"http": self.proxy_url, "https": self.proxy_url}
  385. headers = {
  386. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
  387. "Accept": "application/json, text/plain, */*",
  388. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  389. "Connection": "keep-alive",
  390. "Cache-Control": "no-cache",
  391. }
  392. retries = 0
  393. while retries <= max_retries:
  394. try:
  395. response = requests.get(
  396. url, proxies=proxies, headers=headers, timeout=10
  397. )
  398. response.raise_for_status()
  399. data_text = response.text
  400. data_json = json.loads(data_text)
  401. status = data_json.get("status", "未知")
  402. if status not in ["success", "cache"]:
  403. raise ValueError(f"响应状态异常: {status}")
  404. status_info = "最新数据" if status == "success" else "缓存数据"
  405. print(f"获取 {id_value} 成功({status_info})")
  406. return data_text, id_value, alias
  407. except Exception as e:
  408. retries += 1
  409. if retries <= max_retries:
  410. base_wait = random.uniform(min_retry_wait, max_retry_wait)
  411. additional_wait = (retries - 1) * random.uniform(1, 2)
  412. wait_time = base_wait + additional_wait
  413. print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
  414. time.sleep(wait_time)
  415. else:
  416. print(f"请求 {id_value} 失败: {e}")
  417. return None, id_value, alias
  418. return None, id_value, alias
  419. def crawl_websites(
  420. self,
  421. ids_list: List[Union[str, Tuple[str, str]]],
  422. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  423. ) -> Tuple[Dict, Dict, List]:
  424. """爬取多个网站数据"""
  425. results = {}
  426. id_to_name = {}
  427. failed_ids = []
  428. for i, id_info in enumerate(ids_list):
  429. if isinstance(id_info, tuple):
  430. id_value, name = id_info
  431. else:
  432. id_value = id_info
  433. name = id_value
  434. id_to_name[id_value] = name
  435. response, _, _ = self.fetch_data(id_info)
  436. if response:
  437. try:
  438. data = json.loads(response)
  439. results[id_value] = {}
  440. for index, item in enumerate(data.get("items", []), 1):
  441. title = item["title"]
  442. url = item.get("url", "")
  443. mobile_url = item.get("mobileUrl", "")
  444. if title in results[id_value]:
  445. results[id_value][title]["ranks"].append(index)
  446. else:
  447. results[id_value][title] = {
  448. "ranks": [index],
  449. "url": url,
  450. "mobileUrl": mobile_url,
  451. }
  452. except json.JSONDecodeError:
  453. print(f"解析 {id_value} 响应失败")
  454. failed_ids.append(id_value)
  455. except Exception as e:
  456. print(f"处理 {id_value} 数据出错: {e}")
  457. failed_ids.append(id_value)
  458. else:
  459. failed_ids.append(id_value)
  460. if i < len(ids_list) - 1:
  461. actual_interval = request_interval + random.randint(-10, 20)
  462. actual_interval = max(50, actual_interval)
  463. time.sleep(actual_interval / 1000)
  464. print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
  465. return results, id_to_name, failed_ids
  466. # === 数据处理 ===
  467. def save_titles_to_file(results: Dict, id_to_name: Dict, failed_ids: List) -> str:
  468. """保存标题到文件"""
  469. file_path = get_output_path("txt", f"{format_time_filename()}.txt")
  470. with open(file_path, "w", encoding="utf-8") as f:
  471. for id_value, title_data in results.items():
  472. # id | name 或 id
  473. name = id_to_name.get(id_value)
  474. if name and name != id_value:
  475. f.write(f"{id_value} | {name}\n")
  476. else:
  477. f.write(f"{id_value}\n")
  478. # 按排名排序标题
  479. sorted_titles = []
  480. for title, info in title_data.items():
  481. cleaned_title = clean_title(title)
  482. if isinstance(info, dict):
  483. ranks = info.get("ranks", [])
  484. url = info.get("url", "")
  485. mobile_url = info.get("mobileUrl", "")
  486. else:
  487. ranks = info if isinstance(info, list) else []
  488. url = ""
  489. mobile_url = ""
  490. rank = ranks[0] if ranks else 1
  491. sorted_titles.append((rank, cleaned_title, url, mobile_url))
  492. sorted_titles.sort(key=lambda x: x[0])
  493. for rank, cleaned_title, url, mobile_url in sorted_titles:
  494. line = f"{rank}. {cleaned_title}"
  495. if url:
  496. line += f" [URL:{url}]"
  497. if mobile_url:
  498. line += f" [MOBILE:{mobile_url}]"
  499. f.write(line + "\n")
  500. f.write("\n")
  501. if failed_ids:
  502. f.write("==== 以下ID请求失败 ====\n")
  503. for id_value in failed_ids:
  504. f.write(f"{id_value}\n")
  505. return file_path
  506. def load_frequency_words(
  507. frequency_file: Optional[str] = None,
  508. ) -> Tuple[List[Dict], List[str]]:
  509. """加载频率词配置"""
  510. if frequency_file is None:
  511. frequency_file = os.environ.get(
  512. "FREQUENCY_WORDS_PATH", "config/frequency_words.txt"
  513. )
  514. frequency_path = Path(frequency_file)
  515. if not frequency_path.exists():
  516. raise FileNotFoundError(f"频率词文件 {frequency_file} 不存在")
  517. with open(frequency_path, "r", encoding="utf-8") as f:
  518. content = f.read()
  519. word_groups = [group.strip() for group in content.split("\n\n") if group.strip()]
  520. processed_groups = []
  521. filter_words = []
  522. for group in word_groups:
  523. words = [word.strip() for word in group.split("\n") if word.strip()]
  524. group_required_words = []
  525. group_normal_words = []
  526. group_filter_words = []
  527. for word in words:
  528. if word.startswith("!"):
  529. filter_words.append(word[1:])
  530. group_filter_words.append(word[1:])
  531. elif word.startswith("+"):
  532. group_required_words.append(word[1:])
  533. else:
  534. group_normal_words.append(word)
  535. if group_required_words or group_normal_words:
  536. if group_normal_words:
  537. group_key = " ".join(group_normal_words)
  538. else:
  539. group_key = " ".join(group_required_words)
  540. processed_groups.append(
  541. {
  542. "required": group_required_words,
  543. "normal": group_normal_words,
  544. "group_key": group_key,
  545. }
  546. )
  547. return processed_groups, filter_words
  548. def parse_file_titles(file_path: Path) -> Tuple[Dict, Dict]:
  549. """解析单个txt文件的标题数据,返回(titles_by_id, id_to_name)"""
  550. titles_by_id = {}
  551. id_to_name = {}
  552. with open(file_path, "r", encoding="utf-8") as f:
  553. content = f.read()
  554. sections = content.split("\n\n")
  555. for section in sections:
  556. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  557. continue
  558. lines = section.strip().split("\n")
  559. if len(lines) < 2:
  560. continue
  561. # id | name 或 id
  562. header_line = lines[0].strip()
  563. if " | " in header_line:
  564. parts = header_line.split(" | ", 1)
  565. source_id = parts[0].strip()
  566. name = parts[1].strip()
  567. id_to_name[source_id] = name
  568. else:
  569. source_id = header_line
  570. id_to_name[source_id] = source_id
  571. titles_by_id[source_id] = {}
  572. for line in lines[1:]:
  573. if line.strip():
  574. try:
  575. title_part = line.strip()
  576. rank = None
  577. # 提取排名
  578. if ". " in title_part and title_part.split(". ")[0].isdigit():
  579. rank_str, title_part = title_part.split(". ", 1)
  580. rank = int(rank_str)
  581. # 提取 MOBILE URL
  582. mobile_url = ""
  583. if " [MOBILE:" in title_part:
  584. title_part, mobile_part = title_part.rsplit(" [MOBILE:", 1)
  585. if mobile_part.endswith("]"):
  586. mobile_url = mobile_part[:-1]
  587. # 提取 URL
  588. url = ""
  589. if " [URL:" in title_part:
  590. title_part, url_part = title_part.rsplit(" [URL:", 1)
  591. if url_part.endswith("]"):
  592. url = url_part[:-1]
  593. title = clean_title(title_part.strip())
  594. ranks = [rank] if rank is not None else [1]
  595. titles_by_id[source_id][title] = {
  596. "ranks": ranks,
  597. "url": url,
  598. "mobileUrl": mobile_url,
  599. }
  600. except Exception as e:
  601. print(f"解析标题行出错: {line}, 错误: {e}")
  602. return titles_by_id, id_to_name
  603. def read_all_today_titles(
  604. current_platform_ids: Optional[List[str]] = None,
  605. ) -> Tuple[Dict, Dict, Dict]:
  606. """读取当天所有标题文件,支持按当前监控平台过滤"""
  607. date_folder = format_date_folder()
  608. txt_dir = Path("output") / date_folder / "txt"
  609. if not txt_dir.exists():
  610. return {}, {}, {}
  611. all_results = {}
  612. final_id_to_name = {}
  613. title_info = {}
  614. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  615. for file_path in files:
  616. time_info = file_path.stem
  617. titles_by_id, file_id_to_name = parse_file_titles(file_path)
  618. if current_platform_ids is not None:
  619. filtered_titles_by_id = {}
  620. filtered_id_to_name = {}
  621. for source_id, title_data in titles_by_id.items():
  622. if source_id in current_platform_ids:
  623. filtered_titles_by_id[source_id] = title_data
  624. if source_id in file_id_to_name:
  625. filtered_id_to_name[source_id] = file_id_to_name[source_id]
  626. titles_by_id = filtered_titles_by_id
  627. file_id_to_name = filtered_id_to_name
  628. final_id_to_name.update(file_id_to_name)
  629. for source_id, title_data in titles_by_id.items():
  630. process_source_data(
  631. source_id, title_data, time_info, all_results, title_info
  632. )
  633. return all_results, final_id_to_name, title_info
  634. def process_source_data(
  635. source_id: str,
  636. title_data: Dict,
  637. time_info: str,
  638. all_results: Dict,
  639. title_info: Dict,
  640. ) -> None:
  641. """处理来源数据,合并重复标题"""
  642. if source_id not in all_results:
  643. all_results[source_id] = title_data
  644. if source_id not in title_info:
  645. title_info[source_id] = {}
  646. for title, data in title_data.items():
  647. ranks = data.get("ranks", [])
  648. url = data.get("url", "")
  649. mobile_url = data.get("mobileUrl", "")
  650. title_info[source_id][title] = {
  651. "first_time": time_info,
  652. "last_time": time_info,
  653. "count": 1,
  654. "ranks": ranks,
  655. "url": url,
  656. "mobileUrl": mobile_url,
  657. }
  658. else:
  659. for title, data in title_data.items():
  660. ranks = data.get("ranks", [])
  661. url = data.get("url", "")
  662. mobile_url = data.get("mobileUrl", "")
  663. if title not in all_results[source_id]:
  664. all_results[source_id][title] = {
  665. "ranks": ranks,
  666. "url": url,
  667. "mobileUrl": mobile_url,
  668. }
  669. title_info[source_id][title] = {
  670. "first_time": time_info,
  671. "last_time": time_info,
  672. "count": 1,
  673. "ranks": ranks,
  674. "url": url,
  675. "mobileUrl": mobile_url,
  676. }
  677. else:
  678. existing_data = all_results[source_id][title]
  679. existing_ranks = existing_data.get("ranks", [])
  680. existing_url = existing_data.get("url", "")
  681. existing_mobile_url = existing_data.get("mobileUrl", "")
  682. merged_ranks = existing_ranks.copy()
  683. for rank in ranks:
  684. if rank not in merged_ranks:
  685. merged_ranks.append(rank)
  686. all_results[source_id][title] = {
  687. "ranks": merged_ranks,
  688. "url": existing_url or url,
  689. "mobileUrl": existing_mobile_url or mobile_url,
  690. }
  691. title_info[source_id][title]["last_time"] = time_info
  692. title_info[source_id][title]["ranks"] = merged_ranks
  693. title_info[source_id][title]["count"] += 1
  694. if not title_info[source_id][title].get("url"):
  695. title_info[source_id][title]["url"] = url
  696. if not title_info[source_id][title].get("mobileUrl"):
  697. title_info[source_id][title]["mobileUrl"] = mobile_url
  698. def detect_latest_new_titles(current_platform_ids: Optional[List[str]] = None) -> Dict:
  699. """检测当日最新批次的新增标题,支持按当前监控平台过滤"""
  700. date_folder = format_date_folder()
  701. txt_dir = Path("output") / date_folder / "txt"
  702. if not txt_dir.exists():
  703. return {}
  704. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  705. if len(files) < 2:
  706. return {}
  707. # 解析最新文件
  708. latest_file = files[-1]
  709. latest_titles, _ = parse_file_titles(latest_file)
  710. # 如果指定了当前平台列表,过滤最新文件数据
  711. if current_platform_ids is not None:
  712. filtered_latest_titles = {}
  713. for source_id, title_data in latest_titles.items():
  714. if source_id in current_platform_ids:
  715. filtered_latest_titles[source_id] = title_data
  716. latest_titles = filtered_latest_titles
  717. # 汇总历史标题(按平台过滤)
  718. historical_titles = {}
  719. for file_path in files[:-1]:
  720. historical_data, _ = parse_file_titles(file_path)
  721. # 过滤历史数据
  722. if current_platform_ids is not None:
  723. filtered_historical_data = {}
  724. for source_id, title_data in historical_data.items():
  725. if source_id in current_platform_ids:
  726. filtered_historical_data[source_id] = title_data
  727. historical_data = filtered_historical_data
  728. for source_id, titles_data in historical_data.items():
  729. if source_id not in historical_titles:
  730. historical_titles[source_id] = set()
  731. for title in titles_data.keys():
  732. historical_titles[source_id].add(title)
  733. # 找出新增标题
  734. new_titles = {}
  735. for source_id, latest_source_titles in latest_titles.items():
  736. historical_set = historical_titles.get(source_id, set())
  737. source_new_titles = {}
  738. for title, title_data in latest_source_titles.items():
  739. if title not in historical_set:
  740. source_new_titles[title] = title_data
  741. if source_new_titles:
  742. new_titles[source_id] = source_new_titles
  743. return new_titles
  744. # === 统计和分析 ===
  745. def calculate_news_weight(
  746. title_data: Dict, rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  747. ) -> float:
  748. """计算新闻权重,用于排序"""
  749. ranks = title_data.get("ranks", [])
  750. if not ranks:
  751. return 0.0
  752. count = title_data.get("count", len(ranks))
  753. weight_config = CONFIG["WEIGHT_CONFIG"]
  754. # 排名权重:Σ(11 - min(rank, 10)) / 出现次数
  755. rank_scores = []
  756. for rank in ranks:
  757. score = 11 - min(rank, 10)
  758. rank_scores.append(score)
  759. rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
  760. # 频次权重:min(出现次数, 10) × 10
  761. frequency_weight = min(count, 10) * 10
  762. # 热度加成:高排名次数 / 总出现次数 × 100
  763. high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
  764. hotness_ratio = high_rank_count / len(ranks) if ranks else 0
  765. hotness_weight = hotness_ratio * 100
  766. total_weight = (
  767. rank_weight * weight_config["RANK_WEIGHT"]
  768. + frequency_weight * weight_config["FREQUENCY_WEIGHT"]
  769. + hotness_weight * weight_config["HOTNESS_WEIGHT"]
  770. )
  771. return total_weight
  772. def matches_word_groups(
  773. title: str, word_groups: List[Dict], filter_words: List[str]
  774. ) -> bool:
  775. """检查标题是否匹配词组规则"""
  776. # 如果没有配置词组,则匹配所有标题(支持显示全部新闻)
  777. if not word_groups:
  778. return True
  779. title_lower = title.lower()
  780. # 过滤词检查
  781. if any(filter_word.lower() in title_lower for filter_word in filter_words):
  782. return False
  783. # 词组匹配检查
  784. for group in word_groups:
  785. required_words = group["required"]
  786. normal_words = group["normal"]
  787. # 必须词检查
  788. if required_words:
  789. all_required_present = all(
  790. req_word.lower() in title_lower for req_word in required_words
  791. )
  792. if not all_required_present:
  793. continue
  794. # 普通词检查
  795. if normal_words:
  796. any_normal_present = any(
  797. normal_word.lower() in title_lower for normal_word in normal_words
  798. )
  799. if not any_normal_present:
  800. continue
  801. return True
  802. return False
  803. def format_time_display(first_time: str, last_time: str) -> str:
  804. """格式化时间显示"""
  805. if not first_time:
  806. return ""
  807. if first_time == last_time or not last_time:
  808. return first_time
  809. else:
  810. return f"[{first_time} ~ {last_time}]"
  811. def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str) -> str:
  812. """统一的排名格式化方法"""
  813. if not ranks:
  814. return ""
  815. unique_ranks = sorted(set(ranks))
  816. min_rank = unique_ranks[0]
  817. max_rank = unique_ranks[-1]
  818. if format_type == "html":
  819. highlight_start = "<font color='red'><strong>"
  820. highlight_end = "</strong></font>"
  821. elif format_type == "feishu":
  822. highlight_start = "<font color='red'>**"
  823. highlight_end = "**</font>"
  824. elif format_type == "dingtalk":
  825. highlight_start = "**"
  826. highlight_end = "**"
  827. elif format_type == "wework":
  828. highlight_start = "**"
  829. highlight_end = "**"
  830. elif format_type == "telegram":
  831. highlight_start = "<b>"
  832. highlight_end = "</b>"
  833. else:
  834. highlight_start = "**"
  835. highlight_end = "**"
  836. if min_rank <= rank_threshold:
  837. if min_rank == max_rank:
  838. return f"{highlight_start}[{min_rank}]{highlight_end}"
  839. else:
  840. return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
  841. else:
  842. if min_rank == max_rank:
  843. return f"[{min_rank}]"
  844. else:
  845. return f"[{min_rank} - {max_rank}]"
  846. def count_word_frequency(
  847. results: Dict,
  848. word_groups: List[Dict],
  849. filter_words: List[str],
  850. id_to_name: Dict,
  851. title_info: Optional[Dict] = None,
  852. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  853. new_titles: Optional[Dict] = None,
  854. mode: str = "daily",
  855. ) -> Tuple[List[Dict], int]:
  856. """统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
  857. # 如果没有配置词组,创建一个包含所有新闻的虚拟词组
  858. if not word_groups:
  859. print("频率词配置为空,将显示所有新闻")
  860. word_groups = [{"required": [], "normal": [], "group_key": "全部新闻"}]
  861. filter_words = [] # 清空过滤词,显示所有新闻
  862. is_first_today = is_first_crawl_today()
  863. # 确定处理的数据源和新增标记逻辑
  864. if mode == "incremental":
  865. if is_first_today:
  866. # 增量模式 + 当天第一次:处理所有新闻,都标记为新增
  867. results_to_process = results
  868. all_news_are_new = True
  869. else:
  870. # 增量模式 + 当天非第一次:只处理新增的新闻
  871. results_to_process = new_titles if new_titles else {}
  872. all_news_are_new = True
  873. elif mode == "current":
  874. # current 模式:只处理当前时间批次的新闻,但统计信息来自全部历史
  875. if title_info:
  876. latest_time = None
  877. for source_titles in title_info.values():
  878. for title_data in source_titles.values():
  879. last_time = title_data.get("last_time", "")
  880. if last_time:
  881. if latest_time is None or last_time > latest_time:
  882. latest_time = last_time
  883. # 只处理 last_time 等于最新时间的新闻
  884. if latest_time:
  885. results_to_process = {}
  886. for source_id, source_titles in results.items():
  887. if source_id in title_info:
  888. filtered_titles = {}
  889. for title, title_data in source_titles.items():
  890. if title in title_info[source_id]:
  891. info = title_info[source_id][title]
  892. if info.get("last_time") == latest_time:
  893. filtered_titles[title] = title_data
  894. if filtered_titles:
  895. results_to_process[source_id] = filtered_titles
  896. print(
  897. f"当前榜单模式:最新时间 {latest_time},筛选出 {sum(len(titles) for titles in results_to_process.values())} 条当前榜单新闻"
  898. )
  899. else:
  900. results_to_process = results
  901. else:
  902. results_to_process = results
  903. all_news_are_new = False
  904. else:
  905. # 当日汇总模式:处理所有新闻
  906. results_to_process = results
  907. all_news_are_new = False
  908. total_input_news = sum(len(titles) for titles in results.values())
  909. filter_status = (
  910. "全部显示"
  911. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  912. else "频率词过滤"
  913. )
  914. print(f"当日汇总模式:处理 {total_input_news} 条新闻,模式:{filter_status}")
  915. word_stats = {}
  916. total_titles = 0
  917. processed_titles = {}
  918. matched_new_count = 0
  919. if title_info is None:
  920. title_info = {}
  921. if new_titles is None:
  922. new_titles = {}
  923. for group in word_groups:
  924. group_key = group["group_key"]
  925. word_stats[group_key] = {"count": 0, "titles": {}}
  926. for source_id, titles_data in results_to_process.items():
  927. total_titles += len(titles_data)
  928. if source_id not in processed_titles:
  929. processed_titles[source_id] = {}
  930. for title, title_data in titles_data.items():
  931. if title in processed_titles.get(source_id, {}):
  932. continue
  933. # 使用统一的匹配逻辑
  934. matches_frequency_words = matches_word_groups(
  935. title, word_groups, filter_words
  936. )
  937. if not matches_frequency_words:
  938. continue
  939. # 如果是增量模式或 current 模式第一次,统计匹配的新增新闻数量
  940. if (mode == "incremental" and all_news_are_new) or (
  941. mode == "current" and is_first_today
  942. ):
  943. matched_new_count += 1
  944. source_ranks = title_data.get("ranks", [])
  945. source_url = title_data.get("url", "")
  946. source_mobile_url = title_data.get("mobileUrl", "")
  947. # 找到匹配的词组
  948. title_lower = title.lower()
  949. for group in word_groups:
  950. required_words = group["required"]
  951. normal_words = group["normal"]
  952. # 如果是"全部新闻"模式,所有标题都匹配第一个(唯一的)词组
  953. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻":
  954. group_key = group["group_key"]
  955. word_stats[group_key]["count"] += 1
  956. if source_id not in word_stats[group_key]["titles"]:
  957. word_stats[group_key]["titles"][source_id] = []
  958. else:
  959. # 原有的匹配逻辑
  960. if required_words:
  961. all_required_present = all(
  962. req_word.lower() in title_lower
  963. for req_word in required_words
  964. )
  965. if not all_required_present:
  966. continue
  967. if normal_words:
  968. any_normal_present = any(
  969. normal_word.lower() in title_lower
  970. for normal_word in normal_words
  971. )
  972. if not any_normal_present:
  973. continue
  974. group_key = group["group_key"]
  975. word_stats[group_key]["count"] += 1
  976. if source_id not in word_stats[group_key]["titles"]:
  977. word_stats[group_key]["titles"][source_id] = []
  978. first_time = ""
  979. last_time = ""
  980. count_info = 1
  981. ranks = source_ranks if source_ranks else []
  982. url = source_url
  983. mobile_url = source_mobile_url
  984. # 对于 current 模式,从历史统计信息中获取完整数据
  985. if (
  986. mode == "current"
  987. and title_info
  988. and source_id in title_info
  989. and title in title_info[source_id]
  990. ):
  991. info = title_info[source_id][title]
  992. first_time = info.get("first_time", "")
  993. last_time = info.get("last_time", "")
  994. count_info = info.get("count", 1)
  995. if "ranks" in info and info["ranks"]:
  996. ranks = info["ranks"]
  997. url = info.get("url", source_url)
  998. mobile_url = info.get("mobileUrl", source_mobile_url)
  999. elif (
  1000. title_info
  1001. and source_id in title_info
  1002. and title in title_info[source_id]
  1003. ):
  1004. info = title_info[source_id][title]
  1005. first_time = info.get("first_time", "")
  1006. last_time = info.get("last_time", "")
  1007. count_info = info.get("count", 1)
  1008. if "ranks" in info and info["ranks"]:
  1009. ranks = info["ranks"]
  1010. url = info.get("url", source_url)
  1011. mobile_url = info.get("mobileUrl", source_mobile_url)
  1012. if not ranks:
  1013. ranks = [99]
  1014. time_display = format_time_display(first_time, last_time)
  1015. source_name = id_to_name.get(source_id, source_id)
  1016. # 判断是否为新增
  1017. is_new = False
  1018. if all_news_are_new:
  1019. # 增量模式下所有处理的新闻都是新增,或者当天第一次的所有新闻都是新增
  1020. is_new = True
  1021. elif new_titles and source_id in new_titles:
  1022. # 检查是否在新增列表中
  1023. new_titles_for_source = new_titles[source_id]
  1024. is_new = title in new_titles_for_source
  1025. word_stats[group_key]["titles"][source_id].append(
  1026. {
  1027. "title": title,
  1028. "source_name": source_name,
  1029. "first_time": first_time,
  1030. "last_time": last_time,
  1031. "time_display": time_display,
  1032. "count": count_info,
  1033. "ranks": ranks,
  1034. "rank_threshold": rank_threshold,
  1035. "url": url,
  1036. "mobileUrl": mobile_url,
  1037. "is_new": is_new,
  1038. }
  1039. )
  1040. if source_id not in processed_titles:
  1041. processed_titles[source_id] = {}
  1042. processed_titles[source_id][title] = True
  1043. break
  1044. # 最后统一打印汇总信息
  1045. if mode == "incremental":
  1046. if is_first_today:
  1047. total_input_news = sum(len(titles) for titles in results.values())
  1048. filter_status = (
  1049. "全部显示"
  1050. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  1051. else "频率词匹配"
  1052. )
  1053. print(
  1054. f"增量模式:当天第一次爬取,{total_input_news} 条新闻中有 {matched_new_count} 条{filter_status}"
  1055. )
  1056. else:
  1057. if new_titles:
  1058. total_new_count = sum(len(titles) for titles in new_titles.values())
  1059. filter_status = (
  1060. "全部显示"
  1061. if len(word_groups) == 1
  1062. and word_groups[0]["group_key"] == "全部新闻"
  1063. else "匹配频率词"
  1064. )
  1065. print(
  1066. f"增量模式:{total_new_count} 条新增新闻中,有 {matched_new_count} 条{filter_status}"
  1067. )
  1068. if matched_new_count == 0 and len(word_groups) > 1:
  1069. print("增量模式:没有新增新闻匹配频率词,将不会发送通知")
  1070. else:
  1071. print("增量模式:未检测到新增新闻")
  1072. elif mode == "current":
  1073. total_input_news = sum(len(titles) for titles in results_to_process.values())
  1074. if is_first_today:
  1075. filter_status = (
  1076. "全部显示"
  1077. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  1078. else "频率词匹配"
  1079. )
  1080. print(
  1081. f"当前榜单模式:当天第一次爬取,{total_input_news} 条当前榜单新闻中有 {matched_new_count} 条{filter_status}"
  1082. )
  1083. else:
  1084. matched_count = sum(stat["count"] for stat in word_stats.values())
  1085. filter_status = (
  1086. "全部显示"
  1087. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  1088. else "频率词匹配"
  1089. )
  1090. print(
  1091. f"当前榜单模式:{total_input_news} 条当前榜单新闻中有 {matched_count} 条{filter_status}"
  1092. )
  1093. stats = []
  1094. for group_key, data in word_stats.items():
  1095. all_titles = []
  1096. for source_id, title_list in data["titles"].items():
  1097. all_titles.extend(title_list)
  1098. # 按权重排序
  1099. sorted_titles = sorted(
  1100. all_titles,
  1101. key=lambda x: (
  1102. -calculate_news_weight(x, rank_threshold),
  1103. min(x["ranks"]) if x["ranks"] else 999,
  1104. -x["count"],
  1105. ),
  1106. )
  1107. stats.append(
  1108. {
  1109. "word": group_key,
  1110. "count": data["count"],
  1111. "titles": sorted_titles,
  1112. "percentage": (
  1113. round(data["count"] / total_titles * 100, 2)
  1114. if total_titles > 0
  1115. else 0
  1116. ),
  1117. }
  1118. )
  1119. stats.sort(key=lambda x: x["count"], reverse=True)
  1120. return stats, total_titles
  1121. # === 报告生成 ===
  1122. def prepare_report_data(
  1123. stats: List[Dict],
  1124. failed_ids: Optional[List] = None,
  1125. new_titles: Optional[Dict] = None,
  1126. id_to_name: Optional[Dict] = None,
  1127. mode: str = "daily",
  1128. ) -> Dict:
  1129. """准备报告数据"""
  1130. processed_new_titles = []
  1131. # 在增量模式下隐藏新增新闻区域
  1132. hide_new_section = mode == "incremental"
  1133. # 只有在非隐藏模式下才处理新增新闻部分
  1134. if not hide_new_section:
  1135. filtered_new_titles = {}
  1136. if new_titles and id_to_name:
  1137. word_groups, filter_words = load_frequency_words()
  1138. for source_id, titles_data in new_titles.items():
  1139. filtered_titles = {}
  1140. for title, title_data in titles_data.items():
  1141. if matches_word_groups(title, word_groups, filter_words):
  1142. filtered_titles[title] = title_data
  1143. if filtered_titles:
  1144. filtered_new_titles[source_id] = filtered_titles
  1145. if filtered_new_titles and id_to_name:
  1146. for source_id, titles_data in filtered_new_titles.items():
  1147. source_name = id_to_name.get(source_id, source_id)
  1148. source_titles = []
  1149. for title, title_data in titles_data.items():
  1150. url = title_data.get("url", "")
  1151. mobile_url = title_data.get("mobileUrl", "")
  1152. ranks = title_data.get("ranks", [])
  1153. processed_title = {
  1154. "title": title,
  1155. "source_name": source_name,
  1156. "time_display": "",
  1157. "count": 1,
  1158. "ranks": ranks,
  1159. "rank_threshold": CONFIG["RANK_THRESHOLD"],
  1160. "url": url,
  1161. "mobile_url": mobile_url,
  1162. "is_new": True,
  1163. }
  1164. source_titles.append(processed_title)
  1165. if source_titles:
  1166. processed_new_titles.append(
  1167. {
  1168. "source_id": source_id,
  1169. "source_name": source_name,
  1170. "titles": source_titles,
  1171. }
  1172. )
  1173. processed_stats = []
  1174. for stat in stats:
  1175. if stat["count"] <= 0:
  1176. continue
  1177. processed_titles = []
  1178. for title_data in stat["titles"]:
  1179. processed_title = {
  1180. "title": title_data["title"],
  1181. "source_name": title_data["source_name"],
  1182. "time_display": title_data["time_display"],
  1183. "count": title_data["count"],
  1184. "ranks": title_data["ranks"],
  1185. "rank_threshold": title_data["rank_threshold"],
  1186. "url": title_data.get("url", ""),
  1187. "mobile_url": title_data.get("mobileUrl", ""),
  1188. "is_new": title_data.get("is_new", False),
  1189. }
  1190. processed_titles.append(processed_title)
  1191. processed_stats.append(
  1192. {
  1193. "word": stat["word"],
  1194. "count": stat["count"],
  1195. "percentage": stat.get("percentage", 0),
  1196. "titles": processed_titles,
  1197. }
  1198. )
  1199. return {
  1200. "stats": processed_stats,
  1201. "new_titles": processed_new_titles,
  1202. "failed_ids": failed_ids or [],
  1203. "total_new_count": sum(
  1204. len(source["titles"]) for source in processed_new_titles
  1205. ),
  1206. }
  1207. def format_title_for_platform(
  1208. platform: str, title_data: Dict, show_source: bool = True
  1209. ) -> str:
  1210. """统一的标题格式化方法"""
  1211. rank_display = format_rank_display(
  1212. title_data["ranks"], title_data["rank_threshold"], platform
  1213. )
  1214. link_url = title_data["mobile_url"] or title_data["url"]
  1215. cleaned_title = clean_title(title_data["title"])
  1216. if platform == "feishu":
  1217. if link_url:
  1218. formatted_title = f"[{cleaned_title}]({link_url})"
  1219. else:
  1220. formatted_title = cleaned_title
  1221. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1222. if show_source:
  1223. result = f"<font color='grey'>[{title_data['source_name']}]</font> {title_prefix}{formatted_title}"
  1224. else:
  1225. result = f"{title_prefix}{formatted_title}"
  1226. if rank_display:
  1227. result += f" {rank_display}"
  1228. if title_data["time_display"]:
  1229. result += f" <font color='grey'>- {title_data['time_display']}</font>"
  1230. if title_data["count"] > 1:
  1231. result += f" <font color='green'>({title_data['count']}次)</font>"
  1232. return result
  1233. elif platform == "dingtalk":
  1234. if link_url:
  1235. formatted_title = f"[{cleaned_title}]({link_url})"
  1236. else:
  1237. formatted_title = cleaned_title
  1238. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1239. if show_source:
  1240. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1241. else:
  1242. result = f"{title_prefix}{formatted_title}"
  1243. if rank_display:
  1244. result += f" {rank_display}"
  1245. if title_data["time_display"]:
  1246. result += f" - {title_data['time_display']}"
  1247. if title_data["count"] > 1:
  1248. result += f" ({title_data['count']}次)"
  1249. return result
  1250. elif platform == "wework":
  1251. if link_url:
  1252. formatted_title = f"[{cleaned_title}]({link_url})"
  1253. else:
  1254. formatted_title = cleaned_title
  1255. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1256. if show_source:
  1257. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1258. else:
  1259. result = f"{title_prefix}{formatted_title}"
  1260. if rank_display:
  1261. result += f" {rank_display}"
  1262. if title_data["time_display"]:
  1263. result += f" - {title_data['time_display']}"
  1264. if title_data["count"] > 1:
  1265. result += f" ({title_data['count']}次)"
  1266. return result
  1267. elif platform == "telegram":
  1268. if link_url:
  1269. formatted_title = f'<a href="{link_url}">{html_escape(cleaned_title)}</a>'
  1270. else:
  1271. formatted_title = cleaned_title
  1272. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1273. if show_source:
  1274. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1275. else:
  1276. result = f"{title_prefix}{formatted_title}"
  1277. if rank_display:
  1278. result += f" {rank_display}"
  1279. if title_data["time_display"]:
  1280. result += f" <code>- {title_data['time_display']}</code>"
  1281. if title_data["count"] > 1:
  1282. result += f" <code>({title_data['count']}次)</code>"
  1283. return result
  1284. elif platform == "ntfy":
  1285. if link_url:
  1286. formatted_title = f"[{cleaned_title}]({link_url})"
  1287. else:
  1288. formatted_title = cleaned_title
  1289. title_prefix = "🆕 " if title_data.get("is_new") else ""
  1290. if show_source:
  1291. result = f"[{title_data['source_name']}] {title_prefix}{formatted_title}"
  1292. else:
  1293. result = f"{title_prefix}{formatted_title}"
  1294. if rank_display:
  1295. result += f" {rank_display}"
  1296. if title_data["time_display"]:
  1297. result += f" `- {title_data['time_display']}`"
  1298. if title_data["count"] > 1:
  1299. result += f" `({title_data['count']}次)`"
  1300. return result
  1301. elif platform == "html":
  1302. rank_display = format_rank_display(
  1303. title_data["ranks"], title_data["rank_threshold"], "html"
  1304. )
  1305. link_url = title_data["mobile_url"] or title_data["url"]
  1306. escaped_title = html_escape(cleaned_title)
  1307. escaped_source_name = html_escape(title_data["source_name"])
  1308. if link_url:
  1309. escaped_url = html_escape(link_url)
  1310. formatted_title = f'[{escaped_source_name}] <a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  1311. else:
  1312. formatted_title = (
  1313. f'[{escaped_source_name}] <span class="no-link">{escaped_title}</span>'
  1314. )
  1315. if rank_display:
  1316. formatted_title += f" {rank_display}"
  1317. if title_data["time_display"]:
  1318. escaped_time = html_escape(title_data["time_display"])
  1319. formatted_title += f" <font color='grey'>- {escaped_time}</font>"
  1320. if title_data["count"] > 1:
  1321. formatted_title += f" <font color='green'>({title_data['count']}次)</font>"
  1322. if title_data.get("is_new"):
  1323. formatted_title = f"<div class='new-title'>🆕 {formatted_title}</div>"
  1324. return formatted_title
  1325. else:
  1326. return cleaned_title
  1327. def generate_html_report(
  1328. stats: List[Dict],
  1329. total_titles: int,
  1330. failed_ids: Optional[List] = None,
  1331. new_titles: Optional[Dict] = None,
  1332. id_to_name: Optional[Dict] = None,
  1333. mode: str = "daily",
  1334. is_daily_summary: bool = False,
  1335. update_info: Optional[Dict] = None,
  1336. ) -> str:
  1337. """生成HTML报告"""
  1338. if is_daily_summary:
  1339. if mode == "current":
  1340. filename = "当前榜单汇总.html"
  1341. elif mode == "incremental":
  1342. filename = "当日增量.html"
  1343. else:
  1344. filename = "当日汇总.html"
  1345. else:
  1346. filename = f"{format_time_filename()}.html"
  1347. file_path = get_output_path("html", filename)
  1348. report_data = prepare_report_data(stats, failed_ids, new_titles, id_to_name, mode)
  1349. html_content = render_html_content(
  1350. report_data, total_titles, is_daily_summary, mode, update_info
  1351. )
  1352. with open(file_path, "w", encoding="utf-8") as f:
  1353. f.write(html_content)
  1354. if is_daily_summary:
  1355. root_file_path = Path("index.html")
  1356. with open(root_file_path, "w", encoding="utf-8") as f:
  1357. f.write(html_content)
  1358. return file_path
  1359. def render_html_content(
  1360. report_data: Dict,
  1361. total_titles: int,
  1362. is_daily_summary: bool = False,
  1363. mode: str = "daily",
  1364. update_info: Optional[Dict] = None,
  1365. ) -> str:
  1366. """渲染HTML内容"""
  1367. html = """
  1368. <!DOCTYPE html>
  1369. <html>
  1370. <head>
  1371. <meta charset="UTF-8">
  1372. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1373. <title>热点新闻分析</title>
  1374. <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  1375. <style>
  1376. * { box-sizing: border-box; }
  1377. body {
  1378. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
  1379. margin: 0;
  1380. padding: 16px;
  1381. background: #fafafa;
  1382. color: #333;
  1383. line-height: 1.5;
  1384. }
  1385. .container {
  1386. max-width: 600px;
  1387. margin: 0 auto;
  1388. background: white;
  1389. border-radius: 12px;
  1390. overflow: hidden;
  1391. box-shadow: 0 2px 16px rgba(0,0,0,0.06);
  1392. }
  1393. .header {
  1394. background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  1395. color: white;
  1396. padding: 32px 24px;
  1397. text-align: center;
  1398. position: relative;
  1399. }
  1400. .save-buttons {
  1401. position: absolute;
  1402. top: 16px;
  1403. right: 16px;
  1404. display: flex;
  1405. gap: 8px;
  1406. }
  1407. .save-btn {
  1408. background: rgba(255, 255, 255, 0.2);
  1409. border: 1px solid rgba(255, 255, 255, 0.3);
  1410. color: white;
  1411. padding: 8px 16px;
  1412. border-radius: 6px;
  1413. cursor: pointer;
  1414. font-size: 13px;
  1415. font-weight: 500;
  1416. transition: all 0.2s ease;
  1417. backdrop-filter: blur(10px);
  1418. white-space: nowrap;
  1419. }
  1420. .save-btn:hover {
  1421. background: rgba(255, 255, 255, 0.3);
  1422. border-color: rgba(255, 255, 255, 0.5);
  1423. transform: translateY(-1px);
  1424. }
  1425. .save-btn:active {
  1426. transform: translateY(0);
  1427. }
  1428. .save-btn:disabled {
  1429. opacity: 0.6;
  1430. cursor: not-allowed;
  1431. }
  1432. .header-title {
  1433. font-size: 22px;
  1434. font-weight: 700;
  1435. margin: 0 0 20px 0;
  1436. }
  1437. .header-info {
  1438. display: grid;
  1439. grid-template-columns: 1fr 1fr;
  1440. gap: 16px;
  1441. font-size: 14px;
  1442. opacity: 0.95;
  1443. }
  1444. .info-item {
  1445. text-align: center;
  1446. }
  1447. .info-label {
  1448. display: block;
  1449. font-size: 12px;
  1450. opacity: 0.8;
  1451. margin-bottom: 4px;
  1452. }
  1453. .info-value {
  1454. font-weight: 600;
  1455. font-size: 16px;
  1456. }
  1457. .content {
  1458. padding: 24px;
  1459. }
  1460. .word-group {
  1461. margin-bottom: 40px;
  1462. }
  1463. .word-group:first-child {
  1464. margin-top: 0;
  1465. }
  1466. .word-header {
  1467. display: flex;
  1468. align-items: center;
  1469. justify-content: space-between;
  1470. margin-bottom: 20px;
  1471. padding-bottom: 8px;
  1472. border-bottom: 1px solid #f0f0f0;
  1473. }
  1474. .word-info {
  1475. display: flex;
  1476. align-items: center;
  1477. gap: 12px;
  1478. }
  1479. .word-name {
  1480. font-size: 17px;
  1481. font-weight: 600;
  1482. color: #1a1a1a;
  1483. }
  1484. .word-count {
  1485. color: #666;
  1486. font-size: 13px;
  1487. font-weight: 500;
  1488. }
  1489. .word-count.hot { color: #dc2626; font-weight: 600; }
  1490. .word-count.warm { color: #ea580c; font-weight: 600; }
  1491. .word-index {
  1492. color: #999;
  1493. font-size: 12px;
  1494. }
  1495. .news-item {
  1496. margin-bottom: 20px;
  1497. padding: 16px 0;
  1498. border-bottom: 1px solid #f5f5f5;
  1499. position: relative;
  1500. display: flex;
  1501. gap: 12px;
  1502. align-items: center;
  1503. }
  1504. .news-item:last-child {
  1505. border-bottom: none;
  1506. }
  1507. .news-item.new::after {
  1508. content: "NEW";
  1509. position: absolute;
  1510. top: 12px;
  1511. right: 0;
  1512. background: #fbbf24;
  1513. color: #92400e;
  1514. font-size: 9px;
  1515. font-weight: 700;
  1516. padding: 3px 6px;
  1517. border-radius: 4px;
  1518. letter-spacing: 0.5px;
  1519. }
  1520. .news-number {
  1521. color: #999;
  1522. font-size: 13px;
  1523. font-weight: 600;
  1524. min-width: 20px;
  1525. text-align: center;
  1526. flex-shrink: 0;
  1527. background: #f8f9fa;
  1528. border-radius: 50%;
  1529. width: 24px;
  1530. height: 24px;
  1531. display: flex;
  1532. align-items: center;
  1533. justify-content: center;
  1534. align-self: flex-start;
  1535. margin-top: 8px;
  1536. }
  1537. .news-content {
  1538. flex: 1;
  1539. min-width: 0;
  1540. padding-right: 40px;
  1541. }
  1542. .news-item.new .news-content {
  1543. padding-right: 50px;
  1544. }
  1545. .news-header {
  1546. display: flex;
  1547. align-items: center;
  1548. gap: 8px;
  1549. margin-bottom: 8px;
  1550. flex-wrap: wrap;
  1551. }
  1552. .source-name {
  1553. color: #666;
  1554. font-size: 12px;
  1555. font-weight: 500;
  1556. }
  1557. .rank-num {
  1558. color: #fff;
  1559. background: #6b7280;
  1560. font-size: 10px;
  1561. font-weight: 700;
  1562. padding: 2px 6px;
  1563. border-radius: 10px;
  1564. min-width: 18px;
  1565. text-align: center;
  1566. }
  1567. .rank-num.top { background: #dc2626; }
  1568. .rank-num.high { background: #ea580c; }
  1569. .time-info {
  1570. color: #999;
  1571. font-size: 11px;
  1572. }
  1573. .count-info {
  1574. color: #059669;
  1575. font-size: 11px;
  1576. font-weight: 500;
  1577. }
  1578. .news-title {
  1579. font-size: 15px;
  1580. line-height: 1.4;
  1581. color: #1a1a1a;
  1582. margin: 0;
  1583. }
  1584. .news-link {
  1585. color: #2563eb;
  1586. text-decoration: none;
  1587. }
  1588. .news-link:hover {
  1589. text-decoration: underline;
  1590. }
  1591. .news-link:visited {
  1592. color: #7c3aed;
  1593. }
  1594. .new-section {
  1595. margin-top: 40px;
  1596. padding-top: 24px;
  1597. border-top: 2px solid #f0f0f0;
  1598. }
  1599. .new-section-title {
  1600. color: #1a1a1a;
  1601. font-size: 16px;
  1602. font-weight: 600;
  1603. margin: 0 0 20px 0;
  1604. }
  1605. .new-source-group {
  1606. margin-bottom: 24px;
  1607. }
  1608. .new-source-title {
  1609. color: #666;
  1610. font-size: 13px;
  1611. font-weight: 500;
  1612. margin: 0 0 12px 0;
  1613. padding-bottom: 6px;
  1614. border-bottom: 1px solid #f5f5f5;
  1615. }
  1616. .new-item {
  1617. display: flex;
  1618. align-items: center;
  1619. gap: 12px;
  1620. padding: 8px 0;
  1621. border-bottom: 1px solid #f9f9f9;
  1622. }
  1623. .new-item:last-child {
  1624. border-bottom: none;
  1625. }
  1626. .new-item-number {
  1627. color: #999;
  1628. font-size: 12px;
  1629. font-weight: 600;
  1630. min-width: 18px;
  1631. text-align: center;
  1632. flex-shrink: 0;
  1633. background: #f8f9fa;
  1634. border-radius: 50%;
  1635. width: 20px;
  1636. height: 20px;
  1637. display: flex;
  1638. align-items: center;
  1639. justify-content: center;
  1640. }
  1641. .new-item-rank {
  1642. color: #fff;
  1643. background: #6b7280;
  1644. font-size: 10px;
  1645. font-weight: 700;
  1646. padding: 3px 6px;
  1647. border-radius: 8px;
  1648. min-width: 20px;
  1649. text-align: center;
  1650. flex-shrink: 0;
  1651. }
  1652. .new-item-rank.top { background: #dc2626; }
  1653. .new-item-rank.high { background: #ea580c; }
  1654. .new-item-content {
  1655. flex: 1;
  1656. min-width: 0;
  1657. }
  1658. .new-item-title {
  1659. font-size: 14px;
  1660. line-height: 1.4;
  1661. color: #1a1a1a;
  1662. margin: 0;
  1663. }
  1664. .error-section {
  1665. background: #fef2f2;
  1666. border: 1px solid #fecaca;
  1667. border-radius: 8px;
  1668. padding: 16px;
  1669. margin-bottom: 24px;
  1670. }
  1671. .error-title {
  1672. color: #dc2626;
  1673. font-size: 14px;
  1674. font-weight: 600;
  1675. margin: 0 0 8px 0;
  1676. }
  1677. .error-list {
  1678. list-style: none;
  1679. padding: 0;
  1680. margin: 0;
  1681. }
  1682. .error-item {
  1683. color: #991b1b;
  1684. font-size: 13px;
  1685. padding: 2px 0;
  1686. font-family: 'SF Mono', Consolas, monospace;
  1687. }
  1688. .footer {
  1689. margin-top: 32px;
  1690. padding: 20px 24px;
  1691. background: #f8f9fa;
  1692. border-top: 1px solid #e5e7eb;
  1693. text-align: center;
  1694. }
  1695. .footer-content {
  1696. font-size: 13px;
  1697. color: #6b7280;
  1698. line-height: 1.6;
  1699. }
  1700. .footer-link {
  1701. color: #4f46e5;
  1702. text-decoration: none;
  1703. font-weight: 500;
  1704. transition: color 0.2s ease;
  1705. }
  1706. .footer-link:hover {
  1707. color: #7c3aed;
  1708. text-decoration: underline;
  1709. }
  1710. .project-name {
  1711. font-weight: 600;
  1712. color: #374151;
  1713. }
  1714. @media (max-width: 480px) {
  1715. body { padding: 12px; }
  1716. .header { padding: 24px 20px; }
  1717. .content { padding: 20px; }
  1718. .footer { padding: 16px 20px; }
  1719. .header-info { grid-template-columns: 1fr; gap: 12px; }
  1720. .news-header { gap: 6px; }
  1721. .news-content { padding-right: 45px; }
  1722. .news-item { gap: 8px; }
  1723. .new-item { gap: 8px; }
  1724. .news-number { width: 20px; height: 20px; font-size: 12px; }
  1725. .save-buttons {
  1726. position: static;
  1727. margin-bottom: 16px;
  1728. display: flex;
  1729. gap: 8px;
  1730. justify-content: center;
  1731. flex-direction: column;
  1732. width: 100%;
  1733. }
  1734. .save-btn {
  1735. width: 100%;
  1736. }
  1737. }
  1738. </style>
  1739. </head>
  1740. <body>
  1741. <div class="container">
  1742. <div class="header">
  1743. <div class="save-buttons">
  1744. <button class="save-btn" onclick="saveAsImage()">保存为图片</button>
  1745. <button class="save-btn" onclick="saveAsMultipleImages()">分段保存</button>
  1746. </div>
  1747. <div class="header-title">热点新闻分析</div>
  1748. <div class="header-info">
  1749. <div class="info-item">
  1750. <span class="info-label">报告类型</span>
  1751. <span class="info-value">"""
  1752. # 处理报告类型显示
  1753. if is_daily_summary:
  1754. if mode == "current":
  1755. html += "当前榜单"
  1756. elif mode == "incremental":
  1757. html += "增量模式"
  1758. else:
  1759. html += "当日汇总"
  1760. else:
  1761. html += "实时分析"
  1762. html += """</span>
  1763. </div>
  1764. <div class="info-item">
  1765. <span class="info-label">新闻总数</span>
  1766. <span class="info-value">"""
  1767. html += f"{total_titles} 条"
  1768. # 计算筛选后的热点新闻数量
  1769. hot_news_count = sum(len(stat["titles"]) for stat in report_data["stats"])
  1770. html += """</span>
  1771. </div>
  1772. <div class="info-item">
  1773. <span class="info-label">热点新闻</span>
  1774. <span class="info-value">"""
  1775. html += f"{hot_news_count} 条"
  1776. html += """</span>
  1777. </div>
  1778. <div class="info-item">
  1779. <span class="info-label">生成时间</span>
  1780. <span class="info-value">"""
  1781. now = get_beijing_time()
  1782. html += now.strftime("%m-%d %H:%M")
  1783. html += """</span>
  1784. </div>
  1785. </div>
  1786. </div>
  1787. <div class="content">"""
  1788. # 处理失败ID错误信息
  1789. if report_data["failed_ids"]:
  1790. html += """
  1791. <div class="error-section">
  1792. <div class="error-title">⚠️ 请求失败的平台</div>
  1793. <ul class="error-list">"""
  1794. for id_value in report_data["failed_ids"]:
  1795. html += f'<li class="error-item">{html_escape(id_value)}</li>'
  1796. html += """
  1797. </ul>
  1798. </div>"""
  1799. # 处理主要统计数据
  1800. if report_data["stats"]:
  1801. total_count = len(report_data["stats"])
  1802. for i, stat in enumerate(report_data["stats"], 1):
  1803. count = stat["count"]
  1804. # 确定热度等级
  1805. if count >= 10:
  1806. count_class = "hot"
  1807. elif count >= 5:
  1808. count_class = "warm"
  1809. else:
  1810. count_class = ""
  1811. escaped_word = html_escape(stat["word"])
  1812. html += f"""
  1813. <div class="word-group">
  1814. <div class="word-header">
  1815. <div class="word-info">
  1816. <div class="word-name">{escaped_word}</div>
  1817. <div class="word-count {count_class}">{count} 条</div>
  1818. </div>
  1819. <div class="word-index">{i}/{total_count}</div>
  1820. </div>"""
  1821. # 处理每个词组下的新闻标题,给每条新闻标上序号
  1822. for j, title_data in enumerate(stat["titles"], 1):
  1823. is_new = title_data.get("is_new", False)
  1824. new_class = "new" if is_new else ""
  1825. html += f"""
  1826. <div class="news-item {new_class}">
  1827. <div class="news-number">{j}</div>
  1828. <div class="news-content">
  1829. <div class="news-header">
  1830. <span class="source-name">{html_escape(title_data["source_name"])}</span>"""
  1831. # 处理排名显示
  1832. ranks = title_data.get("ranks", [])
  1833. if ranks:
  1834. min_rank = min(ranks)
  1835. max_rank = max(ranks)
  1836. rank_threshold = title_data.get("rank_threshold", 10)
  1837. # 确定排名等级
  1838. if min_rank <= 3:
  1839. rank_class = "top"
  1840. elif min_rank <= rank_threshold:
  1841. rank_class = "high"
  1842. else:
  1843. rank_class = ""
  1844. if min_rank == max_rank:
  1845. rank_text = str(min_rank)
  1846. else:
  1847. rank_text = f"{min_rank}-{max_rank}"
  1848. html += f'<span class="rank-num {rank_class}">{rank_text}</span>'
  1849. # 处理时间显示
  1850. time_display = title_data.get("time_display", "")
  1851. if time_display:
  1852. # 简化时间显示格式,将波浪线替换为~
  1853. simplified_time = (
  1854. time_display.replace(" ~ ", "~")
  1855. .replace("[", "")
  1856. .replace("]", "")
  1857. )
  1858. html += (
  1859. f'<span class="time-info">{html_escape(simplified_time)}</span>'
  1860. )
  1861. # 处理出现次数
  1862. count_info = title_data.get("count", 1)
  1863. if count_info > 1:
  1864. html += f'<span class="count-info">{count_info}次</span>'
  1865. html += """
  1866. </div>
  1867. <div class="news-title">"""
  1868. # 处理标题和链接
  1869. escaped_title = html_escape(title_data["title"])
  1870. link_url = title_data.get("mobile_url") or title_data.get("url", "")
  1871. if link_url:
  1872. escaped_url = html_escape(link_url)
  1873. html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  1874. else:
  1875. html += escaped_title
  1876. html += """
  1877. </div>
  1878. </div>
  1879. </div>"""
  1880. html += """
  1881. </div>"""
  1882. # 处理新增新闻区域
  1883. if report_data["new_titles"]:
  1884. html += f"""
  1885. <div class="new-section">
  1886. <div class="new-section-title">本次新增热点 (共 {report_data['total_new_count']} 条)</div>"""
  1887. for source_data in report_data["new_titles"]:
  1888. escaped_source = html_escape(source_data["source_name"])
  1889. titles_count = len(source_data["titles"])
  1890. html += f"""
  1891. <div class="new-source-group">
  1892. <div class="new-source-title">{escaped_source} · {titles_count}条</div>"""
  1893. # 为新增新闻也添加序号
  1894. for idx, title_data in enumerate(source_data["titles"], 1):
  1895. ranks = title_data.get("ranks", [])
  1896. # 处理新增新闻的排名显示
  1897. rank_class = ""
  1898. if ranks:
  1899. min_rank = min(ranks)
  1900. if min_rank <= 3:
  1901. rank_class = "top"
  1902. elif min_rank <= title_data.get("rank_threshold", 10):
  1903. rank_class = "high"
  1904. if len(ranks) == 1:
  1905. rank_text = str(ranks[0])
  1906. else:
  1907. rank_text = f"{min(ranks)}-{max(ranks)}"
  1908. else:
  1909. rank_text = "?"
  1910. html += f"""
  1911. <div class="new-item">
  1912. <div class="new-item-number">{idx}</div>
  1913. <div class="new-item-rank {rank_class}">{rank_text}</div>
  1914. <div class="new-item-content">
  1915. <div class="new-item-title">"""
  1916. # 处理新增新闻的链接
  1917. escaped_title = html_escape(title_data["title"])
  1918. link_url = title_data.get("mobile_url") or title_data.get("url", "")
  1919. if link_url:
  1920. escaped_url = html_escape(link_url)
  1921. html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  1922. else:
  1923. html += escaped_title
  1924. html += """
  1925. </div>
  1926. </div>
  1927. </div>"""
  1928. html += """
  1929. </div>"""
  1930. html += """
  1931. </div>"""
  1932. html += """
  1933. </div>
  1934. <div class="footer">
  1935. <div class="footer-content">
  1936. 由 <span class="project-name">TrendRadar</span> 生成 ·
  1937. <a href="https://github.com/sansan0/TrendRadar" target="_blank" class="footer-link">
  1938. GitHub 开源项目
  1939. </a>"""
  1940. if update_info:
  1941. html += f"""
  1942. <br>
  1943. <span style="color: #ea580c; font-weight: 500;">
  1944. 发现新版本 {update_info['remote_version']},当前版本 {update_info['current_version']}
  1945. </span>"""
  1946. html += """
  1947. </div>
  1948. </div>
  1949. </div>
  1950. <script>
  1951. async function saveAsImage() {
  1952. const button = event.target;
  1953. const originalText = button.textContent;
  1954. try {
  1955. button.textContent = '生成中...';
  1956. button.disabled = true;
  1957. window.scrollTo(0, 0);
  1958. // 等待页面稳定
  1959. await new Promise(resolve => setTimeout(resolve, 200));
  1960. // 截图前隐藏按钮
  1961. const buttons = document.querySelector('.save-buttons');
  1962. buttons.style.visibility = 'hidden';
  1963. // 再次等待确保按钮完全隐藏
  1964. await new Promise(resolve => setTimeout(resolve, 100));
  1965. const container = document.querySelector('.container');
  1966. const canvas = await html2canvas(container, {
  1967. backgroundColor: '#ffffff',
  1968. scale: 1.5,
  1969. useCORS: true,
  1970. allowTaint: false,
  1971. imageTimeout: 10000,
  1972. removeContainer: false,
  1973. foreignObjectRendering: false,
  1974. logging: false,
  1975. width: container.offsetWidth,
  1976. height: container.offsetHeight,
  1977. x: 0,
  1978. y: 0,
  1979. scrollX: 0,
  1980. scrollY: 0,
  1981. windowWidth: window.innerWidth,
  1982. windowHeight: window.innerHeight
  1983. });
  1984. buttons.style.visibility = 'visible';
  1985. const link = document.createElement('a');
  1986. const now = new Date();
  1987. const filename = `TrendRadar_热点新闻分析_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}.png`;
  1988. link.download = filename;
  1989. link.href = canvas.toDataURL('image/png', 1.0);
  1990. // 触发下载
  1991. document.body.appendChild(link);
  1992. link.click();
  1993. document.body.removeChild(link);
  1994. button.textContent = '保存成功!';
  1995. setTimeout(() => {
  1996. button.textContent = originalText;
  1997. button.disabled = false;
  1998. }, 2000);
  1999. } catch (error) {
  2000. const buttons = document.querySelector('.save-buttons');
  2001. buttons.style.visibility = 'visible';
  2002. button.textContent = '保存失败';
  2003. setTimeout(() => {
  2004. button.textContent = originalText;
  2005. button.disabled = false;
  2006. }, 2000);
  2007. }
  2008. }
  2009. async function saveAsMultipleImages() {
  2010. const button = event.target;
  2011. const originalText = button.textContent;
  2012. const container = document.querySelector('.container');
  2013. const scale = 1.5;
  2014. const maxHeight = 5000 / scale;
  2015. try {
  2016. button.textContent = '分析中...';
  2017. button.disabled = true;
  2018. // 获取所有可能的分割元素
  2019. const newsItems = Array.from(container.querySelectorAll('.news-item'));
  2020. const wordGroups = Array.from(container.querySelectorAll('.word-group'));
  2021. const newSection = container.querySelector('.new-section');
  2022. const errorSection = container.querySelector('.error-section');
  2023. const header = container.querySelector('.header');
  2024. const footer = container.querySelector('.footer');
  2025. // 计算元素位置和高度
  2026. const containerRect = container.getBoundingClientRect();
  2027. const elements = [];
  2028. // 添加header作为必须包含的元素
  2029. elements.push({
  2030. type: 'header',
  2031. element: header,
  2032. top: 0,
  2033. bottom: header.offsetHeight,
  2034. height: header.offsetHeight
  2035. });
  2036. // 添加错误信息(如果存在)
  2037. if (errorSection) {
  2038. const rect = errorSection.getBoundingClientRect();
  2039. elements.push({
  2040. type: 'error',
  2041. element: errorSection,
  2042. top: rect.top - containerRect.top,
  2043. bottom: rect.bottom - containerRect.top,
  2044. height: rect.height
  2045. });
  2046. }
  2047. // 按word-group分组处理news-item
  2048. wordGroups.forEach(group => {
  2049. const groupRect = group.getBoundingClientRect();
  2050. const groupNewsItems = group.querySelectorAll('.news-item');
  2051. // 添加word-group的header部分
  2052. const wordHeader = group.querySelector('.word-header');
  2053. if (wordHeader) {
  2054. const headerRect = wordHeader.getBoundingClientRect();
  2055. elements.push({
  2056. type: 'word-header',
  2057. element: wordHeader,
  2058. parent: group,
  2059. top: groupRect.top - containerRect.top,
  2060. bottom: headerRect.bottom - containerRect.top,
  2061. height: headerRect.height
  2062. });
  2063. }
  2064. // 添加每个news-item
  2065. groupNewsItems.forEach(item => {
  2066. const rect = item.getBoundingClientRect();
  2067. elements.push({
  2068. type: 'news-item',
  2069. element: item,
  2070. parent: group,
  2071. top: rect.top - containerRect.top,
  2072. bottom: rect.bottom - containerRect.top,
  2073. height: rect.height
  2074. });
  2075. });
  2076. });
  2077. // 添加新增新闻部分
  2078. if (newSection) {
  2079. const rect = newSection.getBoundingClientRect();
  2080. elements.push({
  2081. type: 'new-section',
  2082. element: newSection,
  2083. top: rect.top - containerRect.top,
  2084. bottom: rect.bottom - containerRect.top,
  2085. height: rect.height
  2086. });
  2087. }
  2088. // 添加footer
  2089. const footerRect = footer.getBoundingClientRect();
  2090. elements.push({
  2091. type: 'footer',
  2092. element: footer,
  2093. top: footerRect.top - containerRect.top,
  2094. bottom: footerRect.bottom - containerRect.top,
  2095. height: footer.offsetHeight
  2096. });
  2097. // 计算分割点
  2098. const segments = [];
  2099. let currentSegment = { start: 0, end: 0, height: 0, includeHeader: true };
  2100. let headerHeight = header.offsetHeight;
  2101. currentSegment.height = headerHeight;
  2102. for (let i = 1; i < elements.length; i++) {
  2103. const element = elements[i];
  2104. const potentialHeight = element.bottom - currentSegment.start;
  2105. // 检查是否需要创建新分段
  2106. if (potentialHeight > maxHeight && currentSegment.height > headerHeight) {
  2107. // 在前一个元素结束处分割
  2108. currentSegment.end = elements[i - 1].bottom;
  2109. segments.push(currentSegment);
  2110. // 开始新分段
  2111. currentSegment = {
  2112. start: currentSegment.end,
  2113. end: 0,
  2114. height: element.bottom - currentSegment.end,
  2115. includeHeader: false
  2116. };
  2117. } else {
  2118. currentSegment.height = potentialHeight;
  2119. currentSegment.end = element.bottom;
  2120. }
  2121. }
  2122. // 添加最后一个分段
  2123. if (currentSegment.height > 0) {
  2124. currentSegment.end = container.offsetHeight;
  2125. segments.push(currentSegment);
  2126. }
  2127. button.textContent = `生成中 (0/${segments.length})...`;
  2128. // 隐藏保存按钮
  2129. const buttons = document.querySelector('.save-buttons');
  2130. buttons.style.visibility = 'hidden';
  2131. // 为每个分段生成图片
  2132. const images = [];
  2133. for (let i = 0; i < segments.length; i++) {
  2134. const segment = segments[i];
  2135. button.textContent = `生成中 (${i + 1}/${segments.length})...`;
  2136. // 创建临时容器用于截图
  2137. const tempContainer = document.createElement('div');
  2138. tempContainer.style.cssText = `
  2139. position: absolute;
  2140. left: -9999px;
  2141. top: 0;
  2142. width: ${container.offsetWidth}px;
  2143. background: white;
  2144. `;
  2145. tempContainer.className = 'container';
  2146. // 克隆容器内容
  2147. const clonedContainer = container.cloneNode(true);
  2148. // 移除克隆内容中的保存按钮
  2149. const clonedButtons = clonedContainer.querySelector('.save-buttons');
  2150. if (clonedButtons) {
  2151. clonedButtons.style.display = 'none';
  2152. }
  2153. tempContainer.appendChild(clonedContainer);
  2154. document.body.appendChild(tempContainer);
  2155. // 等待DOM更新
  2156. await new Promise(resolve => setTimeout(resolve, 100));
  2157. // 使用html2canvas截取特定区域
  2158. const canvas = await html2canvas(clonedContainer, {
  2159. backgroundColor: '#ffffff',
  2160. scale: scale,
  2161. useCORS: true,
  2162. allowTaint: false,
  2163. imageTimeout: 10000,
  2164. logging: false,
  2165. width: container.offsetWidth,
  2166. height: segment.end - segment.start,
  2167. x: 0,
  2168. y: segment.start,
  2169. windowWidth: window.innerWidth,
  2170. windowHeight: window.innerHeight
  2171. });
  2172. images.push(canvas.toDataURL('image/png', 1.0));
  2173. // 清理临时容器
  2174. document.body.removeChild(tempContainer);
  2175. }
  2176. // 恢复按钮显示
  2177. buttons.style.visibility = 'visible';
  2178. // 下载所有图片
  2179. const now = new Date();
  2180. const baseFilename = `TrendRadar_热点新闻分析_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
  2181. for (let i = 0; i < images.length; i++) {
  2182. const link = document.createElement('a');
  2183. link.download = `${baseFilename}_part${i + 1}.png`;
  2184. link.href = images[i];
  2185. document.body.appendChild(link);
  2186. link.click();
  2187. document.body.removeChild(link);
  2188. // 延迟一下避免浏览器阻止多个下载
  2189. await new Promise(resolve => setTimeout(resolve, 100));
  2190. }
  2191. button.textContent = `已保存 ${segments.length} 张图片!`;
  2192. setTimeout(() => {
  2193. button.textContent = originalText;
  2194. button.disabled = false;
  2195. }, 2000);
  2196. } catch (error) {
  2197. console.error('分段保存失败:', error);
  2198. const buttons = document.querySelector('.save-buttons');
  2199. buttons.style.visibility = 'visible';
  2200. button.textContent = '保存失败';
  2201. setTimeout(() => {
  2202. button.textContent = originalText;
  2203. button.disabled = false;
  2204. }, 2000);
  2205. }
  2206. }
  2207. document.addEventListener('DOMContentLoaded', function() {
  2208. window.scrollTo(0, 0);
  2209. });
  2210. </script>
  2211. </body>
  2212. </html>
  2213. """
  2214. return html
  2215. def render_feishu_content(
  2216. report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily"
  2217. ) -> str:
  2218. """渲染飞书内容"""
  2219. text_content = ""
  2220. if report_data["stats"]:
  2221. text_content += f"📊 **热点词汇统计**\n\n"
  2222. total_count = len(report_data["stats"])
  2223. for i, stat in enumerate(report_data["stats"]):
  2224. word = stat["word"]
  2225. count = stat["count"]
  2226. sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>"
  2227. if count >= 10:
  2228. text_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n"
  2229. elif count >= 5:
  2230. text_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n"
  2231. else:
  2232. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2233. for j, title_data in enumerate(stat["titles"], 1):
  2234. formatted_title = format_title_for_platform(
  2235. "feishu", title_data, show_source=True
  2236. )
  2237. text_content += f" {j}. {formatted_title}\n"
  2238. if j < len(stat["titles"]):
  2239. text_content += "\n"
  2240. if i < len(report_data["stats"]) - 1:
  2241. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2242. if not text_content:
  2243. if mode == "incremental":
  2244. mode_text = "增量模式下暂无新增匹配的热点词汇"
  2245. elif mode == "current":
  2246. mode_text = "当前榜单模式下暂无匹配的热点词汇"
  2247. else:
  2248. mode_text = "暂无匹配的热点词汇"
  2249. text_content = f"📭 {mode_text}\n\n"
  2250. if report_data["new_titles"]:
  2251. if text_content and "暂无匹配" not in text_content:
  2252. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2253. text_content += (
  2254. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2255. )
  2256. for source_data in report_data["new_titles"]:
  2257. text_content += (
  2258. f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n"
  2259. )
  2260. for j, title_data in enumerate(source_data["titles"], 1):
  2261. title_data_copy = title_data.copy()
  2262. title_data_copy["is_new"] = False
  2263. formatted_title = format_title_for_platform(
  2264. "feishu", title_data_copy, show_source=False
  2265. )
  2266. text_content += f" {j}. {formatted_title}\n"
  2267. text_content += "\n"
  2268. if report_data["failed_ids"]:
  2269. if text_content and "暂无匹配" not in text_content:
  2270. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2271. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  2272. for i, id_value in enumerate(report_data["failed_ids"], 1):
  2273. text_content += f" • <font color='red'>{id_value}</font>\n"
  2274. now = get_beijing_time()
  2275. text_content += (
  2276. f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  2277. )
  2278. if update_info:
  2279. text_content += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  2280. return text_content
  2281. def render_dingtalk_content(
  2282. report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily"
  2283. ) -> str:
  2284. """渲染钉钉内容"""
  2285. text_content = ""
  2286. total_titles = sum(
  2287. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  2288. )
  2289. now = get_beijing_time()
  2290. text_content += f"**总新闻数:** {total_titles}\n\n"
  2291. text_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  2292. text_content += f"**类型:** 热点分析报告\n\n"
  2293. text_content += "---\n\n"
  2294. if report_data["stats"]:
  2295. text_content += f"📊 **热点词汇统计**\n\n"
  2296. total_count = len(report_data["stats"])
  2297. for i, stat in enumerate(report_data["stats"]):
  2298. word = stat["word"]
  2299. count = stat["count"]
  2300. sequence_display = f"[{i + 1}/{total_count}]"
  2301. if count >= 10:
  2302. text_content += f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2303. elif count >= 5:
  2304. text_content += f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2305. else:
  2306. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2307. for j, title_data in enumerate(stat["titles"], 1):
  2308. formatted_title = format_title_for_platform(
  2309. "dingtalk", title_data, show_source=True
  2310. )
  2311. text_content += f" {j}. {formatted_title}\n"
  2312. if j < len(stat["titles"]):
  2313. text_content += "\n"
  2314. if i < len(report_data["stats"]) - 1:
  2315. text_content += f"\n---\n\n"
  2316. if not report_data["stats"]:
  2317. if mode == "incremental":
  2318. mode_text = "增量模式下暂无新增匹配的热点词汇"
  2319. elif mode == "current":
  2320. mode_text = "当前榜单模式下暂无匹配的热点词汇"
  2321. else:
  2322. mode_text = "暂无匹配的热点词汇"
  2323. text_content += f"📭 {mode_text}\n\n"
  2324. if report_data["new_titles"]:
  2325. if text_content and "暂无匹配" not in text_content:
  2326. text_content += f"\n---\n\n"
  2327. text_content += (
  2328. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2329. )
  2330. for source_data in report_data["new_titles"]:
  2331. text_content += f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2332. for j, title_data in enumerate(source_data["titles"], 1):
  2333. title_data_copy = title_data.copy()
  2334. title_data_copy["is_new"] = False
  2335. formatted_title = format_title_for_platform(
  2336. "dingtalk", title_data_copy, show_source=False
  2337. )
  2338. text_content += f" {j}. {formatted_title}\n"
  2339. text_content += "\n"
  2340. if report_data["failed_ids"]:
  2341. if text_content and "暂无匹配" not in text_content:
  2342. text_content += f"\n---\n\n"
  2343. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  2344. for i, id_value in enumerate(report_data["failed_ids"], 1):
  2345. text_content += f" • **{id_value}**\n"
  2346. text_content += f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2347. if update_info:
  2348. text_content += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2349. return text_content
  2350. def split_content_into_batches(
  2351. report_data: Dict,
  2352. format_type: str,
  2353. update_info: Optional[Dict] = None,
  2354. max_bytes: int = None,
  2355. mode: str = "daily",
  2356. ) -> List[str]:
  2357. """分批处理消息内容,确保词组标题+至少第一条新闻的完整性"""
  2358. if max_bytes is None:
  2359. if format_type == "dingtalk":
  2360. max_bytes = CONFIG.get("DINGTALK_BATCH_SIZE", 20000)
  2361. elif format_type == "feishu":
  2362. max_bytes = CONFIG.get("FEISHU_BATCH_SIZE", 29000)
  2363. elif format_type == "ntfy":
  2364. max_bytes = 3800
  2365. else:
  2366. max_bytes = CONFIG.get("MESSAGE_BATCH_SIZE", 4000)
  2367. batches = []
  2368. total_titles = sum(
  2369. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  2370. )
  2371. now = get_beijing_time()
  2372. base_header = ""
  2373. if format_type == "wework":
  2374. base_header = f"**总新闻数:** {total_titles}\n\n\n\n"
  2375. elif format_type == "telegram":
  2376. base_header = f"总新闻数: {total_titles}\n\n"
  2377. elif format_type == "ntfy":
  2378. base_header = f"**总新闻数:** {total_titles}\n\n"
  2379. elif format_type == "feishu":
  2380. base_header = ""
  2381. elif format_type == "dingtalk":
  2382. base_header = f"**总新闻数:** {total_titles}\n\n"
  2383. base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  2384. base_header += f"**类型:** 热点分析报告\n\n"
  2385. base_header += "---\n\n"
  2386. base_footer = ""
  2387. if format_type == "wework":
  2388. base_footer = f"\n\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2389. if update_info:
  2390. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2391. elif format_type == "telegram":
  2392. base_footer = f"\n\n更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2393. if update_info:
  2394. base_footer += f"\nTrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}"
  2395. elif format_type == "ntfy":
  2396. base_footer = f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2397. if update_info:
  2398. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2399. elif format_type == "feishu":
  2400. base_footer = f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  2401. if update_info:
  2402. base_footer += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  2403. elif format_type == "dingtalk":
  2404. base_footer = f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  2405. if update_info:
  2406. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  2407. stats_header = ""
  2408. if report_data["stats"]:
  2409. if format_type == "wework":
  2410. stats_header = f"📊 **热点词汇统计**\n\n"
  2411. elif format_type == "telegram":
  2412. stats_header = f"📊 热点词汇统计\n\n"
  2413. elif format_type == "ntfy":
  2414. stats_header = f"📊 **热点词汇统计**\n\n"
  2415. elif format_type == "feishu":
  2416. stats_header = f"📊 **热点词汇统计**\n\n"
  2417. elif format_type == "dingtalk":
  2418. stats_header = f"📊 **热点词汇统计**\n\n"
  2419. current_batch = base_header
  2420. current_batch_has_content = False
  2421. if (
  2422. not report_data["stats"]
  2423. and not report_data["new_titles"]
  2424. and not report_data["failed_ids"]
  2425. ):
  2426. if mode == "incremental":
  2427. mode_text = "增量模式下暂无新增匹配的热点词汇"
  2428. elif mode == "current":
  2429. mode_text = "当前榜单模式下暂无匹配的热点词汇"
  2430. else:
  2431. mode_text = "暂无匹配的热点词汇"
  2432. simple_content = f"📭 {mode_text}\n\n"
  2433. final_content = base_header + simple_content + base_footer
  2434. batches.append(final_content)
  2435. return batches
  2436. # 处理热点词汇统计
  2437. if report_data["stats"]:
  2438. total_count = len(report_data["stats"])
  2439. # 添加统计标题
  2440. test_content = current_batch + stats_header
  2441. if (
  2442. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2443. < max_bytes
  2444. ):
  2445. current_batch = test_content
  2446. current_batch_has_content = True
  2447. else:
  2448. if current_batch_has_content:
  2449. batches.append(current_batch + base_footer)
  2450. current_batch = base_header + stats_header
  2451. current_batch_has_content = True
  2452. # 逐个处理词组(确保词组标题+第一条新闻的原子性)
  2453. for i, stat in enumerate(report_data["stats"]):
  2454. word = stat["word"]
  2455. count = stat["count"]
  2456. sequence_display = f"[{i + 1}/{total_count}]"
  2457. # 构建词组标题
  2458. word_header = ""
  2459. if format_type == "wework":
  2460. if count >= 10:
  2461. word_header = (
  2462. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2463. )
  2464. elif count >= 5:
  2465. word_header = (
  2466. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2467. )
  2468. else:
  2469. word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2470. elif format_type == "telegram":
  2471. if count >= 10:
  2472. word_header = f"🔥 {sequence_display} {word} : {count} 条\n\n"
  2473. elif count >= 5:
  2474. word_header = f"📈 {sequence_display} {word} : {count} 条\n\n"
  2475. else:
  2476. word_header = f"📌 {sequence_display} {word} : {count} 条\n\n"
  2477. elif format_type == "ntfy":
  2478. if count >= 10:
  2479. word_header = (
  2480. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2481. )
  2482. elif count >= 5:
  2483. word_header = (
  2484. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2485. )
  2486. else:
  2487. word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2488. elif format_type == "feishu":
  2489. if count >= 10:
  2490. word_header = f"🔥 <font color='grey'>{sequence_display}</font> **{word}** : <font color='red'>{count}</font> 条\n\n"
  2491. elif count >= 5:
  2492. word_header = f"📈 <font color='grey'>{sequence_display}</font> **{word}** : <font color='orange'>{count}</font> 条\n\n"
  2493. else:
  2494. word_header = f"📌 <font color='grey'>{sequence_display}</font> **{word}** : {count} 条\n\n"
  2495. elif format_type == "dingtalk":
  2496. if count >= 10:
  2497. word_header = (
  2498. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  2499. )
  2500. elif count >= 5:
  2501. word_header = (
  2502. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  2503. )
  2504. else:
  2505. word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  2506. # 构建第一条新闻
  2507. first_news_line = ""
  2508. if stat["titles"]:
  2509. first_title_data = stat["titles"][0]
  2510. if format_type == "wework":
  2511. formatted_title = format_title_for_platform(
  2512. "wework", first_title_data, show_source=True
  2513. )
  2514. elif format_type == "telegram":
  2515. formatted_title = format_title_for_platform(
  2516. "telegram", first_title_data, show_source=True
  2517. )
  2518. elif format_type == "ntfy":
  2519. formatted_title = format_title_for_platform(
  2520. "ntfy", first_title_data, show_source=True
  2521. )
  2522. elif format_type == "feishu":
  2523. formatted_title = format_title_for_platform(
  2524. "feishu", first_title_data, show_source=True
  2525. )
  2526. elif format_type == "dingtalk":
  2527. formatted_title = format_title_for_platform(
  2528. "dingtalk", first_title_data, show_source=True
  2529. )
  2530. else:
  2531. formatted_title = f"{first_title_data['title']}"
  2532. first_news_line = f" 1. {formatted_title}\n"
  2533. if len(stat["titles"]) > 1:
  2534. first_news_line += "\n"
  2535. # 原子性检查:词组标题+第一条新闻必须一起处理
  2536. word_with_first_news = word_header + first_news_line
  2537. test_content = current_batch + word_with_first_news
  2538. if (
  2539. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2540. >= max_bytes
  2541. ):
  2542. # 当前批次容纳不下,开启新批次
  2543. if current_batch_has_content:
  2544. batches.append(current_batch + base_footer)
  2545. current_batch = base_header + stats_header + word_with_first_news
  2546. current_batch_has_content = True
  2547. start_index = 1
  2548. else:
  2549. current_batch = test_content
  2550. current_batch_has_content = True
  2551. start_index = 1
  2552. # 处理剩余新闻条目
  2553. for j in range(start_index, len(stat["titles"])):
  2554. title_data = stat["titles"][j]
  2555. if format_type == "wework":
  2556. formatted_title = format_title_for_platform(
  2557. "wework", title_data, show_source=True
  2558. )
  2559. elif format_type == "telegram":
  2560. formatted_title = format_title_for_platform(
  2561. "telegram", title_data, show_source=True
  2562. )
  2563. elif format_type == "ntfy":
  2564. formatted_title = format_title_for_platform(
  2565. "ntfy", title_data, show_source=True
  2566. )
  2567. elif format_type == "feishu":
  2568. formatted_title = format_title_for_platform(
  2569. "feishu", title_data, show_source=True
  2570. )
  2571. elif format_type == "dingtalk":
  2572. formatted_title = format_title_for_platform(
  2573. "dingtalk", title_data, show_source=True
  2574. )
  2575. else:
  2576. formatted_title = f"{title_data['title']}"
  2577. news_line = f" {j + 1}. {formatted_title}\n"
  2578. if j < len(stat["titles"]) - 1:
  2579. news_line += "\n"
  2580. test_content = current_batch + news_line
  2581. if (
  2582. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2583. >= max_bytes
  2584. ):
  2585. if current_batch_has_content:
  2586. batches.append(current_batch + base_footer)
  2587. current_batch = base_header + stats_header + word_header + news_line
  2588. current_batch_has_content = True
  2589. else:
  2590. current_batch = test_content
  2591. current_batch_has_content = True
  2592. # 词组间分隔符
  2593. if i < len(report_data["stats"]) - 1:
  2594. separator = ""
  2595. if format_type == "wework":
  2596. separator = f"\n\n\n\n"
  2597. elif format_type == "telegram":
  2598. separator = f"\n\n"
  2599. elif format_type == "ntfy":
  2600. separator = f"\n\n"
  2601. elif format_type == "feishu":
  2602. separator = f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  2603. elif format_type == "dingtalk":
  2604. separator = f"\n---\n\n"
  2605. test_content = current_batch + separator
  2606. if (
  2607. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2608. < max_bytes
  2609. ):
  2610. current_batch = test_content
  2611. # 处理新增新闻(同样确保来源标题+第一条新闻的原子性)
  2612. if report_data["new_titles"]:
  2613. new_header = ""
  2614. if format_type == "wework":
  2615. new_header = f"\n\n\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2616. elif format_type == "telegram":
  2617. new_header = (
  2618. f"\n\n🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)\n\n"
  2619. )
  2620. elif format_type == "ntfy":
  2621. new_header = f"\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2622. elif format_type == "feishu":
  2623. new_header = f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2624. elif format_type == "dingtalk":
  2625. new_header = f"\n---\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  2626. test_content = current_batch + new_header
  2627. if (
  2628. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2629. >= max_bytes
  2630. ):
  2631. if current_batch_has_content:
  2632. batches.append(current_batch + base_footer)
  2633. current_batch = base_header + new_header
  2634. current_batch_has_content = True
  2635. else:
  2636. current_batch = test_content
  2637. current_batch_has_content = True
  2638. # 逐个处理新增新闻来源
  2639. for source_data in report_data["new_titles"]:
  2640. source_header = ""
  2641. if format_type == "wework":
  2642. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2643. elif format_type == "telegram":
  2644. source_header = f"{source_data['source_name']} ({len(source_data['titles'])} 条):\n\n"
  2645. elif format_type == "ntfy":
  2646. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2647. elif format_type == "feishu":
  2648. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2649. elif format_type == "dingtalk":
  2650. source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n"
  2651. # 构建第一条新增新闻
  2652. first_news_line = ""
  2653. if source_data["titles"]:
  2654. first_title_data = source_data["titles"][0]
  2655. title_data_copy = first_title_data.copy()
  2656. title_data_copy["is_new"] = False
  2657. if format_type == "wework":
  2658. formatted_title = format_title_for_platform(
  2659. "wework", title_data_copy, show_source=False
  2660. )
  2661. elif format_type == "telegram":
  2662. formatted_title = format_title_for_platform(
  2663. "telegram", title_data_copy, show_source=False
  2664. )
  2665. elif format_type == "feishu":
  2666. formatted_title = format_title_for_platform(
  2667. "feishu", title_data_copy, show_source=False
  2668. )
  2669. elif format_type == "dingtalk":
  2670. formatted_title = format_title_for_platform(
  2671. "dingtalk", title_data_copy, show_source=False
  2672. )
  2673. else:
  2674. formatted_title = f"{title_data_copy['title']}"
  2675. first_news_line = f" 1. {formatted_title}\n"
  2676. # 原子性检查:来源标题+第一条新闻
  2677. source_with_first_news = source_header + first_news_line
  2678. test_content = current_batch + source_with_first_news
  2679. if (
  2680. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2681. >= max_bytes
  2682. ):
  2683. if current_batch_has_content:
  2684. batches.append(current_batch + base_footer)
  2685. current_batch = base_header + new_header + source_with_first_news
  2686. current_batch_has_content = True
  2687. start_index = 1
  2688. else:
  2689. current_batch = test_content
  2690. current_batch_has_content = True
  2691. start_index = 1
  2692. # 处理剩余新增新闻
  2693. for j in range(start_index, len(source_data["titles"])):
  2694. title_data = source_data["titles"][j]
  2695. title_data_copy = title_data.copy()
  2696. title_data_copy["is_new"] = False
  2697. if format_type == "wework":
  2698. formatted_title = format_title_for_platform(
  2699. "wework", title_data_copy, show_source=False
  2700. )
  2701. elif format_type == "telegram":
  2702. formatted_title = format_title_for_platform(
  2703. "telegram", title_data_copy, show_source=False
  2704. )
  2705. elif format_type == "feishu":
  2706. formatted_title = format_title_for_platform(
  2707. "feishu", title_data_copy, show_source=False
  2708. )
  2709. elif format_type == "dingtalk":
  2710. formatted_title = format_title_for_platform(
  2711. "dingtalk", title_data_copy, show_source=False
  2712. )
  2713. else:
  2714. formatted_title = f"{title_data_copy['title']}"
  2715. news_line = f" {j + 1}. {formatted_title}\n"
  2716. test_content = current_batch + news_line
  2717. if (
  2718. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2719. >= max_bytes
  2720. ):
  2721. if current_batch_has_content:
  2722. batches.append(current_batch + base_footer)
  2723. current_batch = base_header + new_header + source_header + news_line
  2724. current_batch_has_content = True
  2725. else:
  2726. current_batch = test_content
  2727. current_batch_has_content = True
  2728. current_batch += "\n"
  2729. if report_data["failed_ids"]:
  2730. failed_header = ""
  2731. if format_type == "wework":
  2732. failed_header = f"\n\n\n\n⚠️ **数据获取失败的平台:**\n\n"
  2733. elif format_type == "telegram":
  2734. failed_header = f"\n\n⚠️ 数据获取失败的平台:\n\n"
  2735. elif format_type == "ntfy":
  2736. failed_header = f"\n\n⚠️ **数据获取失败的平台:**\n\n"
  2737. elif format_type == "feishu":
  2738. failed_header = f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n⚠️ **数据获取失败的平台:**\n\n"
  2739. elif format_type == "dingtalk":
  2740. failed_header = f"\n---\n\n⚠️ **数据获取失败的平台:**\n\n"
  2741. test_content = current_batch + failed_header
  2742. if (
  2743. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2744. >= max_bytes
  2745. ):
  2746. if current_batch_has_content:
  2747. batches.append(current_batch + base_footer)
  2748. current_batch = base_header + failed_header
  2749. current_batch_has_content = True
  2750. else:
  2751. current_batch = test_content
  2752. current_batch_has_content = True
  2753. for i, id_value in enumerate(report_data["failed_ids"], 1):
  2754. if format_type == "feishu":
  2755. failed_line = f" • <font color='red'>{id_value}</font>\n"
  2756. elif format_type == "dingtalk":
  2757. failed_line = f" • **{id_value}**\n"
  2758. else:
  2759. failed_line = f" • {id_value}\n"
  2760. test_content = current_batch + failed_line
  2761. if (
  2762. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  2763. >= max_bytes
  2764. ):
  2765. if current_batch_has_content:
  2766. batches.append(current_batch + base_footer)
  2767. current_batch = base_header + failed_header + failed_line
  2768. current_batch_has_content = True
  2769. else:
  2770. current_batch = test_content
  2771. current_batch_has_content = True
  2772. # 完成最后批次
  2773. if current_batch_has_content:
  2774. batches.append(current_batch + base_footer)
  2775. return batches
  2776. def send_to_notifications(
  2777. stats: List[Dict],
  2778. failed_ids: Optional[List] = None,
  2779. report_type: str = "当日汇总",
  2780. new_titles: Optional[Dict] = None,
  2781. id_to_name: Optional[Dict] = None,
  2782. update_info: Optional[Dict] = None,
  2783. proxy_url: Optional[str] = None,
  2784. mode: str = "daily",
  2785. html_file_path: Optional[str] = None,
  2786. ) -> Dict[str, bool]:
  2787. """发送数据到多个通知平台"""
  2788. results = {}
  2789. if CONFIG["PUSH_WINDOW"]["ENABLED"]:
  2790. push_manager = PushRecordManager()
  2791. time_range_start = CONFIG["PUSH_WINDOW"]["TIME_RANGE"]["START"]
  2792. time_range_end = CONFIG["PUSH_WINDOW"]["TIME_RANGE"]["END"]
  2793. if not push_manager.is_in_time_range(time_range_start, time_range_end):
  2794. now = get_beijing_time()
  2795. print(
  2796. f"推送窗口控制:当前时间 {now.strftime('%H:%M')} 不在推送时间窗口 {time_range_start}-{time_range_end} 内,跳过推送"
  2797. )
  2798. return results
  2799. if CONFIG["PUSH_WINDOW"]["ONCE_PER_DAY"]:
  2800. if push_manager.has_pushed_today():
  2801. print(f"推送窗口控制:今天已推送过,跳过本次推送")
  2802. return results
  2803. else:
  2804. print(f"推送窗口控制:今天首次推送")
  2805. report_data = prepare_report_data(stats, failed_ids, new_titles, id_to_name, mode)
  2806. feishu_url = CONFIG["FEISHU_WEBHOOK_URL"]
  2807. dingtalk_url = CONFIG["DINGTALK_WEBHOOK_URL"]
  2808. wework_url = CONFIG["WEWORK_WEBHOOK_URL"]
  2809. telegram_token = CONFIG["TELEGRAM_BOT_TOKEN"]
  2810. telegram_chat_id = CONFIG["TELEGRAM_CHAT_ID"]
  2811. email_from = CONFIG["EMAIL_FROM"]
  2812. email_password = CONFIG["EMAIL_PASSWORD"]
  2813. email_to = CONFIG["EMAIL_TO"]
  2814. email_smtp_server = CONFIG.get("EMAIL_SMTP_SERVER", "")
  2815. email_smtp_port = CONFIG.get("EMAIL_SMTP_PORT", "")
  2816. ntfy_server_url = CONFIG["NTFY_SERVER_URL"]
  2817. ntfy_topic = CONFIG["NTFY_TOPIC"]
  2818. ntfy_token = CONFIG.get("NTFY_TOKEN", "")
  2819. update_info_to_send = update_info if CONFIG["SHOW_VERSION_UPDATE"] else None
  2820. # 发送到飞书
  2821. if feishu_url:
  2822. results["feishu"] = send_to_feishu(
  2823. feishu_url, report_data, report_type, update_info_to_send, proxy_url, mode
  2824. )
  2825. # 发送到钉钉
  2826. if dingtalk_url:
  2827. results["dingtalk"] = send_to_dingtalk(
  2828. dingtalk_url, report_data, report_type, update_info_to_send, proxy_url, mode
  2829. )
  2830. # 发送到企业微信
  2831. if wework_url:
  2832. results["wework"] = send_to_wework(
  2833. wework_url, report_data, report_type, update_info_to_send, proxy_url, mode
  2834. )
  2835. # 发送到 Telegram
  2836. if telegram_token and telegram_chat_id:
  2837. results["telegram"] = send_to_telegram(
  2838. telegram_token,
  2839. telegram_chat_id,
  2840. report_data,
  2841. report_type,
  2842. update_info_to_send,
  2843. proxy_url,
  2844. mode,
  2845. )
  2846. # 发送到 ntfy
  2847. if ntfy_server_url and ntfy_topic:
  2848. results["ntfy"] = send_to_ntfy(
  2849. ntfy_server_url,
  2850. ntfy_topic,
  2851. ntfy_token,
  2852. report_data,
  2853. report_type,
  2854. update_info_to_send,
  2855. proxy_url,
  2856. mode,
  2857. )
  2858. # 发送邮件
  2859. if email_from and email_password and email_to:
  2860. results["email"] = send_to_email(
  2861. email_from,
  2862. email_password,
  2863. email_to,
  2864. report_type,
  2865. html_file_path,
  2866. email_smtp_server,
  2867. email_smtp_port,
  2868. )
  2869. if not results:
  2870. print("未配置任何通知渠道,跳过通知发送")
  2871. # 如果成功发送了任何通知,且启用了每天只推一次,则记录推送
  2872. if (
  2873. CONFIG["PUSH_WINDOW"]["ENABLED"]
  2874. and CONFIG["PUSH_WINDOW"]["ONCE_PER_DAY"]
  2875. and any(results.values())
  2876. ):
  2877. push_manager = PushRecordManager()
  2878. push_manager.record_push(report_type)
  2879. return results
  2880. def send_to_feishu(
  2881. webhook_url: str,
  2882. report_data: Dict,
  2883. report_type: str,
  2884. update_info: Optional[Dict] = None,
  2885. proxy_url: Optional[str] = None,
  2886. mode: str = "daily",
  2887. ) -> bool:
  2888. """发送到飞书(支持分批发送)"""
  2889. headers = {"Content-Type": "application/json"}
  2890. proxies = None
  2891. if proxy_url:
  2892. proxies = {"http": proxy_url, "https": proxy_url}
  2893. # 获取分批内容,使用飞书专用的批次大小
  2894. batches = split_content_into_batches(
  2895. report_data,
  2896. "feishu",
  2897. update_info,
  2898. max_bytes=CONFIG.get("FEISHU_BATCH_SIZE", 29000),
  2899. mode=mode,
  2900. )
  2901. print(f"飞书消息分为 {len(batches)} 批次发送 [{report_type}]")
  2902. # 逐批发送
  2903. for i, batch_content in enumerate(batches, 1):
  2904. batch_size = len(batch_content.encode("utf-8"))
  2905. print(
  2906. f"发送飞书第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  2907. )
  2908. # 添加批次标识
  2909. if len(batches) > 1:
  2910. batch_header = f"**[第 {i}/{len(batches)} 批次]**\n\n"
  2911. # 将批次标识插入到适当位置(在统计标题之后)
  2912. if "📊 **热点词汇统计**" in batch_content:
  2913. batch_content = batch_content.replace(
  2914. "📊 **热点词汇统计**\n\n", f"📊 **热点词汇统计** {batch_header}"
  2915. )
  2916. else:
  2917. # 如果没有统计标题,直接在开头添加
  2918. batch_content = batch_header + batch_content
  2919. total_titles = sum(
  2920. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  2921. )
  2922. now = get_beijing_time()
  2923. payload = {
  2924. "msg_type": "text",
  2925. "content": {
  2926. "total_titles": total_titles,
  2927. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  2928. "report_type": report_type,
  2929. "text": batch_content,
  2930. },
  2931. }
  2932. try:
  2933. response = requests.post(
  2934. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  2935. )
  2936. if response.status_code == 200:
  2937. result = response.json()
  2938. # 检查飞书的响应状态
  2939. if result.get("StatusCode") == 0 or result.get("code") == 0:
  2940. print(f"飞书第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  2941. # 批次间间隔
  2942. if i < len(batches):
  2943. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  2944. else:
  2945. error_msg = result.get("msg") or result.get("StatusMessage", "未知错误")
  2946. print(
  2947. f"飞书第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  2948. )
  2949. return False
  2950. else:
  2951. print(
  2952. f"飞书第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  2953. )
  2954. return False
  2955. except Exception as e:
  2956. print(f"飞书第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  2957. return False
  2958. print(f"飞书所有 {len(batches)} 批次发送完成 [{report_type}]")
  2959. return True
  2960. def send_to_dingtalk(
  2961. webhook_url: str,
  2962. report_data: Dict,
  2963. report_type: str,
  2964. update_info: Optional[Dict] = None,
  2965. proxy_url: Optional[str] = None,
  2966. mode: str = "daily",
  2967. ) -> bool:
  2968. """发送到钉钉(支持分批发送)"""
  2969. headers = {"Content-Type": "application/json"}
  2970. proxies = None
  2971. if proxy_url:
  2972. proxies = {"http": proxy_url, "https": proxy_url}
  2973. # 获取分批内容,使用钉钉专用的批次大小
  2974. batches = split_content_into_batches(
  2975. report_data,
  2976. "dingtalk",
  2977. update_info,
  2978. max_bytes=CONFIG.get("DINGTALK_BATCH_SIZE", 20000),
  2979. mode=mode,
  2980. )
  2981. print(f"钉钉消息分为 {len(batches)} 批次发送 [{report_type}]")
  2982. # 逐批发送
  2983. for i, batch_content in enumerate(batches, 1):
  2984. batch_size = len(batch_content.encode("utf-8"))
  2985. print(
  2986. f"发送钉钉第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  2987. )
  2988. # 添加批次标识
  2989. if len(batches) > 1:
  2990. batch_header = f"**[第 {i}/{len(batches)} 批次]**\n\n"
  2991. # 将批次标识插入到适当位置(在标题之后)
  2992. if "📊 **热点词汇统计**" in batch_content:
  2993. batch_content = batch_content.replace(
  2994. "📊 **热点词汇统计**\n\n", f"📊 **热点词汇统计** {batch_header}\n\n"
  2995. )
  2996. else:
  2997. # 如果没有统计标题,直接在开头添加
  2998. batch_content = batch_header + batch_content
  2999. payload = {
  3000. "msgtype": "markdown",
  3001. "markdown": {
  3002. "title": f"TrendRadar 热点分析报告 - {report_type}",
  3003. "text": batch_content,
  3004. },
  3005. }
  3006. try:
  3007. response = requests.post(
  3008. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  3009. )
  3010. if response.status_code == 200:
  3011. result = response.json()
  3012. if result.get("errcode") == 0:
  3013. print(f"钉钉第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3014. # 批次间间隔
  3015. if i < len(batches):
  3016. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3017. else:
  3018. print(
  3019. f"钉钉第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  3020. )
  3021. return False
  3022. else:
  3023. print(
  3024. f"钉钉第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3025. )
  3026. return False
  3027. except Exception as e:
  3028. print(f"钉钉第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3029. return False
  3030. print(f"钉钉所有 {len(batches)} 批次发送完成 [{report_type}]")
  3031. return True
  3032. def strip_markdown(text: str) -> str:
  3033. """去除文本中的 markdown 语法格式,用于个人微信推送"""
  3034. # 去除粗体 **text** 或 __text__
  3035. text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
  3036. text = re.sub(r'__(.+?)__', r'\1', text)
  3037. # 去除斜体 *text* 或 _text_
  3038. text = re.sub(r'\*(.+?)\*', r'\1', text)
  3039. text = re.sub(r'_(.+?)_', r'\1', text)
  3040. # 去除删除线 ~~text~~
  3041. text = re.sub(r'~~(.+?)~~', r'\1', text)
  3042. # 转换链接 [text](url) -> text url(保留 URL)
  3043. text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1 \2', text)
  3044. # 如果不需要保留 URL,可以使用下面这行(只保留标题文本):
  3045. # text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
  3046. # 去除图片 ![alt](url) -> alt
  3047. text = re.sub(r'!\[(.+?)\]\(.+?\)', r'\1', text)
  3048. # 去除行内代码 `code`
  3049. text = re.sub(r'`(.+?)`', r'\1', text)
  3050. # 去除引用符号 >
  3051. text = re.sub(r'^>\s*', '', text, flags=re.MULTILINE)
  3052. # 去除标题符号 # ## ### 等
  3053. text = re.sub(r'^#+\s*', '', text, flags=re.MULTILINE)
  3054. # 去除水平分割线 --- 或 ***
  3055. text = re.sub(r'^[\-\*]{3,}\s*$', '', text, flags=re.MULTILINE)
  3056. # 去除 HTML 标签 <font color='xxx'>text</font> -> text
  3057. text = re.sub(r'<font[^>]*>(.+?)</font>', r'\1', text)
  3058. text = re.sub(r'<[^>]+>', '', text)
  3059. # 清理多余的空行(保留最多两个连续空行)
  3060. text = re.sub(r'\n{3,}', '\n\n', text)
  3061. return text.strip()
  3062. def send_to_wework(
  3063. webhook_url: str,
  3064. report_data: Dict,
  3065. report_type: str,
  3066. update_info: Optional[Dict] = None,
  3067. proxy_url: Optional[str] = None,
  3068. mode: str = "daily",
  3069. ) -> bool:
  3070. """发送到企业微信(支持分批发送,支持 markdown 和 text 两种格式)"""
  3071. headers = {"Content-Type": "application/json"}
  3072. proxies = None
  3073. if proxy_url:
  3074. proxies = {"http": proxy_url, "https": proxy_url}
  3075. # 获取消息类型配置(markdown 或 text)
  3076. msg_type = CONFIG.get("WEWORK_MSG_TYPE", "markdown").lower()
  3077. is_text_mode = msg_type == "text"
  3078. if is_text_mode:
  3079. print(f"企业微信使用 text 格式(个人微信模式)[{report_type}]")
  3080. else:
  3081. print(f"企业微信使用 markdown 格式(群机器人模式)[{report_type}]")
  3082. # 获取分批内容
  3083. batches = split_content_into_batches(report_data, "wework", update_info, mode=mode)
  3084. print(f"企业微信消息分为 {len(batches)} 批次发送 [{report_type}]")
  3085. # 逐批发送
  3086. for i, batch_content in enumerate(batches, 1):
  3087. # 添加批次标识
  3088. if len(batches) > 1:
  3089. if is_text_mode:
  3090. batch_header = f"[第 {i}/{len(batches)} 批次]\n\n"
  3091. else:
  3092. batch_header = f"**[第 {i}/{len(batches)} 批次]**\n\n"
  3093. batch_content = batch_header + batch_content
  3094. # 根据消息类型构建 payload
  3095. if is_text_mode:
  3096. # text 格式:去除 markdown 语法
  3097. plain_content = strip_markdown(batch_content)
  3098. payload = {"msgtype": "text", "text": {"content": plain_content}}
  3099. batch_size = len(plain_content.encode("utf-8"))
  3100. else:
  3101. # markdown 格式:保持原样
  3102. payload = {"msgtype": "markdown", "markdown": {"content": batch_content}}
  3103. batch_size = len(batch_content.encode("utf-8"))
  3104. print(
  3105. f"发送企业微信第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3106. )
  3107. try:
  3108. response = requests.post(
  3109. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  3110. )
  3111. if response.status_code == 200:
  3112. result = response.json()
  3113. if result.get("errcode") == 0:
  3114. print(f"企业微信第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3115. # 批次间间隔
  3116. if i < len(batches):
  3117. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3118. else:
  3119. print(
  3120. f"企业微信第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  3121. )
  3122. return False
  3123. else:
  3124. print(
  3125. f"企业微信第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3126. )
  3127. return False
  3128. except Exception as e:
  3129. print(f"企业微信第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3130. return False
  3131. print(f"企业微信所有 {len(batches)} 批次发送完成 [{report_type}]")
  3132. return True
  3133. def send_to_telegram(
  3134. bot_token: str,
  3135. chat_id: str,
  3136. report_data: Dict,
  3137. report_type: str,
  3138. update_info: Optional[Dict] = None,
  3139. proxy_url: Optional[str] = None,
  3140. mode: str = "daily",
  3141. ) -> bool:
  3142. """发送到Telegram(支持分批发送)"""
  3143. headers = {"Content-Type": "application/json"}
  3144. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  3145. proxies = None
  3146. if proxy_url:
  3147. proxies = {"http": proxy_url, "https": proxy_url}
  3148. # 获取分批内容
  3149. batches = split_content_into_batches(
  3150. report_data, "telegram", update_info, mode=mode
  3151. )
  3152. print(f"Telegram消息分为 {len(batches)} 批次发送 [{report_type}]")
  3153. # 逐批发送
  3154. for i, batch_content in enumerate(batches, 1):
  3155. batch_size = len(batch_content.encode("utf-8"))
  3156. print(
  3157. f"发送Telegram第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  3158. )
  3159. # 添加批次标识
  3160. if len(batches) > 1:
  3161. batch_header = f"<b>[第 {i}/{len(batches)} 批次]</b>\n\n"
  3162. batch_content = batch_header + batch_content
  3163. payload = {
  3164. "chat_id": chat_id,
  3165. "text": batch_content,
  3166. "parse_mode": "HTML",
  3167. "disable_web_page_preview": True,
  3168. }
  3169. try:
  3170. response = requests.post(
  3171. url, headers=headers, json=payload, proxies=proxies, timeout=30
  3172. )
  3173. if response.status_code == 200:
  3174. result = response.json()
  3175. if result.get("ok"):
  3176. print(f"Telegram第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  3177. # 批次间间隔
  3178. if i < len(batches):
  3179. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  3180. else:
  3181. print(
  3182. f"Telegram第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}"
  3183. )
  3184. return False
  3185. else:
  3186. print(
  3187. f"Telegram第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3188. )
  3189. return False
  3190. except Exception as e:
  3191. print(f"Telegram第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  3192. return False
  3193. print(f"Telegram所有 {len(batches)} 批次发送完成 [{report_type}]")
  3194. return True
  3195. def send_to_email(
  3196. from_email: str,
  3197. password: str,
  3198. to_email: str,
  3199. report_type: str,
  3200. html_file_path: str,
  3201. custom_smtp_server: Optional[str] = None,
  3202. custom_smtp_port: Optional[int] = None,
  3203. ) -> bool:
  3204. """发送邮件通知"""
  3205. try:
  3206. if not html_file_path or not Path(html_file_path).exists():
  3207. print(f"错误:HTML文件不存在或未提供: {html_file_path}")
  3208. return False
  3209. print(f"使用HTML文件: {html_file_path}")
  3210. with open(html_file_path, "r", encoding="utf-8") as f:
  3211. html_content = f.read()
  3212. domain = from_email.split("@")[-1].lower()
  3213. if custom_smtp_server and custom_smtp_port:
  3214. # 使用自定义 SMTP 配置
  3215. smtp_server = custom_smtp_server
  3216. smtp_port = int(custom_smtp_port)
  3217. # 根据端口判断加密方式:465=SSL, 587=TLS
  3218. if smtp_port == 465:
  3219. use_tls = False # SSL 模式(SMTP_SSL)
  3220. elif smtp_port == 587:
  3221. use_tls = True # TLS 模式(STARTTLS)
  3222. else:
  3223. # 其他端口优先尝试 TLS(更安全,更广泛支持)
  3224. use_tls = True
  3225. elif domain in SMTP_CONFIGS:
  3226. # 使用预设配置
  3227. config = SMTP_CONFIGS[domain]
  3228. smtp_server = config["server"]
  3229. smtp_port = config["port"]
  3230. use_tls = config["encryption"] == "TLS"
  3231. else:
  3232. print(f"未识别的邮箱服务商: {domain},使用通用 SMTP 配置")
  3233. smtp_server = f"smtp.{domain}"
  3234. smtp_port = 587
  3235. use_tls = True
  3236. msg = MIMEMultipart("alternative")
  3237. # 严格按照 RFC 标准设置 From header
  3238. sender_name = "TrendRadar"
  3239. msg["From"] = formataddr((sender_name, from_email))
  3240. # 设置收件人
  3241. recipients = [addr.strip() for addr in to_email.split(",")]
  3242. if len(recipients) == 1:
  3243. msg["To"] = recipients[0]
  3244. else:
  3245. msg["To"] = ", ".join(recipients)
  3246. # 设置邮件主题
  3247. now = get_beijing_time()
  3248. subject = f"TrendRadar 热点分析报告 - {report_type} - {now.strftime('%m月%d日 %H:%M')}"
  3249. msg["Subject"] = Header(subject, "utf-8")
  3250. # 设置其他标准 header
  3251. msg["MIME-Version"] = "1.0"
  3252. msg["Date"] = formatdate(localtime=True)
  3253. msg["Message-ID"] = make_msgid()
  3254. # 添加纯文本部分(作为备选)
  3255. text_content = f"""
  3256. TrendRadar 热点分析报告
  3257. ========================
  3258. 报告类型:{report_type}
  3259. 生成时间:{now.strftime('%Y-%m-%d %H:%M:%S')}
  3260. 请使用支持HTML的邮件客户端查看完整报告内容。
  3261. """
  3262. text_part = MIMEText(text_content, "plain", "utf-8")
  3263. msg.attach(text_part)
  3264. html_part = MIMEText(html_content, "html", "utf-8")
  3265. msg.attach(html_part)
  3266. print(f"正在发送邮件到 {to_email}...")
  3267. print(f"SMTP 服务器: {smtp_server}:{smtp_port}")
  3268. print(f"发件人: {from_email}")
  3269. try:
  3270. if use_tls:
  3271. # TLS 模式
  3272. server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
  3273. server.set_debuglevel(0) # 设为1可以查看详细调试信息
  3274. server.ehlo()
  3275. server.starttls()
  3276. server.ehlo()
  3277. else:
  3278. # SSL 模式
  3279. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30)
  3280. server.set_debuglevel(0)
  3281. server.ehlo()
  3282. # 登录
  3283. server.login(from_email, password)
  3284. # 发送邮件
  3285. server.send_message(msg)
  3286. server.quit()
  3287. print(f"邮件发送成功 [{report_type}] -> {to_email}")
  3288. return True
  3289. except smtplib.SMTPServerDisconnected:
  3290. print(f"邮件发送失败:服务器意外断开连接,请检查网络或稍后重试")
  3291. return False
  3292. except smtplib.SMTPAuthenticationError as e:
  3293. print(f"邮件发送失败:认证错误,请检查邮箱和密码/授权码")
  3294. print(f"详细错误: {str(e)}")
  3295. return False
  3296. except smtplib.SMTPRecipientsRefused as e:
  3297. print(f"邮件发送失败:收件人地址被拒绝 {e}")
  3298. return False
  3299. except smtplib.SMTPSenderRefused as e:
  3300. print(f"邮件发送失败:发件人地址被拒绝 {e}")
  3301. return False
  3302. except smtplib.SMTPDataError as e:
  3303. print(f"邮件发送失败:邮件数据错误 {e}")
  3304. return False
  3305. except smtplib.SMTPConnectError as e:
  3306. print(f"邮件发送失败:无法连接到 SMTP 服务器 {smtp_server}:{smtp_port}")
  3307. print(f"详细错误: {str(e)}")
  3308. return False
  3309. except Exception as e:
  3310. print(f"邮件发送失败 [{report_type}]:{e}")
  3311. import traceback
  3312. traceback.print_exc()
  3313. return False
  3314. def send_to_ntfy(
  3315. server_url: str,
  3316. topic: str,
  3317. token: Optional[str],
  3318. report_data: Dict,
  3319. report_type: str,
  3320. update_info: Optional[Dict] = None,
  3321. proxy_url: Optional[str] = None,
  3322. mode: str = "daily",
  3323. ) -> bool:
  3324. """发送到ntfy(支持分批发送,严格遵守4KB限制)"""
  3325. # 避免 HTTP header 编码问题
  3326. report_type_en_map = {
  3327. "当日汇总": "Daily Summary",
  3328. "当前榜单汇总": "Current Ranking",
  3329. "增量更新": "Incremental Update",
  3330. "实时增量": "Realtime Incremental",
  3331. "实时当前榜单": "Realtime Current Ranking",
  3332. }
  3333. report_type_en = report_type_en_map.get(report_type, "News Report")
  3334. headers = {
  3335. "Content-Type": "text/plain; charset=utf-8",
  3336. "Markdown": "yes",
  3337. "Title": report_type_en,
  3338. "Priority": "default",
  3339. "Tags": "news",
  3340. }
  3341. if token:
  3342. headers["Authorization"] = f"Bearer {token}"
  3343. # 构建完整URL,确保格式正确
  3344. base_url = server_url.rstrip("/")
  3345. if not base_url.startswith(("http://", "https://")):
  3346. base_url = f"https://{base_url}"
  3347. url = f"{base_url}/{topic}"
  3348. proxies = None
  3349. if proxy_url:
  3350. proxies = {"http": proxy_url, "https": proxy_url}
  3351. # 获取分批内容,使用ntfy专用的4KB限制
  3352. batches = split_content_into_batches(
  3353. report_data, "ntfy", update_info, max_bytes=3800, mode=mode
  3354. )
  3355. total_batches = len(batches)
  3356. print(f"ntfy消息分为 {total_batches} 批次发送 [{report_type}]")
  3357. # 反转批次顺序,使得在ntfy客户端显示时顺序正确
  3358. # ntfy显示最新消息在上面,所以我们从最后一批开始推送
  3359. reversed_batches = list(reversed(batches))
  3360. print(f"ntfy将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  3361. # 逐批发送(反向顺序)
  3362. success_count = 0
  3363. for idx, batch_content in enumerate(reversed_batches, 1):
  3364. # 计算正确的批次编号(用户视角的编号)
  3365. actual_batch_num = total_batches - idx + 1
  3366. batch_size = len(batch_content.encode("utf-8"))
  3367. print(
  3368. f"发送ntfy第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{batch_size} 字节 [{report_type}]"
  3369. )
  3370. # 检查消息大小,确保不超过4KB
  3371. if batch_size > 4096:
  3372. print(f"警告:ntfy第 {actual_batch_num} 批次消息过大({batch_size} 字节),可能被拒绝")
  3373. # 添加批次标识(使用正确的批次编号)
  3374. current_headers = headers.copy()
  3375. if total_batches > 1:
  3376. batch_header = f"**[第 {actual_batch_num}/{total_batches} 批次]**\n\n"
  3377. batch_content = batch_header + batch_content
  3378. current_headers["Title"] = (
  3379. f"{report_type_en} ({actual_batch_num}/{total_batches})"
  3380. )
  3381. try:
  3382. response = requests.post(
  3383. url,
  3384. headers=current_headers,
  3385. data=batch_content.encode("utf-8"),
  3386. proxies=proxies,
  3387. timeout=30,
  3388. )
  3389. if response.status_code == 200:
  3390. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  3391. success_count += 1
  3392. if idx < total_batches:
  3393. # 公共服务器建议 2-3 秒,自托管可以更短
  3394. interval = 2 if "ntfy.sh" in server_url else 1
  3395. time.sleep(interval)
  3396. elif response.status_code == 429:
  3397. print(
  3398. f"ntfy第 {actual_batch_num}/{total_batches} 批次速率限制 [{report_type}],等待后重试"
  3399. )
  3400. time.sleep(10) # 等待10秒后重试
  3401. # 重试一次
  3402. retry_response = requests.post(
  3403. url,
  3404. headers=current_headers,
  3405. data=batch_content.encode("utf-8"),
  3406. proxies=proxies,
  3407. timeout=30,
  3408. )
  3409. if retry_response.status_code == 200:
  3410. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次重试成功 [{report_type}]")
  3411. success_count += 1
  3412. else:
  3413. print(
  3414. f"ntfy第 {actual_batch_num}/{total_batches} 批次重试失败,状态码:{retry_response.status_code}"
  3415. )
  3416. elif response.status_code == 413:
  3417. print(
  3418. f"ntfy第 {actual_batch_num}/{total_batches} 批次消息过大被拒绝 [{report_type}],消息大小:{batch_size} 字节"
  3419. )
  3420. else:
  3421. print(
  3422. f"ntfy第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  3423. )
  3424. try:
  3425. print(f"错误详情:{response.text}")
  3426. except:
  3427. pass
  3428. except requests.exceptions.ConnectTimeout:
  3429. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  3430. except requests.exceptions.ReadTimeout:
  3431. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  3432. except requests.exceptions.ConnectionError as e:
  3433. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  3434. except Exception as e:
  3435. print(f"ntfy第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  3436. # 判断整体发送是否成功
  3437. if success_count == total_batches:
  3438. print(f"ntfy所有 {total_batches} 批次发送完成 [{report_type}]")
  3439. return True
  3440. elif success_count > 0:
  3441. print(f"ntfy部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  3442. return True # 部分成功也视为成功
  3443. else:
  3444. print(f"ntfy发送完全失败 [{report_type}]")
  3445. return False
  3446. # === 主分析器 ===
  3447. class NewsAnalyzer:
  3448. """新闻分析器"""
  3449. # 模式策略定义
  3450. MODE_STRATEGIES = {
  3451. "incremental": {
  3452. "mode_name": "增量模式",
  3453. "description": "增量模式(只关注新增新闻,无新增时不推送)",
  3454. "realtime_report_type": "实时增量",
  3455. "summary_report_type": "当日汇总",
  3456. "should_send_realtime": True,
  3457. "should_generate_summary": True,
  3458. "summary_mode": "daily",
  3459. },
  3460. "current": {
  3461. "mode_name": "当前榜单模式",
  3462. "description": "当前榜单模式(当前榜单匹配新闻 + 新增新闻区域 + 按时推送)",
  3463. "realtime_report_type": "实时当前榜单",
  3464. "summary_report_type": "当前榜单汇总",
  3465. "should_send_realtime": True,
  3466. "should_generate_summary": True,
  3467. "summary_mode": "current",
  3468. },
  3469. "daily": {
  3470. "mode_name": "当日汇总模式",
  3471. "description": "当日汇总模式(所有匹配新闻 + 新增新闻区域 + 按时推送)",
  3472. "realtime_report_type": "",
  3473. "summary_report_type": "当日汇总",
  3474. "should_send_realtime": False,
  3475. "should_generate_summary": True,
  3476. "summary_mode": "daily",
  3477. },
  3478. }
  3479. def __init__(self):
  3480. self.request_interval = CONFIG["REQUEST_INTERVAL"]
  3481. self.report_mode = CONFIG["REPORT_MODE"]
  3482. self.rank_threshold = CONFIG["RANK_THRESHOLD"]
  3483. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  3484. self.is_docker_container = self._detect_docker_environment()
  3485. self.update_info = None
  3486. self.proxy_url = None
  3487. self._setup_proxy()
  3488. self.data_fetcher = DataFetcher(self.proxy_url)
  3489. if self.is_github_actions:
  3490. self._check_version_update()
  3491. def _detect_docker_environment(self) -> bool:
  3492. """检测是否运行在 Docker 容器中"""
  3493. try:
  3494. if os.environ.get("DOCKER_CONTAINER") == "true":
  3495. return True
  3496. if os.path.exists("/.dockerenv"):
  3497. return True
  3498. return False
  3499. except Exception:
  3500. return False
  3501. def _should_open_browser(self) -> bool:
  3502. """判断是否应该打开浏览器"""
  3503. return not self.is_github_actions and not self.is_docker_container
  3504. def _setup_proxy(self) -> None:
  3505. """设置代理配置"""
  3506. if not self.is_github_actions and CONFIG["USE_PROXY"]:
  3507. self.proxy_url = CONFIG["DEFAULT_PROXY"]
  3508. print("本地环境,使用代理")
  3509. elif not self.is_github_actions and not CONFIG["USE_PROXY"]:
  3510. print("本地环境,未启用代理")
  3511. else:
  3512. print("GitHub Actions环境,不使用代理")
  3513. def _check_version_update(self) -> None:
  3514. """检查版本更新"""
  3515. try:
  3516. need_update, remote_version = check_version_update(
  3517. VERSION, CONFIG["VERSION_CHECK_URL"], self.proxy_url
  3518. )
  3519. if need_update and remote_version:
  3520. self.update_info = {
  3521. "current_version": VERSION,
  3522. "remote_version": remote_version,
  3523. }
  3524. print(f"发现新版本: {remote_version} (当前: {VERSION})")
  3525. else:
  3526. print("版本检查完成,当前为最新版本")
  3527. except Exception as e:
  3528. print(f"版本检查出错: {e}")
  3529. def _get_mode_strategy(self) -> Dict:
  3530. """获取当前模式的策略配置"""
  3531. return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"])
  3532. def _has_notification_configured(self) -> bool:
  3533. """检查是否配置了任何通知渠道"""
  3534. return any(
  3535. [
  3536. CONFIG["FEISHU_WEBHOOK_URL"],
  3537. CONFIG["DINGTALK_WEBHOOK_URL"],
  3538. CONFIG["WEWORK_WEBHOOK_URL"],
  3539. (CONFIG["TELEGRAM_BOT_TOKEN"] and CONFIG["TELEGRAM_CHAT_ID"]),
  3540. (
  3541. CONFIG["EMAIL_FROM"]
  3542. and CONFIG["EMAIL_PASSWORD"]
  3543. and CONFIG["EMAIL_TO"]
  3544. ),
  3545. (CONFIG["NTFY_SERVER_URL"] and CONFIG["NTFY_TOPIC"]),
  3546. ]
  3547. )
  3548. def _has_valid_content(
  3549. self, stats: List[Dict], new_titles: Optional[Dict] = None
  3550. ) -> bool:
  3551. """检查是否有有效的新闻内容"""
  3552. if self.report_mode in ["incremental", "current"]:
  3553. # 增量模式和current模式下,只要stats有内容就说明有匹配的新闻
  3554. return any(stat["count"] > 0 for stat in stats)
  3555. else:
  3556. # 当日汇总模式下,检查是否有匹配的频率词新闻或新增新闻
  3557. has_matched_news = any(stat["count"] > 0 for stat in stats)
  3558. has_new_news = bool(
  3559. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  3560. )
  3561. return has_matched_news or has_new_news
  3562. def _load_analysis_data(
  3563. self,
  3564. ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]:
  3565. """统一的数据加载和预处理,使用当前监控平台列表过滤历史数据"""
  3566. try:
  3567. # 获取当前配置的监控平台ID列表
  3568. current_platform_ids = []
  3569. for platform in CONFIG["PLATFORMS"]:
  3570. current_platform_ids.append(platform["id"])
  3571. print(f"当前监控平台: {current_platform_ids}")
  3572. all_results, id_to_name, title_info = read_all_today_titles(
  3573. current_platform_ids
  3574. )
  3575. if not all_results:
  3576. print("没有找到当天的数据")
  3577. return None
  3578. total_titles = sum(len(titles) for titles in all_results.values())
  3579. print(f"读取到 {total_titles} 个标题(已按当前监控平台过滤)")
  3580. new_titles = detect_latest_new_titles(current_platform_ids)
  3581. word_groups, filter_words = load_frequency_words()
  3582. return (
  3583. all_results,
  3584. id_to_name,
  3585. title_info,
  3586. new_titles,
  3587. word_groups,
  3588. filter_words,
  3589. )
  3590. except Exception as e:
  3591. print(f"数据加载失败: {e}")
  3592. return None
  3593. def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict:
  3594. """从当前抓取结果构建标题信息"""
  3595. title_info = {}
  3596. for source_id, titles_data in results.items():
  3597. title_info[source_id] = {}
  3598. for title, title_data in titles_data.items():
  3599. ranks = title_data.get("ranks", [])
  3600. url = title_data.get("url", "")
  3601. mobile_url = title_data.get("mobileUrl", "")
  3602. title_info[source_id][title] = {
  3603. "first_time": time_info,
  3604. "last_time": time_info,
  3605. "count": 1,
  3606. "ranks": ranks,
  3607. "url": url,
  3608. "mobileUrl": mobile_url,
  3609. }
  3610. return title_info
  3611. def _run_analysis_pipeline(
  3612. self,
  3613. data_source: Dict,
  3614. mode: str,
  3615. title_info: Dict,
  3616. new_titles: Dict,
  3617. word_groups: List[Dict],
  3618. filter_words: List[str],
  3619. id_to_name: Dict,
  3620. failed_ids: Optional[List] = None,
  3621. is_daily_summary: bool = False,
  3622. ) -> Tuple[List[Dict], str]:
  3623. """统一的分析流水线:数据处理 → 统计计算 → HTML生成"""
  3624. # 统计计算
  3625. stats, total_titles = count_word_frequency(
  3626. data_source,
  3627. word_groups,
  3628. filter_words,
  3629. id_to_name,
  3630. title_info,
  3631. self.rank_threshold,
  3632. new_titles,
  3633. mode=mode,
  3634. )
  3635. # HTML生成
  3636. html_file = generate_html_report(
  3637. stats,
  3638. total_titles,
  3639. failed_ids=failed_ids,
  3640. new_titles=new_titles,
  3641. id_to_name=id_to_name,
  3642. mode=mode,
  3643. is_daily_summary=is_daily_summary,
  3644. update_info=self.update_info if CONFIG["SHOW_VERSION_UPDATE"] else None,
  3645. )
  3646. return stats, html_file
  3647. def _send_notification_if_needed(
  3648. self,
  3649. stats: List[Dict],
  3650. report_type: str,
  3651. mode: str,
  3652. failed_ids: Optional[List] = None,
  3653. new_titles: Optional[Dict] = None,
  3654. id_to_name: Optional[Dict] = None,
  3655. html_file_path: Optional[str] = None,
  3656. ) -> bool:
  3657. """统一的通知发送逻辑,包含所有判断条件"""
  3658. has_notification = self._has_notification_configured()
  3659. if (
  3660. CONFIG["ENABLE_NOTIFICATION"]
  3661. and has_notification
  3662. and self._has_valid_content(stats, new_titles)
  3663. ):
  3664. send_to_notifications(
  3665. stats,
  3666. failed_ids or [],
  3667. report_type,
  3668. new_titles,
  3669. id_to_name,
  3670. self.update_info,
  3671. self.proxy_url,
  3672. mode=mode,
  3673. html_file_path=html_file_path,
  3674. )
  3675. return True
  3676. elif CONFIG["ENABLE_NOTIFICATION"] and not has_notification:
  3677. print("⚠️ 警告:通知功能已启用但未配置任何通知渠道,将跳过通知发送")
  3678. elif not CONFIG["ENABLE_NOTIFICATION"]:
  3679. print(f"跳过{report_type}通知:通知功能已禁用")
  3680. elif (
  3681. CONFIG["ENABLE_NOTIFICATION"]
  3682. and has_notification
  3683. and not self._has_valid_content(stats, new_titles)
  3684. ):
  3685. mode_strategy = self._get_mode_strategy()
  3686. if "实时" in report_type:
  3687. print(
  3688. f"跳过实时推送通知:{mode_strategy['mode_name']}下未检测到匹配的新闻"
  3689. )
  3690. else:
  3691. print(
  3692. f"跳过{mode_strategy['summary_report_type']}通知:未匹配到有效的新闻内容"
  3693. )
  3694. return False
  3695. def _generate_summary_report(self, mode_strategy: Dict) -> Optional[str]:
  3696. """生成汇总报告(带通知)"""
  3697. summary_type = (
  3698. "当前榜单汇总" if mode_strategy["summary_mode"] == "current" else "当日汇总"
  3699. )
  3700. print(f"生成{summary_type}报告...")
  3701. # 加载分析数据
  3702. analysis_data = self._load_analysis_data()
  3703. if not analysis_data:
  3704. return None
  3705. all_results, id_to_name, title_info, new_titles, word_groups, filter_words = (
  3706. analysis_data
  3707. )
  3708. # 运行分析流水线
  3709. stats, html_file = self._run_analysis_pipeline(
  3710. all_results,
  3711. mode_strategy["summary_mode"],
  3712. title_info,
  3713. new_titles,
  3714. word_groups,
  3715. filter_words,
  3716. id_to_name,
  3717. is_daily_summary=True,
  3718. )
  3719. print(f"{summary_type}报告已生成: {html_file}")
  3720. # 发送通知
  3721. self._send_notification_if_needed(
  3722. stats,
  3723. mode_strategy["summary_report_type"],
  3724. mode_strategy["summary_mode"],
  3725. failed_ids=[],
  3726. new_titles=new_titles,
  3727. id_to_name=id_to_name,
  3728. html_file_path=html_file,
  3729. )
  3730. return html_file
  3731. def _generate_summary_html(self, mode: str = "daily") -> Optional[str]:
  3732. """生成汇总HTML"""
  3733. summary_type = "当前榜单汇总" if mode == "current" else "当日汇总"
  3734. print(f"生成{summary_type}HTML...")
  3735. # 加载分析数据
  3736. analysis_data = self._load_analysis_data()
  3737. if not analysis_data:
  3738. return None
  3739. all_results, id_to_name, title_info, new_titles, word_groups, filter_words = (
  3740. analysis_data
  3741. )
  3742. # 运行分析流水线
  3743. _, html_file = self._run_analysis_pipeline(
  3744. all_results,
  3745. mode,
  3746. title_info,
  3747. new_titles,
  3748. word_groups,
  3749. filter_words,
  3750. id_to_name,
  3751. is_daily_summary=True,
  3752. )
  3753. print(f"{summary_type}HTML已生成: {html_file}")
  3754. return html_file
  3755. def _initialize_and_check_config(self) -> None:
  3756. """通用初始化和配置检查"""
  3757. now = get_beijing_time()
  3758. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  3759. if not CONFIG["ENABLE_CRAWLER"]:
  3760. print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出")
  3761. return
  3762. has_notification = self._has_notification_configured()
  3763. if not CONFIG["ENABLE_NOTIFICATION"]:
  3764. print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取")
  3765. elif not has_notification:
  3766. print("未配置任何通知渠道,将只进行数据抓取,不发送通知")
  3767. else:
  3768. print("通知功能已启用,将发送通知")
  3769. mode_strategy = self._get_mode_strategy()
  3770. print(f"报告模式: {self.report_mode}")
  3771. print(f"运行模式: {mode_strategy['description']}")
  3772. def _crawl_data(self) -> Tuple[Dict, Dict, List]:
  3773. """执行数据爬取"""
  3774. ids = []
  3775. for platform in CONFIG["PLATFORMS"]:
  3776. if "name" in platform:
  3777. ids.append((platform["id"], platform["name"]))
  3778. else:
  3779. ids.append(platform["id"])
  3780. print(
  3781. f"配置的监控平台: {[p.get('name', p['id']) for p in CONFIG['PLATFORMS']]}"
  3782. )
  3783. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  3784. ensure_directory_exists("output")
  3785. results, id_to_name, failed_ids = self.data_fetcher.crawl_websites(
  3786. ids, self.request_interval
  3787. )
  3788. title_file = save_titles_to_file(results, id_to_name, failed_ids)
  3789. print(f"标题已保存到: {title_file}")
  3790. return results, id_to_name, failed_ids
  3791. def _execute_mode_strategy(
  3792. self, mode_strategy: Dict, results: Dict, id_to_name: Dict, failed_ids: List
  3793. ) -> Optional[str]:
  3794. """执行模式特定逻辑"""
  3795. # 获取当前监控平台ID列表
  3796. current_platform_ids = [platform["id"] for platform in CONFIG["PLATFORMS"]]
  3797. new_titles = detect_latest_new_titles(current_platform_ids)
  3798. time_info = Path(save_titles_to_file(results, id_to_name, failed_ids)).stem
  3799. word_groups, filter_words = load_frequency_words()
  3800. # current模式下,实时推送需要使用完整的历史数据来保证统计信息的完整性
  3801. if self.report_mode == "current":
  3802. # 加载完整的历史数据(已按当前平台过滤)
  3803. analysis_data = self._load_analysis_data()
  3804. if analysis_data:
  3805. (
  3806. all_results,
  3807. historical_id_to_name,
  3808. historical_title_info,
  3809. historical_new_titles,
  3810. _,
  3811. _,
  3812. ) = analysis_data
  3813. print(
  3814. f"current模式:使用过滤后的历史数据,包含平台:{list(all_results.keys())}"
  3815. )
  3816. stats, html_file = self._run_analysis_pipeline(
  3817. all_results,
  3818. self.report_mode,
  3819. historical_title_info,
  3820. historical_new_titles,
  3821. word_groups,
  3822. filter_words,
  3823. historical_id_to_name,
  3824. failed_ids=failed_ids,
  3825. )
  3826. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  3827. print(f"HTML报告已生成: {html_file}")
  3828. # 发送实时通知(使用完整历史数据的统计结果)
  3829. summary_html = None
  3830. if mode_strategy["should_send_realtime"]:
  3831. self._send_notification_if_needed(
  3832. stats,
  3833. mode_strategy["realtime_report_type"],
  3834. self.report_mode,
  3835. failed_ids=failed_ids,
  3836. new_titles=historical_new_titles,
  3837. id_to_name=combined_id_to_name,
  3838. html_file_path=html_file,
  3839. )
  3840. else:
  3841. print("❌ 严重错误:无法读取刚保存的数据文件")
  3842. raise RuntimeError("数据一致性检查失败:保存后立即读取失败")
  3843. else:
  3844. title_info = self._prepare_current_title_info(results, time_info)
  3845. stats, html_file = self._run_analysis_pipeline(
  3846. results,
  3847. self.report_mode,
  3848. title_info,
  3849. new_titles,
  3850. word_groups,
  3851. filter_words,
  3852. id_to_name,
  3853. failed_ids=failed_ids,
  3854. )
  3855. print(f"HTML报告已生成: {html_file}")
  3856. # 发送实时通知(如果需要)
  3857. summary_html = None
  3858. if mode_strategy["should_send_realtime"]:
  3859. self._send_notification_if_needed(
  3860. stats,
  3861. mode_strategy["realtime_report_type"],
  3862. self.report_mode,
  3863. failed_ids=failed_ids,
  3864. new_titles=new_titles,
  3865. id_to_name=id_to_name,
  3866. html_file_path=html_file,
  3867. )
  3868. # 生成汇总报告(如果需要)
  3869. summary_html = None
  3870. if mode_strategy["should_generate_summary"]:
  3871. if mode_strategy["should_send_realtime"]:
  3872. # 如果已经发送了实时通知,汇总只生成HTML不发送通知
  3873. summary_html = self._generate_summary_html(
  3874. mode_strategy["summary_mode"]
  3875. )
  3876. else:
  3877. # daily模式:直接生成汇总报告并发送通知
  3878. summary_html = self._generate_summary_report(mode_strategy)
  3879. # 打开浏览器(仅在非容器环境)
  3880. if self._should_open_browser() and html_file:
  3881. if summary_html:
  3882. summary_url = "file://" + str(Path(summary_html).resolve())
  3883. print(f"正在打开汇总报告: {summary_url}")
  3884. webbrowser.open(summary_url)
  3885. else:
  3886. file_url = "file://" + str(Path(html_file).resolve())
  3887. print(f"正在打开HTML报告: {file_url}")
  3888. webbrowser.open(file_url)
  3889. elif self.is_docker_container and html_file:
  3890. if summary_html:
  3891. print(f"汇总报告已生成(Docker环境): {summary_html}")
  3892. else:
  3893. print(f"HTML报告已生成(Docker环境): {html_file}")
  3894. return summary_html
  3895. def run(self) -> None:
  3896. """执行分析流程"""
  3897. try:
  3898. self._initialize_and_check_config()
  3899. mode_strategy = self._get_mode_strategy()
  3900. results, id_to_name, failed_ids = self._crawl_data()
  3901. self._execute_mode_strategy(mode_strategy, results, id_to_name, failed_ids)
  3902. except Exception as e:
  3903. print(f"分析流程执行出错: {e}")
  3904. raise
  3905. def main():
  3906. try:
  3907. analyzer = NewsAnalyzer()
  3908. analyzer.run()
  3909. except FileNotFoundError as e:
  3910. print(f"❌ 配置文件错误: {e}")
  3911. print("\n请确保以下文件存在:")
  3912. print(" • config/config.yaml")
  3913. print(" • config/frequency_words.txt")
  3914. print("\n参考项目文档进行正确配置")
  3915. except Exception as e:
  3916. print(f"❌ 程序运行错误: {e}")
  3917. raise
  3918. if __name__ == "__main__":
  3919. main()