Mercurial Hosting > chat
view src/lib/Notify.luan @ 110:d2637760cd00 default tip
better notification
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 15 Sep 2025 13:29:10 -0600 |
parents | 46418395c860 |
children |
line wrap: on
line source
local Luan = require "luan:Luan.luan" local error = Luan.error local ipairs = Luan.ipairs or error() local pairs = Luan.pairs or error() local stringify = Luan.stringify or error() local Time = require "luan:Time.luan" local time_now = Time.now or error() local Thread = require "luan:Thread.luan" local Http = require "luan:http/Http.luan" local Chat = require "site:/lib/Chat.luan" local User = require "site:/lib/User.luan" local get_user_by_id = User.get_by_id or error() local Db = require "site:/lib/Db.luan" local run_in_transaction = Db.run_in_transaction or error() local Shared = require "site:/lib/Shared.luan" local send_mail = Shared.send_mail or error() local Utils = require "site:/lib/Utils.luan" local shallow_copy = Utils.shallow_copy or error() local Logging = require "luan:logging/Logging.luan" local logger = Logging.logger "Notify" local Notify = {} local base_url = Http.domain and "https://"..Http.domain or "http://localhost:8080" local wait = Time.period{seconds=10} local function set_notified(user,was_notified) run_in_transaction( function() user = user.reload() user.was_notified = was_notified user.save() end ) end local function init() local users = {} local fns = {} function fns.notify(user_ids,mute_ids,user_name,post_content,chat_id) local now = time_now() for _, user_id in ipairs(user_ids) do local user = get_user_by_id(user_id) if users[user_id] == nil \ and user.notify_email ~= nil \ and not mute_ids[user_id] \ and (user.multi_notify or not user.was_notified) \ then send_mail { To = user.notify_email Subject = "Message from "..user_name body = `%> <%= post_content %> <%= base_url %>/?chat=<%= chat_id %> To unsubscribe: <%= base_url %>/unsubscribe.html?user=<%=user_id%>&password=<%=user.password%> <% ` } if not user.multi_notify then set_notified(user,true) end end end end function fns.active(user_id) users[user_id] = time_now() -- logger.info("active "..user_id) end function fns.remove() -- logger.info("remove") local now = time_now() for user_id, when in pairs(shallow_copy(users)) do if now - when > wait then users[user_id] = nil end end end return fns end local glob = Thread.global_callable("notify",init) function Notify.notify(chat,post,user) Thread.run(function() local user_name = user.name or user.email glob.notify(chat.user_ids,chat.mute_ids,user_name,post.content,chat.id) end) end function Notify.active(user) Thread.run(function() glob.active(user.id) if user.was_notified then set_notified(user,false) end end) end Thread.schedule( glob.remove, { repeating_delay=Time.period{seconds=10} } ) return Notify