Merge branch 'feat/client_app_details' into 'develop'
[akkoma] / lib / pleroma / web / plugs / frontend_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.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 @api_routes Pleroma.Web.get_api_routes()
14
15 def file_path(path, frontend_type \\ :primary) do
16 if configuration = Pleroma.Config.get([:frontends, frontend_type]) do
17 instance_static_path = Pleroma.Config.get([:instance, :static_dir], "instance/static")
18
19 Path.join([
20 instance_static_path,
21 "frontends",
22 configuration["name"],
23 configuration["ref"],
24 path
25 ])
26 else
27 nil
28 end
29 end
30
31 def init(opts) do
32 opts
33 |> Keyword.put(:from, "__unconfigured_frontend_static_plug")
34 |> Plug.Static.init()
35 |> Map.put(:frontend_type, opts[:frontend_type])
36 end
37
38 def call(conn, opts) do
39 with false <- api_route?(conn.path_info),
40 false <- invalid_path?(conn.path_info),
41 frontend_type <- Map.get(opts, :frontend_type, :primary),
42 path when not is_nil(path) <- file_path("", frontend_type) do
43 call_static(conn, opts, path)
44 else
45 _ ->
46 conn
47 end
48 end
49
50 defp invalid_path?(list) do
51 invalid_path?(list, :binary.compile_pattern(["/", "\\", ":", "\0"]))
52 end
53
54 defp invalid_path?([h | _], _match) when h in [".", "..", ""], do: true
55 defp invalid_path?([h | t], match), do: String.contains?(h, match) or invalid_path?(t)
56 defp invalid_path?([], _match), do: false
57
58 defp api_route?([h | _]) when h in @api_routes, do: true
59 defp api_route?([_ | t]), do: api_route?(t)
60 defp api_route?([]), do: false
61
62 defp call_static(conn, opts, from) do
63 opts = Map.put(opts, :from, from)
64 Plug.Static.call(conn, opts)
65 end
66 end