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