main.py 161 KB

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