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