Update Copyrights
[akkoma] / lib / pleroma / plugs / uploaded_media.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Plugs.UploadedMedia do
6 @moduledoc """
7 """
8
9 import Plug.Conn
10 import Pleroma.Web.Gettext
11 require Logger
12
13 @behaviour Plug
14 # no slashes
15 @path "media"
16
17 def init(_opts) do
18 static_plug_opts =
19 []
20 |> Keyword.put(:from, "__unconfigured_media_plug")
21 |> Keyword.put(:at, "/__unconfigured_media_plug")
22 |> Plug.Static.init()
23
24 %{static_plug_opts: static_plug_opts}
25 end
26
27 def call(%{request_path: <<"/", @path, "/", file::binary>>} = conn, opts) do
28 conn =
29 case fetch_query_params(conn) do
30 %{query_params: %{"name" => name}} = conn ->
31 name = String.replace(name, "\"", "\\\"")
32
33 conn
34 |> put_resp_header("content-disposition", "filename=\"#{name}\"")
35
36 conn ->
37 conn
38 end
39
40 config = Pleroma.Config.get(Pleroma.Upload)
41
42 with uploader <- Keyword.fetch!(config, :uploader),
43 proxy_remote = Keyword.get(config, :proxy_remote, false),
44 {:ok, get_method} <- uploader.get_file(file) do
45 get_media(conn, get_method, proxy_remote, opts)
46 else
47 _ ->
48 conn
49 |> send_resp(:internal_server_error, dgettext("errors", "Failed"))
50 |> halt()
51 end
52 end
53
54 def call(conn, _opts), do: conn
55
56 defp get_media(conn, {:static_dir, directory}, _, opts) do
57 static_opts =
58 Map.get(opts, :static_plug_opts)
59 |> Map.put(:at, [@path])
60 |> Map.put(:from, directory)
61
62 conn = Plug.Static.call(conn, static_opts)
63
64 if conn.halted do
65 conn
66 else
67 conn
68 |> send_resp(:not_found, dgettext("errors", "Not found"))
69 |> halt()
70 end
71 end
72
73 defp get_media(conn, {:url, url}, true, _) do
74 conn
75 |> Pleroma.ReverseProxy.call(url, Pleroma.Config.get([Pleroma.Upload, :proxy_opts], []))
76 end
77
78 defp get_media(conn, {:url, url}, _, _) do
79 conn
80 |> Phoenix.Controller.redirect(external: url)
81 |> halt()
82 end
83
84 defp get_media(conn, unknown, _, _) do
85 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
86
87 conn
88 |> send_resp(:internal_server_error, dgettext("errors", "Internal Error"))
89 |> halt()
90 end
91 end