refinspector.ex 856 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. defmodule PlausibleWeb.RefInspector do
  2. def parse(nil), do: nil
  3. def parse(ref) do
  4. case ref.source do
  5. :unknown ->
  6. uri = URI.parse(String.trim(ref.referer))
  7. if right_uri?(uri) do
  8. format_referrer_host(uri)
  9. end
  10. source ->
  11. source
  12. end
  13. end
  14. def format_referrer(uri) do
  15. path = String.trim_trailing(uri.path || "", "/")
  16. format_referrer_host(uri) <> path
  17. end
  18. def right_uri?(%URI{host: nil}), do: false
  19. def right_uri?(%URI{host: host, scheme: scheme})
  20. when scheme in ["http", "https", "android-app"] and byte_size(host) > 0,
  21. do: true
  22. def right_uri?(_), do: false
  23. defp format_referrer_host(uri) do
  24. protocol = if uri.scheme == "android-app", do: "android-app://", else: ""
  25. host = String.replace_prefix(uri.host, "www.", "")
  26. protocol <> host
  27. end
  28. end