Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / components / enhanced_bookmarks / enhanced_bookmark_model.cc
blobe9b8baea3c910d39c3f13ca333604698f39a2770
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/enhanced_bookmarks/enhanced_bookmark_model.h"
7 #include <iomanip>
8 #include <sstream>
10 #include "base/base64.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/rand_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "components/bookmarks/browser/bookmark_model.h"
16 #include "components/bookmarks/browser/bookmark_node.h"
17 #include "components/enhanced_bookmarks/enhanced_bookmark_model_observer.h"
18 #include "components/enhanced_bookmarks/proto/metadata.pb.h"
19 #include "ui/base/models/tree_node_iterator.h"
20 #include "url/gurl.h"
22 namespace {
23 const char* kBookmarkBarId = "f_bookmarks_bar";
25 const char* kFlagsKey = "stars.flags";
26 const char* kIdKey = "stars.id";
27 const char* kImageDataKey = "stars.imageData";
28 const char* kNoteKey = "stars.note";
29 const char* kOldIdKey = "stars.oldId";
30 const char* kPageDataKey = "stars.pageData";
31 const char* kVersionKey = "stars.version";
33 const char* kBookmarkPrefix = "ebc_";
35 enum Flags {
36 // When set the server will attempt to fill in image and snippet information.
37 NEEDS_OFFLINE_PROCESSING = 0x1,
40 // Helper method for working with bookmark metainfo.
41 std::string DataForMetaInfoField(const BookmarkNode* node,
42 const std::string& field) {
43 std::string value;
44 if (!node->GetMetaInfo(field, &value))
45 return std::string();
47 std::string decoded;
48 if (!base::Base64Decode(value, &decoded))
49 return std::string();
51 return decoded;
54 // Helper method for working with ImageData_ImageInfo.
55 bool PopulateImageData(const image::collections::ImageData_ImageInfo& info,
56 GURL* out_url,
57 int* width,
58 int* height) {
59 if (!info.has_url() || !info.has_width() || !info.has_height())
60 return false;
62 GURL url(info.url());
63 if (!url.is_valid())
64 return false;
66 *out_url = url;
67 *width = info.width();
68 *height = info.height();
69 return true;
72 // Generate a random remote id, with a prefix that depends on whether the node
73 // is a folder or a bookmark.
74 std::string GenerateRemoteId() {
75 std::stringstream random_id;
76 random_id << kBookmarkPrefix;
78 // Generate 32 digit hex string random suffix.
79 random_id << std::hex << std::setfill('0') << std::setw(16);
80 random_id << base::RandUint64() << base::RandUint64();
81 return random_id.str();
83 } // namespace
85 namespace enhanced_bookmarks {
87 EnhancedBookmarkModel::EnhancedBookmarkModel(BookmarkModel* bookmark_model,
88 const std::string& version)
89 : bookmark_model_(bookmark_model),
90 loaded_(false),
91 version_(version),
92 weak_ptr_factory_(this) {
93 bookmark_model_->AddObserver(this);
94 if (bookmark_model_->loaded()) {
95 InitializeIdMap();
96 loaded_ = true;
100 EnhancedBookmarkModel::~EnhancedBookmarkModel() {
101 Shutdown();
104 void EnhancedBookmarkModel::Shutdown() {
105 if (bookmark_model_) {
106 FOR_EACH_OBSERVER(EnhancedBookmarkModelObserver,
107 observers_,
108 EnhancedBookmarkModelShuttingDown());
109 weak_ptr_factory_.InvalidateWeakPtrs();
110 bookmark_model_->RemoveObserver(this);
111 bookmark_model_ = NULL;
115 void EnhancedBookmarkModel::AddObserver(
116 EnhancedBookmarkModelObserver* observer) {
117 observers_.AddObserver(observer);
120 void EnhancedBookmarkModel::RemoveObserver(
121 EnhancedBookmarkModelObserver* observer) {
122 observers_.RemoveObserver(observer);
125 // Moves |node| to |new_parent| and inserts it at the given |index|.
126 void EnhancedBookmarkModel::Move(const BookmarkNode* node,
127 const BookmarkNode* new_parent,
128 int index) {
129 bookmark_model_->Move(node, new_parent, index);
132 // Adds a new folder node at the specified position.
133 const BookmarkNode* EnhancedBookmarkModel::AddFolder(
134 const BookmarkNode* parent,
135 int index,
136 const base::string16& title) {
137 return bookmark_model_->AddFolder(parent, index, title);
140 // Adds a url at the specified position.
141 const BookmarkNode* EnhancedBookmarkModel::AddURL(
142 const BookmarkNode* parent,
143 int index,
144 const base::string16& title,
145 const GURL& url,
146 const base::Time& creation_time) {
147 BookmarkNode::MetaInfoMap meta_info;
148 meta_info[kIdKey] = GenerateRemoteId();
149 return bookmark_model_->AddURLWithCreationTimeAndMetaInfo(
150 parent, index, title, url, creation_time, &meta_info);
153 std::string EnhancedBookmarkModel::GetRemoteId(const BookmarkNode* node) {
154 if (node == bookmark_model_->bookmark_bar_node())
155 return kBookmarkBarId;
157 std::string id;
158 if (!node->GetMetaInfo(kIdKey, &id))
159 return std::string();
160 return id;
163 const BookmarkNode* EnhancedBookmarkModel::BookmarkForRemoteId(
164 const std::string& remote_id) {
165 IdToNodeMap::iterator it = id_map_.find(remote_id);
166 if (it != id_map_.end())
167 return it->second;
168 return NULL;
171 void EnhancedBookmarkModel::SetDescription(const BookmarkNode* node,
172 const std::string& description) {
173 SetMetaInfo(node, kNoteKey, description);
176 std::string EnhancedBookmarkModel::GetDescription(const BookmarkNode* node) {
177 // First, look for a custom note set by the user.
178 std::string description;
179 if (node->GetMetaInfo(kNoteKey, &description) && !description.empty())
180 return description;
182 // If none are present, return the snippet.
183 return GetSnippet(node);
186 bool EnhancedBookmarkModel::SetOriginalImage(const BookmarkNode* node,
187 const GURL& url,
188 int width,
189 int height) {
190 DCHECK(node->is_url());
191 DCHECK(url.is_valid());
193 std::string decoded(DataForMetaInfoField(node, kImageDataKey));
194 image::collections::ImageData data;
196 // Try to populate the imageData with the existing data.
197 if (decoded != "") {
198 // If the parsing fails, something is wrong. Immediately fail.
199 bool result = data.ParseFromString(decoded);
200 if (!result)
201 return false;
204 scoped_ptr<image::collections::ImageData_ImageInfo> info(
205 new image::collections::ImageData_ImageInfo);
206 info->set_url(url.spec());
207 info->set_width(width);
208 info->set_height(height);
209 data.set_allocated_original_info(info.release());
211 std::string output;
212 bool result = data.SerializePartialToString(&output);
213 if (!result)
214 return false;
216 std::string encoded;
217 base::Base64Encode(output, &encoded);
218 SetMetaInfo(node, kImageDataKey, encoded);
219 return true;
222 bool EnhancedBookmarkModel::GetOriginalImage(const BookmarkNode* node,
223 GURL* url,
224 int* width,
225 int* height) {
226 std::string decoded(DataForMetaInfoField(node, kImageDataKey));
227 if (decoded == "")
228 return false;
230 image::collections::ImageData data;
231 bool result = data.ParseFromString(decoded);
232 if (!result)
233 return false;
235 if (!data.has_original_info())
236 return false;
238 return PopulateImageData(data.original_info(), url, width, height);
241 bool EnhancedBookmarkModel::GetThumbnailImage(const BookmarkNode* node,
242 GURL* url,
243 int* width,
244 int* height) {
245 std::string decoded(DataForMetaInfoField(node, kImageDataKey));
246 if (decoded == "")
247 return false;
249 image::collections::ImageData data;
250 bool result = data.ParseFromString(decoded);
251 if (!result)
252 return false;
254 if (!data.has_thumbnail_info())
255 return false;
257 return PopulateImageData(data.thumbnail_info(), url, width, height);
260 std::string EnhancedBookmarkModel::GetSnippet(const BookmarkNode* node) {
261 std::string decoded(DataForMetaInfoField(node, kPageDataKey));
262 if (decoded.empty())
263 return decoded;
265 image::collections::PageData data;
266 bool result = data.ParseFromString(decoded);
267 if (!result)
268 return std::string();
270 return data.snippet();
273 void EnhancedBookmarkModel::SetVersionSuffix(
274 const std::string& version_suffix) {
275 version_suffix_ = version_suffix;
278 void EnhancedBookmarkModel::BookmarkModelChanged() {
281 void EnhancedBookmarkModel::BookmarkModelLoaded(BookmarkModel* model,
282 bool ids_reassigned) {
283 InitializeIdMap();
284 loaded_ = true;
285 FOR_EACH_OBSERVER(
286 EnhancedBookmarkModelObserver, observers_, EnhancedBookmarkModelLoaded());
289 void EnhancedBookmarkModel::BookmarkNodeAdded(BookmarkModel* model,
290 const BookmarkNode* parent,
291 int index) {
292 const BookmarkNode* node = parent->GetChild(index);
293 std::string remote_id;
294 if (node->GetMetaInfo(kIdKey, &remote_id)) {
295 AddToIdMap(node);
296 ScheduleResetDuplicateRemoteIds();
297 } else if (node->is_url()) {
298 set_needs_offline_processing_tasks_[node] =
299 make_linked_ptr(new base::CancelableClosure(
300 base::Bind(&EnhancedBookmarkModel::SetNeedsOfflineProcessing,
301 weak_ptr_factory_.GetWeakPtr(),
302 base::Unretained(node))));
303 base::MessageLoopProxy::current()->PostTask(
304 FROM_HERE, set_needs_offline_processing_tasks_[node]->callback());
306 FOR_EACH_OBSERVER(
307 EnhancedBookmarkModelObserver, observers_, EnhancedBookmarkAdded(node));
310 void EnhancedBookmarkModel::BookmarkNodeRemoved(
311 BookmarkModel* model,
312 const BookmarkNode* parent,
313 int old_index,
314 const BookmarkNode* node,
315 const std::set<GURL>& removed_urls) {
316 RemoveNodeFromMaps(node);
317 FOR_EACH_OBSERVER(
318 EnhancedBookmarkModelObserver, observers_, EnhancedBookmarkRemoved(node));
321 void EnhancedBookmarkModel::BookmarkNodeChanged(BookmarkModel* model,
322 const BookmarkNode* node) {
323 FOR_EACH_OBSERVER(
324 EnhancedBookmarkModelObserver, observers_,
325 EnhancedBookmarkNodeChanged(node));
328 void EnhancedBookmarkModel::OnWillChangeBookmarkMetaInfo(
329 BookmarkModel* model,
330 const BookmarkNode* node) {
331 prev_remote_id_ = GetRemoteId(node);
334 void EnhancedBookmarkModel::BookmarkMetaInfoChanged(BookmarkModel* model,
335 const BookmarkNode* node) {
336 std::string remote_id = GetRemoteId(node);
337 if (remote_id != prev_remote_id_) {
338 id_map_.erase(prev_remote_id_);
339 if (!remote_id.empty()) {
340 AddToIdMap(node);
341 ScheduleResetDuplicateRemoteIds();
343 FOR_EACH_OBSERVER(
344 EnhancedBookmarkModelObserver,
345 observers_,
346 EnhancedBookmarkRemoteIdChanged(node, prev_remote_id_, remote_id));
350 void EnhancedBookmarkModel::BookmarkAllUserNodesRemoved(
351 BookmarkModel* model,
352 const std::set<GURL>& removed_urls) {
353 id_map_.clear();
354 // Re-initialize so non-user nodes with remote ids are present in the map.
355 InitializeIdMap();
356 FOR_EACH_OBSERVER(EnhancedBookmarkModelObserver,
357 observers_,
358 EnhancedBookmarkAllUserNodesRemoved());
361 void EnhancedBookmarkModel::InitializeIdMap() {
362 ui::TreeNodeIterator<const BookmarkNode> iterator(
363 bookmark_model_->root_node());
364 while (iterator.has_next()) {
365 AddToIdMap(iterator.Next());
367 ScheduleResetDuplicateRemoteIds();
370 void EnhancedBookmarkModel::AddToIdMap(const BookmarkNode* node) {
371 std::string remote_id = GetRemoteId(node);
372 if (remote_id.empty())
373 return;
375 // Try to insert the node.
376 std::pair<IdToNodeMap::iterator, bool> result =
377 id_map_.insert(make_pair(remote_id, node));
378 if (!result.second) {
379 // Some node already had the same remote id, so add both nodes to the
380 // to-be-reset set.
381 nodes_to_reset_[result.first->second] = remote_id;
382 nodes_to_reset_[node] = remote_id;
386 void EnhancedBookmarkModel::RemoveNodeFromMaps(const BookmarkNode* node) {
387 for (int i = 0; i < node->child_count(); i++) {
388 RemoveNodeFromMaps(node->GetChild(i));
390 std::string remote_id = GetRemoteId(node);
391 id_map_.erase(remote_id);
392 nodes_to_reset_.erase(node);
393 set_needs_offline_processing_tasks_.erase(node);
396 void EnhancedBookmarkModel::ScheduleResetDuplicateRemoteIds() {
397 if (!nodes_to_reset_.empty()) {
398 base::MessageLoopProxy::current()->PostTask(
399 FROM_HERE,
400 base::Bind(&EnhancedBookmarkModel::ResetDuplicateRemoteIds,
401 weak_ptr_factory_.GetWeakPtr()));
405 void EnhancedBookmarkModel::ResetDuplicateRemoteIds() {
406 for (NodeToIdMap::iterator it = nodes_to_reset_.begin();
407 it != nodes_to_reset_.end();
408 ++it) {
409 BookmarkNode::MetaInfoMap meta_info;
410 meta_info[kIdKey] = "";
411 meta_info[kOldIdKey] = it->second;
412 SetMultipleMetaInfo(it->first, meta_info);
414 nodes_to_reset_.clear();
417 void EnhancedBookmarkModel::SetNeedsOfflineProcessing(
418 const BookmarkNode* node) {
419 set_needs_offline_processing_tasks_.erase(node);
420 int flags = 0;
421 std::string flags_str;
422 if (node->GetMetaInfo(kFlagsKey, &flags_str)) {
423 if (!base::StringToInt(flags_str, &flags))
424 flags = 0;
426 flags |= NEEDS_OFFLINE_PROCESSING;
427 SetMetaInfo(node, kFlagsKey, base::IntToString(flags));
430 void EnhancedBookmarkModel::SetMetaInfo(const BookmarkNode* node,
431 const std::string& field,
432 const std::string& value) {
433 DCHECK(!bookmark_model_->is_permanent_node(node));
435 BookmarkNode::MetaInfoMap meta_info;
436 const BookmarkNode::MetaInfoMap* old_meta_info = node->GetMetaInfoMap();
437 if (old_meta_info)
438 meta_info.insert(old_meta_info->begin(), old_meta_info->end());
440 // Don't update anything if the value to set is already there.
441 BookmarkNode::MetaInfoMap::iterator it = meta_info.find(field);
442 if (it != meta_info.end() && it->second == value)
443 return;
445 meta_info[field] = value;
446 meta_info[kVersionKey] = GetVersionString();
447 bookmark_model_->SetNodeMetaInfoMap(node, meta_info);
450 std::string EnhancedBookmarkModel::GetVersionString() {
451 if (version_suffix_.empty())
452 return version_;
453 return version_ + '/' + version_suffix_;
456 void EnhancedBookmarkModel::SetMultipleMetaInfo(
457 const BookmarkNode* node,
458 BookmarkNode::MetaInfoMap meta_info) {
459 DCHECK(!bookmark_model_->is_permanent_node(node));
461 // Don't update anything if every value is already set correctly.
462 if (node->GetMetaInfoMap()) {
463 bool changed = false;
464 const BookmarkNode::MetaInfoMap* old_meta_info = node->GetMetaInfoMap();
465 for (BookmarkNode::MetaInfoMap::iterator it = meta_info.begin();
466 it != meta_info.end();
467 ++it) {
468 BookmarkNode::MetaInfoMap::const_iterator old_field =
469 old_meta_info->find(it->first);
470 if (old_field == old_meta_info->end() ||
471 old_field->second != it->second) {
472 changed = true;
473 break;
476 if (!changed)
477 return;
479 // Fill in the values that aren't changing
480 meta_info.insert(old_meta_info->begin(), old_meta_info->end());
483 meta_info[kVersionKey] = GetVersionString();
484 bookmark_model_->SetNodeMetaInfoMap(node, meta_info);
487 bool EnhancedBookmarkModel::SetAllImages(const BookmarkNode* node,
488 const GURL& image_url,
489 int image_width,
490 int image_height,
491 const GURL& thumbnail_url,
492 int thumbnail_width,
493 int thumbnail_height) {
494 DCHECK(node->is_url());
495 DCHECK(image_url.is_valid() || image_url.is_empty());
496 DCHECK(thumbnail_url.is_valid() || thumbnail_url.is_empty());
497 std::string decoded(DataForMetaInfoField(node, kImageDataKey));
498 image::collections::ImageData data;
500 // Try to populate the imageData with the existing data.
501 if (decoded != "") {
502 // If the parsing fails, something is wrong. Immediately fail.
503 bool result = data.ParseFromString(decoded);
504 if (!result)
505 return false;
508 if (image_url.is_empty()) {
509 data.release_original_info();
510 } else {
511 // Regardless of whether an image info exists, we make a new one.
512 // Intentially make a raw pointer.
513 image::collections::ImageData_ImageInfo* info =
514 new image::collections::ImageData_ImageInfo;
515 info->set_url(image_url.spec());
516 info->set_width(image_width);
517 info->set_height(image_height);
518 // This method consumes the raw pointer.
519 data.set_allocated_original_info(info);
522 if (thumbnail_url.is_empty()) {
523 data.release_thumbnail_info();
524 } else {
525 // Regardless of whether an image info exists, we make a new one.
526 // Intentially make a raw pointer.
527 image::collections::ImageData_ImageInfo* info =
528 new image::collections::ImageData_ImageInfo;
529 info->set_url(thumbnail_url.spec());
530 info->set_width(thumbnail_width);
531 info->set_height(thumbnail_height);
532 // This method consumes the raw pointer.
533 data.set_allocated_thumbnail_info(info);
535 std::string output;
536 bool result = data.SerializePartialToString(&output);
537 if (!result)
538 return false;
540 std::string encoded;
541 base::Base64Encode(output, &encoded);
542 bookmark_model_->SetNodeMetaInfo(node, kImageDataKey, encoded);
543 return true;
546 } // namespace enhanced_bookmarks