Skip to content

Fix getLocale calling back twice and repeating the failing locale - #4357

Open
jamalkamaladdin wants to merge 1 commit into
code-charity:masterfrom
jamalkamaladdin:fix/issue-4108
Open

jamalkamaladdin wants to merge 1 commit into
code-charity:masterfrom
jamalkamaladdin:fix/issue-4108

Conversation

@jamalkamaladdin

Copy link
Copy Markdown
Contributor

Fixes #4108.

getLocale fetched the two letter locale code on the first try, not the full locale.
Region locales such as pt_BR, en_GB, and es_419 in _locales were never requested directly.
On failure it called getLocale('en', callback) twice.
Callback and updateContextMenu each ran twice for every locale lookup that missed.
getLocale now tries the full locale first, then the two letter code, then en.

@ImprovedTube2

Copy link
Copy Markdown
Member

hi and thank you @jamalkamaladdin
make sense!

  1. Sorry, this function yet only translates the 2 words on right click on the extension (rate me, donate).
    So (as of now) we should avoid loading the whole file there, so we could skip / save the computing in background.js

  2. For the buttons added to youtube.com we currently use static Englisch terms only 😆

  3. For our settings menu we use the following function falling back per message in two steps per message,
    to make it possible to deduplicate our locale files beyond standard
    (pt_BR and pt_PT only require their have unique changes, compared to pt. Finally the gaps in pt are fetched from en.)

    youtube/menu/satus.js

    Lines 1033 to 1091 in 1971426

    function importLocale (locale, successCallback) {
    promiseChain = promiseChain.then(() => {
    var url = chrome.runtime.getURL(path + locale + '/messages.json');
    return fetch(url)
    .then(response => response.ok ? response.json() : {})
    .then(data => {
    for (var key in data) {
    if (!satus.locale.data[key]) {
    satus.locale.data[key] = data[key].message;
    }
    }
    })
    .catch(() => {})
    .finally(() => successCallback && successCallback());
    });
    }
    if (code) {
    let language = code.replace('-', '_');
    if (language.indexOf('_') !== -1) {
    importLocale(language, () => importLocale(language.split('_')[0], () => importLocale('en', callback)));
    } else {
    importLocale(language, () => importLocale('en', callback));
    }
    } else { // try chrome://settings/languages:
    try {
    chrome.i18n.getAcceptLanguages(function (languages) {
    languages = languages.map(language => language.replace('-', '_'));
    for (let i = languages.length - 1; i >= 0; i--) {
    if (languages[i].includes('_')) {
    let languageWithoutCountryCode = languages[i].substring(0, 2);
    if (!languages.includes(languageWithoutCountryCode)) {
    languages.splice(i + 1, 0, languageWithoutCountryCode);
    }
    }
    }
    languages.includes("en") || languages.push("en");
    languages.forEach((language, index) => index === languages.length - 1 ? importLocale(language, callback) : importLocale(language, () => {}));
    /* equals:
    languages.length === 1 && importLocale(languages[0], callback);
    languages.length === 2 && importLocale(languages[0], () => importLocale(languages[1], callback));
    languages.length === 3 && importLocale(languages[0], () => importLocale(languages[1], () => importLocale(languages[2], callback)));
    ... */
    // console.log(languages);
    });
    } catch (error) {
    // Finally, if code nor chrome://settings/languages are available, use window.navigator.language:
    let language = window.navigator.language.replace('-', '_');
    if (language.indexOf('_') !== -1) {
    importLocale(language, () => importLocale(language.split('_')[0], () => importLocale('en', callback)));
    } else {
    importLocale(language, () => importLocale('en', callback));
    }
    console.log(error);
    };
    }
    };

    (if this was cached, then this function would only run once in the background.js at if (installed.reason == 'update') {
    or on change of the users browser language/s or ourr language settings)

@jamalkamaladdin

Copy link
Copy Markdown
Contributor Author

agreed background.js needs only two strings. I can cache donate and rateMe in storage.local. Cache refresh runs on install, update and language change. Top-level updateContextMenu() reads the cache and skips getLocale on every service worker wake.

@wahajahmed010

Copy link
Copy Markdown

Good catch — the original getLocale was definitely double-calling the callback (once on the short-locale branch and once in the unconditional fallback). The new structure removes the redundant call.

A couple of concerns:

  1. fallbackToEnglish is defined but never called when language === 'en' — tryShortLanguage checks if (shortLanguage === language) and just returns without falling back. That means if en itself 404s (it shouldn't, but), the user gets an empty callback. The old code had the same blind spot. Probably fine in practice, but consider at least a final hardcoded {} fallback so the extension never crashes on a missing locale.

  2. fetch(...).catch(tryShortLanguage) and tryShortLanguage().catch(fallbackToEnglish) — .catch here returns the promise from the fallback, but tryShortLanguage itself doesn't return the fetch promise in a way that's reachable. Actually it does, via fetch(...).then(...).catch(fallbackToEnglish). OK, that works.

  3. getLocale now has three nested function declarations inside (fallbackToEnglish, tryShortLanguage, plus the outer fetch). For a small helper this is fine, but the original was also nested and the indentation is inconsistent with the rest of background.js — please run the project's formatter (Prettier?) and confirm the diff matches existing style.

  4. Tests? I don't see a test file change. If the project has any unit-test harness for background.js (or a Jest config), a couple of cases would be valuable:

    • getLocale('en_US') → resolves to en_US/messages.json
    • getLocale('en_US') → falls back to en/messages.json when en_US/messages.json is missing
    • getLocale('en') → resolves to en/messages.json (no infinite recursion)
    • getLocale('en') 404 → callback called with en/messages.json content (or {})

Otherwise: clean fix. Removing the duplicate getLocale('en', callback) is the actual bug fix and the new structure is easier to reason about.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐞 background.js getLocale fallback URL is identical to failing URL; also double-invokes callback on failure

3 participants