File size: 8,475 Bytes
88211d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
defmodule PlausibleWeb.Live.CSVExport do
  @moduledoc """
  LiveView allowing scheduling, watching, downloading, and deleting S3 and local exports.
  """
  use PlausibleWeb, :live_view

  alias Plausible.Exports

  # :not_mounted_at_router ensures we have already done auth checks in the controller
  # if this liveview becomes available from the router, please make sure
  # to check that site_role is allowed to manage site exports
  @impl true
  def mount(:not_mounted_at_router, session, socket) do
    %{
      "storage" => storage,
      "site_id" => site_id,
      "email_to" => email_to
    } = session

    socket =
      socket
      |> assign(site_id: site_id, email_to: email_to, storage: storage)
      |> assign_new(:site, fn -> Plausible.Repo.get!(Plausible.Site, site_id) end)
      |> fetch_export()

    if connected?(socket) do
      Exports.oban_listen()
    end

    {:ok, socket}
  end

  defp fetch_export(socket) do
    %{storage: storage, site_id: site_id} = socket.assigns

    get_export =
      case storage do
        "s3" ->
          &Exports.get_s3_export!/1

        "local" ->
          %{domain: domain, timezone: timezone} = socket.assigns.site
          &Exports.get_local_export(&1, domain, timezone)
      end

    socket = assign(socket, export: nil)

    if job = Exports.get_last_export_job(site_id) do
      %Oban.Job{state: state} = job

      case state do
        _ when state in ["scheduled", "available", "retryable"] ->
          assign(socket, status: "in_progress")

        "executing" ->
          # Exports.oban_notify/1 is called in `perform/1` and
          # the notification arrives while the job.state is still "executing"
          if export = get_export.(site_id) do
            assign(socket, status: "ready", export: export)
          else
            assign(socket, status: "in_progress")
          end

        "completed" ->
          if export = get_export.(site_id) do
            assign(socket, status: "ready", export: export)
          else
            assign(socket, status: "can_schedule")
          end

        "discarded" ->
          assign(socket, status: "export_failed")

        "cancelled" ->
          # credo:disable-for-next-line Credo.Check.Refactor.Nesting
          if export = get_export.(site_id) do
            assign(socket, status: "ready", export: export)
          else
            assign(socket, status: "can_schedule")
          end
      end
    else
      if export = get_export.(site_id) do
        assign(socket, status: "ready", export: export)
      else
        assign(socket, status: "can_schedule")
      end
    end
  rescue
    _e ->
      assign(socket, status: "fetch_error", export: nil)
  end

  @impl true
  def render(assigns) do
    ~H"""
    <%= case @status do %>
      <% "can_schedule" -> %>
        <.prepare_download />
      <% "in_progress" -> %>
        <.in_progress />
      <% "export_failed" -> %>
        <.export_failed />
      <% "fetch_error" -> %>
        <.fetch_export_failed />
      <% "ready" -> %>
        <.download
          storage={@storage}
          export={@export}
          href={Routes.site_path(@socket, :download_export, @site.domain)}
        />
    <% end %>
    """
  end

  defp prepare_download(assigns) do
    ~H"""
    <p class="text-sm">
      Prepare your data for download by clicking the button below. When that's done, a Zip file that you can download will appear.
    </p>
    <.button phx-click="export">Prepare download</.button>
    """
  end

  defp in_progress(assigns) do
    ~H"""
    <div class="flex items-center justify-between space-x-2">
      <div class="flex items-center">
        <.spinner />
        <span class="ml-2 text-sm">We are preparing your download ...</span>
      </div>
      <button
        phx-click="cancel"
        class="text-red-500 font-semibold text-sm"
        data-confirm="Are you sure you want to cancel this export?"
      >
        Cancel
      </button>
    </div>
    <p class="text-sm mt-4">
      The preparation of your stats might take a while. Depending on the volume of your data, it might take up to 20 minutes. Feel free to leave the page and return later.
    </p>
    """
  end

  defp fetch_export_failed(assigns) do
    ~H"""
    <.notice title="Something went wrong when fetching exports" theme={:red}>
      Please try again later.
    </.notice>
    """
  end

  defp export_failed(assigns) do
    ~H"""
    <div class="flex items-center">
      <Heroicons.exclamation_circle class="w-4 h-4 text-red-500" />
      <p class="ml-2 text-sm">
        Something went wrong when preparing your download. Please
        <button phx-click="export" class="text-indigo-500">try again.</button>
      </p>
    </div>
    """
  end

  defp download(assigns) do
    ~H"""
    <.table rows={[@export]}>
      <:thead>
        <.th>Export</.th>
        <.th invisible>Actions</.th>
      </:thead>
      <:tbody :let={export}>
        <.td>
          <.styled_link href={@href}>
            {export.name}
          </.styled_link>
        </.td>
        <.td actions>
          <.delete_button
            phx-click="delete"
            data-confirm="Are you sure you want to delete this export?"
          />
        </.td>
      </:tbody>
    </.table>

    <p :if={@export.expires_at} class="text-sm">
      Note: this file will expire
      <.hint message={@export.expires_at}>
        {Plausible.Times.humanize(@export.expires_at)}.
      </.hint>
    </p>

    <p :if={@storage == "local"} class="text-sm">
      Located at
      <.hint message={@export.path}>{format_path(@export.path)}</.hint>
      ({format_bytes(@export.size)})
    </p>
    """
  end

  defp hint(assigns) do
    ~H"""
    <span title={@message} class="underline cursor-help underline-offset-2 decoration-dashed">
      {render_slot(@inner_block)}
    </span>
    """
  end

  @impl true
  def handle_event("export", _params, socket) do
    %{storage: storage, site_id: site_id, email_to: email_to} =
      socket.assigns

    schedule_result =
      case storage do
        "s3" -> Exports.schedule_s3_export(site_id, email_to)
        "local" -> Exports.schedule_local_export(site_id, email_to)
      end

    socket =
      case schedule_result do
        {:ok, _job} ->
          fetch_export(socket)

        {:error, :no_data} ->
          socket
          |> put_flash(:error, "There is no data to export")
          |> redirect(
            to: Routes.site_path(socket, :settings_imports_exports, socket.assigns.site.domain)
          )
      end

    {:noreply, socket}
  end

  def handle_event("cancel", _params, socket) do
    if job = Exports.get_last_export_job(socket.assigns.site_id), do: Oban.cancel_job(job)
    {:noreply, fetch_export(socket)}
  end

  def handle_event("delete", _params, socket) do
    %{storage: storage, site_id: site_id} = socket.assigns

    case storage do
      "s3" -> Exports.delete_s3_export!(site_id)
      "local" -> Exports.delete_local_export(site_id)
    end

    {:noreply, fetch_export(socket)}
  end

  @impl true
  def handle_info({:notification, Exports, %{"site_id" => site_id}}, socket) do
    socket =
      if site_id == socket.assigns.site_id do
        fetch_export(socket)
      else
        socket
      end

    {:noreply, socket}
  end

  @format_path_regex ~r/^(?<beginning>((.+?\/){3})).*(?<ending>(\/.*){3})$/

  defp format_path(path) do
    path_string =
      path
      |> to_string()
      |> String.replace_prefix("\"", "")
      |> String.replace_suffix("\"", "")

    case Regex.named_captures(@format_path_regex, path_string) do
      %{"beginning" => beginning, "ending" => ending} -> "#{beginning}...#{ending}"
      _ -> path_string
    end
  end

  defp format_bytes(bytes) when is_integer(bytes) do
    cond do
      bytes >= memory_unit("TiB") -> format_bytes(bytes, "TiB")
      bytes >= memory_unit("GiB") -> format_bytes(bytes, "GiB")
      bytes >= memory_unit("MiB") -> format_bytes(bytes, "MiB")
      bytes >= memory_unit("KiB") -> format_bytes(bytes, "KiB")
      true -> format_bytes(bytes, "B")
    end
  end

  defp format_bytes(bytes, "B"), do: "#{bytes} B"

  defp format_bytes(bytes, unit) do
    value = bytes / memory_unit(unit)
    "#{:erlang.float_to_binary(value, decimals: 1)} #{unit}"
  end

  defp memory_unit("TiB"), do: 1024 * 1024 * 1024 * 1024
  defp memory_unit("GiB"), do: 1024 * 1024 * 1024
  defp memory_unit("MiB"), do: 1024 * 1024
  defp memory_unit("KiB"), do: 1024
end