From 721430b466d6ac02d1678d6e1336c745ebaa3f0e Mon Sep 17 00:00:00 2001 From: Rohan Rangray Date: Tue, 2 Jun 2015 00:26:35 -0700 Subject: [PATCH] Added broken code for gcm push notifs in SettingsController.js --- cmg/README.md | 16 --- cmg/analytics.js | 46 -------- cmg/config.js | 8 -- cmg/demo.js | 29 ----- cmg/images/icon-192x192.png | Bin 1668 -> 0 bytes cmg/images/indexwrapper.js | 87 -------------- cmg/images/sample-serviceworker.js | 140 ----------------------- cmg/images/sampleindex.html | 54 --------- cmg/images/samplejs.js | 87 -------------- cmg/index.html | 81 ------------- cmg/main.js | 227 ------------------------------------- cmg/manifest.json | 14 --- cmg/service-worker.js | 46 -------- manifest.json | 3 +- scripts/SettingsController.js | 38 ++++++- 15 files changed, 37 insertions(+), 839 deletions(-) delete mode 100644 cmg/README.md delete mode 100644 cmg/analytics.js delete mode 100644 cmg/config.js delete mode 100644 cmg/demo.js delete mode 100644 cmg/images/icon-192x192.png delete mode 100644 cmg/images/indexwrapper.js delete mode 100644 cmg/images/sample-serviceworker.js delete mode 100644 cmg/images/sampleindex.html delete mode 100644 cmg/images/samplejs.js delete mode 100644 cmg/index.html delete mode 100644 cmg/main.js delete mode 100644 cmg/manifest.json delete mode 100644 cmg/service-worker.js diff --git a/cmg/README.md b/cmg/README.md deleted file mode 100644 index a6daaaf..0000000 --- a/cmg/README.md +++ /dev/null @@ -1,16 +0,0 @@ -Push Messaging and Notification Sample -=== - -Learn more at http://www.chromestatus.com/feature/5416033485586432 and http://www.chromestatus.com/feature/5480344312610816 - -To use this sample please do the following: - -1. Create a project in the [Google Developer Console](https://console.developers.google.com) (detailed instructions are availabl at https://developer.android.com/google/gcm/gs.html) -1. Enable GCM support -1. Create a copy of [config.sample.js](config.sample.js) called config.js -1. Create a copy of [manifest.sample.json](manifest.sample.json) called manifest.json -1. Replace `` in your new `config.js` file with your own API key from the Google Developer Console project -4. Replace `` in your new `manifest.json` with your own project number from the Google Developer Console project - -# Related Samples - Push messaging and notifications are built on [service workers](https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker). diff --git a/cmg/analytics.js b/cmg/analytics.js deleted file mode 100644 index c2adf37..0000000 --- a/cmg/analytics.js +++ /dev/null @@ -1,46 +0,0 @@ -/* -This is provided from the sample as well. Its suppose to be from a live link, but i copied and pasted the code over. -*/ - -(function(){var aa=encodeURIComponent,f=window,n=Math;function Pc(a,b){return a.href=b} -var Qc="replace",q="data",m="match",ja="port",u="createElement",id="setAttribute",da="getTime",A="split",B="location",ra="hasOwnProperty",ma="hostname",ga="search",E="protocol",Ab="href",kd="action",G="apply",p="push",h="hash",pa="test",ha="slice",r="cookie",t="indexOf",ia="defaultValue",v="name",y="length",Ga="sendBeacon",z="prototype",la="clientWidth",jd="target",C="call",na="clientHeight",F="substring",oa="navigator",H="join",I="toLowerCase";var $c=function(a){this.w=a||[]};$c[z].set=function(a){this.w[a]=!0};$c[z].encode=function(){for(var a=[],b=0;b=b[y])wc(a,b,c);else if(8192>=b[y])x(a,b,c)||wd(a,b,c)||wc(a,b,c);else throw ge("len",b[y]),new Da(b[y]);},wc=function(a,b,c){var d=ta(a+"?"+b);d.onload=d.onerror=function(){d.onload=null;d.onerror=null;c()}},wd=function(a,b,c){var d=O.XMLHttpRequest;if(!d)return!1;var e=new d;if(!("withCredentials"in e))return!1;e.open("POST", -a,!0);e.withCredentials=!0;e.setRequestHeader("Content-Type","text/plain");e.onreadystatechange=function(){4==e.readyState&&(c(),e=null)};e.send(b);return!0},x=function(a,b,c){if(!O[oa][Ga])return!1;2036>=b[y]&&(a+="?"+b,b="");return O[oa][Ga](a,b)?(c(),!0):!1},ge=function(a,b,c){1<=100*n.random()||Aa("?")||(a=["t=error","_e="+a,"_v=j36","sr=1"],b&&a[p]("_f="+b),c&&a[p]("_m="+K(c[F](0,100))),a[p]("aip=1"),a[p]("z="+fe()),wc(oc()+"/collect",a[H]("&"),ua))};var Ha=function(){this.t=[]};Ha[z].add=function(a){this.t[p](a)};Ha[z].D=function(a){try{for(var b=0;b=100*R(a,Ka))throw"abort";}function Ma(a){if(Aa(P(a,Na)))throw"abort";}function Oa(){var a=M[B][E];if("http:"!=a&&"https:"!=a)throw"abort";} -function Pa(a){try{O[oa][Ga]?J(42):O.XMLHttpRequest&&"withCredentials"in new O.XMLHttpRequest&&J(40)}catch(b){}a.set(ld,Td(a),!0);a.set(Ac,R(a,Ac)+1);var c=[];Qa.map(function(b,e){if(e.p){var g=a.get(b);void 0!=g&&g!=e[ia]&&("boolean"==typeof g&&(g*=1),c[p](e.p+"="+K(""+g)))}});c[p]("z="+Bd());a.set(Ra,c[H]("&"),!0)} -function Sa(a){var b=P(a,gd)||oc()+"/collect",c=P(a,fa);!c&&a.get(Vd)&&(c="beacon");if(c){var d=P(a,Ra),e=a.get(Ia),e=e||ua;"image"==c?wc(b,d,e):"xhr"==c&&wd(b,d,e)||"beacon"==c&&x(b,d,e)||ba(b,d,e)}else ba(b,P(a,Ra),a.get(Ia));a.set(Ia,ua,!0)}function Hc(a){var b=O.gaData;b&&(b.expId&&a.set(Nc,b.expId),b.expVar&&a.set(Oc,b.expVar))}function cd(){if(O[oa]&&"preview"==O[oa].loadPurpose)throw"abort";}function yd(a){var b=O.gaDevIds;ka(b)&&0!=b[y]&&a.set("&did",b[H](","),!0)} -function vb(a){if(!a.get(Na))throw"abort";};var hd=function(){return n.round(2147483647*n.random())},Bd=function(){try{var a=new Uint32Array(1);O.crypto.getRandomValues(a);return a[0]&2147483647}catch(b){return hd()}},fe=hd;function Ta(a){var b=R(a,Ua);500<=b&&J(15);var c=P(a,Va);if("transaction"!=c&&"item"!=c){var c=R(a,Wa),d=(new Date)[da](),e=R(a,Xa);0==e&&a.set(Xa,d);e=n.round(2*(d-e)/1E3);0=c)throw"abort";a.set(Wa,--c)}a.set(Ua,++b)};var Ya=function(){this.data=new ee},Qa=new ee,Za=[];Ya[z].get=function(a){var b=$a(a),c=this[q].get(a);b&&void 0==c&&(c=ea(b[ia])?b[ia]():b[ia]);return b&&b.n?b.n(this,a,c):c};var P=function(a,b){var c=a.get(b);return void 0==c?"":""+c},R=function(a,b){var c=a.get(b);return void 0==c||""===c?0:1*c};Ya[z].set=function(a,b,c){if(a)if("object"==typeof a)for(var d in a)a[ra](d)&&ab(this,d,a[d],c);else ab(this,a,b,c)}; -var ab=function(a,b,c,d){if(void 0!=c)switch(b){case Na:wb[pa](c)}var e=$a(b);e&&e.o?e.o(a,b,c,d):a[q].set(b,c,d)},bb=function(a,b,c,d,e){this.name=a;this.p=b;this.n=d;this.o=e;this.defaultValue=c},$a=function(a){var b=Qa.get(a);if(!b)for(var c=0;c=b)){var c=(new Date).getHours(),d=[Bd(),Bd(),Bd()][H](".");a=(3==b||5==b?"https:":"http:")+"//www.google-analytics.com/collect?z=br.";a+=[b,"A",c,d][H](".");var e=1!=b%3?"https:":"http:",e=e+"//www.google-analytics.com/collect?z=br.",e=e+[b,"B",c,d][H](".");7==b&&(e=e[Qc]("//www.","//ssl."));c=function(){4<=b&&6>=b?O[oa][Ga](e,""):ta(e)};Bd()%2?(ta(a),c()):(c(),ta(a))}}};function fc(){var a,b,c;if((c=(c=O[oa])?c.plugins:null)&&c[y])for(var d=0;d=c)&&(c={},Ec(c)||Fc(c))){var d=c[Eb];void 0==d||Infinity==d||isNaN(d)||(0c)a[b]=void 0},Fd=function(a){return function(b){"pageview"!=b.get(Va)||a.I||(a.I=!0,gc(b,function(b){a.send("timing",b)}))}};var hc=!1,mc=function(a){if("cookie"==P(a,ac)){var b=P(a,U),c=nd(a),d=kc(P(a,Yb)),e=lc(P(a,W)),g=1E3*R(a,Zb),ca=P(a,Na);if("auto"!=e)zc(b,c,d,e,ca,g)&&(hc=!0);else{J(32);var l;a:{c=[];e=xa()[A](".");if(4==e[y]&&(l=e[e[y]-1],parseInt(l,10)==l)){l=["none"];break a}for(l=e[y]-2;0<=l;l--)c[p](e[ha](l)[H]("."));c[p]("none");l=c}for(var k=0;k=a&&d[p]({hash:ca[0],R:e[g],O:ca})}return 0==d[y]?void 0:1==d[y]?d[0]:Zc(b,d)||Zc(c,d)||Zc(null,d)||d[0]}function Zc(a,b){var c,d;null==a?c=d=1:(c=La(a),d=La(D(a,".")?a[F](1):"."+a));for(var e=0;ed[y])){c=[];for(var e=0;e=ca[0]||0>=ca[1]?"":ca[H]("x");a.set(rb,c);a.set(tb,fc());a.set(ob,M.characterSet||M.charset);a.set(sb,b&&"function"===typeof b.javaEnabled&&b.javaEnabled()||!1);a.set(nb,(b&&(b.language||b.browserLanguage)||"")[I]());if(d&&a.get(cc)&&(b=M[B][h])){b=b[A](/[?&#]+/);d=[];for(c=0;carguments[y])){var b,c;"string"===typeof arguments[0]?(b=arguments[0],c=[][ha][C](arguments,1)):(b=arguments[0]&&arguments[0][Va],c=arguments);b&&(c=za(qc[b]||[],c),c[Va]=b,this.b.set(c,void 0,!0),this.filters.D(this.b),this.b[q].m={},je(this.b))}};var rc=function(a){if("prerender"==M.visibilityState)return!1;a();return!0};var td=/^(?:(\w+)\.)?(?:(\w+):)?(\w+)$/,sc=function(a){if(ea(a[0]))this.u=a[0];else{var b=td.exec(a[0]);null!=b&&4==b[y]&&(this.c=b[1]||"t0",this.e=b[2]||"",this.d=b[3],this.a=[][ha][C](a,1),this.e||(this.A="create"==this.d,this.i="require"==this.d,this.g="provide"==this.d,this.ba="remove"==this.d),this.i&&(3<=this.a[y]?(this.X=this.a[1],this.W=this.a[2]):this.a[1]&&(qa(this.a[1])?this.X=this.a[1]:this.W=this.a[1])));b=a[1];a=a[2];if(!this.d)throw"abort";if(this.i&&(!qa(b)||""==b))throw"abort";if(this.g&& -(!qa(b)||""==b||!ea(a)))throw"abort";if(ud(this.c)||ud(this.e))throw"abort";if(this.g&&"t0"!=this.c)throw"abort";}};function ud(a){return 0<=a[t](".")||0<=a[t](":")};var Yd,Zd,$d;Yd=new ee;$d=new ee;Zd={ec:45,ecommerce:46,linkid:47}; -var ae=function(a){function b(a){var b=(a[ma]||"")[A](":")[0][I](),c=(a[E]||"")[I](),c=1*a[ja]||("http:"==c?80:"https:"==c?443:"");a=a.pathname||"";D(a,"/")||(a="/"+a);return[b,""+c,a]}var c=M[u]("a");Pc(c,M[B][Ab]);var d=(c[E]||"")[I](),e=b(c),g=c[ga]||"",ca=d+"//"+e[0]+(e[1]?":"+e[1]:"");D(a,"//")?a=d+a:D(a,"/")?a=ca+a:!a||D(a,"?")?a=ca+e[2]+(a||g):0>a[A]("/")[0][t](":")&&(a=ca+e[2][F](0,e[2].lastIndexOf("/"))+"/"+a);Pc(c,a);d=b(c);return{protocol:(c[E]||"")[I](),host:d[0],port:d[1],path:d[2],G:c[ga]|| -"",url:a||""}};var Z={ga:function(){Z.f=[]}};Z.ga();Z.D=function(a){var b=Z.J[G](Z,arguments),b=Z.f.concat(b);for(Z.f=[];0c;c++){var d=b[c].src;if(d&&0==d[t]("https://www.google-analytics.com/analytics")){J(33);b=!0;break a}}b=!1}b&&(Ba=!0)}Ud()|| -Ba||!Ed(new Od)||(J(36),Ba=!0);(O.gaplugins=O.gaplugins||{}).Linker=Dc;b=Dc[z];Yd.set("linker",Dc);X("decorate",b,b.Q,20);X("autoLink",b,b.S,25);Yd.set("displayfeatures",fd);Yd.set("adfeatures",fd);a=a&&a.q;ka(a)?Z.D[G](N,a):J(50)}};N.k=function(){for(var a=N.getAll(),b=0;b>21:b;return b};})(window); \ No newline at end of file diff --git a/cmg/config.js b/cmg/config.js deleted file mode 100644 index 345b2ae..0000000 --- a/cmg/config.js +++ /dev/null @@ -1,8 +0,0 @@ -/* -This file sets up a global variable gcmAPIKey, which contains our key. -*/ - -window.GoogleSamples = window.GoogleSamples || {}; -window.GoogleSamples.Config = window.GoogleSamples.Config || { - gcmAPIKey: 'AIzaSyCPjkgseoVp8shXOMwFnGBeEijizpLDXOs' -}; diff --git a/cmg/demo.js b/cmg/demo.js deleted file mode 100644 index 520d8f2..0000000 --- a/cmg/demo.js +++ /dev/null @@ -1,29 +0,0 @@ -/* -This demo provides functionality that output debug messages. -*/ - -'use strict'; - -function Debug() { - -} - -Debug.prototype.log = function() { - var paragraphElement = document.createElement('p'); - paragraphElement.textContent = Array.prototype.join.call(arguments, ''); - document.querySelector('.js-log').appendChild(paragraphElement); -} - -window.addEventListener('load', function() { - var logDiv = document.createElement('div'); - logDiv.classList.add('js-log'); - - var heading = document.createElement('h2'); - heading.textContent = 'Log'; - logDiv.appendChild(heading); - - document.body.appendChild(logDiv); - - window.Demo = window.Demo || {}; - window.Demo.debug = window.Demo.debug || new Debug(); -}); diff --git a/cmg/images/icon-192x192.png b/cmg/images/icon-192x192.png deleted file mode 100644 index f6ba515101d3aed9289c2cfb93374548cb60f07a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1668 zcmV-~27CF5P)l>6ao#a--7#_AGjiYm|NpVc^HGN6>+$@LvF*^__i~--cTM+D00008 zbW%=J0Hf*{JIP>!j`I|!000I1Nkl>ma|WDSwQ;@1nQqTvXJGB;O{12pXRzi z;HQN4Md0={mjwdH&n&kH+@9u|K%l&x<+fl;U`upXi)p)<<_>|twJ;joAjtF>7ak-a z{O35j6q|Hn+RmrBGJpPhn!vVuAnZxY>%t=hys-GgB;+n7mSMX>petE!EdGGIGb_7r zCQnlYf)i>4Do7}U5J#abH?%VlSOqC%@En1eb_N`)ph+2oGzVq55P?G{JaO;Pas8g_C+a3D}$8g^emTlPtAY%(ZBbX2tbH0Pkau5 zzylge4-k0u4#C||pu*$3cV~u0An=}s(gOtgn>T^(i{pL*@!hGjkmXQpuim`W`w8r? zUY~X$%YpE`f=YXhKr54D4W^(G5c0{LGz(cyMalI~qc!9v%i7z+1dcv73`RpjYdKMd z1`;T(&O=k66*Ss;0|^vGJ7T|bw1NhNGQb2{S3-xsML|*-^fV_KS65pA6eK@WE+m0r z+yO~Lyn>`M=xMHs#vR}_)tAT@CxqfRLgqhQuBziuuF|U)yeyzWvn^xe@ ztax?us;Y_CjRwblnxQ;Yh&ps5!UGE8ZOt$JKmrs*7lL2<0jDa6DFkm>9UGvaNBV1T z#}`2&6vX$}p_}pr5g`TX{gtyUuc0JYfVcIqED0ZGF5csp!YKmfOTnd0e#5@Q3z1Kr zvtY!1vi3+J@RLKvbR#T1QV8bcbMQ<5Kp{#!-$Dzp^caHkfPqz1e(6ayv9pUzJ^T}D zYQVe!*9~6?esocgrRNJV;ZT4WT7adek?00A&<(z+BzUy}@is`G$FO<60qOghe@;OW zXh47s;^!eapaC5fuz~w`44jqzns2rNGIgwqMlxdL@ScIY_;`AYEiV~)i$DYF!y|~1 z?Hf=TMY7({b|eAikuwk*m?wxT*NNZH_y*L^K39coV4NVjCN+IOvrQ01!GGGU1Z4d+*^m7^jDp=?C@f&U6fu=bad~p}A41ggDP=x$dQL)#?4e;C(5rxJUdBIc+(qg>Asd;yETazJCpT6;$h%h>`qeM(qI`B@AbM#jGk7JQ zfw$J&-^$j_OAZbb6&~lBKOi62%Wb;- z_^Eq(0p48skeBN;fz3puW(Pn%gqIIt37z&5K0EMUo&-oC+p5{Y{-+)S@KT}q(+Cm% zN+aNv_P==If$zJ*nm_Mly$SB7^3k^hy^BO+`3xlN{pA6ZkDZryVbBd^2M)lqL~+o; zX9qssDF~|e^z2~iWd{__8UJj8K1SO-kR5EcgrqkxzWMWTm#2UcX#N&n4%4au&ELSw zyW|{QKIUHb9|2zFYwzVG{<*b$^rM|Db_Fj%36;TkI zy_ds@KNYfrxtHCkatY1f66y3^s28ka>*aJ-Z=`$eseTp~78Vx%75oLQplz&$rPpx) O0000 0) { - // Start with one to account for the new notification - // we are adding - var notificationCount = 1; - for (var i = 0; i < notifications.length; i++) { - var existingNotification = notifications[i]; - if (existingNotification.data && - existingNotification.data.notoficationCount) { - notificationCount += existingNotification.data.notoficationCount; - } else { - notificationCount++; - } - } - message = 'You have ' + notificationCount + - ' weather updates.'; - notificationData.notificationCount = notificationCount; - } - - return showNotification(title, message, icon, notificationData); - }); - } else { - return showNotification(title, message, icon, notificationData); - } - }); - }).catch(function(err) { - console.error('Unable to retrieve data', err); - - var title = 'An error occured'; - var message = 'We were unable to get the information for this ' + - 'push message'; - - return showNotification(title, message); - }) - ); -}); - -self.addEventListener('notificationclick', function(event) { - console.log('On notification click: ', event); - - if (Notification.prototype.hasOwnProperty('data')) { - console.log('Using Data'); - var url = event.notification.data.url; - event.waitUntil(clients.openWindow(url)); - } else { - event.waitUntil(getIdb().get(KEY_VALUE_STORE_NAME, event.notification.tag).then(function(url) { - // At the moment you cannot open third party URL's, a simple trick - // is to redirect to the desired URL from a URL on your domain - var redirectUrl = '/redirect.html?redirect=' + - url; - return clients.openWindow(redirectUrl); - })); - } -}); diff --git a/cmg/images/sampleindex.html b/cmg/images/sampleindex.html deleted file mode 100644 index e0c512b..0000000 --- a/cmg/images/sampleindex.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - Simple Push Demo - - - - - - - - - - - - - - -

Push Demo

-
-
-
-
-

- -

-

OR

- -

Copy and paste the following CURL command into your terminal to send a push message to your browser.

- -

- -

-
-

- -

-
-

The Weather API is

- - - \ No newline at end of file diff --git a/cmg/images/samplejs.js b/cmg/images/samplejs.js deleted file mode 100644 index 1e9e0f4..0000000 --- a/cmg/images/samplejs.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -function promisifyRequest(obj) { - return new Promise(function(resolve, reject) { - function onsuccess(event) { - resolve(obj.result); - unlisten(); - } - function onerror(event) { - reject(obj.error); - unlisten(); - } - function unlisten() { - obj.removeEventListener('complete', onsuccess); - obj.removeEventListener('success', onsuccess); - obj.removeEventListener('error', onerror); - obj.removeEventListener('abort', onerror); - } - obj.addEventListener('complete', onsuccess); - obj.addEventListener('success', onsuccess); - obj.addEventListener('error', onerror); - obj.addEventListener('abort', onerror); - }); -} - -function IndexDBWrapper(name, version, upgradeCallback) { - var request = indexedDB.open(name, version); - this.ready = promisifyRequest(request); - request.onupgradeneeded = function(event) { - upgradeCallback(request.result, event.oldVersion); - }; -} - -IndexDBWrapper.supported = 'indexedDB' in self; - -var IndexDBWrapperProto = IndexDBWrapper.prototype; - -IndexDBWrapperProto.transaction = function(stores, modeOrCallback, callback) { - return this.ready.then(function(db) { - var mode = 'readonly'; - - if (modeOrCallback.apply) { - callback = modeOrCallback; - } - else if (modeOrCallback) { - mode = modeOrCallback; - } - - var tx = db.transaction(stores, mode); - var val = callback(tx, db); - var promise = promisifyRequest(tx); - var readPromise; - - if (!val) { - return promise; - } - - if (val[0] && 'result' in val[0]) { - readPromise = Promise.all(val.map(promisifyRequest)); - } - else { - readPromise = promisifyRequest(val); - } - - return promise.then(function() { - return readPromise; - }); - }); -}; - -IndexDBWrapperProto.get = function(store, key) { - return this.transaction(store, function(tx) { - return tx.objectStore(store).get(key); - }); -}; - -IndexDBWrapperProto.put = function(store, key, value) { - return this.transaction(store, 'readwrite', function(tx) { - tx.objectStore(store).put(value, key); - }); -}; - -IndexDBWrapperProto.delete = function(store, key) { - return this.transaction(store, 'readwrite', function(tx) { - tx.objectStore(store).delete(key); - }); -}; \ No newline at end of file diff --git a/cmg/index.html b/cmg/index.html deleted file mode 100644 index 670a028..0000000 --- a/cmg/index.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - Push Messaging & Notifications - - - - - - - - - - - - -

Push Messaging & Notifications

- -

Available in Chrome 42+ & Chrome 42+

- -

To use this sample please do the following:

- -
    -
  1. Refer to Google Developer Console.
  2. -
  3. For API reference and our key and project numbers.
  4. -
- - -

- -

- -
-
- -

cURL Command to Send Push

-
- - - - - - - - diff --git a/cmg/main.js b/cmg/main.js deleted file mode 100644 index 61a7cf7..0000000 --- a/cmg/main.js +++ /dev/null @@ -1,227 +0,0 @@ -/* -This page contains subscribing user's ip to our system. -sendSubscriptionToServer is not implemented yet. -All methods have comments from the sample. -*/ - -'use strict'; - -var API_KEY = window.GoogleSamples.Config.gcmAPIKey; -var GCM_ENDPOINT = 'https://android.googleapis.com/gcm/send'; - -var curlCommandDiv = document.querySelector('.js-curl-command'); -var isPushEnabled = false; - -// This method handles the removal of subscriptionId -// in Chrome 44 by concatenating the subscription Id -// to the subscription endpoint -function endpointWorkaround(pushSubscription) { - // Make sure we only mess with GCM - if (pushSubscription.endpoint.indexOf('https://android.googleapis.com/gcm/send') !== 0) { - return pushSubscription.endpoint; - } - - var mergedEndpoint = pushSubscription.endpoint; - // Chrome 42 + 43 will not have the subscriptionId attached - // to the endpoint. - if (pushSubscription.subscriptionId && - pushSubscription.endpoint.indexOf(pushSubscription.subscriptionId) === -1) { - // Handle version 42 where you have separate subId and Endpoint - mergedEndpoint = pushSubscription.endpoint + '/' + - pushSubscription.subscriptionId; - } - return mergedEndpoint; -} - -function sendSubscriptionToServer(subscription) { - // TODO: Send the subscription.endpoint - // to your server and save it to send a - // push message at a later date - // - // For compatibly of Chrome 43, get the endpoint via - // endpointWorkaround(subscription) - console.log('TODO: Implement sendSubscriptionToServer()'); - - var mergedEndpoint = endpointWorkaround(subscription); - - // This is just for demo purposes / an easy to test by - // generating the appropriate cURL command - showCurlCommand(mergedEndpoint); -} - -// NOTE: This code is only suitable for GCM endpoints, -// When another browser has a working version, alter -// this to send a PUSH request directly to the endpoint -function showCurlCommand(mergedEndpoint) { - // The curl command to trigger a push message straight from GCM - if (mergedEndpoint.indexOf(GCM_ENDPOINT) !== 0) { - window.Demo.debug.log('This browser isn\'t currently ' + - 'supported for this demo'); - return; - } - - var endpointSections = mergedEndpoint.split('/'); - var subscriptionId = endpointSections[endpointSections.length - 1]; - - var curlCommand = 'curl --header "Authorization: key=' + API_KEY + - '" --header Content-Type:"application/json" ' + GCM_ENDPOINT + - ' -d "{\\"registration_ids\\":[\\"' + subscriptionId + '\\"]}"'; - - curlCommandDiv.textContent = curlCommand; -} - -function unsubscribe() { - var pushButton = document.querySelector('.js-push-button'); - pushButton.disabled = true; - curlCommandDiv.textContent = ''; - - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - // To unsubscribe from push messaging, you need get the - // subcription object, which you can call unsubscribe() on. - serviceWorkerRegistration.pushManager.getSubscription().then( - function(pushSubscription) { - // Check we have a subscription to unsubscribe - if (!pushSubscription) { - // No subscription object, so set the state - // to allow the user to subscribe to push - isPushEnabled = false; - pushButton.disabled = false; - pushButton.textContent = 'Enable Push Messages'; - return; - } - - // TODO: Make a request to your server to remove - // the users data from your data store so you - // don't attempt to send them push messages anymore - - // We have a subcription, so call unsubscribe on it - pushSubscription.unsubscribe().then(function(successful) { - pushButton.disabled = false; - pushButton.textContent = 'Enable Push Messages'; - isPushEnabled = false; - }).catch(function(e) { - // We failed to unsubscribe, this can lead to - // an unusual state, so may be best to remove - // the subscription id from your data store and - // inform the user that you disabled push - - window.Demo.debug.log('Unsubscription error: ', e); - pushButton.disabled = false; - }); - }).catch(function(e) { - window.Demo.debug.log('Error thrown while unsubscribing from ' + - 'push messaging.', e); - }); - }); -} - -function subscribe() { - // Disable the button so it can't be changed while - // we process the permission request - var pushButton = document.querySelector('.js-push-button'); - pushButton.disabled = true; - - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true}) - .then(function(subscription) { - // The subscription was successful - isPushEnabled = true; - pushButton.textContent = 'Disable Push Messages'; - pushButton.disabled = false; - - // TODO: Send the subscription subscription.endpoint - // to your server and save it to send a push message - // at a later date - return sendSubscriptionToServer(subscription); - }) - .catch(function(e) { - if (Notification.permission === 'denied') { - // The user denied the notification permission which - // means we failed to subscribe and the user will need - // to manually change the notification permission to - // subscribe to push messages - window.Demo.debug.log('Permission for Notifications was denied'); - pushButton.disabled = true; - } else { - // A problem occurred with the subscription, this can - // often be down to an issue or lack of the gcm_sender_id - // and / or gcm_user_visible_only - window.Demo.debug.log('Unable to subscribe to push.', e); - pushButton.disabled = false; - pushButton.textContent = 'Enable Push Messages'; - } - }); - }); -} - -// Once the service worker is registered set the initial state -function initialiseState() { - // Are Notifications supported in the service worker? - if (!('showNotification' in ServiceWorkerRegistration.prototype)) { - window.Demo.debug.log('Notifications aren\'t supported.'); - return; - } - - // Check the current Notification permission. - // If its denied, it's a permanent block until the - // user changes the permission - if (Notification.permission === 'denied') { - window.Demo.debug.log('The user has blocked notifications.'); - return; - } - - // Check if push messaging is supported - if (!('PushManager' in window)) { - window.Demo.debug.log('Push messaging isn\'t supported.'); - return; - } - - // We need the service worker registration to check for a subscription - navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { - // Do we already have a push message subscription? - serviceWorkerRegistration.pushManager.getSubscription() - .then(function(subscription) { - // Enable any UI which subscribes / unsubscribes from - // push messages. - var pushButton = document.querySelector('.js-push-button'); - pushButton.disabled = false; - - if (!subscription) { - // We aren’t subscribed to push, so set UI - // to allow the user to enable push - return; - } - - // Keep your server in sync with the latest subscription - sendSubscriptionToServer(subscription); - - // Set your UI to show they have subscribed for - // push messages - pushButton.textContent = 'Disable Push Messages'; - isPushEnabled = true; - }) - .catch(function(err) { - window.Demo.debug.log('Error during getSubscription()', err); - }); - }); -} - -window.addEventListener('load', function() { - var pushButton = document.querySelector('.js-push-button'); - pushButton.addEventListener('click', function() { - if (isPushEnabled) { - unsubscribe(); - } else { - subscribe(); - } - }); - - // Check that service workers are supported, if so, progressively - // enhance and add push messaging support, otherwise continue without it. - if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('./service-worker.js') - .then(initialiseState); - } else { - window.Demo.debug.log('Service workers aren\'t supported in this browser.'); - } -}); diff --git a/cmg/manifest.json b/cmg/manifest.json deleted file mode 100644 index ce56698..0000000 --- a/cmg/manifest.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "Push Demo", - "short_name": "Push Demo", - "icons": [{ - "src": "images/icon-192x192.png", - "sizes": "192x192" - }], - "start_url": "./index.html?homescreen=1", - "display": "standalone", - "gcm_sender_id": "45066531702", - - "//": "gcm_user_visible_only is only needed until Chrome 44 is in stable ", - "gcm_user_visible_only": true -} diff --git a/cmg/service-worker.js b/cmg/service-worker.js deleted file mode 100644 index ab3f5d7..0000000 --- a/cmg/service-worker.js +++ /dev/null @@ -1,46 +0,0 @@ -/* -Still not sure what this does, but i think it handles the event -in the background. -*/ - -'use strict'; - -self.addEventListener('push', function(event) { - console.log('Received a push message', event); - - var title = 'Yay a message.'; - var body = 'We have received a push message.'; - var icon = '/images/icon-192x192.png'; - var tag = 'simple-push-demo-notification-tag'; - - event.waitUntil( - self.registration.showNotification(title, { - body: body, - icon: icon, - tag: tag - }) - ); -}); - - -self.addEventListener('notificationclick', function(event) { - console.log('On notification click: ', event.notification.tag); - // Android doesn’t close the notification when you click on it - // See: http://crbug.com/463146 - event.notification.close(); - - // This looks to see if the current is already open and - // focuses if it is - event.waitUntil(clients.matchAll({ - type: "window" - }).then(function(clientList) { - for (var i = 0; i < clientList.length; i++) { - var client = clientList[i]; - if (client.url == '/' && 'focus' in client) - return client.focus(); - } - if (clients.openWindow) - return clients.openWindow('/'); - })); - -}); diff --git a/manifest.json b/manifest.json index 9b9ff50..ff369b0 100644 --- a/manifest.json +++ b/manifest.json @@ -9,5 +9,6 @@ "start_url": "/index.html", "display": "standalone", "gcm_sender_id": "45066531702", - "gcm_user_visible_only": true + "gcm_user_visible_only": true + "permissions": ["gcm"] } diff --git a/scripts/SettingsController.js b/scripts/SettingsController.js index 58e55b3..300b191 100644 --- a/scripts/SettingsController.js +++ b/scripts/SettingsController.js @@ -1,13 +1,45 @@ angular.module('flashy.SettingsController', ['ui.router']). - controller('SettingsController', function($scope) { - - + controller('SettingsController', function($scope, $http) { $scope.changePassword = function(oldPassword, newPassword, confirmedNewPassword) { }; + console.log("checking to see if chrome"); + if (!chrome) { return; } + console.log("chrome"); + $scope.registerCallback = function(registrationId) { + if (chrome.runtime.lastError) { + console.log("Registration failed") + } + + sendRegistrationId(registrationId, function(succeed) { + if (succeed) { + chrome.storage.local.set({registered: true}); + } + }); + }; + function sendRegistrationId(registrationId, callback) { + console.log("registration id: "+registrationId); + $http.post('/api/subscribe/', JSON.stringify({ + 'registration_id': registrationId + })); + callback(true); + } + + console.log(chrome.runtime.onStartup); + chrome.runtime.onStartup.addListener(function() { + chrome.storage.local.get("registered", function(result) { + // If already registered, bail out. + if (result["registered"]) + return; + + // Up to 100 senders are allowed. + var senderIds = ["45066531702"]; + chrome.gcm.register(senderIds, registerCallback); + }); + }); }); -- 1.9.1