Mercurial Hosting > chat
diff src/chat.luan @ 59:8270106644db
add chat.luan
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 04 Mar 2025 08:22:45 -0700 |
parents | |
children | a47036fd0158 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/chat.luan Tue Mar 04 08:22:45 2025 -0700 @@ -0,0 +1,65 @@ +local Luan = require "luan:Luan.luan" +local error = Luan.error +local pairs = Luan.pairs or error() +local Table = require "luan:Table.luan" +local concat = Table.concat or error() +local is_empty = Table.is_empty or error() +local Http = require "luan:http/Http.luan" +local Shared = require "site:/lib/Shared.luan" +local http_push_to_users = Shared.http_push_to_users or error() +local User = require "site:/lib/User.luan" +local current_user = User.current or error() +local get_user_by_email = User.get_by_email or error() +local Utils = require "site:/lib/Utils.luan" +local to_set = Utils.to_set or error() +local Db = require "site:/lib/Db.luan" +local run_in_transaction = Db.run_in_transaction or error() +local Chat = require "site:/lib/Chat.luan" +local get_chat_by_user_ids = Chat.get_by_user_ids or error() + + +return function() + local with = Http.request.parameters.with + local user = current_user() + with = to_set(with) + if user == nil then + local url = "/login.html" + if not is_empty(with) then + local t = {} + for email in pairs(with) do + t[#t+1] = "with="..email + end + url = url.."?"..concat(t,"&") + end + Http.response.send_redirect(url) + return + end + if is_empty(with) then + Http.response.send_redirect("/") + return + end + with[user.email] = true + local ids = {} + for email in pairs(with) do + local with_user = get_user_by_email(email) or error() + local id = with_user.id + ids[#ids+1] = id + end + local need_push = false + local chat = run_in_transaction( function() + local chat = get_chat_by_user_ids(ids) + if chat == nil then + chat = Chat.new{ + user_ids = ids + } + chat.save() + need_push = true + end + return chat + end ) + if need_push then + local js = "getChats('"..chat.id.."')" + http_push_to_users( chat.user_ids, js ) + end + Http.response.send_redirect("/?chat="..chat.id) +end