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
Dogfood script v2 (#5504)
RobertJoonas6369d0efadac
diff --git a/assets/js/liveview/live_socket.js b/assets/js/liveview/live_socket.jsindex d87a08ff05..37bbfc5164 100644--- a/assets/js/liveview/live_socket.js+++ b/assets/js/liveview/live_socket.js@@ -18,13 +18,8 @@ if (csrfToken && websocketUrl) {Hooks.Metrics = {mounted() {this.handleEvent('send-metrics', ({ event_name }) => {- const afterMetrics = () => {- this.pushEvent('send-metrics-after', { event_name })- }- setTimeout(afterMetrics, 5000)- if (window.trackCustomEvent) {- window.trackCustomEvent(event_name, { callback: afterMetrics })- }+ window.plausible(event_name)+ this.pushEvent('send-metrics-after', { event_name })})}}diff --git a/extra/lib/plausible_web/dogfood.ex b/extra/lib/plausible_web/dogfood.exindex ee82b071ff..dc5974116f 100644--- a/extra/lib/plausible_web/dogfood.ex+++ b/extra/lib/plausible_web/dogfood.ex@@ -3,29 +3,73 @@ defmodule PlausibleWeb.Dogfood doPlausible tracking itself functions"""- @doc """- Temporary override to do more testing of the new ingest.plausible.io endpoint for accepting events. In staging and locally- will fall back to staging.plausible.io/api/event and localhost:8000/api/event respectively.- """- def api_destination() do- if Application.get_env(:plausible, :environment) == "prod" do- "https://ingest.plausible.io/api/event"- end+ def script_params(assigns) do+ %{+ script_url: script_url(assigns),+ domain_to_replace: domain_to_replace(assigns),+ location_override: location_override(assigns),+ custom_properties: custom_properties(assigns),+ capture_on_localhost: Application.get_env(:plausible, :environment) == "dev"+ }end- def script_url() do- if Application.get_env(:plausible, :environment) in ["prod", "staging"] do- "#{PlausibleWeb.Endpoint.url()}/js/script.manual.pageview-props.tagged-events.pageleave.js"- else- "#{PlausibleWeb.Endpoint.url()}/js/script.local.manual.pageview-props.tagged-events.pageleave.js"- end+ defp script_url(assigns) do+ env = Application.get_env(:plausible, :environment)+ selfhost? = Application.get_env(:plausible, :is_selfhost)++ tracker_script_config_id =+ cond do+ env == "prod" and selfhost? ->+ "V5OUguy5m04s95qHnmGbH"++ env == "prod" and assigns[:embedded] ->+ "Qo3A7Ksnbn-wYQWMijuR3"++ env == "prod" ->+ "6_srOGVV9SLMWJ1ZpUAbG"++ env == "staging" ->+ "egYOCIzzYzPL9v6GHLc-7"++ env in ["dev", "ce_dev"] ->+ # By default we're not letting the app track itself on localhost.+ # The requested script will be `s-.js` and it will respond with 404.+ # If you wish to track the app itself, uncomment the following line+ # and replace the site_id if necessary (1 stands for dummy.site).++ # PlausibleWeb.Tracker.get_or_create_tracker_script_configuration!(1).id+ ""++ env in ["test", "ce_test"] ->+ ""+ end++ "#{PlausibleWeb.Endpoint.url()}/js/s-#{tracker_script_config_id}.js"end- def domain(conn) do- cond do- Application.get_env(:plausible, :is_selfhost) -> "ee.plausible.io"- conn.assigns[:embedded] -> "embed." <> PlausibleWeb.Endpoint.host()- true -> PlausibleWeb.Endpoint.host()+ # TRICKY: The React dashboard uses history-based SPA navigation+ # which triggers pageviews on routes that the backend is unaware+ # of (e.g.`/:domain/pages`). As opposed to other site paths like+ # `/:domain/settings/general` we cannot override the entire URL.+ # To still make sure we're not capturing customer domains we run+ # a string replace in `payload.u`.+ defp domain_to_replace(assigns) do+ if not is_nil(assigns[:site]) and assigns[:demo] != true do+ URI.encode_www_form(assigns.site.domain)endend++ defp location_override(%{dogfood_page_path: path}) when is_binary(path) do+ Path.join(PlausibleWeb.Endpoint.url(), path)+ end++ defp location_override(_), do: nil++ defp custom_properties(%{current_user: user}) when is_map(user) do+ %{logged_in: true, theme: user.theme}+ end++ defp custom_properties(_) do+ %{logged_in: false}+ endenddiff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.exindex 186a8c6246..6688125649 100644--- a/lib/plausible_web/controllers/stats_controller.ex+++ b/lib/plausible_web/controllers/stats_controller.ex@@ -58,7 +58,7 @@ defmodule PlausibleWeb.StatsController docurrent_user = conn.assigns[:current_user]stats_start_date = Plausible.Sites.stats_start_date(site)can_see_stats? = not Teams.locked?(site.team) or site_role == :super_admin- demo = site.domain == PlausibleWeb.Endpoint.host()+ demo = site.domain == "plausible.io"dogfood_page_path = if demo, do: "/#{site.domain}", else: "/:dashboard"skip_to_dashboard? = conn.params["skip_to_dashboard"] == "true"@@ -83,7 +83,6 @@ defmodule PlausibleWeb.StatsController dodemo: demo,flags: flags,is_dbip: is_dbip(),- dogfood_page_path: dogfood_page_path,segments: segments,load_dashboard_js: true,hide_footer?: if(ce?() || demo, do: false, else: site_role != :public)@@ -392,7 +391,6 @@ defmodule PlausibleWeb.StatsController donative_stats_start_date: NaiveDateTime.to_date(shared_link.site.native_stats_start_at),title: title(conn, shared_link.site),demo: false,- dogfood_page_path: "/share/:dashboard",shared_link_auth: shared_link.slug,embedded: embedded?,background: conn.params["background"],diff --git a/lib/plausible_web/templates/layout/_tracking.html.heex b/lib/plausible_web/templates/layout/_tracking.html.heexindex 4db5c84388..6608bfb2c2 100644--- a/lib/plausible_web/templates/layout/_tracking.html.heex+++ b/lib/plausible_web/templates/layout/_tracking.html.heex@@ -1,44 +1,27 @@<%= on_ee do %>- <%= if [email protected][:skip_plausible_tracking] do %>- <script- defer- data-api={PlausibleWeb.Dogfood.api_destination()}- data-domain={PlausibleWeb.Dogfood.domain(@conn)}- src={PlausibleWeb.Dogfood.script_url()}- >- </script>- <script>- window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }+ <script+ :if={[email protected][:skip_plausible_tracking]}+ id="dogfood-script"+ data-script-params={JSON.encode!(PlausibleWeb.Dogfood.script_params(@conn.assigns))}+ >+ var scriptParams = JSON.parse(document.currentScript.dataset.scriptParams)- <%= if @conn.assigns[:dogfood_page_path] do %>- const pageUrl = '<%= Path.join(plausible_url(), @conn.assigns[:dogfood_page_path]) %>'- <% else %>- const pageUrl = window.location.href- <% end %>+ window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=function(i){window.plausible.o=i||{}};var script=document.createElement("script");script.type="text/javascript",script.defer=!0,script.src=scriptParams.script_url;var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(script,r);- const props = {- logged_in: <%= is_map(@conn.assigns[:current_user]) %>,+ plausible.init({+ captureOnLocalhost: scriptParams.capture_on_localhost,+ customProperties: {+ ...scriptParams.custom_properties,browser_language: navigator.language || navigator.userLanguage- }-- <%= if @conn.assigns[:current_user] do %>- props.theme = '<%= @conn.assigns[:current_user].theme %>'- <% end %>-- const defaultEventOptions = {u: pageUrl, props: props}-- window.trackCustomEvent = function(event_name, options) {- plausible(event_name, {...defaultEventOptions, ...options})- }-- plausible('pageview', defaultEventOptions)-- window.addEventListener('pageshow', function(event) {- if (event.persisted) {- // Page was restored from bfcache - trigger a pageview- plausible('pageview', defaultEventOptions);+ },+ transformRequest: function (payload) {+ if (scriptParams.location_override) {+ payload.u = scriptParams.location_override+ } else if (scriptParams.domain_to_replace) {+ payload.u = payload.u.replace(scriptParams.domain_to_replace, ':dashboard')}- })- </script>- <% end %>+ return payload+ }+ })+ </script><% end %>diff --git a/test/plausible_web/controllers/stats_controller_test.exs b/test/plausible_web/controllers/stats_controller_test.exsindex 9509e8d723..469784a478 100644--- a/test/plausible_web/controllers/stats_controller_test.exs+++ b/test/plausible_web/controllers/stats_controller_test.exs@@ -91,6 +91,7 @@ defmodule PlausibleWeb.StatsControllerTest doassert text_of_element(resp, "title") == "Plausible Analytics: Live Demo"assert resp =~ "Login"+ assert resp =~ "Want these stats for your website?"assert resp =~ "Getting started"end@@ -1482,4 +1483,101 @@ defmodule PlausibleWeb.StatsControllerTest doassert html_response(conn, 200) =~ "Enter password"endend++ describe "dogfood tracking" do+ @describetag :ee_only++ test "does not set domain_to_replace on live demo dashboard", %{conn: conn} do+ site = new_site(domain: "plausible.io", public: true)+ populate_stats(site, [build(:pageview)])+ conn = get(conn, "/#{site.domain}")+ script_params = html_response(conn, 200) |> get_script_params()++ assert %{+ "location_override" => nil,+ "domain_to_replace" => nil+ } = script_params+ end++ test "sets domain_to_replace on any other dashboard", %{conn: conn} do+ site = new_site(domain: "öö.ee", public: true)+ populate_stats(site, [build(:pageview)])+ conn = get(conn, "/#{site.domain}")+ script_params = html_response(conn, 200) |> get_script_params()++ assert %{+ "location_override" => nil,+ "domain_to_replace" => "%C3%B6%C3%B6.ee"+ } = script_params+ end++ test "sets domain_to_replace on live demo shared link", %{conn: conn} do+ site = new_site(domain: "plausible.io", public: true)+ link = insert(:shared_link, site: site)++ populate_stats(site, [build(:pageview)])++ conn = get(conn, "/share/#{site.domain}/?auth=#{link.slug}")+ script_params = html_response(conn, 200) |> get_script_params()++ assert %{+ "location_override" => nil,+ "domain_to_replace" => "plausible.io"+ } = script_params+ end++ test "sets location_override on a locked dashboard", %{conn: conn} do+ locked_site = new_site(public: true)+ locked_site.team |> Ecto.Changeset.change(locked: true) |> Repo.update!()++ conn = get(conn, "/" <> locked_site.domain)+ html = html_response(conn, 200)++ script_params = html |> get_script_params()++ assert html =~ "Dashboard Locked"+ assert script_params["location_override"] == PlausibleWeb.Endpoint.url() <> "/:dashboard"+ end++ test "sets location_override on a locked shared link", %{conn: conn} do+ locked_site = new_site()+ link = insert(:shared_link, site: locked_site)++ insert(:starter_subscription, team: locked_site.team)++ conn = get(conn, "/share/#{locked_site.domain}/?auth=#{link.slug}")+ html = html_response(conn, 200)++ script_params = get_script_params(html)++ assert html =~ "Shared Link Unavailable"++ assert script_params["location_override"] ==+ PlausibleWeb.Endpoint.url() <> "/share/:dashboard"+ end++ test "sets location_override on shared_link_password.html", %{conn: conn} do+ site = new_site()++ link =+ insert(:shared_link, site: site, password_hash: Plausible.Auth.Password.hash("password"))++ conn = get(conn, "/share/#{site.domain}?auth=#{link.slug}")+ html = html_response(conn, 200)++ script_params = get_script_params(html)++ assert html =~ "Enter password"++ assert script_params["location_override"] ==+ PlausibleWeb.Endpoint.url() <> "/share/:dashboard"+ end+ end++ defp get_script_params(html) do+ html+ |> find("#dogfood-script")+ |> text_of_attr("data-script-params")+ |> JSON.decode!()+ endend