main.py 167 KB

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