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