util_notify.lua 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 ~= nil and config.DINGTALK_SECRET ~= "") then
  124. local timestamp = tostring(os.time()) .. "000"
  125. local sign = crypto.hmac_sha256(timestamp .. "\n" .. config.DINGTALK_SECRET, config.DINGTALK_SECRET):fromHex():toBase64():urlEncode()
  126. url = url .. "&timestamp=" .. timestamp .. "&sign=" .. sign
  127. end
  128. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  129. local body = { msgtype = "text", text = { content = msg } }
  130. body = json.encode(body)
  131. log.info("util_notify", "POST", url)
  132. return util_http.fetch(nil, "POST", url, header, body)
  133. end,
  134. -- 发送到 feishu
  135. ["feishu"] = function(msg)
  136. if config.FEISHU_WEBHOOK == nil or config.FEISHU_WEBHOOK == "" then
  137. log.error("util_notify", "未配置 `config.FEISHU_WEBHOOK`")
  138. return
  139. end
  140. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  141. local body = { msg_type = "text", content = { text = msg } }
  142. local json_data = json.encode(body)
  143. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  144. -- json_data = string.gsub(json_data, "\\b", "\\n")
  145. log.info("util_notify", "POST", config.FEISHU_WEBHOOK)
  146. return util_http.fetch(nil, "POST", config.FEISHU_WEBHOOK, header, json_data)
  147. end,
  148. -- 发送到 wecom
  149. ["wecom"] = function(msg)
  150. if config.WECOM_WEBHOOK == nil or config.WECOM_WEBHOOK == "" then
  151. log.error("util_notify", "未配置 `config.WECOM_WEBHOOK`")
  152. return
  153. end
  154. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  155. local body = { msgtype = "text", text = { content = msg } }
  156. local json_data = json.encode(body)
  157. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  158. -- json_data = string.gsub(json_data, "\\b", "\\n")
  159. log.info("util_notify", "POST", config.WECOM_WEBHOOK)
  160. return util_http.fetch(nil, "POST", config.WECOM_WEBHOOK, header, json_data)
  161. end,
  162. -- 发送到 pushover
  163. ["pushover"] = function(msg)
  164. if config.PUSHOVER_API_TOKEN == nil or config.PUSHOVER_API_TOKEN == "" then
  165. log.error("util_notify", "未配置 `config.PUSHOVER_API_TOKEN`")
  166. return
  167. end
  168. if config.PUSHOVER_USER_KEY == nil or config.PUSHOVER_USER_KEY == "" then
  169. log.error("util_notify", "未配置 `config.PUSHOVER_USER_KEY`")
  170. return
  171. end
  172. local header = { ["Content-Type"] = "application/json; charset=utf-8" }
  173. local body = { token = config.PUSHOVER_API_TOKEN, user = config.PUSHOVER_USER_KEY, message = msg }
  174. local json_data = json.encode(body)
  175. -- LuatOS Bug, json.encode 会将 \n 转换为 \b
  176. -- json_data = string.gsub(json_data, "\\b", "\\n")
  177. local url = "https://api.pushover.net/1/messages.json"
  178. log.info("util_notify", "POST", url)
  179. return util_http.fetch(nil, "POST", url, header, json_data)
  180. end,
  181. -- 发送到 inotify
  182. ["inotify"] = function(msg)
  183. if config.INOTIFY_API == nil or config.INOTIFY_API == "" then
  184. log.error("util_notify", "未配置 `config.INOTIFY_API`")
  185. return
  186. end
  187. if not config.INOTIFY_API:endsWith(".send") then
  188. log.error("util_notify", "`config.INOTIFY_API` 必须以 `.send` 结尾")
  189. return
  190. end
  191. local url = config.INOTIFY_API .. "/" .. string.urlEncode(msg)
  192. log.info("util_notify", "GET", url)
  193. return util_http.fetch(nil, "GET", url)
  194. end,
  195. -- 发送到 next-smtp-proxy
  196. ["next-smtp-proxy"] = function(msg)
  197. if config.NEXT_SMTP_PROXY_API == nil or config.NEXT_SMTP_PROXY_API == "" then
  198. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_API`")
  199. return
  200. end
  201. if config.NEXT_SMTP_PROXY_USER == nil or config.NEXT_SMTP_PROXY_USER == "" then
  202. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_USER`")
  203. return
  204. end
  205. if config.NEXT_SMTP_PROXY_PASSWORD == nil or config.NEXT_SMTP_PROXY_PASSWORD == "" then
  206. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_PASSWORD`")
  207. return
  208. end
  209. if config.NEXT_SMTP_PROXY_HOST == nil or config.NEXT_SMTP_PROXY_HOST == "" then
  210. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_HOST`")
  211. return
  212. end
  213. if config.NEXT_SMTP_PROXY_PORT == nil or config.NEXT_SMTP_PROXY_PORT == "" then
  214. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_PORT`")
  215. return
  216. end
  217. if config.NEXT_SMTP_PROXY_TO_EMAIL == nil or config.NEXT_SMTP_PROXY_TO_EMAIL == "" then
  218. log.error("util_notify", "未配置 `config.NEXT_SMTP_PROXY_TO_EMAIL`")
  219. return
  220. end
  221. local header = { ["Content-Type"] = "application/x-www-form-urlencoded" }
  222. local body = {
  223. user = config.NEXT_SMTP_PROXY_USER,
  224. password = config.NEXT_SMTP_PROXY_PASSWORD,
  225. host = config.NEXT_SMTP_PROXY_HOST,
  226. port = config.NEXT_SMTP_PROXY_PORT,
  227. form_name = config.NEXT_SMTP_PROXY_FORM_NAME,
  228. to_email = config.NEXT_SMTP_PROXY_TO_EMAIL,
  229. subject = config.NEXT_SMTP_PROXY_SUBJECT,
  230. text = msg,
  231. }
  232. log.info("util_notify", "POST", config.NEXT_SMTP_PROXY_API)
  233. return util_http.fetch(nil, "POST", config.NEXT_SMTP_PROXY_API, header, urlencodeTab(body))
  234. end,
  235. ["smtp"] = function(msg)
  236. local smtp_config = {
  237. host = config.SMTP_HOST,
  238. port = config.SMTP_PORT,
  239. username = config.SMTP_USERNAME,
  240. password = config.SMTP_PASSWORD,
  241. mail_from = config.SMTP_MAIL_FROM,
  242. mail_to = config.SMTP_MAIL_TO,
  243. tls_enable = config.SMTP_TLS_ENABLE,
  244. }
  245. local result = lib_smtp.send(msg, config.SMTP_MAIL_SUBJECT, smtp_config)
  246. log.info("util_notify", "SMTP", result.success, result.message, result.is_retry)
  247. if result.success then return 200, nil, result.message end
  248. if result.is_retry then return 500, nil, result.message end
  249. return 400, nil, result.message
  250. end,
  251. -- 发送到 serial
  252. ["serial"] = function(msg)
  253. uart.write(1, msg)
  254. log.info("util_notify", "serial", "消息已转发到串口")
  255. sys.wait(1000)
  256. return 200
  257. end,
  258. }
  259. local function append()
  260. local msg = "\n"
  261. -- 本机号码
  262. local number = mobile.number(mobile.simid()) or config.FALLBACK_LOCAL_NUMBER
  263. if number then msg = msg .. "\n本机号码: " .. number end
  264. -- 开机时长
  265. local ms = mcu.ticks()
  266. local seconds = math.floor(ms / 1000)
  267. local minutes = math.floor(seconds / 60)
  268. local hours = math.floor(minutes / 60)
  269. seconds = seconds % 60
  270. minutes = minutes % 60
  271. local boot_time = string.format("%02d:%02d:%02d", hours, minutes, seconds)
  272. if ms >= 0 then msg = msg .. "\n开机时长: " .. boot_time end
  273. -- 运营商
  274. local oper = util_mobile.getOper(true)
  275. if oper ~= "" then msg = msg .. "\n运营商: " .. oper end
  276. -- 信号
  277. local rsrp = mobile.rsrp()
  278. if rsrp ~= 0 then msg = msg .. "\n信号: " .. rsrp .. "dBm" end
  279. -- 频段
  280. local band = util_mobile.getBand()
  281. if band >= 0 then msg = msg .. "\n频段: B" .. band end
  282. -- 电压, 读取 VBAT 供电电压, 单位为 mV
  283. adc.open(adc.CH_VBAT)
  284. local vbat = adc.get(adc.CH_VBAT)
  285. adc.close(adc.CH_VBAT)
  286. if vbat >= 0 then msg = msg .. "\n电压: " .. string.format("%.1f", vbat / 1000) .. "V" end
  287. -- 温度
  288. adc.open(adc.CH_CPU)
  289. local temp = adc.get(adc.CH_CPU)
  290. adc.close(adc.CH_CPU)
  291. if temp >= 0 then msg = msg .. "\n温度: " .. string.format("%.1f", temp / 1000) .. "°C" end
  292. -- 流量统计
  293. -- local uplinkGB, uplinkB, downlinkGB, downlinkB = mobile.dataTraffic()
  294. -- uplinkB = uplinkGB * 1024 * 1024 * 1024 + uplinkB
  295. -- downlinkB = downlinkGB * 1024 * 1024 * 1024 + downlinkB
  296. -- local function formatBytes(bytes)
  297. -- if bytes < 1024 then
  298. -- return bytes .. "B"
  299. -- elseif bytes < 1024 * 1024 then
  300. -- return string.format("%.2fKB", bytes / 1024)
  301. -- elseif bytes < 1024 * 1024 * 1024 then
  302. -- return string.format("%.2fMB", bytes / 1024 / 1024)
  303. -- else
  304. -- return string.format("%.2fGB", bytes / 1024 / 1024 / 1024)
  305. -- end
  306. -- end
  307. -- msg = msg .. "\n流量: ↑" .. formatBytes(uplinkB) .. " ↓" .. formatBytes(downlinkB)
  308. -- 位置
  309. local _, _, map_link = util_location.get()
  310. if map_link ~= "" then
  311. msg = msg .. "\n位置: " .. map_link -- 这里使用 U+00a0 防止换行
  312. end
  313. return msg
  314. end
  315. --- 发送通知
  316. -- @param msg 消息内容
  317. -- @param channel 通知渠道
  318. -- @return true: 无需重发, false: 需要重发
  319. function util_notify.send(msg, channel)
  320. log.info("util_notify.send", "发送通知", channel)
  321. -- 判断消息内容 msg
  322. if type(msg) ~= "string" then
  323. log.error("util_notify.send", "发送通知失败", "参数类型错误", type(msg))
  324. return true
  325. end
  326. if msg == "" then
  327. log.error("util_notify.send", "发送通知失败", "消息为空")
  328. return true
  329. end
  330. -- 判断通知渠道 channel
  331. if channel and notify[channel] == nil then
  332. log.error("util_notify.send", "发送通知失败", "未知通知渠道", channel)
  333. return true
  334. end
  335. -- 发送通知
  336. local code, headers, body = notify[channel](msg)
  337. if code == nil then
  338. log.info("util_notify.send", "发送通知失败, 无需重发", "code:", code, "body:", body)
  339. return true
  340. end
  341. if code == -6 then
  342. -- 发生在 url 过长时, 重发也不会成功
  343. log.info("util_notify.send", "发送通知失败, 无需重发", "code:", code, "body:", body)
  344. return true
  345. end
  346. if code >= 200 and code < 500 then
  347. -- http 2xx 成功
  348. -- http 3xx 重定向, 重发也不会成功
  349. -- http 4xx 客户端错误, 重发也不会成功
  350. log.info("util_notify.send", "发送通知成功", "code:", code, "body:", body)
  351. return true
  352. end
  353. log.error("util_notify.send", "发送通知失败, 等待重发", "code:", code, "body:", body)
  354. return false
  355. end
  356. --- 添加到消息队列
  357. -- @param msg 消息内容
  358. -- @param channels 通知渠道
  359. function util_notify.add(msg, channels)
  360. if type(msg) == "table" then msg = table.concat(msg, "\n") end
  361. -- 通知内容追加更多信息, 若已经包含则不再追加
  362. local is_append = true
  363. if string.find(msg, "本机号码:") and string.find(msg, "开机时长:") then
  364. log.info("util_notify.send", "不追加更多信息")
  365. is_append = false
  366. end
  367. if config.NOTIFY_APPEND_MORE_INFO and is_append then msg = msg .. append() end
  368. channels = channels or config.NOTIFY_TYPE
  369. if type(channels) ~= "table" then channels = { channels } end
  370. for _, channel in ipairs(channels) do table.insert(msg_queue, { channel = channel, msg = msg, retry = 0 }) end
  371. sys.publish("NEW_MSG")
  372. log.debug("util_notify.add", "添加到消息队列, 当前队列长度:", #msg_queue)
  373. log.debug("util_notify.add", "添加到消息队列的内容:", msg:gsub("\r", "\\r"):gsub("\n", "\\n"))
  374. end
  375. -- 轮询消息队列
  376. -- 发送成功则从消息队列中删除
  377. -- 发送失败则等待下次轮询
  378. local function poll()
  379. local item, result
  380. local codes = {
  381. [0] = "网络未注册",
  382. [1] = "网络已注册",
  383. [2] = "网络搜索中",
  384. [3] = "网络注册被拒绝",
  385. [4] = "网络状态未知",
  386. [5] = "网络已注册,漫游",
  387. [6] = "网络已注册,仅SMS",
  388. [7] = "网络已注册,漫游,仅SMS",
  389. [8] = "网络已注册,紧急服务",
  390. [9] = "网络已注册,非主要服务",
  391. [10] = "网络已注册,非主要服务,漫游",
  392. }
  393. while true do
  394. -- 打印网络状态
  395. if mobile.status() ~= 1 then log.debug("mobile.status:", codes[mobile.status() or 0] or "未知网络状态") end
  396. -- 消息队列非空, 且网络已注册
  397. if next(msg_queue) ~= nil and (mobile.status() == 1 or mobile.status() == 5) then
  398. log.debug("util_notify.poll", "轮询消息队列中, 当前队列长度:", #msg_queue)
  399. item = msg_queue[1]
  400. table.remove(msg_queue, 1)
  401. if item.retry > (config.NOTIFY_RETRY_MAX or 100) then
  402. log.error("util_notify.poll", "超过最大重发次数", "msg:", item.msg)
  403. else
  404. result = util_notify.send(item.msg, item.channel)
  405. item.retry = item.retry + 1
  406. if not result then
  407. -- 发送失败, 移到队尾
  408. table.insert(msg_queue, item)
  409. sys.wait(5000)
  410. end
  411. end
  412. if item.retry % 10 == 0 then
  413. mobile.reset()
  414. log.warn("util_notify.poll", "重发次数太多, 重启 LTE 协议栈")
  415. end
  416. sys.wait(50)
  417. else
  418. sys.waitUntil("NEW_MSG", 1000 * 10)
  419. end
  420. end
  421. end
  422. sys.taskInit(poll)
  423. return util_notify