diff options
author | Alex Auvolat <alex@adnab.me> | 2018-07-03 15:42:17 +0200 |
---|---|---|
committer | Alex Auvolat <alex@adnab.me> | 2018-07-03 15:42:17 +0200 |
commit | 8f3009715ee9ccdd7ecb54fea1244a32a29b62c0 (patch) | |
tree | 416fb96c39effa4217864bb6a93243803ba8edba /lib/web | |
download | shard-8f3009715ee9ccdd7ecb54fea1244a32a29b62c0.tar.gz shard-8f3009715ee9ccdd7ecb54fea1244a32a29b62c0.zip |
Initialize shard repo with code from somewhere
Diffstat (limited to 'lib/web')
-rw-r--r-- | lib/web/httprouter.ex | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/lib/web/httprouter.ex b/lib/web/httprouter.ex new file mode 100644 index 0000000..5027df4 --- /dev/null +++ b/lib/web/httprouter.ex @@ -0,0 +1,53 @@ +defmodule SWeb.HTTPRouter do + use Plug.Router + use Plug.ErrorHandler + + plug Plug.Parsers, parsers: [:urlencoded, :multipart] + + plug :match + plug :dispatch + + get "/" do + main_page(conn) + end + + post "/" do + if Map.has_key?(conn.params, "msg") do + SApp.Chat.send(conn.params["msg"]) + end + if Map.has_key?(conn.params, "nick") do + Shard.Identity.set_nickname(conn.params["nick"]) + end + if Map.has_key?(conn.params, "peer") do + [ipstr, portstr] = String.split(conn.params["peer"], ":") + {:ok, ip} = :inet.parse_address (to_charlist ipstr) + {port, _} = Integer.parse portstr + SNet.TCPServer.add_peer(ip, port) + end + + main_page(conn) + end + + match _ do + send_resp(conn, 404, "Oops!") + end + + def main_page(conn) do + {:ok, messages, _} = GenServer.call(SApp.Chat.Log, {:read, nil, 42}) + + msgtxt = messages + |> Enum.map(fn {ts, nick, msg} -> "#{ts |> DateTime.from_unix! |> DateTime.to_iso8601} <#{nick}> #{msg}\n" end) + + peerlist = SNet.ConnSupervisor + |> DynamicSupervisor.which_children + |> Enum.map(fn {_, pid, _, _} -> "#{GenServer.call(pid, :get_host_str)}\n" end) + + conn + |> put_resp_content_type("text/html") + |> send_resp(200, "<pre>#{msgtxt}</pre>" <> + "<form method=POST><input type=text name=msg /><input type=submit value=send /></form>" <> + "<form method=POST><input type=text name=nick value=\"#{Shard.Identity.get_nickname}\" /><input type=submit value=\"change nick\" /></form>" <> + "<hr/><pre>#{peerlist}</pre>" <> + "<form method=POST><input type=text name=peer /><input type=submit value=\"add peer\" /></form>") + end +end |