logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

ipfs.ex (2062B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Uploaders.IPFS do
  5. @behaviour Pleroma.Uploaders.Uploader
  6. require Logger
  7. alias Tesla.Multipart
  8. @api_add "/api/v0/add"
  9. @api_delete "/api/v0/files/rm"
  10. @config_impl Application.compile_env(:pleroma, [__MODULE__, :config_impl], Pleroma.Config)
  11. @placeholder "{CID}"
  12. def placeholder, do: @placeholder
  13. @impl true
  14. def get_file(file) do
  15. b_url = Pleroma.Upload.base_url()
  16. if String.contains?(b_url, @placeholder) do
  17. {:ok, {:url, String.replace(b_url, @placeholder, URI.decode(file))}}
  18. else
  19. {:error, "IPFS Get URL doesn't contain 'cid' placeholder"}
  20. end
  21. end
  22. @impl true
  23. def put_file(%Pleroma.Upload{tempfile: tempfile}) do
  24. mp =
  25. Multipart.new()
  26. |> Multipart.add_content_type_param("charset=utf-8")
  27. |> Multipart.add_file(tempfile)
  28. endpoint = ipfs_endpoint(@api_add)
  29. with {:ok, %{body: body}} when is_binary(body) <-
  30. Pleroma.HTTP.post(endpoint, mp, [], params: ["cid-version": "1"], pool: :upload),
  31. {_, {:ok, decoded}} <- {:json, Jason.decode(body)},
  32. {_, true} <- {:hash, Map.has_key?(decoded, "Hash")} do
  33. {:ok, {:file, decoded["Hash"]}}
  34. else
  35. {:hash, false} ->
  36. {:error, "JSON doesn't contain Hash key"}
  37. {:json, error} ->
  38. Logger.error("#{__MODULE__}: #{inspect(error)}")
  39. {:error, "JSON decode failed"}
  40. error ->
  41. Logger.error("#{__MODULE__}: #{inspect(error)}")
  42. {:error, "IPFS Gateway upload failed"}
  43. end
  44. end
  45. @impl true
  46. def delete_file(file) do
  47. endpoint = ipfs_endpoint(@api_delete)
  48. case Pleroma.HTTP.post(endpoint, "", [], params: [arg: file]) do
  49. {:ok, %{status: 204}} -> :ok
  50. error -> {:error, inspect(error)}
  51. end
  52. end
  53. defp ipfs_endpoint(path) do
  54. URI.parse(@config_impl.get([__MODULE__, :post_gateway_url]))
  55. |> Map.put(:path, path)
  56. |> URI.to_string()
  57. end
  58. end