File size: 9,134 Bytes
8da2481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
defmodule PlausibleWeb.GoogleAnalyticsController do
  use PlausibleWeb, :controller

  alias Plausible.Google
  alias Plausible.Imported
  use Plausible

  plug(PlausibleWeb.RequireAccountPlug)

  plug(PlausibleWeb.Plugs.AuthorizeSiteAccess, [:owner, :editor, :admin, :super_admin])

  def property_form(
        conn,
        %{
          "access_token" => access_token,
          "refresh_token" => refresh_token,
          "expires_at" => expires_at
        } = params
      ) do
    site = conn.assigns.site

    redirect_route = Routes.site_path(conn, :settings_imports_exports, site.domain)

    result = Google.API.list_properties(access_token)

    error =
      case params["error"] do
        "no_data" ->
          "No data found. Nothing to import."

        "no_time_window" ->
          "Imported data time range is completely overlapping with existing data. Nothing to import."

        _ ->
          nil
      end

    case result do
      {:ok, properties} ->
        conn
        |> assign(:skip_plausible_tracking, true)
        |> render("property_form.html",
          access_token: access_token,
          refresh_token: refresh_token,
          expires_at: expires_at,
          site: conn.assigns.site,
          properties: properties,
          selected_property_error: error
        )

      {:error, :rate_limit_exceeded} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics rate limit has been exceeded. Please try again later."
        )
        |> redirect(to: redirect_route)

      {:error, {:authentication_failed, message}} ->
        default_message =
          "We were unable to authenticate your Google Analytics account. Please check that you have granted us permission to 'See and download your Google Analytics data' and try again."

        message =
          if ce?() do
            message || default_message
          else
            default_message
          end

        conn
        |> put_flash(:ttl, :timer.seconds(5))
        |> put_flash(:error, message)
        |> redirect(to: redirect_route)

      {:error, :timeout} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics API has timed out. Please try again."
        )
        |> redirect(to: redirect_route)

      {:error, _any} ->
        conn
        |> put_flash(
          :error,
          "We were unable to list your Google Analytics properties. If the problem persists, please contact support for assistance."
        )
        |> redirect(to: redirect_route)
    end
  end

  def property(
        conn,
        %{
          "property" => property,
          "access_token" => access_token,
          "refresh_token" => refresh_token,
          "expires_at" => expires_at
        } = params
      ) do
    site = conn.assigns.site

    redirect_route = Routes.site_path(conn, :settings_imports_exports, site.domain)

    with {:ok, api_start_date} <- Google.API.get_analytics_start_date(access_token, property),
         {:ok, api_end_date} <- Google.API.get_analytics_end_date(access_token, property),
         :ok <- ensure_dates(api_start_date, api_end_date),
         {:ok, start_date, end_date} <- Imported.clamp_dates(site, api_start_date, api_end_date) do
      redirect(conn,
        to:
          Routes.google_analytics_path(conn, :confirm, site.domain,
            property: property,
            access_token: access_token,
            refresh_token: refresh_token,
            expires_at: expires_at,
            start_date: Date.to_iso8601(start_date),
            end_date: Date.to_iso8601(end_date)
          )
      )
    else
      {:error, error} when error in [:no_data, :no_time_window] ->
        params =
          params
          |> Map.take(["access_token", "refresh_token", "expires_at"])
          |> Map.put("error", Atom.to_string(error))

        property_form(conn, params)

      {:error, :rate_limit_exceeded} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics rate limit has been exceeded. Please try again later."
        )
        |> redirect(to: redirect_route)

      {:error, {:authentication_failed, message}} ->
        default_message =
          "Google Analytics authentication seems to have expired. Please try again."

        message =
          if ce?() do
            message || default_message
          else
            default_message
          end

        conn
        |> put_flash(:ttl, :timer.seconds(5))
        |> put_flash(:error, message)
        |> redirect(to: redirect_route)

      {:error, :timeout} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics API has timed out. Please try again."
        )
        |> redirect(to: redirect_route)

      {:error, _any} ->
        conn
        |> put_flash(
          :error,
          "We were unable to retrieve information from Google Analytics. If the problem persists, please contact support for assistance."
        )
        |> redirect(to: redirect_route)
    end
  end

  def confirm(conn, %{
        "property" => property,
        "access_token" => access_token,
        "refresh_token" => refresh_token,
        "expires_at" => expires_at,
        "start_date" => start_date,
        "end_date" => end_date
      }) do
    site = conn.assigns.site

    start_date = Date.from_iso8601!(start_date)
    end_date = Date.from_iso8601!(end_date)

    redirect_route = Routes.site_path(conn, :settings_imports_exports, site.domain)

    case Google.API.get_property(access_token, property) do
      {:ok, %{name: property_name, id: property}} ->
        conn
        |> assign(:skip_plausible_tracking, true)
        |> render("confirm.html",
          access_token: access_token,
          refresh_token: refresh_token,
          expires_at: expires_at,
          site: site,
          selected_property: property,
          selected_property_name: property_name,
          start_date: start_date,
          end_date: end_date
        )

      {:error, :rate_limit_exceeded} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics rate limit has been exceeded. Please try again later."
        )
        |> redirect(to: redirect_route)

      {:error, {:authentication_failed, message}} ->
        default_message =
          "Google Analytics authentication seems to have expired. Please try again."

        message =
          if ce?() do
            message || default_message
          else
            default_message
          end

        conn
        |> put_flash(:ttl, :timer.seconds(5))
        |> put_flash(:error, message)
        |> redirect(to: redirect_route)

      {:error, :timeout} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics API has timed out. Please try again."
        )
        |> redirect(to: redirect_route)

      {:error, :not_found} ->
        conn
        |> put_flash(
          :error,
          "Google Analytics property not found. Please try again."
        )
        |> redirect(to: redirect_route)

      {:error, _any} ->
        conn
        |> put_flash(
          :error,
          "We were unable to retrieve information from Google Analytics. If the problem persists, please contact support for assistance."
        )
        |> redirect(to: redirect_route)
    end
  end

  def import(conn, %{
        "property" => property,
        "start_date" => start_date,
        "end_date" => end_date,
        "access_token" => access_token,
        "refresh_token" => refresh_token,
        "expires_at" => expires_at
      }) do
    site = conn.assigns.site
    current_user = conn.assigns.current_user

    start_date = Date.from_iso8601!(start_date)
    end_date = Date.from_iso8601!(end_date)

    redirect_route = Routes.site_path(conn, :settings_imports_exports, site.domain)

    import_opts = [
      label: property,
      property: property,
      start_date: start_date,
      end_date: end_date,
      access_token: access_token,
      refresh_token: refresh_token,
      token_expires_at: expires_at
    ]

    with {:ok, start_date, end_date} <- Imported.clamp_dates(site, start_date, end_date),
         import_opts = [{:start_date, start_date}, {:end_date, end_date} | import_opts],
         {:ok, _} <- Imported.GoogleAnalytics4.new_import(site, current_user, import_opts) do
      conn
      |> put_flash(:success, "Import scheduled. An email will be sent when it completes.")
      |> redirect(to: redirect_route)
    else
      {:error, :no_time_window} ->
        conn
        |> put_flash(
          :error,
          "Import failed. No data could be imported because date range overlaps with existing data."
        )
        |> redirect(to: redirect_route)

      {:error, :import_in_progress} ->
        conn
        |> put_flash(
          :error,
          "There's another import still in progress. Please wait until it's completed or cancel it before starting a new one."
        )
        |> redirect(to: redirect_route)
    end
  end

  defp ensure_dates(%Date{}, %Date{}), do: :ok
  defp ensure_dates(_, _), do: {:error, :no_data}
end