MOBILE-2333 core: Use parseJSON from text utils

main
Dani Palou 2018-03-13 09:12:30 +01:00
parent 9684f9789a
commit 489de4fc09
13 changed files with 74 additions and 93 deletions

View File

@ -21,6 +21,7 @@ import { AddonMessagesOfflineProvider } from './messages-offline';
import { AddonMessagesProvider } from './messages';
import { CoreUserProvider } from '@core/user/providers/user';
import { CoreEventsProvider } from '@providers/events';
import { CoreTextUtilsProvider } from '@providers/utils/text';
import { CoreUtilsProvider } from '@providers/utils/utils';
import { TranslateService } from '@ngx-translate/core';
import { CoreSyncProvider } from '@providers/sync';
@ -37,8 +38,8 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider {
protected appProvider: CoreAppProvider, private messagesOffline: AddonMessagesOfflineProvider,
private eventsProvider: CoreEventsProvider, private messagesProvider: AddonMessagesProvider,
private userProvider: CoreUserProvider, private translate: TranslateService, private utils: CoreUtilsProvider,
syncProvider: CoreSyncProvider) {
super('AddonMessagesSync', sitesProvider, loggerProvider, appProvider, syncProvider);
syncProvider: CoreSyncProvider, protected textUtils: CoreTextUtilsProvider) {
super('AddonMessagesSync', sitesProvider, loggerProvider, appProvider, syncProvider, textUtils);
}
/**

View File

@ -288,7 +288,7 @@ export class AddonModBookProvider {
return [];
}
return JSON.parse(contents[0].content);
return this.textUtils.parseJSON(contents[0].content, []);
}
/**

View File

@ -16,6 +16,7 @@ import { CoreSitesProvider } from '@providers/sites';
import { CoreSyncProvider } from '@providers/sync';
import { CoreLoggerProvider } from '@providers/logger';
import { CoreAppProvider } from '@providers/app';
import { CoreTextUtilsProvider } from '@providers/utils/text';
/**
* Base class to create sync providers. It provides some common functions.
@ -44,7 +45,8 @@ export class CoreSyncBaseProvider {
protected syncPromises: { [siteId: string]: { [uniqueId: string]: Promise<any> } } = {};
constructor(component: string, protected sitesProvider: CoreSitesProvider, protected loggerProvider: CoreLoggerProvider,
protected appProvider: CoreAppProvider, protected syncProvider: CoreSyncProvider) {
protected appProvider: CoreAppProvider, protected syncProvider: CoreSyncProvider,
protected textUtils: CoreTextUtilsProvider) {
this.logger = this.loggerProvider.getInstance(component);
this.component = component;
}
@ -115,11 +117,7 @@ export class CoreSyncBaseProvider {
*/
getSyncWarnings(id: string | number, siteId?: string): Promise<string[]> {
return this.syncProvider.getSyncRecord(this.component, id, siteId).then((entry) => {
try {
return JSON.parse(entry.warnings);
} catch (ex) {
return [];
}
return this.textUtils.parseJSON(entry.warnings, []);
}).catch(() => {
return [];
});

View File

@ -734,7 +734,7 @@ export class CoreSite {
const expires = (entry.expirationTime - now) / 1000;
this.logger.info(`Cached element found, id: ${id} expires in ${expires} seconds`);
return JSON.parse(entry.data);
return this.textUtils.parseJSON(entry.data, {});
}
return Promise.reject(null);

View File

@ -942,9 +942,8 @@ export class CoreLoginHelperProvider {
const params = url.split(':::');
return this.configProvider.get(CoreConstants.LOGIN_LAUNCH_DATA).then((data): any => {
try {
data = JSON.parse(data);
} catch (ex) {
data = this.textUtils.parseJSON(data, null);
if (data === null) {
return Promise.reject(null);
}

View File

@ -18,6 +18,7 @@ import { CoreLangProvider } from '@providers/lang';
import { CoreLoggerProvider } from '@providers/logger';
import { CoreSite } from '@classes/site';
import { CoreSitesProvider } from '@providers/sites';
import { CoreTextUtilsProvider } from '@providers/utils/text';
import { CoreUtilsProvider } from '@providers/utils/utils';
import { CoreSitePluginsProvider } from './siteplugins';
import { CoreCompileProvider } from '@core/compile/providers/compile';
@ -59,7 +60,8 @@ export class CoreSitePluginsHelperProvider {
private sitePluginsProvider: CoreSitePluginsProvider, private prefetchDelegate: CoreCourseModulePrefetchDelegate,
private compileProvider: CoreCompileProvider, private utils: CoreUtilsProvider,
private courseOptionsDelegate: CoreCourseOptionsDelegate, eventsProvider: CoreEventsProvider,
private courseFormatDelegate: CoreCourseFormatDelegate, private profileFieldDelegate: CoreUserProfileFieldDelegate) {
private courseFormatDelegate: CoreCourseFormatDelegate, private profileFieldDelegate: CoreUserProfileFieldDelegate,
private textUtils: CoreTextUtilsProvider) {
this.logger = logger.getInstance('CoreSitePluginsHelperProvider');
// Fetch the plugins on login.
@ -201,15 +203,12 @@ export class CoreSitePluginsHelperProvider {
isSitePluginEnabled(plugin: any, site: CoreSite): boolean {
if (!site.isFeatureDisabled('sitePlugin_' + plugin.component + '_' + plugin.addon) && plugin.handlers) {
// Site plugin not disabled. Check if it has handlers.
try {
if (!plugin.parsedHandlers) {
plugin.parsedHandlers = JSON.parse(plugin.handlers);
}
return !!(plugin.parsedHandlers && Object.keys(plugin.parsedHandlers).length);
} catch (ex) {
this.logger.warn('Error parsing site plugin', ex);
if (!plugin.parsedHandlers) {
plugin.parsedHandlers = this.textUtils.parseJSON(plugin.handlers, null,
this.logger.error.bind(this.logger, 'Error parsing site plugin handlers'));
}
return !!(plugin.parsedHandlers && Object.keys(plugin.parsedHandlers).length);
}
return false;
@ -243,25 +242,23 @@ export class CoreSitePluginsHelperProvider {
this.logger.debug('Load site plugin:', plugin);
try {
if (!plugin.parsedHandlers) {
plugin.parsedHandlers = JSON.parse(plugin.handlers);
}
if (!plugin.parsedLang && plugin.lang) {
plugin.parsedLang = JSON.parse(plugin.lang);
}
if (!plugin.parsedHandlers) {
plugin.parsedHandlers = this.textUtils.parseJSON(plugin.handlers, null,
this.logger.error.bind(this.logger, 'Error parsing site plugin handlers'));
}
if (!plugin.parsedLang && plugin.lang) {
plugin.parsedLang = this.textUtils.parseJSON(plugin.lang, null,
this.logger.error.bind(this.logger, 'Error parsing site plugin lang'));
}
this.sitePluginsProvider.hasSitePluginsLoaded = true;
this.sitePluginsProvider.hasSitePluginsLoaded = true;
// Register lang strings.
this.loadLangStrings(plugin);
// Register lang strings.
this.loadLangStrings(plugin);
// Register all the handlers.
for (const name in plugin.parsedHandlers) {
promises.push(this.registerHandler(plugin, name, plugin.parsedHandlers[name]));
}
} catch (ex) {
this.logger.warn('Error parsing site plugin', ex);
// Register all the handlers.
for (const name in plugin.parsedHandlers) {
promises.push(this.registerHandler(plugin, name, plugin.parsedHandlers[name]));
}
return this.utils.allPromises(promises);

View File

@ -20,6 +20,7 @@ import { CoreLangProvider } from '@providers/lang';
import { CoreLoggerProvider } from '@providers/logger';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreSitesProvider } from '@providers/sites';
import { CoreTextUtilsProvider } from '@providers/utils/text';
import { CoreUtilsProvider } from '@providers/utils/utils';
import { CoreConfigConstants } from '../../../configconstants';
import { CoreCoursesProvider } from '@core/courses/providers/courses';
@ -66,7 +67,8 @@ export class CoreSitePluginsProvider {
constructor(logger: CoreLoggerProvider, private sitesProvider: CoreSitesProvider, private utils: CoreUtilsProvider,
private langProvider: CoreLangProvider, private appProvider: CoreAppProvider, private platform: Platform,
private filepoolProvider: CoreFilepoolProvider, private coursesProvider: CoreCoursesProvider) {
private filepoolProvider: CoreFilepoolProvider, private coursesProvider: CoreCoursesProvider,
private textUtils: CoreTextUtilsProvider) {
this.logger = logger.getInstance('CoreUserProvider');
}
@ -215,11 +217,8 @@ export class CoreSitePluginsProvider {
return this.sitesProvider.getCurrentSite().read('tool_mobile_get_content', data, preSets);
}).then((result) => {
if (result.otherdata) {
try {
result.otherdata = JSON.parse(result.otherdata) || {};
} catch (ex) {
// Ignore errors.
}
result.otherdata = this.textUtils.parseJSON(result.otherdata, {},
this.logger.error.bind(this.logger, 'Error parsing get_content otherdata', method));
} else {
result.otherdata = {};
}

View File

@ -383,7 +383,7 @@ export class CoreFormatTextDirective implements OnChanges {
return;
}
const data = JSON.parse(video.getAttribute('data-setup') || video.getAttribute('data-setup-lazy') || '{}'),
const data = this.textUtils.parseJSON(video.getAttribute('data-setup') || video.getAttribute('data-setup-lazy') || '{}'),
youtubeId = data.techOrder && data.techOrder[0] && data.techOrder[0] == 'youtube' && data.sources && data.sources[0] &&
data.sources[0].src && this.youtubeGetId(data.sources[0].src);

View File

@ -2183,7 +2183,7 @@ export class CoreFilepoolProvider {
return Promise.reject(null);
}
// Convert the links to an object.
entry.links = JSON.parse(entry.links);
entry.links = this.textUtils.parseJSON(entry.links, []);
return entry;
});
@ -2421,7 +2421,7 @@ export class CoreFilepoolProvider {
return Promise.reject(this.ERR_QUEUE_IS_EMPTY);
}
// Convert the links to an object.
item.links = JSON.parse(item.links);
item.links = this.textUtils.parseJSON(item.links, []);
return this.processQueueItem(item);
}, () => {

View File

@ -19,6 +19,7 @@ import { CoreAppProvider } from './app';
import { CoreConfigProvider } from './config';
import { CoreLoggerProvider } from './logger';
import { CoreDomUtilsProvider } from './utils/dom';
import { CoreTextUtilsProvider } from './utils/text';
import { CoreUtilsProvider } from './utils/utils';
import { SQLiteDB } from '@classes/sqlitedb';
import { CoreConstants } from '@core/constants';
@ -112,7 +113,7 @@ export class CoreLocalNotificationsProvider {
constructor(logger: CoreLoggerProvider, private localNotifications: LocalNotifications, private platform: Platform,
private appProvider: CoreAppProvider, private utils: CoreUtilsProvider, private configProvider: CoreConfigProvider,
private domUtils: CoreDomUtilsProvider) {
private domUtils: CoreDomUtilsProvider, private textUtils: CoreTextUtilsProvider) {
this.logger = logger.getInstance('CoreLocalNotificationsProvider');
this.appDB = appProvider.getDB();
this.appDB.createTablesFromSchema(this.tablesSchema);
@ -151,7 +152,7 @@ export class CoreLocalNotificationsProvider {
scheduled.forEach((notif) => {
if (typeof notif.data == 'string') {
notif.data = JSON.parse(notif.data);
notif.data = this.textUtils.parseJSON(notif.data);
}
if (typeof notif.data == 'object' && notif.data.siteId === siteId) {
@ -403,7 +404,7 @@ export class CoreLocalNotificationsProvider {
notifications.forEach((notification) => {
// Convert some properties to the needed types.
notification.at = new Date(notification.at * 1000);
notification.data = notification.data ? JSON.parse(notification.data) : {};
notification.data = notification.data ? this.textUtils.parseJSON(notification.data, {}) : {};
promises.push(this.scheduleNotification(notification));
});

View File

@ -19,6 +19,7 @@ import { CoreAppProvider } from './app';
import { CoreEventsProvider } from './events';
import { CoreLoggerProvider } from './logger';
import { CoreSitesFactoryProvider } from './sites-factory';
import { CoreTextUtilsProvider } from './utils/text';
import { CoreUrlUtilsProvider } from './utils/url';
import { CoreUtilsProvider } from './utils/utils';
import { CoreConstants } from '@core/constants';
@ -211,7 +212,8 @@ export class CoreSitesProvider {
constructor(logger: CoreLoggerProvider, private http: HttpClient, private sitesFactory: CoreSitesFactoryProvider,
private appProvider: CoreAppProvider, private utils: CoreUtilsProvider, private translate: TranslateService,
private eventsProvider: CoreEventsProvider, private urlUtils: CoreUrlUtilsProvider) {
private eventsProvider: CoreEventsProvider, private urlUtils: CoreUrlUtilsProvider,
private textUtils: CoreTextUtilsProvider) {
this.logger = logger.getInstance('CoreSitesProvider');
this.appDB = appProvider.getDB();
@ -787,18 +789,9 @@ export class CoreSitesProvider {
info = entry.info,
config = entry.config;
// Try to parse info and config.
try {
info = info ? JSON.parse(info) : info;
} catch (ex) {
// Ignore errors.
}
try {
config = config ? JSON.parse(config) : config;
} catch (ex) {
// Ignore errors.
}
// Parse info and config.
info = info ? this.textUtils.parseJSON(info) : info;
config = config ? this.textUtils.parseJSON(config) : config;
site = this.sitesFactory.makeSite(entry.id, entry.siteUrl, entry.token,
info, entry.privateToken, config, entry.loggedOut == 1);
@ -862,21 +855,15 @@ export class CoreSitesProvider {
const formattedSites = [];
sites.forEach((site) => {
if (!ids || ids.indexOf(site.id) > -1) {
// Try to parse info.
let siteInfo = site.info;
try {
siteInfo = siteInfo ? JSON.parse(siteInfo) : siteInfo;
} catch (ex) {
// Ignore errors.
}
const basicInfo: CoreSiteBasicInfo = {
id: site.id,
siteUrl: site.siteUrl,
fullName: siteInfo && siteInfo.fullname,
siteName: siteInfo && siteInfo.sitename,
avatar: siteInfo && siteInfo.userpictureurl
};
// Parse info.
const siteInfo = site.info ? this.textUtils.parseJSON(site.info) : site.info,
basicInfo: CoreSiteBasicInfo = {
id: site.id,
siteUrl: site.siteUrl,
fullName: siteInfo && siteInfo.fullname,
siteName: siteInfo && siteInfo.sitename,
avatar: siteInfo && siteInfo.userpictureurl
};
formattedSites.push(basicInfo);
}
});

View File

@ -383,19 +383,25 @@ export class CoreTextUtilsProvider {
}
/**
* Same as Javascript's JSON.parse, but if an exception is thrown it will return the original text.
* Same as Javascript's JSON.parse, but it will handle errors.
*
* @param {string} json JSON text.
* @param {any} [defaultValue] Default value t oreturn if the parse fails. Defaults to the original value.
* @param {Function} [logErrorFn] An error to call with the exception to log the error. If not supplied, no error.
* @return {any} JSON parsed as object or what it gets.
*/
parseJSON(json: string): any {
parseJSON(json: string, defaultValue?: any, logErrorFn?: Function): any {
try {
return JSON.parse(json);
} catch (ex) {
// Error, use the json text.
// Error, log the error if needed.
if (logErrorFn) {
logErrorFn(ex);
}
}
return json;
// Error parsing, return the default value or the original value.
return typeof defaultValue != 'undefined' ? defaultValue : json;
}
/**

View File

@ -682,11 +682,7 @@ export class CoreWSProvider {
}
// Treat response.
try {
data = JSON.parse(data);
} catch (ex) {
// Ignore errors.
}
data = this.textUtils.parseJSON(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.
@ -750,12 +746,9 @@ export class CoreWSProvider {
};
return transfer.upload(filePath, uploadUrl, options, true).then((success) => {
let data: any = success.response;
try {
data = JSON.parse(data);
} catch (err) {
this.logger.error('Error parsing response from upload:', err, data);
const data = this.textUtils.parseJSON(success.response, null,
this.logger.error.bind(this.logger, 'Error parsing response from upload'));
if (data === null) {
return Promise.reject(this.translate.instant('core.errorinvalidresponse'));
}