-
-
Save hfabre/5b45e5128dc349b49221d519f819d3e1 to your computer and use it in GitHub Desktop.
Process uploaded file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment