summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/google_now/background.js
blob: 4e35dc153cc3765e500c5be6be703ce82aba55c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * @fileoverview The event page for Google Now for Chrome implementation.
 * The Google Now event page gets Google Now cards from the server and shows
 * them as Chrome notifications.
 * The service performs periodic updating of Google Now cards.
 * Each updating of the cards includes 4 steps:
 * 1. Obtaining the location of the machine;
 * 2. Processing requests for cards dismissals that are not yet sent to the
 *    server;
 * 3. Making a server request based on that location;
 * 4. Showing the received cards as notifications.
 */

// TODO(vadimt): Use background permission to show notifications even when all
// browser windows are closed.
// TODO(vadimt): Decide what to do in incognito mode.
// TODO(vadimt): Honor the flag the enables Google Now integration.
// TODO(vadimt): Figure out the final values of the constants.
// TODO(vadimt): Remove 'console' calls.
// TODO(vadimt): Consider sending JS stacks for chrome.* API errors and
// malformed server responses.

/**
 * Standard response code for successful HTTP requests. This is the only success
 * code the server will send.
 */
var HTTP_OK = 200;

var HTTP_BAD_REQUEST = 400;
var HTTP_UNAUTHORIZED = 401;
var HTTP_FORBIDDEN = 403;
var HTTP_METHOD_NOT_ALLOWED = 405;

/**
 * Initial period for polling for Google Now Notifications cards to use when the
 * period from the server is not available.
 */
var INITIAL_POLLING_PERIOD_SECONDS = 5 * 60;  // 5 minutes

/**
 * Maximal period for polling for Google Now Notifications cards to use when the
 * period from the server is not available.
 */
var MAXIMUM_POLLING_PERIOD_SECONDS = 60 * 60;  // 1 hour

/**
 * Initial period for retrying the server request for dismissing cards.
 */
var INITIAL_RETRY_DISMISS_PERIOD_SECONDS = 60;  // 1 minute

/**
 * Maximum period for retrying the server request for dismissing cards.
 */
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

/**
 * Time we keep dismissals after successful server dismiss requests.
 */
var DISMISS_RETENTION_TIME_MS = 20 * 60 * 1000;  // 20 minutes

/**
 * Names for tasks that can be created by the extension.
 */
var UPDATE_CARDS_TASK_NAME = 'update-cards';
var DISMISS_CARD_TASK_NAME = 'dismiss-card';
var RETRY_DISMISS_TASK_NAME = 'retry-dismiss';
var STATE_CHANGED_TASK_NAME = 'state-changed';

var LOCATION_WATCH_NAME = 'location-watch';

var WELCOME_TOAST_NOTIFICATION_ID = 'enable-now-toast';

/**
 * The indices of the buttons that are displayed on the welcome toast.
 * @enum {number}
 */
var ToastButtonIndex = {YES: 0, NO: 1};

/**
 * Checks if a new task can't be scheduled when another task is already
 * scheduled.
 * @param {string} newTaskName Name of the new task.
 * @param {string} scheduledTaskName Name of the scheduled task.
 * @return {boolean} Whether the new task conflicts with the existing task.
 */
function areTasksConflicting(newTaskName, scheduledTaskName) {
  if (newTaskName == UPDATE_CARDS_TASK_NAME &&
      scheduledTaskName == UPDATE_CARDS_TASK_NAME) {
    // If a card update is requested while an old update is still scheduled, we
    // don't need the new update.
    return true;
  }

  if (newTaskName == RETRY_DISMISS_TASK_NAME &&
      (scheduledTaskName == UPDATE_CARDS_TASK_NAME ||
       scheduledTaskName == DISMISS_CARD_TASK_NAME ||
       scheduledTaskName == RETRY_DISMISS_TASK_NAME)) {
    // No need to schedule retry-dismiss action if another action that tries to
    // send dismissals is scheduled.
    return true;
  }

  return false;
}

var googleGeolocationAccessEnabledPref =
    chrome.preferencesPrivate.googleGeolocationAccessEnabled;

var tasks = buildTaskManager(areTasksConflicting);

// Add error processing to API calls.
tasks.instrumentApiFunction(chrome.identity, 'getAuthToken', 1);
tasks.instrumentApiFunction(chrome.identity, 'removeCachedAuthToken', 1);
tasks.instrumentApiFunction(chrome.location.onLocationUpdate, 'addListener', 0);
tasks.instrumentApiFunction(chrome.notifications, 'create', 2);
tasks.instrumentApiFunction(chrome.notifications, 'update', 2);
tasks.instrumentApiFunction(chrome.notifications, 'getAll', 0);
tasks.instrumentApiFunction(
    chrome.notifications.onButtonClicked, 'addListener', 0);
tasks.instrumentApiFunction(chrome.notifications.onClicked, 'addListener', 0);
tasks.instrumentApiFunction(chrome.notifications.onClosed, 'addListener', 0);
tasks.instrumentApiFunction(
    googleGeolocationAccessEnabledPref.onChange,
    'addListener',
    0);
tasks.instrumentApiFunction(chrome.runtime.onInstalled, 'addListener', 0);
tasks.instrumentApiFunction(chrome.runtime.onStartup, 'addListener', 0);
tasks.instrumentApiFunction(chrome.tabs, 'create', 1);
tasks.instrumentApiFunction(storage, 'get', 1);

var updateCardsAttempts = buildAttemptManager(
    'cards-update',
    requestLocation,
    INITIAL_POLLING_PERIOD_SECONDS,
    MAXIMUM_POLLING_PERIOD_SECONDS);
var dismissalAttempts = buildAttemptManager(
    'dismiss',
    retryPendingDismissals,
    INITIAL_RETRY_DISMISS_PERIOD_SECONDS,
    MAXIMUM_RETRY_DISMISS_PERIOD_SECONDS);
var cardSet = buildCardSet();

/**
 * Google Now UMA event identifier.
 * @enum {number}
 */
var GoogleNowEvent = {
  REQUEST_FOR_CARDS_TOTAL: 0,
  REQUEST_FOR_CARDS_SUCCESS: 1,
  CARDS_PARSE_SUCCESS: 2,
  DISMISS_REQUEST_TOTAL: 3,
  DISMISS_REQUEST_SUCCESS: 4,
  LOCATION_REQUEST: 5,
  LOCATION_UPDATE: 6,
  EXTENSION_START: 7,
  SHOW_WELCOME_TOAST: 8,
  EVENTS_TOTAL: 9  // EVENTS_TOTAL is not an event; all new events need to be
                   // added before it.
};

/**
 * Records a Google Now Event.
 * @param {GoogleNowEvent} event Event identifier.
 */
function recordEvent(event) {
  var metricDescription = {
    metricName: 'GoogleNow.Event',
    type: 'histogram-linear',
    min: 1,
    max: GoogleNowEvent.EVENTS_TOTAL,
    buckets: GoogleNowEvent.EVENTS_TOTAL + 1
  };

  chrome.metricsPrivate.recordValue(metricDescription, event);
}

/**
 * Adds authorization behavior to the request.
 * @param {XMLHttpRequest} request Server request.
 * @param {function(boolean)} callbackBoolean Completion callback with 'success'
 *     parameter.
 */
function setAuthorization(request, callbackBoolean) {
  tasks.debugSetStepName('setAuthorization-getAuthToken');
  chrome.identity.getAuthToken({interactive: false}, function(token) {
    var errorMessage =
        chrome.runtime.lastError && chrome.runtime.lastError.message;
    console.log('setAuthorization: error=' + errorMessage +
                ', token=' + (token && 'non-empty'));
    if (chrome.runtime.lastError || !token) {
      callbackBoolean(false);
      return;
    }

    request.setRequestHeader('Authorization', 'Bearer ' + token);

    // Instrument onloadend to remove stale auth tokens.
    var originalOnLoadEnd = request.onloadend;
    request.onloadend = tasks.wrapCallback(function(event) {
      if (request.status == HTTP_FORBIDDEN ||
          request.status == HTTP_UNAUTHORIZED) {
        tasks.debugSetStepName('setAuthorization-removeCachedAuthToken');
        chrome.identity.removeCachedAuthToken({token: token}, function() {
          // After purging the token cache, call getAuthToken() again to let
          // Chrome know about the problem with the token.
          chrome.identity.getAuthToken({interactive: false}, function() {});
          originalOnLoadEnd(event);
        });
      } else {
        originalOnLoadEnd(event);
      }
    });

    callbackBoolean(true);
  });
}

/**
 * Parses JSON response from the notification server, show notifications and
 * schedule next update.
 * @param {string} response Server response.
 * @param {function()} callback Completion callback.
 */
function parseAndShowNotificationCards(response, callback) {
  console.log('parseAndShowNotificationCards ' + response);
  try {
    var parsedResponse = JSON.parse(response);
  } catch (error) {
    console.error('parseAndShowNotificationCards parse error: ' + error);
    callback();
    return;
  }

  var cards = parsedResponse.cards;

  if (!(cards instanceof Array)) {
    callback();
    return;
  }

  if (typeof parsedResponse.next_poll_seconds != 'number') {
    callback();
    return;
  }

  tasks.debugSetStepName('parseAndShowNotificationCards-storage-get');
  storage.get(['notificationsData', 'recentDismissals'], function(items) {
    console.log('parseAndShowNotificationCards-get ' + JSON.stringify(items));
    items.notificationsData = items.notificationsData || {};
    items.recentDismissals = items.recentDismissals || {};

    tasks.debugSetStepName(
        'parseAndShowNotificationCards-notifications-getAll');
    chrome.notifications.getAll(function(notifications) {
      console.log('parseAndShowNotificationCards-getAll ' +
          JSON.stringify(notifications));
      // TODO(vadimt): Figure out what to do when notifications are disabled for
      // our extension.
      notifications = notifications || {};

      // Build a set of non-expired recent dismissals. It will be used for
      // client-side filtering of cards.
      var updatedRecentDismissals = {};
      var currentTimeMs = Date.now();
      for (var notificationId in items.recentDismissals) {
        if (currentTimeMs - items.recentDismissals[notificationId] <
            DISMISS_RETENTION_TIME_MS) {
          updatedRecentDismissals[notificationId] =
              items.recentDismissals[notificationId];
        }
      }

      // Mark existing notifications that received an update in this server
      // response.
      var updatedNotifications = {};

      for (var i = 0; i < cards.length; ++i) {
        var notificationId = cards[i].notificationId;
        if (!(notificationId in updatedRecentDismissals) &&
            notificationId in notifications) {
          updatedNotifications[notificationId] = true;
        }
      }

      // Delete notifications that didn't receive an update.
      for (var notificationId in notifications) {
        console.log('parseAndShowNotificationCards-delete-check ' +
                    notificationId);
        if (!(notificationId in updatedNotifications)) {
          console.log('parseAndShowNotificationCards-delete ' + notificationId);
          cardSet.clear(notificationId);
        }
      }

      recordEvent(GoogleNowEvent.CARDS_PARSE_SUCCESS);

      // Create/update notifications and store their new properties.
      var newNotificationsData = {};
      for (var i = 0; i < cards.length; ++i) {
        var card = cards[i];
        if (!(card.notificationId in updatedRecentDismissals)) {
          var notificationData = items.notificationsData[card.notificationId];
          var previousVersion = notifications[card.notificationId] &&
                                notificationData &&
                                notificationData.cardCreateInfo &&
                                notificationData.cardCreateInfo.version;
          newNotificationsData[card.notificationId] =
              cardSet.update(card, previousVersion);
        }
      }

      updateCardsAttempts.start(parsedResponse.next_poll_seconds);

      storage.set({
        notificationsData: newNotificationsData,
        recentDismissals: updatedRecentDismissals
      });
      callback();
    });
  });
}

/**
 * Removes all cards and card state on Google Now close down.
 * For example, this occurs when the geolocation preference is unchecked in the
 * content settings.
 */
function removeAllCards() {
  console.log('removeAllCards');

  // TODO(robliao): Once Google Now clears its own checkbox in the
  // notifications center and bug 260376 is fixed, the below clearing
  // code is no longer necessary.
  chrome.notifications.getAll(function(notifications) {
    for (var notificationId in notifications) {
      chrome.notifications.clear(notificationId, function() {});
    }
    storage.set({notificationsData: {}});
  });
}

/**
 * Requests notification cards from the server.
 * @param {Location} position Location of this computer.
 * @param {function()} callback Completion callback.
 */
function requestNotificationCards(position, callback) {
  console.log('requestNotificationCards ' + JSON.stringify(position) +
      ' from ' + NOTIFICATION_CARDS_URL);

  if (!NOTIFICATION_CARDS_URL) {
    callback();
    return;
  }

  recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL);

  // TODO(vadimt): Should we use 'q' as the parameter name?
  var requestParameters =
      'q=' + position.coords.latitude +
      ',' + position.coords.longitude +
      ',' + position.coords.accuracy;

  var request = buildServerRequest('notifications',
                                   'application/x-www-form-urlencoded');

  request.onloadend = function(event) {
    console.log('requestNotificationCards-onloadend ' + request.status);
    if (request.status == HTTP_OK) {
      recordEvent(GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
      parseAndShowNotificationCards(request.response, callback);
    } else {
      callback();
    }
  };

  setAuthorization(request, function(success) {
    if (success) {
      tasks.debugSetStepName('requestNotificationCards-send-request');
      request.send(requestParameters);
    } else {
      callback();
    }
  });
}

/**
 * Starts getting location for a cards update.
 */
function requestLocation() {
  console.log('requestLocation');
  recordEvent(GoogleNowEvent.LOCATION_REQUEST);
  // TODO(vadimt): Figure out location request options.
  chrome.location.watchLocation(LOCATION_WATCH_NAME, {});
}

/**
 * Stops getting the location.
 */
function stopRequestLocation() {
  console.log('stopRequestLocation');
  chrome.location.clearWatch(LOCATION_WATCH_NAME);
}

/**
 * Obtains new location; requests and shows notification cards based on this
 * location.
 * @param {Location} position Location of this computer.
 */
function updateNotificationsCards(position) {
  console.log('updateNotificationsCards ' + JSON.stringify(position) +
      ' @' + new Date());
  tasks.add(UPDATE_CARDS_TASK_NAME, function(callback) {
    console.log('updateNotificationsCards-task-begin');
    updateCardsAttempts.isRunning(function(running) {
      if (running) {
        updateCardsAttempts.planForNext(function() {
          processPendingDismissals(function(success) {
            if (success) {
              // The cards are requested only if there are no unsent dismissals.
              requestNotificationCards(position, callback);
            } else {
              callback();
            }
          });
        });
      }
    });
  });
}

/**
 * Sends a server request to dismiss a card.
 * @param {string} notificationId Unique identifier of the card.
 * @param {number} dismissalTimeMs Time of the user's dismissal of the card in
 *     milliseconds since epoch.
 * @param {Object} dismissalParameters Dismissal parameters.
 * @param {function(boolean)} callbackBoolean Completion callback with 'done'
 *     parameter.
 */
function requestCardDismissal(
    notificationId, dismissalTimeMs, dismissalParameters, callbackBoolean) {
  console.log('requestDismissingCard ' + notificationId + ' from ' +
      NOTIFICATION_CARDS_URL);

  var dismissalAge = Date.now() - dismissalTimeMs;

  if (dismissalAge > MAXIMUM_DISMISSAL_AGE_MS) {
    callbackBoolean(true);
    return;
  }

  recordEvent(GoogleNowEvent.DISMISS_REQUEST_TOTAL);
  var request = buildServerRequest('dismiss', 'application/json');
  request.onloadend = function(event) {
    console.log('requestDismissingCard-onloadend ' + request.status);
    if (request.status == HTTP_OK)
      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.
    var done = request.status == HTTP_OK ||
        request.status == HTTP_BAD_REQUEST ||
        request.status == HTTP_METHOD_NOT_ALLOWED;
    callbackBoolean(done);
  };

  setAuthorization(request, function(success) {
    if (success) {
      tasks.debugSetStepName('requestCardDismissal-send-request');

      var dismissalObject = {
        id: notificationId,
        age: dismissalAge,
        dismissal: dismissalParameters
      };
      request.send(JSON.stringify(dismissalObject));
    } else {
      callbackBoolean(false);
    }
  });
}

/**
 * Tries to send dismiss requests for all pending dismissals.
 * @param {function(boolean)} callbackBoolean Completion callback with 'success'
 *     parameter. Success means that no pending dismissals are left.
 */
function processPendingDismissals(callbackBoolean) {
  tasks.debugSetStepName('processPendingDismissals-storage-get');
  storage.get(['pendingDismissals', 'recentDismissals'], function(items) {
    console.log('processPendingDismissals-storage-get ' +
                JSON.stringify(items));
    items.pendingDismissals = items.pendingDismissals || [];
    items.recentDismissals = items.recentDismissals || {};

    var dismissalsChanged = false;

    function onFinish(success) {
      if (dismissalsChanged) {
        storage.set({
          pendingDismissals: items.pendingDismissals,
          recentDismissals: items.recentDismissals
        });
      }
      callbackBoolean(success);
    }

    function doProcessDismissals() {
      if (items.pendingDismissals.length == 0) {
        dismissalAttempts.stop();
        onFinish(true);
        return;
      }

      // Send dismissal for the first card, and if successful, repeat
      // recursively with the rest.
      var dismissal = items.pendingDismissals[0];
      requestCardDismissal(
          dismissal.notificationId,
          dismissal.time,
          dismissal.parameters,
          function(done) {
            if (done) {
              dismissalsChanged = true;
              items.pendingDismissals.splice(0, 1);
              items.recentDismissals[dismissal.notificationId] = Date.now();
              doProcessDismissals();
            } else {
              onFinish(false);
            }
          });
    }

    doProcessDismissals();
  });
}

/**
 * Submits a task to send pending dismissals.
 */
function retryPendingDismissals() {
  tasks.add(RETRY_DISMISS_TASK_NAME, function(callback) {
    dismissalAttempts.planForNext(function() {
      processPendingDismissals(function(success) { callback(); });
     });
  });
}

/**
 * Opens URL corresponding to the clicked part of the notification.
 * @param {string} notificationId Unique identifier of the notification.
 * @param {function(Object): string} selector Function that extracts the url for
 *     the clicked area from the button action URLs info.
 */
function onNotificationClicked(notificationId, selector) {
  storage.get('notificationsData', function(items) {
    items.notificationsData = items.notificationsData || {};

    var notificationData = items.notificationsData[notificationId];

    if (!notificationData) {
      // 'notificationsData' in storage may not match the actual list of
      // notifications.
      return;
    }

    var actionUrls = notificationData.actionUrls;
    if (typeof actionUrls != 'object') {
      return;
    }

    var url = selector(actionUrls);

    if (typeof url != 'string')
      return;

    chrome.tabs.create({url: url}, function(tab) {
      if (!tab)
        chrome.windows.create({url: url});
    });
  });
}

/**
 * Responds to a click of one of the buttons on the welcome toast.
 * @param {number} buttonIndex The index of the button which was clicked.
 */
function onToastNotificationClicked(buttonIndex) {
  storage.set({userRespondedToToast: true});

  if (buttonIndex == ToastButtonIndex.YES) {
    chrome.metricsPrivate.recordUserAction('GoogleNow.WelcomeToastClickedYes');
    googleGeolocationAccessEnabledPref.set({value: true});
    // The googlegeolocationaccessenabled preference change callback
    // will take care of starting the poll for cards.
  } else {
    chrome.metricsPrivate.recordUserAction('GoogleNow.WelcomeToastClickedNo');
    onStateChange();
  }
}

/**
 * Callback for chrome.notifications.onClosed event.
 * @param {string} notificationId Unique identifier of the notification.
 * @param {boolean} byUser Whether the notification was closed by the user.
 */
function onNotificationClosed(notificationId, byUser) {
  if (!byUser)
    return;

  if (notificationId == WELCOME_TOAST_NOTIFICATION_ID) {
    // Even though they only closed the notification without clicking no, treat
    // it as though they clicked No anwyay, and don't show the toast again.
    chrome.metricsPrivate.recordUserAction('GoogleNow.WelcomeToastDismissed');
    storage.set({userRespondedToToast: true});
    return;
  }

  // At this point we are guaranteed that the notification is a now card.
  chrome.metricsPrivate.recordUserAction('GoogleNow.Dismissed');

  tasks.add(DISMISS_CARD_TASK_NAME, function(callback) {
    dismissalAttempts.start();

    // Deleting the notification in case it was re-added while this task was
    // scheduled, waiting for execution.
    cardSet.clear(notificationId);

    tasks.debugSetStepName('onNotificationClosed-storage-get');
    storage.get(['pendingDismissals', 'notificationsData'], function(items) {
      items.pendingDismissals = items.pendingDismissals || [];
      items.notificationsData = items.notificationsData || {};

      var notificationData = items.notificationsData[notificationId];

      var dismissal = {
        notificationId: notificationId,
        time: Date.now(),
        parameters: notificationData && notificationData.dismissalParameters
      };
      items.pendingDismissals.push(dismissal);
      storage.set({pendingDismissals: items.pendingDismissals});
      processPendingDismissals(function(success) { callback(); });
    });
  });
}

/**
 * Initializes the polling system to start monitoring location and fetching
 * cards.
 */
function startPollingCards() {
  // Create an update timer for a case when for some reason location request
  // gets stuck.
  updateCardsAttempts.start(MAXIMUM_POLLING_PERIOD_SECONDS);

  requestLocation();
}

/**
 * Stops all machinery in the polling system.
 */
function stopPollingCards() {
  stopRequestLocation();

  updateCardsAttempts.stop();

  removeAllCards();
}

/**
 * Initializes the event page on install or on browser startup.
 */
function initialize() {
  recordEvent(GoogleNowEvent.EXTENSION_START);

  // Alarms persist across chrome restarts. This is undesirable since it
  // prevents us from starting up everything (alarms are a heuristic to
  // determine if we are already running). To mitigate this, we will
  // shut everything down on initialize before starting everything up.
  stopPollingCards();
  onStateChange();
}

/**
 * Starts or stops the polling of cards.
 * @param {boolean} shouldPollCardsRequest true to start and
 *     false to stop polling cards.
 * @param {function} onSuccess Called on completion.
 */
function setShouldPollCards(shouldPollCardsRequest, onSuccess) {
  tasks.debugSetStepName(
        'setShouldRun-shouldRun-updateCardsAttemptsIsRunning');
  updateCardsAttempts.isRunning(function(currentValue) {
    if (shouldPollCardsRequest != currentValue) {
      if (shouldPollCardsRequest)
        startPollingCards();
      else
        stopPollingCards();
    }
    onSuccess();
  });
}

/**
 * Shows or hides the toast.
 * @param {boolean} visibleRequest true to show the toast and
 *     false to hide the toast.
 * @param {function} onSuccess Called on completion.
 */
function setToastVisible(visibleRequest, onSuccess) {
  tasks.debugSetStepName(
      'setToastVisible-shouldSetToastVisible-getAllNotifications');
  chrome.notifications.getAll(function(notifications) {
    // TODO(vadimt): Figure out what to do when notifications are disabled for
    // our extension.
    notifications = notifications || {};

    if (visibleRequest != !!notifications[WELCOME_TOAST_NOTIFICATION_ID]) {
      if (visibleRequest)
        showWelcomeToast();
      else
        hideWelcomeToast();
    }

    onSuccess();
  });
}

/**
 * Does the actual work of deciding what Google Now should do
 * based off of the current state of Chrome.
 * @param {boolean} signedIn true if the user is signed in.
 * @param {boolean} geolocationEnabled true if
 *     the geolocation option is enabled.
 * @param {boolean} userRespondedToToast true if
 *     the user has responded to the toast.
 * @param {function()} callback Call this function on completion.
 */
function updateRunningState(
    signedIn,
    geolocationEnabled,
    userRespondedToToast,
    callback) {

  var shouldSetToastVisible = false;
  var shouldPollCards = false;

  if (signedIn) {
    if (geolocationEnabled) {
      if (!userRespondedToToast) {
        // If the user enabled geolocation independently of Google Now,
        // the user has implicitly responded to the toast.
        // We do not want to show it again.
        storage.set({userRespondedToToast: true});
      }

      shouldPollCards = true;
    } else {
      if (!userRespondedToToast)
        shouldSetToastVisible = true;
    }
  }

  setToastVisible(shouldSetToastVisible, function() {
    setShouldPollCards(shouldPollCards, callback);
  });
}

/**
 * Coordinates the behavior of Google Now for Chrome depending on
 * Chrome and extension state.
 */
function onStateChange() {
  tasks.add(STATE_CHANGED_TASK_NAME, function(callback) {
    tasks.debugSetStepName('onStateChange-getAuthToken');
    chrome.identity.getAuthToken({interactive: false}, function(token) {
      var signedIn =
          !chrome.runtime.lastError &&
          token &&
          !!NOTIFICATION_CARDS_URL;
      tasks.debugSetStepName(
          'onStateChange-get-googleGeolocationAccessEnabledPref');
      googleGeolocationAccessEnabledPref.get({}, function(prefValue) {
        var geolocationEnabled = !!prefValue.value;
        tasks.debugSetStepName(
          'onStateChange-get-userRespondedToToast');
        storage.get('userRespondedToToast', function(items) {
          var userRespondedToToast = !!items.userRespondedToToast;
          updateRunningState(
              signedIn,
              geolocationEnabled,
              userRespondedToToast,
              callback);
        });
      });
    });
  });
}

/**
 * Displays a toast to the user asking if they want to opt in to receiving
 * Google Now cards.
 */
function showWelcomeToast() {
  recordEvent(GoogleNowEvent.SHOW_WELCOME_TOAST);
  // TODO(zturner): Localize this once the component extension localization
  // api is complete.
  // TODO(zturner): Add icons.
  var buttons = [{title: 'Yes'}, {title: 'No'}];
  var options = {
    type: 'basic',
    title: 'Enable Google Now Cards',
    message: 'Would you like to be shown Google Now cards?',
    iconUrl: 'http://www.gstatic.com/googlenow/chrome/default.png',
    priority: 2,
    buttons: buttons
  };
  chrome.notifications.create(WELCOME_TOAST_NOTIFICATION_ID, options,
      function(notificationId) {});
}

/**
 * Hides the welcome toast.
 */
function hideWelcomeToast() {
  chrome.notifications.clear(
      WELCOME_TOAST_NOTIFICATION_ID,
      function() {});
}

chrome.runtime.onInstalled.addListener(function(details) {
  console.log('onInstalled ' + JSON.stringify(details));
  if (details.reason != 'chrome_update') {
    initialize();
  }
});

chrome.runtime.onStartup.addListener(function() {
  console.log('onStartup');
  initialize();
});

googleGeolocationAccessEnabledPref.onChange.addListener(function(prefValue) {
  console.log('googleGeolocationAccessEnabledPref onChange ' + prefValue.value);
  onStateChange();
});

chrome.notifications.onClicked.addListener(
    function(notificationId) {
      chrome.metricsPrivate.recordUserAction('GoogleNow.MessageClicked');
      onNotificationClicked(notificationId, function(actionUrls) {
        return actionUrls.messageUrl;
      });
    });

chrome.notifications.onButtonClicked.addListener(
    function(notificationId, buttonIndex) {
      if (notificationId == WELCOME_TOAST_NOTIFICATION_ID) {
        onToastNotificationClicked(buttonIndex);
      } else {
        chrome.metricsPrivate.recordUserAction(
            'GoogleNow.ButtonClicked' + buttonIndex);
        onNotificationClicked(notificationId, function(actionUrls) {
          if (!Array.isArray(actionUrls.buttonUrls))
            return undefined;

          return actionUrls.buttonUrls[buttonIndex];
        });
      }
    });

chrome.notifications.onClosed.addListener(onNotificationClosed);

chrome.location.onLocationUpdate.addListener(function(position) {
  recordEvent(GoogleNowEvent.LOCATION_UPDATE);
  updateNotificationsCards(position);
});

chrome.omnibox.onInputEntered.addListener(function(text) {
  localStorage['server_url'] = NOTIFICATION_CARDS_URL = text;
  initialize();
});