Mercurial Hosting > chat
view src/lib/Chat.luan @ 33:e2b7f6393dab
add online
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sun, 10 Nov 2024 19:57:14 -0700 |
parents | 9f45d32670ae |
children | 42b741a1d5c6 |
line wrap: on
line source
local Luan = require "luan:Luan.luan" local error = Luan.error local ipairs = Luan.ipairs or error() local Time = require "luan:Time.luan" local time_now = Time.now or error() local Http = require "luan:http/Http.luan" local Db = require "site:/lib/Db.luan" local run_in_transaction = Db.run_in_transaction or error() local Utils = require "site:/lib/Utils.luan" local base_url = Utils.base_url or error() local Chat = {} local function from_doc(doc) doc.type == "chat" or error "wrong type" return Chat.new { id = doc.id user_ids = doc.chat_user_ids updated = doc.chat_updated } end local function to_doc(chat) return { type = "chat" id = chat.id chat_user_ids = chat.user_ids or error() chat_updated = chat.updated or error() } end function Chat.new(chat) chat.updated = chat.updated or time_now() function chat.save() local doc = to_doc(chat) Db.save(doc) chat.id = doc.id end function chat.delete() run_in_transaction( function() local id = chat.id Db.delete("post_chat_id:"..id) Db.delete("id:"..id) end ) end function chat.http_push(message) local url = base_url().."/chat/"..chat.id Http.push(url,message) end return chat end function Chat.search(query,sort,rows) rows = rows or 1000000 local chats = {} local docs = Db.search(query,1,rows,{sort=sort}) for _, doc in ipairs(docs) do chats[#chats+1] = from_doc(doc) end return chats end function Chat.get_by_id(id) local doc = Db.get_document("id:"..id) return doc and doc.type=="chat" and from_doc(doc) or nil end return Chat