PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/cartridges/int_push/cartridge/static/default/js/main.js

https://gitlab.com/zautre/dw-push
JavaScript | 463 lines | 347 code | 44 blank | 72 comment | 65 complexity | 6c0640a09b00ee999317e500c3db8c2a MD5 | raw file
  1. 'use strict';
  2. var API_KEY = gcmAPIKey;
  3. var isPushEnabled = false;
  4. // This method handles the removal of subscriptionId
  5. // in Chrome 44 by concatenating the subscription Id
  6. // to the subscription endpoint
  7. function endpointWorkaround(pushSubscription)
  8. {
  9. // Make sure we only mess with GCM
  10. if (pushSubscription.endpoint.indexOf('https://android.googleapis.com/gcm/send') !== 0)
  11. {
  12. return pushSubscription.endpoint;
  13. }
  14. var mergedEndpoint = pushSubscription.endpoint;
  15. // Chrome 42 + 43 will not have the subscriptionId attached
  16. // to the endpoint.
  17. if (pushSubscription.subscriptionId &&
  18. pushSubscription.endpoint.indexOf(pushSubscription.subscriptionId) === -1)
  19. {
  20. // Handle version 42 where you have separate subId and Endpoint
  21. mergedEndpoint = pushSubscription.endpoint + '/' +
  22. pushSubscription.subscriptionId;
  23. }
  24. return mergedEndpoint;
  25. }
  26. function sendSubscriptionToServer(subscription)
  27. {
  28. var xmlDoc = getXmlDoc();
  29. xmlDoc.open('POST', subscribeURL, true);
  30. xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  31. var subscriptionJSON = JSON.parse(JSON.stringify(subscription));
  32. var browser = detectBrowser();
  33. xmlDoc.send("endpoint=" + subscriptionJSON.endpoint + "&" + "p256dh=" + subscriptionJSON.keys.p256dh + "&" + "auth=" + subscriptionJSON.keys.auth + "&" + "browser=" + browser);
  34. xmlDoc.onreadystatechange = function ()
  35. {
  36. if (xmlDoc.readyState === XMLHttpRequest.DONE && xmlDoc.status === 200)
  37. {
  38. console.log('Successfuly sent subscription object to DW server ');
  39. }
  40. else
  41. {
  42. console.log('DW server response code not 200');
  43. }
  44. }
  45. // For compatibly of Chrome 43, get the endpoint via
  46. // endpointWorkaround(subscription)
  47. var mergedEndpoint = endpointWorkaround(subscription);
  48. }
  49. function sendUnSubscriptionToServer(subscription)
  50. {
  51. var xmlDoc = getXmlDoc();
  52. xmlDoc.open('POST', unSubscribeURL, true);
  53. xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  54. var subscriptionJSON = JSON.parse(JSON.stringify(subscription));
  55. var browser = detectBrowser();
  56. xmlDoc.send("endpoint=" + subscriptionJSON.endpoint + "&" + "p256dh=" + subscriptionJSON.keys.p256dh + "&" + "auth=" + subscriptionJSON.keys.auth + "&" + "browser=" + browser);
  57. xmlDoc.onreadystatechange = function ()
  58. {
  59. if (xmlDoc.readyState === XMLHttpRequest.DONE && xmlDoc.status === 200)
  60. {
  61. console.log('Successfuly sent un subscription object to DW server ');
  62. }
  63. else
  64. {
  65. console.log('DW server response code not 200');
  66. }
  67. }
  68. // For compatibly of Chrome 43, get the endpoint via
  69. // endpointWorkaround(subscription)
  70. var mergedEndpoint = endpointWorkaround(subscription);
  71. }
  72. function unsubscribe()
  73. {
  74. var pushButton = document.querySelector('.js-push-button');
  75. pushButton.disabled = true;
  76. navigator.serviceWorker.ready.then(function (serviceWorkerRegistration)
  77. {
  78. // To unsubscribe from push messaging, you need get the
  79. // subcription object, which you can call unsubscribe() on.
  80. serviceWorkerRegistration.pushManager.getSubscription().then(
  81. function (pushSubscription)
  82. {
  83. // Check we have a subscription to unsubscribe
  84. if (!pushSubscription)
  85. {
  86. // No subscription object, so set the state
  87. // to allow the user to subscribe to push
  88. isPushEnabled = false;
  89. pushButton.disabled = false;
  90. pushButton.textContent = 'Enable Push Messages';
  91. return;
  92. }
  93. sendUnSubscriptionToServer(pushSubscription);
  94. // We have a subcription, so call unsubscribe on it
  95. pushSubscription.unsubscribe().then(function ()
  96. {
  97. pushButton.disabled = false;
  98. pushButton.textContent = 'Enable Push Messages';
  99. isPushEnabled = false;
  100. }).catch(function (e)
  101. {
  102. // We failed to unsubscribe, this can lead to
  103. // an unusual state, so may be best to remove
  104. // the subscription id from your data store and
  105. // inform the user that you disabled push
  106. window.Demo.debug.log('Unsubscription error: ', e);
  107. pushButton.disabled = false;
  108. });
  109. }).catch(function (e)
  110. {
  111. window.Demo.debug.log('Error thrown while unsubscribing from ' +
  112. 'push messaging.', e);
  113. });
  114. });
  115. }
  116. function urlBase64ToUint8Array(base64String)
  117. {
  118. const padding = '='.repeat((4 - base64String.length % 4) % 4);
  119. const base64 = (base64String + padding)
  120. .replace(/\-/g, '+')
  121. .replace(/_/g, '/');
  122. const rawData = window.atob(base64);
  123. const outputArray = new Uint8Array(rawData.length);
  124. for (let i = 0; i < rawData.length; ++i)
  125. {
  126. outputArray[i] = rawData.charCodeAt(i);
  127. }
  128. return outputArray;
  129. }
  130. function subscribe()
  131. {
  132. // Disable the button so it can't be changed while
  133. // we process the permission request
  134. var pushButton = document.querySelector('.js-push-button');
  135. pushButton.disabled = true;
  136. navigator.serviceWorker.ready.then(function (serviceWorkerRegistration)
  137. {
  138. serviceWorkerRegistration.pushManager.subscribe(
  139. {
  140. userVisibleOnly: true,
  141. applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
  142. }).then(function (subscription)
  143. {
  144. // The subscription was successful
  145. isPushEnabled = true;
  146. pushButton.textContent = 'Disable Push Messages';
  147. pushButton.disabled = false;
  148. // TODO: Send the subscription subscription.endpoint
  149. // to your server and save it to send a push message
  150. // at a later date
  151. return sendSubscriptionToServer(subscription);
  152. })
  153. .catch(function (e)
  154. {
  155. if (Notification.permission === 'denied')
  156. {
  157. // The user denied the notification permission which
  158. // means we failed to subscribe and the user will need
  159. // to manually change the notification permission to
  160. // subscribe to push messages
  161. window.Demo.debug.log('Permission for Notifications was denied');
  162. pushButton.disabled = true;
  163. }
  164. else
  165. {
  166. // A problem occurred with the subscription, this can
  167. // often be down to an issue or lack of the gcm_sender_id
  168. // and / or gcm_user_visible_only
  169. window.Demo.debug.log('Unable to subscribe to push.', e);
  170. pushButton.disabled = false;
  171. pushButton.textContent = 'Enable Push Messages';
  172. }
  173. });
  174. });
  175. }
  176. // Once the service worker is registered set the initial state
  177. function initialiseState()
  178. {
  179. // Are Notifications supported in the service worker?
  180. if (!('showNotification' in ServiceWorkerRegistration.prototype))
  181. {
  182. window.Demo.debug.log('Notifications aren\'t supported.');
  183. return;
  184. }
  185. // Check the current Notification permission.
  186. // If its denied, it's a permanent block until the
  187. // user changes the permission
  188. if (Notification.permission === 'denied')
  189. {
  190. window.Demo.debug.log('The user has blocked notifications.');
  191. return;
  192. }
  193. // Check if push messaging is supported
  194. if (!('PushManager' in window))
  195. {
  196. window.Demo.debug.log('Push messaging isn\'t supported.');
  197. return;
  198. }
  199. // We need the service worker registration to check for a subscription
  200. navigator.serviceWorker.ready.then(function (serviceWorkerRegistration)
  201. {
  202. // Do we already have a push message subscription?
  203. serviceWorkerRegistration.pushManager.getSubscription()
  204. .then(function (subscription)
  205. {
  206. // Enable any UI which subscribes / unsubscribes from
  207. // push messages.
  208. var pushButton = document.querySelector('.js-push-button');
  209. pushButton.disabled = false;
  210. if (!subscription)
  211. {
  212. // We aren’t subscribed to push, so set UI
  213. // to allow the user to enable push
  214. return;
  215. }
  216. // Keep your server in sync with the latest subscription
  217. sendSubscriptionToServer(subscription);
  218. // Set your UI to show they have subscribed for
  219. // push messages
  220. pushButton.textContent = 'Disable Push Messages';
  221. isPushEnabled = true;
  222. })
  223. .catch(function (err)
  224. {
  225. window.Demo.debug.log('Error during getSubscription()', err);
  226. });
  227. });
  228. }
  229. window.addEventListener('load', function ()
  230. {
  231. var pushButton = document.querySelector('.js-push-button');
  232. pushButton.addEventListener('click', function ()
  233. {
  234. if (isPushEnabled)
  235. {
  236. unsubscribe();
  237. }
  238. else
  239. {
  240. subscribe();
  241. }
  242. });
  243. // Check that service workers are supported, if so, progressively
  244. // enhance and add push messaging support, otherwise continue without it.
  245. if ('serviceWorker' in navigator)
  246. {
  247. navigator.serviceWorker.register(swURL)
  248. .then(initialiseState);
  249. }
  250. else
  251. {
  252. window.Demo.debug.log('Service workers aren\'t supported in this browser.');
  253. }
  254. });
  255. function getXmlDoc()
  256. {
  257. var xmlDoc;
  258. if (window.XMLHttpRequest)
  259. {
  260. // code for IE7+, Firefox, Chrome, Opera, Safari
  261. xmlDoc = new XMLHttpRequest();
  262. }
  263. else
  264. {
  265. // code for IE6, IE5
  266. xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
  267. }
  268. return xmlDoc;
  269. }
  270. /**
  271. * JavaScript Client Detection
  272. * (C) viazenetti GmbH (Christian Ludwig)
  273. * changed according zaUtre needs
  274. */
  275. function detectBrowser() {
  276. {
  277. var unknown = '-';
  278. // browser
  279. var nVer = navigator.appVersion;
  280. var nAgt = navigator.userAgent;
  281. var browser = navigator.appName;
  282. var version = '' + parseFloat(navigator.appVersion);
  283. var majorVersion = parseInt(navigator.appVersion, 10);
  284. var nameOffset, verOffset, ix;
  285. // Opera
  286. if ((verOffset = nAgt.indexOf('Opera')) != -1) {
  287. browser = 'Opera';
  288. version = nAgt.substring(verOffset + 6);
  289. if ((verOffset = nAgt.indexOf('Version')) != -1) {
  290. version = nAgt.substring(verOffset + 8);
  291. }
  292. }
  293. // Opera Next
  294. if ((verOffset = nAgt.indexOf('OPR')) != -1) {
  295. browser = 'Opera';
  296. version = nAgt.substring(verOffset + 4);
  297. }
  298. // Edge
  299. else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
  300. browser = 'Microsoft Edge';
  301. version = nAgt.substring(verOffset + 5);
  302. }
  303. // MSIE
  304. else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
  305. browser = 'Microsoft Internet Explorer';
  306. version = nAgt.substring(verOffset + 5);
  307. }
  308. // Chrome
  309. else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
  310. browser = 'Chrome';
  311. version = nAgt.substring(verOffset + 7);
  312. }
  313. // Safari
  314. else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
  315. browser = 'Safari';
  316. version = nAgt.substring(verOffset + 7);
  317. if ((verOffset = nAgt.indexOf('Version')) != -1) {
  318. version = nAgt.substring(verOffset + 8);
  319. }
  320. }
  321. // Firefox
  322. else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
  323. browser = 'Firefox';
  324. version = nAgt.substring(verOffset + 8);
  325. }
  326. // MSIE 11+
  327. else if (nAgt.indexOf('Trident/') != -1) {
  328. browser = 'Microsoft Internet Explorer';
  329. version = nAgt.substring(nAgt.indexOf('rv:') + 3);
  330. }
  331. // Other browsers
  332. else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
  333. browser = nAgt.substring(nameOffset, verOffset);
  334. version = nAgt.substring(verOffset + 1);
  335. if (browser.toLowerCase() == browser.toUpperCase()) {
  336. browser = navigator.appName;
  337. }
  338. }
  339. // trim the version string
  340. if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
  341. if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
  342. if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
  343. majorVersion = parseInt('' + version, 10);
  344. if (isNaN(majorVersion)) {
  345. version = '' + parseFloat(navigator.appVersion);
  346. majorVersion = parseInt(navigator.appVersion, 10);
  347. }
  348. // mobile version
  349. var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
  350. if (mobile) {
  351. mobile = "Mobile Version";
  352. }
  353. else {
  354. mobile = "Desktop Version";
  355. }
  356. // cookie
  357. var cookieEnabled = (navigator.cookieEnabled) ? true : false;
  358. if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
  359. document.cookie = 'testcookie';
  360. cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
  361. }
  362. // system
  363. var os = unknown;
  364. var clientStrings = [
  365. {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
  366. {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
  367. {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
  368. {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
  369. {s:'Windows Vista', r:/Windows NT 6.0/},
  370. {s:'Windows Server 2003', r:/Windows NT 5.2/},
  371. {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
  372. {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
  373. {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
  374. {s:'Windows 98', r:/(Windows 98|Win98)/},
  375. {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
  376. {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
  377. {s:'Windows CE', r:/Windows CE/},
  378. {s:'Windows 3.11', r:/Win16/},
  379. {s:'Android', r:/Android/},
  380. {s:'Open BSD', r:/OpenBSD/},
  381. {s:'Sun OS', r:/SunOS/},
  382. {s:'Linux', r:/(Linux|X11)/},
  383. {s:'iOS', r:/(iPhone|iPad|iPod)/},
  384. {s:'Mac OS X', r:/Mac OS X/},
  385. {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
  386. {s:'QNX', r:/QNX/},
  387. {s:'UNIX', r:/UNIX/},
  388. {s:'BeOS', r:/BeOS/},
  389. {s:'OS/2', r:/OS\/2/},
  390. {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
  391. ];
  392. for (var id in clientStrings) {
  393. var cs = clientStrings[id];
  394. if (cs.r.test(nAgt)) {
  395. os = cs.s;
  396. break;
  397. }
  398. }
  399. var osVersion = unknown;
  400. if (/Windows/.test(os)) {
  401. osVersion = /Windows (.*)/.exec(os)[1];
  402. os = 'Windows';
  403. }
  404. switch (os) {
  405. case 'Mac OS X':
  406. osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
  407. break;
  408. case 'Android':
  409. osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
  410. break;
  411. case 'iOS':
  412. osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
  413. osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
  414. break;
  415. }
  416. }
  417. let provider = browser + ' ' + version + ' / ' + os + ' ' + osVersion + ' / ' + mobile;
  418. return provider;
  419. }