From fceb8093f17f3fce8462e619d3fddc7399672771 Mon Sep 17 00:00:00 2001 From: syeopite <70992037+syeopite@users.noreply.github.com> Date: Tue, 24 Aug 2021 19:59:27 +0000 Subject: [PATCH] Use `athena-negotiation` to detect language through Accept-Language header (#2324) Detect language through Accept-Language header --- shard.lock | 4 ++++ shard.yml | 3 +++ src/invidious.cr | 17 ++++++++++++++--- src/invidious/routes/login.cr | 7 +++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/shard.lock b/shard.lock index 35d1aefd..bfb54ee1 100644 --- a/shard.lock +++ b/shard.lock @@ -1,5 +1,9 @@ version: 2.0 shards: + athena-negotiation: + git: https://github.com/athena-framework/negotiation.git + version: 0.1.1 + db: git: https://github.com/crystal-lang/crystal-db.git version: 0.10.1 diff --git a/shard.yml b/shard.yml index 2df4909c..3292e505 100644 --- a/shard.yml +++ b/shard.yml @@ -25,6 +25,9 @@ dependencies: lsquic: github: iv-org/lsquic.cr version: ~> 2.18.1-2 + athena-negotiation: + github: athena-framework/negotiation + version: ~> 0.1.1 crystal: ">= 1.0.0, < 2.0.0" diff --git a/src/invidious.cr b/src/invidious.cr index c940dadf..4d739340 100644 --- a/src/invidious.cr +++ b/src/invidious.cr @@ -17,6 +17,7 @@ require "digest/md5" require "file_utils" require "kemal" +require "athena-negotiation" require "openssl/hmac" require "option_parser" require "pg" @@ -166,10 +167,20 @@ def popular_videos end before_all do |env| - preferences = begin - Preferences.from_json(URI.decode_www_form(env.request.cookies["PREFS"]?.try &.value || "{}")) + preferences = Preferences.from_json("{}") + + begin + if prefs_cookie = env.request.cookies["PREFS"]? + preferences = Preferences.from_json(URI.decode_www_form(prefs_cookie.value)) + else + if language_header = env.request.headers["Accept-Language"]? + if language = ANG.language_negotiator.best(language_header, LOCALES.keys) + preferences.locale = language.header + end + end + end rescue - Preferences.from_json("{}") + preferences = Preferences.from_json("{}") end env.set "preferences", preferences diff --git a/src/invidious/routes/login.cr b/src/invidious/routes/login.cr index 21d3fafd..f052d3f4 100644 --- a/src/invidious/routes/login.cr +++ b/src/invidious/routes/login.cr @@ -434,6 +434,13 @@ module Invidious::Routes::Login sid = Base64.urlsafe_encode(Random::Secure.random_bytes(32)) user, sid = create_user(sid, email, password) + + if language_header = env.request.headers["Accept-Language"]? + if language = ANG.language_negotiator.best(language_header, LOCALES.keys) + user.preferences.locale = language.header + end + end + user_array = user.to_a user_array[4] = user_array[4].to_json # User preferences