summaryrefslogtreecommitdiff
path: root/lib/mix/tasks/pleroma/frontend.ex
blob: b3b3caa9bcc5caab07fb54124d6dbbd3d83dbac2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Mix.Tasks.Pleroma.Frontend do
  use Mix.Task

  import Mix.Pleroma

  @shortdoc "Manages bundled Pleroma frontends"
  @moduledoc File.read!("docs/administration/CLI_tasks/frontend.md")

  @frontends %{
    "admin" => %{"project" => "pleroma/admin-fe"},
    "kenoma" => %{"project" => "lambadalambda/kenoma"},
    "mastodon" => %{"project" => "pleroma/mastofe"},
    "pleroma" => %{"project" => "pleroma/pleroma-fe"},
    "fedi" => %{"project" => "dockyard/fedi-fe"}
  }
  @known_frontends Map.keys(@frontends)

  @ref_local "__local__"
  @ref_develop "__develop__"
  @ref_stable "__stable__"

  @pleroma_gitlab_host "git.pleroma.social"

  def run(["install", "none" | _args]) do
    shell_info("Skipping frontend installation because none was requested")
    "none"
  end

  def run(["install", "all" | options]) do
    start_pleroma()

    configs = Pleroma.Config.get(:frontends, %{})

    with config when not is_nil(config) <- configs[:primary],
         ref when ref != "none" <- config["ref"] do
      run(["install", config["name"], "--ref", ref | options])
    end

    with config when not is_nil(config) <- configs[:mastodon],
         ref when ref != "none" <- config["ref"] do
      run(["install", "mastodon", "--ref", ref | options])
    end

    with config when not is_nil(config) <- configs[:admin],
         ref when ref != "none" <- config["ref"] do
      run(["install", "admin", "--ref", ref | options])
    end
  end

  def run(["install", unknown_fe | _args]) when unknown_fe not in @known_frontends do
    shell_error(
      "Frontend \"#{unknown_fe}\" is not known. Known frontends are: #{
        Enum.join(@known_frontends, ", ")
      }"
    )
  end

  def run(["install", frontend | args]) do
    log_level = Logger.level()
    Logger.configure(level: :warn)
    start_pleroma()

    {options, [], []} =
      OptionParser.parse(
        args,
        strict: [
          ref: :string,
          path: :string,
          develop: :boolean,
          static_dir: :string
        ]
      )

    instance_static_dir =
      with nil <- options[:static_dir] do
        Pleroma.Config.get!([:instance, :static_dir])
      end

    ref =
      case options[:path] do
        nil ->
          ref0 =
            cond do
              options[:ref] -> options[:ref]
              options[:develop] -> @ref_develop
              true -> @ref_stable
            end

          web_frontend_ref(frontend, ref0)

        path ->
          local_path_frontend_ref(path)
      end

    dest =
      Path.join([
        instance_static_dir,
        "frontends",
        frontend,
        ref
      ])

    fe_label = "#{frontend} (#{ref})"

    {from, proceed?} =
      with nil <- options[:path] do
        tmp_dir = Path.join(dest, "tmp/src")

        shell_info("Downloading pre-built bundle for #{fe_label}")

        proceed? =
          with {:error, error} <- download_frontend(frontend, ref, tmp_dir, :build) do
            shell_info("Could not download pre-built bundle: #{inspect(error)}.")
            shell_info("Falling back to building locally from source")

            download_and_build = fn callback ->
              case Pleroma.Utils.command_available?("yarn") do
                false ->
                  message =
                    "To build frontend #{fe_label} from sources, `yarn` command is required. Please install it before continue. ([C]ontinue/[A]bort)"

                  case String.downcase(shell_prompt(message, "C")) do
                    abort when abort in ["a", "abort"] ->
                      false

                    _continue ->
                      callback.(callback)
                  end

                _ ->
                  shell_info("Downloading #{fe_label} sources to #{tmp_dir}")
                  :ok = download_frontend(frontend, ref, tmp_dir, :source)

                  shell_info("Building #{fe_label} (this will take some time)")
                  :ok = build_frontend(frontend, tmp_dir)
              end
            end

            download_and_build.(download_and_build)
          else
            _ ->
              true
          end

        {tmp_dir, proceed?}
      else
        path ->
          {path, true}
      end

    if proceed? do
      shell_info("Installing #{fe_label} to #{dest}")

      :ok = install_frontend(frontend, from, dest)

      shell_info("Frontend #{fe_label} installed to #{dest}")
    end

    Logger.configure(level: log_level)
    ref
  end

  defp download_frontend(frontend, ref, dest, kind) do
    url = frontend_url(frontend, ref, kind)

    with {:ok, %{status: 200, body: zip_body}} <-
           Pleroma.HTTP.get(url, [], timeout: 120_000, recv_timeout: 120_000),
         {:ok, unzipped} <- :zip.unzip(zip_body, [:memory]) do
      File.rm_rf!(dest)
      File.mkdir_p!(dest)

      Enum.each(unzipped, fn {filename, data} ->
        path =
          case kind do
            :source ->
              filename
              |> Path.split()
              |> Enum.drop(1)
              |> Enum.join("/")

            :build ->
              filename
          end

        new_file_path = Path.join(dest, path)

        new_file_path
        |> Path.dirname()
        |> File.mkdir_p!()

        File.write!(new_file_path, data)
      end)
    else
      {:ok, %{status: 404}} ->
        {:error, "Zip archive with frontend #{kind} not found at #{url}"}

      error ->
        {:error, error}
    end
  end

  defp build_frontend("admin", path) do
    yarn = Pleroma.Config.get(:yarn, "yarn")
    {_out, 0} = System.cmd(yarn, [], cd: path)
    {_out, 0} = System.cmd(yarn, ["build:prod"], cd: path)
    :ok
  end

  defp build_frontend(_frontend, path) do
    yarn = Pleroma.Config.get(:yarn, "yarn")
    {_out, 0} = System.cmd(yarn, [], cd: path)
    {_out, 0} = System.cmd(yarn, ["build"], cd: path)
    :ok
  end

  defp web_frontend_ref(frontend, @ref_develop) do
    url = project_url(frontend) <> "/repository/branches"

    {:ok, %{status: 200, body: body}} =
      Pleroma.HTTP.get(url, [], timeout: 120_000, recv_timeout: 120_000)

    json = Jason.decode!(body)

    %{"commit" => %{"short_id" => last_commit_ref}} = Enum.find(json, & &1["default"])

    last_commit_ref
  end

  # fallback to develop version if compatible stable ref is not defined in
  # mix.exs for the given frontend
  defp web_frontend_ref(frontend, @ref_stable) do
    case Map.get(Pleroma.Application.frontends(), frontend) do
      nil ->
        web_frontend_ref(frontend, @ref_develop)

      ref ->
        ref
    end
  end

  defp web_frontend_ref(_frontend, ref), do: ref

  defp project_url(frontend),
    do:
      "https://#{@pleroma_gitlab_host}/api/v4/projects/#{
        URI.encode_www_form(@frontends[frontend]["project"])
      }"

  defp source_url(frontend, ref),
    do: "https://#{@pleroma_gitlab_host}/#{@frontends[frontend]["project"]}/-/archive/#{ref}.zip"

  defp build_url(frontend, ref),
    do:
      "https://#{@pleroma_gitlab_host}/#{@frontends[frontend]["project"]}/-/jobs/artifacts/#{ref}/download?job=build"

  defp frontend_url(frontend, ref, :source), do: source_url(frontend, ref)
  defp frontend_url(frontend, ref, :build), do: build_url(frontend, ref)

  defp local_path_frontend_ref(path) do
    path
    |> Path.join("package.json")
    |> File.read()
    |> case do
      {:ok, bin} ->
        bin
        |> Jason.decode!()
        |> Map.get("version", @ref_local)

      _ ->
        @ref_local
    end
  end

  defp post_install("mastodon", path) do
    File.rename!("#{path}/assets/sw.js", "#{path}/sw.js")

    {:ok, files} = File.ls(path)

    Enum.each(files, fn file ->
      with false <- file in ~w(packs sw.js) do
        [path, file]
        |> Path.join()
        |> File.rm_rf!()
      end
    end)
  end

  defp post_install(_frontend, _path) do
    :ok
  end

  defp install_frontend(frontend, source, dest) do
    from =
      case frontend do
        "mastodon" ->
          "public"

        "kenoma" ->
          "build"

        _ ->
          "dist"
      end

    File.mkdir_p!(dest)
    File.cp_r!(Path.join([source, from]), dest)
    post_install(frontend, dest)
  end
end