upload.ex 1.53 KB
Newer Older
lain's avatar
lain committed
1
defmodule Pleroma.Upload do
2
3
  alias Ecto.UUID
  alias Pleroma.Web
lain's avatar
lain committed
4
  def store(%Plug.Upload{} = file) do
5
    uuid = UUID.generate
lain's avatar
lain committed
6
7
8
9
10
11
12
    upload_folder = Path.join(upload_path(), uuid)
    File.mkdir_p!(upload_folder)
    result_file = Path.join(upload_folder, file.filename)
    File.cp!(file.path, result_file)

    %{
      "type" => "Image",
lain's avatar
lain committed
13
14
15
      "url" => [%{
        "type" => "Link",
        "mediaType" => file.content_type,
16
        "href" => url_for(Path.join(uuid, :cow_uri.urlencode(file.filename)))
lain's avatar
lain committed
17
      }],
lain's avatar
lain committed
18
19
20
21
22
      "name" => file.filename,
      "uuid" => uuid
    }
  end

lain's avatar
lain committed
23
24
25
  def store(%{"img" => "data:image/" <> image_data}) do
    parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
    data = Base.decode64!(parsed["data"])
26
    uuid = UUID.generate
lain's avatar
lain committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    upload_folder = Path.join(upload_path(), uuid)
    File.mkdir_p!(upload_folder)
    filename = Base.encode16(:crypto.hash(:sha256, data)) <> ".#{parsed["filetype"]}"
    result_file = Path.join(upload_folder, filename)

    File.write!(result_file, data)

    content_type = "image/#{parsed["filetype"]}"

    %{
      "type" => "Image",
      "url" => [%{
        "type" => "Link",
        "mediaType" => content_type,
41
        "href" => url_for(Path.join(uuid, :cow_uri.urlencode(filename)))
lain's avatar
lain committed
42
43
44
45
46
47
      }],
      "name" => filename,
      "uuid" => uuid
    }
  end

lain's avatar
lain committed
48
  defp upload_path do
49
50
    settings = Application.get_env(:pleroma, Pleroma.Upload)
    Keyword.fetch!(settings, :uploads)
lain's avatar
lain committed
51
52
53
  end

  defp url_for(file) do
54
    "#{Web.base_url()}/media/#{file}"
lain's avatar
lain committed
55
56
  end
end