- defp update_file_and_send(conn, updated_full_pack, pack_file_p) do
- # Write the emoji pack file
- File.write!(pack_file_p, Jason.encode!(updated_full_pack, pretty: true))
-
- # Return the modified file list
- json(conn, updated_full_pack["files"])
- end
-
- @doc """
- Updates a file in a pack.
-
- Updating can mean three things:
-
- - `add` adds an emoji named `shortcode` to the pack `pack_name`,
- that means that the emoji file needs to be uploaded with the request
- (thus requiring it to be a multipart request) and be named `file`.
- There can also be an optional `filename` that will be the new emoji file name
- (if it's not there, the name will be taken from the uploaded file).
- - `update` changes emoji shortcode (from `shortcode` to `new_shortcode` or moves the file
- (from the current filename to `new_filename`)
- - `remove` removes the emoji named `shortcode` and it's associated file
- """
-
- # Add
- def update_file(
- conn,
- %{"pack_name" => pack_name, "action" => "add", "shortcode" => shortcode} = params
- ) do
- pack_dir = Path.join(emoji_dir_path(), pack_name)
- pack_file_p = Path.join(pack_dir, "pack.json")
-
- full_pack = Jason.decode!(File.read!(pack_file_p))
-
- with {_, false} <- {:has_shortcode, Map.has_key?(full_pack["files"], shortcode)},
- filename <- get_filename(params),
- false <- empty?(shortcode),
- false <- empty?(filename) do
- file_path = Path.join(pack_dir, filename)
-
- # If the name contains directories, create them
- if String.contains?(file_path, "/") do
- File.mkdir_p!(Path.dirname(file_path))
- end
-
- case params["file"] do
- %Plug.Upload{path: upload_path} ->
- # Copy the uploaded file from the temporary directory
- File.copy!(upload_path, file_path)
-
- url when is_binary(url) ->
- # Download and write the file
- file_contents = Tesla.get!(url).body
- File.write!(file_path, file_contents)
- end
-
- updated_full_pack = put_in(full_pack, ["files", shortcode], filename)
- update_file_and_send(conn, updated_full_pack, pack_file_p)