1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 # NOTE: this module is based on https://github.com/smeevil/set_locale
6 defmodule Pleroma.Web.Plugs.SetLocalePlug do
7 import Plug.Conn, only: [get_req_header: 2, assign: 3]
9 def frontend_language_cookie_name, do: "userLanguage"
14 locales = get_locales_from_header(conn)
15 first_locale = Enum.at(locales, 0, Gettext.get_locale())
17 Pleroma.Web.Gettext.put_locales(locales)
20 |> assign(:locale, first_locale)
21 |> assign(:locales, locales)
24 defp get_locales_from_header(conn) do
26 |> extract_preferred_language()
27 |> normalize_language_codes()
32 defp all_supported(locales) do
34 |> Pleroma.Web.Gettext.ensure_fallbacks()
35 |> Enum.filter(&supported_locale?/1)
38 defp normalize_language_codes(codes) do
40 |> Enum.map(fn code -> Pleroma.Web.Gettext.normalize_locale(code) end)
43 defp extract_preferred_language(conn) do
44 extract_frontend_language(conn) ++ extract_accept_language(conn)
47 defp extract_frontend_language(conn) do
48 %{req_cookies: cookies} =
50 |> Plug.Conn.fetch_cookies()
52 case cookies[frontend_language_cookie_name()] do
57 String.split(fe_lang, ",")
61 defp extract_accept_language(conn) do
62 case get_req_header(conn, "accept-language") do
66 |> Enum.map(&parse_language_option/1)
67 |> Enum.sort(&(&1.quality > &2.quality))
69 |> Enum.reject(&is_nil/1)
76 defp supported_locale?(locale) do
77 Pleroma.Web.Gettext.supports_locale?(locale)
80 defp parse_language_option(string) do
81 captures = Regex.named_captures(~r/^\s?(?<tag>[\w\-]+)(?:;q=(?<quality>[\d\.]+))?$/i, string)
84 case Float.parse(captures["quality"] || "1.0") do
89 %{tag: captures["tag"], quality: quality}