2019-10-23 12:38:11 +00:00
|
|
|
defmodule UiWeb.MorseLive do
|
|
|
|
use Phoenix.LiveView
|
2020-04-17 20:20:24 +00:00
|
|
|
require Logger
|
2019-10-23 12:38:11 +00:00
|
|
|
|
|
|
|
@topic "morse_progress"
|
|
|
|
|
|
|
|
def render(assigns) do
|
|
|
|
UiWeb.PageView.render("morse.html", assigns)
|
|
|
|
end
|
|
|
|
|
2019-10-24 20:58:09 +00:00
|
|
|
def mount(%{ip: ip}, socket) do
|
2019-10-23 12:38:11 +00:00
|
|
|
UiWeb.Endpoint.subscribe(@topic)
|
2019-10-24 20:58:09 +00:00
|
|
|
{:ok, assign(socket, default_assigns(ip))}
|
2019-10-23 12:38:11 +00:00
|
|
|
end
|
|
|
|
|
2019-10-25 11:33:22 +00:00
|
|
|
def handle_event("toggle_morse", _value, %{assigns: %{ip: ip}} = socket) do
|
2020-04-17 20:20:24 +00:00
|
|
|
Logger.info("#{ip} pressed the button!")
|
|
|
|
|
2019-10-30 19:31:58 +00:00
|
|
|
if not Morse.Server.in_progress?() and ip_send_message?(ip) do
|
2020-04-17 20:20:24 +00:00
|
|
|
Logger.info("Sending Telegram message.")
|
2019-10-30 19:31:58 +00:00
|
|
|
spawn(fn -> Ui.TelegramBot.message("#{ip} pressed the button!") end)
|
2019-10-24 20:58:09 +00:00
|
|
|
end
|
2019-10-25 14:30:13 +00:00
|
|
|
|
2019-10-25 11:33:22 +00:00
|
|
|
Morse.Server.toggle_morse()
|
2019-10-24 20:58:09 +00:00
|
|
|
|
2019-10-23 12:38:11 +00:00
|
|
|
{:noreply, socket}
|
|
|
|
end
|
|
|
|
|
2019-10-24 19:07:26 +00:00
|
|
|
def handle_event("toggle_hint", _value, socket) do
|
|
|
|
{:noreply, update(socket, :hints_visible, &(not &1))}
|
|
|
|
end
|
|
|
|
|
2019-10-23 12:38:11 +00:00
|
|
|
def handle_info(progress, socket) do
|
2019-10-24 19:07:26 +00:00
|
|
|
{:noreply, assign(socket, progress: progress, in_progress?: Morse.Server.in_progress?())}
|
2019-10-23 12:38:11 +00:00
|
|
|
end
|
2019-10-24 14:54:50 +00:00
|
|
|
|
2019-10-24 20:58:09 +00:00
|
|
|
defp default_assigns(ip) do
|
2019-10-24 14:54:50 +00:00
|
|
|
[
|
|
|
|
progress: Morse.Server.progress(),
|
2019-10-24 19:07:26 +00:00
|
|
|
in_progress?: Morse.Server.in_progress?(),
|
2019-10-24 20:58:09 +00:00
|
|
|
hints_visible: false,
|
|
|
|
ip: ip
|
2019-10-24 14:54:50 +00:00
|
|
|
]
|
|
|
|
end
|
2019-10-30 19:31:58 +00:00
|
|
|
|
|
|
|
defp ip_send_message?(ip) do
|
|
|
|
not (String.starts_with?(ip, "192.168.") or String.starts_with?(ip, "10.")
|
|
|
|
or ip == "127.0.0.1" or ip == "localhost" or ip == "0.0.0.0")
|
|
|
|
end
|
2019-10-23 12:38:11 +00:00
|
|
|
end
|