Merge branch 'stable' into release/2.0.0
[akkoma] / lib / pleroma / plugs / instance_static.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.InstanceStatic do
6 @moduledoc """
7 This is a shim to call `Plug.Static` but with runtime `from` configuration.
8
9 Mountpoints are defined directly in the module to avoid calling the configuration for every request including non-static ones.
10 """
11 @behaviour Plug
12
13 def file_path(path) do
14 instance_path =
15 Path.join(Pleroma.Config.get([:instance, :static_dir], "instance/static/"), path)
16
17 if File.exists?(instance_path) do
18 instance_path
19 else
20 Path.join(Application.app_dir(:pleroma, "priv/static/"), path)
21 end
22 end
23
24 @only ~w(index.html robots.txt static emoji packs sounds images instance favicon.png sw.js
25 sw-pleroma.js)
26
27 def init(opts) do
28 opts
29 |> Keyword.put(:from, "__unconfigured_instance_static_plug")
30 |> Keyword.put(:at, "/__unconfigured_instance_static_plug")
31 |> Plug.Static.init()
32 end
33
34 for only <- @only do
35 at = Plug.Router.Utils.split("/")
36
37 def call(%{request_path: "/" <> unquote(only) <> _} = conn, opts) do
38 call_static(
39 conn,
40 opts,
41 unquote(at),
42 Pleroma.Config.get([:instance, :static_dir], "instance/static")
43 )
44 end
45 end
46
47 def call(conn, _) do
48 conn
49 end
50
51 defp call_static(conn, opts, at, from) do
52 opts =
53 opts
54 |> Map.put(:from, from)
55 |> Map.put(:at, at)
56
57 Plug.Static.call(conn, opts)
58 end
59 end