util_notify.lua 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. local lib_smtp = require "lib_smtp"
  2. local util_notify = {}
  3. -- 消息队列
  4. local msg_queue = {}
  5. local function urlencodeTab(params)
  6. local msg = {}
  7. for k, v in pairs(params) do
  8. table.insert(msg, string.urlEncode(k) .. "=" .. string.urlEncode(v))
  9. table.insert(msg, "&")
  10. end
  11. table.remove(msg)
  12. return table.concat(msg)
  13. end
  14. local notify = {
  15. -- 发送到 custom_post
  16. ["custom_post"] = function(msg)
  17. if config.CUSTOM_POST_URL == nil or config.CUSTOM_POST_URL == "" then
  18. log.error("util_notify", "未配置 `config.CUSTOM_POST_URL`")
  19. return
  20. end
  21. if type(config.CUSTOM_POST_BODY_TABLE) ~= "table" then
  22. log.error("util_notify", "未配置 `config.CUSTOM_POST_BODY_TABLE`")
  23. return
  24. end
  25. local header = { ["content-type"] = config.CUSTOM_POST_CONTENT_TYPE }
  26. local body = json.decode(json.encode(config.CUSTOM_POST_BODY_TABLE))
  27. -- 遍历并替换其中的变量
  28. local function traverse_and_replace(t)
  29. for k, v in pairs(t) do
  30. if type(v) == "table" then
  31. traverse_and_replace(v)
  32. elseif type(v) == "string" then
  33. t[k] = string.gsub(v, "{msg}", msg)
  34. end
  35. end
  36. end
  37. traverse_and_replace(body)
  38. -- 根据 content-type 进行编码, 默认为 application/x-www-form-urlencoded
  39. if string.find(config.CUSTOM_POST_CONTENT_TYPE, "json") then
  40. body = json.encode(body)
  41. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  42. body = string.gsub(body, "\\b", "\\n")
  43. else
  44. body = urlencodeTab(body)
  45. end
  46. log.info("util_notify", "POST", config.CUSTOM_POST_URL, config.CUSTOM_POST_CONTENT_TYPE, body)
  47. return util_http.fetch(nil, "POST", config.CUSTOM_POST_URL, header, body)
  48. end,
  49. -- 发送到 telegram
  50. ["telegram"] = function(msg)
  51. if config.TELEGRAM_API == nil or config.TELEGRAM_API == "" then
  52. log.error("util_notify", "未配置 `config.TELEGRAM_API`")
  53. return
  54. end
  55. if config.TELEGRAM_CHAT_ID == nil or config.TELEGRAM_CHAT_ID == "" then
  56. log.error("util_notify", "未配置 `config.TELEGRAM_CHAT_ID`")
  57. return
  58. end
  59. local header = { ["content-type"] = "application/json" }
  60. local body = { ["chat_id"] = config.TELEGRAM_CHAT_ID, ["disable_web_page_preview"] = true, ["text"] = msg }
  61. local json_data = json.encode(body)
  62. -- json_data = string.gsub(json_data, "\\b", "\\n")
  63. log.info("util_notify", "POST", config.TELEGRAM_API)
  64. return util_http.fetch(nil, "POST", config.TELEGRAM_API, header, json_data)
  65. end,
  66. -- 发送到 gotify
  67. ["gotify"] = function(msg)
  68. if config.GOTIFY_API == nil or config.GOTIFY_API == "" then
  69. log.error("util_notify", "未配置 `config.GOTIFY_API`")
  70. return
  71. end
  72. if config.GOTIFY_TOKEN == nil or config.GOTIFY_TOKEN == "" then
  73. log.error("util_notify", "未配置 `config.GOTIFY_TOKEN`")
  74. return
  75. end
  76. local url = config.GOTIFY_API .. "/message?token=" .. config.GOTIFY_TOKEN
  77. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  78. local body = { title = config.GOTIFY_TITLE, message = msg, priority = config.GOTIFY_PRIORITY }
  79. local json_data = json.encode(body)
  80. -- json_data = string.gsub(json_data, "\\b", "\\n")
  81. log.info("util_notify", "POST", config.GOTIFY_API)
  82. return util_http.fetch(nil, "POST", url, header, json_data)
  83. end,
  84. -- 发送到 pushdeer
  85. ["pushdeer"] = function(msg)
  86. if config.PUSHDEER_API == nil or config.PUSHDEER_API == "" then
  87. log.error("util_notify", "未配置 `config.PUSHDEER_API`")
  88. return
  89. end
  90. if config.PUSHDEER_KEY == nil or config.PUSHDEER_KEY == "" then
  91. log.error("util_notify", "未配置 `config.PUSHDEER_KEY`")
  92. return
  93. end
  94. local header = { ["Content-Type"] = "application/x-www-form-urlencoded" }
  95. local body = { pushkey = config.PUSHDEER_KEY or "", type = "text", text = msg }
  96. log.info("util_notify", "POST", config.PUSHDEER_API)
  97. return util_http.fetch(nil, "POST", config.PUSHDEER_API, header, urlencodeTab(body))
  98. end,
  99. -- 发送到 bark
  100. ["bark"] = function(msg)
  101. if config.BARK_API == nil or config.BARK_API == "" then
  102. log.error("util_notify", "未配置 `config.BARK_API`")
  103. return
  104. end
  105. if config.BARK_KEY == nil or config.BARK_KEY == "" then
  106. log.error("util_notify", "未配置 `config.BARK_KEY`")
  107. return
  108. end
  109. local header = { ["Content-Type"] = "application/x-www-form-urlencoded" }
  110. local body = { body = msg }
  111. local url = config.BARK_API .. "/" .. config.BARK_KEY
  112. log.info("util_notify", "POST", url)
  113. return util_http.fetch(nil, "POST", url, header, urlencodeTab(body))
  114. end,
  115. -- 发送到 dingtalk
  116. ["dingtalk"] = function(msg)
  117. if config.DINGTALK_WEBHOOK == nil or config.DINGTALK_WEBHOOK == "" then
  118. log.error("util_notify", "未配置 `config.DINGTALK_WEBHOOK`")
  119. return
  120. end
  121. local url = config.DINGTALK_WEBHOOK
  122. -- 如果配置了 config.DINGTALK_SECRET 则需要签名(加签), 没配置则为自定义关键词
  123. if (config.DINGTALK_SECRET and config.DINGTALK_SECRET ~= "") then
  124. -- 时间异常则等待同步
  125. if os.time() < 1714500000 then
  126. socket.sntp()
  127. sys.waitUntil("NTP_UPDATE", 1000 * 10)
  128. end
  129. local timestamp = tostring(os.time()) .. "000"
  130. local sign = crypto.hmac_sha256(timestamp .. "\n" .. config.DINGTALK_SECRET, config.DINGTALK_SECRET):fromHex():toBase64():urlEncode()
  131. url = url .. "&timestamp=" .. timestamp .. "&sign=" .. sign
  132. end
  133. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  134. local body = { msgtype = "text", text = { content = msg } }
  135. body = json.encode(body)
  136. log.info("util_notify", "POST", url)
  137. local res_code, res_headers, res_body = util_http.fetch(nil, "POST", url, header, body)
  138. -- 处理响应
  139. -- https://open.dingtalk.com/document/orgapp/custom-robots-send-group-messages
  140. if res_code == 200 and res_body and res_body ~= "" then
  141. local res_data = json.decode(res_body)
  142. local res_errcode = res_data.errcode or 0
  143. local res_errmsg = res_data.errmsg or ""
  144. -- 系统繁忙 / 发送速度太快而限流
  145. if res_errcode == -1 or res_errcode == 410100 then
  146. return 500, res_headers, res_body
  147. end
  148. -- timestamp 无效
  149. if res_errcode == 310000 and (string.find(res_errmsg, "timestamp") or string.find(res_errmsg, "过期")) then
  150. socket.sntp()
  151. return 500, res_headers, res_body
  152. end
  153. end
  154. return res_code, res_headers, res_body
  155. end,
  156. -- 发送到 feishu
  157. ["feishu"] = function(msg)
  158. if config.FEISHU_WEBHOOK == nil or config.FEISHU_WEBHOOK == "" then
  159. log.error("util_notify", "未配置 `config.FEISHU_WEBHOOK`")
  160. return
  161. end
  162. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  163. local body = { msg_type = "text", content = { text = msg } }
  164. local json_data = json.encode(body)
  165. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  166. -- json_data = string.gsub(json_data, "\\b", "\\n")
  167. log.info("util_notify", "POST", config.FEISHU_WEBHOOK)
  168. return util_http.fetch(nil, "POST", config.FEISHU_WEBHOOK, header, json_data)
  169. end,
  170. -- 发送到 wecom
  171. ["wecom"] = function(msg)
  172. if config.WECOM_WEBHOOK == nil or config.WECOM_WEBHOOK == "" then
  173. log.error("util_notify", "未配置 `config.WECOM_WEBHOOK`")
  174. return
  175. end
  176. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  177. local body = { msgtype = "text", text = { content = msg } }
  178. local json_data = json.encode(body)
  179. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  180. -- json_data = string.gsub(json_data, "\\b", "\\n")
  181. log.info("util_notify", "POST", config.WECOM_WEBHOOK)
  182. return util_http.fetch(nil, "POST", config.WECOM_WEBHOOK, header, json_data)
  183. end,
  184. -- 发送到 pushover
  185. ["pushover"] = function(msg)
  186. if config.PUSHOVER_API_TOKEN == nil or config.PUSHOVER_API_TOKEN == "" then
  187. log.error("util_notify", "未配置 `config.PUSHOVER_API_TOKEN`")
  188. return
  189. end
  190. if config.PUSHOVER_USER_KEY == nil or config.PUSHOVER_USER_KEY == "" then
  191. log.error("util_notify", "未配置 `config.PUSHOVER_USER_KEY`")
  192. return
  193. end
  194. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  195. local body = { token = config.PUSHOVER_API_TOKEN, user = config.PUSHOVER_USER_KEY, message = msg }
  196. local json_data = json.encode(body)
  197. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  198. -- json_data = string.gsub(json_data, "\\b", "\\n")
  199. local url = "https://api.pushover.net/1/messages.json"
  200. log.info("util_notify", "POST", url)
  201. return util_http.fetch(nil, "POST", url, header, json_data)
  202. end,
  203. -- 发送到 inotify
  204. ["inotify"] = function(msg)
  205. if config.INOTIFY_API == nil or config.INOTIFY_API == "" then
  206. log.error("util_notify", "未配置 `config.INOTIFY_API`")
  207. return
  208. end
  209. if not config.INOTIFY_API:endsWith(".send") then
  210. log.error("util_notify", "`config.INOTIFY_API` 必须以 `.send` 结尾")
  211. return
  212. end
  213. local url = config.INOTIFY_API .. "/" .. string.urlEncode(msg)
  214. log.info("util_notify", "GET", url)
  215. return util_http.fetch(nil, "GET", url)
  216. end,
  217. -- 发送到 next-smtp-proxy
  218. ["next-smtp-proxy"] = function(msg)
  219. if config.NEXT_SMTP_PROXY_API == nil or config.NEXT_SMTP_PROXY_API == "" then
  220. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_API`")
  221. return
  222. end
  223. if config.NEXT_SMTP_PROXY_USER == nil or config.NEXT_SMTP_PROXY_USER == "" then
  224. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_USER`")
  225. return
  226. end
  227. if config.NEXT_SMTP_PROXY_PASSWORD == nil or config.NEXT_SMTP_PROXY_PASSWORD == "" then
  228. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_PASSWORD`")
  229. return
  230. end
  231. if config.NEXT_SMTP_PROXY_HOST == nil or config.NEXT_SMTP_PROXY_HOST == "" then
  232. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_HOST`")
  233. return
  234. end
  235. if config.NEXT_SMTP_PROXY_PORT == nil or config.NEXT_SMTP_PROXY_PORT == "" then
  236. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_PORT`")
  237. return
  238. end
  239. if config.NEXT_SMTP_PROXY_TO_EMAIL == nil or config.NEXT_SMTP_PROXY_TO_EMAIL == "" then
  240. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_TO_EMAIL`")
  241. return
  242. end
  243. local header = { ["Content-Type"] = "application/x-www-form-urlencoded" }
  244. local body = {
  245. user = config.NEXT_SMTP_PROXY_USER,
  246. password = config.NEXT_SMTP_PROXY_PASSWORD,
  247. host = config.NEXT_SMTP_PROXY_HOST,
  248. port = config.NEXT_SMTP_PROXY_PORT,
  249. form_name = config.NEXT_SMTP_PROXY_FORM_NAME,
  250. to_email = config.NEXT_SMTP_PROXY_TO_EMAIL,
  251. subject = config.NEXT_SMTP_PROXY_SUBJECT,
  252. text = msg,
  253. }
  254. log.info("util_notify", "POST", config.NEXT_SMTP_PROXY_API)
  255. return util_http.fetch(nil, "POST", config.NEXT_SMTP_PROXY_API, header, urlencodeTab(body))
  256. end,
  257. ["smtp"] = function(msg)
  258. local smtp_config = {
  259. host = config.SMTP_HOST,
  260. port = config.SMTP_PORT,
  261. username = config.SMTP_USERNAME,
  262. password = config.SMTP_PASSWORD,
  263. mail_from = config.SMTP_MAIL_FROM,
  264. mail_to = config.SMTP_MAIL_TO,
  265. tls_enable = config.SMTP_TLS_ENABLE,
  266. }
  267. local result = lib_smtp.send(msg, config.SMTP_MAIL_SUBJECT, smtp_config)
  268. log.info("util_notify", "SMTP", result.success, result.message, result.is_retry)
  269. if result.success then return 200, nil, result.message end
  270. if result.is_retry then return 500, nil, result.message end
  271. return 400, nil, result.message
  272. end,
  273. -- 发送到 serial
  274. ["serial"] = function(msg)
  275. uart.write(1, msg)
  276. log.info("util_notify", "serial", "消息已转发到串口")
  277. sys.wait(1000)
  278. return 200
  279. end,
  280. }
  281. local function append()
  282. local msg = "\n"
  283. -- 本机号码
  284. local number = mobile.number(mobile.simid()) or config.FALLBACK_LOCAL_NUMBER
  285. if number then msg = msg .. "\n本机号码: " .. number end
  286. -- 开机时长
  287. local ms = mcu.ticks()
  288. local seconds = math.floor(ms / 1000)
  289. local minutes = math.floor(seconds / 60)
  290. local hours = math.floor(minutes / 60)
  291. seconds = seconds % 60
  292. minutes = minutes % 60
  293. local boot_time = string.format("%02d:%02d:%02d", hours, minutes, seconds)
  294. if ms >= 0 then msg = msg .. "\n开机时长: " .. boot_time end
  295. -- 运营商
  296. local oper = util_mobile.getOper(true)
  297. if oper ~= "" then msg = msg .. "\n运营商: " .. oper end
  298. -- 信号
  299. local rsrp = mobile.rsrp()
  300. if rsrp ~= 0 then msg = msg .. "\n信号: " .. rsrp .. "dBm" end
  301. -- 频段
  302. local band = util_mobile.getBand()
  303. if band >= 0 then msg = msg .. "\n频段: B" .. band end
  304. -- 电压, 读取 VBAT 供电电压, 单位为 mV
  305. adc.open(adc.CH_VBAT)
  306. local vbat = adc.get(adc.CH_VBAT)
  307. adc.close(adc.CH_VBAT)
  308. if vbat >= 0 then msg = msg .. "\n电压: " .. string.format("%.1f", vbat / 1000) .. "V" end
  309. -- 温度
  310. adc.open(adc.CH_CPU)
  311. local temp = adc.get(adc.CH_CPU)
  312. adc.close(adc.CH_CPU)
  313. if temp >= 0 then msg = msg .. "\n温度: " .. string.format("%.1f", temp / 1000) .. "°C" end
  314. -- 流量统计
  315. -- local uplinkGB, uplinkB, downlinkGB, downlinkB = mobile.dataTraffic()
  316. -- uplinkB = uplinkGB * 1024 * 1024 * 1024 + uplinkB
  317. -- downlinkB = downlinkGB * 1024 * 1024 * 1024 + downlinkB
  318. -- local function formatBytes(bytes)
  319. -- if bytes < 1024 then
  320. -- return bytes .. "B"
  321. -- elseif bytes < 1024 * 1024 then
  322. -- return string.format("%.2fKB", bytes / 1024)
  323. -- elseif bytes < 1024 * 1024 * 1024 then
  324. -- return string.format("%.2fMB", bytes / 1024 / 1024)
  325. -- else
  326. -- return string.format("%.2fGB", bytes / 1024 / 1024 / 1024)
  327. -- end
  328. -- end
  329. -- msg = msg .. "\n流量: ↑" .. formatBytes(uplinkB) .. " ↓" .. formatBytes(downlinkB)
  330. -- 位置
  331. local _, _, map_link = util_location.get()
  332. if map_link ~= "" then
  333. msg = msg .. "\n位置: " .. map_link -- 这里使用 U+00a0 防止换行
  334. end
  335. return msg
  336. end
  337. --- 发送通知
  338. -- @param msg 消息内容
  339. -- @param channel 通知渠道
  340. -- @return true: 无需重发, false: 需要重发
  341. function util_notify.send(msg, channel)
  342. log.info("util_notify.send", "发送通知", channel)
  343. -- 判断消息内容 msg
  344. if type(msg) ~= "string" then
  345. log.error("util_notify.send", "发送通知失败", "参数类型错误", type(msg))
  346. return true
  347. end
  348. if msg == "" then
  349. log.error("util_notify.send", "发送通知失败", "消息为空")
  350. return true
  351. end
  352. -- 判断通知渠道 channel
  353. if channel and notify[channel] == nil then
  354. log.error("util_notify.send", "发送通知失败", "未知通知渠道", channel)
  355. return true
  356. end
  357. -- 发送通知
  358. local code, headers, body = notify[channel](msg)
  359. if code == nil then
  360. log.info("util_notify.send", "发送通知失败, 无需重发", "code:", code, "body:", body)
  361. return true
  362. end
  363. -- if code == -6 then
  364. -- -- 发生在 url 过长时, 重发也不会成功
  365. -- log.info("util_notify.send", "发送通知失败, 无需重发", "code:", code, "body:", body)
  366. -- return true
  367. -- end
  368. if code >= 200 and code < 500 and code ~= 429 then
  369. -- http 2xx 成功
  370. -- http 3xx 重定向, 重发也不会成功
  371. -- http 4xx 客户端错误, 重发也不会成功
  372. log.info("util_notify.send", "发送通知成功", "code:", code, "body:", body)
  373. return true
  374. end
  375. log.error("util_notify.send", "发送通知失败, 等待重发", "code:", code, "body:", body)
  376. return false
  377. end
  378. --- 添加到消息队列
  379. -- @param msg 消息内容
  380. -- @param channels 通知渠道
  381. function util_notify.add(msg, channels)
  382. if type(msg) == "table" then msg = table.concat(msg, "\n") end
  383. -- 通知内容追加更多信息, 若已经包含则不再追加
  384. local is_append = true
  385. if string.find(msg, "本机号码:") and string.find(msg, "开机时长:") then
  386. log.info("util_notify.send", "不追加更多信息")
  387. is_append = false
  388. end
  389. if config.NOTIFY_APPEND_MORE_INFO and is_append then msg = msg .. append() end
  390. channels = channels or config.NOTIFY_TYPE
  391. if type(channels) ~= "table" then channels = { channels } end
  392. for _, channel in ipairs(channels) do table.insert(msg_queue, { channel = channel, msg = msg, retry = 0 }) end
  393. sys.publish("NEW_MSG")
  394. log.debug("util_notify.add", "添加到消息队列, 当前队列长度:", #msg_queue)
  395. log.debug("util_notify.add", "添加到消息队列的内容:", msg:gsub("\r", "\\r"):gsub("\n", "\\n"))
  396. end
  397. -- 轮询消息队列
  398. -- 发送成功则从消息队列中删除
  399. -- 发送失败则等待下次轮询
  400. local function poll()
  401. local item, result
  402. local codes = {
  403. [0] = "网络未注册",
  404. [1] = "网络已注册",
  405. [2] = "网络搜索中",
  406. [3] = "网络注册被拒绝",
  407. [4] = "网络状态未知",
  408. [5] = "网络已注册,漫游",
  409. [6] = "网络已注册,仅SMS",
  410. [7] = "网络已注册,漫游,仅SMS",
  411. [8] = "网络已注册,紧急服务",
  412. [9] = "网络已注册,非主要服务",
  413. [10] = "网络已注册,非主要服务,漫游",
  414. }
  415. while true do
  416. -- 打印网络状态
  417. if mobile.status() ~= 1 then
  418. log.debug("mobile.status:", codes[mobile.status() or 0] or "未知网络状态")
  419. end
  420. -- 消息队列非空, 且网络已注册
  421. if next(msg_queue) ~= nil and (mobile.status() == 1 or mobile.status() == 5) then
  422. log.debug("util_notify.poll", "轮询消息队列中", "队列长度:", #msg_queue, "重发次数:", msg_queue[1].retry)
  423. item = msg_queue[1]
  424. table.remove(msg_queue, 1)
  425. local msg = item.msg
  426. -- 通知内容添加重发次数
  427. if item.retry > 0 then
  428. msg = msg .. "\n重发次数: " .. item.retry
  429. end
  430. if item.retry > (config.NOTIFY_RETRY_MAX or 100) then
  431. log.error("util_notify.poll", "超过最大重发次数", "msg:", item.msg)
  432. else
  433. result = util_notify.send(msg, item.channel)
  434. item.retry = item.retry + 1
  435. if not result then
  436. -- 发送失败, 移到队尾
  437. table.insert(msg_queue, item)
  438. -- 等待重发时间, 每次增加 2 秒
  439. local delay = 5000 + 2000 * (item.retry - 1)
  440. log.debug("util_notify.poll", "等待下次重发", delay .. "ms")
  441. sys.wait(delay)
  442. end
  443. end
  444. if item.retry % 5 == 0 then
  445. log.warn("util_notify.poll", "重发次数过多, 开关飞行模式")
  446. mobile.flymode(0, true)
  447. sys.wait(1000)
  448. mobile.flymode(0, false)
  449. end
  450. sys.wait(50)
  451. else
  452. sys.waitUntil("NEW_MSG", 1000 * 10)
  453. end
  454. end
  455. end
  456. sys.taskInit(poll)
  457. return util_notify