dynamicsmobile
Version:
Allows development of off-line mobile and web business apps over the Dynamics Mobile platform. More info on https://www.dynamicsmobile.com
189 lines • 8.71 kB
JavaScript
;
/* eslint-disable @typescript-eslint/no-this-alias */
Object.defineProperty(exports, "__esModule", { value: true });
exports.PwaAppService = void 0;
const tslib_1 = require("tslib");
const dms_root_container_1 = require("../ioc/dms-root-container");
const dms_ioc_1 = require("../ioc/dms-ioc");
const userinterface_service_1 = require("../lib-core/userinterface-service");
const application_context_service_1 = require("../lib-core/application-context-service");
const livelink_query_service_1 = require("../lib-core/livelink-query-service");
let PwaAppService = exports.PwaAppService = class PwaAppService {
constructor() {
// Initialize deferredPrompt for use later to show browser install prompt.
this.deferredPrompt = null;
this.refreshing = false;
}
getPWADisplayMode() {
const appInstalled = localStorage ? localStorage.getItem('appInstalled') : 'false';
if (appInstalled == 'true')
return 'standalone';
const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
if (document.referrer.startsWith('android-app://')) {
return 'pwa';
}
else if (navigator.standalone || isStandalone) {
return 'standalone';
}
return 'browser';
}
invokeServiceWorkerUpdateFlow(registration) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const ui = dms_root_container_1.RootDIContainer.inject(userinterface_service_1.UserInterfaceService);
const refeshPrompt = yield ui.confirm("New version of the app is available. Refresh now?");
if (refeshPrompt) {
if (registration.waiting) {
// let waiting Service Worker know it should became active
registration.waiting.postMessage('SKIP_WAITING');
}
}
});
}
registerServiceWorker() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const me = this;
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/service-worker.js")
.then(function (registration) {
window.pwa = registration;
})
.catch(function (error) {
//console.log('Service worker registration failed, error:', error);
});
}
var page_start_time = performance.now();
if (navigator && navigator.serviceWorker) {
navigator.serviceWorker.addEventListener("controllerchange", function () {
// Prompt the user to refresh instead
//$("#refreshpwa").show();
});
}
var nhours = 1 * 60 * 60 * 1000;
setInterval(() => {
if (window.pwa && window.pwa.update) {
window.pwa.update();
}
}, nhours);
// detect controller change and refresh the page
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (!me.refreshing) {
window.location.reload();
me.refreshing = true;
}
});
});
}
showInstallPromotion() {
const me = this;
const dms = dms_root_container_1.RootDIContainer.inject(application_context_service_1.DmsApplicationService);
//wait a bit for the app to complete the loading
if (dms.app.device.android) {
if (localStorage.getItem('supressinstallpromotion') != 'true') {
const dialog = dms.app.dialog.create({
content: `<div>Install this app on your device and use it as any other app?<br/></div><hr/>`,
buttons: [{
text: "Install",
bold: true,
close: true,
onClick: () => tslib_1.__awaiter(this, void 0, void 0, function* () {
// Show the install prompt
me.deferredPrompt.prompt();
// Wait for the user to respond to the prompt
const { outcome } = yield me.deferredPrompt.userChoice;
localStorage.setItem('appInstalled', 'true');
// Optionally, send analytics event with outcome of user choice
//console.log(`User response to the install prompt: ${outcome}`);
// We've used the prompt, and can't use it again, throw it away
me.deferredPrompt = null;
})
},
{
text: "Cancel",
bold: false,
close: true,
onClick: () => {
//just closing the dialog
}
},
{
text: "Never",
bold: false,
close: true,
cssClass: 'color-red',
onClick: () => {
localStorage.setItem('supressinstallpromotion', 'true');
}
}
]
});
dialog.open();
}
}
}
hideInstallPromotion() {
//$('#installPromotion').hide();
}
jwtDecode(token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
isJwtExpired(token) {
const decoded = this.jwtDecode(token);
const now = new Date();
const exp = new Date(decoded.exp * 1000);
return now > exp;
}
enablePwaApp() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (window.location.href.indexOf('app.dynamicsmobile.com') < 0) {
return;
}
//check if the jwt token is expired
const jwt = livelink_query_service_1.LiveLinkQuery.getAuthroizationToken();
if (this.isJwtExpired(jwt)) {
const ui = dms_root_container_1.RootDIContainer.inject(userinterface_service_1.UserInterfaceService);
const dms = dms_root_container_1.RootDIContainer.inject(application_context_service_1.DmsApplicationService);
const appArea = yield ui.getApparea();
const app = dms.appCode;
const url = `${window.location.protocol}//${window.location.host}${(window.location.port && window.location.port != '443' && window.location.port != '80') ? (':' + window.location.port) : ''}/loginsuccess.html?app=${app}&appArea=${appArea}&returnUrl=${window.location.href}`;
window.location.assign(url);
return;
}
//install the service worker
const me = this;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent the mini-infobar from appearing on mobile
e.preventDefault();
// Stash the event so it can be triggered later.
me.deferredPrompt = e;
// Update UI notify the user they can install the PWA
me.showInstallPromotion();
});
window.addEventListener('appinstalled', () => {
// Hide the app-provided install promotion
me.hideInstallPromotion();
// Clear the deferredPrompt so it can be garbage collected
me.deferredPrompt = null;
});
//authenticated
if (me.getPWADisplayMode() == 'browser') {
//setTimeout(() => {
me.showInstallPromotion();
//}, 1000 );
}
else {
me.hideInstallPromotion();
}
yield me.registerServiceWorker();
});
}
};
exports.PwaAppService = PwaAppService = tslib_1.__decorate([
(0, dms_ioc_1.Service)()
], PwaAppService);
//# sourceMappingURL=mobile-pwa-app-service.js.map