723b256793b28485e2f947003ec383c66c92db12
[akkoma] / lib / pleroma / web / plugs / instance_static.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Plugs.InstanceStatic do
6 require Pleroma.Constants
7
8 @moduledoc """
9 This is a shim to call `Plug.Static` but with runtime `from` configuration.
10
11 Mountpoints are defined directly in the module to avoid calling the configuration for every request including non-static ones.
12 """
13 @behaviour Plug
14
15 def file_path(path) do
16 instance_path =
17 Path.join(Pleroma.Config.get([:instance, :static_dir], "instance/static/"), path)
18
19 frontend_path = Pleroma.Web.Plugs.FrontendStatic.file_path(path, :primary)
20
21 (File.exists?(instance_path) && instance_path) ||
22 (frontend_path && File.exists?(frontend_path) && frontend_path) ||
23 Path.join(Application.app_dir(:pleroma, "priv/static/"), path)
24 end
25
26 def init(opts) do
27 opts
28 |> Keyword.put(:from, "__unconfigured_instance_static_plug")
29 |> Plug.Static.init()
30 end
31
32 for only <- Pleroma.Constants.static_only_files() do
33 def call(%{request_path: "/" <> unquote(only) <> _} = conn, opts) do
34 call_static(
35 conn,
36 opts,
37 Pleroma.Config.get([:instance, :static_dir], "instance/static")
38 )
39 end
40 end
41
42 def call(conn, _) do
43 conn
44 end
45
46 defp call_static(conn, opts, from) do
47 opts =
48 opts
49 |> Map.put(:from, from)
50
51 Plug.Static.call(conn, opts)
52 end
53 end