diff src/chat.html.luan @ 4:2da10ece826f

add Chat
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 27 Oct 2024 20:39:18 -0600
parents src/login_sent.html.luan@2c63b10781e1
children a49866b52cc2
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/chat.html.luan	Sun Oct 27 20:39:18 2024 -0600
@@ -0,0 +1,93 @@
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local ipairs = Luan.ipairs or error()
+local pairs = Luan.pairs or error()
+local Table = require "luan:Table.luan"
+local concat = Table.concat or error()
+local Io = require "luan:Io.luan"
+local Http = require "luan:http/Http.luan"
+local Shared = require "site:/lib/Shared.luan"
+local head = Shared.head or error()
+local header = Shared.header or error()
+local User = require "site:/lib/User.luan"
+local current_user = User.current_required or error()
+local get_user_by_id = User.get_by_id 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 chat_search = Chat.search or error()
+
+
+local function other_users(user,chat)
+	local my_id = user.id
+	local t = {}
+	for _, user_id in ipairs(chat.user_ids) do
+		if user_id ~= my_id then
+			local other_user = get_user_by_id(user_id) or error()
+			t[#t+1] = other_user.email
+		end
+	end
+	return concat( t, ", " )
+end
+
+local function get_chat(with)
+	local t = {}
+	local ids = {}
+	for email in pairs(with) do
+		local with_user = get_user_by_email(email) or error()
+		local id = with_user.id
+		t[#t+1] = "+chat_user_ids:"..id
+		ids[#ids+1] = id
+	end
+	local query = concat(t," ")
+	run_in_transaction( function()
+		local chats = chat_search(query)
+		local n = #chats
+		if n == 0 then
+			local chat = Chat.new{
+				user_ids = ids
+			}
+			chat.save()
+			return chat
+		elseif n == 1 then
+			return chats[1]
+		else
+			error("multiple chats for: "..query)
+		end
+	end )
+end
+
+return function()
+	local user = current_user()
+	if user == nil then
+		return
+	end
+	local with = Http.request.parameters.with
+	if with ~= nil then
+		with = to_set(with)
+		with[user.email] = true
+		get_chat(with)
+	end
+	local chats = user.get_chats()
+	Io.stdout = Http.response.text_writer()
+%>
+<!doctype html>
+<html>
+	<head>
+<%		head() %>
+	</head>
+	<body>
+<%		header() %>
+		<div content>
+			<h1>Chat</h1>
+<%	for _, chat in ipairs(chats) do %>
+			<p><%= other_users(user,chat) %></p>
+<%	end %>
+		</div>
+	</body>
+</html>
+<%
+end