This source file includes following definitions.
- observer_
- DoWrite
- OpenFile
- IncrementIndent
- DecrementIndent
- NotifyOnFinish
- Write
- Write
- WriteIndent
- WriteTime
- WriteNode
- observer_
- ExportBookmarks
- Observe
- ExtractUrls
- ExecuteWriter
- FetchNextFavicon
- OnFaviconDataAvailable
- WriteBookmarks
#include "chrome/browser/bookmarks/bookmark_html_writer.h"
#include "base/base64.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/files/file.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/platform_file.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/bookmark_codec.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/favicon/favicon_service.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/common/favicon/favicon_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_source.h"
#include "grit/generated_resources.h"
#include "net/base/escape.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/favicon_size.h"
using content::BrowserThread;
namespace {
static BookmarkFaviconFetcher* fetcher = NULL;
const char kHeader[] =
"<!DOCTYPE NETSCAPE-Bookmark-file-1>\r\n"
"<!-- This is an automatically generated file.\r\n"
" It will be read and overwritten.\r\n"
" DO NOT EDIT! -->\r\n"
"<META HTTP-EQUIV=\"Content-Type\""
" CONTENT=\"text/html; charset=UTF-8\">\r\n"
"<TITLE>Bookmarks</TITLE>\r\n"
"<H1>Bookmarks</H1>\r\n"
"<DL><p>\r\n";
const char kNewline[] = "\r\n";
const char kBookmarkStart[] = "<DT><A HREF=\"";
const char kAddDate[] = "\" ADD_DATE=\"";
const char kIcon[] = "\" ICON=\"";
const char kBookmarkAttributeEnd[] = "\">";
const char kBookmarkEnd[] = "</A>";
const char kFolderStart[] = "<DT><H3 ADD_DATE=\"";
const char kLastModified[] = "\" LAST_MODIFIED=\"";
const char kBookmarkBar[] = "\" PERSONAL_TOOLBAR_FOLDER=\"true\">";
const char kFolderAttributeEnd[] = "\">";
const char kFolderEnd[] = "</H3>";
const char kFolderChildren[] = "<DL><p>";
const char kFolderChildrenEnd[] = "</DL><p>";
const size_t kIndentSize = 4;
class Writer : public base::RefCountedThreadSafe<Writer> {
public:
Writer(base::Value* bookmarks,
const base::FilePath& path,
BookmarkFaviconFetcher::URLFaviconMap* favicons_map,
BookmarksExportObserver* observer)
: bookmarks_(bookmarks),
path_(path),
favicons_map_(favicons_map),
observer_(observer) {
}
void DoWrite() {
if (!OpenFile())
return;
base::Value* roots = NULL;
if (!Write(kHeader) ||
bookmarks_->GetType() != base::Value::TYPE_DICTIONARY ||
!static_cast<base::DictionaryValue*>(bookmarks_.get())->Get(
BookmarkCodec::kRootsKey, &roots) ||
roots->GetType() != base::Value::TYPE_DICTIONARY) {
NOTREACHED();
return;
}
base::DictionaryValue* roots_d_value =
static_cast<base::DictionaryValue*>(roots);
base::Value* root_folder_value;
base::Value* other_folder_value = NULL;
base::Value* mobile_folder_value = NULL;
if (!roots_d_value->Get(BookmarkCodec::kRootFolderNameKey,
&root_folder_value) ||
root_folder_value->GetType() != base::Value::TYPE_DICTIONARY ||
!roots_d_value->Get(BookmarkCodec::kOtherBookmarkFolderNameKey,
&other_folder_value) ||
other_folder_value->GetType() != base::Value::TYPE_DICTIONARY ||
!roots_d_value->Get(BookmarkCodec::kMobileBookmarkFolderNameKey,
&mobile_folder_value) ||
mobile_folder_value->GetType() != base::Value::TYPE_DICTIONARY) {
NOTREACHED();
return;
}
IncrementIndent();
if (!WriteNode(*static_cast<base::DictionaryValue*>(root_folder_value),
BookmarkNode::BOOKMARK_BAR) ||
!WriteNode(*static_cast<base::DictionaryValue*>(other_folder_value),
BookmarkNode::OTHER_NODE) ||
!WriteNode(*static_cast<base::DictionaryValue*>(mobile_folder_value),
BookmarkNode::MOBILE)) {
return;
}
DecrementIndent();
Write(kFolderChildrenEnd);
Write(kNewline);
file_.reset();
NotifyOnFinish();
}
private:
friend class base::RefCountedThreadSafe<Writer>;
enum TextType {
ATTRIBUTE_VALUE,
CONTENT
};
~Writer() {}
bool OpenFile() {
int flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
file_.reset(new base::File(path_, flags));
return file_->IsValid();
}
void IncrementIndent() {
indent_.resize(indent_.size() + kIndentSize, ' ');
}
void DecrementIndent() {
DCHECK(!indent_.empty());
indent_.resize(indent_.size() - kIndentSize, ' ');
}
void NotifyOnFinish() {
if (observer_ != NULL) {
observer_->OnExportFinished();
}
}
bool Write(const std::string& text) {
if (!text.length())
return true;
size_t wrote = file_->WriteAtCurrentPos(text.c_str(), text.length());
bool result = (wrote == text.length());
DCHECK(result);
return result;
}
bool Write(const std::string& text, TextType type) {
DCHECK(IsStringUTF8(text));
std::string utf8_string;
switch (type) {
case ATTRIBUTE_VALUE:
utf8_string = text;
ReplaceSubstringsAfterOffset(&utf8_string, 0, "\"", """);
break;
case CONTENT:
utf8_string = net::EscapeForHTML(text);
break;
default:
NOTREACHED();
}
return Write(utf8_string);
}
bool WriteIndent() {
return Write(indent_);
}
bool WriteTime(const std::string& time_string) {
int64 internal_value;
base::StringToInt64(time_string, &internal_value);
return Write(base::Int64ToString(
base::Time::FromInternalValue(internal_value).ToTimeT()));
}
bool WriteNode(const base::DictionaryValue& value,
BookmarkNode::Type folder_type) {
std::string title, date_added_string, type_string;
if (!value.GetString(BookmarkCodec::kNameKey, &title) ||
!value.GetString(BookmarkCodec::kDateAddedKey, &date_added_string) ||
!value.GetString(BookmarkCodec::kTypeKey, &type_string) ||
(type_string != BookmarkCodec::kTypeURL &&
type_string != BookmarkCodec::kTypeFolder)) {
NOTREACHED();
return false;
}
if (type_string == BookmarkCodec::kTypeURL) {
std::string url_string;
if (!value.GetString(BookmarkCodec::kURLKey, &url_string)) {
NOTREACHED();
return false;
}
std::string favicon_string;
BookmarkFaviconFetcher::URLFaviconMap::iterator itr =
favicons_map_->find(url_string);
if (itr != favicons_map_->end()) {
scoped_refptr<base::RefCountedMemory> data(itr->second.get());
std::string favicon_base64_encoded;
base::Base64Encode(std::string(data->front_as<char>(), data->size()),
&favicon_base64_encoded);
GURL favicon_url("data:image/png;base64," + favicon_base64_encoded);
favicon_string = favicon_url.spec();
}
if (!WriteIndent() ||
!Write(kBookmarkStart) ||
!Write(url_string, ATTRIBUTE_VALUE) ||
!Write(kAddDate) ||
!WriteTime(date_added_string) ||
(!favicon_string.empty() &&
(!Write(kIcon) ||
!Write(favicon_string, ATTRIBUTE_VALUE))) ||
!Write(kBookmarkAttributeEnd) ||
!Write(title, CONTENT) ||
!Write(kBookmarkEnd) ||
!Write(kNewline)) {
return false;
}
return true;
}
std::string last_modified_date;
const base::Value* child_values = NULL;
if (!value.GetString(BookmarkCodec::kDateModifiedKey,
&last_modified_date) ||
!value.Get(BookmarkCodec::kChildrenKey, &child_values) ||
child_values->GetType() != base::Value::TYPE_LIST) {
NOTREACHED();
return false;
}
if (folder_type != BookmarkNode::OTHER_NODE &&
folder_type != BookmarkNode::MOBILE) {
if (!WriteIndent() ||
!Write(kFolderStart) ||
!WriteTime(date_added_string) ||
!Write(kLastModified) ||
!WriteTime(last_modified_date)) {
return false;
}
if (folder_type == BookmarkNode::BOOKMARK_BAR) {
if (!Write(kBookmarkBar))
return false;
title = l10n_util::GetStringUTF8(IDS_BOOKMARK_BAR_FOLDER_NAME);
} else if (!Write(kFolderAttributeEnd)) {
return false;
}
if (!Write(title, CONTENT) ||
!Write(kFolderEnd) ||
!Write(kNewline) ||
!WriteIndent() ||
!Write(kFolderChildren) ||
!Write(kNewline)) {
return false;
}
IncrementIndent();
}
const base::ListValue* children =
static_cast<const base::ListValue*>(child_values);
for (size_t i = 0; i < children->GetSize(); ++i) {
const base::Value* child_value;
if (!children->Get(i, &child_value) ||
child_value->GetType() != base::Value::TYPE_DICTIONARY) {
NOTREACHED();
return false;
}
if (!WriteNode(*static_cast<const base::DictionaryValue*>(child_value),
BookmarkNode::FOLDER)) {
return false;
}
}
if (folder_type != BookmarkNode::OTHER_NODE &&
folder_type != BookmarkNode::MOBILE) {
DecrementIndent();
if (!WriteIndent() ||
!Write(kFolderChildrenEnd) ||
!Write(kNewline)) {
return false;
}
}
return true;
}
scoped_ptr<base::Value> bookmarks_;
base::FilePath path_;
scoped_ptr<BookmarkFaviconFetcher::URLFaviconMap> favicons_map_;
BookmarksExportObserver* observer_;
scoped_ptr<base::File> file_;
std::string indent_;
DISALLOW_COPY_AND_ASSIGN(Writer);
};
}
BookmarkFaviconFetcher::BookmarkFaviconFetcher(
Profile* profile,
const base::FilePath& path,
BookmarksExportObserver* observer)
: profile_(profile),
path_(path),
observer_(observer) {
favicons_map_.reset(new URLFaviconMap());
registrar_.Add(this,
chrome::NOTIFICATION_PROFILE_DESTROYED,
content::Source<Profile>(profile_));
}
BookmarkFaviconFetcher::~BookmarkFaviconFetcher() {
}
void BookmarkFaviconFetcher::ExportBookmarks() {
ExtractUrls(BookmarkModelFactory::GetForProfile(
profile_)->bookmark_bar_node());
ExtractUrls(BookmarkModelFactory::GetForProfile(profile_)->other_node());
ExtractUrls(BookmarkModelFactory::GetForProfile(profile_)->mobile_node());
if (!bookmark_urls_.empty())
FetchNextFavicon();
else
ExecuteWriter();
}
void BookmarkFaviconFetcher::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (chrome::NOTIFICATION_PROFILE_DESTROYED == type && fetcher != NULL) {
base::MessageLoop::current()->DeleteSoon(FROM_HERE, fetcher);
fetcher = NULL;
}
}
void BookmarkFaviconFetcher::ExtractUrls(const BookmarkNode* node) {
if (node->is_url()) {
std::string url = node->url().spec();
if (!url.empty())
bookmark_urls_.push_back(url);
} else {
for (int i = 0; i < node->child_count(); ++i)
ExtractUrls(node->GetChild(i));
}
}
void BookmarkFaviconFetcher::ExecuteWriter() {
BookmarkCodec codec;
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&Writer::DoWrite,
new Writer(codec.Encode(BookmarkModelFactory::GetForProfile(
profile_)),
path_, favicons_map_.release(), observer_)));
if (fetcher != NULL) {
base::MessageLoop::current()->DeleteSoon(FROM_HERE, fetcher);
fetcher = NULL;
}
}
bool BookmarkFaviconFetcher::FetchNextFavicon() {
if (bookmark_urls_.empty()) {
return false;
}
do {
std::string url = bookmark_urls_.front();
URLFaviconMap::const_iterator iter = favicons_map_->find(url);
if (favicons_map_->end() == iter) {
FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
profile_, Profile::EXPLICIT_ACCESS);
favicon_service->GetRawFaviconForURL(
FaviconService::FaviconForURLParams(
GURL(url), chrome::FAVICON, gfx::kFaviconSize),
ui::SCALE_FACTOR_100P,
base::Bind(&BookmarkFaviconFetcher::OnFaviconDataAvailable,
base::Unretained(this)),
&cancelable_task_tracker_);
return true;
} else {
bookmark_urls_.pop_front();
}
} while (!bookmark_urls_.empty());
return false;
}
void BookmarkFaviconFetcher::OnFaviconDataAvailable(
const chrome::FaviconBitmapResult& bitmap_result) {
GURL url;
if (!bookmark_urls_.empty()) {
url = GURL(bookmark_urls_.front());
bookmark_urls_.pop_front();
}
if (bitmap_result.is_valid() && !url.is_empty()) {
favicons_map_->insert(
make_pair(url.spec(), bitmap_result.bitmap_data));
}
if (FetchNextFavicon()) {
return;
}
ExecuteWriter();
}
namespace bookmark_html_writer {
void WriteBookmarks(Profile* profile,
const base::FilePath& path,
BookmarksExportObserver* observer) {
if (fetcher == NULL) {
fetcher = new BookmarkFaviconFetcher(profile, path, observer);
fetcher->ExportBookmarks();
}
}
}