Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(42)

Side by Side Diff: chrome/browser/resources/google_now/background.js

Issue 187263002: Refactor Authenticated Server Requests to use Promises (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Clarify the scoping Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | chrome/browser/resources/google_now/utility.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 'use strict'; 5 'use strict';
6 6
7 /** 7 /**
8 * @fileoverview The event page for Google Now for Chrome implementation. 8 * @fileoverview The event page for Google Now for Chrome implementation.
9 * The Google Now event page gets Google Now cards from the server and shows 9 * The Google Now event page gets Google Now cards from the server and shows
10 * them as Chrome notifications. 10 * them as Chrome notifications.
(...skipping 230 matching lines...) Expand 10 before | Expand all | Expand 10 after
241 type: 'histogram-linear', 241 type: 'histogram-linear',
242 min: 1, 242 min: 1,
243 max: GoogleNowEvent.EVENTS_TOTAL, 243 max: GoogleNowEvent.EVENTS_TOTAL,
244 buckets: GoogleNowEvent.EVENTS_TOTAL + 1 244 buckets: GoogleNowEvent.EVENTS_TOTAL + 1
245 }; 245 };
246 246
247 chrome.metricsPrivate.recordValue(metricDescription, event); 247 chrome.metricsPrivate.recordValue(metricDescription, event);
248 } 248 }
249 249
250 /** 250 /**
251 * Adds authorization behavior to the request. 251 * Checks the result of the HTTP Request and updates the authentication
252 * @param {XMLHttpRequest} request Server request. 252 * manager on any failure.
253 * @param {function(boolean)} callbackBoolean Completion callback with 'success' 253 * @param {XMLHttpRequest} request XMLHTTPRequest that sent the authenticated
rgustafson 2014/03/12 21:26:28 Nitpicky: match capitalization on the second usage
robliao 2014/03/12 22:21:32 Done.
254 * parameter. 254 * request.
255 */ 255 */
256 function setAuthorization(request, callbackBoolean) { 256 function checkAuthenticationStatus(request) {
257 authenticationManager.getAuthToken().then(function(token) { 257 if (request.status == HTTP_FORBIDDEN ||
258 request.status == HTTP_UNAUTHORIZED) {
259 authenticationManager.removeToken(token);
260 }
261 }
262
263 /**
264 * Builds and sends an authenticated request to the notification server.
265 * @param {string} method Request method.
266 * @param {string} handlerName Server handler to send the request to.
267 * @param {string=} opt_contentType Value for the Content-type header.
268 * @return {Promise} A promise to issue a request to the server.
269 * The promise rejects if there is a client-side authentication issue.
270 */
271 function requestFromServer(method, handlerName, opt_contentType) {
272 return authenticationManager.getAuthToken().then(function(token) {
273 var request = buildServerRequest(method, handlerName, opt_contentType);
258 request.setRequestHeader('Authorization', 'Bearer ' + token); 274 request.setRequestHeader('Authorization', 'Bearer ' + token);
259 275 var requestPromise = new Promise(function(resolve) {
260 // Instrument onloadend to remove stale auth tokens. 276 request.addEventListener('loadend', function() {
261 var originalOnLoadEnd = request.onloadend; 277 resolve(request);
262 request.onloadend = wrapper.wrapCallback(function(event) { 278 }, false);
263 if (request.status == HTTP_FORBIDDEN || 279 request.send();
264 request.status == HTTP_UNAUTHORIZED) {
265 authenticationManager.removeToken(token).then(function() {
266 originalOnLoadEnd(event);
267 });
268 } else {
269 originalOnLoadEnd(event);
270 }
271 }); 280 });
272 281 requestPromise.then(checkAuthenticationStatus);
273 callbackBoolean(true); 282 return requestPromise;
274 }).catch(function() {
275 callbackBoolean(false);
276 }); 283 });
277 } 284 }
278 285
279 /** 286 /**
280 * Shows parsed and combined cards as notifications. 287 * Shows parsed and combined cards as notifications.
281 * @param {Object.<string, StoredNotificationGroup>} notificationGroups Map from 288 * @param {Object.<string, StoredNotificationGroup>} notificationGroups Map from
282 * group name to group information. 289 * group name to group information.
283 * @param {Object.<ChromeNotificationId, CombinedCard>} cards Map from 290 * @param {Object.<ChromeNotificationId, CombinedCard>} cards Map from
284 * chromeNotificationId to the combined card, containing cards to show. 291 * chromeNotificationId to the combined card, containing cards to show.
285 * @param {function()} onSuccess Called on success. 292 * @param {function()} onSuccess Called on success.
(...skipping 274 matching lines...) Expand 10 before | Expand all | Expand 10 after
560 } 567 }
561 568
562 groupNames.forEach(function(groupName) { 569 groupNames.forEach(function(groupName) {
563 requestParameters += ('&requestTypes=' + groupName); 570 requestParameters += ('&requestTypes=' + groupName);
564 }); 571 });
565 572
566 requestParameters += '&uiLocale=' + navigator.language; 573 requestParameters += '&uiLocale=' + navigator.language;
567 574
568 console.log('requestNotificationGroups: request=' + requestParameters); 575 console.log('requestNotificationGroups: request=' + requestParameters);
569 576
570 var request = buildServerRequest('GET', 'notifications' + requestParameters); 577 requestFromServer('GET', 'notifications' + requestParameters).then(
571 578 function(request) {
572 request.onloadend = function(event) { 579 console.log('requestNotificationGroups-received ' + request.status);
573 console.log('requestNotificationGroups-onloadend ' + request.status); 580 if (request.status == HTTP_OK) {
574 if (request.status == HTTP_OK) { 581 recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
575 recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS); 582 processServerResponse(
576 processServerResponse( 583 JSON.parse(request.responseText), cardShownCallback);
577 JSON.parse(request.responseText), cardShownCallback); 584 }
578 } 585 });
579 };
580
581 setAuthorization(request, function(success) {
582 if (success)
583 request.send();
584 });
585 } 586 }
586 587
587 /** 588 /**
588 * Requests the account opted-in state from the server. 589 * Requests the account opted-in state from the server.
589 * @param {function()} optedInCallback Function that will be called if 590 * @param {function()} optedInCallback Function that will be called if
590 * opted-in state is 'true'. 591 * opted-in state is 'true'.
591 */ 592 */
592 function requestOptedIn(optedInCallback) { 593 function requestOptedIn(optedInCallback) {
593 console.log('requestOptedIn from ' + NOTIFICATION_CARDS_URL); 594 console.log('requestOptedIn from ' + NOTIFICATION_CARDS_URL);
594 595
595 var request = buildServerRequest('GET', 'settings/optin'); 596 requestFromServer('GET', 'settings/optin').then(function(request) {
596
597 request.onloadend = function(event) {
598 console.log( 597 console.log(
599 'requestOptedIn-onloadend ' + request.status + ' ' + request.response); 598 'requestOptedIn-received ' + request.status + ' ' + request.response);
600 if (request.status == HTTP_OK) { 599 if (request.status == HTTP_OK) {
601 var parsedResponse = JSON.parse(request.responseText); 600 var parsedResponse = JSON.parse(request.responseText);
602 if (parsedResponse.value) { 601 if (parsedResponse.value) {
603 chrome.storage.local.set({googleNowEnabled: true}); 602 chrome.storage.local.set({googleNowEnabled: true});
604 optedInCallback(); 603 optedInCallback();
605 // Google Now was disabled, now it's enabled. This is a state change. 604 // Google Now was disabled, now it's enabled. This is a state change.
606 onStateChange(); 605 onStateChange();
607 } else { 606 } else {
608 scheduleNextPoll({}, false); 607 scheduleNextPoll({}, false);
609 } 608 }
610 } 609 }
611 };
612
613 setAuthorization(request, function(success) {
614 if (success)
615 request.send();
616 }); 610 });
617 } 611 }
618 612
619 /** 613 /**
620 * Requests notification cards from the server. 614 * Requests notification cards from the server.
621 */ 615 */
622 function requestNotificationCards() { 616 function requestNotificationCards() {
623 console.log('requestNotificationCards'); 617 console.log('requestNotificationCards');
624 618
625 fillFromChromeLocalStorage({ 619 fillFromChromeLocalStorage({
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
704 var requestParameters = 'notifications/' + dismissalData.notificationId + 698 var requestParameters = 'notifications/' + dismissalData.notificationId +
705 '?age=' + dismissalAge + 699 '?age=' + dismissalAge +
706 '&chromeNotificationId=' + chromeNotificationId; 700 '&chromeNotificationId=' + chromeNotificationId;
707 701
708 for (var paramField in dismissalData.parameters) 702 for (var paramField in dismissalData.parameters)
709 requestParameters += ('&' + paramField + 703 requestParameters += ('&' + paramField +
710 '=' + dismissalData.parameters[paramField]); 704 '=' + dismissalData.parameters[paramField]);
711 705
712 console.log('requestCardDismissal: requestParameters=' + requestParameters); 706 console.log('requestCardDismissal: requestParameters=' + requestParameters);
713 707
714 var request = buildServerRequest('DELETE', requestParameters); 708 requestFromServer('DELETE', requestParameters).then(function(request) {
715 request.onloadend = function(event) {
716 console.log('requestDismissingCard-onloadend ' + request.status); 709 console.log('requestDismissingCard-onloadend ' + request.status);
717 if (request.status == HTTP_NOCONTENT) 710 if (request.status == HTTP_NOCONTENT)
718 recordEvent(GoogleNowEvent.DISMISS_REQUEST_SUCCESS); 711 recordEvent(GoogleNowEvent.DISMISS_REQUEST_SUCCESS);
719 712
720 // A dismissal doesn't require further retries if it was successful or 713 // A dismissal doesn't require further retries if it was successful or
721 // doesn't have a chance for successful completion. 714 // doesn't have a chance for successful completion.
722 var done = request.status == HTTP_NOCONTENT || 715 var done = request.status == HTTP_NOCONTENT ||
723 request.status == HTTP_BAD_REQUEST || 716 request.status == HTTP_BAD_REQUEST ||
724 request.status == HTTP_METHOD_NOT_ALLOWED; 717 request.status == HTTP_METHOD_NOT_ALLOWED;
725 callbackBoolean(done); 718 callbackBoolean(done);
726 }; 719 }).catch(function() {
727 720 callbackBoolean(false);
728 setAuthorization(request, function(success) {
729 if (success)
730 request.send();
731 else
732 callbackBoolean(false);
733 }); 721 });
734 } 722 }
735 723
736 /** 724 /**
737 * Tries to send dismiss requests for all pending dismissals. 725 * Tries to send dismiss requests for all pending dismissals.
738 * @param {function(boolean)} callbackBoolean Completion callback with 'success' 726 * @param {function(boolean)} callbackBoolean Completion callback with 'success'
739 * parameter. Success means that no pending dismissals are left. 727 * parameter. Success means that no pending dismissals are left.
740 */ 728 */
741 function processPendingDismissals(callbackBoolean) { 729 function processPendingDismissals(callbackBoolean) {
742 fillFromChromeLocalStorage({ 730 fillFromChromeLocalStorage({
(...skipping 421 matching lines...) Expand 10 before | Expand all | Expand 10 after
1164 lastPollNowPayloads: items.lastPollNowPayloads, 1152 lastPollNowPayloads: items.lastPollNowPayloads,
1165 notificationGroups: items.notificationGroups 1153 notificationGroups: items.notificationGroups
1166 }); 1154 });
1167 1155
1168 requestCards(); 1156 requestCards();
1169 } 1157 }
1170 }); 1158 });
1171 }); 1159 });
1172 } 1160 }
1173 }); 1161 });
OLDNEW
« no previous file with comments | « no previous file | chrome/browser/resources/google_now/utility.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698