Current section

Files

Jump to
urbit_ex lib urbit_ex.ex
Raw

lib/urbit_ex.ex

defmodule UrbitEx do
@moduledoc """
Main API for the UrbitEx Package.
Initializes the Urbit ship, logs in, opens an Eyre channel and starts an Server-side event pipeline.
Start the connection with UrbitEx.start/2
Subscribe to event streams with UrbitEx.subscribe.
Once subscribed, Urbit server-side events will be sent as messages from the GenServer process to the current process.
Set up your own logic to respond to events sent from Urbit inside UrbitEx.recv().
"""
@doc """
Starts the Urbit instance.
## Examples
iex> {:ok, pid} = UrbitEx.start("http://localhost:8080", "sampel-dozzod-mirtyl-marzod")
"""
def start(url, code) do
{:ok, pid} = UrbitEx.Server.start_link(url: url, code: code)
consume_feed(pid)
{:ok, pid}
end
@doc """
Sets the current process as consumer of the Urbit Ship's Eventstream.
Every Urbit event will be sent from the Urbit GenServer to the current process.
"""
defp consume_feed(pid) do
GenServer.cast(pid, {:consume, self()})
end
@doc """
Subscribes to event streams. Takes the pid of the connection (returned by UrbitExstart()),
and a list of subscriptions. If it's a single subscription you want just wrap it in a list.
"""
def subscribe(pid, subscriptions) do
GenServer.cast(pid, {:subscribe, subscriptions})
end
def check_state(pid) do
GenServer.call(pid, :get)
end
@doc """
Starts a recursive loop that reacts to events received from your Urbit ship.
Set up your own logic inside the receive loop.
"""
def recv() do
receive do
%{"json" => json} ->
case json |> Map.keys() do
["graph-update"] ->
IO.puts(:chat_message)
["harkUpdate"] ->
IO.puts(:notifications)
_ ->
IO.puts(:some_other_app)
end
pattern ->
IO.inspect(pattern, label: :pattern2)
end
recv()
end
@doc """
Function provided for testing purposes. It will subscribe to the same event streams as the Landscape client does.
Returns the pid of the GenServer started.
Check the state with check_state(pid) and you can browse all events received, etc.
"""
def test do
{:ok, pid} = UrbitEx.start("http://localhost", "modpub-rilneb-datref-losped")
s = landscape_subs()
subscribe(pid, s)
pid
end
defp landscape_subs() do
[
%{app: "metadata-store", path: "/all"},
%{app: "invite-store", path: "/all"},
%{app: "launch", path: "/all"},
%{app: "weather", path: "/all"},
%{app: "group-store", path: "/groups"},
%{app: "contact-store", path: "/all"},
%{app: "s3-store", path: "/all"},
%{app: "graph-store", path: "/keys"},
%{app: "hark-store", path: "/updates"},
%{app: "hark-graph-hook", path: "/updates"},
%{app: "hark-group-hook", path: "/updates"},
%{app: "settings-store", path: "/all"},
%{app: "group-view", path: "/all"},
%{app: "contact-pull-hook", path: "/nacks"},
%{app: "graph-store", path: "/updates"}
]
end
end
f = fn
%{"json" => j} -> j
%{} -> "Hello, Anonymous Stranger!"
end