summaryrefslogtreecommitdiffstats
path: root/components/enhanced_bookmarks/bookmark_server_cluster_service.cc
blob: d58bf5c6f68d7243367e90121d20931622be0c45 (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
// Copyright 2014 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 "components/enhanced_bookmarks/bookmark_server_cluster_service.h"

#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/prefs/pref_service.h"
#include "base/values.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/enhanced_bookmarks/enhanced_bookmark_model.h"
#include "components/enhanced_bookmarks/enhanced_bookmark_utils.h"
#include "components/enhanced_bookmarks/pref_names.h"
#include "components/enhanced_bookmarks/proto/cluster.pb.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/sync_driver/sync_service.h"
#include "net/base/url_util.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_context_getter.h"

using bookmarks::BookmarkNode;

namespace {
const char kClusterUrl[] = "https://www.google.com/stars/cluster";
const int kPrefServiceVersion = 1;
const char kPrefServiceVersionKey[] = "version";
const char kPrefServiceDataKey[] = "data";
const char kAuthIdKey[] = "auth_id";
}  // namespace

namespace enhanced_bookmarks {

BookmarkServerClusterService::BookmarkServerClusterService(
    const std::string& application_language_code,
    scoped_refptr<net::URLRequestContextGetter> request_context_getter,
    ProfileOAuth2TokenService* token_service,
    SigninManagerBase* signin_manager,
    enhanced_bookmarks::EnhancedBookmarkModel* enhanced_bookmark_model,
    sync_driver::SyncService* sync_service,
    PrefService* pref_service)
    : BookmarkServerService(request_context_getter,
                            token_service,
                            signin_manager,
                            enhanced_bookmark_model),
      application_language_code_(application_language_code),
      sync_service_(sync_service),
      pref_service_(pref_service),
      sync_refresh_skipped_(false),
      refreshes_needed_(0) {
  LoadModel();

  if (model_->loaded())
    TriggerTokenRequest(false);

  GetSigninManager()->AddObserver(this);
  if (sync_service_)
    sync_service_->AddObserver(this);
}

BookmarkServerClusterService::~BookmarkServerClusterService() {
}

void BookmarkServerClusterService::Shutdown() {
  if (sync_service_)
    sync_service_->RemoveObserver(this);
  GetSigninManager()->RemoveObserver(this);
}

const std::vector<const BookmarkNode*>
BookmarkServerClusterService::BookmarksForClusterNamed(
    const std::string& cluster_name) const {
  std::vector<const BookmarkNode*> results;

  ClusterMap::const_iterator cluster_it = cluster_data_.find(cluster_name);
  if (cluster_it == cluster_data_.end())
    return results;

  for (auto& star_id : cluster_it->second) {
    const BookmarkNode* bookmark = BookmarkForRemoteId(star_id);
    if (bookmark)
      results.push_back(bookmark);
  }
  return results;
}

const std::vector<std::string>
BookmarkServerClusterService::ClustersForBookmark(
    const BookmarkNode* bookmark) const {
  const std::string& star_id = RemoteIDForBookmark(bookmark);

  // TODO(noyau): if this turns out to be a perf bottleneck this may be improved
  // by storing a reverse map from id to cluster.
  std::vector<std::string> clusters;
  for (auto& pair : cluster_data_) {
    const std::vector<std::string>& stars_ids = pair.second;
    if (std::find(stars_ids.begin(), stars_ids.end(), star_id) !=
        stars_ids.end())
      clusters.push_back(pair.first);
  }
  return clusters;
}

const std::vector<std::string> BookmarkServerClusterService::GetClusters()
    const {
  std::vector<std::string> cluster_names;

  for (auto& pair : cluster_data_) {
    for (auto& star_id : pair.second) {
      const BookmarkNode* bookmark = BookmarkForRemoteId(star_id);
      if (bookmark) {
        // Only add clusters that have children.
        cluster_names.push_back(pair.first);
        break;
      }
    }
  }

  return cluster_names;
}

void BookmarkServerClusterService::AddObserver(
    enhanced_bookmarks::BookmarkServerServiceObserver* observer) {
  BookmarkServerService::AddObserver(observer);
  if (sync_refresh_skipped_) {
    TriggerTokenRequest(false);
    sync_refresh_skipped_ = true;
  }
}

// static
void BookmarkServerClusterService::RegisterPrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterDictionaryPref(prefs::kBookmarkClusters);
}

scoped_ptr<net::URLFetcher> BookmarkServerClusterService::CreateFetcher() {
  // Add the necessary arguments to the URI.
  GURL url(kClusterUrl);
  url = net::AppendQueryParameter(url, "output", "proto");

  // Append language.
  if (!application_language_code_.empty())
    url = net::AppendQueryParameter(url, "hl", application_language_code_);

  url = net::AppendQueryParameter(url, "v", model_->GetVersionString());

  // Build the URLFetcher to perform the request.
  scoped_ptr<net::URLFetcher> url_fetcher =
      net::URLFetcher::Create(url, net::URLFetcher::POST, this);

  // Binary encode a basic request proto.
  image_collections::ClusterRequest request_proto;
  request_proto.set_cluster_all(true);

  std::string proto_output;
  bool result = request_proto.SerializePartialToString(&proto_output);
  DCHECK(result);

  url_fetcher->SetUploadData("application/octet-stream", proto_output);
  return url_fetcher;
}

bool BookmarkServerClusterService::ProcessResponse(const std::string& response,
                                                   bool* should_notify) {
  DCHECK(*should_notify);
  image_collections::ClusterResponse response_proto;
  bool result = response_proto.ParseFromString(response);
  if (!result)
    return false;  // Not formatted properly.

  ClusterMap new_cluster_data;
  for (const auto& cluster : response_proto.clusters()) {
    const std::string& title = cluster.title();
    if (title.empty())
      continue;
    std::vector<std::string> stars_ids;
    for (auto& doc : cluster.docs()) {
      if (!doc.empty())
        stars_ids.push_back(doc);
    }
    if (stars_ids.size())
      new_cluster_data[title] = stars_ids;
  }

  if (new_cluster_data.size() == cluster_data_.size() &&
      std::equal(new_cluster_data.begin(),
                 new_cluster_data.end(),
                 cluster_data_.begin())) {
    *should_notify = false;
  } else {
    SwapModel(&new_cluster_data);
  }
  return true;
}

void BookmarkServerClusterService::CleanAfterFailure() {
  if (cluster_data_.empty())
    return;

  ClusterMap empty;
  SwapModel(&empty);
}

void BookmarkServerClusterService::EnhancedBookmarkModelLoaded() {
  TriggerTokenRequest(false);
}

void BookmarkServerClusterService::EnhancedBookmarkAdded(
    const BookmarkNode* node) {
  InvalidateCache();
}

void BookmarkServerClusterService::EnhancedBookmarkRemoved(
    const BookmarkNode* node) {
  // It is possible to remove the entries from the map here, but as those are
  // filtered in ClustersForBookmark() this is not strictly necessary.
  InvalidateCache();
}

void BookmarkServerClusterService::EnhancedBookmarkNodeChanged(
    const BookmarkNode* node) {
  InvalidateCache();
}

void BookmarkServerClusterService::EnhancedBookmarkAllUserNodesRemoved() {
  if (!cluster_data_.empty()) {
    ClusterMap empty;
    SwapModel(&empty);
  }
}

void BookmarkServerClusterService::EnhancedBookmarkRemoteIdChanged(
    const BookmarkNode* node,
    const std::string& old_remote_id,
    const std::string& remote_id) {
  std::vector<std::string> clusters;
  for (auto& pair : cluster_data_) {
    std::vector<std::string>& stars_ids = pair.second;
    std::replace(stars_ids.begin(), stars_ids.end(), old_remote_id, remote_id);
  }
}

void BookmarkServerClusterService::GoogleSignedOut(
    const std::string& account_id,
    const std::string& username) {
  if (!cluster_data_.empty()) {
    ClusterMap empty;
    SwapModel(&empty);
  }
}

void BookmarkServerClusterService::SwapModel(ClusterMap* cluster_map) {
  cluster_data_.swap(*cluster_map);
  const std::string& auth_id = GetSigninManager()->GetAuthenticatedAccountId();
  scoped_ptr<base::DictionaryValue> dictionary(
      Serialize(cluster_data_, auth_id));
  pref_service_->Set(prefs::kBookmarkClusters, *dictionary);
}

void BookmarkServerClusterService::LoadModel() {
  const base::DictionaryValue* dictionary =
      pref_service_->GetDictionary(prefs::kBookmarkClusters);
  const std::string& auth_id = GetSigninManager()->GetAuthenticatedAccountId();

  ClusterMap loaded_data;
  bool result = BookmarkServerClusterService::Deserialize(
      *dictionary, auth_id, &loaded_data);
  if (result)
    cluster_data_.swap(loaded_data);
}

void BookmarkServerClusterService::OnStateChanged() {
  // Do nothing.
}

void BookmarkServerClusterService::OnSyncCycleCompleted() {
  // The stars cluster API relies on the information in chrome-sync. Sending a
  // cluster request immediately after a bookmark is changed from the bookmark
  // observer notification will yield the wrong results. The request must be
  // delayed until the sync cycle has completed.
  // Note that we will be skipping calling this cluster API if there is no
  // observer attached, because calling that is meaningless without UI to show.
  // We also will avoid requesting for clusters if the bookmark data hasn't
  // changed.
  if (refreshes_needed_ > 0) {
    DCHECK(model_->loaded());
    if (observers_.might_have_observers()) {
      TriggerTokenRequest(false);
      sync_refresh_skipped_ = false;
    } else {
      sync_refresh_skipped_ = true;
    }
    --refreshes_needed_;
  }
}

void BookmarkServerClusterService::InvalidateCache() {
  // Bookmark changes can happen locally or via sync. It is difficult to
  // determine if a given SyncCycle contains all the local modifications.
  //
  // Consider the following sequence:
  //  1. SyncCycleBeginning (bookmark version:1)
  //  2. Bookmarks mutate locally (bookmark version:2)
  //  3. SyncCycleCompleted (bookmark version:1)
  //
  // In this case, the bookmarks modified locally won't be sent to the server
  // until the next SyncCycleCompleted.  Since we can't accurately determine
  // if a bookmark change has been sent on a SyncCycleCompleted, we're always
  // assuming that we need to wait for 2 sync cycles.
  refreshes_needed_ = 2;
}

//
// Serialization.
//
// static
scoped_ptr<base::DictionaryValue> BookmarkServerClusterService::Serialize(
    const ClusterMap& cluster_map,
    const std::string& auth_id) {
  // Create a list of all clusters. For each cluster, make another list. The
  // first element in the list is the key (cluster name). All subsequent
  // elements are stars ids.
  scoped_ptr<base::ListValue> all_clusters(new base::ListValue);
  for (auto& pair : cluster_map) {
    scoped_ptr<base::ListValue> cluster(new base::ListValue);
    cluster->AppendString(pair.first);
    cluster->AppendStrings(pair.second);
    all_clusters->Append(cluster.release());
  }

  // The dictionary that will be serialized has two fields: a version field and
  // a data field.
  scoped_ptr<base::DictionaryValue> data(new base::DictionaryValue);
  data->SetInteger(kPrefServiceVersionKey, kPrefServiceVersion);
  data->Set(kPrefServiceDataKey, all_clusters.release());
  data->SetString(kAuthIdKey, auth_id);

  return data.Pass();
}

// static
bool BookmarkServerClusterService::Deserialize(
    const base::DictionaryValue& value,
    const std::string& auth_id,
    ClusterMap* out_map) {
  ClusterMap output;

  // Check version.
  int version;
  if (!value.GetInteger(kPrefServiceVersionKey, &version))
    return false;
  if (version != kPrefServiceVersion)
    return false;

  // Check auth id.
  std::string id;
  if (!value.GetString(kAuthIdKey, &id))
    return false;
  if (id != auth_id)
    return false;

  const base::ListValue* all_clusters = NULL;
  if (!value.GetList(kPrefServiceDataKey, &all_clusters))
    return false;

  for (size_t index = 0; index < all_clusters->GetSize(); ++index) {
    const base::ListValue* cluster = NULL;
    if (!all_clusters->GetList(index, &cluster))
      return false;
    if (cluster->GetSize() < 1)
      return false;
    std::string key;
    if (!cluster->GetString(0, &key))
      return false;
    std::vector<std::string> stars_ids;
    for (size_t index = 1; index < cluster->GetSize(); ++index) {
      std::string stars_id;
      if (!cluster->GetString(index, &stars_id))
        return false;
      stars_ids.push_back(stars_id);
    }
    output.insert(std::make_pair(key, stars_ids));
  }
  out_map->swap(output);
  return true;
}

}  // namespace enhanced_bookmarks