From 494ab40ac890d17b6f714d78822f7562cbeafdde Mon Sep 17 00:00:00 2001 From: Sam <85004512+aar2dee2@users.noreply.github.com> Date: Mon, 7 Feb 2022 18:09:23 +0530 Subject: [PATCH] add function to open notebook urls (#986) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add function to open notebook urls * Update lib/livebook/utils.ex Co-authored-by: José Valim * Update lib/livebook/utils.ex Co-authored-by: José Valim * open notebook with notebook_open_url/2 * Update server.ex * format Livebook.Utils * Update lib/livebook_cli/server.ex Co-authored-by: José Valim * correct function doc Co-authored-by: José Valim --- lib/livebook/utils.ex | 18 ++++++++++++++++++ lib/livebook_cli/server.ex | 3 +-- 2 files changed, 19 insertions(+), 2 deletions(-) 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) ->