Add support for install via `file` and `build_url` params
[akkoma] / lib / pleroma / frontend.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.Frontend do
6 alias Pleroma.Config
7
8 require Logger
9
10 def install(name, opts \\ []) do
11 frontend_info = %{
12 "ref" => opts[:ref],
13 "build_url" => opts[:build_url],
14 "build_dir" => opts[:build_dir]
15 }
16
17 frontend_info =
18 [:frontends, :available, name]
19 |> Config.get(%{})
20 |> Map.merge(frontend_info, fn _key, config, cmd ->
21 # This only overrides things that are actually set
22 cmd || config
23 end)
24
25 ref = frontend_info["ref"]
26
27 unless ref do
28 raise "No ref given or configured"
29 end
30
31 dest = Path.join([dir(), name, ref])
32
33 label = "#{name} (#{ref})"
34 tmp_dir = Path.join(dir(), "tmp")
35
36 with {_, :ok} <-
37 {:download_or_unzip, download_or_unzip(frontend_info, tmp_dir, opts[:file])},
38 Logger.info("Installing #{label} to #{dest}"),
39 :ok <- install_frontend(frontend_info, tmp_dir, dest) do
40 File.rm_rf!(tmp_dir)
41 Logger.info("Frontend #{label} installed to #{dest}")
42 else
43 {:download_or_unzip, _} ->
44 Logger.info("Could not download or unzip the frontend")
45
46 _e ->
47 Logger.info("Could not install the frontend")
48 end
49 end
50
51 def dir(opts \\ []) do
52 if is_nil(opts[:static_dir]) do
53 Pleroma.Config.get!([:instance, :static_dir])
54 else
55 opts[:static_dir]
56 end
57 |> Path.join("frontends")
58 end
59
60 defp download_or_unzip(frontend_info, temp_dir, nil),
61 do: download_build(frontend_info, temp_dir)
62
63 defp download_or_unzip(_frontend_info, temp_dir, file) do
64 with {:ok, zip} <- File.read(Path.expand(file)) do
65 unzip(zip, temp_dir)
66 end
67 end
68
69 def unzip(zip, dest) do
70 with {:ok, unzipped} <- :zip.unzip(zip, [:memory]) do
71 File.rm_rf!(dest)
72 File.mkdir_p!(dest)
73
74 Enum.each(unzipped, fn {filename, data} ->
75 path = filename
76
77 new_file_path = Path.join(dest, path)
78
79 new_file_path
80 |> Path.dirname()
81 |> File.mkdir_p!()
82
83 File.write!(new_file_path, data)
84 end)
85 end
86 end
87
88 defp download_build(frontend_info, dest) do
89 Logger.info("Downloading pre-built bundle for #{frontend_info["name"]}")
90 url = String.replace(frontend_info["build_url"], "${ref}", frontend_info["ref"])
91
92 with {:ok, %{status: 200, body: zip_body}} <-
93 Pleroma.HTTP.get(url, [], pool: :media, recv_timeout: 120_000) do
94 unzip(zip_body, dest)
95 else
96 {:error, e} -> {:error, e}
97 e -> {:error, e}
98 end
99 end
100
101 defp install_frontend(frontend_info, source, dest) do
102 from = frontend_info["build_dir"] || "dist"
103 File.rm_rf!(dest)
104 File.mkdir_p!(dest)
105 File.cp_r!(Path.join([source, from]), dest)
106 :ok
107 end
108 end