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