| 59 | 1 local Luan = require "luan:Luan.luan" | 
|  | 2 local error = Luan.error | 
|  | 3 local pairs = Luan.pairs or error() | 
|  | 4 local Table = require "luan:Table.luan" | 
|  | 5 local concat = Table.concat or error() | 
|  | 6 local is_empty = Table.is_empty or error() | 
|  | 7 local Http = require "luan:http/Http.luan" | 
|  | 8 local Shared = require "site:/lib/Shared.luan" | 
|  | 9 local http_push_to_users = Shared.http_push_to_users or error() | 
|  | 10 local User = require "site:/lib/User.luan" | 
|  | 11 local current_user = User.current or error() | 
|  | 12 local get_user_by_email = User.get_by_email or error() | 
|  | 13 local Utils = require "site:/lib/Utils.luan" | 
|  | 14 local to_set = Utils.to_set or error() | 
|  | 15 local Db = require "site:/lib/Db.luan" | 
|  | 16 local run_in_transaction = Db.run_in_transaction or error() | 
|  | 17 local Chat = require "site:/lib/Chat.luan" | 
|  | 18 local get_chat_by_user_ids = Chat.get_by_user_ids or error() | 
|  | 19 | 
|  | 20 | 
|  | 21 return function() | 
|  | 22 	local with = Http.request.parameters.with | 
|  | 23 	local user = current_user() | 
|  | 24 	with = to_set(with) | 
|  | 25 	if user == nil then | 
|  | 26 		local url = "/login.html" | 
|  | 27 		if not is_empty(with) then | 
|  | 28 			local t = {} | 
|  | 29 			for email in pairs(with) do | 
|  | 30 				t[#t+1] = "with="..email | 
|  | 31 			end | 
|  | 32 			url = url.."?"..concat(t,"&") | 
|  | 33 		end | 
|  | 34 		Http.response.send_redirect(url) | 
|  | 35 		return | 
|  | 36 	end | 
|  | 37 	if is_empty(with) then | 
|  | 38 		Http.response.send_redirect("/") | 
|  | 39 		return | 
|  | 40 	end | 
|  | 41 	with[user.email] = true | 
|  | 42 	local ids = {} | 
|  | 43 	for email in pairs(with) do | 
|  | 44 		local with_user = get_user_by_email(email) or error() | 
|  | 45 		local id = with_user.id | 
|  | 46 		ids[#ids+1] = id | 
|  | 47 	end | 
|  | 48 	local need_push = false | 
|  | 49 	local chat = run_in_transaction( function() | 
|  | 50 		local chat = get_chat_by_user_ids(ids) | 
|  | 51 		if chat == nil then | 
|  | 52 			chat = Chat.new{ | 
|  | 53 				user_ids = ids | 
|  | 54 			} | 
|  | 55 			chat.save() | 
|  | 56 			need_push = true | 
|  | 57 		end | 
|  | 58 		return chat | 
|  | 59 	end ) | 
|  | 60 	if need_push then | 
|  | 61 		local js = "getChats('"..chat.id.."')" | 
|  | 62 		http_push_to_users( chat.user_ids, js ) | 
|  | 63 	end | 
|  | 64 	Http.response.send_redirect("/?chat="..chat.id) | 
|  | 65 end |