Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Fix improper pattern matching on Finch responses (#2181)
Adam Rutkowski1a294854e3af
diff --git a/lib/plausible/billing/billing.ex b/lib/plausible/billing/billing.exindex d309b95c66..885dc8731a 100644--- a/lib/plausible/billing/billing.ex+++ b/lib/plausible/billing/billing.ex@@ -1,6 +1,6 @@defmodule Plausible.Billing douse Plausible.Repo- alias Plausible.Billing.{Subscription, PaddleApi}+ alias Plausible.Billing.Subscriptiondef active_subscription_for(user_id) doRepo.get_by(Subscription, user_id: user_id, status: "active")@@ -113,7 +113,16 @@ defmodule Plausible.Billing doenddef change_plan_preview(subscription, new_plan_id) do- PaddleApi.update_subscription_preview(subscription.paddle_subscription_id, new_plan_id)+ case paddle_api().update_subscription_preview(+ subscription.paddle_subscription_id,+ new_plan_id+ ) do+ {:ok, response} ->+ {:ok, response}++ {:error, reason} ->+ {:error, reason}+ endenddef needs_to_upgrade?(%Plausible.Auth.User{trial_expiry_date: nil}), do: {true, :no_trial}diff --git a/lib/plausible/billing/paddle_api.ex b/lib/plausible/billing/paddle_api.exindex 977488cf7e..92c3df5520 100644--- a/lib/plausible/billing/paddle_api.ex+++ b/lib/plausible/billing/paddle_api.ex@@ -1,11 +1,9 @@defmodule Plausible.Billing.PaddleApi doalias Plausible.HTTPClient- @update_endpoint "https://vendors.paddle.com/api/2.0/subscription/users/update"- @get_endpoint "https://vendors.paddle.com/api/2.0/subscription/users"@headers [- {"Content-type", "application/json"},- {"Accept", "application/json"}+ {"content-type", "application/json"},+ {"accept", "application/json"}]def update_subscription_preview(paddle_subscription_id, new_plan_id) do@@ -22,19 +20,18 @@ defmodule Plausible.Billing.PaddleApi doquantity: 1}- {:ok, response} =- HTTPClient.post(- vendors_domain() <> "/api/2.0/subscription/preview_update",- @headers,- Jason.encode!(params)- )+ case HTTPClient.post(preview_update_url(), @headers, params) do+ {:ok, response} ->+ body = Jason.decode!(response.body)- body = Jason.decode!(response.body)+ if body["success"] do+ {:ok, body["response"]}+ else+ {:error, body["error"]}+ end- if body["success"] do- {:ok, body["response"]}- else- {:error, body["error"]}+ {:error, error} ->+ {:error, error}endend@@ -52,13 +49,18 @@ defmodule Plausible.Billing.PaddleApi doquantity: 1})- {:ok, response} = HTTPClient.post(@update_endpoint, @headers, Jason.encode!(params))- body = Jason.decode!(response.body)+ case HTTPClient.post(update_subscription_url(), @headers, params) do+ {:ok, response} ->+ body = Jason.decode!(response.body)- if body["success"] do- {:ok, body["response"]}- else- {:error, body["error"]}+ if body["success"] do+ {:ok, body["response"]}+ else+ {:error, body["error"]}+ end++ {:error, %{reason: reason}} ->+ {:error, reason}endend@@ -71,14 +73,19 @@ defmodule Plausible.Billing.PaddleApi dosubscription_id: paddle_subscription_id}- {:ok, response} = HTTPClient.post(@get_endpoint, @headers, Jason.encode!(params))- body = Jason.decode!(response.body)+ case HTTPClient.post(get_subscription_url(), @headers, params) do+ {:ok, response} ->+ body = Jason.decode!(response.body)++ if body["success"] do+ [subscription] = body["response"]+ {:ok, subscription}+ else+ {:error, body["error"]}+ end- if body["success"] do- [subscription] = body["response"]- {:ok, subscription}- else- {:error, body["error"]}+ {:error, %{reason: reason}} ->+ {:error, reason}endend@@ -96,7 +103,7 @@ defmodule Plausible.Billing.PaddleApi doto: Timex.shift(Timex.today(), days: 1) |> Timex.format!("{YYYY}-{0M}-{0D}")}- case HTTPClient.post(invoices_endpoint(), @headers, Jason.encode!(params)) do+ case HTTPClient.post(invoices_url(), @headers, params) do{:ok, response} ->body = Jason.decode!(response.body)@@ -111,13 +118,6 @@ defmodule Plausible.Billing.PaddleApi doendend- defp invoices_endpoint() do- case Application.get_env(:plausible, :environment) do- "dev" -> "https://sandbox-vendors.paddle.com/api/2.0/subscription/payments"- _ -> "https://vendors.paddle.com/api/2.0/subscription/payments"- end- end-defp last_12_invoices(invoice_list) doEnum.sort(invoice_list, fn %{"payout_date" => d1}, %{"payout_date" => d2} ->Date.compare(Date.from_iso8601!(d1), Date.from_iso8601!(d2)) == :gt@@ -142,4 +142,20 @@ defmodule Plausible.Billing.PaddleApi dodefp get_config() doApplication.get_env(:plausible, :paddle)end++ defp invoices_url() do+ Path.join(vendors_domain(), "/api/2.0/subscription/payments")+ end++ defp preview_update_url() do+ Path.join(vendors_domain(), "/api/2.0/subscription/preview_update")+ end++ defp update_subscription_url() do+ Path.join(vendors_domain(), "/api/2.0/subscription/users/update")+ end++ defp get_subscription_url() do+ Path.join(vendors_domain(), "/api/2.0/subscription/users")+ endenddiff --git a/lib/plausible/google/http.ex b/lib/plausible/google/http.exindex cf283c618e..78cb1afd89 100644--- a/lib/plausible/google/http.ex+++ b/lib/plausible/google/http.ex@@ -97,20 +97,30 @@ defmodule Plausible.Google.HTTP dourl = "https://www.googleapis.com/webmasters/v3/sites"headers = [{"Content-Type", "application/json"}, {"Authorization", "Bearer #{access_token}"}]- {:ok, response} = HTTPClient.get(url, headers)+ case HTTPClient.get(url, headers) do+ {:ok, response} ->+ response+ |> Map.get(:body)+ |> Jason.decode!()+ |> then(&{:ok, &1})- response- |> Map.get(:body)- |> Jason.decode!()- |> then(&{:ok, &1})+ {:error, reason} = e ->+ Logger.error("Google Analytics: failed to list sites: #{reason}")+ e+ endenddef fetch_access_token(code) dourl = "https://www.googleapis.com/oauth2/v4/token"headers = [{"Content-Type", "application/x-www-form-urlencoded"}]- params =- "client_id=#{client_id()}&client_secret=#{client_secret()}&code=#{code}&grant_type=authorization_code&redirect_uri=#{redirect_uri()}"+ params = %{+ client_id: client_id(),+ client_secret: client_secret(),+ code: code,+ grant_type: :authorization_code,+ redirect_uri: redirect_uri()+ }{:ok, response} = HTTPClient.post(url, headers, params)@@ -129,13 +139,13 @@ defmodule Plausible.Google.HTTP do{:ok, %Finch.Response{body: body, status: 200}} ->{:ok, Jason.decode!(body)}- {:error, %Mint.TransportError{reason: reason}} ->- Sentry.capture_message("Error fetching Google view ID", extra: inspect(reason))- {:error, reason}-- {:error, %Finch.Response{body: body}} ->+ {:ok, %Finch.Response{body: body}} ->Sentry.capture_message("Error fetching Google view ID", extra: Jason.decode!(body)){:error, body}++ {:error, %{reason: reason}} ->+ Sentry.capture_message("Error fetching Google view ID", extra: inspect(reason))+ {:error, reason}endend@@ -150,14 +160,13 @@ defmodule Plausible.Google.HTTP do%{}end- params =- Jason.encode!(%{- startDate: Date.to_iso8601(date_range.first),- endDate: Date.to_iso8601(date_range.last),- dimensions: ["query"],- rowLimit: limit,- dimensionFilterGroups: filter_groups- })+ params = %{+ startDate: Date.to_iso8601(date_range.first),+ endDate: Date.to_iso8601(date_range.last),+ dimensions: ["query"],+ rowLimit: limit,+ dimensionFilterGroups: filter_groups+ }url = "https://www.googleapis.com/webmasters/v3/sites/#{property}/searchAnalytics/query"headers = [{"Authorization", "Bearer #{access_token}"}]@@ -178,6 +187,10 @@ defmodule Plausible.Google.HTTP do{:ok, %Finch.Response{body: body}} ->Sentry.capture_message("Error fetching Google queries", extra: Jason.decode!(body)){:error, :unknown}++ {:error, %{reason: reason}} ->+ Sentry.capture_message("Error fetching Google queries", extra: reason)+ {:error, :unknown}endend@@ -186,10 +199,15 @@ defmodule Plausible.Google.HTTP dodef refresh_auth_token(refresh_token) dourl = "https://www.googleapis.com/oauth2/v4/token"- headers = [{"Content-Type", "application/x-www-form-urlencoded"}]+ headers = [{"content-type", "application/x-www-form-urlencoded"}]- params =- "client_id=#{client_id()}&client_secret=#{client_secret()}&refresh_token=#{refresh_token}&grant_type=refresh_token&redirect_uri=#{redirect_uri()}"+ params = %{+ client_id: client_id(),+ client_secret: client_secret(),+ refresh_token: refresh_token,+ grant_type: :refresh_token,+ redirect_uri: redirect_uri()+ }case HTTPClient.post(url, headers, params) do{:ok, %Finch.Response{body: body, status: 200}} ->@@ -201,31 +219,30 @@ defmodule Plausible.Google.HTTP do|> Map.get("error")|> then(&{:error, &1})- {:error, %Finch.Response{body: body}} ->- Sentry.capture_message("Error fetching Google queries", extra: Jason.decode!(body))+ {:error, %{reason: reason}} ->+ Sentry.capture_message("Error fetching Google queries", extra: reason){:error, :unknown}endend@earliest_valid_date "2005-01-01"def get_analytics_start_date(view_id, access_token) do- params =- Jason.encode!(%{- reportRequests: [- %{- viewId: view_id,- dateRanges: [- %{startDate: @earliest_valid_date, endDate: Date.to_iso8601(Timex.today())}- ],- dimensions: [%{name: "ga:date", histogramBuckets: []}],- metrics: [%{expression: "ga:pageviews"}],- hideTotals: true,- hideValueRanges: true,- orderBys: [%{fieldName: "ga:date", sortOrder: "ASCENDING"}],- pageSize: 1- }- ]- })+ params = %{+ reportRequests: [+ %{+ viewId: view_id,+ dateRanges: [+ %{startDate: @earliest_valid_date, endDate: Date.to_iso8601(Timex.today())}+ ],+ dimensions: [%{name: "ga:date", histogramBuckets: []}],+ metrics: [%{expression: "ga:pageviews"}],+ hideTotals: true,+ hideValueRanges: true,+ orderBys: [%{fieldName: "ga:date", sortOrder: "ASCENDING"}],+ pageSize: 1+ }+ ]+ }url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet"headers = [{"Authorization", "Bearer #{access_token}"}]@@ -245,9 +262,13 @@ defmodule Plausible.Google.HTTP do{:ok, date}- {:error, %Finch.Response{body: body}} ->+ {:ok, %Finch.Response{body: body}} ->Sentry.capture_message("Error fetching Google view ID", extra: Jason.decode!(body)){:error, body}++ {:error, %{reason: reason}} ->+ Sentry.capture_message("Error fetching Google view ID", extra: reason)+ {:error, reason}endenddiff --git a/lib/plausible/http_client.ex b/lib/plausible/http_client.exindex f493bd9b72..2a971e35db 100644--- a/lib/plausible/http_client.ex+++ b/lib/plausible/http_client.ex@@ -1,23 +1,38 @@defmodule Plausible.HTTPClient do@moduledoc """HTTP Client built on top of Finch.++ By default, request parameters are json-encoded.++ If a raw binary value is supplied, no encoding is performed.+ If x-www-form-urlencoded content-type is set in headers,+ URL encoding is invoked."""+ @type url() :: Finch.Request.url()+ @type headers() :: Finch.Request.headers()+ @type params() :: Finch.Request.body() | map()+ @type response() :: {:ok, Finch.Response.t()} | {:error, Mint.Types.error() | Finch.Error.t()}+@doc """Make a POST request"""- def post(url, headers \\ [], params \\ nil) do+ @spec post(url(), headers(), params()) :: response()+ def(post(url, headers \\ [], params \\ nil)) docall(:post, url, headers, params)end@doc """Make a GET request"""+ @spec get(url(), headers(), params()) :: response()def get(url, headers \\ [], params \\ nil) docall(:get, url, headers, params)enddefp call(method, url, headers, params) do+ params = maybe_encode_params(params, headers)+method|> build_request(url, headers, params)|> do_request@@ -30,4 +45,25 @@ defmodule Plausible.HTTPClient dodefp do_request(request) doFinch.request(request, Plausible.Finch)end++ defp maybe_encode_params(params, _headers) when is_binary(params) or is_nil(params) do+ params+ end++ defp maybe_encode_params(params, headers) when is_map(params) do+ content_type =+ Enum.find_value(headers, "", fn {k, v} ->+ if String.downcase(k) == "content-type" do+ v+ end+ end)++ case String.downcase(content_type) do+ "x-www-form-urlencoded" ->+ URI.encode_query(params)++ _ ->+ Jason.encode!(params)+ end+ endenddiff --git a/lib/plausible_web/captcha.ex b/lib/plausible_web/captcha.exindex bffde5634a..dcb5616eb4 100644--- a/lib/plausible_web/captcha.ex+++ b/lib/plausible_web/captcha.ex@@ -17,8 +17,11 @@ defmodule PlausibleWeb.Captcha dores =HTTPClient.post(@verify_endpoint,- [{"Content-Type", "application/x-www-form-urlencoded"}],- "response=#{token}&secret=#{secret()}"+ [{"content-type", "application/x-www-form-urlencoded"}],+ %{+ response: token,+ secret: secret()+ })case res dodiff --git a/lib/plausible_web/controllers/billing_controller.ex b/lib/plausible_web/controllers/billing_controller.exindex e54109446d..22dacba709 100644--- a/lib/plausible_web/controllers/billing_controller.ex+++ b/lib/plausible_web/controllers/billing_controller.ex@@ -109,18 +109,16 @@ defmodule PlausibleWeb.BillingController doenddef change_plan_preview(conn, %{"plan_id" => new_plan_id}) do- subscription = Billing.active_subscription_for(conn.assigns[:current_user].id)-- if subscription do- {:ok, preview_info} = Billing.change_plan_preview(subscription, new_plan_id)-+ with {:ok, {subscription, preview_info}} <-+ preview_subscription(conn.assigns.current_user, new_plan_id) dorender(conn, "change_plan_preview.html",subscription: subscription,preview_info: preview_info,layout: {PlausibleWeb.LayoutView, "focus.html"})else- redirect(conn, to: "/billing/upgrade")+ _ ->+ redirect(conn, to: "/billing/upgrade")endend@@ -159,4 +157,20 @@ defmodule PlausibleWeb.BillingController do|> redirect(to: "/settings")endend++ defp preview_subscription(%{id: user_id}, new_plan_id) do+ subscription = Billing.active_subscription_for(user_id)++ if subscription do+ with {:ok, preview_info} <- Billing.change_plan_preview(subscription, new_plan_id) do+ {:ok, {subscription, preview_info}}+ end+ else+ {:error, :no_subscription}+ end+ end++ def preview_susbcription(_, _) do+ {:error, :no_user_id}+ endend