Unify object representation.
[akkoma] / lib / pleroma / upload.ex
1 defmodule Pleroma.Upload do
2 alias Ecto.UUID
3 alias Pleroma.Web
4 def store(%Plug.Upload{} = file) do
5 uuid = UUID.generate
6 upload_folder = Path.join(upload_path(), uuid)
7 File.mkdir_p!(upload_folder)
8 result_file = Path.join(upload_folder, file.filename)
9 File.cp!(file.path, result_file)
10
11 # fix content type on some image uploads
12 content_type = if file.content_type in [nil, "application/octet-stream"] do
13 get_content_type(file.path)
14 else
15 file.content_type
16 end
17
18 %{
19 "type" => "Image",
20 "url" => [%{
21 "type" => "Link",
22 "mediaType" => content_type,
23 "href" => url_for(Path.join(uuid, :cow_uri.urlencode(file.filename)))
24 }],
25 "name" => file.filename,
26 "uuid" => uuid
27 }
28 end
29
30 def store(%{"img" => "data:image/" <> image_data}) do
31 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
32 data = Base.decode64!(parsed["data"])
33 uuid = UUID.generate
34 upload_folder = Path.join(upload_path(), uuid)
35 File.mkdir_p!(upload_folder)
36 filename = Base.encode16(:crypto.hash(:sha256, data)) <> ".#{parsed["filetype"]}"
37 result_file = Path.join(upload_folder, filename)
38
39 File.write!(result_file, data)
40
41 content_type = "image/#{parsed["filetype"]}"
42
43 %{
44 "type" => "Image",
45 "url" => [%{
46 "type" => "Link",
47 "mediaType" => content_type,
48 "href" => url_for(Path.join(uuid, :cow_uri.urlencode(filename)))
49 }],
50 "name" => filename,
51 "uuid" => uuid
52 }
53 end
54
55 defp upload_path do
56 settings = Application.get_env(:pleroma, Pleroma.Upload)
57 Keyword.fetch!(settings, :uploads)
58 end
59
60 defp url_for(file) do
61 "#{Web.base_url()}/media/#{file}"
62 end
63
64 def get_content_type(file) do
65 match = File.open(file, [:read], fn(f) ->
66 case IO.binread(f, 8) do
67 <<0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a>> ->
68 "image/png"
69 <<0x47, 0x49, 0x46, 0x38, _, 0x61, _, _>> ->
70 "image/gif"
71 <<0xff, 0xd8, 0xff, _, _, _, _, _>> ->
72 "image/jpeg"
73 <<0x1a, 0x45, 0xdf, 0xa3, _, _, _, _>> ->
74 "video/webm"
75 <<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70>> ->
76 "video/mp4"
77 <<0x49, 0x44, 0x33, _, _, _, _, _>> ->
78 "audio/mpeg"
79 <<0x4f, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00>> ->
80 "audio/ogg"
81 <<0x52, 0x49, 0x46, 0x46, _, _, _, _>> ->
82 "audio/wav"
83 _ ->
84 "application/octet-stream"
85 end
86 end)
87
88 case match do
89 {:ok, type} -> type
90 _e -> "application/octet-stream"
91 end
92 end
93 end