diff --git a/lib/livebook/utils.ex b/lib/livebook/utils.ex index 871354335..9334d70d4 100644 --- a/lib/livebook/utils.ex +++ b/lib/livebook/utils.ex @@ -387,6 +387,24 @@ defmodule Livebook.Utils do |> URI.to_string() end + @doc """ + Returns a URL (including localhost) to open the given `url` as a notebook + + iex> Livebook.Utils.notebook_open_url("https://example.com/foo.livemd") + "http://localhost:4002/open?path=https%3A%2F%2Fexample.com%2Ffoo.livemd" + + iex> Livebook.Utils.notebook_open_url("https://my_host", "https://example.com/foo.livemd") + "https://my_host/open?path=https%3A%2F%2Fexample.com%2Ffoo.livemd" + + """ + def notebook_open_url(base_url \\ LivebookWeb.Endpoint.access_struct_url(), url) do + base_url + |> URI.parse() + |> Map.replace!(:path, "/open") + |> append_query("path=#{URI.encode_www_form(url)}") + |> URI.to_string() + end + # TODO: On Elixir v1.14, use URI.append_query/2 def append_query(%URI{query: query} = uri, query_to_add) when query in [nil, ""] do %{uri | query: query_to_add} diff --git a/lib/livebook_cli/server.ex b/lib/livebook_cli/server.ex index a830dcc80..2441e1fa1 100644 --- a/lib/livebook_cli/server.ex +++ b/lib/livebook_cli/server.ex @@ -168,8 +168,7 @@ defmodule LivebookCLI.Server do File.regular?(path) -> base_url - |> append_path("open") - |> update_query(%{"path" => path}) + |> Livebook.Utils.notebook_open_url(url_or_file_or_dir) |> Livebook.Utils.browser_open() File.dir?(path) ->