birdy_chat/lib/birdy_chat/identity.ex

56 lines
1.3 KiB
Elixir

defmodule BirdyChat.Identity do
use Agent
defstruct [:identity, :peers, :mode]
def start_link(opts) do
name = opts[:name] || __MODULE__
input = opts[:input]
Agent.start_link(fn -> initialise(input) end, name: name)
end
def mode(pid \\ __MODULE__) do
Agent.get(pid, & &1.mode)
end
def identity(pid \\ __MODULE__) do
Agent.get(pid, & &1.identity)
end
def peers(pid \\ __MODULE__) do
Agent.get(pid, & &1.peers)
end
def parse_identity(value) do
case Integer.parse(value) do
{_number, ""} -> value
_ -> raise "Identity must be a string that can be converted to Integer, got: >>#{value}<<."
end
end
def parse_peers(peers) do
values = String.split(peers, ";")
for value <- values,
[identity, address] = String.split(value, "::"), into: %{} do
{identity, address}
end
end
def initialise(%{peers: peers, identity: identity}) do
peers = parse_peers(peers)
identity = parse_identity(identity)
%__MODULE__{identity: identity, peers: peers, mode: :connected}
end
def initialise(nil) do
identity = System.get_env("BIRDY_CHAT_IDENTITY")
peers = System.get_env("BIRDY_CHAT_PEERS")
case {identity, peers} do
{nil, nil} -> %__MODULE__{identity: "test", peers: [], mode: :singleton}
end
end
end