diff --git a/src/addon/calendar/providers/calendar.ts b/src/addon/calendar/providers/calendar.ts index 886a21670..d5a9a89fc 100644 --- a/src/addon/calendar/providers/calendar.ts +++ b/src/addon/calendar/providers/calendar.ts @@ -230,8 +230,8 @@ export class AddonCalendarProvider { return this.groupsProvider.getUserGroups(courses, siteId).then((groups) => { let now = this.timeUtils.timestamp(), - start = now + (CoreConstants.secondsDay * daysToStart), - end = start + (CoreConstants.secondsDay * daysInterval); + start = now + (CoreConstants.SECONDS_DAY * daysToStart), + end = start + (CoreConstants.SECONDS_DAY * daysInterval); // The core_calendar_get_calendar_events needs all the current user courses and groups. let data = { diff --git a/src/classes/site.ts b/src/classes/site.ts index 261887d74..3b730ea47 100644 --- a/src/classes/site.ts +++ b/src/classes/site.ts @@ -435,7 +435,7 @@ export class CoreSite { // Check if the method is available, use a prefixed version if possible. // We ignore this check when we do not have the site info, as the list of functions is not loaded yet. if (this.getInfo() && !this.wsAvailable(method, false)) { - const compatibilityMethod = CoreConstants.wsPrefix + method; + const compatibilityMethod = CoreConstants.WS_PREFIX + method; if (this.wsAvailable(compatibilityMethod, false)) { this.logger.info(`Using compatibility WS method '${compatibilityMethod}'`); method = compatibilityMethod; @@ -565,7 +565,7 @@ export class CoreSite { // Let's try again with the compatibility prefix. if (checkPrefix) { - return this.wsAvailable(CoreConstants.wsPrefix + method, false); + return this.wsAvailable(CoreConstants.WS_PREFIX + method, false); } return false; @@ -877,7 +877,7 @@ export class CoreSite { return Promise.resolve({code: 0}); } - let observable = this.http.post(checkUrl, {service: service}).timeout(CoreConstants.wsTimeout); + let observable = this.http.post(checkUrl, {service: service}).timeout(CoreConstants.WS_TIMEOUT); return this.utils.observableToPromise(observable).then((data: any) => { if (typeof data != 'undefined' && data.errorcode === 'requirecorrectaccess') { if (!retrying) { @@ -930,7 +930,7 @@ export class CoreSite { } this.infos.functions.forEach((func) => { - if (func.name.indexOf(CoreConstants.wsPrefix) != -1) { + if (func.name.indexOf(CoreConstants.WS_PREFIX) != -1) { appUsesLocalMobile = true; } }); @@ -1074,7 +1074,7 @@ export class CoreSite { }; if (!this.privateToken || !this.wsAvailable('tool_mobile_get_autologin_key') || - (this.lastAutoLogin && this.timeUtils.timestamp() - this.lastAutoLogin < 6 * CoreConstants.secondsMinute)) { + (this.lastAutoLogin && this.timeUtils.timestamp() - this.lastAutoLogin < 6 * CoreConstants.SECONDS_MINUTE)) { // No private token, WS not available or last auto-login was less than 6 minutes ago. // Open the final URL without auto-login. return Promise.resolve(open(url)); diff --git a/src/components/file/file.ts b/src/components/file/file.ts index 0506bea4f..4c33517d8 100644 --- a/src/components/file/file.ts +++ b/src/components/file/file.ts @@ -102,10 +102,10 @@ export class CoreFileComponent implements OnInit, OnDestroy { return this.filepoolProvider.getFileStateByUrl(this.siteId, this.fileUrl, this.timemodified).then((state) => { let canDownload = this.sitesProvider.getCurrentSite().canDownloadFiles(); - this.isDownloaded = state === CoreConstants.downloaded || state === CoreConstants.outdated; - this.isDownloading = canDownload && state === CoreConstants.downloading; - this.showDownload = canDownload && (state === CoreConstants.notDownloaded || state === CoreConstants.outdated || - (this.alwaysDownload && state === CoreConstants.downloaded)); + this.isDownloaded = state === CoreConstants.DOWNLOADED || state === CoreConstants.OUTDATED; + this.isDownloading = canDownload && state === CoreConstants.DOWNLOADING; + this.showDownload = canDownload && (state === CoreConstants.NOT_DOWNLOADED || state === CoreConstants.OUTDATED || + (this.alwaysDownload && state === CoreConstants.DOWNLOADED)); }); } @@ -207,7 +207,7 @@ export class CoreFileComponent implements OnInit, OnDestroy { let subPromise; - if (status === CoreConstants.notDownloaded) { + if (status === CoreConstants.NOT_DOWNLOADED) { // File is not downloaded, download and then return the local URL. subPromise = this.downloadFile(); } else { diff --git a/src/core/constants.ts b/src/core/constants.ts index 524cc86ec..519460a68 100644 --- a/src/core/constants.ts +++ b/src/core/constants.ts @@ -16,34 +16,34 @@ * Static class to contain all the core constants. */ export class CoreConstants { - public static secondsYear = 31536000; - public static secondsWeek = 604800; - public static secondsDay = 86400; - public static secondsHour = 3600; - public static secondsMinute = 60; - public static wifiDownloadThreshold = 104857600; // 100MB. - public static downloadThreshold = 10485760; // 10MB. - public static dontShowError = 'CoreDontShowError'; - public static noSiteId = 'NoSite'; + public static SECONDS_YEAR = 31536000; + public static SECONDS_WEEK = 604800; + public static SECONDS_DAY = 86400; + public static SECONDS_HOUR = 3600; + public static SECONDS_MINUTE = 60; + public static WIFI_DOWNLOAD_THRESHOLD = 104857600; // 100MB. + public static DOWNLOAD_THRESHOLD = 10485760; // 10MB. + public static DONT_SHOW_ERROR = 'CoreDontShowError'; + public static NO_SITE_ID = 'NoSite'; // Settings constants. - public static settingsRichTextEditor = 'CoreSettingsRichTextEditor'; - public static settingsNotificationSound = 'CoreSettingsNotificationSound'; - public static settingsSyncOnlyOnWifi = 'mmCoreSyncOnlyOnWifi'; + public static SETTINGS_RICH_TEXT_EDITOR = 'CoreSettingsRichTextEditor'; + public static SETTINGS_NOTIFICATION_SOUND = 'CoreSettingsNotificationSound'; + public static SETTINGS_SYNC_ONLY_ON_WIFI = 'CoreSettingsSyncOnlyOnWifi'; // WS constants. - public static wsTimeout = 30000; - public static wsPrefix = 'local_mobile_'; + public static WS_TIMEOUT = 30000; + public static WS_PREFIX = 'local_mobile_'; // Login constants. - public static loginSSOCode = 2; // SSO in browser window is required. - public static loginSSOInAppCode = 3; // SSO in embedded browser is required. - public static loginLaunchData = 'mmLoginLaunchData'; + public static LOGIN_SSO_CODE = 2; // SSO in browser window is required. + public static LOGIN_SSO_INAPP_CODE = 3; // SSO in embedded browser is required. + public static LOGIN_LAUNCH_DATA = 'CoreLoginLaunchData'; // Download status constants. - public static downloaded = 'downloaded'; - public static downloading = 'downloading'; - public static notDownloaded = 'notdownloaded'; - public static outdated = 'outdated'; - public static notDownloadable = 'notdownloadable'; + public static DOWNLOADED = 'downloaded'; + public static DOWNLOADING = 'downloading'; + public static NOT_DOWNLOADED = 'notdownloaded'; + public static OUTDATED = 'outdated'; + public static NOT_DOWNLOADABLE = 'notdownloadable'; } diff --git a/src/core/course/formats/weeks/providers/handler.ts b/src/core/course/formats/weeks/providers/handler.ts index 3405f9721..b6f5beff7 100644 --- a/src/core/course/formats/weeks/providers/handler.ts +++ b/src/core/course/formats/weeks/providers/handler.ts @@ -78,10 +78,10 @@ export class CoreCourseFormatWeeksHandler implements CoreCourseFormatHandler { startDate = startDate + 7200; let dates = { - start: startDate + (CoreConstants.secondsWeek * (section.section - 1)), + start: startDate + (CoreConstants.SECONDS_WEEK * (section.section - 1)), end: 0 }; - dates.end = dates.start + CoreConstants.secondsWeek; + dates.end = dates.start + CoreConstants.SECONDS_WEEK; return dates; } } diff --git a/src/core/course/providers/course.ts b/src/core/course/providers/course.ts index 1323b9ef9..4c4300cc9 100644 --- a/src/core/course/providers/course.ts +++ b/src/core/course/providers/course.ts @@ -28,6 +28,7 @@ import { CoreConstants } from '../../constants'; @Injectable() export class CoreCourseProvider { public static ALL_SECTIONS_ID = -1; + protected ROOT_CACHE_KEY = 'mmCourse:'; // Variables for database. protected COURSE_STATUS_TABLE = 'course_status'; @@ -64,7 +65,7 @@ export class CoreCourseProvider { } protected logger; - protected coreModules = [ + protected CORE_MODULES = [ 'assign', 'assignment', 'book', 'chat', 'choice', 'data', 'database', 'date', 'external-tool', 'feedback', 'file', 'folder', 'forum', 'glossary', 'ims', 'imscp', 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop' @@ -103,7 +104,7 @@ export class CoreCourseProvider { this.logger.debug('Clear all course status for site ' + site.id); return site.getDb().deleteRecords(this.COURSE_STATUS_TABLE).then(() => { - this.triggerCourseStatusChanged(-1, CoreConstants.notDownloaded, site.id); + this.triggerCourseStatusChanged(-1, CoreConstants.NOT_DOWNLOADED, site.id); }); }); } @@ -147,7 +148,7 @@ export class CoreCourseProvider { * @return {string} Cache key. */ protected getActivitiesCompletionCacheKey(courseId: number, userId: number) : string { - return this.getRootCacheKey() + 'activitiescompletion:' + courseId + ':' + userId; + return this.ROOT_CACHE_KEY + 'activitiescompletion:' + courseId + ':' + userId; } /** @@ -177,9 +178,9 @@ export class CoreCourseProvider { */ getCourseStatus(courseId: number, siteId?: string) : Promise { return this.getCourseStatusData(courseId, siteId).then((entry) => { - return entry.status || CoreConstants.notDownloaded; + return entry.status || CoreConstants.NOT_DOWNLOADED; }).catch(() => { - return CoreConstants.notDownloaded; + return CoreConstants.NOT_DOWNLOADED; }); } @@ -352,7 +353,7 @@ export class CoreCourseProvider { * @return {string} Cache key. */ protected getModuleBasicInfoByInstanceCacheKey(id: number, module: string) : string { - return this.getRootCacheKey() + 'moduleByInstance:' + module + ':' + id; + return this.ROOT_CACHE_KEY + 'moduleByInstance:' + module + ':' + id; } /** @@ -362,7 +363,7 @@ export class CoreCourseProvider { * @return {string} Cache key. */ protected getModuleCacheKey(moduleId: number) : string { - return this.getRootCacheKey() + 'module:' + moduleId; + return this.ROOT_CACHE_KEY + 'module:' + moduleId; } /** @@ -372,7 +373,7 @@ export class CoreCourseProvider { * @return {string} The IMG src. */ getModuleIconSrc(moduleName: string) : string { - if (this.coreModules.indexOf(moduleName) < 0) { + if (this.CORE_MODULES.indexOf(moduleName) < 0) { moduleName = 'external-tool'; } @@ -393,15 +394,6 @@ export class CoreCourseProvider { }); } - /** - * Get the root cache key for the WS calls related to courses. - * - * @return {string} Root cache key. - */ - protected getRootCacheKey() : string { - return 'mmCourse:'; - } - /** * Return a specific section. * @@ -487,7 +479,7 @@ export class CoreCourseProvider { * @return {string} Cache key. */ protected getSectionsCacheKey(courseId) : string { - return this.getRootCacheKey() + 'sections:' + courseId; + return this.ROOT_CACHE_KEY + 'sections:' + courseId; } /** @@ -609,9 +601,9 @@ export class CoreCourseProvider { return this.getCourseStatusData(courseId, siteId).then((entry) => { this.logger.debug(`Set previous status '${entry.status}' for course ${courseId}`); - newData.status = entry.previous || CoreConstants.notDownloaded; + newData.status = entry.previous || CoreConstants.NOT_DOWNLOADED; newData.updated = Date.now(); - if (entry.status == CoreConstants.downloading) { + if (entry.status == CoreConstants.DOWNLOADING) { // Going back from downloading to previous status, restore previous download time. newData.downloadTime = entry.previousDownloadTime; } @@ -642,7 +634,7 @@ export class CoreCourseProvider { let downloadTime, previousDownloadTime; - if (status == CoreConstants.downloading) { + if (status == CoreConstants.DOWNLOADING) { // Set download time if course is now downloading. downloadTime = this.timeUtils.timestamp(); } @@ -689,7 +681,7 @@ export class CoreCourseProvider { * @return {string} Translated name. */ translateModuleName(moduleName: string) : string { - if (this.coreModules.indexOf(moduleName) < 0) { + if (this.CORE_MODULES.indexOf(moduleName) < 0) { moduleName = 'external-tool'; } diff --git a/src/core/courses/providers/courses.ts b/src/core/courses/providers/courses.ts index 9e8e0623b..ebb15e8d8 100644 --- a/src/core/courses/providers/courses.ts +++ b/src/core/courses/providers/courses.ts @@ -28,6 +28,7 @@ export class CoreCoursesProvider { public static EVENT_MY_COURSES_REFRESHED = 'courses_my_courses_refreshed'; public static ACCESS_GUEST = 'courses_access_guest'; public static ACCESS_DEFAULT = 'courses_access_default'; + protected ROOT_CACHE_KEY = 'mmCourses:'; protected logger; constructor(logger: CoreLoggerProvider, private sitesProvider: CoreSitesProvider) { @@ -68,7 +69,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getCategoriesCacheKey(categoryId: number, addSubcategories?: boolean) : string { - return this.getRootCacheKey() + 'categories:' + categoryId + ':' + !!addSubcategories; + return this.ROOT_CACHE_KEY + 'categories:' + categoryId + ':' + !!addSubcategories; } /** @@ -121,15 +122,6 @@ export class CoreCoursesProvider { }); } - /** - * Get the root cache key for the WS calls related to courses. - * - * @return {string} Root cache key. - */ - protected getRootCacheKey() : string { - return 'mmCourses:'; - } - /** * Check if My Courses is disabled in a certain site. * @@ -219,7 +211,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getCourseEnrolmentMethodsCacheKey(id: number) : string { - return this.getRootCacheKey() + 'enrolmentmethods:' + id; + return this.ROOT_CACHE_KEY + 'enrolmentmethods:' + id; } /** @@ -251,7 +243,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getCourseGuestEnrolmentInfoCacheKey(instanceId: number) : string { - return this.getRootCacheKey() + 'guestinfo:' + instanceId; + return this.ROOT_CACHE_KEY + 'guestinfo:' + instanceId; } /** @@ -291,7 +283,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getCoursesCacheKey(ids: number[]) : string { - return this.getRootCacheKey() + 'course:' + JSON.stringify(ids); + return this.ROOT_CACHE_KEY + 'course:' + JSON.stringify(ids); } /** @@ -352,7 +344,7 @@ export class CoreCoursesProvider { protected getCoursesByFieldCacheKey(field?: string, value?: any) : string { field = field || ''; value = field ? value : ''; - return this.getRootCacheKey() + 'coursesbyfield:' + field + ':' + value; + return this.ROOT_CACHE_KEY + 'coursesbyfield:' + field + ':' + value; } /** @@ -408,7 +400,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getUserAdministrationOptionsCommonCacheKey() : string { - return this.getRootCacheKey() + 'administrationOptions:'; + return this.ROOT_CACHE_KEY + 'administrationOptions:'; } /** @@ -451,7 +443,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getUserNavigationOptionsCommonCacheKey() : string { - return this.getRootCacheKey() + 'navigationOptions:'; + return this.ROOT_CACHE_KEY + 'navigationOptions:'; } /** @@ -566,7 +558,7 @@ export class CoreCoursesProvider { * @return {string} Cache key. */ protected getUserCoursesCacheKey() : string { - return this.getRootCacheKey() + 'usercourses'; + return this.ROOT_CACHE_KEY + 'usercourses'; } /** diff --git a/src/core/courses/providers/my-overview.ts b/src/core/courses/providers/my-overview.ts index aab67f913..a6b785fde 100644 --- a/src/core/courses/providers/my-overview.ts +++ b/src/core/courses/providers/my-overview.ts @@ -24,6 +24,7 @@ import * as moment from 'moment'; export class CoreCoursesMyOverviewProvider { public static EVENTS_LIMIT = 20; public static EVENTS_LIMIT_PER_COURSE = 10; + protected ROOT_CACHE_KEY = 'myoverview:'; constructor(private sitesProvider: CoreSitesProvider) {} @@ -113,7 +114,7 @@ export class CoreCoursesMyOverviewProvider { * @return {string} Cache key. */ protected getActionEventsByCoursesCacheKey() : string { - return this.getRootCacheKey() + 'bycourse'; + return this.ROOT_CACHE_KEY + 'bycourse'; } /** @@ -165,7 +166,7 @@ export class CoreCoursesMyOverviewProvider { * @return {string} Cache key. */ protected getActionEventsByTimesortPrefixCacheKey() : string { - return this.getRootCacheKey() + 'bytimesort:'; + return this.ROOT_CACHE_KEY + 'bytimesort:'; } /** @@ -181,15 +182,6 @@ export class CoreCoursesMyOverviewProvider { return this.getActionEventsByTimesortPrefixCacheKey() + afterEventId + ':' + limit; } - /** - * Get the root cache key for the WS calls related to overview. - * - * @return {string} Root cache key. - */ - protected getRootCacheKey() : string { - return 'myoverview:'; - } - /** * Invalidates get calendar action events for a given list of courses WS call. * diff --git a/src/core/emulator/pages/capture-media/capture-media.ts b/src/core/emulator/pages/capture-media/capture-media.ts index e94d15be5..353648b3e 100644 --- a/src/core/emulator/pages/capture-media/capture-media.ts +++ b/src/core/emulator/pages/capture-media/capture-media.ts @@ -354,7 +354,7 @@ export class CoreEmulatorCaptureMediaPage implements OnInit, OnDestroy { // Create the file and return it. let fileName = this.type + '_' + this.timeUtils.readableTimestamp() + '.' + this.extension, - path = this.textUtils.concatenatePaths(this.fileProvider.TMPFOLDER, 'media/' + fileName); + path = this.textUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, 'media/' + fileName); let loadingModal = this.domUtils.showModalLoading(); diff --git a/src/core/emulator/providers/local-notifications.ts b/src/core/emulator/providers/local-notifications.ts index d7eef13db..2d8e27af1 100644 --- a/src/core/emulator/providers/local-notifications.ts +++ b/src/core/emulator/providers/local-notifications.ts @@ -466,7 +466,7 @@ export class LocalNotificationsMock extends LocalNotifications { // Schedule the notification again unless it should have been triggered more than an hour ago. delete notification.triggered; notification.at = notification.at * 1000; - if (notification.at - Date.now() > - CoreConstants.secondsHour * 1000) { + if (notification.at - Date.now() > - CoreConstants.SECONDS_HOUR * 1000) { this.schedule(notification); } } @@ -551,19 +551,19 @@ export class LocalNotificationsMock extends LocalNotifications { } else if (every == 'second') { interval = 1000; } else if (every == 'minute') { - interval = CoreConstants.secondsMinute * 1000; + interval = CoreConstants.SECONDS_MINUTE * 1000; } else if (every == 'hour') { - interval = CoreConstants.secondsHour * 1000; + interval = CoreConstants.SECONDS_HOUR * 1000; } else if (every == 'day') { - interval = CoreConstants.secondsDay * 1000; + interval = CoreConstants.SECONDS_DAY * 1000; } else if (every == 'week') { - interval = CoreConstants.secondsDay * 7 * 1000; + interval = CoreConstants.SECONDS_DAY * 7 * 1000; } else if (every == 'month') { - interval = CoreConstants.secondsDay * 31 * 1000; + interval = CoreConstants.SECONDS_DAY * 31 * 1000; } else if (every == 'quarter') { - interval = CoreConstants.secondsHour * 2190 * 1000; + interval = CoreConstants.SECONDS_HOUR * 2190 * 1000; } else if (every == 'year') { - interval = CoreConstants.secondsYear * 1000; + interval = CoreConstants.SECONDS_YEAR * 1000; } else { interval = parseInt(every, 10); if (isNaN(interval)) { @@ -713,7 +713,7 @@ export class LocalNotificationsMock extends LocalNotifications { tag: notification.id + '', template: this.tileTemplate, strings: [notification.title, notification.text, notification.title, notification.text, notification.title, notification.text], - expirationTime: new Date(Date.now() + CoreConstants.secondsHour * 1000) // Expire in 1 hour. + expirationTime: new Date(Date.now() + CoreConstants.SECONDS_HOUR * 1000) // Expire in 1 hour. }) tileNotif.show() diff --git a/src/core/fileuploader/providers/helper.ts b/src/core/fileuploader/providers/helper.ts index 07936bb1d..438ee93c9 100644 --- a/src/core/fileuploader/providers/helper.ts +++ b/src/core/fileuploader/providers/helper.ts @@ -94,13 +94,13 @@ export class CoreFileUploaderHelperProvider { fileData; // We have the data of the file to be uploaded, but not its URL (needed). Create a copy of the file to upload it. - return this.fileProvider.readFileData(file, this.fileProvider.FORMATARRAYBUFFER).then((data) => { + return this.fileProvider.readFileData(file, CoreFileProvider.FORMATARRAYBUFFER).then((data) => { fileData = data; // Get unique name for the copy. - return this.fileProvider.getUniqueNameInFolder(this.fileProvider.TMPFOLDER, name); + return this.fileProvider.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, name); }).then((newName) => { - let filePath = this.textUtils.concatenatePaths(this.fileProvider.TMPFOLDER, newName); + let filePath = this.textUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, newName); return this.fileProvider.writeFile(filePath, fileData); }).catch((error) => { @@ -158,10 +158,10 @@ export class CoreFileUploaderHelperProvider { fileName = fileName.replace(/(\.[^\.]*)\?[^\.]*$/, '$1'); // Get a unique name in the folder to prevent overriding another file. - return this.fileProvider.getUniqueNameInFolder(this.fileProvider.TMPFOLDER, fileName, defaultExt); + return this.fileProvider.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, fileName, defaultExt); }).then((newName) => { // Now move or copy the file. - const destPath = this.textUtils.concatenatePaths(this.fileProvider.TMPFOLDER, newName); + const destPath = this.textUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, newName); if (shouldDelete) { return this.fileProvider.moveExternalFile(path, destPath); } else { diff --git a/src/core/login/pages/init/init.ts b/src/core/login/pages/init/init.ts index 7be53c668..7926f43f1 100644 --- a/src/core/login/pages/init/init.ts +++ b/src/core/login/pages/init/init.ts @@ -47,7 +47,7 @@ export class CoreLoginInitPage { // Only accept the redirect if it was stored less than 20 seconds ago. if (Date.now() - redirectData.timemodified < 20000) { - if (redirectData.siteId != CoreConstants.noSiteId) { + if (redirectData.siteId != CoreConstants.NO_SITE_ID) { // The redirect is pointing to a site, load it. return this.sitesProvider.loadSite(redirectData.siteId).then(() => { if (!this.loginHelper.isSiteLoggedOut(redirectData.page, redirectData.params)) { diff --git a/src/core/login/providers/helper.ts b/src/core/login/providers/helper.ts index 08caa097c..8f21a8a52 100644 --- a/src/core/login/providers/helper.ts +++ b/src/core/login/providers/helper.ts @@ -187,7 +187,7 @@ export class CoreLoginHelperProvider { * Show a confirm modal if needed and open a browser to perform SSO login. * * @param {string} siteurl URL of the site where the SSO login will be performed. - * @param {number} typeOfLogin CoreConstants.loginSSOCode or CoreConstants.loginSSOInAppCode. + * @param {number} typeOfLogin CoreConstants.LOGIN_SSO_CODE or CoreConstants.LOGIN_SSO_INAPP_CODE. * @param {string} [service] The service to use. If not defined, external service will be used. * @param {string} [launchUrl] The URL to open for SSO. If not defined, local_mobile launch URL will be used. * @return {Void} @@ -594,7 +594,7 @@ export class CoreLoginHelperProvider { return true; } - return code == CoreConstants.loginSSOInAppCode; + return code == CoreConstants.LOGIN_SSO_INAPP_CODE; } /** @@ -604,7 +604,7 @@ export class CoreLoginHelperProvider { * @return {boolean} True if SSO login is needed, false othwerise. */ isSSOLoginNeeded(code: number) : boolean { - return code == CoreConstants.loginSSOCode || code == CoreConstants.loginSSOInAppCode; + return code == CoreConstants.LOGIN_SSO_CODE || code == CoreConstants.LOGIN_SSO_INAPP_CODE; } /** @@ -615,7 +615,7 @@ export class CoreLoginHelperProvider { * @param {string} siteId Site to load. */ protected loadSiteAndPage(page: string, params: any, siteId: string) : void { - if (siteId == CoreConstants.noSiteId) { + if (siteId == CoreConstants.NO_SITE_ID) { // Page doesn't belong to a site, just load the page. this.appProvider.getRootNavController().setRoot(page, params); } else { @@ -687,7 +687,7 @@ export class CoreLoginHelperProvider { * Open a browser to perform SSO login. * * @param {string} siteurl URL of the site where the SSO login will be performed. - * @param {number} typeOfLogin CoreConstants.loginSSOCode or CoreConstants.loginSSOInAppCode. + * @param {number} typeOfLogin CoreConstants.LOGIN_SSO_CODE or CoreConstants.LOGIN_SSO_INAPP_CODE. * @param {string} [service] The service to use. If not defined, external service will be used. * @param {string} [launchUrl] The URL to open for SSO. If not defined, local_mobile launch URL will be used. * @param {string} [pageName] Name of the page to go once authenticated. If not defined, site initial page. @@ -791,7 +791,7 @@ export class CoreLoginHelperProvider { // Store the siteurl and passport in $mmConfig for persistence. We are "configuring" // the app to wait for an SSO. $mmConfig shouldn't be used as a temporary storage. - this.configProvider.set(CoreConstants.loginLaunchData, JSON.stringify({ + this.configProvider.set(CoreConstants.LOGIN_LAUNCH_DATA, JSON.stringify({ siteUrl: siteUrl, passport: passport, pageName: pageName || '', @@ -934,7 +934,7 @@ export class CoreLoginHelperProvider { /** * Check if a confirm should be shown to open a SSO authentication. * - * @param {number} typeOfLogin CoreConstants.loginSSOCode or CoreConstants.loginSSOInAppCode. + * @param {number} typeOfLogin CoreConstants.LOGIN_SSO_CODE or CoreConstants.LOGIN_SSO_INAPP_CODE. * @return {boolean} True if confirm modal should be shown, false otherwise. */ shouldShowSSOConfirm(typeOfLogin: number) : boolean { @@ -988,7 +988,7 @@ export class CoreLoginHelperProvider { // Split signature:::token const params = url.split(":::"); - return this.configProvider.get(CoreConstants.loginLaunchData).then((data): any => { + return this.configProvider.get(CoreConstants.LOGIN_LAUNCH_DATA).then((data): any => { try { data = JSON.parse(data); } catch(ex) { @@ -999,7 +999,7 @@ export class CoreLoginHelperProvider { passport = data.passport; // Reset temporary values. - this.configProvider.delete(CoreConstants.loginLaunchData); + this.configProvider.delete(CoreConstants.LOGIN_LAUNCH_DATA); // Validate the signature. // We need to check both http and https. diff --git a/src/pipes/seconds-to-hms.ts b/src/pipes/seconds-to-hms.ts index 8160522a2..34bd4d3cf 100644 --- a/src/pipes/seconds-to-hms.ts +++ b/src/pipes/seconds-to-hms.ts @@ -57,10 +57,10 @@ export class CoreSecondsToHMSPipe implements PipeTransform { // Don't allow decimals. seconds = Math.floor(seconds); - hours = Math.floor(seconds / CoreConstants.secondsHour); - seconds -= hours * CoreConstants.secondsHour; - minutes = Math.floor(seconds / CoreConstants.secondsMinute); - seconds -= minutes * CoreConstants.secondsMinute; + hours = Math.floor(seconds / CoreConstants.SECONDS_HOUR); + seconds -= hours * CoreConstants.SECONDS_HOUR; + minutes = Math.floor(seconds / CoreConstants.SECONDS_MINUTE); + seconds -= minutes * CoreConstants.SECONDS_MINUTE; return this.textUtils.twoDigits(hours) + ':' + this.textUtils.twoDigits(minutes) + ':' + this.textUtils.twoDigits(seconds); } diff --git a/src/providers/app.ts b/src/providers/app.ts index 7bc1f36be..9679adc9e 100644 --- a/src/providers/app.ts +++ b/src/providers/app.ts @@ -40,11 +40,11 @@ export interface CoreRedirectData { */ @Injectable() export class CoreAppProvider { - DBNAME = 'MoodleMobile'; - db: SQLiteDB; - logger; - ssoAuthenticationPromise : Promise; - isKeyboardShown: boolean = false; + protected DBNAME = 'MoodleMobile'; + protected db: SQLiteDB; + protected logger; + protected ssoAuthenticationPromise : Promise; + protected isKeyboardShown: boolean = false; constructor(dbProvider: CoreDbProvider, private platform: Platform, private keyboard: Keyboard, private appCtrl: App, private network: Network, logger: CoreLoggerProvider) { diff --git a/src/providers/config.ts b/src/providers/config.ts index 88cf788c9..7b9f4970e 100644 --- a/src/providers/config.ts +++ b/src/providers/config.ts @@ -22,9 +22,9 @@ import { SQLiteDB } from '../classes/sqlitedb'; */ @Injectable() export class CoreConfigProvider { - appDB: SQLiteDB; - TABLE_NAME = 'core_config'; - tableSchema = { + protected appDB: SQLiteDB; + protected TABLE_NAME = 'core_config'; + protected tableSchema = { name: this.TABLE_NAME, columns: [ { diff --git a/src/providers/cron.ts b/src/providers/cron.ts index c6605700f..b8856769c 100644 --- a/src/providers/cron.ts +++ b/src/providers/cron.ts @@ -109,7 +109,7 @@ export class CoreCronDelegate { if (isSync) { // Check network connection. - promise = this.configProvider.get(CoreConstants.settingsSyncOnlyOnWifi, false).then((syncOnlyOnWifi) => { + promise = this.configProvider.get(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, false).then((syncOnlyOnWifi) => { return !syncOnlyOnWifi || !this.appProvider.isNetworkAccessLimited(); }); } else { diff --git a/src/providers/db.ts b/src/providers/db.ts index 0a463143e..a3c1f4aab 100644 --- a/src/providers/db.ts +++ b/src/providers/db.ts @@ -24,7 +24,7 @@ import { SQLiteDBMock } from '../core/emulator/classes/sqlitedb'; @Injectable() export class CoreDbProvider { - dbInstances = {}; + protected dbInstances = {}; constructor(private sqlite: SQLite, private platform: Platform) {} diff --git a/src/providers/events.ts b/src/providers/events.ts index c586e5925..a9407f618 100644 --- a/src/providers/events.ts +++ b/src/providers/events.ts @@ -49,9 +49,9 @@ export class CoreEventsProvider { public static APP_LAUNCHED_URL = 'app_launched_url'; // App opened with a certain URL (custom URL scheme). public static FILE_SHARED = 'file_shared'; - logger; - observables: {[s: string] : Subject} = {}; - uniqueEvents = {}; + protected logger; + protected observables: {[s: string] : Subject} = {}; + protected uniqueEvents = {}; constructor(logger: CoreLoggerProvider) { this.logger = logger.getInstance('CoreEventsProvider'); diff --git a/src/providers/file.ts b/src/providers/file.ts index e8c693f8a..53d8d0d0a 100644 --- a/src/providers/file.ts +++ b/src/providers/file.ts @@ -27,20 +27,20 @@ import { Zip } from '@ionic-native/zip'; */ @Injectable() export class CoreFileProvider { - logger; - initialized = false; - basePath = ''; - isHTMLAPI = false; + protected logger; + protected initialized = false; + protected basePath = ''; + protected isHTMLAPI = false; // Formats to read a file. - FORMATTEXT = 0; - FORMATDATAURL = 1; - FORMATBINARYSTRING = 2; - FORMATARRAYBUFFER = 3; + public static FORMATTEXT = 0; + public static FORMATDATAURL = 1; + public static FORMATBINARYSTRING = 2; + public static FORMATARRAYBUFFER = 3; // Folders. - SITESFOLDER = 'sites'; - TMPFOLDER = 'tmp'; + public static SITESFOLDER = 'sites'; + public static TMPFOLDER = 'tmp'; constructor(logger: CoreLoggerProvider, private platform: Platform, private file: File, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, private zip: Zip, private mimeUtils: CoreMimetypeUtilsProvider) { @@ -136,7 +136,7 @@ export class CoreFileProvider { * @return {string} Site folder path. */ getSiteFolder(siteId: string) : string { - return this.SITESFOLDER + '/' + siteId; + return CoreFileProvider.SITESFOLDER + '/' + siteId; } /** @@ -380,17 +380,17 @@ export class CoreFileProvider { * FORMATARRAYBUFFER * @return {Promise} Promise to be resolved when the file is read. */ - readFile(path: string, format = this.FORMATTEXT) : Promise { + readFile(path: string, format = CoreFileProvider.FORMATTEXT) : Promise { // Remove basePath if it's in the path. path = this.removeStartingSlash(path.replace(this.basePath, '')); this.logger.debug('Read file ' + path + ' with format ' + format); switch (format) { - case this.FORMATDATAURL: + case CoreFileProvider.FORMATDATAURL: return this.file.readAsDataURL(this.basePath, path); - case this.FORMATBINARYSTRING: + case CoreFileProvider.FORMATBINARYSTRING: return this.file.readAsBinaryString(this.basePath, path); - case this.FORMATARRAYBUFFER: + case CoreFileProvider.FORMATARRAYBUFFER: return this.file.readAsArrayBuffer(this.basePath, path); default: return this.file.readAsText(this.basePath, path); @@ -408,8 +408,8 @@ export class CoreFileProvider { * FORMATARRAYBUFFER * @return {Promise} Promise to be resolved when the file is read. */ - readFileData(fileData: any, format = this.FORMATTEXT) : Promise { - format = format || this.FORMATTEXT; + readFileData(fileData: any, format = CoreFileProvider.FORMATTEXT) : Promise { + format = format || CoreFileProvider.FORMATTEXT; this.logger.debug('Read file from file data with format ' + format); return new Promise((resolve, reject) => { @@ -426,13 +426,13 @@ export class CoreFileProvider { } switch (format) { - case this.FORMATDATAURL: + case CoreFileProvider.FORMATDATAURL: reader.readAsDataURL(fileData); break; - case this.FORMATBINARYSTRING: + case CoreFileProvider.FORMATBINARYSTRING: reader.readAsBinaryString(fileData); break; - case this.FORMATARRAYBUFFER: + case CoreFileProvider.FORMATARRAYBUFFER: reader.readAsArrayBuffer(fileData); break; default: @@ -883,7 +883,7 @@ export class CoreFileProvider { * @return {Promise} Promise resolved when done. */ clearTmpFolder() : Promise { - return this.removeDir(this.TMPFOLDER); + return this.removeDir(CoreFileProvider.TMPFOLDER); } /** diff --git a/src/providers/filepool.ts b/src/providers/filepool.ts index a576880ee..879f2e961 100644 --- a/src/providers/filepool.ts +++ b/src/providers/filepool.ts @@ -648,7 +648,7 @@ export class CoreFilepoolProvider { return site.getDb().deleteRecords(this.PACKAGES_TABLE).then(() => { entries.forEach((entry) => { // Trigger module status changed, setting it as not downloaded. - this.triggerPackageStatusChanged(siteId, CoreConstants.notDownloaded, entry.component, entry.componentId); + this.triggerPackageStatusChanged(siteId, CoreConstants.NOT_DOWNLOADED, entry.component, entry.componentId); }); }); }); @@ -693,13 +693,13 @@ export class CoreFilepoolProvider { /** * Given the current status of a list of packages and the status of one of the packages, * determine the new status for the list of packages. The status of a list of packages is: - * - CoreConstants.nowDownloadable if there are no downloadable packages. - * - CoreConstants.notDownloaded if at least 1 package has status CoreConstants.notDownloaded. - * - CoreConstants.downloaded if ALL the downloadable packages have status CoreConstants.downloaded. - * - CoreConstants.downloading if ALL the downloadable packages have status CoreConstants.downloading or - * CoreConstants.downloaded, with at least 1 package with CoreConstants.downloading. - * - CoreConstants.outdated if ALL the downloadable packages have status CoreConstants.outdated or CoreConstants.downloaded - * or CoreConstants.downloading, with at least 1 package with CoreConstants.outdated. + * - CoreConstants.NOT_DOWNLOADABLE if there are no downloadable packages. + * - CoreConstants.NOT_DOWNLOADED if at least 1 package has status CoreConstants.NOT_DOWNLOADED. + * - CoreConstants.DOWNLOADED if ALL the downloadable packages have status CoreConstants.DOWNLOADED. + * - CoreConstants.DOWNLOADING if ALL the downloadable packages have status CoreConstants.DOWNLOADING or + * CoreConstants.DOWNLOADED, with at least 1 package with CoreConstants.DOWNLOADING. + * - CoreConstants.OUTDATED if ALL the downloadable packages have status CoreConstants.OUTDATED or CoreConstants.DOWNLOADED + * or CoreConstants.DOWNLOADING, with at least 1 package with CoreConstants.OUTDATED. * * @param {string} current Current status of the list of packages. * @param {string} packagestatus Status of one of the packages. @@ -707,22 +707,22 @@ export class CoreFilepoolProvider { */ determinePackagesStatus(current: string, packageStatus: string) : string { if (!current) { - current = CoreConstants.notDownloadable; + current = CoreConstants.NOT_DOWNLOADABLE; } - if (packageStatus === CoreConstants.notDownloaded) { + if (packageStatus === CoreConstants.NOT_DOWNLOADED) { // If 1 package is not downloaded the status of the whole list will always be not downloaded. - return CoreConstants.notDownloaded; - } else if (packageStatus === CoreConstants.downloaded && current === CoreConstants.notDownloadable) { + return CoreConstants.NOT_DOWNLOADED; + } else if (packageStatus === CoreConstants.DOWNLOADED && current === CoreConstants.NOT_DOWNLOADABLE) { // If all packages are downloaded or not downloadable with at least 1 downloaded, status will be downloaded. - return CoreConstants.downloaded; - } else if (packageStatus === CoreConstants.downloading && - (current === CoreConstants.notDownloadable || current === CoreConstants.downloaded)) { + return CoreConstants.DOWNLOADED; + } else if (packageStatus === CoreConstants.DOWNLOADING && + (current === CoreConstants.NOT_DOWNLOADABLE || current === CoreConstants.DOWNLOADED)) { // If all packages are downloading/downloaded/notdownloadable with at least 1 downloading, status will be downloading. - return CoreConstants.downloading; - } else if (packageStatus === CoreConstants.outdated && current !== CoreConstants.notDownloaded) { + return CoreConstants.DOWNLOADING; + } else if (packageStatus === CoreConstants.OUTDATED && current !== CoreConstants.NOT_DOWNLOADED) { // If there are no packages notdownloaded and there is at least 1 outdated, status will be outdated. - return CoreConstants.outdated; + return CoreConstants.OUTDATED; } // Status remains the same. @@ -865,7 +865,7 @@ export class CoreFilepoolProvider { timemodified = timemodified || this.getTimemodifiedFromFileList(fileList); // Set package as downloading. - promise = this.storePackageStatus(siteId, CoreConstants.downloading, component, componentId).then(() => { + promise = this.storePackageStatus(siteId, CoreConstants.DOWNLOADING, component, componentId).then(() => { let promises = [], packageLoaded = 0; @@ -919,7 +919,7 @@ export class CoreFilepoolProvider { return Promise.all(promises).then(() => { // Success prefetching, store package as downloaded. - return this.storePackageStatus(siteId, CoreConstants.downloaded, component, componentId, revision, timemodified); + return this.storePackageStatus(siteId, CoreConstants.DOWNLOADED, component, componentId, revision, timemodified); }).catch(() => { // Error downloading, go back to previous status and reject the promise. return this.setPackagePreviousStatus(siteId, component, componentId).then(() => { @@ -1391,7 +1391,7 @@ export class CoreFilepoolProvider { // Check if the file is in queue (waiting to be downloaded). return this.hasFileInQueue(siteId, fileId).then(() => { - return CoreConstants.downloading; + return CoreConstants.DOWNLOADING; }).catch(() => { // Check if the file is being downloaded right now. let extension = this.mimeUtils.guessExtensionFromUrl(fileUrl), @@ -1400,18 +1400,18 @@ export class CoreFilepoolProvider { return Promise.resolve(path).then((filePath) => { const downloadId = this.getFileDownloadId(fileUrl, filePath); if (this.filePromises[siteId] && this.filePromises[siteId][downloadId]) { - return CoreConstants.downloading; + return CoreConstants.DOWNLOADING; } // File is not being downloaded. Check if it's downloaded and if it's outdated. return this.hasFileInPool(siteId, fileId).then((entry) => { if (this.isFileOutdated(entry, revision, timemodified)) { - return CoreConstants.outdated; + return CoreConstants.OUTDATED; } else { - return CoreConstants.downloaded; + return CoreConstants.DOWNLOADED; } }).catch(() => { - return CoreConstants.notDownloaded; + return CoreConstants.NOT_DOWNLOADED; }); }); }); @@ -1584,9 +1584,9 @@ export class CoreFilepoolProvider { */ getPackageCurrentStatus(siteId: string, component: string, componentId?: string|number) : Promise { return this.getPackageData(siteId, component, componentId).then((entry) => { - return entry.status || CoreConstants.notDownloaded; + return entry.status || CoreConstants.NOT_DOWNLOADED; }).catch(() => { - return CoreConstants.notDownloaded; + return CoreConstants.NOT_DOWNLOADED; }); } @@ -1705,9 +1705,9 @@ export class CoreFilepoolProvider { */ getPackagePreviousStatus(siteId: string, component: string, componentId?: string|number) : Promise { return this.getPackageData(siteId, component, componentId).then((entry) => { - return entry.previous || CoreConstants.notDownloaded; + return entry.previous || CoreConstants.NOT_DOWNLOADED; }).catch(() => { - return CoreConstants.notDownloaded; + return CoreConstants.NOT_DOWNLOADED; }); } @@ -1745,34 +1745,34 @@ export class CoreFilepoolProvider { // Get status. return site.getDb().getRecord(this.PACKAGES_TABLE, conditions).then((entry: CoreFilepoolPackageEntry) => { - if (entry.status === CoreConstants.downloaded) { + if (entry.status === CoreConstants.DOWNLOADED) { if (revision != entry.revision || timemodified > entry.timemodified) { // File is outdated. Let's change its status. let newData: CoreFilepoolPackageEntry = { - status: CoreConstants.outdated, + status: CoreConstants.OUTDATED, updated: Date.now() }; site.getDb().updateRecords(this.PACKAGES_TABLE, newData, conditions).then(() => { // Success inserting, trigger event. - this.triggerPackageStatusChanged(siteId, CoreConstants.outdated, component, componentId); + this.triggerPackageStatusChanged(siteId, CoreConstants.OUTDATED, component, componentId); }); } - } else if (entry.status === CoreConstants.outdated) { + } else if (entry.status === CoreConstants.OUTDATED) { if (revision === entry.revision && timemodified === entry.timemodified) { // File isn't outdated anymore. Let's change its status. let newData: CoreFilepoolPackageEntry = { - status: CoreConstants.downloaded, + status: CoreConstants.DOWNLOADED, updated: Date.now() }; site.getDb().updateRecords(this.PACKAGES_TABLE, newData, conditions).then(() => { // Success inserting, trigger event. - this.triggerPackageStatusChanged(siteId, CoreConstants.downloaded, component, componentId); + this.triggerPackageStatusChanged(siteId, CoreConstants.DOWNLOADED, component, componentId); }); } } return entry.status; }, () => { - return CoreConstants.notDownloaded; + return CoreConstants.NOT_DOWNLOADED; }); }); } @@ -2511,11 +2511,11 @@ export class CoreFilepoolProvider { // Get current stored data, we'll only update 'status' and 'updated' fields. return site.getDb().getRecord(this.PACKAGES_TABLE, {id: packageId}).then((entry: CoreFilepoolPackageEntry) => { let newData: CoreFilepoolPackageEntry = {}; - if (entry.status == CoreConstants.downloading) { + if (entry.status == CoreConstants.DOWNLOADING) { // Going back from downloading to previous status, restore previous download time. newData.downloadTime = entry.previousDownloadTime; } - newData.status = entry.previous || CoreConstants.downloaded; + newData.status = entry.previous || CoreConstants.DOWNLOADED; newData.updated = Date.now(); this.logger.debug(`Set previous status '${entry.status}' for package ${component} ${componentId}`); @@ -2582,7 +2582,7 @@ export class CoreFilepoolProvider { downloadTime, previousDownloadTime; - if (status == CoreConstants.downloading) { + if (status == CoreConstants.DOWNLOADING) { // Set download time if package is now downloading. downloadTime = this.timeUtils.timestamp(); } diff --git a/src/providers/groups.ts b/src/providers/groups.ts index 0762719dc..43411b139 100644 --- a/src/providers/groups.ts +++ b/src/providers/groups.ts @@ -31,6 +31,7 @@ export class CoreGroupsProvider { public static NOGROUPS = 0; public static SEPARATEGROUPS = 1; public static VISIBLEGROUPS = 2; + protected ROOT_CACHE_KEY = 'mmGroups:'; constructor(private sitesProvider: CoreSitesProvider, private translate: TranslateService) {} @@ -86,7 +87,7 @@ export class CoreGroupsProvider { * @return {string} Cache key. */ protected getActivityAllowedGroupsCacheKey(cmId: number, userId: number) : string { - return this.getRootCacheKey() + 'allowedgroups:' + cmId + ':' + userId; + return this.ROOT_CACHE_KEY + 'allowedgroups:' + cmId + ':' + userId; } /** @@ -178,16 +179,7 @@ export class CoreGroupsProvider { * @return {string} Cache key. */ protected getActivityGroupModeCacheKey(cmId: number) : string { - return this.getRootCacheKey() + 'groupmode:' + cmId; - } - - /** - * Get the "root" cache key for WS calls. - * - * @return {string} Cache key. - */ - protected getRootCacheKey() : string { - return 'mmGroups:'; + return this.ROOT_CACHE_KEY + 'groupmode:' + cmId; } /** @@ -249,7 +241,7 @@ export class CoreGroupsProvider { * @return {string} Cache key. */ protected getUserGroupsInCourseCacheKey(courseId: number, userId: number) : string { - return this.getRootCacheKey() + 'courseGroups:' + courseId + ':' + userId; + return this.ROOT_CACHE_KEY + 'courseGroups:' + courseId + ':' + userId; } /** diff --git a/src/providers/init.ts b/src/providers/init.ts index 37dd18ab2..dc08fc64b 100644 --- a/src/providers/init.ts +++ b/src/providers/init.ts @@ -32,9 +32,9 @@ export class CoreInitDelegate { public static DEFAULT_PRIORITY = 100; // Default priority for init processes. public static MAX_RECOMMENDED_PRIORITY = 600; - initProcesses = {}; - logger; - readiness; + protected initProcesses = {}; + protected logger; + protected readiness; constructor(logger: CoreLoggerProvider, platform: Platform, private utils: CoreUtilsProvider) { this.logger = logger.getInstance('CoreInitDelegate'); diff --git a/src/providers/lang.ts b/src/providers/lang.ts index 86b241c9a..af62d6268 100644 --- a/src/providers/lang.ts +++ b/src/providers/lang.ts @@ -26,10 +26,10 @@ import { CoreConfigConstants } from '../configconstants'; */ @Injectable() export class CoreLangProvider { - fallbackLanguage:string = 'en'; // mmCoreConfigConstants.default_lang || 'en', - currentLanguage: string; // Save current language in a variable to speed up the get function. - customStrings = {}; - customStringsRaw: string; + protected fallbackLanguage:string = 'en'; // mmCoreConfigConstants.default_lang || 'en', + protected currentLanguage: string; // Save current language in a variable to speed up the get function. + protected customStrings = {}; + protected customStringsRaw: string; constructor(private translate: TranslateService, private configProvider: CoreConfigProvider, platform: Platform, private globalization: Globalization) { diff --git a/src/providers/local-notifications.ts b/src/providers/local-notifications.ts index c95ef78c4..2a7f6e68c 100644 --- a/src/providers/local-notifications.ts +++ b/src/providers/local-notifications.ts @@ -432,7 +432,7 @@ export class CoreLocalNotificationsProvider { return this.isTriggered(notification).then((triggered) => { if (!triggered) { // Check if sound is enabled for notifications. - return this.configProvider.get(CoreConstants.settingsNotificationSound, true).then((soundEnabled) => { + return this.configProvider.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true).then((soundEnabled) => { if (!soundEnabled) { notification.sound = null; } else { diff --git a/src/providers/sites.ts b/src/providers/sites.ts index e912ef2bf..45c6bceca 100644 --- a/src/providers/sites.ts +++ b/src/providers/sites.ts @@ -234,7 +234,7 @@ export class CoreSitesProvider { this.services[siteUrl] = data.service; // No need to store it in DB. if (data.coreSupported || - (data.code != CoreConstants.loginSSOCode && data.code != CoreConstants.loginSSOInAppCode)) { + (data.code != CoreConstants.LOGIN_SSO_CODE && data.code != CoreConstants.LOGIN_SSO_INAPP_CODE)) { // SSO using local_mobile not needed, try to get the site public config. return temporarySite.getPublicConfig().then((config) : any => { publicConfig = config; @@ -301,7 +301,7 @@ export class CoreSitesProvider { data.service = 'c'; } - const observable = this.http.post(siteUrl + '/login/token.php', data).timeout(CoreConstants.wsTimeout); + const observable = this.http.post(siteUrl + '/login/token.php', data).timeout(CoreConstants.WS_TIMEOUT); return this.utils.observableToPromise(observable).catch((error) => { return Promise.reject(error.message); }).then((data: any) => { @@ -339,7 +339,7 @@ export class CoreSitesProvider { password: password, service: service }, - observable = this.http.post(siteUrl + '/login/token.php', params).timeout(CoreConstants.wsTimeout); + observable = this.http.post(siteUrl + '/login/token.php', params).timeout(CoreConstants.WS_TIMEOUT); return this.utils.observableToPromise(observable).then((data: any) : any => { if (typeof data == 'undefined') { diff --git a/src/providers/utils/dom.ts b/src/providers/utils/dom.ts index 3a3edbbb6..73e377e93 100644 --- a/src/providers/utils/dom.ts +++ b/src/providers/utils/dom.ts @@ -27,11 +27,13 @@ import { CoreConstants } from '../../core/constants'; */ @Injectable() export class CoreDomUtilsProvider { - element = document.createElement('div'); // Fake element to use in some functions, to prevent re-creating it each time. - matchesFn: string; // Name of the "matches" function to use when simulating a closest call. - inputSupportKeyboard = ['date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password', + // List of input types that support keyboard. + protected INPUT_SUPPORT_KEYBOARD = ['date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password', 'search', 'tel', 'text', 'time', 'url', 'week']; + protected element = document.createElement('div'); // Fake element to use in some functions, to prevent creating it each time. + protected matchesFn: string; // Name of the "matches" function to use when simulating a closest call. + constructor(private translate: TranslateService, private loadingCtrl: LoadingController, private toastCtrl: ToastController, private alertCtrl: AlertController, private textUtils: CoreTextUtilsProvider, private appProvider: CoreAppProvider, private platform: Platform, private configProvider: CoreConfigProvider, private urlUtils: CoreUrlUtilsProvider, @@ -103,8 +105,8 @@ export class CoreDomUtilsProvider { */ confirmDownloadSize(size: any, message?: string, unknownMessage?: string, wifiThreshold?: number, limitedThreshold?: number) : Promise { - wifiThreshold = typeof wifiThreshold == 'undefined' ? CoreConstants.wifiDownloadThreshold : wifiThreshold; - limitedThreshold = typeof limitedThreshold == 'undefined' ? CoreConstants.downloadThreshold : limitedThreshold; + wifiThreshold = typeof wifiThreshold == 'undefined' ? CoreConstants.WIFI_DOWNLOAD_THRESHOLD : wifiThreshold; + limitedThreshold = typeof limitedThreshold == 'undefined' ? CoreConstants.DOWNLOAD_THRESHOLD : limitedThreshold; if (size.size < 0 || (size.size == 0 && !size.total)) { // Seems size was unable to be calculated. Show a warning. @@ -424,7 +426,7 @@ export class CoreDomUtilsProvider { */ isRichTextEditorEnabled() : Promise { if (this.isRichTextEditorSupported()) { - return this.configProvider.get(CoreConstants.settingsRichTextEditor, true); + return this.configProvider.get(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, true); } return Promise.resolve(false); @@ -729,7 +731,7 @@ export class CoreDomUtilsProvider { * @return {Alert} The alert modal. */ showErrorModalDefault(error: any, defaultError: any, needsTranslate?: boolean, autocloseTime?: number) : Alert { - if (error != CoreConstants.dontShowError) { + if (error != CoreConstants.DONT_SHOW_ERROR) { if (error && typeof error != 'string') { error = error.message || error.error; } @@ -839,7 +841,7 @@ export class CoreDomUtilsProvider { */ supportsInputKeyboard(el: any) : boolean { return el && !el.disabled && (el.tagName.toLowerCase() == 'textarea' || - (el.tagName.toLowerCase() == 'input' && this.inputSupportKeyboard.indexOf(el.type) != -1)); + (el.tagName.toLowerCase() == 'input' && this.INPUT_SUPPORT_KEYBOARD.indexOf(el.type) != -1)); } /** diff --git a/src/providers/utils/mimetype.ts b/src/providers/utils/mimetype.ts index 096365aaf..fce9e3cd0 100644 --- a/src/providers/utils/mimetype.ts +++ b/src/providers/utils/mimetype.ts @@ -23,12 +23,12 @@ import { CoreTextUtilsProvider } from './text'; */ @Injectable() export class CoreMimetypeUtilsProvider { - logger; - extToMime = {}; // Object to map extensions -> mimetypes. - mimeToExt = {}; // Object to map mimetypes -> extensions. - groupsMimeInfo = {}; // Object to hold extensions and mimetypes that belong to a certain "group" (audio, video, ...). - extensionRegex = /^[a-z0-9]+$/; - wsProvider: any = {}; // @todo + protected logger; + protected extToMime = {}; // Object to map extensions -> mimetypes. + protected mimeToExt = {}; // Object to map mimetypes -> extensions. + protected groupsMimeInfo = {}; // Object to hold extensions and mimetypes that belong to a certain "group" (audio, video, ...). + protected extensionRegex = /^[a-z0-9]+$/; + protected wsProvider: any = {}; // @todo constructor(http: HttpClient, logger: CoreLoggerProvider, private translate: TranslateService, private textUtils: CoreTextUtilsProvider) { diff --git a/src/providers/utils/text.ts b/src/providers/utils/text.ts index e045adc01..587f2f1fd 100644 --- a/src/providers/utils/text.ts +++ b/src/providers/utils/text.ts @@ -22,7 +22,7 @@ import { CoreLangProvider } from '../lang'; */ @Injectable() export class CoreTextUtilsProvider { - element = document.createElement('div'); // Fake element to use in some functions, to prevent re-creating it each time. + protected element = document.createElement('div'); // Fake element to use in some functions, to prevent creating it each time. constructor(private translate: TranslateService, private langProvider: CoreLangProvider, private modalCtrl: ModalController) {} diff --git a/src/providers/utils/time.ts b/src/providers/utils/time.ts index f4deaa138..3382e77eb 100644 --- a/src/providers/utils/time.ts +++ b/src/providers/utils/time.ts @@ -33,17 +33,17 @@ export class CoreTimeUtilsProvider { */ formatTime(seconds: number) : string { let totalSecs = Math.abs(seconds), - years = Math.floor(totalSecs / CoreConstants.secondsYear), - remainder = totalSecs - (years * CoreConstants.secondsYear), - days = Math.floor(remainder / CoreConstants.secondsDay); + years = Math.floor(totalSecs / CoreConstants.SECONDS_YEAR), + remainder = totalSecs - (years * CoreConstants.SECONDS_YEAR), + days = Math.floor(remainder / CoreConstants.SECONDS_DAY); - remainder = totalSecs - (days * CoreConstants.secondsDay); + remainder = totalSecs - (days * CoreConstants.SECONDS_DAY); - let hours = Math.floor(remainder / CoreConstants.secondsHour); - remainder = remainder - (hours * CoreConstants.secondsHour); + let hours = Math.floor(remainder / CoreConstants.SECONDS_HOUR); + remainder = remainder - (hours * CoreConstants.SECONDS_HOUR); - let mins = Math.floor(remainder / CoreConstants.secondsMinute), - secs = remainder - (mins * CoreConstants.secondsMinute), + let mins = Math.floor(remainder / CoreConstants.SECONDS_MINUTE), + secs = remainder - (mins * CoreConstants.SECONDS_MINUTE), ss = this.translate.instant('core.' + (secs == 1 ? 'sec' : 'secs')), sm = this.translate.instant('core.' + (mins == 1 ? 'min' : 'mins')), sh = this.translate.instant('core.' + (hours == 1 ? 'hour' : 'hours')), diff --git a/src/providers/utils/utils.ts b/src/providers/utils/utils.ts index c2a084f09..fec2cc4b7 100644 --- a/src/providers/utils/utils.ts +++ b/src/providers/utils/utils.ts @@ -35,8 +35,8 @@ export interface PromiseDefer { */ @Injectable() export class CoreUtilsProvider { - logger; - iabInstance: InAppBrowserObject; + protected logger; + protected iabInstance: InAppBrowserObject; constructor(private iab: InAppBrowser, private appProvider: CoreAppProvider, private clipboard: Clipboard, private domUtils: CoreDomUtilsProvider, logger: CoreLoggerProvider, private translate: TranslateService, diff --git a/src/providers/ws.ts b/src/providers/ws.ts index 02d04fba4..e6002cd3b 100644 --- a/src/providers/ws.ts +++ b/src/providers/ws.ts @@ -68,11 +68,11 @@ export interface CoreWSFileUploadOptions extends FileUploadOptions { */ @Injectable() export class CoreWSProvider { - logger; - mimeTypeCache = {}; // A "cache" to store file mimetypes to prevent performing too many HEAD requests. - ongoingCalls = {}; - retryCalls = []; - retryTimeout = 0; + protected logger; + protected mimeTypeCache = {}; // A "cache" to store file mimetypes to prevent performing too many HEAD requests. + protected ongoingCalls = {}; + protected retryCalls = []; + protected retryTimeout = 0; constructor(private http: HttpClient, private translate: TranslateService, private appProvider: CoreAppProvider, private textUtils: CoreTextUtilsProvider, logger: CoreLoggerProvider, private utils: CoreUtilsProvider, @@ -180,7 +180,7 @@ export class CoreWSProvider { siteUrl = preSets.siteUrl + '/lib/ajax/service.php'; - let observable = this.http.post(siteUrl, JSON.stringify(ajaxData)).timeout(CoreConstants.wsTimeout); + let observable = this.http.post(siteUrl, JSON.stringify(ajaxData)).timeout(CoreConstants.WS_TIMEOUT); return this.utils.observableToPromise(observable).then((data: any) => { // Some moodle web services return null. If the responseExpected value is set then so long as no data // is returned, we create a blank object. @@ -436,7 +436,7 @@ export class CoreWSProvider { let promise = this.getPromiseHttp('head', url); if (!promise) { - promise = this.utils.observableToPromise(this.commonHttp.head(url).timeout(CoreConstants.wsTimeout)); + promise = this.utils.observableToPromise(this.commonHttp.head(url).timeout(CoreConstants.WS_TIMEOUT)); promise = this.setPromiseHttp(promise, 'head', url); } @@ -454,7 +454,7 @@ export class CoreWSProvider { */ performPost(method: string, siteUrl: string, ajaxData: any, preSets: CoreWSPreSets) : Promise { // Perform the post request. - let observable = this.http.post(siteUrl, ajaxData).timeout(CoreConstants.wsTimeout), + let observable = this.http.post(siteUrl, ajaxData).timeout(CoreConstants.WS_TIMEOUT), promise; promise = this.utils.observableToPromise(observable).then((data: any) => { @@ -547,7 +547,7 @@ export class CoreWSProvider { // HTTP not finished, but we should delete the promise after timeout. timeout = setTimeout(() => { delete this.ongoingCalls[queueItemId]; - }, CoreConstants.wsTimeout); + }, CoreConstants.WS_TIMEOUT); // HTTP finished, delete from ongoing. return promise.finally(() => {