-
Notifications
You must be signed in to change notification settings - Fork 25
/
document_channel.ex
86 lines (75 loc) · 2.14 KB
/
document_channel.ex
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
defmodule Docs.DocumentChannel do
use Docs.Web, :channel
alias Docs.Document
import SweetXml
def join("documents:" <> doc_id, params, socket) do
send(self, {:after_join, params})
{:ok, assign(socket, :doc_id, doc_id)}
end
def handle_info({:after_join, params}, socket) do
doc = Repo.get(Document, socket.assigns.doc_id)
messages = Repo.all(
from m in assoc(doc, :messages),
order_by: [desc: m.inserted_at],
select: %{id: m.id, body: m.body},
where: m.id > ^params["last_message_id"],
limit: 100
)
push socket, "messages", %{messages: messages}
{:noreply, socket}
end
def handle_in("text_change", %{"ops" => ops}, socket) do
broadcast_from! socket, "text_change", %{
ops: ops
}
{:reply, :ok, socket}
end
def handle_in("save", params, socket) do
Document
|> Repo.get(socket.assigns.doc_id)
|> Document.changeset(params)
|> Repo.update()
|> case do
{:ok, _document} ->
{:reply, :ok, socket}
{:error, changeset} ->
{:reply, {:error, %{reasons: changeset}}, socket}
end
end
def handle_in("new_message", params, socket) do
changeset =
Document
|> Repo.get(socket.assigns.doc_id)
|> Ecto.Model.build(:messages)
|> Message.changeset(params)
case Repo.insert(changeset) do
{:ok, msg} ->
broadcast! socket, "new_message", %{body: msg.body}
{:reply, :ok, socket}
{:error, changeset} ->
{:reply, {:error, %{reasons: changeset}}, socket}
end
end
def handle_in("compute_img", params, socket) do
img_url =
case Docs.InfoSys.compute_img(params["expr"]) do
[%{img_url: img_url} | _] -> img_url
_ -> ""
end
broadcast! socket, "insert_img", %{
start: params["start"],
end: params["end"],
url: img_url
}
{:reply, :ok, socket}
end
def handle_in("selection_change", params, socket) do
broadcast_from! socket, "selection_change", %{
user_id: params["user_id"],
username: params["username"],
color: params["color"],
end: params["end"]
}
{:reply, :ok, socket}
end
end