OLD | NEW |
---|---|
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. |
11 * The service performs periodic updating of Google Now cards. | 11 * The service performs periodic updating of Google Now cards. |
12 * Each updating of the cards includes 4 steps: | 12 * Each updating of the cards includes 4 steps: |
13 * 1. Processing requests for cards dismissals that are not yet sent to the | 13 * 1. Processing requests for cards dismissals that are not yet sent to the |
14 * server. | 14 * server. |
15 * 2. Making a server request. | 15 * 2. Making a server request. |
16 * 3. Showing the received cards as notifications. | 16 * 3. Showing the received cards as notifications. |
17 */ | 17 */ |
18 | 18 |
19 // TODO(vadimt): Decide what to do in incognito mode. | 19 // TODO(robliao): Decide what to do in incognito mode. |
20 // TODO(vadimt): Figure out the final values of the constants. | |
21 | 20 |
22 /** | 21 /** |
23 * Standard response code for successful HTTP requests. This is the only success | 22 * Standard response code for successful HTTP requests. This is the only success |
24 * code the server will send. | 23 * code the server will send. |
25 */ | 24 */ |
26 var HTTP_OK = 200; | 25 var HTTP_OK = 200; |
27 var HTTP_NOCONTENT = 204; | 26 var HTTP_NOCONTENT = 204; |
28 | 27 |
29 var HTTP_BAD_REQUEST = 400; | 28 var HTTP_BAD_REQUEST = 400; |
30 var HTTP_UNAUTHORIZED = 401; | 29 var HTTP_UNAUTHORIZED = 401; |
(...skipping 294 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
325 resolve(request); | 324 resolve(request); |
326 }, false); | 325 }, false); |
327 request.send(); | 326 request.send(); |
328 }); | 327 }); |
329 requestPromise.then(checkAuthenticationStatus(token)); | 328 requestPromise.then(checkAuthenticationStatus(token)); |
330 return requestPromise; | 329 return requestPromise; |
331 }); | 330 }); |
332 } | 331 } |
333 | 332 |
334 /** | 333 /** |
335 * Shows parsed and combined cards as notifications. | 334 * Shows the notification groups as notification cards. |
336 * @param {Object.<string, StoredNotificationGroup>} notificationGroups Map from | 335 * @param {Object.<string, StoredNotificationGroup>} notificationGroups Map from |
337 * group name to group information. | 336 * group name to group information. |
338 * @param {Object.<ChromeNotificationId, CombinedCard>} cards Map from | 337 * @param {function(ReceivedNotification)=} opt_onCardShown Optional parameter |
339 * chromeNotificationId to the combined card, containing cards to show. | |
340 * @param {function()} onSuccess Called on success. | |
341 * @param {function(ReceivedNotification)=} onCardShown Optional parameter | |
342 * called when each card is shown. | 338 * called when each card is shown. |
339 * @return {Promise} A promise to show the notification groups as cards. | |
343 */ | 340 */ |
344 function showNotificationCards( | 341 function showNotificationGroups(notificationGroups, opt_onCardShown) { |
345 notificationGroups, cards, onSuccess, onCardShown) { | 342 var cards = combineCardsFromGroups(notificationGroups); |
346 console.log('showNotificationCards ' + JSON.stringify(cards)); | 343 console.log('showNotificationGroups ' + JSON.stringify(cards)); |
347 | 344 |
348 instrumented.notifications.getAll(function(notifications) { | 345 return new Promise(function(resolve) { |
349 console.log('showNotificationCards-getAll ' + | 346 instrumented.notifications.getAll(function(notifications) { |
350 JSON.stringify(notifications)); | 347 console.log('showNotificationGroups-getAll ' + |
351 notifications = notifications || {}; | 348 JSON.stringify(notifications)); |
349 notifications = notifications || {}; | |
352 | 350 |
353 // Mark notifications that didn't receive an update as having received | 351 // Mark notifications that didn't receive an update as having received |
354 // an empty update. | 352 // an empty update. |
355 for (var chromeNotificationId in notifications) { | 353 for (var chromeNotificationId in notifications) { |
356 cards[chromeNotificationId] = cards[chromeNotificationId] || []; | 354 cards[chromeNotificationId] = cards[chromeNotificationId] || []; |
357 } | 355 } |
358 | 356 |
359 /** @type {Object.<string, NotificationDataEntry>} */ | 357 /** @type {Object.<string, NotificationDataEntry>} */ |
360 var notificationsData = {}; | 358 var notificationsData = {}; |
361 | 359 |
362 // Create/update/delete notifications. | 360 // Create/update/delete notifications. |
363 for (var chromeNotificationId in cards) { | 361 for (var chromeNotificationId in cards) { |
364 notificationsData[chromeNotificationId] = cardSet.update( | 362 notificationsData[chromeNotificationId] = cardSet.update( |
365 chromeNotificationId, | 363 chromeNotificationId, |
366 cards[chromeNotificationId], | 364 cards[chromeNotificationId], |
367 notificationGroups, | 365 notificationGroups, |
368 onCardShown); | 366 opt_onCardShown); |
369 } | 367 } |
370 chrome.storage.local.set({notificationsData: notificationsData}); | 368 chrome.storage.local.set({notificationsData: notificationsData}); |
371 onSuccess(); | 369 resolve(); |
370 }); | |
372 }); | 371 }); |
373 } | 372 } |
374 | 373 |
375 /** | 374 /** |
376 * Removes all cards and card state on Google Now close down. | 375 * Removes all cards and card state on Google Now close down. |
377 */ | 376 */ |
378 function removeAllCards() { | 377 function removeAllCards() { |
379 console.log('removeAllCards'); | 378 console.log('removeAllCards'); |
380 | 379 |
381 // TODO(robliao): Once Google Now clears its own checkbox in the | 380 // TODO(robliao): Once Google Now clears its own checkbox in the |
(...skipping 68 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
450 'GoogleNow', function(params) { | 449 'GoogleNow', function(params) { |
451 var optinPollPeriodSeconds = | 450 var optinPollPeriodSeconds = |
452 parseInt(params && params.optinPollPeriodSeconds, 10) || | 451 parseInt(params && params.optinPollPeriodSeconds, 10) || |
453 DEFAULT_OPTIN_CHECK_PERIOD_SECONDS; | 452 DEFAULT_OPTIN_CHECK_PERIOD_SECONDS; |
454 updateCardsAttempts.start(optinPollPeriodSeconds); | 453 updateCardsAttempts.start(optinPollPeriodSeconds); |
455 }); | 454 }); |
456 } | 455 } |
457 } | 456 } |
458 | 457 |
459 /** | 458 /** |
460 * Combines notification groups into a set of Chrome notifications and shows | 459 * Combines notification groups into a set of Chrome notifications. |
461 * them. | |
462 * @param {Object.<string, StoredNotificationGroup>} notificationGroups Map from | 460 * @param {Object.<string, StoredNotificationGroup>} notificationGroups Map from |
463 * group name to group information. | 461 * group name to group information. |
464 * @param {function()} onSuccess Called on success. | 462 * @return {Object.<ChromeNotificationId, CombinedCard>} Cards to show. |
465 * @param {function(ReceivedNotification)=} onCardShown Optional parameter | |
466 * called when each card is shown. | |
467 */ | 463 */ |
468 function combineAndShowNotificationCards( | 464 function combineCardsFromGroups(notificationGroups) { |
469 notificationGroups, onSuccess, onCardShown) { | 465 console.log('combineCardsFromGroups ' + JSON.stringify(notificationGroups)); |
470 console.log('combineAndShowNotificationCards ' + | |
471 JSON.stringify(notificationGroups)); | |
472 /** @type {Object.<ChromeNotificationId, CombinedCard>} */ | 466 /** @type {Object.<ChromeNotificationId, CombinedCard>} */ |
473 var combinedCards = {}; | 467 var combinedCards = {}; |
474 | 468 |
475 for (var groupName in notificationGroups) | 469 for (var groupName in notificationGroups) |
476 combineGroup(combinedCards, notificationGroups[groupName]); | 470 combineGroup(combinedCards, notificationGroups[groupName]); |
477 | 471 |
478 showNotificationCards( | 472 return combinedCards; |
479 notificationGroups, combinedCards, onSuccess, onCardShown); | |
480 } | 473 } |
481 | 474 |
482 /** | 475 /** |
483 * Based on a response from the notification server, shows notifications and | 476 * Processes a server response for consumption by showNotificationGroups. |
484 * schedules next update. | |
485 * @param {ServerResponse} response Server response. | 477 * @param {ServerResponse} response Server response. |
486 * @param {function(ReceivedNotification)=} onCardShown Optional parameter | 478 * @return {Promise} A promise to process the server response and provide |
487 * called when each card is shown. | 479 * updated groups. Rejects if the server response shouldn't be processed. |
488 */ | 480 */ |
489 function processServerResponse(response, onCardShown) { | 481 function processServerResponse(response) { |
490 console.log('processServerResponse ' + JSON.stringify(response)); | 482 console.log('processServerResponse ' + JSON.stringify(response)); |
491 | 483 |
492 if (response.googleNowDisabled) { | 484 if (response.googleNowDisabled) { |
493 chrome.storage.local.set({googleNowEnabled: false}); | 485 chrome.storage.local.set({googleNowEnabled: false}); |
494 // TODO(vadimt): Remove the line below once the server stops sending groups | 486 // TODO(robliao): Remove the line below once the server stops sending groups |
495 // with 'googleNowDisabled' responses. | 487 // with 'googleNowDisabled' responses. |
496 response.groups = {}; | 488 response.groups = {}; |
497 // Google Now was enabled; now it's disabled. This is a state change. | 489 // Google Now was enabled; now it's disabled. This is a state change. |
498 onStateChange(); | 490 onStateChange(); |
491 return Promise.reject(); | |
499 } | 492 } |
500 | 493 |
501 var receivedGroups = response.groups; | 494 var receivedGroups = response.groups; |
502 | 495 |
503 fillFromChromeLocalStorage({ | 496 return fillFromChromeLocalStorage({ |
504 /** @type {Object.<string, StoredNotificationGroup>} */ | 497 /** @type {Object.<string, StoredNotificationGroup>} */ |
505 notificationGroups: {}, | 498 notificationGroups: {}, |
506 /** @type {Object.<NotificationId, number>} */ | 499 /** @type {Object.<NotificationId, number>} */ |
507 recentDismissals: {} | 500 recentDismissals: {} |
508 }).then(function(items) { | 501 }).then(function(items) { |
509 console.log('processServerResponse-get ' + JSON.stringify(items)); | 502 console.log('processServerResponse-get ' + JSON.stringify(items)); |
510 | 503 |
511 // Build a set of non-expired recent dismissals. It will be used for | 504 // Build a set of non-expired recent dismissals. It will be used for |
512 // client-side filtering of cards. | 505 // client-side filtering of cards. |
513 /** @type {Object.<NotificationId, number>} */ | 506 /** @type {Object.<NotificationId, number>} */ |
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
566 // cards updates. | 559 // cards updates. |
567 if (receivedGroup.nextPollSeconds !== undefined) { | 560 if (receivedGroup.nextPollSeconds !== undefined) { |
568 storedGroup.nextPollTime = | 561 storedGroup.nextPollTime = |
569 now + receivedGroup.nextPollSeconds * MS_IN_SECOND; | 562 now + receivedGroup.nextPollSeconds * MS_IN_SECOND; |
570 } | 563 } |
571 | 564 |
572 updatedGroups[groupName] = storedGroup; | 565 updatedGroups[groupName] = storedGroup; |
573 } | 566 } |
574 | 567 |
575 scheduleNextPoll(updatedGroups, !response.googleNowDisabled); | 568 scheduleNextPoll(updatedGroups, !response.googleNowDisabled); |
576 combineAndShowNotificationCards( | 569 return { |
577 updatedGroups, | 570 updatedGroups: updatedGroups, |
578 function() { | 571 recentDismissals: updatedRecentDismissals |
579 chrome.storage.local.set({ | 572 }; |
580 notificationGroups: updatedGroups, | |
581 recentDismissals: updatedRecentDismissals | |
582 }); | |
583 recordEvent(GoogleNowEvent.CARDS_PARSE_SUCCESS); | |
584 }, | |
585 onCardShown); | |
586 }); | 573 }); |
587 } | 574 } |
588 | 575 |
589 /** | 576 /** |
590 * Update the Explanatory Total Cards Shown Count. | 577 * Update the Explanatory Total Cards Shown Count. |
591 */ | 578 */ |
592 function countExplanatoryCard() { | 579 function countExplanatoryCard() { |
593 localStorage['explanatoryCardsShown']++; | 580 localStorage['explanatoryCardsShown']++; |
594 } | 581 } |
595 | 582 |
596 /** | 583 /** |
584 * Determines if cards should have an explanation link. | |
585 * @return {boolean} true if an explanatory card should be shown. | |
586 */ | |
587 function shouldShowExplanatoryCard() { | |
588 var isBelowThreshold = | |
589 localStorage['explanatoryCardsShown'] < EXPLANATORY_CARDS_LINK_THRESHOLD; | |
590 return isBelowThreshold; | |
591 } | |
592 | |
593 /** | |
597 * Requests notification cards from the server for specified groups. | 594 * Requests notification cards from the server for specified groups. |
598 * @param {Array.<string>} groupNames Names of groups that need to be refreshed. | 595 * @param {Array.<string>} groupNames Names of groups that need to be refreshed. |
596 * @return {Promise} A promise to request the specified notification groups. | |
599 */ | 597 */ |
600 function requestNotificationGroups(groupNames) { | 598 function requestNotificationGroupsFromServer(groupNames) { |
601 console.log('requestNotificationGroups from ' + NOTIFICATION_CARDS_URL + | 599 console.log( |
600 'requestNotificationGroupsFromServer from ' + NOTIFICATION_CARDS_URL + | |
602 ', groupNames=' + JSON.stringify(groupNames)); | 601 ', groupNames=' + JSON.stringify(groupNames)); |
603 | 602 |
604 recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL); | 603 recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL); |
605 | 604 |
606 var requestParameters = '?timeZoneOffsetMs=' + | 605 var requestParameters = '?timeZoneOffsetMs=' + |
607 (-new Date().getTimezoneOffset() * MS_IN_MINUTE); | 606 (-new Date().getTimezoneOffset() * MS_IN_MINUTE); |
608 | 607 |
609 var cardShownCallback = undefined; | 608 if (shouldShowExplanatoryCard()) { |
610 var belowExplanatoryThreshold = | |
611 localStorage['explanatoryCardsShown'] < EXPLANATORY_CARDS_LINK_THRESHOLD; | |
612 if (belowExplanatoryThreshold) { | |
613 requestParameters += '&cardExplanation=true'; | 609 requestParameters += '&cardExplanation=true'; |
614 cardShownCallback = countExplanatoryCard; | |
615 } | 610 } |
616 | 611 |
617 groupNames.forEach(function(groupName) { | 612 groupNames.forEach(function(groupName) { |
618 requestParameters += ('&requestTypes=' + groupName); | 613 requestParameters += ('&requestTypes=' + groupName); |
619 }); | 614 }); |
620 | 615 |
621 requestParameters += '&uiLocale=' + navigator.language; | 616 requestParameters += '&uiLocale=' + navigator.language; |
622 | 617 |
623 console.log('requestNotificationGroups: request=' + requestParameters); | 618 console.log( |
619 'requestNotificationGroupsFromServer: request=' + requestParameters); | |
624 | 620 |
625 requestFromServer('GET', 'notifications' + requestParameters).then( | 621 return requestFromServer('GET', 'notifications' + requestParameters).then( |
626 function(request) { | 622 function(request) { |
627 console.log('requestNotificationGroups-received ' + request.status); | 623 console.log( |
624 'requestNotificationGroupsFromServer-received ' + request.status); | |
628 if (request.status == HTTP_OK) { | 625 if (request.status == HTTP_OK) { |
629 recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS); | 626 recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS); |
630 processServerResponse( | 627 return JSON.parse(request.responseText); |
631 JSON.parse(request.responseText), cardShownCallback); | |
632 } | 628 } |
633 }); | 629 }); |
634 } | 630 } |
635 | 631 |
636 /** | 632 /** |
637 * Requests the account opted-in state from the server. | 633 * Requests the account opted-in state from the server and updates any |
638 * @param {function()} optedInCallback Function that will be called if | 634 * state as necessary. |
639 * opted-in state is 'true'. | 635 * @return {Promise} A promise to request and update the opted-in state. |
636 * The promise resolves if the opt-in state is true. | |
640 */ | 637 */ |
641 function requestOptedIn(optedInCallback) { | 638 function requestAndUpdateOptedIn() { |
642 console.log('requestOptedIn from ' + NOTIFICATION_CARDS_URL); | 639 console.log('requestOptedIn from ' + NOTIFICATION_CARDS_URL); |
643 | 640 |
644 requestFromServer('GET', 'settings/optin').then(function(request) { | 641 return requestFromServer('GET', 'settings/optin').then(function(request) { |
645 console.log( | 642 console.log( |
646 'requestOptedIn-received ' + request.status + ' ' + request.response); | 643 'requestOptedIn-received ' + request.status + ' ' + request.response); |
647 if (request.status == HTTP_OK) { | 644 if (request.status == HTTP_OK) { |
648 var parsedResponse = JSON.parse(request.responseText); | 645 var parsedResponse = JSON.parse(request.responseText); |
649 if (parsedResponse.value) { | 646 return parsedResponse.value; |
650 chrome.storage.local.set({googleNowEnabled: true}); | 647 } else { |
651 optedInCallback(); | 648 return Promise.reject(); |
652 // Google Now was disabled, now it's enabled. This is a state change. | 649 } |
653 onStateChange(); | 650 }).then(function(optedIn) { |
654 } else { | 651 if (optedIn) { |
655 scheduleNextPoll({}, false); | 652 chrome.storage.local.set({googleNowEnabled: true}); |
656 } | 653 // Google Now was disabled, now it's enabled. This is a state change. |
654 onStateChange(); | |
655 return Promise.resolve(); | |
656 } else { | |
657 scheduleNextPoll({}, false); | |
658 return Promise.reject(); | |
657 } | 659 } |
658 }); | 660 }); |
659 } | 661 } |
660 | 662 |
661 /** | 663 /** |
662 * Requests notification cards from the server. | 664 * Determines the groups that need to be requested right now. |
665 * @return {Promise} A promise to determine the groups to request. | |
663 */ | 666 */ |
664 function requestNotificationCards() { | 667 function getGroupsToRequest() { |
665 console.log('requestNotificationCards'); | 668 return fillFromChromeLocalStorage({ |
666 | |
667 fillFromChromeLocalStorage({ | |
668 /** @type {Object.<string, StoredNotificationGroup>} */ | 669 /** @type {Object.<string, StoredNotificationGroup>} */ |
669 notificationGroups: {}, | 670 notificationGroups: {} |
670 googleNowEnabled: false | |
671 }).then(function(items) { | 671 }).then(function(items) { |
672 console.log( | 672 console.log('getGroupsToRequest-storage-get ' + JSON.stringify(items)); |
673 'requestNotificationCards-storage-get ' + JSON.stringify(items)); | |
674 | |
675 var groupsToRequest = []; | 673 var groupsToRequest = []; |
676 | |
677 var now = Date.now(); | 674 var now = Date.now(); |
678 | 675 |
679 for (var groupName in items.notificationGroups) { | 676 for (var groupName in items.notificationGroups) { |
680 var group = items.notificationGroups[groupName]; | 677 var group = items.notificationGroups[groupName]; |
681 if (group.nextPollTime !== undefined && group.nextPollTime <= now) | 678 if (group.nextPollTime !== undefined && group.nextPollTime <= now) |
682 groupsToRequest.push(groupName); | 679 groupsToRequest.push(groupName); |
683 } | 680 } |
684 | 681 return groupsToRequest; |
685 if (items.googleNowEnabled) { | |
686 requestNotificationGroups(groupsToRequest); | |
687 } else { | |
688 requestOptedIn(function() { | |
689 requestNotificationGroups(groupsToRequest); | |
690 }); | |
691 } | |
692 }); | 682 }); |
693 } | 683 } |
694 | 684 |
695 /** | 685 /** |
686 * Requests notification cards from the server. | |
687 * @return {Promise} A promise to request the notification cards. | |
688 * Rejects if the cards won't be requested. | |
689 */ | |
690 function requestNotificationCards() { | |
691 console.log('requestNotificationCards'); | |
692 | |
693 return isGoogleNowEnabled() | |
694 .then(function(googleNowEnabled) { | |
695 return googleNowEnabled ? Promise.resolve() : requestAndUpdateOptedIn(); | |
rgustafson
2014/04/02 18:14:06
[no action] didn't have to resort to variable rena
| |
696 }) | |
697 .then(getGroupsToRequest) | |
698 .then(requestNotificationGroupsFromServer) | |
699 .then(processServerResponse) | |
700 .then(function(processedResponse) { | |
701 var onCardShown = | |
702 shouldShowExplanatoryCard() ? countExplanatoryCard : undefined; | |
703 return showNotificationGroups( | |
704 processedResponse.updatedGroups, onCardShown).then(function() { | |
705 chrome.storage.local.set({ | |
706 notificationGroups: processedResponse.updatedGroups, | |
707 recentDismissals: processedResponse.updatedRecentDismissals | |
708 }); | |
709 recordEvent(GoogleNowEvent.CARDS_PARSE_SUCCESS); | |
710 } | |
711 ); | |
712 }); | |
713 } | |
714 | |
715 /** | |
696 * Requests and shows notification cards. | 716 * Requests and shows notification cards. |
697 */ | 717 */ |
698 function requestCards() { | 718 function requestCards() { |
699 console.log('requestCards @' + new Date()); | 719 console.log('requestCards @' + new Date()); |
700 // LOCATION_REQUEST is a legacy histogram value when we requested location. | 720 // LOCATION_REQUEST is a legacy histogram value when we requested location. |
701 // This corresponds to the extension attempting to request for cards. | 721 // This corresponds to the extension attempting to request for cards. |
702 // We're keeping the name the same to keep our histograms in order. | 722 // We're keeping the name the same to keep our histograms in order. |
703 recordEvent(GoogleNowEvent.LOCATION_REQUEST); | 723 recordEvent(GoogleNowEvent.LOCATION_REQUEST); |
704 tasks.add(UPDATE_CARDS_TASK_NAME, function() { | 724 tasks.add(UPDATE_CARDS_TASK_NAME, function() { |
705 console.log('requestCards-task-begin'); | 725 console.log('requestCards-task-begin'); |
(...skipping 219 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
925 } | 945 } |
926 | 946 |
927 /** | 947 /** |
928 * Initializes the polling system to start fetching cards. | 948 * Initializes the polling system to start fetching cards. |
929 */ | 949 */ |
930 function startPollingCards() { | 950 function startPollingCards() { |
931 console.log('startPollingCards'); | 951 console.log('startPollingCards'); |
932 // Create an update timer for a case when for some reason requesting | 952 // Create an update timer for a case when for some reason requesting |
933 // cards gets stuck. | 953 // cards gets stuck. |
934 updateCardsAttempts.start(MAXIMUM_POLLING_PERIOD_SECONDS); | 954 updateCardsAttempts.start(MAXIMUM_POLLING_PERIOD_SECONDS); |
935 | |
936 requestCards(); | 955 requestCards(); |
937 } | 956 } |
938 | 957 |
939 /** | 958 /** |
940 * Stops all machinery in the polling system. | 959 * Stops all machinery in the polling system. |
941 */ | 960 */ |
942 function stopPollingCards() { | 961 function stopPollingCards() { |
943 console.log('stopPollingCards'); | 962 console.log('stopPollingCards'); |
944 updateCardsAttempts.stop(); | 963 updateCardsAttempts.stop(); |
945 removeAllCards(); | 964 removeAllCards(); |
946 // Mark the Google Now as disabled to start with checking the opt-in state | 965 // Since we're stopping everything, clear all storage too. |
947 // next time startPollingCards() is called. | 966 chrome.storage.local.clear(); |
948 chrome.storage.local.set({googleNowEnabled: false}); | |
949 } | 967 } |
950 | 968 |
951 /** | 969 /** |
952 * Initializes the event page on install or on browser startup. | 970 * Initializes the event page on install or on browser startup. |
953 */ | 971 */ |
954 function initialize() { | 972 function initialize() { |
955 recordEvent(GoogleNowEvent.EXTENSION_START); | 973 recordEvent(GoogleNowEvent.EXTENSION_START); |
956 onStateChange(); | 974 onStateChange(); |
957 } | 975 } |
958 | 976 |
(...skipping 162 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1121 */ | 1139 */ |
1122 function pollOptedIn() { | 1140 function pollOptedIn() { |
1123 /** | 1141 /** |
1124 * Cleans up any state used to recheck the opt-in poll. | 1142 * Cleans up any state used to recheck the opt-in poll. |
1125 */ | 1143 */ |
1126 function clearPollingState() { | 1144 function clearPollingState() { |
1127 localStorage.removeItem('optedInCheckCount'); | 1145 localStorage.removeItem('optedInCheckCount'); |
1128 optInCheckAttempts.stop(); | 1146 optInCheckAttempts.stop(); |
1129 } | 1147 } |
1130 | 1148 |
1131 /** | |
1132 * Performs the actual work for checking the opt-in state and requesting cards | |
1133 * on opted-in. | |
1134 */ | |
1135 function checkOptedIn() { | |
1136 // Limit retries to 5. | |
1137 if (localStorage.optedInCheckCount < 5) { | |
1138 console.log(new Date() + | |
1139 ' checkOptedIn Attempt ' + localStorage.optedInCheckCount); | |
1140 localStorage.optedInCheckCount++; | |
1141 requestOptedIn(function() { | |
1142 clearPollingState(); | |
1143 requestCards(); | |
1144 }); | |
1145 } else { | |
1146 clearPollingState(); | |
1147 } | |
1148 } | |
1149 | |
1150 if (localStorage.optedInCheckCount === undefined) { | 1149 if (localStorage.optedInCheckCount === undefined) { |
1151 localStorage.optedInCheckCount = 0; | 1150 localStorage.optedInCheckCount = 0; |
1152 optInCheckAttempts.start(); | 1151 optInCheckAttempts.start(); |
1153 checkOptedIn(); | |
1154 } else { | |
1155 optInCheckAttempts.planForNext(checkOptedIn); | |
1156 } | 1152 } |
1153 | |
1154 console.log(new Date() + | |
1155 ' checkOptedIn Attempt ' + localStorage.optedInCheckCount); | |
1156 | |
1157 requestAndUpdateOptedIn().then(function() { | |
1158 clearPollingState(); | |
1159 requestCards(); | |
1160 }).catch(function() { | |
1161 if (localStorage.optedInCheckCount < 5) { | |
1162 localStorage.optedInCheckCount++; | |
1163 optInCheckAttempts.planForNext(function() {}); | |
1164 } else { | |
1165 clearPollingState(); | |
1166 } | |
1167 }); | |
1157 } | 1168 } |
1158 | 1169 |
1159 instrumented.runtime.onInstalled.addListener(function(details) { | 1170 instrumented.runtime.onInstalled.addListener(function(details) { |
1160 console.log('onInstalled ' + JSON.stringify(details)); | 1171 console.log('onInstalled ' + JSON.stringify(details)); |
1161 if (details.reason != 'chrome_update') { | 1172 if (details.reason != 'chrome_update') { |
1162 initialize(); | 1173 initialize(); |
1163 } | 1174 } |
1164 }); | 1175 }); |
1165 | 1176 |
1166 instrumented.runtime.onStartup.addListener(function() { | 1177 instrumented.runtime.onStartup.addListener(function() { |
1167 console.log('onStartup'); | 1178 console.log('onStartup'); |
1168 | 1179 |
1169 // Show notifications received by earlier polls. Doing this as early as | 1180 // Show notifications received by earlier polls. Doing this as early as |
1170 // possible to reduce latency of showing first notifications. This mimics how | 1181 // possible to reduce latency of showing first notifications. This mimics how |
1171 // persistent notifications will work. | 1182 // persistent notifications will work. |
1172 tasks.add(SHOW_ON_START_TASK_NAME, function() { | 1183 tasks.add(SHOW_ON_START_TASK_NAME, function() { |
1173 fillFromChromeLocalStorage({ | 1184 fillFromChromeLocalStorage({ |
1174 /** @type {Object.<string, StoredNotificationGroup>} */ | 1185 /** @type {Object.<string, StoredNotificationGroup>} */ |
1175 notificationGroups: {} | 1186 notificationGroups: {} |
1176 }).then(function(items) { | 1187 }).then(function(items) { |
1177 console.log('onStartup-get ' + JSON.stringify(items)); | 1188 console.log('onStartup-get ' + JSON.stringify(items)); |
1178 | 1189 |
1179 combineAndShowNotificationCards(items.notificationGroups, function() { | 1190 showNotificationGroups(items.notificationGroups).then(function() { |
1180 chrome.storage.local.set(items); | 1191 chrome.storage.local.set(items); |
1181 }); | 1192 }); |
1182 }); | 1193 }); |
1183 }); | 1194 }); |
1184 | 1195 |
1185 initialize(); | 1196 initialize(); |
1186 }); | 1197 }); |
1187 | 1198 |
1188 authenticationManager.addListener(function() { | 1199 authenticationManager.addListener(function() { |
1189 console.log('signIn State Change'); | 1200 console.log('signIn State Change'); |
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1261 lastPollNowPayloads: items.lastPollNowPayloads, | 1272 lastPollNowPayloads: items.lastPollNowPayloads, |
1262 notificationGroups: items.notificationGroups | 1273 notificationGroups: items.notificationGroups |
1263 }); | 1274 }); |
1264 | 1275 |
1265 pollOptedIn(); | 1276 pollOptedIn(); |
1266 } | 1277 } |
1267 }); | 1278 }); |
1268 }); | 1279 }); |
1269 } | 1280 } |
1270 }); | 1281 }); |
OLD | NEW |