feat: add server default locale setting (#1536)

* feat: add server default locale setting

* fix: do not modify defaultLocale property of IntlProvider
pull/1556/head
TheCatLady 3 years ago committed by GitHub
parent 4fd452dd18
commit f256a444c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -103,8 +103,10 @@ components:
properties: properties:
apiKey: apiKey:
type: string type: string
example: 'anapikey'
readOnly: true readOnly: true
appLanguage:
type: string
example: en
applicationTitle: applicationTitle:
type: string type: string
example: Overseerr example: Overseerr

@ -45,7 +45,6 @@
"node-cache": "^5.1.2", "node-cache": "^5.1.2",
"node-schedule": "^2.0.0", "node-schedule": "^2.0.0",
"nodemailer": "^6.5.0", "nodemailer": "^6.5.0",
"nookies": "^2.5.2",
"openpgp": "^5.0.0-1", "openpgp": "^5.0.0-1",
"plex-api": "^5.3.1", "plex-api": "^5.3.1",
"pug": "^3.0.2", "pug": "^3.0.2",

@ -32,6 +32,7 @@ export interface PublicSettingsResponse {
cacheImages: boolean; cacheImages: boolean;
vapidPublic: string; vapidPublic: string;
enablePushRegistration: boolean; enablePushRegistration: boolean;
locale: string;
} }
export interface CacheItem { export interface CacheItem {

@ -88,6 +88,7 @@ export interface MainSettings {
originalLanguage: string; originalLanguage: string;
trustProxy: boolean; trustProxy: boolean;
partialRequestsEnabled: boolean; partialRequestsEnabled: boolean;
locale: string;
} }
interface PublicSettings { interface PublicSettings {
@ -106,6 +107,7 @@ interface FullPublicSettings extends PublicSettings {
cacheImages: boolean; cacheImages: boolean;
vapidPublic: string; vapidPublic: string;
enablePushRegistration: boolean; enablePushRegistration: boolean;
locale: string;
} }
export interface NotificationAgentConfig { export interface NotificationAgentConfig {
@ -249,6 +251,7 @@ class Settings {
originalLanguage: '', originalLanguage: '',
trustProxy: false, trustProxy: false,
partialRequestsEnabled: true, partialRequestsEnabled: true,
locale: 'en',
}, },
plex: { plex: {
name: '', name: '',
@ -411,6 +414,7 @@ class Settings {
cacheImages: this.data.main.cacheImages, cacheImages: this.data.main.cacheImages,
vapidPublic: this.vapidPublic, vapidPublic: this.vapidPublic,
enablePushRegistration: this.data.notifications.agents.webpush.enabled, enablePushRegistration: this.data.notifications.agents.webpush.enabled,
locale: this.data.main.locale,
}; };
} }

@ -5,6 +5,7 @@ import { getSettings } from '../lib/settings';
export const checkUser: Middleware = async (req, _res, next) => { export const checkUser: Middleware = async (req, _res, next) => {
const settings = getSettings(); const settings = getSettings();
if (req.header('X-API-Key') === settings.main.apiKey) { if (req.header('X-API-Key') === settings.main.apiKey) {
const userRepository = getRepository(User); const userRepository = getRepository(User);
@ -28,9 +29,12 @@ export const checkUser: Middleware = async (req, _res, next) => {
if (user) { if (user) {
req.user = user; req.user = user;
req.locale = user.settings?.locale; req.locale = user.settings?.locale
? user.settings?.locale
: settings.main.locale;
} }
} }
next(); next();
}; };

@ -6,7 +6,13 @@ import { defineMessages, useIntl } from 'react-intl';
import { useToasts } from 'react-toast-notifications'; import { useToasts } from 'react-toast-notifications';
import useSWR, { mutate } from 'swr'; import useSWR, { mutate } from 'swr';
import * as Yup from 'yup'; import * as Yup from 'yup';
import { UserSettingsGeneralResponse } from '../../../server/interfaces/api/userSettingsInterfaces';
import type { MainSettings } from '../../../server/lib/settings'; import type { MainSettings } from '../../../server/lib/settings';
import {
availableLanguages,
AvailableLocales,
} from '../../context/LanguageContext';
import useLocale from '../../hooks/useLocale';
import { Permission, useUser } from '../../hooks/useUser'; import { Permission, useUser } from '../../hooks/useUser';
import globalMessages from '../../i18n/globalMessages'; import globalMessages from '../../i18n/globalMessages';
import Badge from '../Common/Badge'; import Badge from '../Common/Badge';
@ -50,15 +56,20 @@ const messages = defineMessages({
validationApplicationUrl: 'You must provide a valid URL', validationApplicationUrl: 'You must provide a valid URL',
validationApplicationUrlTrailingSlash: 'URL must not end in a trailing slash', validationApplicationUrlTrailingSlash: 'URL must not end in a trailing slash',
partialRequestsEnabled: 'Allow Partial Series Requests', partialRequestsEnabled: 'Allow Partial Series Requests',
locale: 'Display Language',
}); });
const SettingsMain: React.FC = () => { const SettingsMain: React.FC = () => {
const { addToast } = useToasts(); const { addToast } = useToasts();
const { hasPermission: userHasPermission } = useUser(); const { user: currentUser, hasPermission: userHasPermission } = useUser();
const intl = useIntl(); const intl = useIntl();
const { setLocale } = useLocale();
const { data, error, revalidate } = useSWR<MainSettings>( const { data, error, revalidate } = useSWR<MainSettings>(
'/api/v1/settings/main' '/api/v1/settings/main'
); );
const { data: userData } = useSWR<UserSettingsGeneralResponse>(
currentUser ? `/api/v1/user/${currentUser.id}/settings/main` : null
);
const MainSettingsSchema = Yup.object().shape({ const MainSettingsSchema = Yup.object().shape({
applicationTitle: Yup.string().required( applicationTitle: Yup.string().required(
@ -122,6 +133,7 @@ const SettingsMain: React.FC = () => {
applicationUrl: data?.applicationUrl, applicationUrl: data?.applicationUrl,
csrfProtection: data?.csrfProtection, csrfProtection: data?.csrfProtection,
hideAvailable: data?.hideAvailable, hideAvailable: data?.hideAvailable,
locale: data?.locale ?? 'en',
region: data?.region, region: data?.region,
originalLanguage: data?.originalLanguage, originalLanguage: data?.originalLanguage,
partialRequestsEnabled: data?.partialRequestsEnabled, partialRequestsEnabled: data?.partialRequestsEnabled,
@ -136,6 +148,7 @@ const SettingsMain: React.FC = () => {
applicationUrl: values.applicationUrl, applicationUrl: values.applicationUrl,
csrfProtection: values.csrfProtection, csrfProtection: values.csrfProtection,
hideAvailable: values.hideAvailable, hideAvailable: values.hideAvailable,
locale: values.locale,
region: values.region, region: values.region,
originalLanguage: values.originalLanguage, originalLanguage: values.originalLanguage,
partialRequestsEnabled: values.partialRequestsEnabled, partialRequestsEnabled: values.partialRequestsEnabled,
@ -143,6 +156,14 @@ const SettingsMain: React.FC = () => {
}); });
mutate('/api/v1/settings/public'); mutate('/api/v1/settings/public');
if (setLocale) {
setLocale(
(userData?.locale
? userData.locale
: values.locale) as AvailableLocales
);
}
addToast(intl.formatMessage(messages.toastSettingsSuccess), { addToast(intl.formatMessage(messages.toastSettingsSuccess), {
autoDismiss: true, autoDismiss: true,
appearance: 'success', appearance: 'success',
@ -271,6 +292,28 @@ const SettingsMain: React.FC = () => {
/> />
</div> </div>
</div> </div>
<div className="form-row">
<label htmlFor="locale" className="text-label">
{intl.formatMessage(messages.locale)}
</label>
<div className="form-input">
<div className="form-input-field">
<Field as="select" id="locale" name="locale">
{(Object.keys(
availableLanguages
) as (keyof typeof availableLanguages)[]).map((key) => (
<option
key={key}
value={availableLanguages[key].code}
lang={availableLanguages[key].code}
>
{availableLanguages[key].display}
</option>
))}
</Field>
</div>
</div>
</div>
<div className="form-row"> <div className="form-row">
<label htmlFor="region" className="text-label"> <label htmlFor="region" className="text-label">
<span>{intl.formatMessage(messages.region)}</span> <span>{intl.formatMessage(messages.region)}</span>

@ -44,12 +44,13 @@ const messages = defineMessages({
seriesrequestlimit: 'Series Request Limit', seriesrequestlimit: 'Series Request Limit',
enableOverride: 'Enable Override', enableOverride: 'Enable Override',
applanguage: 'Display Language', applanguage: 'Display Language',
languageDefault: 'Default ({language})',
}); });
const UserGeneralSettings: React.FC = () => { const UserGeneralSettings: React.FC = () => {
const intl = useIntl(); const intl = useIntl();
const { addToast } = useToasts(); const { addToast } = useToasts();
const { setLocale } = useLocale(); const { locale, setLocale } = useLocale();
const [movieQuotaEnabled, setMovieQuotaEnabled] = useState(false); const [movieQuotaEnabled, setMovieQuotaEnabled] = useState(false);
const [tvQuotaEnabled, setTvQuotaEnabled] = useState(false); const [tvQuotaEnabled, setTvQuotaEnabled] = useState(false);
const router = useRouter(); const router = useRouter();
@ -120,7 +121,11 @@ const UserGeneralSettings: React.FC = () => {
}); });
if (currentUser?.id === user?.id && setLocale) { if (currentUser?.id === user?.id && setLocale) {
setLocale(values.locale as AvailableLocales); setLocale(
(values.locale
? values.locale
: currentSettings.locale) as AvailableLocales
);
} }
addToast(intl.formatMessage(messages.toastSettingsSuccess), { addToast(intl.formatMessage(messages.toastSettingsSuccess), {
@ -198,10 +203,20 @@ const UserGeneralSettings: React.FC = () => {
<div className="form-input"> <div className="form-input">
<div className="form-input-field"> <div className="form-input-field">
<Field as="select" id="locale" name="locale"> <Field as="select" id="locale" name="locale">
<option value="" lang={locale}>
{intl.formatMessage(messages.languageDefault, {
language:
availableLanguages[currentSettings.locale].display,
})}
</option>
{(Object.keys( {(Object.keys(
availableLanguages availableLanguages
) as (keyof typeof availableLanguages)[]).map((key) => ( ) as (keyof typeof availableLanguages)[]).map((key) => (
<option key={key} value={availableLanguages[key].code}> <option
key={key}
value={availableLanguages[key].code}
lang={availableLanguages[key].code}
>
{availableLanguages[key].display} {availableLanguages[key].display}
</option> </option>
))} ))}

@ -19,6 +19,7 @@ const defaultSettings = {
cacheImages: false, cacheImages: false,
vapidPublic: '', vapidPublic: '',
enablePushRegistration: false, enablePushRegistration: false,
locale: 'en',
}; };
export const SettingsContext = React.createContext<SettingsContextProps>({ export const SettingsContext = React.createContext<SettingsContextProps>({

@ -566,6 +566,7 @@
"components.Settings.hostname": "Hostname or IP Address", "components.Settings.hostname": "Hostname or IP Address",
"components.Settings.is4k": "4K", "components.Settings.is4k": "4K",
"components.Settings.librariesRemaining": "Libraries Remaining: {count}", "components.Settings.librariesRemaining": "Libraries Remaining: {count}",
"components.Settings.locale": "Display Language",
"components.Settings.manualscan": "Manual Library Scan", "components.Settings.manualscan": "Manual Library Scan",
"components.Settings.manualscanDescription": "Normally, this will only be run once every 24 hours. Overseerr will check your Plex server's recently added more aggressively. If this is your first time configuring Plex, a one-time full manual library scan is recommended!", "components.Settings.manualscanDescription": "Normally, this will only be run once every 24 hours. Overseerr will check your Plex server's recently added more aggressively. If this is your first time configuring Plex, a one-time full manual library scan is recommended!",
"components.Settings.mediaTypeMovie": "movie", "components.Settings.mediaTypeMovie": "movie",
@ -735,6 +736,7 @@
"components.UserProfile.UserSettings.UserGeneralSettings.enableOverride": "Enable Override", "components.UserProfile.UserSettings.UserGeneralSettings.enableOverride": "Enable Override",
"components.UserProfile.UserSettings.UserGeneralSettings.general": "General", "components.UserProfile.UserSettings.UserGeneralSettings.general": "General",
"components.UserProfile.UserSettings.UserGeneralSettings.generalsettings": "General Settings", "components.UserProfile.UserSettings.UserGeneralSettings.generalsettings": "General Settings",
"components.UserProfile.UserSettings.UserGeneralSettings.languageDefault": "Default ({language})",
"components.UserProfile.UserSettings.UserGeneralSettings.localuser": "Local User", "components.UserProfile.UserSettings.UserGeneralSettings.localuser": "Local User",
"components.UserProfile.UserSettings.UserGeneralSettings.movierequestlimit": "Movie Request Limit", "components.UserProfile.UserSettings.UserGeneralSettings.movierequestlimit": "Movie Request Limit",
"components.UserProfile.UserSettings.UserGeneralSettings.originallanguage": "Discover Language", "components.UserProfile.UserSettings.UserGeneralSettings.originallanguage": "Discover Language",

@ -119,7 +119,7 @@ const CoreApp: Omit<NextAppComponentType, 'origGetInitialProps'> = ({
<InteractionProvider> <InteractionProvider>
<ToastProvider components={{ Toast, ToastContainer }}> <ToastProvider components={{ Toast, ToastContainer }}>
<Head> <Head>
<title>Overseerr</title> <title>{currentSettings.applicationTitle}</title>
<meta <meta
name="viewport" name="viewport"
content="initial-scale=1, viewport-fit=cover, width=device-width" content="initial-scale=1, viewport-fit=cover, width=device-width"
@ -156,6 +156,7 @@ CoreApp.getInitialProps = async (initialProps) => {
cacheImages: false, cacheImages: false,
vapidPublic: '', vapidPublic: '',
enablePushRegistration: false, enablePushRegistration: false,
locale: 'en',
}; };
if (ctx.res) { if (ctx.res) {
@ -209,7 +210,9 @@ CoreApp.getInitialProps = async (initialProps) => {
initialProps initialProps
); );
const locale = user?.settings?.locale ?? 'en'; const locale = user?.settings?.locale
? user.settings.locale
: currentSettings.locale;
const messages = await loadLocaleData(locale as AvailableLocales); const messages = await loadLocaleData(locale as AvailableLocales);

@ -1,8 +1,7 @@
import React from 'react'; import axios from 'axios';
import { GetServerSideProps, NextPage } from 'next'; import { GetServerSideProps, NextPage } from 'next';
import React from 'react';
import type { Collection } from '../../../../server/models/Collection'; import type { Collection } from '../../../../server/models/Collection';
import axios from 'axios';
import { parseCookies } from 'nookies';
import CollectionDetails from '../../../components/CollectionDetails'; import CollectionDetails from '../../../components/CollectionDetails';
interface CollectionPageProps { interface CollectionPageProps {
@ -16,11 +15,10 @@ const CollectionPage: NextPage<CollectionPageProps> = ({ collection }) => {
export const getServerSideProps: GetServerSideProps<CollectionPageProps> = async ( export const getServerSideProps: GetServerSideProps<CollectionPageProps> = async (
ctx ctx
) => { ) => {
const cookies = parseCookies(ctx);
const response = await axios.get<Collection>( const response = await axios.get<Collection>(
`http://localhost:${process.env.PORT || 5055}/api/v1/collection/${ `http://localhost:${process.env.PORT || 5055}/api/v1/collection/${
ctx.query.collectionId ctx.query.collectionId
}${cookies.locale ? `?language=${cookies.locale}` : ''}`, }`,
{ {
headers: ctx.req?.headers?.cookie headers: ctx.req?.headers?.cookie
? { cookie: ctx.req.headers.cookie } ? { cookie: ctx.req.headers.cookie }

@ -1,9 +1,8 @@
import React from 'react'; import axios from 'axios';
import { NextPage } from 'next'; import { NextPage } from 'next';
import React from 'react';
import type { MovieDetails as MovieDetailsType } from '../../../../server/models/Movie'; import type { MovieDetails as MovieDetailsType } from '../../../../server/models/Movie';
import MovieDetails from '../../../components/MovieDetails'; import MovieDetails from '../../../components/MovieDetails';
import axios from 'axios';
import { parseCookies } from 'nookies';
interface MoviePageProps { interface MoviePageProps {
movie?: MovieDetailsType; movie?: MovieDetailsType;
@ -15,11 +14,10 @@ const MoviePage: NextPage<MoviePageProps> = ({ movie }) => {
MoviePage.getInitialProps = async (ctx) => { MoviePage.getInitialProps = async (ctx) => {
if (ctx.req) { if (ctx.req) {
const cookies = parseCookies(ctx);
const response = await axios.get<MovieDetailsType>( const response = await axios.get<MovieDetailsType>(
`http://localhost:${process.env.PORT || 5055}/api/v1/movie/${ `http://localhost:${process.env.PORT || 5055}/api/v1/movie/${
ctx.query.movieId ctx.query.movieId
}${cookies.locale ? `?language=${cookies.locale}` : ''}`, }`,
{ {
headers: ctx.req?.headers?.cookie headers: ctx.req?.headers?.cookie
? { cookie: ctx.req.headers.cookie } ? { cookie: ctx.req.headers.cookie }

@ -1,9 +1,8 @@
import React from 'react';
import { NextPage } from 'next';
import axios from 'axios'; import axios from 'axios';
import { parseCookies } from 'nookies'; import { NextPage } from 'next';
import TvDetails from '../../../components/TvDetails'; import React from 'react';
import type { TvDetails as TvDetailsType } from '../../../../server/models/Tv'; import type { TvDetails as TvDetailsType } from '../../../../server/models/Tv';
import TvDetails from '../../../components/TvDetails';
interface TvPageProps { interface TvPageProps {
tv?: TvDetailsType; tv?: TvDetailsType;
@ -15,11 +14,10 @@ const TvPage: NextPage<TvPageProps> = ({ tv }) => {
TvPage.getInitialProps = async (ctx) => { TvPage.getInitialProps = async (ctx) => {
if (ctx.req) { if (ctx.req) {
const cookies = parseCookies(ctx);
const response = await axios.get<TvDetailsType>( const response = await axios.get<TvDetailsType>(
`http://localhost:${process.env.PORT || 5055}/api/v1/tv/${ `http://localhost:${process.env.PORT || 5055}/api/v1/tv/${
ctx.query.tvId ctx.query.tvId
}${cookies.locale ? `?language=${cookies.locale}` : ''}`, }`,
{ {
headers: ctx.req?.headers?.cookie headers: ctx.req?.headers?.cookie
? { cookie: ctx.req.headers.cookie } ? { cookie: ctx.req.headers.cookie }

@ -4419,11 +4419,6 @@ cookie@0.4.0:
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba"
integrity sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg== integrity sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==
cookie@^0.4.1:
version "0.4.1"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.1.tgz#afd713fe26ebd21ba95ceb61f9a8116e50a537d1"
integrity sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA==
copy-concurrently@^1.0.0: copy-concurrently@^1.0.0:
version "1.0.5" version "1.0.5"
resolved "https://registry.yarnpkg.com/copy-concurrently/-/copy-concurrently-1.0.5.tgz#92297398cae34937fcafd6ec8139c18051f0b5e0" resolved "https://registry.yarnpkg.com/copy-concurrently/-/copy-concurrently-1.0.5.tgz#92297398cae34937fcafd6ec8139c18051f0b5e0"
@ -9584,14 +9579,6 @@ noms@0.0.0:
inherits "^2.0.1" inherits "^2.0.1"
readable-stream "~1.0.31" readable-stream "~1.0.31"
nookies@^2.5.2:
version "2.5.2"
resolved "https://registry.yarnpkg.com/nookies/-/nookies-2.5.2.tgz#cc55547efa982d013a21475bd0db0c02c1b35b27"
integrity sha512-x0TRSaosAEonNKyCrShoUaJ5rrT5KHRNZ5DwPCuizjgrnkpE5DRf3VL7AyyQin4htict92X1EQ7ejDbaHDVdYA==
dependencies:
cookie "^0.4.1"
set-cookie-parser "^2.4.6"
nopt@^4.0.1, nopt@^4.0.3: nopt@^4.0.1, nopt@^4.0.3:
version "4.0.3" version "4.0.3"
resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.3.tgz#a375cad9d02fd921278d954c2254d5aa57e15e48" resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.3.tgz#a375cad9d02fd921278d954c2254d5aa57e15e48"
@ -12156,11 +12143,6 @@ set-blocking@^2.0.0, set-blocking@~2.0.0:
resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7"
integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc=
set-cookie-parser@^2.4.6:
version "2.4.6"
resolved "https://registry.yarnpkg.com/set-cookie-parser/-/set-cookie-parser-2.4.6.tgz#43bdea028b9e6f176474ee5298e758b4a44799c3"
integrity sha512-mNCnTUF0OYPwYzSHbdRdCfNNHqrne+HS5tS5xNb6yJbdP9wInV0q5xPLE0EyfV/Q3tImo3y/OXpD8Jn0Jtnjrg==
set-harmonic-interval@^1.0.1: set-harmonic-interval@^1.0.1:
version "1.0.1" version "1.0.1"
resolved "https://registry.yarnpkg.com/set-harmonic-interval/-/set-harmonic-interval-1.0.1.tgz#e1773705539cdfb80ce1c3d99e7f298bb3995249" resolved "https://registry.yarnpkg.com/set-harmonic-interval/-/set-harmonic-interval-1.0.1.tgz#e1773705539cdfb80ce1c3d99e7f298bb3995249"

Loading…
Cancel
Save