Skip to content

Instantly share code, notes, and snippets.

@nshafer
Created June 17, 2024 14:53
Show Gist options
  • Save nshafer/b1149dcf5d70ee76e6bee99e15014087 to your computer and use it in GitHub Desktop.
Save nshafer/b1149dcf5d70ee76e6bee99e15014087 to your computer and use it in GitHub Desktop.
Process uploaded file
def handle_event("import", _params, socket) do
results =
consume_uploaded_entries(socket, :import, fn %{path: path}, _entry ->
temp_dir = Briefly.create!(type: :directory)
csv_file = Path.join(temp_dir, "import.csv")
# Attempt to create a new hard link to the file
case File.ln(path, csv_file) do
:ok ->
{:ok, csv_file}
{:error, reason} ->
Logger.error("Failed to create hard link: #{inspect(reason)}, attempting cp instead")
File.cp!(path, csv_file)
{:ok, csv_file}
end
end)
# Send messages to this LV to update the progress bar
lv_pid = self()
import_progress = fn count, total ->
send(lv_pid, {:import_progress, count, total})
end
case results do
[] ->
{:noreply, assign(socket, import_errors: ["No files uploaded"])}
[path] ->
{:noreply,
socket
|> assign(import_state: :processing)
|> assign(import_progress: 0)
|> start_async(:import, fn -> Core.Import.import_computers(path, progress_callback: import_progress) end)}
results ->
Logger.error("Got multiple results?!?!?! #{inspect(results)}")
{:noreply, assign(socket, import_errors: ["Unknown error"])}
end
end
def handle_async(:import, {:ok, {:ok, results}}, socket) do
{
:noreply,
socket
|> assign(import_state: :done)
|> assign(import_errors: errors)
}
end
def handle_async(:import, {:ok, {:error, error}}, socket) do
{
:noreply,
socket
|> assign(import_state: :idle)
|> assign(import_errors: [error])
}
end
def handle_async(:import, {:ok, {:errors, errors}}, socket) do
{
:noreply,
socket
|> assign(import_state: :idle)
|> assign(import_errors: errors)
}
end
def handle_async(:import, {:exit, reason}, socket) do
{
:noreply,
socket
|> assign(import_state: :idle)
|> assign(import_errors: ["Unknown error"])
}
end
@nshafer
Copy link
Author

nshafer commented Jun 17, 2024

Oh and handling the progress messages:

  def handle_info({:import_progress, count, total}, socket) do
    {:noreply, assign(socket, import_progress: count / total * 100)}
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment