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

View File

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

View File

@ -734,7 +734,7 @@ export class CoreSite {
const expires = (entry.expirationTime - now) / 1000; const expires = (entry.expirationTime - now) / 1000;
this.logger.info(`Cached element found, id: ${id} expires in ${expires} seconds`); 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); return Promise.reject(null);

View File

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

View File

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

View File

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

View File

@ -383,7 +383,7 @@ export class CoreFormatTextDirective implements OnChanges {
return; 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] && 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); data.sources[0].src && this.youtubeGetId(data.sources[0].src);

View File

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

View File

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

View File

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

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 {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. * @return {any} JSON parsed as object or what it gets.
*/ */
parseJSON(json: string): any { parseJSON(json: string, defaultValue?: any, logErrorFn?: Function): any {
try { try {
return JSON.parse(json); return JSON.parse(json);
} catch (ex) { } 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. // Treat response.
try { data = this.textUtils.parseJSON(data);
data = JSON.parse(data);
} catch (ex) {
// Ignore errors.
}
// Some moodle web services return null. // 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. // 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) => { return transfer.upload(filePath, uploadUrl, options, true).then((success) => {
let data: any = success.response; const data = this.textUtils.parseJSON(success.response, null,
try { this.logger.error.bind(this.logger, 'Error parsing response from upload'));
data = JSON.parse(data); if (data === null) {
} catch (err) {
this.logger.error('Error parsing response from upload:', err, data);
return Promise.reject(this.translate.instant('core.errorinvalidresponse')); return Promise.reject(this.translate.instant('core.errorinvalidresponse'));
} }