4
|
1 local Luan = require "luan:Luan.luan"
|
|
2 local error = Luan.error
|
|
3 local ipairs = Luan.ipairs or error()
|
7
|
4 local Table = require "luan:Table.luan"
|
|
5 local concat = Table.concat or error()
|
|
6 local is_empty = Table.is_empty or error()
|
4
|
7 local Time = require "luan:Time.luan"
|
|
8 local time_now = Time.now or error()
|
12
|
9 local Http = require "luan:http/Http.luan"
|
4
|
10 local Db = require "site:/lib/Db.luan"
|
|
11 local run_in_transaction = Db.run_in_transaction or error()
|
12
|
12 local Utils = require "site:/lib/Utils.luan"
|
|
13 local base_url = Utils.base_url or error()
|
4
|
14
|
|
15
|
|
16 local Chat = {}
|
|
17
|
|
18 local function from_doc(doc)
|
|
19 doc.type == "chat" or error "wrong type"
|
|
20 return Chat.new {
|
|
21 id = doc.id
|
|
22 user_ids = doc.chat_user_ids
|
|
23 updated = doc.chat_updated
|
|
24 }
|
|
25 end
|
|
26
|
|
27 local function to_doc(chat)
|
|
28 return {
|
|
29 type = "chat"
|
|
30 id = chat.id
|
|
31 chat_user_ids = chat.user_ids or error()
|
|
32 chat_updated = chat.updated or error()
|
|
33 }
|
|
34 end
|
|
35
|
|
36 function Chat.new(chat)
|
|
37 chat.updated = chat.updated or time_now()
|
|
38
|
|
39 function chat.save()
|
|
40 local doc = to_doc(chat)
|
|
41 Db.save(doc)
|
|
42 chat.id = doc.id
|
|
43 end
|
|
44
|
|
45 function chat.delete()
|
|
46 run_in_transaction( function()
|
|
47 local id = chat.id
|
11
|
48 Db.delete("post_chat_id:"..id)
|
4
|
49 Db.delete("id:"..id)
|
|
50 end )
|
|
51 end
|
|
52
|
7
|
53 function chat.other_users_email(user)
|
|
54 local User = require "site:/lib/User.luan"
|
|
55 local get_user_by_id = User.get_by_id or error()
|
|
56
|
|
57 local my_id = user.id
|
|
58 local t = {}
|
|
59 for _, user_id in ipairs(chat.user_ids) do
|
|
60 if user_id ~= my_id then
|
|
61 local other_user = get_user_by_id(user_id) or error()
|
|
62 t[#t+1] = other_user.email
|
|
63 end
|
|
64 end
|
|
65 return concat( t, ", " )
|
|
66 end
|
|
67
|
12
|
68 function chat.http_push(message)
|
|
69 local url = base_url().."/chat/"..chat.id
|
|
70 Http.push(url,message)
|
|
71 end
|
|
72
|
4
|
73 return chat
|
|
74 end
|
|
75
|
|
76 function Chat.search(query,sort,rows)
|
|
77 rows = rows or 1000000
|
|
78 local chats = {}
|
|
79 local docs = Db.search(query,1,rows,{sort=sort})
|
|
80 for _, doc in ipairs(docs) do
|
|
81 chats[#chats+1] = from_doc(doc)
|
|
82 end
|
|
83 return chats
|
|
84 end
|
|
85
|
7
|
86 function Chat.get_by_id(id)
|
|
87 local doc = Db.get_document("id:"..id)
|
|
88 return doc and doc.type=="chat" and from_doc(doc) or nil
|
|
89 end
|
|
90
|
4
|
91 return Chat
|