My goal with this code: When a user clicks the link, I want to log into a system via SSH, get a file and then download that file to the users machine.
I am probably making this more complicated that it needs to be and if there is a simpler way please let me know.
Live view named sims_live.ex
defmodule AppWeb.SimsLive do
use AppWeb, :live_view
def mount(_params, _session, socket) do
{:ok,
assign(socket,
nothing: ""
)}
end
def handle_event("get_JSON", params, socket) do
IO.inspect params
{:ok, conn} =
SSH.connect(
"system_ip.whatever",
user: "root",
identity: "/.ssh/id_rsa_nop",
save_accepted_host: false,
silently_accept_hosts: true,
user_interaction: false
)
file_path = "priv/data.json"
result = SSH.fetch(conn, "/data.json")
{:ok, json_data} = result
case File.write(file_path, json_data) do
:ok ->
# IO.puts("File written successfully")
{:noreply, redirect(socket, to: "/download")}
{:error, reason} ->
IO.puts("Failed to write to file: #{reason}")
{:noreply, socket}
end
end
def render(assigns) do
~H"""
<div>
<a phx-click="get_JSON"> Click me </a>
</div>
"""
end
end
Controller named: download_controller
defmodule AppWeb.DownloadController do
use AppWeb, :controller
def home(conn, _params) do
path = Application.app_dir(:app, "priv/data.json") #static directory
send_download(conn, {:file, path})
render(conn, :home, layout: false)
end
end
The code above (kinda) works but there are two problems.
The first problem is that when a user clicks the event element the file is captured and downloads, but if the user clicks it again nothing happens without refreshing the page. I don’t know how to fix this. I think the download_controller may need a redirect of some sort, but everything I have tried has failed.
The second problem is this error, and I have no idea how to interpret it.
[error] Ranch listener AppWeb.Endpoint.HTTP had connection process started with :cowboy_clear:start_link/4 at #PID<0.834.0> exit with reason: {:function_clause, [{:cowboy_http, :commands, [{:state, #PID<0.602.0>, AppWeb.Endpoint.HTTP, #Port<0.33>, :ranch_tcp, :undefined, %{env: %{dispatch: [{:_, [], [{:_, [], Plug.Cowboy.Handler, {Phoenix.Endpoint.SyncCodeReloadPlug, {AppWeb.Endpoint, []}}}]}]},