Remove _misskey_reaction matching (#500)
[akkoma] / lib / pleroma / web / plugs / set_locale_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
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]
8
9 def frontend_language_cookie_name, do: "userLanguage"
10
11 def init(_), do: nil
12
13 def call(conn, _) do
14 locales = get_locales_from_header(conn)
15 first_locale = Enum.at(locales, 0, Gettext.get_locale())
16
17 Pleroma.Web.Gettext.put_locales(locales)
18
19 conn
20 |> assign(:locale, first_locale)
21 |> assign(:locales, locales)
22 end
23
24 defp get_locales_from_header(conn) do
25 conn
26 |> extract_preferred_language()
27 |> normalize_language_codes()
28 |> all_supported()
29 |> Enum.uniq()
30 end
31
32 defp all_supported(locales) do
33 locales
34 |> Pleroma.Web.Gettext.ensure_fallbacks()
35 |> Enum.filter(&supported_locale?/1)
36 end
37
38 defp normalize_language_codes(codes) do
39 codes
40 |> Enum.map(fn code -> Pleroma.Web.Gettext.normalize_locale(code) end)
41 end
42
43 defp extract_preferred_language(conn) do
44 extract_frontend_language(conn) ++ extract_accept_language(conn)
45 end
46
47 defp extract_frontend_language(conn) do
48 %{req_cookies: cookies} =
49 conn
50 |> Plug.Conn.fetch_cookies()
51
52 case cookies[frontend_language_cookie_name()] do
53 nil ->
54 []
55
56 fe_lang ->
57 String.split(fe_lang, ",")
58 end
59 end
60
61 defp extract_accept_language(conn) do
62 case get_req_header(conn, "accept-language") do
63 [value | _] ->
64 value
65 |> String.split(",")
66 |> Enum.map(&parse_language_option/1)
67 |> Enum.sort(&(&1.quality > &2.quality))
68 |> Enum.map(& &1.tag)
69 |> Enum.reject(&is_nil/1)
70
71 _ ->
72 []
73 end
74 end
75
76 defp supported_locale?(locale) do
77 Pleroma.Web.Gettext.supports_locale?(locale)
78 end
79
80 defp parse_language_option(string) do
81 captures = Regex.named_captures(~r/^\s?(?<tag>[\w\-]+)(?:;q=(?<quality>[\d\.]+))?$/i, string)
82
83 quality =
84 case Float.parse(captures["quality"] || "1.0") do
85 {val, _} -> val
86 :error -> 1.0
87 end
88
89 %{tag: captures["tag"], quality: quality}
90 end
91 end