MOBILE-3902 airnotifier: Use is_system_configured WS

main
Dani Palou 2022-01-31 15:55:57 +01:00
parent f07d087947
commit 9d40a6d2af
7 changed files with 124 additions and 98 deletions

View File

@ -234,6 +234,7 @@
"addon.coursecompletion.status": "moodle", "addon.coursecompletion.status": "moodle",
"addon.coursecompletion.viewcoursereport": "completion", "addon.coursecompletion.viewcoursereport": "completion",
"addon.messageoutput_airnotifier.processorsettingsdesc": "local_moodlemobileapp", "addon.messageoutput_airnotifier.processorsettingsdesc": "local_moodlemobileapp",
"addon.messageoutput_airnotifier.pushdisabledwarning": "local_moodlemobileapp",
"addon.messages.acceptandaddcontact": "message", "addon.messages.acceptandaddcontact": "message",
"addon.messages.addcontact": "message", "addon.messages.addcontact": "message",
"addon.messages.addcontactconfirm": "message", "addon.messages.addcontactconfirm": "message",
@ -1087,7 +1088,6 @@
"addon.notifications.notificationpreferences": "message", "addon.notifications.notificationpreferences": "message",
"addon.notifications.notifications": "local_moodlemobileapp", "addon.notifications.notifications": "local_moodlemobileapp",
"addon.notifications.playsound": "local_moodlemobileapp", "addon.notifications.playsound": "local_moodlemobileapp",
"addon.notifications.pushdisabledwarning": "local_moodlemobileapp",
"addon.notifications.therearentnotificationsyet": "local_moodlemobileapp", "addon.notifications.therearentnotificationsyet": "local_moodlemobileapp",
"addon.notifications.unreadnotification": "message", "addon.notifications.unreadnotification": "message",
"addon.privatefiles.couldnotloadfiles": "local_moodlemobileapp", "addon.privatefiles.couldnotloadfiles": "local_moodlemobileapp",
@ -2332,8 +2332,8 @@
"core.userdeleted": "moodle", "core.userdeleted": "moodle",
"core.userdetails": "moodle", "core.userdetails": "moodle",
"core.usernotfullysetup": "error", "core.usernotfullysetup": "error",
"core.usersuspended": "moodle",
"core.users": "moodle", "core.users": "moodle",
"core.usersuspended": "tool_reportbuilder",
"core.view": "moodle", "core.view": "moodle",
"core.viewcode": "local_moodlemobileapp", "core.viewcode": "local_moodlemobileapp",
"core.vieweditor": "local_moodlemobileapp", "core.vieweditor": "local_moodlemobileapp",

View File

@ -21,6 +21,7 @@ import {
AddonMessageOutputAirnotifierHandler, AddonMessageOutputAirnotifierHandler,
AddonMessageOutputAirnotifierHandlerService, AddonMessageOutputAirnotifierHandlerService,
} from './services/handlers/messageoutput'; } from './services/handlers/messageoutput';
import { AddonMessageOutputAirnotifier } from './services/airnotifier';
const routes: Routes = [ const routes: Routes = [
{ {
@ -41,6 +42,7 @@ const routes: Routes = [
multi: true, multi: true,
useValue: () => { useValue: () => {
AddonMessageOutputDelegate.registerHandler(AddonMessageOutputAirnotifierHandler.instance); AddonMessageOutputDelegate.registerHandler(AddonMessageOutputAirnotifierHandler.instance);
AddonMessageOutputAirnotifier.initialize();
}, },
}, },
], ],

View File

@ -1,3 +1,4 @@
{ {
"processorsettingsdesc": "Configure devices" "processorsettingsdesc": "Configure devices",
} "pushdisabledwarning": "Your users are not receiving any notification from this site on their mobile devices. Enable mobile notifications in the Notification settings page."
}

View File

@ -14,14 +14,17 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { CoreSites } from '@services/sites'; import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreWSExternalWarning } from '@services/ws'; import { CoreWSExternalWarning } from '@services/ws';
import { CoreConstants } from '@/core/constants'; import { CoreConstants } from '@/core/constants';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreError } from '@classes/errors/error'; import { CoreError } from '@classes/errors/error';
import { CoreWSError } from '@classes/errors/wserror'; import { CoreWSError } from '@classes/errors/wserror';
import { makeSingleton } from '@singletons'; import { makeSingleton, Translate } from '@singletons';
import { CoreEvents, CoreEventSiteData } from '@singletons/events'; import { CoreEvents, CoreEventSiteData } from '@singletons/events';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
const ROOT_CACHE_KEY = 'mmaMessageOutputAirnotifier:'; const ROOT_CACHE_KEY = 'mmaMessageOutputAirnotifier:';
@ -31,11 +34,18 @@ const ROOT_CACHE_KEY = 'mmaMessageOutputAirnotifier:';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class AddonMessageOutputAirnotifierProvider { export class AddonMessageOutputAirnotifierProvider {
constructor() { /**
* Initialize.
*/
initialize(): void {
CoreEvents.on(CoreEvents.DEVICE_REGISTERED_IN_MOODLE, async (data: CoreEventSiteData) => { CoreEvents.on(CoreEvents.DEVICE_REGISTERED_IN_MOODLE, async (data: CoreEventSiteData) => {
// Get user devices to make Moodle send the devices data to Airnotifier. // Get user devices to make Moodle send the devices data to Airnotifier.
this.getUserDevices(true, data.siteId); this.getUserDevices(true, data.siteId);
}); });
CoreEvents.on(CoreEvents.LOGIN, (data) => {
this.warnPushDisabledForAdmin(data.siteId);
});
} }
/** /**
@ -71,6 +81,35 @@ export class AddonMessageOutputAirnotifierProvider {
throw new CoreError('Error enabling device'); throw new CoreError('Error enabling device');
} }
/**
* Get the cache key for the is system configured call.
*
* @return Cache key.
*/
protected getSystemConfiguredCacheKey(): string {
return ROOT_CACHE_KEY + 'isAirnotifierConfigured';
}
/**
* Check if airnotifier is configured.
*
* @param options Options.
* @return Promise resolved with boolean: whether it's configured.
*/
async isSystemConfigured(options: CoreSitesCommonWSOptions = {}): Promise<boolean> {
const site = await CoreSites.getSite(options.siteId);
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getSystemConfiguredCacheKey(),
updateFrequency: CoreSite.FREQUENCY_RARELY,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const result = await site.read<number>('message_airnotifier_is_system_configured', {}, preSets);
return result === 1;
}
/** /**
* Get the cache key for the get user devices call. * Get the cache key for the get user devices call.
* *
@ -125,6 +164,78 @@ export class AddonMessageOutputAirnotifierProvider {
return site.invalidateWsCacheForKey(this.getUserDevicesCacheKey()); return site.invalidateWsCacheForKey(this.getUserDevicesCacheKey());
} }
/**
* Is user is an admin and push are disabled, notify him.
*
* @param siteId Site ID.
* @return Promise resolved when done.
*/
protected async warnPushDisabledForAdmin(siteId?: string): Promise<void> {
if (!siteId) {
return;
}
try {
const site = await CoreSites.getSite(siteId);
if (!site.getInfo()?.userissiteadmin) {
// Not an admin or we don't know, stop.
return;
}
// Check if the admin already asked not to be reminded.
const dontAsk = await site.getLocalSiteConfig('AddonMessageOutputAirnotifierDontRemindDisabled', 0);
if (dontAsk) {
return;
}
// Check if airnotifier is configured.
const isConfigured = await this.isSystemConfigured({
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
if (isConfigured) {
return;
}
// Warn the admin.
const dontShowAgain = await CoreDomUtils.showPrompt(
Translate.instant('addon.messageoutput_airnotifier.pushdisabledwarning'),
undefined,
Translate.instant('core.dontshowagain'),
'checkbox',
[
{
text: Translate.instant('core.ok'),
},
{
text: Translate.instant('core.goto', { $a: Translate.instant('core.settings.settings') }),
handler: (data, resolve) => {
resolve(data[0]);
const url = CoreTextUtils.concatenatePaths(
site.getURL(),
site.isVersionGreaterEqualThan('3.11') ?
'message/output/airnotifier/checkconfiguration.php' :
'admin/message.php',
);
// Don't try auto-login, admins cannot use it.
CoreUtils.openInBrowser(url);
},
},
],
);
if (dontShowAgain) {
await site.setLocalSiteConfig('AddonMessageOutputAirnotifierDontRemindDisabled', 1);
}
} catch {
// Ignore errors.
}
}
} }
export const AddonMessageOutputAirnotifier = makeSingleton(AddonMessageOutputAirnotifierProvider); export const AddonMessageOutputAirnotifier = makeSingleton(AddonMessageOutputAirnotifierProvider);

View File

@ -4,7 +4,6 @@
"notificationpreferences": "Notification preferences", "notificationpreferences": "Notification preferences",
"notifications": "Notifications", "notifications": "Notifications",
"playsound": "Play sound", "playsound": "Play sound",
"pushdisabledwarning": "Your users are not receiving any notification from this site on their mobile devices. Enable mobile notifications in the Notification settings page.",
"therearentnotificationsyet": "There are no notifications.", "therearentnotificationsyet": "There are no notifications.",
"unreadnotification": "Unread notification: {{$a}}" "unreadnotification": "Unread notification: {{$a}}"
} }

View File

@ -26,7 +26,7 @@ import { AddonNotificationsCronHandler } from './services/handlers/cron';
import { AddonNotificationsPushClickHandler } from './services/handlers/push-click'; import { AddonNotificationsPushClickHandler } from './services/handlers/push-click';
import { AddonNotificationsSettingsHandler, AddonNotificationsSettingsHandlerService } from './services/handlers/settings'; import { AddonNotificationsSettingsHandler, AddonNotificationsSettingsHandlerService } from './services/handlers/settings';
import { CoreSitePreferencesRoutingModule } from '@features/settings/pages/site/site-routing'; import { CoreSitePreferencesRoutingModule } from '@features/settings/pages/site/site-routing';
import { AddonNotifications, AddonNotificationsProvider } from './services/notifications'; import { AddonNotificationsProvider } from './services/notifications';
import { AddonNotificationsHelperProvider } from './services/notifications-helper'; import { AddonNotificationsHelperProvider } from './services/notifications-helper';
export const ADDON_NOTIFICATIONS_SERVICES: Type<unknown>[] = [ export const ADDON_NOTIFICATIONS_SERVICES: Type<unknown>[] = [
@ -65,7 +65,6 @@ const preferencesRoutes: Routes = [
CoreSettingsDelegate.registerHandler(AddonNotificationsSettingsHandler.instance); CoreSettingsDelegate.registerHandler(AddonNotificationsSettingsHandler.instance);
AddonNotificationsMainMenuHandler.initialize(); AddonNotificationsMainMenuHandler.initialize();
AddonNotifications.initialize();
}, },
}, },
], ],

View File

@ -14,18 +14,15 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites'; import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites';
import { CoreWSExternalWarning } from '@services/ws'; import { CoreWSExternalWarning } from '@services/ws';
import { CoreTextUtils } from '@services/utils/text'; import { CoreTextUtils } from '@services/utils/text';
import { CoreTimeUtils } from '@services/utils/time'; import { CoreTimeUtils } from '@services/utils/time';
import { CoreUser } from '@features/user/services/user'; import { CoreUser } from '@features/user/services/user';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreLogger } from '@singletons/logger'; import { CoreLogger } from '@singletons/logger';
import { makeSingleton, Translate } from '@singletons'; import { makeSingleton } from '@singletons';
import { CoreCourseModuleDelegate } from '@features/course/services/module-delegate'; import { CoreCourseModuleDelegate } from '@features/course/services/module-delegate';
import { CoreEvents } from '@singletons/events';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreUtils } from '@services/utils/utils';
const ROOT_CACHE_KEY = 'mmaNotifications:'; const ROOT_CACHE_KEY = 'mmaNotifications:';
@ -46,15 +43,6 @@ export class AddonNotificationsProvider {
this.logger = CoreLogger.getInstance('AddonNotificationsProvider'); this.logger = CoreLogger.getInstance('AddonNotificationsProvider');
} }
/**
* Initialize the service.
*/
initialize(): void {
CoreEvents.on(CoreEvents.LOGIN, (data) => {
this.warnPushDisabledForAdmin(data.siteId);
});
}
/** /**
* Function to format notification data. * Function to format notification data.
* *
@ -395,80 +383,6 @@ export class AddonNotificationsProvider {
await site.invalidateWsCacheForKey(this.getNotificationsCacheKey()); await site.invalidateWsCacheForKey(this.getNotificationsCacheKey());
} }
/**
* Is user is an admin and push are disabled, notify him.
*
* @param siteId Site ID.
* @return Promise resolved when done.
*/
protected async warnPushDisabledForAdmin(siteId?: string): Promise<void> {
if (!siteId) {
return;
}
try {
const site = await CoreSites.getSite(siteId);
if (!site.getInfo()?.userissiteadmin) {
// Not an admin or we don't know, stop.
return;
}
// Check if the admin already asked not to be reminded.
const dontAsk = await site.getLocalSiteConfig('AddonNotificationsDontRemindPushDisabled', 0);
if (dontAsk) {
return;
}
// Check if push are disabled.
const preferences = await this.getNotificationPreferences({
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
const processor = preferences.processors.find(processor => processor.name === 'airnotifier');
if (processor) {
// Enabled.
return;
}
// Warn the admin.
const dontShowAgain = await CoreDomUtils.showPrompt(
Translate.instant('addon.notifications.pushdisabledwarning'),
undefined,
Translate.instant('core.dontshowagain'),
'checkbox',
[
{
text: Translate.instant('core.ok'),
},
{
text: Translate.instant('core.goto', { $a: Translate.instant('core.settings.settings') }),
handler: (data, resolve) => {
resolve(data[0]);
const url = CoreTextUtils.concatenatePaths(
site.getURL(),
site.isVersionGreaterEqualThan('3.11') ?
'message/output/airnotifier/checkconfiguration.php' :
'admin/message.php',
);
// Don't try auto-login, admins cannot use it.
CoreUtils.openInBrowser(url);
},
},
],
);
if (dontShowAgain) {
await site.setLocalSiteConfig('AddonNotificationsDontRemindPushDisabled', 1);
}
} catch {
// Ignore errors.
}
}
} }
export const AddonNotifications = makeSingleton(AddonNotificationsProvider); export const AddonNotifications = makeSingleton(AddonNotificationsProvider);