-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstarjump_socket.ex
More file actions
70 lines (55 loc) · 1.85 KB
/
Copy pathstarjump_socket.ex
File metadata and controls
70 lines (55 loc) · 1.85 KB
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
defmodule StarjumpsWeb.Websockets.StarjumpSocket do
@moduledoc """
`Phoenix.Socket.Transport` implementation for sending star jump images
to the client connection.
"""
@behaviour Phoenix.Socket.Transport
require Logger
alias Starjumps.{Starjumping, JumpRates}
@base_mount_path "/star-jumping"
@doc """
The base path used to mount on the EndPoint, without the token
"""
@spec base_mount_path :: String.t()
def base_mount_path, do: @base_mount_path
@impl true
def child_spec(_opts) do
# Nothing to do here, so noop.
%{id: Task, start: {Task, :start_link, [fn -> :ok end]}, restart: :transient}
end
@impl true
def connect(%{params: %{"token" => token, "jump_rate" => jump_rate}}) do
{:ok, %{token: token, jump_rate: String.to_integer(jump_rate)}}
end
@impl true
def init(%{token: token, jump_rate: jump_rate} = args) do
debug_msg(fn -> "init with #{inspect(args)}" end)
send(self(), :send_image)
JumpRates.subscribe(token)
{:ok, %{next_image_in: jump_rate, jump: 0}}
end
@impl true
def handle_in({message, opts}, state) do
debug_msg(fn -> "handle_in with message: #{inspect(message)}, opts: #{inspect(opts)}" end)
{:ok, state}
end
@impl true
def handle_info(:send_image, %{jump: jump, next_image_in: send_after} = state) do
Process.send_after(self(), :send_image, send_after)
{:push, {:binary, Starjumping.image(jump)}, %{state | jump: jump + 1}}
end
def handle_info({:jump_rate_change, new_next_image_in}, state) do
{:ok, %{state | next_image_in: new_next_image_in}}
end
def handle_info(_, state) do
{:ok, state}
end
@impl true
def terminate(reason, _state) do
debug_msg(fn -> "terminating because #{inspect(reason)}" end)
:ok
end
defp debug_msg(msg_fn) do
Logger.debug(fn -> "StarjumpSocket #{inspect(self())} " <> msg_fn.() end)
end
end