MOBILE-4653 utils: Move country related utils functions

main
Pau Ferrer Ocaña 2024-11-15 13:09:29 +01:00
parent e72fea3630
commit 453a2bd8c2
5 changed files with 152 additions and 103 deletions

View File

@ -17,7 +17,7 @@ import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'
import { CoreDomUtils } from '@services/utils/dom';
import { CoreText } from '@singletons/text';
import { CoreCountry, CoreUtils } from '@services/utils/utils';
import { CoreCountries, CoreCountry } from '@singletons/countries';
import { CoreWS, CoreWSExternalWarning } from '@services/ws';
import { Translate } from '@singletons';
import { CoreSitePublicConfigResponse, CoreUnauthenticatedSite } from '@classes/sites/unauthenticated-site';
@ -245,7 +245,7 @@ export class CoreLoginEmailSignupPage implements OnInit {
}
this.namefieldsErrors = namefieldsErrors;
this.countries = await CoreUtils.getCountryListSorted();
this.countries = await CoreCountries.getCountryListSorted();
}
/**

View File

@ -50,6 +50,7 @@ import { CoreModals } from '@services/modals';
import { CoreQRScan } from '@services/qrscan';
import { CoreLoadings } from '@services/loadings';
import { CorePromiseUtils } from '@singletons/promise-utils';
import { CoreCountries } from '@singletons/countries';
/**
* Site (url) chooser when adding a new site.
@ -223,7 +224,7 @@ export class CoreLoginSitePage implements OnInit {
site.title = name && alias ? name + ' (' + alias + ')' : name + alias;
const country = this.siteFinderSettings.displaycountry && site.countrycode ?
CoreUtils.getCountryName(site.countrycode) : '';
CoreCountries.getCountryName(site.countrycode) : '';
const city = this.siteFinderSettings.displaycity && site.city ?
site.city : '';

View File

@ -17,7 +17,7 @@ import { Injectable } from '@angular/core';
import { CoreNetwork } from '@services/network';
import { CoreFilepool } from '@services/filepool';
import { CoreSites } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { CoreCountries } from '@singletons/countries';
import { CoreUserOffline } from './user-offline';
import { CoreLogger } from '@singletons/logger';
import { CoreSite } from '@classes/sites/site';
@ -399,7 +399,7 @@ export class CoreUserProvider {
const user: CoreUserData | CoreUserCourseProfile = users[0];
if (user.country) {
user.country = CoreUtils.getCountryName(user.country);
user.country = CoreCountries.getCountryName(user.country);
}
this.storeUser(user.id, user.fullname, user.profileimageurl);

View File

@ -16,7 +16,6 @@ import { Injectable } from '@angular/core';
import { InAppBrowserObject } from '@awesome-cordova-plugins/in-app-browser';
import { FileEntry } from '@awesome-cordova-plugins/file/ngx';
import { CoreFileUtils } from '@singletons/file-utils';
import { CoreLang } from '@services/lang';
import { CoreWS } from '@services/ws';
import { CoreMimetypeUtils } from '@services/utils/mimetype';
import { makeSingleton, Translate } from '@singletons';
@ -30,6 +29,7 @@ import { CoreQRScan } from '@services/qrscan';
import { CoreErrorHelper } from '@services/error-helper';
import { CorePromiseUtils, OrderedPromiseData } from '@singletons/promise-utils';
import { CoreOpener, CoreOpenerOpenFileOptions, CoreOpenerOpenInBrowserOptions } from '@singletons/opener';
import { CoreCountries, CoreCountry } from '@singletons/countries';
export type TreeNode<T> = T & { children: TreeNode<T>[] };
@ -570,100 +570,30 @@ export class CoreUtilsProvider {
*
* @param code Country code (AF, ES, US, ...).
* @returns Country name. If the country is not found, return the country code.
* @deprecated since 5.0. Use CoreCountries.getCountryName instead.
*/
getCountryName(code: string): string {
const countryKey = 'assets.countries.' + code;
const countryName = Translate.instant(countryKey);
return countryName !== countryKey ? countryName : code;
return CoreCountries.getCountryName(code);
}
/**
* Get list of countries with their code and translated name.
*
* @returns Promise resolved with the list of countries.
* @deprecated since 5.0. Use CoreCountries.getCountryList instead.
*/
async getCountryList(): Promise<Record<string, string>> {
// Get the keys of the countries.
const keys = await this.getCountryKeysList();
// Now get the code and the translated name.
const countries: Record<string, string> = {};
keys.forEach((key) => {
if (key.indexOf('assets.countries.') === 0) {
const code = key.replace('assets.countries.', '');
countries[code] = Translate.instant(key);
}
});
return countries;
return CoreCountries.getCountryList();
}
/**
* Get list of countries with their code and translated name. Sorted by the name of the country.
*
* @returns Promise resolved with the list of countries.
* @deprecated since 5.0. Use CoreCountries.getCountryListSorted instead.
*/
async getCountryListSorted(): Promise<CoreCountry[]> {
// Get the keys of the countries.
const countries = await this.getCountryList();
// Sort translations.
return Object.keys(countries)
.sort((a, b) => countries[a].localeCompare(countries[b]))
.map((code) => ({ code, name: countries[code] }));
}
/**
* Get the list of language keys of the countries.
*
* @returns Promise resolved with the countries list. Rejected if not translated.
*/
protected async getCountryKeysList(): Promise<string[]> {
// It's possible that the current language isn't translated, so try with default language first.
const defaultLang = CoreLang.getDefaultLanguage();
try {
return await this.getCountryKeysListForLanguage(defaultLang);
} catch {
// Not translated, try to use the fallback language.
const fallbackLang = CoreLang.getFallbackLanguage();
if (fallbackLang === defaultLang) {
// Same language, just reject.
throw new Error('Countries not found.');
}
return this.getCountryKeysListForLanguage(fallbackLang);
}
}
/**
* Get the list of language keys of the countries, based on the translation table for a certain language.
*
* @param lang Language to check.
* @returns Promise resolved with the countries list. Rejected if not translated.
*/
protected async getCountryKeysListForLanguage(lang: string): Promise<string[]> {
// Get the translation table for the language.
const table = await CoreLang.getTranslationTable(lang);
// Gather all the keys for countries,
const keys: string[] = [];
for (const name in table) {
if (name.indexOf('assets.countries.') === 0) {
keys.push(name);
}
}
if (keys.length === 0) {
// Not translated, reject.
throw new Error('Countries not found.');
}
return keys;
return CoreCountries.getCountryListSorted();
}
/**
@ -673,21 +603,10 @@ export class CoreUtilsProvider {
*
* @param url The URL of the file.
* @returns Promise resolved with the mimetype.
* @deprecated since 5.0. Use CoreMimetypeUtils.getMimeTypeFromUrl instead.
*/
async getMimeTypeFromUrl(url: string): Promise<string> {
// First check if it can be guessed from the URL.
const extension = CoreMimetypeUtils.guessExtensionFromUrl(url);
const mimetype = extension && CoreMimetypeUtils.getMimeType(extension);
// Ignore PHP extension for now, it could be serving a file.
if (mimetype && extension !== 'php') {
return mimetype;
}
// Can't be guessed, get the remote mimetype.
const remoteMimetype = await CoreWS.getRemoteFileMimeType(url);
return remoteMimetype || mimetype || '';
return CoreMimetypeUtils.getMimeTypeFromUrl(url);
}
/**
@ -1432,14 +1351,6 @@ export class CoreUtilsProvider {
export const CoreUtils = makeSingleton(CoreUtilsProvider);
/**
* Data about a country.
*/
export type CoreCountry = {
code: string;
name: string;
};
/**
* Menu item.
*/

View File

@ -0,0 +1,137 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { CoreLang } from '@services/lang';
import { Translate } from '@singletons';
/**
* Singleton with helper functions for country lists.
*/
export class CoreCountries {
// Avoid creating singleton instances.
private constructor() {
// Nothing to do.
}
/**
* Get country name based on country code.
*
* @param code Country code (AF, ES, US, ...).
* @returns Country name. If the country is not found, return the country code.
*/
static getCountryName(code: string): string {
const countryKey = 'assets.countries.' + code;
const countryName = Translate.instant(countryKey);
return countryName !== countryKey ? countryName : code;
}
/**
* Get list of countries with their code and translated name.
*
* @returns Promise resolved with the list of countries.
*/
static async getCountryList(): Promise<Record<string, string>> {
// Get the keys of the countries.
const keys = await CoreCountries.getCountryKeysList();
// Now get the code and the translated name.
const countries: Record<string, string> = {};
keys.forEach((key) => {
if (key.indexOf('assets.countries.') === 0) {
const code = key.replace('assets.countries.', '');
countries[code] = Translate.instant(key);
}
});
return countries;
}
/**
* Get list of countries with their code and translated name. Sorted by the name of the country.
*
* @returns Promise resolved with the list of countries.
*/
static async getCountryListSorted(): Promise<CoreCountry[]> {
// Get the keys of the countries.
const countries = await CoreCountries.getCountryList();
// Sort translations.
return Object.keys(countries)
.sort((a, b) => countries[a].localeCompare(countries[b]))
.map((code) => ({ code, name: countries[code] }));
}
/**
* Get the list of language keys of the countries.
*
* @returns Promise resolved with the countries list. Rejected if not translated.
*/
protected static async getCountryKeysList(): Promise<string[]> {
// It's possible that the current language isn't translated, so try with default language first.
const defaultLang = CoreLang.getDefaultLanguage();
try {
return await CoreCountries.getCountryKeysListForLanguage(defaultLang);
} catch {
// Not translated, try to use the fallback language.
const fallbackLang = CoreLang.getFallbackLanguage();
if (fallbackLang === defaultLang) {
// Same language, just reject.
throw new Error('Countries not found.');
}
return CoreCountries.getCountryKeysListForLanguage(fallbackLang);
}
}
/**
* Get the list of language keys of the countries, based on the translation table for a certain language.
*
* @param lang Language to check.
* @returns Promise resolved with the countries list. Rejected if not translated.
*/
protected static async getCountryKeysListForLanguage(lang: string): Promise<string[]> {
// Get the translation table for the language.
const table = await CoreLang.getTranslationTable(lang);
// Gather all the keys for countries,
const keys: string[] = [];
for (const name in table) {
if (name.indexOf('assets.countries.') === 0) {
keys.push(name);
}
}
if (keys.length === 0) {
// Not translated, reject.
throw new Error('Countries not found.');
}
return keys;
}
}
/**
* Data about a country.
*/
export type CoreCountry = {
code: string;
name: string;
};