summaryrefslogtreecommitdiffstats
path: root/chrome/browser/services/gcm/gcm_profile_service.cc
blob: 971cf0cb4c72a02b2d75a8761016fa2c62ac473c (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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
// 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.

#include "chrome/browser/services/gcm/gcm_profile_service.h"

#include "base/base64.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/services/gcm/gcm_client_factory.h"
#include "chrome/browser/services/gcm/gcm_event_router.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "components/webdata/encryptor/encryptor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/common/extension.h"

using extensions::Extension;

namespace gcm {

const char kRegistrationKey[] = "gcm.registration";
const char kSendersKey[] = "senders";
const char kRegistrationIDKey[] = "reg_id";

// Helper class to save tasks to run until we're ready to execute them.
class GCMProfileService::DelayedTaskController {
 public:
  DelayedTaskController();
  ~DelayedTaskController();

  // Adds an app to the tracking list. It will be first marked as not ready.
  // Tasks will be queued for delay execution until the app is marked as ready.
  void AddApp(const std::string& app_id);

  // Removes the app from the tracking list.
  void RemoveApp(const std::string& app_id);

  // Adds a task that will be invoked once we're ready.
  void AddTask(const std::string& app_id, base::Closure task);

  // Marks that GCM is ready. GCM is ready only when GCMClient is ready and
  // the user check-in is completed.
  void SetGCMReady();

  // Marks that the app is ready to have operations performed.
  void SetAppReady(const std::string& app_id);

  // Returns true if it is ready to perform operations for an app.
  bool CanRunTaskWithoutDelay(const std::string& app_id) const;

  // Returns true if the app has been tracked for readiness.
  bool IsAppTracked(const std::string& app_id) const;

 private:
  struct AppTaskQueue {
    AppTaskQueue();
    ~AppTaskQueue();

    // The flag that indicates if GCMProfileService completes loading the
    // persistent data for the app.
    bool ready;

    // Tasks to be invoked upon ready.
    std::vector<base::Closure> tasks;
  };

  void RunTasks(AppTaskQueue* task_queue);

  // Flag that indicates that GCM is done.
  bool gcm_ready_;

  // Map from app_id to AppTaskQueue storing the tasks that will be invoked
  // when both GCM and the app get ready.
  typedef std::map<std::string, AppTaskQueue*> DelayedTaskMap;
  DelayedTaskMap delayed_task_map_;
};

GCMProfileService::DelayedTaskController::AppTaskQueue::AppTaskQueue()
    : ready(false) {
}

GCMProfileService::DelayedTaskController::AppTaskQueue::~AppTaskQueue() {
}

GCMProfileService::DelayedTaskController::DelayedTaskController()
    : gcm_ready_(false) {
}

GCMProfileService::DelayedTaskController::~DelayedTaskController() {
  for (DelayedTaskMap::const_iterator iter = delayed_task_map_.begin();
       iter != delayed_task_map_.end(); ++iter) {
    delete iter->second;
  }
}

void GCMProfileService::DelayedTaskController::AddApp(
    const std::string& app_id) {
  DCHECK(delayed_task_map_.find(app_id) == delayed_task_map_.end());
  delayed_task_map_[app_id] = new AppTaskQueue;
}

void GCMProfileService::DelayedTaskController::RemoveApp(
    const std::string& app_id) {
  DelayedTaskMap::iterator iter = delayed_task_map_.find(app_id);
  if (iter == delayed_task_map_.end())
    return;
  delete iter->second;
  delayed_task_map_.erase(iter);
}

void GCMProfileService::DelayedTaskController::AddTask(
    const std::string& app_id, base::Closure task) {
  DelayedTaskMap::const_iterator iter = delayed_task_map_.find(app_id);
  DCHECK(iter != delayed_task_map_.end());
  iter->second->tasks.push_back(task);
}

void GCMProfileService::DelayedTaskController::SetGCMReady() {
  gcm_ready_ = true;

  for (DelayedTaskMap::iterator iter = delayed_task_map_.begin();
       iter != delayed_task_map_.end(); ++iter) {
    if (iter->second->ready)
      RunTasks(iter->second);
  }
}

void GCMProfileService::DelayedTaskController::SetAppReady(
    const std::string& app_id) {
  DelayedTaskMap::iterator iter = delayed_task_map_.find(app_id);
  DCHECK(iter != delayed_task_map_.end());

  AppTaskQueue* task_queue = iter->second;
  DCHECK(task_queue);
  task_queue->ready = true;

  if (gcm_ready_)
    RunTasks(task_queue);
}

bool GCMProfileService::DelayedTaskController::CanRunTaskWithoutDelay(
    const std::string& app_id) const {
  if (!gcm_ready_)
    return false;
  DelayedTaskMap::const_iterator iter = delayed_task_map_.find(app_id);
  if (iter == delayed_task_map_.end())
    return true;
  return iter->second->ready;
}

bool GCMProfileService::DelayedTaskController::IsAppTracked(
    const std::string& app_id) const {
  return delayed_task_map_.find(app_id) != delayed_task_map_.end();
}

void GCMProfileService::DelayedTaskController::RunTasks(
    AppTaskQueue* task_queue) {
  DCHECK(gcm_ready_ && task_queue->ready);

  for (size_t i = 0; i < task_queue->tasks.size(); ++i)
    task_queue->tasks[i].Run();
  task_queue->tasks.clear();
}

class GCMProfileService::IOWorker
    : public GCMClient::Delegate,
      public base::RefCountedThreadSafe<GCMProfileService::IOWorker>{
 public:
  // Called on UI thread.
  explicit IOWorker(const base::WeakPtr<GCMProfileService>& service);

  // Overridden from GCMClient::Delegate:
  // Called on IO thread.
  virtual void OnCheckInFinished(const GCMClient::CheckinInfo& checkin_info,
                                 GCMClient::Result result) OVERRIDE;
  virtual void OnRegisterFinished(const std::string& app_id,
                                  const std::string& registration_id,
                                  GCMClient::Result result) OVERRIDE;
  virtual void OnSendFinished(const std::string& app_id,
                              const std::string& message_id,
                              GCMClient::Result result) OVERRIDE;
  virtual void OnMessageReceived(
      const std::string& app_id,
      const GCMClient::IncomingMessage& message) OVERRIDE;
  virtual void OnMessagesDeleted(const std::string& app_id) OVERRIDE;
  virtual void OnMessageSendError(const std::string& app_id,
                                  const std::string& message_id,
                                  GCMClient::Result result) OVERRIDE;
  virtual GCMClient::CheckinInfo GetCheckinInfo() const OVERRIDE;
  virtual void OnLoadingCompleted() OVERRIDE;

  // Called on IO thread.
  void Initialize();
  void SetUser(const std::string& username);
  void RemoveUser();
  void CheckIn();
  void SetCheckinInfo(const GCMClient::CheckinInfo& checkin_info);
  void CheckOut();
  void Register(const std::string& app_id,
                const std::vector<std::string>& sender_ids,
                const std::string& cert);
  void Unregister(const std::string& app_id);
  void Send(const std::string& app_id,
            const std::string& receiver_id,
            const GCMClient::OutgoingMessage& message);

 private:
  friend class base::RefCountedThreadSafe<IOWorker>;
  virtual ~IOWorker();

  const base::WeakPtr<GCMProfileService> service_;

  // Not owned.
  GCMClient* gcm_client_;

  // The username (email address) of the signed-in user.
  std::string username_;

  // The checkin info obtained from the server for the signed in user associated
  // with the profile.
  GCMClient::CheckinInfo checkin_info_;
};

GCMProfileService::IOWorker::IOWorker(
    const base::WeakPtr<GCMProfileService>& service)
    : service_(service),
      gcm_client_(NULL) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
}

GCMProfileService::IOWorker::~IOWorker() {
}

void GCMProfileService::IOWorker::Initialize() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  gcm_client_ = GCMClientFactory::GetClient();

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::CheckGCMClientLoadingFinished,
                 service_,
                 gcm_client_->IsLoading()));
}

void GCMProfileService::IOWorker::OnCheckInFinished(
    const GCMClient::CheckinInfo& checkin_info,
    GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  checkin_info_ = checkin_info;

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::CheckInFinished,
                 service_,
                 checkin_info_,
                 result));
}

void GCMProfileService::IOWorker::OnRegisterFinished(
    const std::string& app_id,
    const std::string& registration_id,
    GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::RegisterFinished,
                 service_,
                 app_id,
                 registration_id,
                 result));
}

void GCMProfileService::IOWorker::OnSendFinished(
    const std::string& app_id,
    const std::string& message_id,
    GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::SendFinished,
                 service_,
                 app_id,
                 message_id,
                 result));
}

void GCMProfileService::IOWorker::OnMessageReceived(
    const std::string& app_id,
    const GCMClient::IncomingMessage& message) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::MessageReceived,
                 service_,
                 app_id,
                 message));
}

void GCMProfileService::IOWorker::OnMessagesDeleted(const std::string& app_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::MessagesDeleted,
                 service_,
                 app_id));
}

void GCMProfileService::IOWorker::OnMessageSendError(
    const std::string& app_id,
    const std::string& message_id,
    GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::MessageSendError,
                 service_,
                 app_id,
                 message_id,
                 result));
}

GCMClient::CheckinInfo GCMProfileService::IOWorker::GetCheckinInfo() const {
  return checkin_info_;
}

void GCMProfileService::IOWorker::OnLoadingCompleted() {
  content::BrowserThread::PostTask(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GCMProfileService::GCMClientLoadingFinished,
                 service_));
}

void GCMProfileService::IOWorker::SetUser(const std::string& username) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
  DCHECK(username_.empty() && !username.empty());

  username_ = username;
  gcm_client_->SetUserDelegate(username_, this);
}

void GCMProfileService::IOWorker::RemoveUser() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  if (username_.empty())
    return;
  gcm_client_->SetUserDelegate(username_, NULL);
  username_.clear();
}

void GCMProfileService::IOWorker::CheckIn() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  gcm_client_->CheckIn(username_);
}

void GCMProfileService::IOWorker::SetCheckinInfo(
    const GCMClient::CheckinInfo& checkin_info) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  checkin_info_ = checkin_info;
}

void GCMProfileService::IOWorker::CheckOut() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  checkin_info_.Reset();
  RemoveUser();
}

void GCMProfileService::IOWorker::Register(
    const std::string& app_id,
    const std::vector<std::string>& sender_ids,
    const std::string& cert) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
  DCHECK(!username_.empty() && checkin_info_.IsValid());

  gcm_client_->Register(username_, app_id, cert, sender_ids);
}

void GCMProfileService::IOWorker::Unregister(const std::string& app_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
  DCHECK(!username_.empty() && checkin_info_.IsValid());

  gcm_client_->Unregister(username_, app_id);
}

void GCMProfileService::IOWorker::Send(
    const std::string& app_id,
    const std::string& receiver_id,
    const GCMClient::OutgoingMessage& message) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
  DCHECK(!username_.empty() && checkin_info_.IsValid());

  gcm_client_->Send(username_, app_id, receiver_id, message);
}

GCMProfileService::RegistrationInfo::RegistrationInfo() {
}

GCMProfileService::RegistrationInfo::~RegistrationInfo() {
}

bool GCMProfileService::RegistrationInfo::IsValid() const {
  return !sender_ids.empty() && !registration_id.empty();
}

bool GCMProfileService::enable_gcm_for_testing_ = false;

// static
bool GCMProfileService::IsGCMEnabled(Profile* profile) {
  // GCM is not enabled in incognito mode.
  if (profile->IsOffTheRecord())
    return false;

  if (enable_gcm_for_testing_)
    return true;

  // GCM support is only enabled for Canary/Dev builds.
  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  return channel == chrome::VersionInfo::CHANNEL_UNKNOWN ||
         channel == chrome::VersionInfo::CHANNEL_CANARY ||
         channel == chrome::VersionInfo::CHANNEL_DEV;
}

// static
void GCMProfileService::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterUint64Pref(
      prefs::kGCMUserAccountID,
      0,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterStringPref(
      prefs::kGCMUserToken,
      "",
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}

GCMProfileService::GCMProfileService(Profile* profile)
    : profile_(profile),
      gcm_client_ready_(false),
      checkin_info_read_(false),
      testing_delegate_(NULL),
      weak_ptr_factory_(this) {
  DCHECK(!profile->IsOffTheRecord());
}

GCMProfileService::~GCMProfileService() {
  if (username_.empty())
    return;
  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::RemoveUser,
                 io_worker_));
}

void GCMProfileService::Initialize() {
  delayed_task_controller_.reset(new DelayedTaskController);

  // This has to be done first since CheckIn depends on it.
  io_worker_ = new IOWorker(weak_ptr_factory_.GetWeakPtr());

  // This initializes GCMClient and also does the check to find out if GCMClient
  // has finished the loading.
  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::Initialize, io_worker_));

  // In case that the profile has been signed in before GCMProfileService is
  // created.
  SigninManagerBase* manager = SigninManagerFactory::GetForProfile(profile_);
  if (manager)
    AddUser(manager->GetAuthenticatedUsername());

  registrar_.Add(this,
                 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
                 content::Source<Profile>(profile_));
  registrar_.Add(this,
                 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT,
                 content::Source<Profile>(profile_));
  // TODO(jianli): move extension specific logic out of GCMProfileService.
  registrar_.Add(this,
                 chrome::NOTIFICATION_EXTENSION_LOADED,
                 content::Source<Profile>(profile_));
  registrar_.Add(this,
                 chrome:: NOTIFICATION_EXTENSION_UNINSTALLED,
                 content::Source<Profile>(profile_));
}

void GCMProfileService::Register(const std::string& app_id,
                                 const std::vector<std::string>& sender_ids,
                                 const std::string& cert,
                                 RegisterCallback callback) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!app_id.empty() && !sender_ids.empty() && !callback.is_null());

  // If the profile was not signed in, bail out.
  if (username_.empty()) {
    callback.Run(std::string(), GCMClient::NOT_SIGNED_IN);
    return;
  }

  // If previous register operation is still in progress, bail out.
  if (register_callbacks_.find(app_id) != register_callbacks_.end()) {
    callback.Run(std::string(), GCMClient::ASYNC_OPERATION_PENDING);
    return;
  }

  register_callbacks_[app_id] = callback;

  EnsureAppReady(app_id);

  // Delay the register operation until the loading is done.
  if (!delayed_task_controller_->CanRunTaskWithoutDelay(app_id)) {
    delayed_task_controller_->AddTask(
        app_id,
        base::Bind(&GCMProfileService::DoRegister,
                   weak_ptr_factory_.GetWeakPtr(),
                   app_id,
                   sender_ids,
                   cert));
    return;
  }

  DoRegister(app_id, sender_ids, cert);
}

void GCMProfileService::DoCheckIn() {
  // No need to do check-in if the info has been read from prefs store.
  if (checkin_info_read_) {
    delayed_task_controller_->SetGCMReady();
    return;
  }

  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::CheckIn, io_worker_));
}

void GCMProfileService::DoRegister(const std::string& app_id,
                                   const std::vector<std::string>& sender_ids,
                                   const std::string& cert) {
  std::map<std::string, RegisterCallback>::iterator callback_iter =
      register_callbacks_.find(app_id);
  if (callback_iter == register_callbacks_.end()) {
    // The callback could have been removed when the app is uninstalled.
    return;
  }

  // Normalize the sender IDs by making them sorted.
  std::vector<std::string> normalized_sender_ids = sender_ids;
  std::sort(normalized_sender_ids.begin(), normalized_sender_ids.end());

  // If the same sender ids is provided, return the cached registration ID
  // directly.
  RegistrationInfoMap::const_iterator registration_info_iter =
      registration_info_map_.find(app_id);
  if (registration_info_iter != registration_info_map_.end() &&
      registration_info_iter->second.sender_ids == normalized_sender_ids) {
    RegisterCallback callback = callback_iter->second;
    register_callbacks_.erase(callback_iter);
    callback.Run(registration_info_iter->second.registration_id,
                 GCMClient::SUCCESS);
    return;
  }

  // Cache the sender IDs. The registration ID will be filled when the
  // registration completes.
  RegistrationInfo registration_info;
  registration_info.sender_ids = normalized_sender_ids;
  registration_info_map_[app_id] = registration_info;

  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::Register,
                 io_worker_,
                 app_id,
                 normalized_sender_ids,
                 cert));
}

void GCMProfileService::Send(const std::string& app_id,
                             const std::string& receiver_id,
                             const GCMClient::OutgoingMessage& message,
                             SendCallback callback) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!app_id.empty() && !receiver_id.empty() && !callback.is_null());

  // If the profile was not signed in, bail out.
  if (username_.empty()) {
    callback.Run(std::string(), GCMClient::NOT_SIGNED_IN);
    return;
  }

  // If the message with send ID is still in progress, bail out.
  std::pair<std::string, std::string> key(app_id, message.id);
  if (send_callbacks_.find(key) != send_callbacks_.end()) {
    callback.Run(message.id, GCMClient::INVALID_PARAMETER);
    return;
  }
  send_callbacks_[key] = callback;

  EnsureAppReady(app_id);

  // Delay the send operation until all the loadings are done.
  if (!delayed_task_controller_->CanRunTaskWithoutDelay(app_id)) {
    delayed_task_controller_->AddTask(
        app_id,
        base::Bind(&GCMProfileService::DoSend,
                   weak_ptr_factory_.GetWeakPtr(),
                   app_id,
                   receiver_id,
                   message));
    return;
  }

  DoSend(app_id, receiver_id, message);
}

void GCMProfileService::DoSend(const std::string& app_id,
                               const std::string& receiver_id,
                               const GCMClient::OutgoingMessage& message) {
  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::Send,
                 io_worker_,
                 app_id,
                 receiver_id,
                 message));
}

void GCMProfileService::Observe(int type,
                                const content::NotificationSource& source,
                                const content::NotificationDetails& details) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  switch (type) {
    case chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL: {
      const GoogleServiceSigninSuccessDetails* signin_details =
          content::Details<GoogleServiceSigninSuccessDetails>(details).ptr();
      AddUser(signin_details->username);
      break;
    }
    case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT:
      username_.clear();
      RemoveUser();
      break;
    case chrome::NOTIFICATION_EXTENSION_LOADED: {
      extensions::Extension* extension =
          content::Details<extensions::Extension>(details).ptr();
      // No need to load the persisted registration info if the extension does
      // not have the GCM permission.
      if (extension->HasAPIPermission(extensions::APIPermission::kGcm))
        EnsureAppReady(extension->id());
      break;
    }
    case chrome:: NOTIFICATION_EXTENSION_UNINSTALLED: {
      extensions::Extension* extension =
          content::Details<extensions::Extension>(details).ptr();
      Unregister(extension->id());
      break;
    }
    default:
      NOTREACHED();
  }
}

void GCMProfileService::AddUser(const std::string& username) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  // If re-signin occurs due to password change, there is no need to do
  // check-in again.
  if (username_ == username || username.empty())
    return;
  username_ = username;

  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::SetUser,
                 io_worker_,
                 username_));

  // Try to read persisted check-in info from the profile's prefs store.
  PrefService* pref_service = profile_->GetPrefs();
  uint64 android_id = pref_service->GetUint64(prefs::kGCMUserAccountID);
  std::string base64_token = pref_service->GetString(prefs::kGCMUserToken);
  std::string encrypted_secret;
  base::Base64Decode(base::StringPiece(base64_token), &encrypted_secret);
  if (android_id && !encrypted_secret.empty()) {
    std::string decrypted_secret;
    Encryptor::DecryptString(encrypted_secret, &decrypted_secret);
    uint64 secret = 0;
    if (base::StringToUint64(decrypted_secret, &secret) && secret) {
      checkin_info_read_ = true;
      GCMClient::CheckinInfo checkin_info;
      checkin_info.android_id = android_id;
      checkin_info.secret = secret;
      content::BrowserThread::PostTask(
          content::BrowserThread::IO,
          FROM_HERE,
          base::Bind(&GCMProfileService::IOWorker::SetCheckinInfo,
                     io_worker_,
                     checkin_info));

      if (testing_delegate_)
        testing_delegate_->CheckInFinished(checkin_info, GCMClient::SUCCESS);

      return;
    }
  }

  // Check-in could only be initiated after GCMClient gets ready.
  if (gcm_client_ready_)
    DoCheckIn();
}

void GCMProfileService::RemoveUser() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  PrefService* pref_service = profile_->GetPrefs();
  pref_service->ClearPref(prefs::kGCMUserAccountID);
  pref_service->ClearPref(prefs::kGCMUserToken);

  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::CheckOut, io_worker_));
}

void GCMProfileService::EnsureAppReady(const std::string& app_id) {
  if (delayed_task_controller_->IsAppTracked(app_id))
    return;

  ReadRegistrationInfo(app_id);
}

void GCMProfileService::Unregister(const std::string& app_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  // This is unlikely to happen because the app will not be uninstalled before
  // the asynchronous extension function completes.
  DCHECK(register_callbacks_.find(app_id) == register_callbacks_.end());

  // Remove the cached registration info. If not found, there is no need to
  // ask the server to unregister it.
  RegistrationInfoMap::iterator registration_info_iter =
      registration_info_map_.find(app_id);
  if (registration_info_iter == registration_info_map_.end())
    return;
  registration_info_map_.erase(registration_info_iter);

  // Remove the persisted registration info.
  DeleteRegistrationInfo(app_id);

  // No need to track the app any more.
  delayed_task_controller_->RemoveApp(app_id);

  // Ask the server to unregister it. There could be a small chance that the
  // unregister request fails. If this occurs, it does not bring any harm since
  // we simply reject the messages/events received from the server.
  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&GCMProfileService::IOWorker::Unregister,
                 io_worker_,
                 app_id));
}

void GCMProfileService::CheckInFinished(
    const GCMClient::CheckinInfo& checkin_info, GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  delayed_task_controller_->SetGCMReady();

  // Save the check-in info into the profile's prefs store.
  PrefService* pref_service = profile_->GetPrefs();
  pref_service->SetUint64(prefs::kGCMUserAccountID, checkin_info.android_id);

  // Encrypt the secret for persisting purpose.
  std::string encrypted_secret;
  Encryptor::EncryptString(base::Uint64ToString(checkin_info.secret),
                           &encrypted_secret);

  // |encrypted_secret| might contain binary data and our prefs store only
  // works for the text.
  std::string base64_token;
  base::Base64Encode(encrypted_secret, &base64_token);
  pref_service->SetString(prefs::kGCMUserToken, base64_token);

  if (testing_delegate_)
    testing_delegate_->CheckInFinished(checkin_info, result);
}

void GCMProfileService::RegisterFinished(const std::string& app_id,
                                         const std::string& registration_id,
                                         GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  std::map<std::string, RegisterCallback>::iterator callback_iter =
      register_callbacks_.find(app_id);
  if (callback_iter == register_callbacks_.end()) {
    // The callback could have been removed when the app is uninstalled.
    return;
  }

  // Cache the registration ID if the registration succeeds. Otherwise,
  // removed the cached info.
  RegistrationInfoMap::iterator registration_info_iter =
      registration_info_map_.find(app_id);
  // This is unlikely to happen because the app will not be uninstalled before
  // the asynchronous extension function completes.
  DCHECK(registration_info_iter != registration_info_map_.end());
  if (result == GCMClient::SUCCESS) {
    registration_info_iter->second.registration_id = registration_id;
    WriteRegistrationInfo(app_id);
  } else {
    registration_info_map_.erase(registration_info_iter);
  }

  RegisterCallback callback = callback_iter->second;
  register_callbacks_.erase(callback_iter);
  callback.Run(registration_id, result);
}

void GCMProfileService::SendFinished(const std::string& app_id,
                                     const std::string& message_id,
                                     GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  std::map<std::pair<std::string, std::string>, SendCallback>::iterator
      callback_iter = send_callbacks_.find(
          std::pair<std::string, std::string>(app_id, message_id));
  if (callback_iter == send_callbacks_.end()) {
    // The callback could have been removed when the app is uninstalled.
    return;
  }

  SendCallback callback = callback_iter->second;
  send_callbacks_.erase(callback_iter);
  callback.Run(message_id, result);
}

void GCMProfileService::MessageReceived(const std::string& app_id,
                                        GCMClient::IncomingMessage message) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  // Drop the event if signed out.
  if (username_.empty())
    return;

  GetEventRouter(app_id)->OnMessage(app_id, message);
}

void GCMProfileService::MessagesDeleted(const std::string& app_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  // Drop the event if signed out.
  if (username_.empty())
    return;

  GetEventRouter(app_id)->OnMessagesDeleted(app_id);
}

void GCMProfileService::MessageSendError(const std::string& app_id,
                                         const std::string& message_id,
                                         GCMClient::Result result) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  // Drop the event if signed out.
  if (username_.empty())
    return;

  GetEventRouter(app_id)->OnSendError(app_id, message_id, result);
}

void GCMProfileService::CheckGCMClientLoadingFinished(bool is_loading) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  gcm_client_ready_ = !is_loading;
  if (gcm_client_ready_)
    DoCheckIn();
}

void GCMProfileService::GCMClientLoadingFinished() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  if (gcm_client_ready_)
    return;
  gcm_client_ready_ = true;

  DoCheckIn();
}

GCMEventRouter* GCMProfileService::GetEventRouter(const std::string& app_id) {
  if (testing_delegate_ && testing_delegate_->GetEventRouter())
    return testing_delegate_->GetEventRouter();
  // TODO(fgorski): check and create the event router for JS routing.
  return js_event_router_.get();
}

void GCMProfileService::DeleteRegistrationInfo(const std::string& app_id) {
  extensions::StateStore* storage =
      extensions::ExtensionSystem::Get(profile_)->state_store();
  DCHECK(storage);

  storage->RemoveExtensionValue(app_id, kRegistrationKey);
}

void GCMProfileService::WriteRegistrationInfo(const std::string& app_id) {
  extensions::StateStore* storage =
      extensions::ExtensionSystem::Get(profile_)->state_store();
  DCHECK(storage);

  RegistrationInfoMap::const_iterator registration_info_iter =
      registration_info_map_.find(app_id);
  if (registration_info_iter == registration_info_map_.end())
    return;
  const RegistrationInfo& registration_info = registration_info_iter->second;

  scoped_ptr<base::ListValue> senders_list(new base::ListValue());
  for (std::vector<std::string>::const_iterator senders_iter =
           registration_info.sender_ids.begin();
       senders_iter != registration_info.sender_ids.end();
       ++senders_iter) {
    senders_list->AppendString(*senders_iter);
  }

  scoped_ptr<base::DictionaryValue> registration_info_dict(
      new base::DictionaryValue());
  registration_info_dict->Set(kSendersKey, senders_list.release());
  registration_info_dict->SetString(kRegistrationIDKey,
                                    registration_info.registration_id);

  storage->SetExtensionValue(
      app_id, kRegistrationKey, registration_info_dict.PassAs<base::Value>());
}

void GCMProfileService::ReadRegistrationInfo(const std::string& app_id) {
  delayed_task_controller_->AddApp(app_id);

  extensions::StateStore* storage =
      extensions::ExtensionSystem::Get(profile_)->state_store();
  DCHECK(storage);
  storage->GetExtensionValue(
      app_id,
      kRegistrationKey,
      base::Bind(
          &GCMProfileService::ReadRegistrationInfoFinished,
          weak_ptr_factory_.GetWeakPtr(),
          app_id));
}

void GCMProfileService::ReadRegistrationInfoFinished(
    const std::string& app_id,
    scoped_ptr<base::Value> value) {
  RegistrationInfo registration_info;
  if (value &&
     !ParsePersistedRegistrationInfo(value.Pass(), &registration_info)) {
    // Delete the persisted data if it is corrupted.
    DeleteRegistrationInfo(app_id);
  }

  if (registration_info.IsValid())
    registration_info_map_[app_id] = registration_info;

  delayed_task_controller_->SetAppReady(app_id);
}

bool GCMProfileService::ParsePersistedRegistrationInfo(
    scoped_ptr<base::Value> value,
    RegistrationInfo* registration_info) {
  base::DictionaryValue* dict = NULL;
  if (!value.get() || !value->GetAsDictionary(&dict))
    return false;

  if (!dict->GetString(kRegistrationIDKey, &registration_info->registration_id))
    return false;

  const base::ListValue* senders_list = NULL;
  if (!dict->GetList(kSendersKey, &senders_list) || !senders_list->GetSize())
    return false;
  for (size_t i = 0; i < senders_list->GetSize(); ++i) {
    std::string sender;
    if (!senders_list->GetString(i, &sender))
      return false;
    registration_info->sender_ids.push_back(sender);
  }

  return true;
}

// static
const char* GCMProfileService::GetPersistentRegisterKeyForTesting() {
  return kRegistrationKey;
}

}  // namespace gcm