main.py 170 KB

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