-
Notifications
You must be signed in to change notification settings - Fork 979
/
messages.cljs
71 lines (63 loc) · 2.19 KB
/
messages.cljs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
(ns syng-im.models.messages
(:require [syng-im.persistence.realm :as r]
[re-frame.core :refer [dispatch]]
[cljs.reader :refer [read-string]]
[syng-im.utils.random :refer [timestamp]]
[syng-im.db :as db]
[syng-im.utils.logging :as log]
[clojure.string :refer [join split]]
[clojure.walk :refer [stringify-keys keywordize-keys]]
[syng-im.constants :as c]))
(defn- map-to-str
[m]
(join ";" (map #(join "=" %) (stringify-keys m))))
(defn- str-to-map
[s]
(keywordize-keys (apply hash-map (split s #"[;=]"))))
(def default-values
{:outgoing false
:to nil
:same-author false
:same-direction false})
(defn save-message
;; todo remove chat-id parameter
[chat-id {:keys [msg-id content]
:as message}]
(when-not (r/exists? :msgs :msg-id msg-id)
(r/write
(fn []
(let [content' (if (string? content)
content
(map-to-str content))
message' (merge default-values
message
{:chat-id chat-id
:content content'
:timestamp (timestamp)
:delivery-status nil})]
(r/create :msgs message' true))))))
(defn command-type? [type]
(contains?
#{c/content-type-command c/content-type-command-request}
type))
(defn get-messages [chat-id]
(->> (-> (r/get-by-field :msgs :chat-id chat-id)
(r/sorted :timestamp :asc)
(r/collection->map))
(into '())
(map (fn [{:keys [content-type] :as message}]
(if (command-type? content-type)
(update message :content str-to-map)
message)))))
(defn update-message! [{:keys [msg-id] :as msg}]
(log/debug "update-message!" msg)
(r/write
(fn []
(when (r/exists? :msgs :msg-id msg-id)
(r/create :msgs msg true)))))
(defn clear-history [chat-id]
(r/write
(fn []
(r/delete (r/get-by-field :msgs :chat-id chat-id))))
;; TODO temp. Update chat in db atom
(dispatch [:initialize-chats]))