ntfy.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. // ============================================================================
  2. //go:build !service
  3. // ntfy.go — 工具页 ntfy 消息推送
  4. //
  5. // 把消息通过 ntfy 推送服务(默认 https://ntfy.sh)发送到指定主题(频道),
  6. // 用于给监听该主题的手机 / 浏览器 / 其他设备推送通知。
  7. // 主题输入会记忆最近使用过的主题(独立文件持久化),便于下拉选择。
  8. // ============================================================================
  9. package main
  10. import (
  11. "bufio"
  12. "bytes"
  13. "context"
  14. "encoding/json"
  15. "errors"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "strings"
  23. "sync"
  24. "time"
  25. )
  26. // ntfy 默认推送服务器(ntfy.sh 公共实例)
  27. const ntfyServer = "https://ntfy.sh"
  28. // ntfy 主题历史最多记忆条数
  29. const ntfyTopicHistoryLimit = 20
  30. // ntfy 昵称历史最多记忆条数
  31. const ntfyNicknameHistoryLimit = 20
  32. // ntfyTopicsFile 返回主题历史文件路径:<用户配置目录>/TengTuToolbox/ntfy_topics.json
  33. func ntfyTopicsFile() (string, error) {
  34. dir, err := os.UserConfigDir()
  35. if err != nil {
  36. return "", err
  37. }
  38. return filepath.Join(dir, "TengTuToolbox", "ntfy_topics.json"), nil
  39. }
  40. // loadNtfyTopics 读取已记忆的主题列表(文件不存在或损坏时返回空列表)
  41. func loadNtfyTopics() []string {
  42. path, err := ntfyTopicsFile()
  43. if err != nil {
  44. return nil
  45. }
  46. data, err := os.ReadFile(path)
  47. if err != nil {
  48. return nil
  49. }
  50. var topics []string
  51. if err := json.Unmarshal(data, &topics); err != nil {
  52. return nil
  53. }
  54. return topics
  55. }
  56. // saveNtfyTopics 把主题列表写回历史文件(目录不存在时自动创建)
  57. func saveNtfyTopics(topics []string) error {
  58. path, err := ntfyTopicsFile()
  59. if err != nil {
  60. return err
  61. }
  62. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  63. return err
  64. }
  65. data, err := json.MarshalIndent(topics, "", " ")
  66. if err != nil {
  67. return err
  68. }
  69. return os.WriteFile(path, data, 0o644)
  70. }
  71. var ntfyMu sync.Mutex // 保护主题历史的并发读写
  72. // ntfyNicknamesFile 返回昵称历史文件路径:<用户配置目录>/TengTuToolbox/ntfy_nicknames.json
  73. func ntfyNicknamesFile() (string, error) {
  74. dir, err := os.UserConfigDir()
  75. if err != nil {
  76. return "", err
  77. }
  78. return filepath.Join(dir, "TengTuToolbox", "ntfy_nicknames.json"), nil
  79. }
  80. // loadNtfyNicknames 读取已记忆的昵称列表(文件不存在或损坏时返回空列表)
  81. func loadNtfyNicknames() []string {
  82. path, err := ntfyNicknamesFile()
  83. if err != nil {
  84. return nil
  85. }
  86. data, err := os.ReadFile(path)
  87. if err != nil {
  88. return nil
  89. }
  90. var nicknames []string
  91. if err := json.Unmarshal(data, &nicknames); err != nil {
  92. return nil
  93. }
  94. return nicknames
  95. }
  96. // saveNtfyNicknames 把昵称列表写回历史文件(目录不存在时自动创建)
  97. func saveNtfyNicknames(nicknames []string) error {
  98. path, err := ntfyNicknamesFile()
  99. if err != nil {
  100. return err
  101. }
  102. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  103. return err
  104. }
  105. data, err := json.MarshalIndent(nicknames, "", " ")
  106. if err != nil {
  107. return err
  108. }
  109. return os.WriteFile(path, data, 0o644)
  110. }
  111. // AddNtfyNickname 记录一个昵称:去重、置顶、上限 ntfyNicknameHistoryLimit 条,返回更新后列表。
  112. // 昵称可为空(不记忆空昵称)。
  113. func AddNtfyNickname(nickname string) []string {
  114. nickname = strings.TrimSpace(nickname)
  115. if nickname == "" {
  116. return loadNtfyNicknames()
  117. }
  118. ntfyMu.Lock()
  119. defer ntfyMu.Unlock()
  120. nicknames := loadNtfyNicknames()
  121. next := []string{nickname}
  122. for _, n := range nicknames {
  123. if n != nickname {
  124. next = append(next, n)
  125. }
  126. }
  127. if len(next) > ntfyNicknameHistoryLimit {
  128. next = next[:ntfyNicknameHistoryLimit]
  129. }
  130. if err := saveNtfyNicknames(next); err != nil {
  131. return nicknames
  132. }
  133. return next
  134. }
  135. // GetNtfyNicknames 返回已记忆的昵称列表(用于前端下拉建议)
  136. func (s *SettingsService) GetNtfyNicknames() []string {
  137. ntfyMu.Lock()
  138. defer ntfyMu.Unlock()
  139. return loadNtfyNicknames()
  140. }
  141. // SendNtfyChat 向聊天室(主题)发送一条消息,nickname 作为标题发送。
  142. // 与 SendNtfyMessage 的区别:昵称固定作为标题,便于聊天室按昵称区分发言者。
  143. func (s *SettingsService) SendNtfyChat(topic, nickname, message string) error {
  144. nickname = strings.TrimSpace(nickname)
  145. topic = strings.TrimSpace(topic)
  146. message = strings.TrimSpace(message)
  147. // 先记录本地发送,再发送。
  148. // 关键:ntfy 服务器收到消息后会立即通过 SSE 广播回声,往往比 HTTP 响应
  149. // 更快到达。若在发送成功后才记录,回声到达时记录尚不存在,去重必然失败
  150. // → 自己发送的消息又被当作 SSE 消息显示一次(表现为「显示两次」)。
  151. // 因此必须「先记录、后发送」,保证 SSE 回声到达时去重记录已就位。
  152. rememberLocalChat(topic, message)
  153. logDebug("SENT remember: topic=%q msg=%q", topic, message)
  154. err := s.SendNtfyMessage(topic, nickname, message)
  155. if err != nil {
  156. // 发送失败:移除刚记录的回声,避免误吞后续同主题同内容的真实消息
  157. forgetLocalChat(topic, message)
  158. return err
  159. }
  160. AddNtfyNickname(nickname) // 发送成功后记忆昵称
  161. return nil
  162. }
  163. // SendNtfyMessage 向指定主题推送一条 ntfy 消息。
  164. // topic 为推送主题(频道名),title 可为空(使用主题名),message 为消息内容。
  165. func (s *SettingsService) SendNtfyMessage(topic, title, message string) error {
  166. topic = strings.TrimSpace(topic)
  167. message = strings.TrimSpace(message)
  168. if topic == "" {
  169. return errors.New("请输入推送主题(Topic)")
  170. }
  171. if message == "" {
  172. return errors.New("请输入消息内容")
  173. }
  174. if len(topic) > 64 || len(message) > 4000 {
  175. return errors.New("主题过长或内容过长(主题 ≤64、内容 ≤4000 字符)")
  176. }
  177. // 校验主题为合法 URL 路径片段(允许字母数字、- _ .)
  178. for _, r := range topic {
  179. if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.') {
  180. return errors.New("主题只能包含字母、数字、-、_、. 字符")
  181. }
  182. }
  183. body := bytes.NewBufferString(message)
  184. req, err := http.NewRequest(http.MethodPost, ntfyServer+"/"+url.PathEscape(topic), body)
  185. if err != nil {
  186. return err
  187. }
  188. req.Header.Set("Content-Type", "text/plain; charset=utf-8")
  189. if strings.TrimSpace(title) != "" {
  190. req.Header.Set("Title", strings.TrimSpace(title)) // 通知标题,缺省用主题名
  191. }
  192. client := &http.Client{Timeout: 15 * time.Second}
  193. resp, err := client.Do(req)
  194. if err != nil {
  195. return errors.New("推送请求失败:" + err.Error())
  196. }
  197. defer resp.Body.Close()
  198. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  199. raw, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
  200. return errors.New("推送失败,状态 " + resp.Status + ":" + strings.TrimSpace(string(raw)))
  201. }
  202. // 发送成功后记忆主题(去重置顶)
  203. AddNtfyTopic(topic)
  204. return nil
  205. }
  206. // GetNtfyTopics 返回已记忆的主题列表(用于前端下拉建议)
  207. func (s *SettingsService) GetNtfyTopics() []string {
  208. ntfyMu.Lock()
  209. defer ntfyMu.Unlock()
  210. return loadNtfyTopics()
  211. }
  212. // AddNtfyTopic 记录一个主题:去重、置顶、上限 ntfyTopicHistoryLimit 条,返回更新后列表。
  213. // 发送失败的主题不记录;仅在成功发送时调用。
  214. func AddNtfyTopic(topic string) []string {
  215. topic = strings.TrimSpace(topic)
  216. if topic == "" {
  217. return loadNtfyTopics()
  218. }
  219. ntfyMu.Lock()
  220. defer ntfyMu.Unlock()
  221. topics := loadNtfyTopics()
  222. next := []string{topic}
  223. for _, t := range topics {
  224. if t != topic {
  225. next = append(next, t)
  226. }
  227. }
  228. if len(next) > ntfyTopicHistoryLimit {
  229. next = next[:ntfyTopicHistoryLimit] // 只保留最近 N 条
  230. }
  231. if err := saveNtfyTopics(next); err != nil {
  232. // 持久化失败不影响本次返回(仅记录历史)
  233. return topics
  234. }
  235. return next
  236. }
  237. // ============================================================================
  238. // ntfy 聊天室:订阅一个主题,实时监听该主题收到的消息并广播给前端
  239. // ============================================================================
  240. // NtfyChatMessage 聊天室收到的一条消息(JSON 序列化后经 ntfyChat 事件发给前端)
  241. type NtfyChatMessage struct {
  242. Topic string `json:"topic"` // 所属主题(聊天室名)
  243. Title string `json:"title"` // 通知标题(可为空)
  244. Message string `json:"message"` // 消息内容
  245. Time string `json:"time"` // 收到时间(本地时区 HH:MM:SS)
  246. }
  247. // ntfyEchoRecent 记录近期本地发送的消息,用于去重 ntfy 的 SSE 回声:
  248. // 自己发送的消息会被 ntfy 经 SSE 回传一次,若不加去重会在前端重复显示。
  249. type ntfyEchoRecord struct {
  250. Topic string
  251. Message string
  252. At time.Time
  253. }
  254. var (
  255. ntfyEchoMu sync.Mutex
  256. ntfyEchoRecent []ntfyEchoRecord
  257. ntfyEchoWindow = 8 * time.Second // 8 秒内的同主题同内容消息视为回声
  258. ntfyEchoMax = 20 // 最多记忆条数
  259. )
  260. // rememberLocalChat 记录一次本地发送(由 SendNtfyChat 成功发送后调用)。
  261. func rememberLocalChat(topic, message string) {
  262. ntfyEchoMu.Lock()
  263. defer ntfyEchoMu.Unlock()
  264. now := time.Now()
  265. // 先清理过期记录,再追加
  266. valid := ntfyEchoRecent[:0]
  267. for _, r := range ntfyEchoRecent {
  268. if now.Sub(r.At) < ntfyEchoWindow {
  269. valid = append(valid, r)
  270. }
  271. }
  272. valid = append(valid, ntfyEchoRecord{Topic: topic, Message: message, At: now})
  273. if len(valid) > ntfyEchoMax {
  274. valid = valid[len(valid)-ntfyEchoMax:]
  275. }
  276. ntfyEchoRecent = valid
  277. }
  278. // consumeEchoChat 检查一条收到的 SSE 消息是否为本地发送的回声。
  279. // 若是(8 秒内同主题同内容),消费并返回 true,调用方应丢弃该消息。
  280. func consumeEchoChat(topic, message string) bool {
  281. ntfyEchoMu.Lock()
  282. defer ntfyEchoMu.Unlock()
  283. now := time.Now()
  284. for i, r := range ntfyEchoRecent {
  285. if now.Sub(r.At) < ntfyEchoWindow && r.Topic == topic && r.Message == message {
  286. // 移除该条,避免后续重复命中
  287. ntfyEchoRecent = append(ntfyEchoRecent[:i], ntfyEchoRecent[i+1:]...)
  288. return true
  289. }
  290. }
  291. return false
  292. }
  293. // forgetLocalChat 移除一条本地发送记录(发送失败时回滚)。
  294. // 若发送失败,SSE 不会收到回声,需移除记录避免误吞后续同主题同内容的真实消息。
  295. func forgetLocalChat(topic, message string) {
  296. ntfyEchoMu.Lock()
  297. defer ntfyEchoMu.Unlock()
  298. for i, r := range ntfyEchoRecent {
  299. if r.Topic == topic && r.Message == message {
  300. ntfyEchoRecent = append(ntfyEchoRecent[:i], ntfyEchoRecent[i+1:]...)
  301. return
  302. }
  303. }
  304. }
  305. // ntfyChatState 聊天室监听状态:当前订阅的主题与取消函数
  306. type ntfyChatState struct {
  307. mu sync.Mutex
  308. topic string // 当前监听的主题,空表示未监听
  309. cancel func() // 取消当前监听(关闭 HTTP 响应体)
  310. }
  311. var ntfyChat = &ntfyChatState{}
  312. // SetNtfyChatTopic 设置聊天室要监听的主题。
  313. // 传入空字符串则停止监听(无主题不监听)。
  314. // 若与当前监听主题相同则不做任何事;不同则先停止旧监听再启动新监听。
  315. func (s *SettingsService) SetNtfyChatTopic(topic string) error {
  316. topic = strings.TrimSpace(topic)
  317. if topic == "" {
  318. StopNtfyChat()
  319. return nil
  320. }
  321. // 主题合法性校验(与发送一致)
  322. for _, r := range topic {
  323. if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.') {
  324. return errors.New("主题只能包含字母、数字、-、_、. 字符")
  325. }
  326. }
  327. ntfyChat.mu.Lock()
  328. defer ntfyChat.mu.Unlock()
  329. if ntfyChat.topic == topic {
  330. return nil // 已在监听该主题,无需重启
  331. }
  332. // 停止旧的监听
  333. if ntfyChat.cancel != nil {
  334. ntfyChat.cancel()
  335. ntfyChat.cancel = nil
  336. }
  337. // 启动新监听
  338. ctx, cancel := context.WithCancel(context.Background())
  339. ntfyChat.topic = topic
  340. ntfyChat.cancel = cancel
  341. go listenNtfyChat(ctx, topic)
  342. return nil
  343. }
  344. // StopNtfyChat 停止聊天室监听(清空主题并取消请求)
  345. func StopNtfyChat() {
  346. ntfyChat.mu.Lock()
  347. defer ntfyChat.mu.Unlock()
  348. if ntfyChat.cancel != nil {
  349. ntfyChat.cancel()
  350. ntfyChat.cancel = nil
  351. }
  352. ntfyChat.topic = ""
  353. }
  354. // GetNtfyChatTopic 返回当前监听的聊天室主题(空表示未监听)
  355. func (s *SettingsService) GetNtfyChatTopic() string {
  356. ntfyChat.mu.Lock()
  357. defer ntfyChat.mu.Unlock()
  358. return ntfyChat.topic
  359. }
  360. // listenNtfyChat 用 SSE 长连接订阅 ntfy 主题,循环读取消息并广播 ntfyChat 事件。
  361. // ctx 取消时关闭请求退出;连接中断后按 backoff 自动重连,直到被取消。
  362. func listenNtfyChat(ctx context.Context, topic string) {
  363. client := &http.Client{}
  364. backoff := time.Second
  365. for {
  366. select {
  367. case <-ctx.Done():
  368. return // 被取消,退出
  369. default:
  370. }
  371. err := ntfyChatOnce(client, ctx, topic, backoff)
  372. // 连接结束(错误或中断),增大重连间隔,若已被取消则退出
  373. select {
  374. case <-ctx.Done():
  375. return
  376. default:
  377. }
  378. if backoff < 30*time.Second {
  379. backoff += 5 * time.Second // 逐步增大重连间隔
  380. }
  381. _ = err
  382. }
  383. }
  384. // ntfyChatOnce 建立一次 SSE 连接并阻塞读取消息,直到连接结束或被取消。
  385. // 成功接收任意一条消息后重置 backoff(由调用方在收到消息时处理)。
  386. func ntfyChatOnce(client *http.Client, ctx context.Context, topic string, backoff time.Duration) error {
  387. req, err := http.NewRequestWithContext(ctx, http.MethodGet, ntfyServer+"/"+url.PathEscape(topic)+"/sse", nil)
  388. if err != nil {
  389. return err
  390. }
  391. req.Header.Set("Accept", "text/event-stream")
  392. resp, err := client.Do(req)
  393. if err != nil {
  394. return err
  395. }
  396. defer resp.Body.Close()
  397. // 非 2xx:不重试(如主题非法 / 服务拒绝),直接返回错误
  398. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  399. raw, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
  400. return fmt.Errorf("subscribe failed: %s %s", resp.Status, strings.TrimSpace(string(raw)))
  401. }
  402. scanner := bufio.NewScanner(resp.Body)
  403. scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) // 单行最大 1MB,容纳长消息
  404. // SSE 字段:ntfy.sh 只发 data: 行(内含 JSON,事件类型在 JSON 的 event 键),
  405. // 没有独立的 event: 字段;空行分隔一条事件。keepalive 为注释行(: ping),不含 data:。
  406. var data string
  407. for scanner.Scan() {
  408. line := scanner.Text()
  409. if line == "" {
  410. // 一条 SSE 事件结束
  411. if data != "" {
  412. emitNtfyChat(topic, data)
  413. }
  414. data = ""
  415. continue
  416. }
  417. if strings.HasPrefix(line, "data:") {
  418. data = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
  419. }
  420. }
  421. return scanner.Err()
  422. }
  423. // emitNtfyChat 解析一条消息 data 并广播 ntfyChat 事件给前端。
  424. // ntfy 的 SSE data 为 JSON,内含 event 字段:只处理 message 事件,忽略 open/keepalive 等。
  425. func emitNtfyChat(topic, data string) {
  426. // data 可能是 JSON(发布时带标题 / event 字段)或纯文本。
  427. // 注意:ntfy JSON 的 time 字段是数字,必须用 map[string]any 解析,
  428. // 若用 map[string]string 会因 number→string 失败导致解析整个失败,
  429. // 从而把整条原始 JSON 当作消息回退显示(表现为「直接显示 ntfy 消息」)。
  430. var title, msg string
  431. showTime := time.Now().Format("15:04:05") // 默认用收到时间
  432. var raw map[string]any
  433. if json.Unmarshal([]byte(data), &raw) == nil {
  434. // 仅处理 message 事件;无 event 字段时按纯文本消息处理
  435. if ev, ok := raw["event"].(string); ok && ev != "message" {
  436. return // open / keepalive 等非消息事件,忽略
  437. }
  438. if v, ok := raw["message"].(string); ok {
  439. msg = v
  440. }
  441. if v, ok := raw["title"].(string); ok {
  442. title = v
  443. }
  444. // ntfy 的 time 为 Unix 时间戳(秒),转本地时间显示发送时刻
  445. if ts, ok := raw["time"].(float64); ok && ts > 0 {
  446. showTime = time.Unix(int64(ts), 0).Format("15:04:05")
  447. }
  448. }
  449. if msg == "" {
  450. msg = data // 纯文本消息
  451. }
  452. if title == "" {
  453. title = topic // 无标题时显示主题名
  454. }
  455. // 去重 SSE 回声:自己刚发送的消息会被 ntfy 回传一次,
  456. // 若 8 秒内同主题同内容则判定为回声,直接丢弃(本地已显示)。
  457. if consumeEchoChat(topic, msg) {
  458. logDebug("ECHO dropped: listenTopic=%q title=%q msg=%q", topic, title, msg)
  459. return
  460. }
  461. logDebug("ECHO broadcast: listenTopic=%q title=%q msg=%q", topic, title, msg)
  462. payload := NtfyChatMessage{
  463. Topic: topic,
  464. Title: title,
  465. Message: msg,
  466. Time: showTime,
  467. }
  468. b, _ := json.Marshal(payload)
  469. if app != nil {
  470. app.Event.Emit("ntfyChat", string(b))
  471. }
  472. }
  473. // logDebug 把调试日志追加写入 %TEMP%\ntfy_debug.log(临时诊断,定位后移除)。
  474. func logDebug(format string, args ...any) {
  475. dir := os.Getenv("TEMP")
  476. if dir == "" {
  477. dir = os.TempDir()
  478. }
  479. path := filepath.Join(dir, "ntfy_debug.log")
  480. f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
  481. if err != nil {
  482. return
  483. }
  484. defer f.Close()
  485. fmt.Fprintf(f, "%s %s\n", time.Now().Format("15:04:05.000"), fmt.Sprintf(format, args...))
  486. }