Merge branch 'fix-object-deletion-timeout' into 'develop'
[akkoma] / lib / pleroma / frontend.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.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 {:error, "Could not download or unzip the frontend"}
46
47 _e ->
48 Logger.info("Could not install the frontend")
49 {:error, "Could not install the frontend"}
50 end
51 end
52
53 def dir(opts \\ []) do
54 if is_nil(opts[:static_dir]) do
55 Pleroma.Config.get!([:instance, :static_dir])
56 else
57 opts[:static_dir]
58 end
59 |> Path.join("frontends")
60 end
61
62 defp download_or_unzip(frontend_info, temp_dir, nil),
63 do: download_build(frontend_info, temp_dir)
64
65 defp download_or_unzip(_frontend_info, temp_dir, file) do
66 with {:ok, zip} <- File.read(Path.expand(file)) do
67 unzip(zip, temp_dir)
68 end
69 end
70
71 def unzip(zip, dest) do
72 with {:ok, unzipped} <- :zip.unzip(zip, [:memory]) do
73 File.rm_rf!(dest)
74 File.mkdir_p!(dest)
75
76 Enum.each(unzipped, fn {filename, data} ->
77 path = filename
78
79 new_file_path = Path.join(dest, path)
80
81 new_file_path
82 |> Path.dirname()
83 |> File.mkdir_p!()
84
85 File.write!(new_file_path, data)
86 end)
87 end
88 end
89
90 defp download_build(frontend_info, dest) do
91 Logger.info("Downloading pre-built bundle for #{frontend_info["name"]}")
92 url = String.replace(frontend_info["build_url"], "${ref}", frontend_info["ref"])
93
94 with {:ok, %{status: 200, body: zip_body}} <-
95 Pleroma.HTTP.get(url, [], pool: :media, recv_timeout: 120_000) do
96 unzip(zip_body, dest)
97 else
98 {:error, e} -> {:error, e}
99 e -> {:error, e}
100 end
101 end
102
103 defp install_frontend(frontend_info, source, dest) do
104 from = frontend_info["build_dir"] || "dist"
105 File.rm_rf!(dest)
106 File.mkdir_p!(dest)
107 File.cp_r!(Path.join([source, from]), dest)
108 :ok
109 end
110 end