MOBILE-2310 core: Apply constant and protected guidelines

main
Dani Palou 2018-01-12 14:28:46 +01:00
parent cbc983637d
commit 2194c8e294
32 changed files with 215 additions and 245 deletions

View File

@ -230,8 +230,8 @@ export class AddonCalendarProvider {
return this.groupsProvider.getUserGroups(courses, siteId).then((groups) => { return this.groupsProvider.getUserGroups(courses, siteId).then((groups) => {
let now = this.timeUtils.timestamp(), let now = this.timeUtils.timestamp(),
start = now + (CoreConstants.secondsDay * daysToStart), start = now + (CoreConstants.SECONDS_DAY * daysToStart),
end = start + (CoreConstants.secondsDay * daysInterval); end = start + (CoreConstants.SECONDS_DAY * daysInterval);
// The core_calendar_get_calendar_events needs all the current user courses and groups. // The core_calendar_get_calendar_events needs all the current user courses and groups.
let data = { let data = {

View File

@ -435,7 +435,7 @@ export class CoreSite {
// Check if the method is available, use a prefixed version if possible. // 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. // 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)) { if (this.getInfo() && !this.wsAvailable(method, false)) {
const compatibilityMethod = CoreConstants.wsPrefix + method; const compatibilityMethod = CoreConstants.WS_PREFIX + method;
if (this.wsAvailable(compatibilityMethod, false)) { if (this.wsAvailable(compatibilityMethod, false)) {
this.logger.info(`Using compatibility WS method '${compatibilityMethod}'`); this.logger.info(`Using compatibility WS method '${compatibilityMethod}'`);
method = compatibilityMethod; method = compatibilityMethod;
@ -565,7 +565,7 @@ export class CoreSite {
// Let's try again with the compatibility prefix. // Let's try again with the compatibility prefix.
if (checkPrefix) { if (checkPrefix) {
return this.wsAvailable(CoreConstants.wsPrefix + method, false); return this.wsAvailable(CoreConstants.WS_PREFIX + method, false);
} }
return false; return false;
@ -877,7 +877,7 @@ export class CoreSite {
return Promise.resolve({code: 0}); 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) => { return this.utils.observableToPromise(observable).then((data: any) => {
if (typeof data != 'undefined' && data.errorcode === 'requirecorrectaccess') { if (typeof data != 'undefined' && data.errorcode === 'requirecorrectaccess') {
if (!retrying) { if (!retrying) {
@ -930,7 +930,7 @@ export class CoreSite {
} }
this.infos.functions.forEach((func) => { this.infos.functions.forEach((func) => {
if (func.name.indexOf(CoreConstants.wsPrefix) != -1) { if (func.name.indexOf(CoreConstants.WS_PREFIX) != -1) {
appUsesLocalMobile = true; appUsesLocalMobile = true;
} }
}); });
@ -1074,7 +1074,7 @@ export class CoreSite {
}; };
if (!this.privateToken || !this.wsAvailable('tool_mobile_get_autologin_key') || 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. // No private token, WS not available or last auto-login was less than 6 minutes ago.
// Open the final URL without auto-login. // Open the final URL without auto-login.
return Promise.resolve(open(url)); return Promise.resolve(open(url));

View File

@ -102,10 +102,10 @@ export class CoreFileComponent implements OnInit, OnDestroy {
return this.filepoolProvider.getFileStateByUrl(this.siteId, this.fileUrl, this.timemodified).then((state) => { return this.filepoolProvider.getFileStateByUrl(this.siteId, this.fileUrl, this.timemodified).then((state) => {
let canDownload = this.sitesProvider.getCurrentSite().canDownloadFiles(); let canDownload = this.sitesProvider.getCurrentSite().canDownloadFiles();
this.isDownloaded = state === CoreConstants.downloaded || state === CoreConstants.outdated; this.isDownloaded = state === CoreConstants.DOWNLOADED || state === CoreConstants.OUTDATED;
this.isDownloading = canDownload && state === CoreConstants.downloading; this.isDownloading = canDownload && state === CoreConstants.DOWNLOADING;
this.showDownload = canDownload && (state === CoreConstants.notDownloaded || state === CoreConstants.outdated || this.showDownload = canDownload && (state === CoreConstants.NOT_DOWNLOADED || state === CoreConstants.OUTDATED ||
(this.alwaysDownload && state === CoreConstants.downloaded)); (this.alwaysDownload && state === CoreConstants.DOWNLOADED));
}); });
} }
@ -207,7 +207,7 @@ export class CoreFileComponent implements OnInit, OnDestroy {
let subPromise; let subPromise;
if (status === CoreConstants.notDownloaded) { if (status === CoreConstants.NOT_DOWNLOADED) {
// File is not downloaded, download and then return the local URL. // File is not downloaded, download and then return the local URL.
subPromise = this.downloadFile(); subPromise = this.downloadFile();
} else { } else {

View File

@ -16,34 +16,34 @@
* Static class to contain all the core constants. * Static class to contain all the core constants.
*/ */
export class CoreConstants { export class CoreConstants {
public static secondsYear = 31536000; public static SECONDS_YEAR = 31536000;
public static secondsWeek = 604800; public static SECONDS_WEEK = 604800;
public static secondsDay = 86400; public static SECONDS_DAY = 86400;
public static secondsHour = 3600; public static SECONDS_HOUR = 3600;
public static secondsMinute = 60; public static SECONDS_MINUTE = 60;
public static wifiDownloadThreshold = 104857600; // 100MB. public static WIFI_DOWNLOAD_THRESHOLD = 104857600; // 100MB.
public static downloadThreshold = 10485760; // 10MB. public static DOWNLOAD_THRESHOLD = 10485760; // 10MB.
public static dontShowError = 'CoreDontShowError'; public static DONT_SHOW_ERROR = 'CoreDontShowError';
public static noSiteId = 'NoSite'; public static NO_SITE_ID = 'NoSite';
// Settings constants. // Settings constants.
public static settingsRichTextEditor = 'CoreSettingsRichTextEditor'; public static SETTINGS_RICH_TEXT_EDITOR = 'CoreSettingsRichTextEditor';
public static settingsNotificationSound = 'CoreSettingsNotificationSound'; public static SETTINGS_NOTIFICATION_SOUND = 'CoreSettingsNotificationSound';
public static settingsSyncOnlyOnWifi = 'mmCoreSyncOnlyOnWifi'; public static SETTINGS_SYNC_ONLY_ON_WIFI = 'CoreSettingsSyncOnlyOnWifi';
// WS constants. // WS constants.
public static wsTimeout = 30000; public static WS_TIMEOUT = 30000;
public static wsPrefix = 'local_mobile_'; public static WS_PREFIX = 'local_mobile_';
// Login constants. // Login constants.
public static loginSSOCode = 2; // SSO in browser window is required. public static LOGIN_SSO_CODE = 2; // SSO in browser window is required.
public static loginSSOInAppCode = 3; // SSO in embedded browser is required. public static LOGIN_SSO_INAPP_CODE = 3; // SSO in embedded browser is required.
public static loginLaunchData = 'mmLoginLaunchData'; public static LOGIN_LAUNCH_DATA = 'CoreLoginLaunchData';
// Download status constants. // Download status constants.
public static downloaded = 'downloaded'; public static DOWNLOADED = 'downloaded';
public static downloading = 'downloading'; public static DOWNLOADING = 'downloading';
public static notDownloaded = 'notdownloaded'; public static NOT_DOWNLOADED = 'notdownloaded';
public static outdated = 'outdated'; public static OUTDATED = 'outdated';
public static notDownloadable = 'notdownloadable'; public static NOT_DOWNLOADABLE = 'notdownloadable';
} }

View File

@ -78,10 +78,10 @@ export class CoreCourseFormatWeeksHandler implements CoreCourseFormatHandler {
startDate = startDate + 7200; startDate = startDate + 7200;
let dates = { let dates = {
start: startDate + (CoreConstants.secondsWeek * (section.section - 1)), start: startDate + (CoreConstants.SECONDS_WEEK * (section.section - 1)),
end: 0 end: 0
}; };
dates.end = dates.start + CoreConstants.secondsWeek; dates.end = dates.start + CoreConstants.SECONDS_WEEK;
return dates; return dates;
} }
} }

View File

@ -28,6 +28,7 @@ import { CoreConstants } from '../../constants';
@Injectable() @Injectable()
export class CoreCourseProvider { export class CoreCourseProvider {
public static ALL_SECTIONS_ID = -1; public static ALL_SECTIONS_ID = -1;
protected ROOT_CACHE_KEY = 'mmCourse:';
// Variables for database. // Variables for database.
protected COURSE_STATUS_TABLE = 'course_status'; protected COURSE_STATUS_TABLE = 'course_status';
@ -64,7 +65,7 @@ export class CoreCourseProvider {
} }
protected logger; protected logger;
protected coreModules = [ protected CORE_MODULES = [
'assign', 'assignment', 'book', 'chat', 'choice', 'data', 'database', 'date', 'external-tool', 'assign', 'assignment', 'book', 'chat', 'choice', 'data', 'database', 'date', 'external-tool',
'feedback', 'file', 'folder', 'forum', 'glossary', 'ims', 'imscp', 'label', 'lesson', 'lti', 'page', 'quiz', 'feedback', 'file', 'folder', 'forum', 'glossary', 'ims', 'imscp', 'label', 'lesson', 'lti', 'page', 'quiz',
'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop' 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop'
@ -103,7 +104,7 @@ export class CoreCourseProvider {
this.logger.debug('Clear all course status for site ' + site.id); this.logger.debug('Clear all course status for site ' + site.id);
return site.getDb().deleteRecords(this.COURSE_STATUS_TABLE).then(() => { 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. * @return {string} Cache key.
*/ */
protected getActivitiesCompletionCacheKey(courseId: number, userId: number) : string { 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<string> { getCourseStatus(courseId: number, siteId?: string) : Promise<string> {
return this.getCourseStatusData(courseId, siteId).then((entry) => { return this.getCourseStatusData(courseId, siteId).then((entry) => {
return entry.status || CoreConstants.notDownloaded; return entry.status || CoreConstants.NOT_DOWNLOADED;
}).catch(() => { }).catch(() => {
return CoreConstants.notDownloaded; return CoreConstants.NOT_DOWNLOADED;
}); });
} }
@ -352,7 +353,7 @@ export class CoreCourseProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getModuleBasicInfoByInstanceCacheKey(id: number, module: string) : string { 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. * @return {string} Cache key.
*/ */
protected getModuleCacheKey(moduleId: number) : string { 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. * @return {string} The IMG src.
*/ */
getModuleIconSrc(moduleName: string) : string { getModuleIconSrc(moduleName: string) : string {
if (this.coreModules.indexOf(moduleName) < 0) { if (this.CORE_MODULES.indexOf(moduleName) < 0) {
moduleName = 'external-tool'; 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. * Return a specific section.
* *
@ -487,7 +479,7 @@ export class CoreCourseProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getSectionsCacheKey(courseId) : string { 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) => { return this.getCourseStatusData(courseId, siteId).then((entry) => {
this.logger.debug(`Set previous status '${entry.status}' for course ${courseId}`); 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(); 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. // Going back from downloading to previous status, restore previous download time.
newData.downloadTime = entry.previousDownloadTime; newData.downloadTime = entry.previousDownloadTime;
} }
@ -642,7 +634,7 @@ export class CoreCourseProvider {
let downloadTime, let downloadTime,
previousDownloadTime; previousDownloadTime;
if (status == CoreConstants.downloading) { if (status == CoreConstants.DOWNLOADING) {
// Set download time if course is now downloading. // Set download time if course is now downloading.
downloadTime = this.timeUtils.timestamp(); downloadTime = this.timeUtils.timestamp();
} }
@ -689,7 +681,7 @@ export class CoreCourseProvider {
* @return {string} Translated name. * @return {string} Translated name.
*/ */
translateModuleName(moduleName: string) : string { translateModuleName(moduleName: string) : string {
if (this.coreModules.indexOf(moduleName) < 0) { if (this.CORE_MODULES.indexOf(moduleName) < 0) {
moduleName = 'external-tool'; moduleName = 'external-tool';
} }

View File

@ -28,6 +28,7 @@ export class CoreCoursesProvider {
public static EVENT_MY_COURSES_REFRESHED = 'courses_my_courses_refreshed'; public static EVENT_MY_COURSES_REFRESHED = 'courses_my_courses_refreshed';
public static ACCESS_GUEST = 'courses_access_guest'; public static ACCESS_GUEST = 'courses_access_guest';
public static ACCESS_DEFAULT = 'courses_access_default'; public static ACCESS_DEFAULT = 'courses_access_default';
protected ROOT_CACHE_KEY = 'mmCourses:';
protected logger; protected logger;
constructor(logger: CoreLoggerProvider, private sitesProvider: CoreSitesProvider) { constructor(logger: CoreLoggerProvider, private sitesProvider: CoreSitesProvider) {
@ -68,7 +69,7 @@ export class CoreCoursesProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getCategoriesCacheKey(categoryId: number, addSubcategories?: boolean) : string { 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. * Check if My Courses is disabled in a certain site.
* *
@ -219,7 +211,7 @@ export class CoreCoursesProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getCourseEnrolmentMethodsCacheKey(id: number) : string { 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. * @return {string} Cache key.
*/ */
protected getCourseGuestEnrolmentInfoCacheKey(instanceId: number) : string { 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. * @return {string} Cache key.
*/ */
protected getCoursesCacheKey(ids: number[]) : string { 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 { protected getCoursesByFieldCacheKey(field?: string, value?: any) : string {
field = field || ''; field = field || '';
value = field ? value : ''; 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. * @return {string} Cache key.
*/ */
protected getUserAdministrationOptionsCommonCacheKey() : string { protected getUserAdministrationOptionsCommonCacheKey() : string {
return this.getRootCacheKey() + 'administrationOptions:'; return this.ROOT_CACHE_KEY + 'administrationOptions:';
} }
/** /**
@ -451,7 +443,7 @@ export class CoreCoursesProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getUserNavigationOptionsCommonCacheKey() : string { protected getUserNavigationOptionsCommonCacheKey() : string {
return this.getRootCacheKey() + 'navigationOptions:'; return this.ROOT_CACHE_KEY + 'navigationOptions:';
} }
/** /**
@ -566,7 +558,7 @@ export class CoreCoursesProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getUserCoursesCacheKey() : string { protected getUserCoursesCacheKey() : string {
return this.getRootCacheKey() + 'usercourses'; return this.ROOT_CACHE_KEY + 'usercourses';
} }
/** /**

View File

@ -24,6 +24,7 @@ import * as moment from 'moment';
export class CoreCoursesMyOverviewProvider { export class CoreCoursesMyOverviewProvider {
public static EVENTS_LIMIT = 20; public static EVENTS_LIMIT = 20;
public static EVENTS_LIMIT_PER_COURSE = 10; public static EVENTS_LIMIT_PER_COURSE = 10;
protected ROOT_CACHE_KEY = 'myoverview:';
constructor(private sitesProvider: CoreSitesProvider) {} constructor(private sitesProvider: CoreSitesProvider) {}
@ -113,7 +114,7 @@ export class CoreCoursesMyOverviewProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getActionEventsByCoursesCacheKey() : string { protected getActionEventsByCoursesCacheKey() : string {
return this.getRootCacheKey() + 'bycourse'; return this.ROOT_CACHE_KEY + 'bycourse';
} }
/** /**
@ -165,7 +166,7 @@ export class CoreCoursesMyOverviewProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getActionEventsByTimesortPrefixCacheKey() : string { 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; 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. * Invalidates get calendar action events for a given list of courses WS call.
* *

View File

@ -354,7 +354,7 @@ export class CoreEmulatorCaptureMediaPage implements OnInit, OnDestroy {
// Create the file and return it. // Create the file and return it.
let fileName = this.type + '_' + this.timeUtils.readableTimestamp() + '.' + this.extension, 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(); let loadingModal = this.domUtils.showModalLoading();

View File

@ -466,7 +466,7 @@ export class LocalNotificationsMock extends LocalNotifications {
// Schedule the notification again unless it should have been triggered more than an hour ago. // Schedule the notification again unless it should have been triggered more than an hour ago.
delete notification.triggered; delete notification.triggered;
notification.at = notification.at * 1000; 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); this.schedule(notification);
} }
} }
@ -551,19 +551,19 @@ export class LocalNotificationsMock extends LocalNotifications {
} else if (every == 'second') { } else if (every == 'second') {
interval = 1000; interval = 1000;
} else if (every == 'minute') { } else if (every == 'minute') {
interval = CoreConstants.secondsMinute * 1000; interval = CoreConstants.SECONDS_MINUTE * 1000;
} else if (every == 'hour') { } else if (every == 'hour') {
interval = CoreConstants.secondsHour * 1000; interval = CoreConstants.SECONDS_HOUR * 1000;
} else if (every == 'day') { } else if (every == 'day') {
interval = CoreConstants.secondsDay * 1000; interval = CoreConstants.SECONDS_DAY * 1000;
} else if (every == 'week') { } else if (every == 'week') {
interval = CoreConstants.secondsDay * 7 * 1000; interval = CoreConstants.SECONDS_DAY * 7 * 1000;
} else if (every == 'month') { } else if (every == 'month') {
interval = CoreConstants.secondsDay * 31 * 1000; interval = CoreConstants.SECONDS_DAY * 31 * 1000;
} else if (every == 'quarter') { } else if (every == 'quarter') {
interval = CoreConstants.secondsHour * 2190 * 1000; interval = CoreConstants.SECONDS_HOUR * 2190 * 1000;
} else if (every == 'year') { } else if (every == 'year') {
interval = CoreConstants.secondsYear * 1000; interval = CoreConstants.SECONDS_YEAR * 1000;
} else { } else {
interval = parseInt(every, 10); interval = parseInt(every, 10);
if (isNaN(interval)) { if (isNaN(interval)) {
@ -713,7 +713,7 @@ export class LocalNotificationsMock extends LocalNotifications {
tag: notification.id + '', tag: notification.id + '',
template: this.tileTemplate, template: this.tileTemplate,
strings: [notification.title, notification.text, notification.title, notification.text, notification.title, notification.text], 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() tileNotif.show()

View File

@ -94,13 +94,13 @@ export class CoreFileUploaderHelperProvider {
fileData; 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. // 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; fileData = data;
// Get unique name for the copy. // Get unique name for the copy.
return this.fileProvider.getUniqueNameInFolder(this.fileProvider.TMPFOLDER, name); return this.fileProvider.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, name);
}).then((newName) => { }).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); return this.fileProvider.writeFile(filePath, fileData);
}).catch((error) => { }).catch((error) => {
@ -158,10 +158,10 @@ export class CoreFileUploaderHelperProvider {
fileName = fileName.replace(/(\.[^\.]*)\?[^\.]*$/, '$1'); fileName = fileName.replace(/(\.[^\.]*)\?[^\.]*$/, '$1');
// Get a unique name in the folder to prevent overriding another file. // 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) => { }).then((newName) => {
// Now move or copy the file. // 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) { if (shouldDelete) {
return this.fileProvider.moveExternalFile(path, destPath); return this.fileProvider.moveExternalFile(path, destPath);
} else { } else {

View File

@ -47,7 +47,7 @@ export class CoreLoginInitPage {
// Only accept the redirect if it was stored less than 20 seconds ago. // Only accept the redirect if it was stored less than 20 seconds ago.
if (Date.now() - redirectData.timemodified < 20000) { 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. // The redirect is pointing to a site, load it.
return this.sitesProvider.loadSite(redirectData.siteId).then(() => { return this.sitesProvider.loadSite(redirectData.siteId).then(() => {
if (!this.loginHelper.isSiteLoggedOut(redirectData.page, redirectData.params)) { if (!this.loginHelper.isSiteLoggedOut(redirectData.page, redirectData.params)) {

View File

@ -187,7 +187,7 @@ export class CoreLoginHelperProvider {
* Show a confirm modal if needed and open a browser to perform SSO login. * 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 {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} [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} [launchUrl] The URL to open for SSO. If not defined, local_mobile launch URL will be used.
* @return {Void} * @return {Void}
@ -594,7 +594,7 @@ export class CoreLoginHelperProvider {
return true; 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. * @return {boolean} True if SSO login is needed, false othwerise.
*/ */
isSSOLoginNeeded(code: number) : boolean { 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. * @param {string} siteId Site to load.
*/ */
protected loadSiteAndPage(page: string, params: any, siteId: string) : void { 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. // Page doesn't belong to a site, just load the page.
this.appProvider.getRootNavController().setRoot(page, params); this.appProvider.getRootNavController().setRoot(page, params);
} else { } else {
@ -687,7 +687,7 @@ export class CoreLoginHelperProvider {
* Open a browser to perform SSO login. * Open a browser to perform SSO login.
* *
* @param {string} siteurl URL of the site where the SSO login will be performed. * @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} [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} [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. * @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" // 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. // 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, siteUrl: siteUrl,
passport: passport, passport: passport,
pageName: pageName || '', pageName: pageName || '',
@ -934,7 +934,7 @@ export class CoreLoginHelperProvider {
/** /**
* Check if a confirm should be shown to open a SSO authentication. * 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. * @return {boolean} True if confirm modal should be shown, false otherwise.
*/ */
shouldShowSSOConfirm(typeOfLogin: number) : boolean { shouldShowSSOConfirm(typeOfLogin: number) : boolean {
@ -988,7 +988,7 @@ export class CoreLoginHelperProvider {
// Split signature:::token // Split signature:::token
const params = url.split(":::"); 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 { try {
data = JSON.parse(data); data = JSON.parse(data);
} catch(ex) { } catch(ex) {
@ -999,7 +999,7 @@ export class CoreLoginHelperProvider {
passport = data.passport; passport = data.passport;
// Reset temporary values. // Reset temporary values.
this.configProvider.delete(CoreConstants.loginLaunchData); this.configProvider.delete(CoreConstants.LOGIN_LAUNCH_DATA);
// Validate the signature. // Validate the signature.
// We need to check both http and https. // We need to check both http and https.

View File

@ -57,10 +57,10 @@ export class CoreSecondsToHMSPipe implements PipeTransform {
// Don't allow decimals. // Don't allow decimals.
seconds = Math.floor(seconds); seconds = Math.floor(seconds);
hours = Math.floor(seconds / CoreConstants.secondsHour); hours = Math.floor(seconds / CoreConstants.SECONDS_HOUR);
seconds -= hours * CoreConstants.secondsHour; seconds -= hours * CoreConstants.SECONDS_HOUR;
minutes = Math.floor(seconds / CoreConstants.secondsMinute); minutes = Math.floor(seconds / CoreConstants.SECONDS_MINUTE);
seconds -= minutes * CoreConstants.secondsMinute; seconds -= minutes * CoreConstants.SECONDS_MINUTE;
return this.textUtils.twoDigits(hours) + ':' + this.textUtils.twoDigits(minutes) + ':' + this.textUtils.twoDigits(seconds); return this.textUtils.twoDigits(hours) + ':' + this.textUtils.twoDigits(minutes) + ':' + this.textUtils.twoDigits(seconds);
} }

View File

@ -40,11 +40,11 @@ export interface CoreRedirectData {
*/ */
@Injectable() @Injectable()
export class CoreAppProvider { export class CoreAppProvider {
DBNAME = 'MoodleMobile'; protected DBNAME = 'MoodleMobile';
db: SQLiteDB; protected db: SQLiteDB;
logger; protected logger;
ssoAuthenticationPromise : Promise<any>; protected ssoAuthenticationPromise : Promise<any>;
isKeyboardShown: boolean = false; protected isKeyboardShown: boolean = false;
constructor(dbProvider: CoreDbProvider, private platform: Platform, private keyboard: Keyboard, private appCtrl: App, constructor(dbProvider: CoreDbProvider, private platform: Platform, private keyboard: Keyboard, private appCtrl: App,
private network: Network, logger: CoreLoggerProvider) { private network: Network, logger: CoreLoggerProvider) {

View File

@ -22,9 +22,9 @@ import { SQLiteDB } from '../classes/sqlitedb';
*/ */
@Injectable() @Injectable()
export class CoreConfigProvider { export class CoreConfigProvider {
appDB: SQLiteDB; protected appDB: SQLiteDB;
TABLE_NAME = 'core_config'; protected TABLE_NAME = 'core_config';
tableSchema = { protected tableSchema = {
name: this.TABLE_NAME, name: this.TABLE_NAME,
columns: [ columns: [
{ {

View File

@ -109,7 +109,7 @@ export class CoreCronDelegate {
if (isSync) { if (isSync) {
// Check network connection. // 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(); return !syncOnlyOnWifi || !this.appProvider.isNetworkAccessLimited();
}); });
} else { } else {

View File

@ -24,7 +24,7 @@ import { SQLiteDBMock } from '../core/emulator/classes/sqlitedb';
@Injectable() @Injectable()
export class CoreDbProvider { export class CoreDbProvider {
dbInstances = {}; protected dbInstances = {};
constructor(private sqlite: SQLite, private platform: Platform) {} constructor(private sqlite: SQLite, private platform: Platform) {}

View File

@ -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 APP_LAUNCHED_URL = 'app_launched_url'; // App opened with a certain URL (custom URL scheme).
public static FILE_SHARED = 'file_shared'; public static FILE_SHARED = 'file_shared';
logger; protected logger;
observables: {[s: string] : Subject<any>} = {}; protected observables: {[s: string] : Subject<any>} = {};
uniqueEvents = {}; protected uniqueEvents = {};
constructor(logger: CoreLoggerProvider) { constructor(logger: CoreLoggerProvider) {
this.logger = logger.getInstance('CoreEventsProvider'); this.logger = logger.getInstance('CoreEventsProvider');

View File

@ -27,20 +27,20 @@ import { Zip } from '@ionic-native/zip';
*/ */
@Injectable() @Injectable()
export class CoreFileProvider { export class CoreFileProvider {
logger; protected logger;
initialized = false; protected initialized = false;
basePath = ''; protected basePath = '';
isHTMLAPI = false; protected isHTMLAPI = false;
// Formats to read a file. // Formats to read a file.
FORMATTEXT = 0; public static FORMATTEXT = 0;
FORMATDATAURL = 1; public static FORMATDATAURL = 1;
FORMATBINARYSTRING = 2; public static FORMATBINARYSTRING = 2;
FORMATARRAYBUFFER = 3; public static FORMATARRAYBUFFER = 3;
// Folders. // Folders.
SITESFOLDER = 'sites'; public static SITESFOLDER = 'sites';
TMPFOLDER = 'tmp'; public static TMPFOLDER = 'tmp';
constructor(logger: CoreLoggerProvider, private platform: Platform, private file: File, private appProvider: CoreAppProvider, constructor(logger: CoreLoggerProvider, private platform: Platform, private file: File, private appProvider: CoreAppProvider,
private textUtils: CoreTextUtilsProvider, private zip: Zip, private mimeUtils: CoreMimetypeUtilsProvider) { private textUtils: CoreTextUtilsProvider, private zip: Zip, private mimeUtils: CoreMimetypeUtilsProvider) {
@ -136,7 +136,7 @@ export class CoreFileProvider {
* @return {string} Site folder path. * @return {string} Site folder path.
*/ */
getSiteFolder(siteId: string) : string { getSiteFolder(siteId: string) : string {
return this.SITESFOLDER + '/' + siteId; return CoreFileProvider.SITESFOLDER + '/' + siteId;
} }
/** /**
@ -380,17 +380,17 @@ export class CoreFileProvider {
* FORMATARRAYBUFFER * FORMATARRAYBUFFER
* @return {Promise<any>} Promise to be resolved when the file is read. * @return {Promise<any>} Promise to be resolved when the file is read.
*/ */
readFile(path: string, format = this.FORMATTEXT) : Promise<any> { readFile(path: string, format = CoreFileProvider.FORMATTEXT) : Promise<any> {
// Remove basePath if it's in the path. // Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, '')); path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Read file ' + path + ' with format ' + format); this.logger.debug('Read file ' + path + ' with format ' + format);
switch (format) { switch (format) {
case this.FORMATDATAURL: case CoreFileProvider.FORMATDATAURL:
return this.file.readAsDataURL(this.basePath, path); return this.file.readAsDataURL(this.basePath, path);
case this.FORMATBINARYSTRING: case CoreFileProvider.FORMATBINARYSTRING:
return this.file.readAsBinaryString(this.basePath, path); return this.file.readAsBinaryString(this.basePath, path);
case this.FORMATARRAYBUFFER: case CoreFileProvider.FORMATARRAYBUFFER:
return this.file.readAsArrayBuffer(this.basePath, path); return this.file.readAsArrayBuffer(this.basePath, path);
default: default:
return this.file.readAsText(this.basePath, path); return this.file.readAsText(this.basePath, path);
@ -408,8 +408,8 @@ export class CoreFileProvider {
* FORMATARRAYBUFFER * FORMATARRAYBUFFER
* @return {Promise<any>} Promise to be resolved when the file is read. * @return {Promise<any>} Promise to be resolved when the file is read.
*/ */
readFileData(fileData: any, format = this.FORMATTEXT) : Promise<any> { readFileData(fileData: any, format = CoreFileProvider.FORMATTEXT) : Promise<any> {
format = format || this.FORMATTEXT; format = format || CoreFileProvider.FORMATTEXT;
this.logger.debug('Read file from file data with format ' + format); this.logger.debug('Read file from file data with format ' + format);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -426,13 +426,13 @@ export class CoreFileProvider {
} }
switch (format) { switch (format) {
case this.FORMATDATAURL: case CoreFileProvider.FORMATDATAURL:
reader.readAsDataURL(fileData); reader.readAsDataURL(fileData);
break; break;
case this.FORMATBINARYSTRING: case CoreFileProvider.FORMATBINARYSTRING:
reader.readAsBinaryString(fileData); reader.readAsBinaryString(fileData);
break; break;
case this.FORMATARRAYBUFFER: case CoreFileProvider.FORMATARRAYBUFFER:
reader.readAsArrayBuffer(fileData); reader.readAsArrayBuffer(fileData);
break; break;
default: default:
@ -883,7 +883,7 @@ export class CoreFileProvider {
* @return {Promise<any>} Promise resolved when done. * @return {Promise<any>} Promise resolved when done.
*/ */
clearTmpFolder() : Promise<any> { clearTmpFolder() : Promise<any> {
return this.removeDir(this.TMPFOLDER); return this.removeDir(CoreFileProvider.TMPFOLDER);
} }
/** /**

View File

@ -648,7 +648,7 @@ export class CoreFilepoolProvider {
return site.getDb().deleteRecords(this.PACKAGES_TABLE).then(() => { return site.getDb().deleteRecords(this.PACKAGES_TABLE).then(() => {
entries.forEach((entry) => { entries.forEach((entry) => {
// Trigger module status changed, setting it as not downloaded. // 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, * 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: * 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.NOT_DOWNLOADABLE if there are no downloadable packages.
* - CoreConstants.notDownloaded if at least 1 package has status CoreConstants.notDownloaded. * - 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.DOWNLOADED if ALL the downloadable packages have status CoreConstants.DOWNLOADED.
* - CoreConstants.downloading if ALL the downloadable packages have status CoreConstants.downloading or * - CoreConstants.DOWNLOADING if ALL the downloadable packages have status CoreConstants.DOWNLOADING or
* CoreConstants.downloaded, with at least 1 package with CoreConstants.downloading. * CoreConstants.DOWNLOADED, with at least 1 package with CoreConstants.DOWNLOADING.
* - CoreConstants.outdated if ALL the downloadable packages have status CoreConstants.outdated or CoreConstants.downloaded * - 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. * or CoreConstants.DOWNLOADING, with at least 1 package with CoreConstants.OUTDATED.
* *
* @param {string} current Current status of the list of packages. * @param {string} current Current status of the list of packages.
* @param {string} packagestatus Status of one of the packages. * @param {string} packagestatus Status of one of the packages.
@ -707,22 +707,22 @@ export class CoreFilepoolProvider {
*/ */
determinePackagesStatus(current: string, packageStatus: string) : string { determinePackagesStatus(current: string, packageStatus: string) : string {
if (!current) { 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. // If 1 package is not downloaded the status of the whole list will always be not downloaded.
return CoreConstants.notDownloaded; return CoreConstants.NOT_DOWNLOADED;
} else if (packageStatus === CoreConstants.downloaded && current === CoreConstants.notDownloadable) { } 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. // If all packages are downloaded or not downloadable with at least 1 downloaded, status will be downloaded.
return CoreConstants.downloaded; return CoreConstants.DOWNLOADED;
} else if (packageStatus === CoreConstants.downloading && } else if (packageStatus === CoreConstants.DOWNLOADING &&
(current === CoreConstants.notDownloadable || current === CoreConstants.downloaded)) { (current === CoreConstants.NOT_DOWNLOADABLE || current === CoreConstants.DOWNLOADED)) {
// If all packages are downloading/downloaded/notdownloadable with at least 1 downloading, status will be downloading. // If all packages are downloading/downloaded/notdownloadable with at least 1 downloading, status will be downloading.
return CoreConstants.downloading; return CoreConstants.DOWNLOADING;
} else if (packageStatus === CoreConstants.outdated && current !== CoreConstants.notDownloaded) { } 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. // 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. // Status remains the same.
@ -865,7 +865,7 @@ export class CoreFilepoolProvider {
timemodified = timemodified || this.getTimemodifiedFromFileList(fileList); timemodified = timemodified || this.getTimemodifiedFromFileList(fileList);
// Set package as downloading. // Set package as downloading.
promise = this.storePackageStatus(siteId, CoreConstants.downloading, component, componentId).then(() => { promise = this.storePackageStatus(siteId, CoreConstants.DOWNLOADING, component, componentId).then(() => {
let promises = [], let promises = [],
packageLoaded = 0; packageLoaded = 0;
@ -919,7 +919,7 @@ export class CoreFilepoolProvider {
return Promise.all(promises).then(() => { return Promise.all(promises).then(() => {
// Success prefetching, store package as downloaded. // 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(() => { }).catch(() => {
// Error downloading, go back to previous status and reject the promise. // Error downloading, go back to previous status and reject the promise.
return this.setPackagePreviousStatus(siteId, component, componentId).then(() => { 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). // Check if the file is in queue (waiting to be downloaded).
return this.hasFileInQueue(siteId, fileId).then(() => { return this.hasFileInQueue(siteId, fileId).then(() => {
return CoreConstants.downloading; return CoreConstants.DOWNLOADING;
}).catch(() => { }).catch(() => {
// Check if the file is being downloaded right now. // Check if the file is being downloaded right now.
let extension = this.mimeUtils.guessExtensionFromUrl(fileUrl), let extension = this.mimeUtils.guessExtensionFromUrl(fileUrl),
@ -1400,18 +1400,18 @@ export class CoreFilepoolProvider {
return Promise.resolve(path).then((filePath) => { return Promise.resolve(path).then((filePath) => {
const downloadId = this.getFileDownloadId(fileUrl, filePath); const downloadId = this.getFileDownloadId(fileUrl, filePath);
if (this.filePromises[siteId] && this.filePromises[siteId][downloadId]) { 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. // File is not being downloaded. Check if it's downloaded and if it's outdated.
return this.hasFileInPool(siteId, fileId).then((entry) => { return this.hasFileInPool(siteId, fileId).then((entry) => {
if (this.isFileOutdated(entry, revision, timemodified)) { if (this.isFileOutdated(entry, revision, timemodified)) {
return CoreConstants.outdated; return CoreConstants.OUTDATED;
} else { } else {
return CoreConstants.downloaded; return CoreConstants.DOWNLOADED;
} }
}).catch(() => { }).catch(() => {
return CoreConstants.notDownloaded; return CoreConstants.NOT_DOWNLOADED;
}); });
}); });
}); });
@ -1584,9 +1584,9 @@ export class CoreFilepoolProvider {
*/ */
getPackageCurrentStatus(siteId: string, component: string, componentId?: string|number) : Promise<string> { getPackageCurrentStatus(siteId: string, component: string, componentId?: string|number) : Promise<string> {
return this.getPackageData(siteId, component, componentId).then((entry) => { return this.getPackageData(siteId, component, componentId).then((entry) => {
return entry.status || CoreConstants.notDownloaded; return entry.status || CoreConstants.NOT_DOWNLOADED;
}).catch(() => { }).catch(() => {
return CoreConstants.notDownloaded; return CoreConstants.NOT_DOWNLOADED;
}); });
} }
@ -1705,9 +1705,9 @@ export class CoreFilepoolProvider {
*/ */
getPackagePreviousStatus(siteId: string, component: string, componentId?: string|number) : Promise<string> { getPackagePreviousStatus(siteId: string, component: string, componentId?: string|number) : Promise<string> {
return this.getPackageData(siteId, component, componentId).then((entry) => { return this.getPackageData(siteId, component, componentId).then((entry) => {
return entry.previous || CoreConstants.notDownloaded; return entry.previous || CoreConstants.NOT_DOWNLOADED;
}).catch(() => { }).catch(() => {
return CoreConstants.notDownloaded; return CoreConstants.NOT_DOWNLOADED;
}); });
} }
@ -1745,34 +1745,34 @@ export class CoreFilepoolProvider {
// Get status. // Get status.
return site.getDb().getRecord(this.PACKAGES_TABLE, conditions).then((entry: CoreFilepoolPackageEntry) => { 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) { if (revision != entry.revision || timemodified > entry.timemodified) {
// File is outdated. Let's change its status. // File is outdated. Let's change its status.
let newData: CoreFilepoolPackageEntry = { let newData: CoreFilepoolPackageEntry = {
status: CoreConstants.outdated, status: CoreConstants.OUTDATED,
updated: Date.now() updated: Date.now()
}; };
site.getDb().updateRecords(this.PACKAGES_TABLE, newData, conditions).then(() => { site.getDb().updateRecords(this.PACKAGES_TABLE, newData, conditions).then(() => {
// Success inserting, trigger event. // 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) { if (revision === entry.revision && timemodified === entry.timemodified) {
// File isn't outdated anymore. Let's change its status. // File isn't outdated anymore. Let's change its status.
let newData: CoreFilepoolPackageEntry = { let newData: CoreFilepoolPackageEntry = {
status: CoreConstants.downloaded, status: CoreConstants.DOWNLOADED,
updated: Date.now() updated: Date.now()
}; };
site.getDb().updateRecords(this.PACKAGES_TABLE, newData, conditions).then(() => { site.getDb().updateRecords(this.PACKAGES_TABLE, newData, conditions).then(() => {
// Success inserting, trigger event. // Success inserting, trigger event.
this.triggerPackageStatusChanged(siteId, CoreConstants.downloaded, component, componentId); this.triggerPackageStatusChanged(siteId, CoreConstants.DOWNLOADED, component, componentId);
}); });
} }
} }
return entry.status; 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. // Get current stored data, we'll only update 'status' and 'updated' fields.
return site.getDb().getRecord(this.PACKAGES_TABLE, {id: packageId}).then((entry: CoreFilepoolPackageEntry) => { return site.getDb().getRecord(this.PACKAGES_TABLE, {id: packageId}).then((entry: CoreFilepoolPackageEntry) => {
let newData: 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. // Going back from downloading to previous status, restore previous download time.
newData.downloadTime = entry.previousDownloadTime; newData.downloadTime = entry.previousDownloadTime;
} }
newData.status = entry.previous || CoreConstants.downloaded; newData.status = entry.previous || CoreConstants.DOWNLOADED;
newData.updated = Date.now(); newData.updated = Date.now();
this.logger.debug(`Set previous status '${entry.status}' for package ${component} ${componentId}`); this.logger.debug(`Set previous status '${entry.status}' for package ${component} ${componentId}`);
@ -2582,7 +2582,7 @@ export class CoreFilepoolProvider {
downloadTime, downloadTime,
previousDownloadTime; previousDownloadTime;
if (status == CoreConstants.downloading) { if (status == CoreConstants.DOWNLOADING) {
// Set download time if package is now downloading. // Set download time if package is now downloading.
downloadTime = this.timeUtils.timestamp(); downloadTime = this.timeUtils.timestamp();
} }

View File

@ -31,6 +31,7 @@ export class CoreGroupsProvider {
public static NOGROUPS = 0; public static NOGROUPS = 0;
public static SEPARATEGROUPS = 1; public static SEPARATEGROUPS = 1;
public static VISIBLEGROUPS = 2; public static VISIBLEGROUPS = 2;
protected ROOT_CACHE_KEY = 'mmGroups:';
constructor(private sitesProvider: CoreSitesProvider, private translate: TranslateService) {} constructor(private sitesProvider: CoreSitesProvider, private translate: TranslateService) {}
@ -86,7 +87,7 @@ export class CoreGroupsProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getActivityAllowedGroupsCacheKey(cmId: number, userId: number) : string { 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. * @return {string} Cache key.
*/ */
protected getActivityGroupModeCacheKey(cmId: number) : string { protected getActivityGroupModeCacheKey(cmId: number) : string {
return this.getRootCacheKey() + 'groupmode:' + cmId; return this.ROOT_CACHE_KEY + 'groupmode:' + cmId;
}
/**
* Get the "root" cache key for WS calls.
*
* @return {string} Cache key.
*/
protected getRootCacheKey() : string {
return 'mmGroups:';
} }
/** /**
@ -249,7 +241,7 @@ export class CoreGroupsProvider {
* @return {string} Cache key. * @return {string} Cache key.
*/ */
protected getUserGroupsInCourseCacheKey(courseId: number, userId: number) : string { protected getUserGroupsInCourseCacheKey(courseId: number, userId: number) : string {
return this.getRootCacheKey() + 'courseGroups:' + courseId + ':' + userId; return this.ROOT_CACHE_KEY + 'courseGroups:' + courseId + ':' + userId;
} }
/** /**

View File

@ -32,9 +32,9 @@ export class CoreInitDelegate {
public static DEFAULT_PRIORITY = 100; // Default priority for init processes. public static DEFAULT_PRIORITY = 100; // Default priority for init processes.
public static MAX_RECOMMENDED_PRIORITY = 600; public static MAX_RECOMMENDED_PRIORITY = 600;
initProcesses = {}; protected initProcesses = {};
logger; protected logger;
readiness; protected readiness;
constructor(logger: CoreLoggerProvider, platform: Platform, private utils: CoreUtilsProvider) { constructor(logger: CoreLoggerProvider, platform: Platform, private utils: CoreUtilsProvider) {
this.logger = logger.getInstance('CoreInitDelegate'); this.logger = logger.getInstance('CoreInitDelegate');

View File

@ -26,10 +26,10 @@ import { CoreConfigConstants } from '../configconstants';
*/ */
@Injectable() @Injectable()
export class CoreLangProvider { export class CoreLangProvider {
fallbackLanguage:string = 'en'; // mmCoreConfigConstants.default_lang || 'en', protected fallbackLanguage:string = 'en'; // mmCoreConfigConstants.default_lang || 'en',
currentLanguage: string; // Save current language in a variable to speed up the get function. protected currentLanguage: string; // Save current language in a variable to speed up the get function.
customStrings = {}; protected customStrings = {};
customStringsRaw: string; protected customStringsRaw: string;
constructor(private translate: TranslateService, private configProvider: CoreConfigProvider, platform: Platform, constructor(private translate: TranslateService, private configProvider: CoreConfigProvider, platform: Platform,
private globalization: Globalization) { private globalization: Globalization) {

View File

@ -432,7 +432,7 @@ export class CoreLocalNotificationsProvider {
return this.isTriggered(notification).then((triggered) => { return this.isTriggered(notification).then((triggered) => {
if (!triggered) { if (!triggered) {
// Check if sound is enabled for notifications. // 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) { if (!soundEnabled) {
notification.sound = null; notification.sound = null;
} else { } else {

View File

@ -234,7 +234,7 @@ export class CoreSitesProvider {
this.services[siteUrl] = data.service; // No need to store it in DB. this.services[siteUrl] = data.service; // No need to store it in DB.
if (data.coreSupported || 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. // SSO using local_mobile not needed, try to get the site public config.
return temporarySite.getPublicConfig().then((config) : any => { return temporarySite.getPublicConfig().then((config) : any => {
publicConfig = config; publicConfig = config;
@ -301,7 +301,7 @@ export class CoreSitesProvider {
data.service = 'c'; 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 this.utils.observableToPromise(observable).catch((error) => {
return Promise.reject(error.message); return Promise.reject(error.message);
}).then((data: any) => { }).then((data: any) => {
@ -339,7 +339,7 @@ export class CoreSitesProvider {
password: password, password: password,
service: service 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 => { return this.utils.observableToPromise(observable).then((data: any) : any => {
if (typeof data == 'undefined') { if (typeof data == 'undefined') {

View File

@ -27,11 +27,13 @@ import { CoreConstants } from '../../core/constants';
*/ */
@Injectable() @Injectable()
export class CoreDomUtilsProvider { export class CoreDomUtilsProvider {
element = document.createElement('div'); // Fake element to use in some functions, to prevent re-creating it each time. // List of input types that support keyboard.
matchesFn: string; // Name of the "matches" function to use when simulating a closest call. protected INPUT_SUPPORT_KEYBOARD = ['date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password',
inputSupportKeyboard = ['date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password',
'search', 'tel', 'text', 'time', 'url', 'week']; '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, constructor(private translate: TranslateService, private loadingCtrl: LoadingController, private toastCtrl: ToastController,
private alertCtrl: AlertController, private textUtils: CoreTextUtilsProvider, private appProvider: CoreAppProvider, private alertCtrl: AlertController, private textUtils: CoreTextUtilsProvider, private appProvider: CoreAppProvider,
private platform: Platform, private configProvider: CoreConfigProvider, private urlUtils: CoreUrlUtilsProvider, 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) confirmDownloadSize(size: any, message?: string, unknownMessage?: string, wifiThreshold?: number, limitedThreshold?: number)
: Promise<void> { : Promise<void> {
wifiThreshold = typeof wifiThreshold == 'undefined' ? CoreConstants.wifiDownloadThreshold : wifiThreshold; wifiThreshold = typeof wifiThreshold == 'undefined' ? CoreConstants.WIFI_DOWNLOAD_THRESHOLD : wifiThreshold;
limitedThreshold = typeof limitedThreshold == 'undefined' ? CoreConstants.downloadThreshold : limitedThreshold; limitedThreshold = typeof limitedThreshold == 'undefined' ? CoreConstants.DOWNLOAD_THRESHOLD : limitedThreshold;
if (size.size < 0 || (size.size == 0 && !size.total)) { if (size.size < 0 || (size.size == 0 && !size.total)) {
// Seems size was unable to be calculated. Show a warning. // Seems size was unable to be calculated. Show a warning.
@ -424,7 +426,7 @@ export class CoreDomUtilsProvider {
*/ */
isRichTextEditorEnabled() : Promise<boolean> { isRichTextEditorEnabled() : Promise<boolean> {
if (this.isRichTextEditorSupported()) { if (this.isRichTextEditorSupported()) {
return this.configProvider.get(CoreConstants.settingsRichTextEditor, true); return this.configProvider.get(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, true);
} }
return Promise.resolve(false); return Promise.resolve(false);
@ -729,7 +731,7 @@ export class CoreDomUtilsProvider {
* @return {Alert} The alert modal. * @return {Alert} The alert modal.
*/ */
showErrorModalDefault(error: any, defaultError: any, needsTranslate?: boolean, autocloseTime?: number) : Alert { 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') { if (error && typeof error != 'string') {
error = error.message || error.error; error = error.message || error.error;
} }
@ -839,7 +841,7 @@ export class CoreDomUtilsProvider {
*/ */
supportsInputKeyboard(el: any) : boolean { supportsInputKeyboard(el: any) : boolean {
return el && !el.disabled && (el.tagName.toLowerCase() == 'textarea' || 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));
} }
/** /**

View File

@ -23,12 +23,12 @@ import { CoreTextUtilsProvider } from './text';
*/ */
@Injectable() @Injectable()
export class CoreMimetypeUtilsProvider { export class CoreMimetypeUtilsProvider {
logger; protected logger;
extToMime = {}; // Object to map extensions -> mimetypes. protected extToMime = {}; // Object to map extensions -> mimetypes.
mimeToExt = {}; // Object to map mimetypes -> extensions. protected mimeToExt = {}; // Object to map mimetypes -> extensions.
groupsMimeInfo = {}; // Object to hold extensions and mimetypes that belong to a certain "group" (audio, video, ...). protected groupsMimeInfo = {}; // Object to hold extensions and mimetypes that belong to a certain "group" (audio, video, ...).
extensionRegex = /^[a-z0-9]+$/; protected extensionRegex = /^[a-z0-9]+$/;
wsProvider: any = {}; // @todo protected wsProvider: any = {}; // @todo
constructor(http: HttpClient, logger: CoreLoggerProvider, private translate: TranslateService, constructor(http: HttpClient, logger: CoreLoggerProvider, private translate: TranslateService,
private textUtils: CoreTextUtilsProvider) { private textUtils: CoreTextUtilsProvider) {

View File

@ -22,7 +22,7 @@ import { CoreLangProvider } from '../lang';
*/ */
@Injectable() @Injectable()
export class CoreTextUtilsProvider { 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) {} constructor(private translate: TranslateService, private langProvider: CoreLangProvider, private modalCtrl: ModalController) {}

View File

@ -33,17 +33,17 @@ export class CoreTimeUtilsProvider {
*/ */
formatTime(seconds: number) : string { formatTime(seconds: number) : string {
let totalSecs = Math.abs(seconds), let totalSecs = Math.abs(seconds),
years = Math.floor(totalSecs / CoreConstants.secondsYear), years = Math.floor(totalSecs / CoreConstants.SECONDS_YEAR),
remainder = totalSecs - (years * CoreConstants.secondsYear), remainder = totalSecs - (years * CoreConstants.SECONDS_YEAR),
days = Math.floor(remainder / CoreConstants.secondsDay); 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); let hours = Math.floor(remainder / CoreConstants.SECONDS_HOUR);
remainder = remainder - (hours * CoreConstants.secondsHour); remainder = remainder - (hours * CoreConstants.SECONDS_HOUR);
let mins = Math.floor(remainder / CoreConstants.secondsMinute), let mins = Math.floor(remainder / CoreConstants.SECONDS_MINUTE),
secs = remainder - (mins * CoreConstants.secondsMinute), secs = remainder - (mins * CoreConstants.SECONDS_MINUTE),
ss = this.translate.instant('core.' + (secs == 1 ? 'sec' : 'secs')), ss = this.translate.instant('core.' + (secs == 1 ? 'sec' : 'secs')),
sm = this.translate.instant('core.' + (mins == 1 ? 'min' : 'mins')), sm = this.translate.instant('core.' + (mins == 1 ? 'min' : 'mins')),
sh = this.translate.instant('core.' + (hours == 1 ? 'hour' : 'hours')), sh = this.translate.instant('core.' + (hours == 1 ? 'hour' : 'hours')),

View File

@ -35,8 +35,8 @@ export interface PromiseDefer {
*/ */
@Injectable() @Injectable()
export class CoreUtilsProvider { export class CoreUtilsProvider {
logger; protected logger;
iabInstance: InAppBrowserObject; protected iabInstance: InAppBrowserObject;
constructor(private iab: InAppBrowser, private appProvider: CoreAppProvider, private clipboard: Clipboard, constructor(private iab: InAppBrowser, private appProvider: CoreAppProvider, private clipboard: Clipboard,
private domUtils: CoreDomUtilsProvider, logger: CoreLoggerProvider, private translate: TranslateService, private domUtils: CoreDomUtilsProvider, logger: CoreLoggerProvider, private translate: TranslateService,

View File

@ -68,11 +68,11 @@ export interface CoreWSFileUploadOptions extends FileUploadOptions {
*/ */
@Injectable() @Injectable()
export class CoreWSProvider { export class CoreWSProvider {
logger; protected logger;
mimeTypeCache = {}; // A "cache" to store file mimetypes to prevent performing too many HEAD requests. protected mimeTypeCache = {}; // A "cache" to store file mimetypes to prevent performing too many HEAD requests.
ongoingCalls = {}; protected ongoingCalls = {};
retryCalls = []; protected retryCalls = [];
retryTimeout = 0; protected retryTimeout = 0;
constructor(private http: HttpClient, private translate: TranslateService, private appProvider: CoreAppProvider, constructor(private http: HttpClient, private translate: TranslateService, private appProvider: CoreAppProvider,
private textUtils: CoreTextUtilsProvider, logger: CoreLoggerProvider, private utils: CoreUtilsProvider, private textUtils: CoreTextUtilsProvider, logger: CoreLoggerProvider, private utils: CoreUtilsProvider,
@ -180,7 +180,7 @@ export class CoreWSProvider {
siteUrl = preSets.siteUrl + '/lib/ajax/service.php'; 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) => { 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 // 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. // is returned, we create a blank object.
@ -436,7 +436,7 @@ export class CoreWSProvider {
let promise = this.getPromiseHttp('head', url); let promise = this.getPromiseHttp('head', url);
if (!promise) { 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); promise = this.setPromiseHttp(promise, 'head', url);
} }
@ -454,7 +454,7 @@ export class CoreWSProvider {
*/ */
performPost(method: string, siteUrl: string, ajaxData: any, preSets: CoreWSPreSets) : Promise<any> { performPost(method: string, siteUrl: string, ajaxData: any, preSets: CoreWSPreSets) : Promise<any> {
// Perform the post request. // 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;
promise = this.utils.observableToPromise(observable).then((data: any) => { 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. // HTTP not finished, but we should delete the promise after timeout.
timeout = setTimeout(() => { timeout = setTimeout(() => {
delete this.ongoingCalls[queueItemId]; delete this.ongoingCalls[queueItemId];
}, CoreConstants.wsTimeout); }, CoreConstants.WS_TIMEOUT);
// HTTP finished, delete from ongoing. // HTTP finished, delete from ongoing.
return promise.finally(() => { return promise.finally(() => {