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

Unified Diff: chrome/browser/resources/google_now/background.js

Issue 2617663002: WIP: run clang-format-js on lots of things (Closed)
Patch Set: merge Created 3 years, 11 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 side-by-side diff with in-line comments
Download patch
Index: chrome/browser/resources/google_now/background.js
diff --git a/chrome/browser/resources/google_now/background.js b/chrome/browser/resources/google_now/background.js
index b0bda7a6aca535d65116893299230e2eac89cea4..780c2a9f4d3dbff6e3a9198255c182fae5c13f0b 100644
--- a/chrome/browser/resources/google_now/background.js
+++ b/chrome/browser/resources/google_now/background.js
@@ -76,7 +76,7 @@ var MAXIMUM_RETRY_DISMISS_PERIOD_SECONDS = 60 * 60; // 1 hour
/**
* Time we keep retrying dismissals.
*/
-var MAXIMUM_DISMISSAL_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
+var MAXIMUM_DISMISSAL_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
/**
* Time we keep dismissals after successful server dismiss requests.
@@ -86,7 +86,7 @@ var DISMISS_RETENTION_TIME_MS = 20 * 60 * 1000; // 20 minutes
/**
* Default period for checking whether the user is opted in to Google Now.
*/
-var DEFAULT_OPTIN_CHECK_PERIOD_SECONDS = 60 * 60 * 24 * 7; // 1 week
+var DEFAULT_OPTIN_CHECK_PERIOD_SECONDS = 60 * 60 * 24 * 7; // 1 week
/**
* URL to open when the user clicked on a link for the our notification
@@ -224,24 +224,16 @@ wrapper.instrumentChromeApiFunction('storage.onChanged.addListener', 0);
wrapper.instrumentChromeApiFunction('tabs.create', 1);
var updateCardsAttempts = buildAttemptManager(
- 'cards-update',
- requestCards,
- INITIAL_POLLING_PERIOD_SECONDS,
+ 'cards-update', requestCards, INITIAL_POLLING_PERIOD_SECONDS,
MAXIMUM_POLLING_PERIOD_SECONDS);
var optInPollAttempts = buildAttemptManager(
- 'optin',
- pollOptedInNoImmediateRecheck,
- INITIAL_POLLING_PERIOD_SECONDS,
+ 'optin', pollOptedInNoImmediateRecheck, INITIAL_POLLING_PERIOD_SECONDS,
MAXIMUM_POLLING_PERIOD_SECONDS);
var optInRecheckAttempts = buildAttemptManager(
- 'optin-recheck',
- pollOptedInWithRecheck,
- INITIAL_OPTIN_RECHECK_PERIOD_SECONDS,
- MAXIMUM_OPTIN_RECHECK_PERIOD_SECONDS);
+ 'optin-recheck', pollOptedInWithRecheck,
+ INITIAL_OPTIN_RECHECK_PERIOD_SECONDS, MAXIMUM_OPTIN_RECHECK_PERIOD_SECONDS);
var dismissalAttempts = buildAttemptManager(
- 'dismiss',
- retryPendingDismissals,
- INITIAL_RETRY_DISMISS_PERIOD_SECONDS,
+ 'dismiss', retryPendingDismissals, INITIAL_RETRY_DISMISS_PERIOD_SECONDS,
MAXIMUM_RETRY_DISMISS_PERIOD_SECONDS);
var cardSet = buildCardSet();
@@ -368,8 +360,8 @@ function showNotificationGroups(notificationGroups, opt_onCardShown) {
return new Promise(function(resolve) {
instrumented.notifications.getAll(function(notifications) {
- console.log('showNotificationGroups-getAll ' +
- JSON.stringify(notifications));
+ console.log(
+ 'showNotificationGroups-getAll ' + JSON.stringify(notifications));
notifications = notifications || {};
// Mark notifications that didn't receive an update as having received
@@ -384,10 +376,8 @@ function showNotificationGroups(notificationGroups, opt_onCardShown) {
// Create/update/delete notifications.
for (var chromeNotificationId in cards) {
notificationsData[chromeNotificationId] = cardSet.update(
- chromeNotificationId,
- cards[chromeNotificationId],
- notificationGroups,
- opt_onCardShown);
+ chromeNotificationId, cards[chromeNotificationId],
+ notificationGroups, opt_onCardShown);
}
chrome.storage.local.set({notificationsData: notificationsData});
resolve();
@@ -430,10 +420,10 @@ function combineGroup(combinedCards, storedGroup) {
var uncombinedNotification = {
receivedNotification: receivedNotification,
showTime: receivedNotification.trigger.showTimeSec &&
- (storedGroup.cardsTimestamp +
- receivedNotification.trigger.showTimeSec * MS_IN_SECOND),
+ (storedGroup.cardsTimestamp +
+ receivedNotification.trigger.showTimeSec * MS_IN_SECOND),
hideTime: storedGroup.cardsTimestamp +
- receivedNotification.trigger.hideTimeSec * MS_IN_SECOND
+ receivedNotification.trigger.hideTimeSec * MS_IN_SECOND
};
var combinedCard =
@@ -456,7 +446,8 @@ function calculateNextPollTimeMilliseconds(groups) {
var group = groups[groupName];
if (group.nextPollTime !== undefined) {
nextPollTime = nextPollTime == null ?
- group.nextPollTime : Math.min(group.nextPollTime, nextPollTime);
+ group.nextPollTime :
+ Math.min(group.nextPollTime, nextPollTime);
}
}
@@ -483,8 +474,7 @@ function scheduleNextCardsPoll(groups) {
* Schedules the next opt-in check poll.
*/
function scheduleOptInCheckPoll() {
- instrumented.metricsPrivate.getVariationParams(
- 'GoogleNow', function(params) {
+ instrumented.metricsPrivate.getVariationParams('GoogleNow', function(params) {
var optinPollPeriodSeconds =
parseInt(params && params.optinPollPeriodSeconds, 10) ||
DEFAULT_OPTIN_CHECK_PERIOD_SECONDS;
@@ -527,83 +517,84 @@ function processServerResponse(response) {
var receivedGroups = response.groups;
return fillFromChromeLocalStorage({
- /** @type {Object<StoredNotificationGroup>} */
- notificationGroups: {},
- /** @type {Object<ServerNotificationId, number>} */
- recentDismissals: {}
- }).then(function(items) {
- console.log('processServerResponse-get ' + JSON.stringify(items));
-
- // Build a set of non-expired recent dismissals. It will be used for
- // client-side filtering of cards.
- /** @type {Object<ServerNotificationId, number>} */
- var updatedRecentDismissals = {};
- var now = Date.now();
- for (var serverNotificationId in items.recentDismissals) {
- var dismissalAge = now - items.recentDismissals[serverNotificationId];
- if (dismissalAge < DISMISS_RETENTION_TIME_MS) {
- updatedRecentDismissals[serverNotificationId] =
- items.recentDismissals[serverNotificationId];
- }
- }
+ /** @type {Object<StoredNotificationGroup>} */
+ notificationGroups: {},
+ /** @type {Object<ServerNotificationId, number>} */
+ recentDismissals: {}
+ })
+ .then(function(items) {
+ console.log('processServerResponse-get ' + JSON.stringify(items));
+
+ // Build a set of non-expired recent dismissals. It will be used for
+ // client-side filtering of cards.
+ /** @type {Object<ServerNotificationId, number>} */
+ var updatedRecentDismissals = {};
+ var now = Date.now();
+ for (var serverNotificationId in items.recentDismissals) {
+ var dismissalAge = now - items.recentDismissals[serverNotificationId];
+ if (dismissalAge < DISMISS_RETENTION_TIME_MS) {
+ updatedRecentDismissals[serverNotificationId] =
+ items.recentDismissals[serverNotificationId];
+ }
+ }
- // Populate groups with corresponding cards.
- if (response.notifications) {
- for (var i = 0; i < response.notifications.length; ++i) {
- /** @type {ReceivedNotification} */
- var card = response.notifications[i];
- if (!(card.notificationId in updatedRecentDismissals)) {
- var group = receivedGroups[card.groupName];
- group.cards = group.cards || [];
- group.cards.push(card);
+ // Populate groups with corresponding cards.
+ if (response.notifications) {
+ for (var i = 0; i < response.notifications.length; ++i) {
+ /** @type {ReceivedNotification} */
+ var card = response.notifications[i];
+ if (!(card.notificationId in updatedRecentDismissals)) {
+ var group = receivedGroups[card.groupName];
+ group.cards = group.cards || [];
+ group.cards.push(card);
+ }
+ }
}
- }
- }
- // Build updated set of groups.
- var updatedGroups = {};
-
- for (var groupName in receivedGroups) {
- var receivedGroup = receivedGroups[groupName];
- var storedGroup = items.notificationGroups[groupName] || {
- cards: [],
- cardsTimestamp: undefined,
- nextPollTime: undefined,
- rank: undefined
- };
-
- if (receivedGroup.requested)
- receivedGroup.cards = receivedGroup.cards || [];
-
- if (receivedGroup.cards) {
- // If the group contains a cards update, all its fields will get new
- // values.
- storedGroup.cards = receivedGroup.cards;
- storedGroup.cardsTimestamp = now;
- storedGroup.rank = receivedGroup.rank;
- storedGroup.nextPollTime = undefined;
- // The code below assigns nextPollTime a defined value if
- // nextPollSeconds is specified in the received group.
- // If the group's cards are not updated, and nextPollSeconds is
- // unspecified, this method doesn't change group's nextPollTime.
- }
+ // Build updated set of groups.
+ var updatedGroups = {};
- // 'nextPollSeconds' may be sent even for groups that don't contain
- // cards updates.
- if (receivedGroup.nextPollSeconds !== undefined) {
- storedGroup.nextPollTime =
- now + receivedGroup.nextPollSeconds * MS_IN_SECOND;
- }
+ for (var groupName in receivedGroups) {
+ var receivedGroup = receivedGroups[groupName];
+ var storedGroup = items.notificationGroups[groupName] || {
+ cards: [],
+ cardsTimestamp: undefined,
+ nextPollTime: undefined,
+ rank: undefined
+ };
- updatedGroups[groupName] = storedGroup;
- }
+ if (receivedGroup.requested)
+ receivedGroup.cards = receivedGroup.cards || [];
+
+ if (receivedGroup.cards) {
+ // If the group contains a cards update, all its fields will get new
+ // values.
+ storedGroup.cards = receivedGroup.cards;
+ storedGroup.cardsTimestamp = now;
+ storedGroup.rank = receivedGroup.rank;
+ storedGroup.nextPollTime = undefined;
+ // The code below assigns nextPollTime a defined value if
+ // nextPollSeconds is specified in the received group.
+ // If the group's cards are not updated, and nextPollSeconds is
+ // unspecified, this method doesn't change group's nextPollTime.
+ }
+
+ // 'nextPollSeconds' may be sent even for groups that don't contain
+ // cards updates.
+ if (receivedGroup.nextPollSeconds !== undefined) {
+ storedGroup.nextPollTime =
+ now + receivedGroup.nextPollSeconds * MS_IN_SECOND;
+ }
+
+ updatedGroups[groupName] = storedGroup;
+ }
- scheduleNextCardsPoll(updatedGroups);
- return {
- updatedGroups: updatedGroups,
- recentDismissals: updatedRecentDismissals
- };
- });
+ scheduleNextCardsPoll(updatedGroups);
+ return {
+ updatedGroups: updatedGroups,
+ recentDismissals: updatedRecentDismissals
+ };
+ });
}
/**
@@ -635,8 +626,8 @@ function requestNotificationGroupsFromServer(groupNames) {
recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL);
- var requestParameters = '?timeZoneOffsetMs=' +
- (-new Date().getTimezoneOffset() * MS_IN_MINUTE);
+ var requestParameters =
+ '?timeZoneOffsetMs=' + (-new Date().getTimezoneOffset() * MS_IN_MINUTE);
if (shouldShowExplanatoryCard()) {
requestParameters += '&cardExplanation=true';
@@ -651,15 +642,15 @@ function requestNotificationGroupsFromServer(groupNames) {
console.log(
'requestNotificationGroupsFromServer: request=' + requestParameters);
- return requestFromServer('GET', 'notifications' + requestParameters).then(
- function(request) {
- console.log(
- 'requestNotificationGroupsFromServer-received ' + request.status);
- if (request.status == HTTP_OK) {
- recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
- return JSON.parse(request.responseText);
- }
- });
+ return requestFromServer('GET', 'notifications' + requestParameters)
+ .then(function(request) {
+ console.log(
+ 'requestNotificationGroupsFromServer-received ' + request.status);
+ if (request.status == HTTP_OK) {
+ recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
+ return JSON.parse(request.responseText);
+ }
+ });
}
/**
@@ -688,17 +679,20 @@ function pollOptedInNoImmediateRecheck() {
function requestAndUpdateOptedIn() {
console.log('requestOptedIn from ' + NOTIFICATION_CARDS_URL);
- return requestFromServer('GET', 'settings/optin').then(function(request) {
- console.log(
- 'requestOptedIn-received ' + request.status + ' ' + request.response);
- if (request.status == HTTP_OK) {
- var parsedResponse = JSON.parse(request.responseText);
- return parsedResponse.value;
- }
- }).then(function(optedIn) {
- chrome.storage.local.set({googleNowEnabled: optedIn});
- return optedIn;
- });
+ return requestFromServer('GET', 'settings/optin')
+ .then(function(request) {
+ console.log(
+ 'requestOptedIn-received ' + request.status + ' ' +
+ request.response);
+ if (request.status == HTTP_OK) {
+ var parsedResponse = JSON.parse(request.responseText);
+ return parsedResponse.value;
+ }
+ })
+ .then(function(optedIn) {
+ chrome.storage.local.set({googleNowEnabled: optedIn});
+ return optedIn;
+ });
}
/**
@@ -707,20 +701,21 @@ function requestAndUpdateOptedIn() {
*/
function getGroupsToRequest() {
return fillFromChromeLocalStorage({
- /** @type {Object<StoredNotificationGroup>} */
- notificationGroups: {}
- }).then(function(items) {
- console.log('getGroupsToRequest-storage-get ' + JSON.stringify(items));
- var groupsToRequest = [];
- var now = Date.now();
-
- for (var groupName in items.notificationGroups) {
- var group = items.notificationGroups[groupName];
- if (group.nextPollTime !== undefined && group.nextPollTime <= now)
- groupsToRequest.push(groupName);
- }
- return groupsToRequest;
- });
+ /** @type {Object<StoredNotificationGroup>} */
+ notificationGroups: {}
+ })
+ .then(function(items) {
+ console.log('getGroupsToRequest-storage-get ' + JSON.stringify(items));
+ var groupsToRequest = [];
+ var now = Date.now();
+
+ for (var groupName in items.notificationGroups) {
+ var group = items.notificationGroups[groupName];
+ if (group.nextPollTime !== undefined && group.nextPollTime <= now)
+ groupsToRequest.push(groupName);
+ }
+ return groupsToRequest;
+ });
}
/**
@@ -737,14 +732,14 @@ function requestNotificationCards() {
var onCardShown =
shouldShowExplanatoryCard() ? countExplanatoryCard : undefined;
return showNotificationGroups(
- processedResponse.updatedGroups, onCardShown).then(function() {
+ processedResponse.updatedGroups, onCardShown)
+ .then(function() {
chrome.storage.local.set({
notificationGroups: processedResponse.updatedGroups,
recentDismissals: processedResponse.updatedRecentDismissals
});
recordEvent(GoogleNowEvent.CARDS_PARSE_SUCCESS);
- }
- );
+ });
});
}
@@ -798,9 +793,10 @@ function requestCards() {
*/
function requestCardDismissal(
chromeNotificationId, dismissalTimeMs, dismissalData) {
- console.log('requestDismissingCard ' + chromeNotificationId +
- ' from ' + NOTIFICATION_CARDS_URL +
- ', dismissalData=' + JSON.stringify(dismissalData));
+ console.log(
+ 'requestDismissingCard ' + chromeNotificationId + ' from ' +
+ NOTIFICATION_CARDS_URL + ', dismissalData=' +
+ JSON.stringify(dismissalData));
var dismissalAge = Date.now() - dismissalTimeMs;
@@ -811,32 +807,32 @@ function requestCardDismissal(
recordEvent(GoogleNowEvent.DISMISS_REQUEST_TOTAL);
var requestParameters = 'notifications/' + dismissalData.notificationId +
- '?age=' + dismissalAge +
- '&chromeNotificationId=' + chromeNotificationId;
+ '?age=' + dismissalAge + '&chromeNotificationId=' + chromeNotificationId;
for (var paramField in dismissalData.parameters)
- requestParameters += ('&' + paramField +
- '=' + dismissalData.parameters[paramField]);
+ requestParameters +=
+ ('&' + paramField + '=' + dismissalData.parameters[paramField]);
console.log('requestCardDismissal: requestParameters=' + requestParameters);
- return requestFromServer('DELETE', requestParameters).then(function(request) {
- console.log('requestDismissingCard-onloadend ' + request.status);
- if (request.status == HTTP_NOCONTENT)
- recordEvent(GoogleNowEvent.DISMISS_REQUEST_SUCCESS);
-
- // A dismissal doesn't require further retries if it was successful or
- // doesn't have a chance for successful completion.
- return (request.status == HTTP_NOCONTENT) ?
- Promise.resolve() :
- Promise.reject();
- }).catch(function(request) {
- request = (typeof request === 'object') ? request : {};
- return (request.status == HTTP_BAD_REQUEST ||
- request.status == HTTP_METHOD_NOT_ALLOWED) ?
- Promise.resolve() :
- Promise.reject();
- });
+ return requestFromServer('DELETE', requestParameters)
+ .then(function(request) {
+ console.log('requestDismissingCard-onloadend ' + request.status);
+ if (request.status == HTTP_NOCONTENT)
+ recordEvent(GoogleNowEvent.DISMISS_REQUEST_SUCCESS);
+
+ // A dismissal doesn't require further retries if it was successful or
+ // doesn't have a chance for successful completion.
+ return (request.status == HTTP_NOCONTENT) ? Promise.resolve() :
+ Promise.reject();
+ })
+ .catch(function(request) {
+ request = (typeof request === 'object') ? request : {};
+ return (request.status == HTTP_BAD_REQUEST ||
+ request.status == HTTP_METHOD_NOT_ALLOWED) ?
+ Promise.resolve() :
+ Promise.reject();
+ });
}
/**
@@ -846,52 +842,54 @@ function requestCardDismissal(
*/
function processPendingDismissals() {
return fillFromChromeLocalStorage({
- /** @type {Array<PendingDismissal>} */
- pendingDismissals: [],
- /** @type {Object<ServerNotificationId, number>} */
- recentDismissals: {}
- }).then(function(items) {
- console.log(
- 'processPendingDismissals-storage-get ' + JSON.stringify(items));
+ /** @type {Array<PendingDismissal>} */
+ pendingDismissals: [],
+ /** @type {Object<ServerNotificationId, number>} */
+ recentDismissals: {}
+ })
+ .then(function(items) {
+ console.log(
+ 'processPendingDismissals-storage-get ' + JSON.stringify(items));
- var dismissalsChanged = false;
+ var dismissalsChanged = false;
- function onFinish(success) {
- if (dismissalsChanged) {
- chrome.storage.local.set({
- pendingDismissals: items.pendingDismissals,
- recentDismissals: items.recentDismissals
- });
- }
- return success ? Promise.resolve() : Promise.reject();
- }
-
- function doProcessDismissals() {
- if (items.pendingDismissals.length == 0) {
- dismissalAttempts.stop();
- return onFinish(true);
- }
+ function onFinish(success) {
+ if (dismissalsChanged) {
+ chrome.storage.local.set({
+ pendingDismissals: items.pendingDismissals,
+ recentDismissals: items.recentDismissals
+ });
+ }
+ return success ? Promise.resolve() : Promise.reject();
+ }
- // Send dismissal for the first card, and if successful, repeat
- // recursively with the rest.
- /** @type {PendingDismissal} */
- var dismissal = items.pendingDismissals[0];
- return requestCardDismissal(
- dismissal.chromeNotificationId,
- dismissal.time,
- dismissal.dismissalData).then(function() {
- dismissalsChanged = true;
- items.pendingDismissals.splice(0, 1);
- items.recentDismissals[dismissal.dismissalData.notificationId] =
- Date.now();
- return doProcessDismissals();
- }).catch(function() {
- return onFinish(false);
- });
- }
+ function doProcessDismissals() {
+ if (items.pendingDismissals.length == 0) {
+ dismissalAttempts.stop();
+ return onFinish(true);
+ }
+
+ // Send dismissal for the first card, and if successful, repeat
+ // recursively with the rest.
+ /** @type {PendingDismissal} */
+ var dismissal = items.pendingDismissals[0];
+ return requestCardDismissal(
+ dismissal.chromeNotificationId, dismissal.time,
+ dismissal.dismissalData)
+ .then(function() {
+ dismissalsChanged = true;
+ items.pendingDismissals.splice(0, 1);
+ items.recentDismissals[dismissal.dismissalData.notificationId] =
+ Date.now();
+ return doProcessDismissals();
+ })
+ .catch(function() {
+ return onFinish(false);
+ });
+ }
- return doProcessDismissals();
- });
+ return doProcessDismissals();
+ });
}
/**
@@ -967,18 +965,11 @@ function onNotificationClosed(chromeNotificationId, byUser) {
notificationGroups: {}
}).then(function(items) {
/** @type {NotificationDataEntry} */
- var notificationData =
- items.notificationsData[chromeNotificationId] ||
- {
- timestamp: Date.now(),
- combinedCard: []
- };
+ var notificationData = items.notificationsData[chromeNotificationId] ||
+ {timestamp: Date.now(), combinedCard: []};
- var dismissalResult =
- cardSet.onDismissal(
- chromeNotificationId,
- notificationData,
- items.notificationGroups);
+ var dismissalResult = cardSet.onDismissal(
+ chromeNotificationId, notificationData, items.notificationGroups);
for (var i = 0; i < dismissalResult.dismissals.length; i++) {
/** @type {PendingDismissal} */
@@ -1086,8 +1077,8 @@ function setShouldPollOptInStatus(shouldPollOptInStatus) {
* false to not run in the background.
*/
function setBackgroundEnable(backgroundEnable) {
- instrumented.permissions.contains({permissions: ['background']},
- function(hasPermission) {
+ instrumented.permissions.contains(
+ {permissions: ['background']}, function(hasPermission) {
if (backgroundEnable != hasPermission) {
console.log('Action Taken setBackgroundEnable=' + backgroundEnable);
if (backgroundEnable)
@@ -1130,10 +1121,7 @@ function recordEventIfNoCards(signedIn, notificationEnabled, googleNowEnabled) {
* the Google Now is enabled for the user.
*/
function updateRunningState(
- signedIn,
- canEnableBackground,
- notificationEnabled,
- googleNowEnabled) {
+ signedIn, canEnableBackground, notificationEnabled, googleNowEnabled) {
console.log(
'State Update signedIn=' + signedIn + ' ' +
'canEnableBackground=' + canEnableBackground + ' ' +
@@ -1173,11 +1161,11 @@ function updateRunningState(
*/
function onStateChange() {
tasks.add(STATE_CHANGED_TASK_NAME, function() {
- Promise.all([
- authenticationManager.isSignedIn(),
- canEnableBackground(),
- isNotificationsEnabled(),
- isGoogleNowEnabled()])
+ Promise
+ .all([
+ authenticationManager.isSignedIn(), canEnableBackground(),
+ isNotificationsEnabled(), isGoogleNowEnabled()
+ ])
.then(function(results) {
updateRunningState.apply(null, results);
});
@@ -1191,8 +1179,7 @@ function onStateChange() {
function canEnableBackground() {
return new Promise(function(resolve) {
instrumented.metricsPrivate.getVariationParams(
- 'GoogleNow',
- function(response) {
+ 'GoogleNow', function(response) {
resolve(!response || (response.canEnableBackground != 'false'));
});
});
@@ -1254,39 +1241,41 @@ function getGcmNotificationKey() {
*/
function requestNewGcmNotificationKey() {
return getGcmRegistrationId().then(function(gcmId) {
- authenticationManager.getAuthToken().then(function(token) {
- authenticationManager.getLogin().then(function(username) {
- return new Promise(function(resolve, reject) {
- var xhr = new XMLHttpRequest();
- xhr.responseType = 'application/json';
- xhr.open('POST', GCM_REGISTRATION_URL, true);
- xhr.setRequestHeader('Content-Type', 'application/json');
- xhr.setRequestHeader('Authorization', 'Bearer ' + token);
- xhr.setRequestHeader('project_id', GCM_PROJECT_ID);
- var payload = {
- 'operation': 'add',
- 'notification_key_name': username,
- 'registration_ids': [gcmId]
- };
- xhr.onloadend = function() {
- if (xhr.status != 200) {
- reject();
- }
- var obj = JSON.parse(xhr.responseText);
- var key = obj && obj.notification_key;
- if (!key) {
- reject();
- }
- console.log('gcm notification key POST: ' + key);
- chrome.storage.local.set({gcmNotificationKey: key});
- resolve(key);
- };
- xhr.send(JSON.stringify(payload));
+ authenticationManager.getAuthToken()
+ .then(function(token) {
+ authenticationManager.getLogin().then(function(username) {
+ return new Promise(function(resolve, reject) {
+ var xhr = new XMLHttpRequest();
+ xhr.responseType = 'application/json';
+ xhr.open('POST', GCM_REGISTRATION_URL, true);
+ xhr.setRequestHeader('Content-Type', 'application/json');
+ xhr.setRequestHeader('Authorization', 'Bearer ' + token);
+ xhr.setRequestHeader('project_id', GCM_PROJECT_ID);
+ var payload = {
+ 'operation': 'add',
+ 'notification_key_name': username,
+ 'registration_ids': [gcmId]
+ };
+ xhr.onloadend = function() {
+ if (xhr.status != 200) {
+ reject();
+ }
+ var obj = JSON.parse(xhr.responseText);
+ var key = obj && obj.notification_key;
+ if (!key) {
+ reject();
+ }
+ console.log('gcm notification key POST: ' + key);
+ chrome.storage.local.set({gcmNotificationKey: key});
+ resolve(key);
+ };
+ xhr.send(JSON.stringify(payload));
+ });
+ });
+ })
+ .catch(function() {
+ // Couldn't obtain a GCM ID. Ignore and fallback to polling.
});
- });
- }).catch(function() {
- // Couldn't obtain a GCM ID. Ignore and fallback to polling.
- });
});
}
@@ -1321,18 +1310,19 @@ function getGcmRegistrationId() {
* Unregisters from GCM if previously registered.
*/
function unregisterFromGcm() {
- fillFromChromeLocalStorage({gcmRegistrationId: undefined})
- .then(function(items) {
- if (items.gcmRegistrationId) {
- console.log('Unregistering from gcm.');
- instrumented.gcm.unregister(function() {
- if (!chrome.runtime.lastError) {
- chrome.storage.local.remove(
- ['gcmNotificationKey', 'gcmRegistrationId']);
- }
- });
+ fillFromChromeLocalStorage({
+ gcmRegistrationId: undefined
+ }).then(function(items) {
+ if (items.gcmRegistrationId) {
+ console.log('Unregistering from gcm.');
+ instrumented.gcm.unregister(function() {
+ if (!chrome.runtime.lastError) {
+ chrome.storage.local.remove(
+ ['gcmNotificationKey', 'gcmRegistrationId']);
}
});
+ }
+ });
}
/**
@@ -1354,25 +1344,27 @@ function pollOptedInWithRecheck() {
optInRecheckAttempts.start();
}
- console.log(new Date() +
- ' checkOptedIn Attempt ' + localStorage.optedInCheckCount);
+ console.log(
+ new Date() + ' checkOptedIn Attempt ' + localStorage.optedInCheckCount);
- requestAndUpdateOptedIn().then(function(optedIn) {
- if (optedIn) {
- clearPollingState();
- return Promise.resolve();
- } else {
- // If we're not opted in, reject to retry.
- return Promise.reject();
- }
- }).catch(function() {
- if (localStorage.optedInCheckCount < 5) {
- localStorage.optedInCheckCount++;
- optInRecheckAttempts.scheduleRetry();
- } else {
- clearPollingState();
- }
- });
+ requestAndUpdateOptedIn()
+ .then(function(optedIn) {
+ if (optedIn) {
+ clearPollingState();
+ return Promise.resolve();
+ } else {
+ // If we're not opted in, reject to retry.
+ return Promise.reject();
+ }
+ })
+ .catch(function() {
+ if (localStorage.optedInCheckCount < 5) {
+ localStorage.optedInCheckCount++;
+ optInRecheckAttempts.scheduleRetry();
+ } else {
+ clearPollingState();
+ }
+ });
}
instrumented.runtime.onInstalled.addListener(function(details) {
@@ -1409,49 +1401,46 @@ authenticationManager.addListener(function() {
onStateChange();
});
-instrumented.notifications.onClicked.addListener(
- function(chromeNotificationId) {
- chrome.metricsPrivate.recordUserAction('GoogleNow.MessageClicked');
- onNotificationClicked(chromeNotificationId,
- function(notificationDataEntry) {
- var actionUrls = notificationDataEntry.actionUrls;
- var url = actionUrls && actionUrls.messageUrl;
- if (url) {
- recordNotificationClick(notificationDataEntry.cardTypeId);
- }
- return url;
- });
- });
+instrumented.notifications.onClicked.addListener(function(
+ chromeNotificationId) {
+ chrome.metricsPrivate.recordUserAction('GoogleNow.MessageClicked');
+ onNotificationClicked(chromeNotificationId, function(notificationDataEntry) {
+ var actionUrls = notificationDataEntry.actionUrls;
+ var url = actionUrls && actionUrls.messageUrl;
+ if (url) {
+ recordNotificationClick(notificationDataEntry.cardTypeId);
+ }
+ return url;
+ });
+});
-instrumented.notifications.onButtonClicked.addListener(
- function(chromeNotificationId, buttonIndex) {
- chrome.metricsPrivate.recordUserAction(
- 'GoogleNow.ButtonClicked' + buttonIndex);
- onNotificationClicked(chromeNotificationId,
- function(notificationDataEntry) {
- var actionUrls = notificationDataEntry.actionUrls;
- var url = actionUrls.buttonUrls[buttonIndex];
- if (url) {
- recordButtonClick(notificationDataEntry.cardTypeId, buttonIndex);
- } else {
- verify(false, 'onButtonClicked: no url for a button');
- console.log(
- 'buttonIndex=' + buttonIndex + ' ' +
- 'chromeNotificationId=' + chromeNotificationId + ' ' +
- 'notificationDataEntry=' +
- JSON.stringify(notificationDataEntry));
- }
- return url;
- });
- });
+instrumented.notifications.onButtonClicked.addListener(function(
+ chromeNotificationId, buttonIndex) {
+ chrome.metricsPrivate.recordUserAction(
+ 'GoogleNow.ButtonClicked' + buttonIndex);
+ onNotificationClicked(chromeNotificationId, function(notificationDataEntry) {
+ var actionUrls = notificationDataEntry.actionUrls;
+ var url = actionUrls.buttonUrls[buttonIndex];
+ if (url) {
+ recordButtonClick(notificationDataEntry.cardTypeId, buttonIndex);
+ } else {
+ verify(false, 'onButtonClicked: no url for a button');
+ console.log(
+ 'buttonIndex=' + buttonIndex + ' ' +
+ 'chromeNotificationId=' + chromeNotificationId + ' ' +
+ 'notificationDataEntry=' + JSON.stringify(notificationDataEntry));
+ }
+ return url;
+ });
+});
instrumented.notifications.onClosed.addListener(onNotificationClosed);
-instrumented.notifications.onPermissionLevelChanged.addListener(
- function(permissionLevel) {
- console.log('Notifications permissionLevel Change');
- onStateChange();
- });
+instrumented.notifications.onPermissionLevelChanged.addListener(function(
+ permissionLevel) {
+ console.log('Notifications permissionLevel Change');
+ onStateChange();
+});
instrumented.notifications.onShowSettings.addListener(function() {
openUrl(SETTINGS_URL);
@@ -1478,27 +1467,30 @@ instrumented.gcm.onMessage.addListener(function(message) {
tasks.add(ON_PUSH_MESSAGE_START_TASK_NAME, function() {
// Accept promise rejection on failure since it's safer to do nothing,
// preventing polling the server when the payload really didn't change.
- fillFromChromeLocalStorage({
- lastPollNowPayloads: {},
- /** @type {Object<StoredNotificationGroup>} */
- notificationGroups: {}
- }, PromiseRejection.ALLOW).then(function(items) {
- if (items.lastPollNowPayloads[tag] != payload) {
- items.lastPollNowPayloads[tag] = payload;
-
- items.notificationGroups['PUSH' + tag] = {
- cards: [],
- nextPollTime: Date.now()
- };
+ fillFromChromeLocalStorage(
+ {
+ lastPollNowPayloads: {},
+ /** @type {Object<StoredNotificationGroup>} */
+ notificationGroups: {}
+ },
+ PromiseRejection.ALLOW)
+ .then(function(items) {
+ if (items.lastPollNowPayloads[tag] != payload) {
+ items.lastPollNowPayloads[tag] = payload;
+
+ items.notificationGroups['PUSH' + tag] = {
+ cards: [],
+ nextPollTime: Date.now()
+ };
- chrome.storage.local.set({
- lastPollNowPayloads: items.lastPollNowPayloads,
- notificationGroups: items.notificationGroups
- });
+ chrome.storage.local.set({
+ lastPollNowPayloads: items.lastPollNowPayloads,
+ notificationGroups: items.notificationGroups
+ });
- pollOptedInWithRecheck();
- }
- });
+ pollOptedInWithRecheck();
+ }
+ });
});
}
});

Powered by Google App Engine
This is Rietveld 408576698