-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathezpush-client.js
1 lines (1 loc) · 6.2 KB
/
ezpush-client.js
1
var EzPush={};!function(window){"use strict";function loadSettings(){return new Promise(function(resolve,reject){var request=new XMLHttpRequest;request.open("GET","./ezpush.json",!0),request.send(null),request.onreadystatechange=function(){if(4===request.readyState)if(200===request.status){try{var data=JSON.parse(request.responseText)}catch(e){reject("Error while reading ezpush.json\n"+e)}EzPush.vapidKey=data.vapidKey,EzPush.apiKey=data.apiKey,EzPush.appId=data.appId,EzPush.hostPort=data.hostPort,EzPush.hostSSL=data.hostSSL,EzPush.hostUrl="http"+(EzPush.hostSSL?"s":"")+"://"+data.hostUrl+":"+EzPush.hostPort,resolve()}else reject("Error while reading ezpush.json")},request.ontimeout=function(){reject("Error while reading ezpush.json")}})}function initSubscription(){"serviceWorker"in window.navigator?window.navigator.serviceWorker.register("./sw.js").then(function(){checkWorkerToErrors().then(function(){initialiseState()},function(err){EzPush.warn(err)})},function(err){EzPush.warn(err)}):EzPush.warn("Service workers aren't supported in this browser.")}function checkWorkerToErrors(){return new Promise(function(resolve,reject){return"showNotification"in window.ServiceWorkerRegistration.prototype?"denied"===window.Notification.permission?void reject("The user has blocked notifications."):"PushManager"in window?void resolve():void reject("Push messaging isn't supported."):void reject("Notifications aren't supported.")})}function initialiseState(){window.navigator.serviceWorker.ready.then(function(serviceWorkerRegistration){serviceWorkerRegistration.pushManager.getSubscription().then(function(subscription){subscription?(EzPush.log("Subscription is ok."),sendSubscriptionToServer(subscription)):(EzPush.log("Subscription is in process."),subscribe())}).catch(function(err){EzPush.warn("Error during getSubscription(). "+err)})})}function urlBase64ToUint8Array(base64String){for(var padding="=".repeat((4-base64String.length%4)%4),base64=(base64String+padding).replace(/\-/g,"+").replace(/_/g,"/"),rawData=window.atob(base64),outputArray=new Uint8Array(rawData.length),i=0;i<rawData.length;++i)outputArray[i]=rawData.charCodeAt(i);return outputArray}function subscribe(){urlBase64ToUint8Array(EzPush.vapidKey);window.navigator.serviceWorker.ready.then(function(serviceWorkerRegistration){serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly:!0}).then(function(subscription){return sendSubscriptionToServer(subscription)}).catch(function(err){"denied"===window.Notification.permission?EzPush.warn("Permission for Notifications was denied"):EzPush.warn("Unable to subscribe to push. "+err)})})}function sendSubscriptionToServer(subscription){if(subscription.subscriptionId)EzPush.subscriptionId=subscription.subscriptionId;else{var endpointSections=subscription.endpoint.split("/");EzPush.subscriptionId=endpointSections[endpointSections.length-1]}var keys=JSON.parse(JSON.stringify(subscription)).keys||null;registerDevice(keys,subscription.endpoint)}function registerDevice(keys,endpoint){var registerDeviceRequest={qualifier:"pt.openapi.push.devreg/registerDevice/1.0",contextId:EzPush.contextId,data:{_id:{hwid:EzPush.subscriptionId,applicationId:EzPush.appId},endpoint:endpoint,pushToken:EzPush.subscriptionId,auth:keys&&keys.auth||"",p256dh:keys&&keys.p256dh||"",language:window.navigator.language&&window.navigator.language.substr(0,2)||"en",platform:EzPush.chromePlatformCode,timeZone:(new Date).getTimezoneOffset()}};sendJsonBySocket(registerDeviceRequest)}function createContext(){var createContextRequest={qualifier:"pt.openapi.context/createContextRequest",data:{properties:null}};sendJsonBySocket(createContextRequest)}function connectSocket(){try{EzPush.socket=io.connect(EzPush.hostUrl)}catch(err){EzPush.warn("Can't connect to EzPush Server: "+err)}}function addSocketEventListeners(){EzPush.socket.on("connect",function(){EzPush.log("Socket Connected"),EzPush.contextId||createContext()}),EzPush.socket.on("message",function(data){EzPush.log("Get: "+data),data=window.JSON.parse(data),"pt.openapi.context/createContextResponse"===data.qualifier&&(EzPush.contextId=data.data.contextId,initSubscription()),"pt.openapi.push.devreg/registerDeviceResponse"===data.qualifier&&EzPush.socket.disconnect()})}function sendJsonBySocket(json){EzPush.log("Send: "+window.JSON.stringify(json)),EzPush.socket.send(window.JSON.stringify(json))}function setUserAlias(alias){var updateUserId={qualifier:"pt.openapi.push.devreg/updateUserId",contextId:EzPush.contextId,data:{deviceRegistrationId:{hwid:EzPush.subscriptionId,applicationId:EzPush.appId},userIdentity:alias}};return EzPush.subscriptionId?alias?EzPush.appId?void sendJsonBySocket(updateUserId):void EzPush.warn("Id is absent"):void EzPush.warn("User alias is absent"):void EzPush.warn("Please, init push service!")}function updateUserTags(arr){var updateTags={qualifier:"pt.openapi.push.devreg/updateTags",contextId:EzPush.contextId,data:{deviceRegistrationId:{hwid:EzPush.subscriptionId,applicationId:EzPush.appId},tags:arr}};return EzPush.subscriptionId?EzPush.appId?Array.isArray(arr)&&0!==arr.length?void sendJsonBySocket(updateTags):void EzPush.warn("Users tags array is absent or empty!"):void EzPush.warn("Id is absent"):void EzPush.warn("Please, init push service!")}function updateLocation(){var updateLocation={qualifier:"pt.openapi.push.devreg/updateLocation",contextId:EzPush.contextId,data:{hwid:EzPush.subscriptionId,longitude:"",latitude:""}};return EzPush.subscriptionId?navigator.geolocation?void navigator.geolocation.getCurrentPosition(function(pos){updateLocation.data.longitude=pos.coords.longitude,updateLocation.data.latitude=pos.coords.latitude,sendJsonBySocket(updateLocation)},function(error){ezPush.warn(error)}):void EzPush.warn("Your browser does not support geolocation. Please update it."):void EzPush.warn("Please, init push service!")}EzPush={version:"16.9.3",logEnabled:!0,apiKey:null,appId:null,hostUrl:null,hostPort:null,hostSSL:null,chromePlatformCode:4,socket:{},contextId:"",vapidKey:"",log:function(msg){EzPush.logEnabled&&console.log(msg)},warn:function(msg){EzPush.logEnabled&&console.warn(msg)},init:function(){loadSettings().then(function(){connectSocket(),addSocketEventListeners()},function(err){EzPush.warn(err)})},setUserAlias:setUserAlias,updateUserTags:updateUserTags,updateLocation:updateLocation}}(window);