aboutsummaryrefslogtreecommitdiff
path: root/lib/app/chat.ex
diff options
context:
space:
mode:
Diffstat (limited to 'lib/app/chat.ex')
-rw-r--r--lib/app/chat.ex38
1 files changed, 33 insertions, 5 deletions
diff --git a/lib/app/chat.ex b/lib/app/chat.ex
index 42991ce..a9cfb1e 100644
--- a/lib/app/chat.ex
+++ b/lib/app/chat.ex
@@ -39,7 +39,15 @@ defmodule SApp.Chat do
GenServer.cast(Shard.Manager, {:register, id, manifest, self()})
GenServer.cast(self(), :init_pull)
- {:ok, %{channel: channel, id: id, manifest: manifest, store: store, peers: MapSet.new}}
+ {:ok,
+ %{channel: channel,
+ id: id,
+ manifest: manifest,
+ store: store,
+ peers: MapSet.new,
+ subs: MapSet.new,
+ }
+ }
end
@doc """
@@ -49,6 +57,11 @@ defmodule SApp.Chat do
{:reply, state.manifest, state}
end
+ def handle_call({:read_history, start, num}, _from, state) do
+ ret = ML.read(state.store, start, num)
+ {:reply, ret, state}
+ end
+
@doc """
Implementation of the :redundant handler: if another process is already
synchronizing this channel then we exit.
@@ -80,6 +93,12 @@ defmodule SApp.Chat do
msg}
new_state = %{state | store: ML.insert(state.store, msgitem)}
+ for pid <- state.subs do
+ if Process.alive?(pid) do
+ send(pid, {:chat_send, state.channel, msgitem})
+ end
+ end
+
for peer <- state.peers do
push_messages(new_state, peer, nil, 5)
end
@@ -97,6 +116,11 @@ defmodule SApp.Chat do
{:noreply, %{ state | peers: new_peers }}
end
+ def handle_cast({:subscribe, pid}, state) do
+ new_subs = MapSet.put(state.subs, pid)
+ {:noreply, %{ state | subs: new_subs }}
+ end
+
@doc """
Implementation of the :msg handler, which is the main handler for messages
comming from other peers concerning this chat room.
@@ -110,7 +134,7 @@ defmodule SApp.Chat do
case msg do
{:get_manifest} ->
Shard.Manager.send(peer_id, {state.id, {:manifest, state.manifest}})
- {:get, start} -> push_messages(peer_id, state, start, 20)
+ {:get, start} -> push_messages(state, peer_id, start, 20)
{:info, _start, list, rest} ->
if rest != nil and not ML.has(state.store, rest) do
Shard.Manager.send(peer_id, {state.id, {:get, rest}})
@@ -131,7 +155,7 @@ defmodule SApp.Chat do
end
def handle_cast({:deferred_insert, list}, state) do
- new_store = ML.insert_many(state.store, list, (fn msg -> msg_callback(state.channel, msg) end))
+ new_store = ML.insert_many(state.store, list, (fn msg -> msg_callback(state, msg) end))
{:noreply, %{state | store: new_store}}
end
@@ -143,8 +167,12 @@ defmodule SApp.Chat do
end
end
- defp msg_callback(chan, {ts, nick, msg}) do
- IO.puts "#{ts |> DateTime.from_unix! |> DateTime.to_iso8601} ##{chan} <#{nick}> #{msg}"
+ defp msg_callback(state, {ts, nick, msg}) do
+ for pid <- state.subs do
+ if Process.alive?(pid) do
+ send(pid, {:chat_recv, state.channel, {ts, nick, msg}})
+ end
+ end
end
defp msg_cmp({ts1, nick1, msg1}, {ts2, nick2, msg2}) do