aboutsummaryrefslogblamecommitdiff
path: root/shard/lib/shard_uri.ex
blob: 81b4ab1929a7d6421c9ca2a2e4270c67c3a1914e (plain) (tree)
1
2
3
4
5
6
7
8
9

                     

                                                                                 

     


                                          










                                                                               

                                                


       


                                              














                                                                                

                                                               







                        
defmodule ShardURI do
  @moduledoc"""
  Convert Shard manifests to and from text strings. Not used by the shard library
  internally, only provided for convenience.
  """

  @doc"""
  Get URI corresponding to shard manifest.
  """
  def from_manifest(m) do
    case m do
      %SApp.Chat.Manifest{channel: chan} -> "shard:chat:#{chan}"
      %SApp.Chat.PrivChat.Manifest{pk_list: pk_list} ->
        "shard:privchat:#{pk_list|>Enum.map(&Base.encode16/1)|>Enum.join(",")}"
      %SApp.Identity.Manifest{pk: pk} ->
        "shard:identity:#{pk|>Base.encode16}"
      %SApp.Directory.Manifest{owner: owner, public: true, name: name} ->
        "shard:dir:pub:#{owner|>Base.encode16}:#{name}"
      %SApp.Directory.Manifest{owner: owner, public: false, name: name} ->
        "shard:dir:priv:#{owner|>Base.encode16}:#{name}"
      %SApp.File.Manifest{infohash: infohash} ->
        "shard:file:#{infohash|>Base.encode16}"
    end
  end

  @doc"""
  Parse URI and return corresponding manifest.
  """
  def to_manifest(p) do
    case p do
      "shard:chat:" <> chan ->
        %SApp.Chat.Manifest{channel: chan}
      "shard:privchat:" <> pklist ->
        pklist
        |> String.split(",")
        |> Enum.map(&parse_pk/1)
        |> SApp.Chat.PrivChat.Manifest.new()
      "shard:identity:" <> pk ->
        %SApp.Identity.Manifest{pk: parse_pk pk}
      "shard:dir:pub:" <> <<pk::bytes-size(64)>> <> ":" <> name ->
        %SApp.Directory.Manifest{owner: parse_pk(pk), public: true, name: name}
      "shard:dir:priv:" <> <<pk::bytes-size(64)>> <> ":" <> name ->
        %SApp.Directory.Manifest{owner: parse_pk(pk), public: false, name: name}
      "shard:file:" <> <<infohash::bytes-size(64)>> ->
        %SApp.File.Manifest{infohash: Base.decode16!(infohash)}
    end
  end

  def parse_pk(pkstr) do
    64 = byte_size pkstr
    Base.decode16! pkstr
  end
end