Packages
guard
0.10.4
0.19.1
0.19.0
0.18.0
0.17.2
0.17.1
0.17.0
0.16.3
0.16.2
0.16.1
0.16.0
0.15.3
0.15.2
0.15.1
0.15.0
0.14.9
0.14.8
0.14.7
0.14.6
0.14.5
0.14.4
0.14.3
0.14.2
0.14.1
0.14.0
0.13.1
0.13.0
0.12.9
0.12.8
0.12.7
0.12.6
0.12.5
0.12.4
0.12.3
0.12.2
0.12.1
0.12.0
0.11.3
0.11.2
0.11.1
0.11.0
0.10.4
0.10.3
0.10.2
0.10.1
0.10.0
0.9.0
0.8.0
0.7.1
0.7.0
0.6.1
0.6.0
0.5.0
0.4.1
0.4.0
0.3.0
0.2.0
0.1.0
Useful package for dealing with user authentication and signup
Current section
Files
Jump to
Current section
Files
lib/guard/pusher/server.ex
defmodule Guard.Pusher.Server do
use GenServer
use Tesla
adapter Tesla.Adapter.Hackney
def start_link(name, config) do
GenServer.start_link(__MODULE__, config, name: name)
end
def send_user_message(pid, user, message, callback) do
GenServer.cast(pid, {:user, user, message, callback})
end
def send_message(pid, message, callback) do
GenServer.cast(pid, {:message, message, callback})
end
def status(pid) do
GenServer.call(pid, {:status})
end
## GenServer Callbacks
def init(config) do
client = Tesla.client([
{Tesla.Middleware.BaseUrl, "https://fcm.googleapis.com/fcm"},
{Tesla.Middleware.Headers, [{"Authorization", "key=" <> (config[:key] || "") }]},
Tesla.Middleware.JSON
])
{:ok, %{options: config[:options], client: client}}
end
def handle_call({:status}, _from, state) do
{:reply, {:ok, state}, state}
end
def handle_cast({:user, user, message, callback}, state) do
devices = Guard.Users.list_devices(user)
if length(devices) > 0 do
Enum.each(devices, fn(d) ->
resp = try do
resp = do_post(state.client, state.options, Map.merge(message, %{to: d.token}))
if resp.body != nil do
if resp.body["failure"] == 1 do
Guard.Repo.delete(d)
end
end
resp
rescue
error -> {:error, error}
end
if !is_nil(callback) do
callback.(resp)
end
end)
end
{:noreply, state, :hibernate}
end
def handle_cast({:message, message, callback}, state) do
resp = try do
do_post(state.client, state.options, message)
rescue
error -> {:error, error}
end
if !is_nil(callback) do
callback.(resp)
end
{:noreply, state, :hibernate}
end
defp do_post(client, options, message) do
msg = Map.merge(options, message)
post!(client, "/send", msg)
end
end