FrontendStatic: Add plug to serve frontends based on configuration.
[akkoma] / lib / pleroma / plugs / frontend_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.FrontendStatic do
6 require Pleroma.Constants
7
8 @moduledoc """
9 This is a shim to call `Plug.Static` but with runtime `from` configuration`. It dispatches to the different frontends.
10 """
11 @behaviour Plug
12
13 def file_path(path, frontend_type \\ :primary) do
14 if configuration = Pleroma.Config.get([:frontends, frontend_type]) do
15 instance_static_path = Pleroma.Config.get([:instance, :static_dir], "instance/static")
16
17 Path.join([
18 instance_static_path,
19 "frontends",
20 configuration["name"],
21 configuration["ref"],
22 path
23 ])
24 else
25 nil
26 end
27 end
28
29 def init(opts) do
30 opts
31 |> Keyword.put(:from, "__unconfigured_frontend_static_plug")
32 |> Plug.Static.init()
33 end
34
35 def call(conn, opts) do
36 frontend_type = Map.get(opts, :frontend_type, :primary)
37 path = file_path("", frontend_type)
38
39 if path do
40 conn
41 |> call_static(opts, path)
42 else
43 conn
44 end
45 end
46
47 defp call_static(conn, opts, from) do
48 opts =
49 opts
50 |> Map.put(:from, from)
51
52 Plug.Static.call(conn, opts)
53 end
54 end