~cadence/bibliogram-devel

This thread contains a patchset. You're looking at the original emails, but you may wish to use the patch review UI. Review patch

[PATCH] Prefer user language from request header

Суспільне Надбання <k0tyk@autistici.org>
Details
Message ID
<20220506183825.113903-1-k0tyk@autistici.org>
DKIM signature
pass
Download raw message
Patch: +28 -9
Another internationalization tweak on my instance:
taking the Accept-Language header the user sends
and defaulting to the first language present in
the Bibliogram backing translation map, if any.
---
 src/site/api/utils/getsettings.js | 37 +++++++++++++++++++++++--------
 1 file changed, 28 insertions(+), 9 deletions(-)

diff --git a/src/site/api/utils/getsettings.js b/src/site/api/utils/getsettings.js
index 65d1fe6..ffd486e 100644
--- a/src/site/api/utils/getsettings.js
+++ b/src/site/api/utils/getsettings.js
@@ -3,20 +3,39 @@ const {parse: parseCookie} = require("cookie")

const constants = require("../../../lib/constants")
const db = require("../../../lib/db")
const lang = require("../../../lang")

function addDefaults(input = {}) {
function addDefaults(req, input = {}) {
	const result = {}
	for (const setting of constants.user_settings) {
		if (input[setting.name] !== undefined) {
			result[setting.name] = input[setting.name]
		} else {
			if (setting.boolean) {
				result[setting.name] = +(setting.default !== "")
			} else if (setting.name in constants.default_user_settings) {
		} else if (setting.boolean) {
			result[setting.name] = +(setting.default !== "")
		} else if (setting.name in constants.default_user_settings) {
			if (setting.name === "language" &&
					typeof req.headers["accept-language"] === "string") {
				/* Example: uk-UA,uk;q=0.8,en-US;q=0.5,en;q=0.3
				 *
				 * Valid too: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5
				 *
				 * Browsers let users set the order. Quality values are usually
				 * automatic and match it. However, rfc7231 warns that it is
				 * only the status quo, not a requirement. */
				for (let want of
						req.headers["accept-language"].split(/\s*,\s*/)) {
					want = want.split(/\s*;\s*/)[0].toLowerCase()
					if (lang.backing.has(want)) {
						result[setting.name] = want
						break
					}
				}
			}
			if (result[setting.name] === undefined) {
				result[setting.name] = constants.default_user_settings[setting.name]
			} else {
				result[setting.name] = setting.default
			}
		} else {
			result[setting.name] = setting.default
		}
	}
	return result
@@ -35,10 +54,10 @@ function getSettings(req) {
	if (token) {
		const row = db.prepare("SELECT * FROM UserSettings WHERE token = ?").get(token)
		if (row) {
			return addDefaults(row)
			return addDefaults(req, row)
		}
	}
	return addDefaults()
	return addDefaults(req)
}

/*
-- 
2.36.0
Reply to thread Export thread (mbox)