From 32a31c66c74d351bb762860712d9284b9d3446b3 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Wed, 26 Feb 2020 14:43:45 -0700 Subject: [PATCH 01/79] Remove brave sync codes from chromium --- .../brave_bookmark_model_loaded_observer.cc | 25 - .../sync/profile_sync_service_factory.cc | 31 - .../sync/driver/glue/sync_engine_backend.cc | 75 - .../sync/driver/glue/sync_engine_impl.h | 14 - .../sync/driver/profile_sync_service.cc | 81 - .../sync/driver/profile_sync_service.h | 19 - .../components/sync/engine/sync_engine.h | 18 - .../components/sync/engine/sync_manager.h | 22 - .../components/sync/engine_impl/commit.cc | 193 --- .../sync/engine_impl/cycle/sync_cycle.h | 19 - .../sync/engine_impl/get_updates_processor.cc | 260 --- .../sync/engine_impl/get_updates_processor.h | 25 - .../sync/engine_impl/process_updates_util.cc | 15 - .../sync/engine_impl/sync_manager_impl.cc | 17 - .../sync/engine_impl/sync_scheduler_impl.cc | 32 - .../sync/engine_impl/sync_scheduler_impl.h | 24 - .../components/sync/engine_impl/syncer.cc | 34 - .../components/sync/engine_impl/syncer.h | 23 - .../sync/syncable/write_transaction.cc | 19 - .../sync/syncable/write_transaction.h | 19 - .../bookmark_model_type_processor.cc | 40 - .../bookmark_remote_updates_handler.cc | 28 - .../bookmark_specifics_conversions.cc | 26 - components/brave_sync/BUILD.gn | 2 - .../brave_profile_sync_service_impl.cc | 1425 ----------------- .../brave_profile_sync_service_impl.h | 350 ---- ...sync-profile_sync_service_factory.cc.patch | 13 - patches/components-sync-base-BUILD.gn.patch | 12 - ...c-driver-glue-sync_engine_backend.cc.patch | 12 - ...-sync-driver-glue-sync_engine_impl.h.patch | 12 - ...-sync-driver-profile_sync_service.cc.patch | 12 - ...s-sync-driver-profile_sync_service.h.patch | 12 - ...components-sync-engine-sync_engine.h.patch | 12 - ...omponents-sync-engine-sync_manager.h.patch | 12 - ...omponents-sync-engine_impl-commit.cc.patch | 12 - ...-sync-engine_impl-cycle-sync_cycle.h.patch | 12 - ...engine_impl-get_updates_processor.cc.patch | 12 - ...-engine_impl-get_updates_processor.h.patch | 12 - ...-engine_impl-process_updates_util.cc.patch | 12 - ...ync-engine_impl-sync_manager_impl.cc.patch | 15 - ...c-engine_impl-sync_scheduler_impl.cc.patch | 12 - ...nc-engine_impl-sync_scheduler_impl.h.patch | 12 - ...omponents-sync-engine_impl-syncer.cc.patch | 12 - ...components-sync-engine_impl-syncer.h.patch | 12 - ...ync-engine_impl-syncer_proto_util.cc.patch | 20 - ...s-sync-syncable-write_transaction.cc.patch | 12 - ...ts-sync-syncable-write_transaction.h.patch | 12 - ...s-bookmark_remote_updates_handler.cc.patch | 24 - 48 files changed, 3124 deletions(-) delete mode 100644 chromium_src/chrome/browser/sync/profile_sync_service_factory.cc delete mode 100644 chromium_src/components/sync/driver/glue/sync_engine_backend.cc delete mode 100644 chromium_src/components/sync/driver/glue/sync_engine_impl.h delete mode 100644 chromium_src/components/sync/driver/profile_sync_service.cc delete mode 100644 chromium_src/components/sync/driver/profile_sync_service.h delete mode 100644 chromium_src/components/sync/engine/sync_engine.h delete mode 100644 chromium_src/components/sync/engine/sync_manager.h delete mode 100644 chromium_src/components/sync/engine_impl/commit.cc delete mode 100644 chromium_src/components/sync/engine_impl/cycle/sync_cycle.h delete mode 100644 chromium_src/components/sync/engine_impl/get_updates_processor.cc delete mode 100644 chromium_src/components/sync/engine_impl/get_updates_processor.h delete mode 100644 chromium_src/components/sync/engine_impl/process_updates_util.cc delete mode 100644 chromium_src/components/sync/engine_impl/sync_manager_impl.cc delete mode 100644 chromium_src/components/sync/engine_impl/sync_scheduler_impl.cc delete mode 100644 chromium_src/components/sync/engine_impl/sync_scheduler_impl.h delete mode 100644 chromium_src/components/sync/engine_impl/syncer.cc delete mode 100644 chromium_src/components/sync/engine_impl/syncer.h delete mode 100644 chromium_src/components/sync/syncable/write_transaction.cc delete mode 100644 chromium_src/components/sync/syncable/write_transaction.h delete mode 100644 chromium_src/components/sync_bookmarks/bookmark_model_type_processor.cc delete mode 100644 chromium_src/components/sync_bookmarks/bookmark_remote_updates_handler.cc delete mode 100644 chromium_src/components/sync_bookmarks/bookmark_specifics_conversions.cc delete mode 100644 components/brave_sync/brave_profile_sync_service_impl.cc delete mode 100644 components/brave_sync/brave_profile_sync_service_impl.h delete mode 100644 patches/chrome-browser-sync-profile_sync_service_factory.cc.patch delete mode 100644 patches/components-sync-base-BUILD.gn.patch delete mode 100644 patches/components-sync-driver-glue-sync_engine_backend.cc.patch delete mode 100644 patches/components-sync-driver-glue-sync_engine_impl.h.patch delete mode 100644 patches/components-sync-driver-profile_sync_service.cc.patch delete mode 100644 patches/components-sync-driver-profile_sync_service.h.patch delete mode 100644 patches/components-sync-engine-sync_engine.h.patch delete mode 100644 patches/components-sync-engine-sync_manager.h.patch delete mode 100644 patches/components-sync-engine_impl-commit.cc.patch delete mode 100644 patches/components-sync-engine_impl-cycle-sync_cycle.h.patch delete mode 100644 patches/components-sync-engine_impl-get_updates_processor.cc.patch delete mode 100644 patches/components-sync-engine_impl-get_updates_processor.h.patch delete mode 100644 patches/components-sync-engine_impl-process_updates_util.cc.patch delete mode 100644 patches/components-sync-engine_impl-sync_manager_impl.cc.patch delete mode 100644 patches/components-sync-engine_impl-sync_scheduler_impl.cc.patch delete mode 100644 patches/components-sync-engine_impl-sync_scheduler_impl.h.patch delete mode 100644 patches/components-sync-engine_impl-syncer.cc.patch delete mode 100644 patches/components-sync-engine_impl-syncer.h.patch delete mode 100644 patches/components-sync-engine_impl-syncer_proto_util.cc.patch delete mode 100644 patches/components-sync-syncable-write_transaction.cc.patch delete mode 100644 patches/components-sync-syncable-write_transaction.h.patch delete mode 100644 patches/components-sync_bookmarks-bookmark_remote_updates_handler.cc.patch diff --git a/browser/profiles/brave_bookmark_model_loaded_observer.cc b/browser/profiles/brave_bookmark_model_loaded_observer.cc index 2d1bf2eeb919..5f1b1fd96497 100644 --- a/browser/profiles/brave_bookmark_model_loaded_observer.cc +++ b/browser/profiles/brave_bookmark_model_loaded_observer.cc @@ -12,12 +12,6 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/prefs/pref_service.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "brave/components/brave_sync/brave_profile_sync_service_impl.h" -using brave_sync::BraveProfileSyncServiceImpl; -#endif - using bookmarks::BookmarkModel; BraveBookmarkModelLoadedObserver::BraveBookmarkModelLoadedObserver( @@ -28,28 +22,9 @@ void BraveBookmarkModelLoadedObserver::BookmarkModelLoaded( BookmarkModel* model, bool ids_reassigned) { if (!profile_->GetPrefs()->GetBoolean(kOtherBookmarksMigrated)) { -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - BraveProfileSyncServiceImpl* brave_profile_service = - static_cast( - ProfileSyncServiceFactory::GetForProfile(profile_)); - // When sync is enabled, we need to send migration records to other devices - // so it is handled in BraveProfileSyncServiceImpl::OnSyncReady - if (!brave_profile_service || - (brave_profile_service && !brave_profile_service->IsBraveSyncEnabled())) - BraveMigrateOtherNodeFolder(model); -#else BraveMigrateOtherNodeFolder(model); -#endif profile_->GetPrefs()->SetBoolean(kOtherBookmarksMigrated, true); } -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - BraveProfileSyncServiceImpl::AddNonClonedBookmarkKeys(model); - BraveProfileSyncServiceImpl::MigrateDuplicatedBookmarksObjectIds( - base::FeatureList::IsEnabled(brave_sync::features::kBraveSync), - profile_, - model); -#endif - BookmarkModelLoadedObserver::BookmarkModelLoaded(model, ids_reassigned); } diff --git a/chromium_src/chrome/browser/sync/profile_sync_service_factory.cc b/chromium_src/chrome/browser/sync/profile_sync_service_factory.cc deleted file mode 100644 index 3c5a62c9e770..000000000000 --- a/chromium_src/chrome/browser/sync/profile_sync_service_factory.cc +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/sync/driver/profile_sync_service.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" - -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "brave/components/brave_sync/brave_profile_sync_service_impl.h" -using brave_sync::BraveProfileSyncServiceImpl; -#endif - -class Profile; - -namespace { - -std::unique_ptr BraveBuildServiceInstanceFor( - Profile* profile, - syncer::ProfileSyncService::InitParams init_params) { -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - return std::make_unique(profile, - std::move(init_params)); -#else - return std::make_unique(std::move(init_params)); -#endif -} - -} // namespace - -#include "../../../../../chrome/browser/sync/profile_sync_service_factory.cc" // NOLINT diff --git a/chromium_src/components/sync/driver/glue/sync_engine_backend.cc b/chromium_src/components/sync/driver/glue/sync_engine_backend.cc deleted file mode 100644 index 3dd9346e6a27..000000000000 --- a/chromium_src/components/sync/driver/glue/sync_engine_backend.cc +++ /dev/null @@ -1,75 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include - -#include "brave/components/brave_sync/buildflags/buildflags.h" -#include "components/sync/driver/glue/sync_engine_impl.h" -#include "components/sync/engine/sync_engine_host.h" - -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "base/memory/weak_ptr.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/public/brave_profile_sync_service.h" - -using brave_sync::BraveProfileSyncService; -using brave_sync::GetRecordsCallback; -using brave_sync::RecordsList; -#endif - -namespace syncer { - -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -SyncEngineHost* BraveGetSyncEngineHost(SyncEngineImpl* sync_engine) { - return sync_engine->host_; -} - -void OnNudgeSyncCycleOnOwnerThread(base::WeakPtr sync_engine, - brave_sync::RecordsListPtr records_list) { - if (sync_engine.get()) - static_cast( - BraveGetSyncEngineHost(sync_engine.get())) - ->OnNudgeSyncCycle(std::move(records_list)); -} - -void OnNudgeSyncCycle(WeakHandle sync_engine_impl, - brave_sync::RecordsListPtr records_list) { - sync_engine_impl.Call(FROM_HERE, &OnNudgeSyncCycleOnOwnerThread, - base::Passed(&records_list)); -} - -void OnPollSyncCycleOnOwnerThread(base::WeakPtr sync_engine, - GetRecordsCallback cb, - base::WaitableEvent* wevent) { - if (sync_engine.get()) - static_cast( - BraveGetSyncEngineHost(sync_engine.get())) - ->OnPollSyncCycle(std::move(cb), wevent); -} - -void OnPollSyncCycle(WeakHandle sync_engine_impl, - GetRecordsCallback cb, - base::WaitableEvent* wevent) { - sync_engine_impl.Call(FROM_HERE, &OnPollSyncCycleOnOwnerThread, - base::Passed(&cb), wevent); -} -#endif - -void BraveInit(WeakHandle sync_engine_impl, - SyncManager::InitArgs* args) { -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - DCHECK(args); - args->nudge_sync_cycle_delegate_function = - base::BindRepeating(&OnNudgeSyncCycle, sync_engine_impl); - args->poll_sync_cycle_delegate_function = - base::BindRepeating(&OnPollSyncCycle, sync_engine_impl); -#endif -} - -} // namespace syncer - -#define BRAVE_SYNC_ENGINE_BACKEND_DO_INITIALIZE BraveInit(host_, &args); - -#include "../../../../../../components/sync/driver/glue/sync_engine_backend.cc" // NOLINT diff --git a/chromium_src/components/sync/driver/glue/sync_engine_impl.h b/chromium_src/components/sync/driver/glue/sync_engine_impl.h deleted file mode 100644 index 98a3c9aa9129..000000000000 --- a/chromium_src/components/sync/driver/glue/sync_engine_impl.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_GLUE_SYNC_ENGINE_IMPL_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_GLUE_SYNC_ENGINE_IMPL_H_ - -#define BRAVE_SYNC_ENGINE_IMPL_H \ - friend SyncEngineHost* BraveGetSyncEngineHost(SyncEngineImpl*); - -#include "../../../../../../components/sync/driver/glue/sync_engine_impl.h" // NOLINT -#undef BRAVE_SYNC_ENGINE_IMPL_H -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_GLUE_SYNC_ENGINE_IMPL_H_ diff --git a/chromium_src/components/sync/driver/profile_sync_service.cc b/chromium_src/components/sync/driver/profile_sync_service.cc deleted file mode 100644 index 5b995a855e87..000000000000 --- a/chromium_src/components/sync/driver/profile_sync_service.cc +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/chromium_src/components/sync/driver/profile_sync_service.h" - -#include - -#include "brave/components/brave_sync/buildflags/buildflags.h" - -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "base/bind.h" -#include "base/memory/weak_ptr.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/public/brave_profile_sync_service.h" -#include "chrome/browser/sync/chrome_sync_client.h" -#include "content/public/browser/browser_thread.h" - -using brave_sync::BraveProfileSyncService; -#endif - -namespace syncer { - -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -const int64_t kBraveDefaultPollIntervalSeconds = 60; - -bool IsBraveSyncEnabled(ProfileSyncService* profile_sync_service) { - return static_cast(profile_sync_service) - ->IsBraveSyncEnabled(); -} - -void OnNudgeSyncCycle(base::WeakPtr profile_sync_service, - brave_sync::RecordsListPtr records_list) { - if (profile_sync_service.get()) { - static_cast(profile_sync_service.get()) - ->OnNudgeSyncCycle(std::move(records_list)); - } -} - -void OnPollSyncCycle(base::WeakPtr profile_sync_service, - brave_sync::GetRecordsCallback cb, - base::WaitableEvent* wevent) { - if (profile_sync_service.get()) { - static_cast(profile_sync_service.get()) - ->OnPollSyncCycle(std::move(cb), wevent); - } -} -#endif - -void BraveInit(base::WeakPtr profile_sync_service, - SyncPrefs* sync_prefs, - syncer::SyncEngine::InitParams* params) { -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - DCHECK(params); - params->nudge_sync_cycle_delegate_function = - base::BindRepeating(&OnNudgeSyncCycle, profile_sync_service); - params->poll_sync_cycle_delegate_function = - base::BindRepeating(&OnPollSyncCycle, profile_sync_service); - - sync_prefs->SetPollInterval( - base::TimeDelta::FromSeconds(syncer::kBraveDefaultPollIntervalSeconds)); -#endif -} - -} // namespace syncer - -// avoid redefining IsSyncFeatureEnabled in header -#include "components/sync/driver/sync_service.h" -// For use_transport_only_mode -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#define IsSyncFeatureEnabled() IsBraveSyncEnabled(this) -#endif -#define BRAVE_PROFILE_SYNC_SERVICE_START_UP_SLOW_ENGINE_COMPONENTS \ - BraveInit(sync_enabled_weak_factory_.GetWeakPtr(), &sync_prefs_, ¶ms); - -#include "../../../../components/sync/driver/profile_sync_service.cc" // NOLINT -#undef BRAVE_PROFILE_SYNC_SERVICE_START_UP_SLOW_ENGINE_COMPONENTS -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#undef IsSyncFeatureEnabled -#endif diff --git a/chromium_src/components/sync/driver/profile_sync_service.h b/chromium_src/components/sync/driver/profile_sync_service.h deleted file mode 100644 index e516f8872b60..000000000000 --- a/chromium_src/components/sync/driver/profile_sync_service.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_PROFILE_SYNC_SERVICE_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_PROFILE_SYNC_SERVICE_H_ - -namespace brave_sync { -class BraveProfileSyncServiceImpl; -} // namespace brave_sync - -#define BRAVE_PROFILE_SYNC_SERVICE_H \ - friend class brave_sync::BraveProfileSyncServiceImpl; - -#include "../../../../../components/sync/driver/profile_sync_service.h" -#undef BRAVE_PROFILE_SYNC_SERVICE_H - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_PROFILE_SYNC_SERVICE_H_ diff --git a/chromium_src/components/sync/engine/sync_engine.h b/chromium_src/components/sync/engine/sync_engine.h deleted file mode 100644 index 2b27b9836498..000000000000 --- a/chromium_src/components/sync/engine/sync_engine.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_ - -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -#define BRAVE_SYNC_ENGINE_INIT_PARAMS_H \ - brave_sync::NudgeSyncCycleDelegate nudge_sync_cycle_delegate_function; \ - brave_sync::PollSyncCycleDelegate poll_sync_cycle_delegate_function; - -#include "../../../../../components/sync/engine/sync_engine.h" -#undef BRAVE_SYNC_ENGINE_INIT_PARAMS_H - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_ diff --git a/chromium_src/components/sync/engine/sync_manager.h b/chromium_src/components/sync/engine/sync_manager.h deleted file mode 100644 index cd0a9e821e36..000000000000 --- a/chromium_src/components/sync/engine/sync_manager.h +++ /dev/null @@ -1,22 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_SYNC_MANAGER_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_SYNC_MANAGER_H_ - -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -namespace syncer { -class Syncer; -} // namespace syncer - -#define BRAVE_SYNC_MANAGER_INIT_ARGS_H \ - brave_sync::NudgeSyncCycleDelegate nudge_sync_cycle_delegate_function; \ - brave_sync::PollSyncCycleDelegate poll_sync_cycle_delegate_function; - -#include "../../../../../components/sync/engine/sync_manager.h" -#undef BRAVE_SYNC_MANAGER_INIT_ARGS_H - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_SYNC_MANAGER_H_ diff --git a/chromium_src/components/sync/engine_impl/commit.cc b/chromium_src/components/sync/engine_impl/commit.cc deleted file mode 100644 index 19ed5eb726d5..000000000000 --- a/chromium_src/components/sync/engine_impl/commit.cc +++ /dev/null @@ -1,193 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -namespace sync_pb { -class ClientToServerMessage; -class ClientToServerResponse; -} // namespace sync_pb - -namespace syncer { -class SyncCycle; -class SyncerError; -namespace { - -SyncerError PostBraveCommit(sync_pb::ClientToServerMessage* message, - sync_pb::ClientToServerResponse* response, - SyncCycle* cycle); -} - -} // namespace syncer - -#define BRAVE_COMMIT_POST_AND_PROCESS_RESPONSE \ - PostBraveCommit(&message_, &response, cycle); - -#include "../../../../../components/sync/engine_impl/commit.cc" // NOLINT -#undef BRAVE_COMMIT_POST_AND_PROCESS_RESPONSE - -#include "base/base64.h" -#include "brave/components/brave_sync/jslib_const.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/jslib_messages_fwd.h" -#include "brave/components/brave_sync/tools.h" -#include "components/sync/base/time.h" -#include "components/sync/base/unique_position.h" - -namespace syncer { -namespace { -using brave_sync::jslib::MetaInfo; -using brave_sync::jslib::SyncRecord; -// from components/sync_bookmarks/bookmark_model_merger.cc -const char kOtherBookmarksTag[] = "other_bookmarks"; - -void CreateSuccessfulCommitResponse( - const sync_pb::SyncEntity& entity, - sync_pb::CommitResponse::EntryResponse* response, - const std::string& new_object_id) { - response->set_response_type(sync_pb::CommitResponse::SUCCESS); - response->set_non_unique_name(entity.name()); - response->set_version(entity.version() + 1); - response->set_parent_id_string(entity.parent_id_string()); - - if (new_object_id.empty()) - response->set_id_string(entity.id_string()); - else - response->set_id_string(new_object_id); -} - -std::unique_ptr CreateOtherBookmarksRecord(SyncRecord* child) { - auto record = std::make_unique(); - record->objectData = brave_sync::jslib_const::SyncObjectData_BOOKMARK; - auto bookmark = std::make_unique(); - bookmark->site.title = brave_sync::tools::kOtherNodeName; - bookmark->site.customTitle = brave_sync::tools::kOtherNodeName; - // Special order reserved for "Other Bookmarks" folder, it only has effect on - // mobile. On desktop, it is used to distinguish "Other Bookmarks" from normal - // same name folder - bookmark->order = brave_sync::tools::kOtherNodeOrder; - bookmark->site.creationTime = child->GetBookmark().site.creationTime; - bookmark->isFolder = true; - - DCHECK(child->has_bookmark()); - record->objectId = child->GetBookmark().parentFolderObjectId; - record->action = brave_sync::jslib::SyncRecord::Action::A_CREATE; - record->syncTimestamp = child->syncTimestamp; - record->SetBookmark(std::move(bookmark)); - - return record; -} - -brave_sync::RecordsListPtr ConvertCommitsToBraveRecords( - sync_pb::ClientToServerMessage* message, - sync_pb::ClientToServerResponse* response) { - brave_sync::RecordsListPtr record_list = - std::make_unique(); - const sync_pb::CommitMessage& commit_message = message->commit(); - const std::string cache_guid = commit_message.cache_guid(); - bool other_bookmarks_record_created = false; - for (int i = 0; i < commit_message.entries_size(); ++i) { - sync_pb::SyncEntity entity = commit_message.entries(i); - std::string new_object_id; - if (entity.specifics().has_bookmark()) { - const sync_pb::BookmarkSpecifics& bm_specifics = - entity.specifics().bookmark(); - - auto record = std::make_unique(); - record->objectData = brave_sync::jslib_const::SyncObjectData_BOOKMARK; - - auto bookmark = std::make_unique(); - bookmark->site.location = bm_specifics.url(); - bookmark->site.title = bm_specifics.legacy_canonicalized_title(); - bookmark->site.customTitle = bm_specifics.legacy_canonicalized_title(); - // bookmark->site.lastAccessedTime - ignored - bookmark->site.creationTime = - ProtoTimeToTime(bm_specifics.creation_time_us()); - bookmark->site.favicon = bm_specifics.icon_url(); - bookmark->isFolder = entity.folder(); - // only matters for direct children of permanent nodes - bookmark->hideInToolbar = entity.parent_id_string() == kOtherBookmarksTag; - - bool skip_record = false; - for (int i = 0; i < bm_specifics.meta_info_size(); ++i) { - if (bm_specifics.meta_info(i).key() == "order") { - bookmark->order = bm_specifics.meta_info(i).value(); - } else if (bm_specifics.meta_info(i).key() == "object_id") { - new_object_id = bm_specifics.meta_info(i).value(); - } else if (bm_specifics.meta_info(i).key() == "parent_object_id") { - bookmark->parentFolderObjectId = bm_specifics.meta_info(i).value(); - } else if (bm_specifics.meta_info(i).key() == "sync_timestamp") { - record->syncTimestamp = base::Time::FromJsTime( - std::stod(bm_specifics.meta_info(i).value())); - } else if (bm_specifics.meta_info(i).key() == "last_send_time" && - entity.version() == 0) { - // Upgrade from legacy code, we need to prevent sending duplicate - // records which are already on sync chain - skip_record = true; - } - } - - int64_t version = entity.version(); - if (entity.version() == 0) { - record->objectId = new_object_id; - record->action = brave_sync::jslib::SyncRecord::Action::A_CREATE; - } else { - record->objectId = entity.id_string(); - if (entity.deleted()) - record->action = brave_sync::jslib::SyncRecord::Action::A_DELETE; - else - record->action = brave_sync::jslib::SyncRecord::Action::A_UPDATE; - } - - if (entity.deleted() && entity.version() == 0 && - record->objectId.empty()) { - // This is for recover profile after crash with duplicated object ids - // When doing delete of duplicated bookmark, pretend it has a new - // object id to got through nudge/pull cycle - // We are ok, if other devices would get this record, because they have - // nothing to delete in fact - record->objectId = brave_sync::tools::GenerateObjectId(); - record->action = brave_sync::jslib::SyncRecord::Action::A_DELETE; - } - - DCHECK(!record->objectId.empty()); - - MetaInfo metaInfo; - - metaInfo.key = "version"; - metaInfo.value = std::to_string(version); - bookmark->metaInfo.push_back(metaInfo); - - metaInfo.key = "position_in_parent"; - metaInfo.value = std::to_string(entity.position_in_parent()); - bookmark->metaInfo.push_back(metaInfo); - - record->SetBookmark(std::move(bookmark)); - - if (!other_bookmarks_record_created && - entity.parent_id_string() == kOtherBookmarksTag) { - record_list->push_back(CreateOtherBookmarksRecord(record.get())); - other_bookmarks_record_created = true; - } - if (!skip_record) - record_list->push_back(std::move(record)); - } - sync_pb::CommitResponse_EntryResponse* entry_response = - response->mutable_commit()->add_entryresponse(); - CreateSuccessfulCommitResponse(entity, entry_response, new_object_id); - } - return record_list; -} - -SyncerError PostBraveCommit(sync_pb::ClientToServerMessage* message, - sync_pb::ClientToServerResponse* response, - SyncCycle* cycle) { - brave_sync::RecordsListPtr records_list = - ConvertCommitsToBraveRecords(message, response); - cycle->delegate()->OnNudgeSyncCycle(std::move(records_list)); - - return SyncerError(SyncerError::SYNCER_OK); -} - -} // namespace -} // namespace syncer diff --git a/chromium_src/components/sync/engine_impl/cycle/sync_cycle.h b/chromium_src/components/sync/engine_impl/cycle/sync_cycle.h deleted file mode 100644 index 2437341a63cc..000000000000 --- a/chromium_src/components/sync/engine_impl/cycle/sync_cycle.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_CYCLE_SYNC_CYCLE_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_CYCLE_SYNC_CYCLE_H_ - -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -#define BRAVE_SYNC_CYCLE_DELEGATE_H \ - virtual void OnNudgeSyncCycle(brave_sync::RecordsListPtr records_list) {} \ - virtual void OnPollSyncCycle(brave_sync::GetRecordsCallback cb, \ - base::WaitableEvent* wevent) {} - -#include "../../../../../../components/sync/engine_impl/cycle/sync_cycle.h" -#undef BRAVE_SYNC_CYCLE_DELEGATE_H - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_CYCLE_SYNC_CYCLE_H_ diff --git a/chromium_src/components/sync/engine_impl/get_updates_processor.cc b/chromium_src/components/sync/engine_impl/get_updates_processor.cc deleted file mode 100644 index 7a2849c757f9..000000000000 --- a/chromium_src/components/sync/engine_impl/get_updates_processor.cc +++ /dev/null @@ -1,260 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/sync/engine_impl/get_updates_processor.h" - -#include -#include -#include -#include - -namespace syncer { -namespace { -SyncerError ApplyBraveRecords(sync_pb::ClientToServerResponse*, - ModelTypeSet*, - std::unique_ptr); -} // namespace -} // namespace syncer - -#include "../../../../../components/sync/engine_impl/get_updates_processor.cc" // NOLINT -#include "base/base64.h" -#include "base/guid.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "components/sync/base/hash_util.h" -#include "components/sync/base/system_encryptor.h" -#include "components/sync/base/time.h" -#include "components/sync/engine_impl/loopback_server/loopback_server_entity.h" -#include "components/sync/syncable/directory_cryptographer.h" -#include "components/sync/syncable/syncable_proto_util.h" -#include "url/gurl.h" - -namespace syncer { -namespace { - -using brave_sync::jslib::Bookmark; -using brave_sync::jslib::SyncRecord; -using syncable::Id; -static const char kBookmarkBarFolderServerTag[] = "bookmark_bar"; -static const char kBookmarkBarFolderName[] = "Bookmark Bar"; -static const char kOtherBookmarksFolderServerTag[] = "other_bookmarks"; -static const char kOtherBookmarksFolderName[] = "Other Bookmarks"; -static const char kSyncedBookmarksFolderServerTag[] = "synced_bookmarks"; -static const char kSyncedBookmarksFolderName[] = "Synced Bookmarks"; -// The parent tag for children of the root entity. Entities with this parent are -// referred to as top level enities. -static const char kRootParentTag[] = "0"; - -void AddBookmarkSpecifics(sync_pb::EntitySpecifics* specifics, - const SyncRecord* record) { - DCHECK(specifics); - auto bookmark = record->GetBookmark(); - sync_pb::BookmarkSpecifics* bm_specifics = specifics->mutable_bookmark(); - bm_specifics->set_url(bookmark.site.location); - - bm_specifics->set_legacy_canonicalized_title( - bookmark.site.TryGetNonEmptyTitle()); - bm_specifics->set_creation_time_us( - TimeToProtoTime(bookmark.site.creationTime)); - // base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds()); - sync_pb::MetaInfo* meta_info = bm_specifics->add_meta_info(); - meta_info->set_key("order"); - meta_info->set_value(bookmark.order); - // For GetExistingObjects lookup - meta_info = bm_specifics->add_meta_info(); - meta_info->set_key("object_id"); - meta_info->set_value(record->objectId); - meta_info = bm_specifics->add_meta_info(); - meta_info->set_key("parent_object_id"); - meta_info->set_value(bookmark.parentFolderObjectId); - meta_info = bm_specifics->add_meta_info(); - meta_info->set_key("sync_timestamp"); - meta_info->set_value(std::to_string(record->syncTimestamp.ToJsTime())); -} - -void ExtractBookmarkMeta(sync_pb::SyncEntity* entity, - sync_pb::EntitySpecifics* specifics, - const Bookmark& bookmark) { - sync_pb::BookmarkSpecifics* bm_specifics = specifics->mutable_bookmark(); - for (const auto& metaInfo : bookmark.metaInfo) { - // version need to be incremented - if (metaInfo.key != "version") { - sync_pb::MetaInfo* meta_info = bm_specifics->add_meta_info(); - meta_info->set_key(metaInfo.key); - meta_info->set_value(metaInfo.value); - } - if (metaInfo.key == "version") { - int64_t version; - bool result = base::StringToInt64(metaInfo.value, &version); - DCHECK(result); - entity->set_version(++version); - sync_pb::MetaInfo* meta_info = bm_specifics->add_meta_info(); - meta_info->set_key(metaInfo.key); - meta_info->set_value(std::to_string(version)); - } else if (metaInfo.key == "position_in_parent") { - int64_t position_in_parent; - bool result = base::StringToInt64(metaInfo.value, &position_in_parent); - DCHECK(result); - entity->set_position_in_parent(position_in_parent); - } - } - DCHECK(entity->has_version()); -} - -void MigrateFromLegacySync(sync_pb::SyncEntity* entity) { - if (!entity->has_position_in_parent()) { - entity->set_position_in_parent(0); - } -} - -void AddRootForType(sync_pb::SyncEntity* entity, ModelType type) { - DCHECK(entity); - sync_pb::EntitySpecifics specifics; - AddDefaultFieldValue(type, &specifics); - std::string server_tag = ModelTypeToRootTag(type); - std::string name = syncer::ModelTypeToString(type); - std::string id = LoopbackServerEntity::GetTopLevelId(type); - entity->set_server_defined_unique_tag(server_tag); - entity->set_id_string(id); - entity->set_parent_id_string(kRootParentTag); - entity->set_name(name); - entity->set_version(1); - entity->set_folder(true); - entity->mutable_specifics()->CopyFrom(specifics); -} - -void AddPermanentNode(sync_pb::SyncEntity* entity, - const std::string& name, - const std::string& tag) { - DCHECK(entity); - sync_pb::EntitySpecifics specifics; - AddDefaultFieldValue(BOOKMARKS, &specifics); - std::string parent = ModelTypeToRootTag(BOOKMARKS); - std::string id = tag; - std::string parent_id = LoopbackServerEntity::CreateId(BOOKMARKS, parent); - entity->set_server_defined_unique_tag(tag); - entity->set_id_string(id); - entity->set_parent_id_string(parent_id); - entity->set_name(name); - entity->set_folder(true); - entity->set_version(1); - entity->mutable_specifics()->CopyFrom(specifics); -} - -void AddBookmarkNode(sync_pb::SyncEntity* entity, const SyncRecord* record) { - DCHECK(entity); - DCHECK(record); - DCHECK(record->has_bookmark()); - DCHECK(!record->objectId.empty()); - - auto bookmark_record = record->GetBookmark(); - - sync_pb::EntitySpecifics specifics; - AddDefaultFieldValue(BOOKMARKS, &specifics); - entity->set_id_string(record->objectId); - if (!bookmark_record.parentFolderObjectId.empty()) { - // parentFolderObjectId is used for mobile to treat "Other Bookmarks" as - // normal folder - if (bookmark_record.hideInToolbar) - entity->set_parent_id_string(std::string(kOtherBookmarksFolderServerTag)); - else - entity->set_parent_id_string(bookmark_record.parentFolderObjectId); - } else { - entity->set_parent_id_string(std::string(kBookmarkBarFolderServerTag)); - } - entity->set_non_unique_name(bookmark_record.site.TryGetNonEmptyTitle()); - entity->set_folder(bookmark_record.isFolder); - - ExtractBookmarkMeta(entity, &specifics, bookmark_record); - - MigrateFromLegacySync(entity); - - if (record->action == SyncRecord::Action::A_DELETE) - entity->set_deleted(true); - else - AddBookmarkSpecifics(&specifics, record); - entity->mutable_specifics()->CopyFrom(specifics); -} - -void ConstructUpdateResponse(sync_pb::GetUpdatesResponse* gu_response, - ModelTypeSet* request_types, - std::unique_ptr records) { - DCHECK(gu_response); - DCHECK(request_types); - for (ModelType type : *request_types) { - sync_pb::DataTypeProgressMarker* marker = - gu_response->add_new_progress_marker(); - marker->set_data_type_id(GetSpecificsFieldNumberFromModelType(type)); - marker->set_token("token"); - if (type == BOOKMARKS) { - google::protobuf::RepeatedPtrField entities; - AddRootForType(entities.Add(), BOOKMARKS); - AddPermanentNode(entities.Add(), kBookmarkBarFolderName, - kBookmarkBarFolderServerTag); - AddPermanentNode(entities.Add(), kOtherBookmarksFolderName, - kOtherBookmarksFolderServerTag); - // required since 84f01c4c006cf89941138f3591db129a5b3cde54 - AddPermanentNode(entities.Add(), kSyncedBookmarksFolderName, - kSyncedBookmarksFolderServerTag); - if (records) { - for (const auto& record : *records.get()) { - AddBookmarkNode(entities.Add(), record.get()); - } - } - std::copy(entities.begin(), entities.end(), - RepeatedPtrFieldBackInserter(gu_response->mutable_entries())); - } else if (type == NIGORI) { - google::protobuf::RepeatedPtrField entities; - sync_pb::EntitySpecifics specifics; - AddDefaultFieldValue(NIGORI, &specifics); - sync_pb::SyncEntity* entity = entities.Add(); - AddRootForType(entity, NIGORI); - sync_pb::NigoriSpecifics* nigori = specifics.mutable_nigori(); - nigori->set_encrypt_everything(false); - nigori->set_encrypt_bookmarks(false); - syncer::DirectoryCryptographer cryptographer; - KeyParams params = {KeyDerivationParams::CreateForPbkdf2(), "foobar"}; - syncer::KeyDerivationMethod method = params.derivation_params.method(); - bool add_key_result = cryptographer.AddKey(params); - DCHECK(add_key_result); - bool get_keys_result = - cryptographer.GetKeys(nigori->mutable_encryption_keybag()); - DCHECK(get_keys_result); - nigori->set_keybag_is_frozen(true); - nigori->set_keystore_migration_time(1U); - nigori->set_passphrase_type(sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE); - nigori->set_custom_passphrase_key_derivation_method( - EnumKeyDerivationMethodToProto(method)); - entity->mutable_specifics()->CopyFrom(specifics); - - std::copy(entities.begin(), entities.end(), - RepeatedPtrFieldBackInserter(gu_response->mutable_entries())); - } - } - gu_response->set_changes_remaining(0); - gu_response->add_encryption_keys("dummy_encryption_key"); -} - -SyncerError ApplyBraveRecords(sync_pb::ClientToServerResponse* update_response, - ModelTypeSet* request_types, - std::unique_ptr records) { - DCHECK(update_response); - DCHECK(request_types); - sync_pb::GetUpdatesResponse* gu_response = new sync_pb::GetUpdatesResponse(); - ConstructUpdateResponse(gu_response, request_types, std::move(records)); - update_response->set_allocated_get_updates(gu_response); - return SyncerError(SyncerError::SYNCER_OK); -} - -} // namespace - -void GetUpdatesProcessor::AddBraveRecords( - std::unique_ptr records) { - brave_records_ = std::move(records); -} - -} // namespace syncer diff --git a/chromium_src/components/sync/engine_impl/get_updates_processor.h b/chromium_src/components/sync/engine_impl/get_updates_processor.h deleted file mode 100644 index e70f42654ad1..000000000000 --- a/chromium_src/components/sync/engine_impl/get_updates_processor.h +++ /dev/null @@ -1,25 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_GET_UPDATES_PROCESSOR_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_GET_UPDATES_PROCESSOR_H_ - -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -namespace syncer { -using brave_sync::RecordsList; -} // namespace syncer - -#define BRAVE_GET_UPDATES_PROCESSOR_H \ - public: \ - void AddBraveRecords(std::unique_ptr records); \ - \ - private: \ - std::unique_ptr brave_records_; - -#include "../../../../../components/sync/engine_impl/get_updates_processor.h" -#undef BRAVE_GET_UPDATES_PROCESSOR_H - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_GET_UPDATES_PROCESSOR_H_ diff --git a/chromium_src/components/sync/engine_impl/process_updates_util.cc b/chromium_src/components/sync/engine_impl/process_updates_util.cc deleted file mode 100644 index d6fc2f67e126..000000000000 --- a/chromium_src/components/sync/engine_impl/process_updates_util.cc +++ /dev/null @@ -1,15 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// TODO(darkdh): investigate the records flow causing object id not applied to -// local entry in CommitResponse - -#define BRAVE_PROCESS_UPDATE \ - DCHECK(false) << "Brave object id " << server_id \ - << " is not applied to local id " << local_id; \ - return; - -#include "../../../../../components/sync/engine_impl/process_updates_util.cc" // NOLINT -#undef BRAVE_PROCESS_UPDATE diff --git a/chromium_src/components/sync/engine_impl/sync_manager_impl.cc b/chromium_src/components/sync/engine_impl/sync_manager_impl.cc deleted file mode 100644 index 3c3fafb9487f..000000000000 --- a/chromium_src/components/sync/engine_impl/sync_manager_impl.cc +++ /dev/null @@ -1,17 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/sync/engine_impl/sync_scheduler_impl.h" - -#define BRAVE_SYNC_MANAGER_IMPL_INIT \ - static_cast(scheduler_.get()) \ - ->nudge_sync_cycle_delegate_function_ = \ - args->nudge_sync_cycle_delegate_function; \ - static_cast(scheduler_.get()) \ - ->poll_sync_cycle_delegate_function_ = \ - args->poll_sync_cycle_delegate_function; - -#include "../../../../../components/sync/engine_impl/sync_manager_impl.cc" // NOLINT -#undef BRAVE_SYNC_MANAGER_IMPL_INIT diff --git a/chromium_src/components/sync/engine_impl/sync_scheduler_impl.cc b/chromium_src/components/sync/engine_impl/sync_scheduler_impl.cc deleted file mode 100644 index beab44e2497a..000000000000 --- a/chromium_src/components/sync/engine_impl/sync_scheduler_impl.cc +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/sync/engine_impl/sync_scheduler_impl.h" - -#include "brave/components/brave_sync/jslib_messages.h" - -namespace syncer { - -void SyncSchedulerImpl::OnNudgeSyncCycle( - brave_sync::RecordsListPtr records_list) { - DCHECK(nudge_sync_cycle_delegate_function_); - nudge_sync_cycle_delegate_function_.Run(std::move(records_list)); -} - -void SyncSchedulerImpl::OnPollSyncCycle(brave_sync::GetRecordsCallback cb, - base::WaitableEvent* wevent) { - DCHECK(poll_sync_cycle_delegate_function_); - poll_sync_cycle_delegate_function_.Run(std::move(cb), wevent); -} - -} // namespace syncer - -#define BRAVE_SYNC_SCHEDULER_IMPL_TRY_SYNC_CYCLE_JOB \ - SyncCycle cycle(cycle_context_, this); \ - if (mode_ != CONFIGURATION_MODE) { \ - syncer_->DownloadBraveRecords(&cycle); \ - } - -#include "../../../../../components/sync/engine_impl/sync_scheduler_impl.cc" // NOLINT diff --git a/chromium_src/components/sync/engine_impl/sync_scheduler_impl.h b/chromium_src/components/sync/engine_impl/sync_scheduler_impl.h deleted file mode 100644 index 8870a48224bf..000000000000 --- a/chromium_src/components/sync/engine_impl/sync_scheduler_impl.h +++ /dev/null @@ -1,24 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_SYNC_SCHEDULER_IMPL_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_SYNC_SCHEDULER_IMPL_H_ - -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -#define BRAVE_SYNC_SCHEDULER_IMPL_H_ \ - void OnNudgeSyncCycle(brave_sync::RecordsListPtr records_list) override; \ - void OnPollSyncCycle(brave_sync::GetRecordsCallback cb, \ - base::WaitableEvent* wevent) override; \ - \ - private: \ - friend class SyncManagerImpl; \ - brave_sync::NudgeSyncCycleDelegate nudge_sync_cycle_delegate_function_; \ - brave_sync::PollSyncCycleDelegate poll_sync_cycle_delegate_function_; - -#include "../../../../../components/sync/engine_impl/sync_scheduler_impl.h" -#undef BRAVE_SYNC_SCHEDULER_IMPL_H_ - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_SYNC_SCHEDULER_IMPL_H_ diff --git a/chromium_src/components/sync/engine_impl/syncer.cc b/chromium_src/components/sync/engine_impl/syncer.cc deleted file mode 100644 index e6a97e0ac362..000000000000 --- a/chromium_src/components/sync/engine_impl/syncer.cc +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/chromium_src/components/sync/engine_impl/syncer.h" - -#include -#include - -#include "base/bind.h" - -#include "../../../../../components/sync/engine_impl/syncer.cc" // NOLINT - -namespace syncer { - -using brave_sync::GetRecordsCallback; -using brave_sync::RecordsList; - -void Syncer::OnGetRecords(std::unique_ptr records) { - brave_records_ = std::move(records); -} - -void Syncer::DownloadBraveRecords(SyncCycle* cycle) { - // syncer will be alive as long as sync is enabled - brave_records_.reset(); - brave_sync::GetRecordsCallback on_get_records = - base::BindOnce(&Syncer::OnGetRecords, base::Unretained(this)); - base::WaitableEvent wevent; - cycle->delegate()->OnPollSyncCycle(std::move(on_get_records), &wevent); - wevent.Wait(); -} - -} // namespace syncer diff --git a/chromium_src/components/sync/engine_impl/syncer.h b/chromium_src/components/sync/engine_impl/syncer.h deleted file mode 100644 index e0170fe93c2d..000000000000 --- a/chromium_src/components/sync/engine_impl/syncer.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_SYNCER_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_SYNCER_H_ - -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -#define BRAVE_SYNCER_H \ - public: \ - void DownloadBraveRecords(SyncCycle* cycle); \ - \ - private: \ - void OnGetRecords(std::unique_ptr records); \ - std::unique_ptr brave_records_; - -#include "../../../../../components/sync/engine_impl/syncer.h" -#undef BRAVE_SYNCER_H - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_ENGINE_IMPL_SYNCER_H_ diff --git a/chromium_src/components/sync/syncable/write_transaction.cc b/chromium_src/components/sync/syncable/write_transaction.cc deleted file mode 100644 index 77492bb22fa5..000000000000 --- a/chromium_src/components/sync/syncable/write_transaction.cc +++ /dev/null @@ -1,19 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#define BRAVE_WRITE_TRANSACTION if (close_transaction_) -#include "../../../../components/sync/syncable/write_transaction.cc" // NOLINT -#undef BRAVE_WRITE_TRANSACTION - -namespace syncer { - -WriteTransaction::WriteTransaction(const base::Location& from_here, - UserShare* share, - syncable::WriteTransaction* syncable_wr_tr) - : BaseTransaction(share), transaction_(syncable_wr_tr) { - close_transaction_ = false; -} - -} // namespace syncer diff --git a/chromium_src/components/sync/syncable/write_transaction.h b/chromium_src/components/sync/syncable/write_transaction.h deleted file mode 100644 index b96064e243a2..000000000000 --- a/chromium_src/components/sync/syncable/write_transaction.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_SYNCABLE_WRITE_TRANSACTION_H_ -#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_SYNCABLE_WRITE_TRANSACTION_H_ - -#define BRAVE_WRITE_TRANSACTION_H_ \ - WriteTransaction(const base::Location& from_here, UserShare* share, \ - syncable::WriteTransaction* syncable_wr_tr); \ - \ - private: \ - bool close_transaction_ = true; - -#include "../../../../../components/sync/syncable/write_transaction.h" -#undef BRAVE_WRITE_TRANSACTION_H_ - -#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_SYNCABLE_WRITE_TRANSACTION_H_ diff --git a/chromium_src/components/sync_bookmarks/bookmark_model_type_processor.cc b/chromium_src/components/sync_bookmarks/bookmark_model_type_processor.cc deleted file mode 100644 index 2a2febe25d39..000000000000 --- a/chromium_src/components/sync_bookmarks/bookmark_model_type_processor.cc +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/sync_bookmarks/bookmark_model_observer_impl.h" - -#include - -namespace sync_bookmarks { - -class BraveBookmarkModelObserverImpl : public BookmarkModelObserverImpl { - public: - // |bookmark_tracker_| must not be null and must outlive this object. - BraveBookmarkModelObserverImpl( - const base::RepeatingClosure& nudge_for_commit_closure, - base::OnceClosure on_bookmark_model_being_deleted_closure, - SyncedBookmarkTracker* bookmark_tracker) - : BookmarkModelObserverImpl( - nudge_for_commit_closure, - std::move(on_bookmark_model_being_deleted_closure), - bookmark_tracker) {} - ~BraveBookmarkModelObserverImpl() override = default; - - // BookmarkModelObserver: - void BookmarkMetaInfoChanged(bookmarks::BookmarkModel* model, - const bookmarks::BookmarkNode* node) override {} - void BookmarkNodeFaviconChanged( - bookmarks::BookmarkModel* model, - const bookmarks::BookmarkNode* node) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(BraveBookmarkModelObserverImpl); -}; - -} // namespace sync_bookmarks - -#define BookmarkModelObserverImpl BraveBookmarkModelObserverImpl -#include "../../../../components/sync_bookmarks/bookmark_model_type_processor.cc" -#undef BookmarkModelObserverImpl diff --git a/chromium_src/components/sync_bookmarks/bookmark_remote_updates_handler.cc b/chromium_src/components/sync_bookmarks/bookmark_remote_updates_handler.cc deleted file mode 100644 index 153358b7b5b3..000000000000 --- a/chromium_src/components/sync_bookmarks/bookmark_remote_updates_handler.cc +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/syncer_helper.h" - -#define BRAVE_APPLY_REMOTE_UPDATE true ? brave_sync::GetIndex(new_parent, node): - -#define BRAVE_PROCESS_CREATE_1 \ - std::string order; \ - std::string object_id; \ - for (int i = 0; i < update_entity.specifics.bookmark().meta_info_size(); \ - ++i) { \ - if (update_entity.specifics.bookmark().meta_info(i).key() == "order") { \ - order = update_entity.specifics.bookmark().meta_info(i).value(); \ - } else if (update_entity.specifics.bookmark().meta_info(i).key() == \ - "object_id") { \ - object_id = update_entity.specifics.bookmark().meta_info(i).value(); \ - } \ - } - -#define BRAVE_PROCESS_CREATE_2 \ - true ? brave_sync::GetIndex(parent_node, order, object_id): -#include "../../../../components/sync_bookmarks/bookmark_remote_updates_handler.cc" -#undef BRAVE_APPLY_REMOTE_UPDATE -#undef BRAVE_PROCESS_CREATE_1 -#undef BRAVE_PROCESS_CREATE_2 diff --git a/chromium_src/components/sync_bookmarks/bookmark_specifics_conversions.cc b/chromium_src/components/sync_bookmarks/bookmark_specifics_conversions.cc deleted file mode 100644 index 0dfcaf66d748..000000000000 --- a/chromium_src/components/sync_bookmarks/bookmark_specifics_conversions.cc +++ /dev/null @@ -1,26 +0,0 @@ -/* Copyright 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "components/sync_bookmarks/bookmark_specifics_conversions.h" - -#include "brave/components/brave_sync/syncer_helper.h" -#define CreateSpecificsFromBookmarkNode \ - CreateSpecificsFromBookmarkNodeChromiumImpl -#include "../../../../components/sync_bookmarks/bookmark_specifics_conversions.cc" -#undef CreateSpecificsFromBookmarkNode - -namespace sync_bookmarks { - -sync_pb::EntitySpecifics CreateSpecificsFromBookmarkNode( - const bookmarks::BookmarkNode* node, - bookmarks::BookmarkModel* model, - bool force_favicon_load, - bool include_guid) { - brave_sync::AddBraveMetaInfo(node); - return CreateSpecificsFromBookmarkNodeChromiumImpl( - node, model, force_favicon_load, include_guid); -} - -} // namespace sync_bookmarks diff --git a/components/brave_sync/BUILD.gn b/components/brave_sync/BUILD.gn index 8cb90e479992..72c837f50fa2 100644 --- a/components/brave_sync/BUILD.gn +++ b/components/brave_sync/BUILD.gn @@ -17,8 +17,6 @@ config("brave_sync_config") { if (enable_brave_sync) { source_set("js_sync_lib_impl") { sources = [ - "brave_profile_sync_service_impl.cc", - "brave_profile_sync_service_impl.h", "client/brave_sync_client.h", "client/brave_sync_client_impl.cc", "client/brave_sync_client_impl.h", diff --git a/components/brave_sync/brave_profile_sync_service_impl.cc b/components/brave_sync/brave_profile_sync_service_impl.cc deleted file mode 100644 index 70a8ede7b1f3..000000000000 --- a/components/brave_sync/brave_profile_sync_service_impl.cc +++ /dev/null @@ -1,1425 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/brave_profile_sync_service_impl.h" - -#include -#include -#include -#include -#include - -#include "base/bind.h" -#include "base/metrics/histogram_macros.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "brave/common/pref_names.h" -#include "brave/components/brave_sync/brave_sync_prefs.h" -#include "brave/components/brave_sync/brave_sync_service_observer.h" -#include "brave/components/brave_sync/client/brave_sync_client_impl.h" -#include "brave/components/brave_sync/crypto/crypto.h" -#include "brave/components/brave_sync/jslib_const.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/settings.h" -#include "brave/components/brave_sync/sync_devices.h" -#include "brave/components/brave_sync/syncer_helper.h" -#include "brave/components/brave_sync/tools.h" -#include "brave/components/brave_sync/values_conv.h" -#include "chrome/browser/bookmarks/bookmark_model_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/chrome_sync_client.h" -#include "components/bookmarks/browser/bookmark_model.h" -#include "components/prefs/pref_service.h" -#include "components/signin/public/identity_manager/account_info.h" -#include "components/sync/engine_impl/syncer.h" -#include "content/public/browser/browser_thread.h" -#include "net/base/network_interfaces.h" -#include "ui/base/models/tree_node_iterator.h" - -namespace brave_sync { - -using browser_sync::ChromeSyncClient; -using jslib::Device; -using jslib::MetaInfo; -using jslib::SyncRecord; -using jslib_const::kBookmarks; -using jslib_const::kHistorySites; -using jslib_const::kPreferences; -using jslib_const::SyncObjectData_DEVICE; -using jslib_const::SyncRecordType_PREFERENCES; -using tools::IsTimeEmpty; - -const std::vector BraveProfileSyncServiceImpl::kExponentialWaits = { - 10, 20, 40, 80}; -const int BraveProfileSyncServiceImpl::kMaxSendRetries = - BraveProfileSyncServiceImpl::kExponentialWaits.size() - 1; - -namespace { - -AccountInfo GetDummyAccountInfo() { - AccountInfo account_info; - account_info.account_id = CoreAccountId::FromString("dummy_account_id"); - account_info.gaia = "dummy_gaia"; - return account_info; -} - -void NotifyLogMessage(const std::string& message) { - DLOG(INFO) << message; -} - -std::string GetDeviceName() { - std::string hostname = net::GetHostName(); - if (hostname.empty()) { -#if defined(OS_MACOSX) - hostname = std::string("Mac Desktop"); -#elif defined(OS_LINUX) - hostname = std::string("Linux Desktop"); -#elif defined(OS_WIN) - hostname = std::string("Windows Desktop"); -#endif - } - return hostname; -} - -RecordsListPtr CreateDeviceRecord(const std::string& device_name, - const std::string& object_id, - const SyncRecord::Action& action, - const std::string& device_id, - const std::string& device_id_v2) { - RecordsListPtr records = std::make_unique(); - - SyncRecordPtr record = std::make_unique(); - - record->action = action; - record->deviceId = device_id; - record->objectId = object_id; - record->objectData = SyncObjectData_DEVICE; // "device" - - std::unique_ptr device = std::make_unique(); - device->name = device_name; - device->deviceIdV2 = device_id_v2; - record->SetDevice(std::move(device)); - - records->emplace_back(std::move(record)); - - return records; -} - -const bookmarks::BookmarkNode* FindByObjectId(bookmarks::BookmarkModel* model, - const std::string& object_id) { - ui::TreeNodeIterator iterator( - model->root_node()); - while (iterator.has_next()) { - const bookmarks::BookmarkNode* node = iterator.Next(); - std::string node_object_id; - node->GetMetaInfo("object_id", &node_object_id); - - if (!node_object_id.empty() && object_id == node_object_id) - return node; - } - return nullptr; -} - -std::unique_ptr CreateDeleteBookmarkByObjectId( - const prefs::Prefs* brave_sync_prefs, - const std::string& object_id) { - auto record = std::make_unique(); - record->deviceId = brave_sync_prefs->GetThisDeviceId(); - record->objectData = jslib_const::SyncObjectData_BOOKMARK; - record->objectId = object_id; - record->action = jslib::SyncRecord::Action::A_DELETE; - record->syncTimestamp = base::Time::Now(); - auto bookmark = std::make_unique(); - record->SetBookmark(std::move(bookmark)); - return record; -} - -void DoDispatchGetRecordsCallback( - GetRecordsCallback cb, - std::unique_ptr records) { - std::move(cb).Run(std::move(records)); -} - -void AddSyncEntityInfo(jslib::Bookmark* bookmark, - const bookmarks::BookmarkNode* node, - const std::string& key) { - std::string value; - if (node->GetMetaInfo(key, &value)) { - MetaInfo metaInfo; - metaInfo.key = key; - metaInfo.value = value; - bookmark->metaInfo.push_back(metaInfo); - } -} - -SyncRecordPtr PrepareResolvedDevice(SyncDevice* device, - SyncRecord::Action action) { - auto record = std::make_unique(); - record->action = action; - record->deviceId = device->device_id_; - record->objectId = device->object_id_; - record->objectData = jslib_const::SyncObjectData_DEVICE; // "device" - std::unique_ptr device_record = - std::make_unique(); - device_record->name = device->name_; - device_record->deviceIdV2 = device->device_id_v2_; - record->SetDevice(std::move(device_record)); - return record; -} - -using NodesSet = std::set; -using ObjectIdToNodes = std::map; - -void FillObjectsMap(const bookmarks::BookmarkNode* parent, - ObjectIdToNodes* object_id_nodes) { - for (size_t i = 0; i < parent->children().size(); ++i) { - const bookmarks::BookmarkNode* current_child = parent->children()[i].get(); - std::string object_id; - if (current_child->GetMetaInfo("object_id", &object_id) && - !object_id.empty()) { - (*object_id_nodes)[object_id].insert(current_child); - } - if (current_child->is_folder()) { - FillObjectsMap(current_child, object_id_nodes); - } - } -} - -void AddDeletedChildren(const BookmarkNode* node, NodesSet* deleted_nodes) { - for (const auto& child : node->children()) { - deleted_nodes->insert(child.get()); - if (node->is_folder()) { - AddDeletedChildren(child.get(), deleted_nodes); - } - } -} - -void ClearDuplicatedNodes(ObjectIdToNodes* object_id_nodes, - bookmarks::BookmarkModel* model) { - size_t nodes_recreated = 0; - NodesSet nodes_with_duplicates; - for (ObjectIdToNodes::iterator it_object_id = object_id_nodes->begin(); - it_object_id != object_id_nodes->end(); ++it_object_id) { - const NodesSet& nodes = it_object_id->second; - if (nodes.size() > 1) { - nodes_with_duplicates.insert(nodes.begin(), nodes.end()); - } - } - - NodesSet deleted_nodes; - for (const bookmarks::BookmarkNode* node : nodes_with_duplicates) { - if (deleted_nodes.find(node) != deleted_nodes.end()) { - // Node already has been deleted - continue; - } - - deleted_nodes.insert(node); - if (node->is_folder()) { - AddDeletedChildren(node, &deleted_nodes); - } - - const auto* parent = node->parent(); - size_t original_index = parent->GetIndexOf(node); - VLOG(1) << "[BraveSync] " << __func__ - << " Copying node into index=" << original_index; - model->Copy(node, parent, original_index); - VLOG(1) << "[BraveSync] " << __func__ << " Removing original node"; - model->Remove(node); - nodes_recreated++; - } - - VLOG(1) << "[BraveSync] " << __func__ - << " done nodes_recreated=" << nodes_recreated; -} - -} // namespace - -BraveProfileSyncServiceImpl::BraveProfileSyncServiceImpl(Profile* profile, - InitParams init_params) - : BraveProfileSyncService(std::move(init_params)), - brave_sync_client_(BraveSyncClient::Create(this, profile)) { - brave_sync_prefs_ = - std::make_unique(sync_client_->GetPrefService()); - - // Monitor syncs prefs required in GetSettingsAndDevices - brave_pref_change_registrar_.Init(sync_client_->GetPrefService()); - brave_pref_change_registrar_.Add( - prefs::kSyncEnabled, - base::Bind(&BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged, - base::Unretained(this))); - brave_pref_change_registrar_.Add( - prefs::kSyncDeviceName, - base::Bind(&BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged, - base::Unretained(this))); - brave_pref_change_registrar_.Add( - prefs::kSyncDeviceList, - base::Bind(&BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged, - base::Unretained(this))); - brave_pref_change_registrar_.Add( - prefs::kSyncBookmarksEnabled, - base::Bind(&BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged, - base::Unretained(this))); - brave_pref_change_registrar_.Add( - prefs::kSyncSiteSettingsEnabled, - base::Bind(&BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged, - base::Unretained(this))); - brave_pref_change_registrar_.Add( - prefs::kSyncHistoryEnabled, - base::Bind(&BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged, - base::Unretained(this))); - - model_ = BookmarkModelFactory::GetForBrowserContext(profile); - // model_ can be null in some tests - - network_connection_tracker_->AddNetworkConnectionObserver(this); - RecordSyncStateP3A(); -} - -void BraveProfileSyncServiceImpl::BookmarkModelLoaded(BookmarkModel* model, - bool ids_reassigned) { - VLOG(2) << "[BraveSync] bookmarks model just loaded, " - << "resuming pending sync ready callback"; - OnSyncReadyBookmarksModelLoaded(); -} - -void BraveProfileSyncServiceImpl::OnNudgeSyncCycle(RecordsListPtr records) { - if (!brave_sync_prefs_->GetSyncEnabled()) - return; - - for (auto& record : *records) { - record->deviceId = brave_sync_prefs_->GetThisDeviceId(); - CheckOtherBookmarkRecord(record.get()); - CheckOtherBookmarkChildRecord(record.get()); - } - if (!records->empty()) { - SendSyncRecords(jslib_const::SyncRecordType_BOOKMARKS, std::move(records)); - } -} - -BraveProfileSyncServiceImpl::~BraveProfileSyncServiceImpl() { - network_connection_tracker_->RemoveNetworkConnectionObserver(this); - // Tests which use ProfileSyncService and are not configured to run on UI - // thread, fire DCHECK on BookmarkModel::RemoveObserver at a wrong sequence. - // Remove observer only if we have set it. - if (is_model_loaded_observer_set_) { - model_->RemoveObserver(this); - } -} - -void BraveProfileSyncServiceImpl::OnSetupSyncHaveCode( - const std::string& sync_words, - const std::string& device_name) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (sync_words.empty()) { - OnSyncSetupError("ERR_SYNC_WRONG_WORDS"); - return; - } - - Uint8Array seed; - if (!crypto::PassphraseToBytes32(sync_words, &seed)) { - OnSyncSetupError("ERR_SYNC_WRONG_WORDS"); - return; - } - - if (brave_sync_initializing_) { - NotifyLogMessage("currently initializing"); - return; - } - - if (!brave_sync_prefs_->GetSeed().empty()) { - NotifyLogMessage("already configured"); - return; - } - - DCHECK(!brave_sync_prefs_->GetSyncEnabled()); - - if (device_name.empty()) - brave_sync_prefs_->SetThisDeviceName(GetDeviceName()); - else - brave_sync_prefs_->SetThisDeviceName(device_name); - brave_sync_initializing_ = true; - brave_sync_prefs_->SetSyncEnabled(true); - seed_ = seed; -} - -void BraveProfileSyncServiceImpl::OnSetupSyncNewToSync( - const std::string& device_name) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (brave_sync_initializing_) { - NotifyLogMessage("currently initializing"); - return; - } - - if (!brave_sync_prefs_->GetSeed().empty()) { - NotifyLogMessage("already configured"); - return; - } - - DCHECK(!brave_sync_prefs_->GetSyncEnabled()); - - if (device_name.empty()) - brave_sync_prefs_->SetThisDeviceName(GetDeviceName()); - else - brave_sync_prefs_->SetThisDeviceName(device_name); - - brave_sync_initializing_ = true; - - brave_sync_prefs_->SetSyncEnabled(true); -} - -void BraveProfileSyncServiceImpl::OnDeleteDevice( - const std::string& device_id_v2) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto sync_devices = brave_sync_prefs_->GetSyncDevices(); - - const SyncDevice* device = sync_devices->GetByDeviceIdV2(device_id_v2); - if (device) { - const std::string device_name = device->name_; - const std::string device_id = device->device_id_; - const std::string object_id = device->object_id_; - SendDeviceSyncRecord(SyncRecord::Action::A_DELETE, device_name, device_id, - device_id_v2, object_id); - if (device_id_v2 == brave_sync_prefs_->GetThisDeviceIdV2()) { - // Mark state we have sent DELETE for own device and we are going to - // call ResetSyncInternal() at OnRecordsSent after ensuring we had made - // a proper attemp to send the record - pending_self_reset_ = true; - } - FetchDevices(); - } -} - -void BraveProfileSyncServiceImpl::OnResetSync() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto sync_devices = brave_sync_prefs_->GetSyncDevices(); - - if (sync_devices->size() == 0) { - // Fail safe option - VLOG(2) << "[Sync] " << __func__ << " unexpected zero device size"; - ResetSyncInternal(); - } else { - // We have to send delete record and wait for library deleted response then - // we can reset it by ResetSyncInternal() - const std::string device_id_v2 = brave_sync_prefs_->GetThisDeviceIdV2(); - OnDeleteDevice(device_id_v2); - } -} - -void BraveProfileSyncServiceImpl::GetSettingsAndDevices( - const GetSettingsAndDevicesCallback& callback) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - auto settings = brave_sync_prefs_->GetBraveSyncSettings(); - auto devices = brave_sync_prefs_->GetSyncDevices(); - callback.Run(std::move(settings), std::move(devices)); -} - -void BraveProfileSyncServiceImpl::GetSyncWords() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - Uint8Array seed = Uint8ArrayFromString(brave_sync_prefs_->GetSeed()); - NotifyHaveSyncWords(crypto::PassphraseFromBytes32(seed)); -} - -std::string BraveProfileSyncServiceImpl::GetSeed() { - return brave_sync_prefs_->GetSeed(); -} - -void BraveProfileSyncServiceImpl::OnSetSyncEnabled( - const bool sync_this_device) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - brave_sync_prefs_->SetSyncEnabled(sync_this_device); -} - -void BraveProfileSyncServiceImpl::OnSetSyncBookmarks( - const bool sync_bookmarks) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - syncer::UserSelectableTypeSet type_set = - ProfileSyncService::GetUserSettings()->GetSelectedTypes(); - if (sync_bookmarks) - type_set.Put(syncer::UserSelectableType::kBookmarks); - else - type_set.Remove(syncer::UserSelectableType::kBookmarks); - ProfileSyncService::GetUserSettings()->SetSelectedTypes(false, type_set); - if (brave_sync_prefs_->GetSyncBookmarksEnabled() != sync_bookmarks) - brave_sync_prefs_->SetSyncBookmarksEnabled(sync_bookmarks); -} - -void BraveProfileSyncServiceImpl::OnSetSyncBrowsingHistory( - const bool sync_browsing_history) { - brave_sync_prefs_->SetSyncHistoryEnabled(sync_browsing_history); -} - -void BraveProfileSyncServiceImpl::OnSetSyncSavedSiteSettings( - const bool sync_saved_site_settings) { - brave_sync_prefs_->SetSyncSiteSettingsEnabled(sync_saved_site_settings); -} - -void BraveProfileSyncServiceImpl::BackgroundSyncStarted(bool startup) {} - -void BraveProfileSyncServiceImpl::BackgroundSyncStopped(bool shutdown) {} - -void BraveProfileSyncServiceImpl::OnSyncDebug(const std::string& message) { - NotifyLogMessage(message); -} - -void BraveProfileSyncServiceImpl::OnSyncSetupError(const std::string& error) { - if (brave_sync_initializing_) { - brave_sync_prefs_->Clear(); - brave_sync_initializing_ = false; - } - NotifySyncSetupError(error); -} - -void BraveProfileSyncServiceImpl::OnGetInitData( - const std::string& sync_version) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - Uint8Array seed; - if (!seed_.empty()) { - seed = seed_; - } else if (!brave_sync_prefs_->GetSeed().empty()) { - seed = Uint8ArrayFromString(brave_sync_prefs_->GetSeed()); - VLOG(1) << "[Brave Sync] Init from prefs"; - } else { - VLOG(1) << "[Brave Sync] Init new chain"; - } - - Uint8Array device_id; - if (!brave_sync_prefs_->GetThisDeviceId().empty()) { - device_id = Uint8ArrayFromString(brave_sync_prefs_->GetThisDeviceId()); - VLOG(1) << "[Brave Sync] Init device id from prefs: " - << StrFromUint8Array(device_id); - } else { - VLOG(1) << "[Brave Sync] Init empty device id"; - } - - std::string device_id_v2; - if (!brave_sync_prefs_->GetThisDeviceIdV2().empty()) { - device_id_v2 = brave_sync_prefs_->GetThisDeviceIdV2(); - VLOG(1) << "[Brave Sync] Init device id_v2 from prefs: " << device_id_v2; - } else { - VLOG(1) << "[Brave Sync] Init empty device id_v2"; - } - - DCHECK(!sync_version.empty()); - // TODO(bridiver) - this seems broken because using the version we get back - // from the server (currently v1.4.2) causes things to break. What is the - // the point of having this value? - brave_sync_prefs_->SetApiVersion("0"); - - client_data::Config config; - config.api_version = brave_sync_prefs_->GetApiVersion(); - config.server_url = BRAVE_SYNC_ENDPOINT; - config.debug = true; - brave_sync_client_->SendGotInitData(seed, device_id, config, device_id_v2); -} - -void BraveProfileSyncServiceImpl::OnSaveInitData( - const Uint8Array& seed, - const Uint8Array& device_id, - const std::string& device_id_v2) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!brave_sync_ready_); - // OnSaveInitData will not only be triggered by OnSetupSyncNewToSync or - // OnSetupSyncHaveCode, we use it to migrate device which doesn't have - // deviceIdV2 - - std::string seed_str = StrFromUint8Array(seed); - std::string device_id_str = StrFromUint8Array(device_id); - - seed_.clear(); - DCHECK(!seed_str.empty()); - - brave_sync_prefs_->SetSeed(seed_str); - brave_sync_prefs_->SetThisDeviceId(device_id_str); - if (!brave_sync_initializing_ && - brave_sync_prefs_->GetThisDeviceIdV2().empty()) - send_device_id_v2_update_ = true; - brave_sync_prefs_->SetThisDeviceIdV2(device_id_v2); - - brave_sync_initializing_ = false; -} - -void BraveProfileSyncServiceImpl::OnSyncReady() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - const std::string bookmarks_base_order = - brave_sync_prefs_->GetBookmarksBaseOrder(); - if (bookmarks_base_order.empty()) { - std::string platform = tools::GetPlatformName(); - brave_sync_client_->SendGetBookmarksBaseOrder( - brave_sync_prefs_->GetThisDeviceId(), platform); - // OnSyncReady will be called by OnSaveBookmarksBaseOrder - return; - } - - DCHECK(false == brave_sync_ready_); - brave_sync_ready_ = true; - - DCHECK(model_); - if (model_->loaded()) { - OnSyncReadyBookmarksModelLoaded(); - } else { - // Will call OnSyncReadyBookmarksModelLoaded once model is loaded - VLOG(2) << "[BraveSync] bookmarks model is not yet loaded, " - << "OnSyncReady will be delayed"; - model_->AddObserver(this); - is_model_loaded_observer_set_ = true; - } -} - -void BraveProfileSyncServiceImpl::OnSyncReadyBookmarksModelLoaded() { - // For launching from legacy sync profile and also brand new profile - if (brave_sync_prefs_->GetMigratedBookmarksVersion() < 2) - SetPermanentNodesOrder(brave_sync_prefs_->GetBookmarksBaseOrder()); - - syncer::SyncPrefs sync_prefs(sync_client_->GetPrefService()); - // first time setup sync or migrated from legacy sync - if (sync_prefs.GetLastSyncedTime().is_null()) { - ProfileSyncService::GetUserSettings()->SetSelectedTypes( - false, syncer::UserSelectableTypeSet()); - // default enable bookmark - // this is important, don't change - // to brave_sync_prefs_->SetSyncBookmarksEnabled(true); - OnSetSyncBookmarks(true); - ProfileSyncService::GetUserSettings()->SetSyncRequested(true); - } - - if (!sync_client_->GetPrefService()->GetBoolean(kOtherBookmarksMigrated)) { - BraveMigrateOtherNodeFolder(model_); - sync_client_->GetPrefService()->SetBoolean(kOtherBookmarksMigrated, true); - } -} - -// static -void BraveProfileSyncServiceImpl::AddNonClonedBookmarkKeys( - BookmarkModel* model) { - DCHECK(model); - DCHECK(model->loaded()); - model->AddNonClonedKey("object_id"); - model->AddNonClonedKey("order"); - model->AddNonClonedKey("sync_timestamp"); - model->AddNonClonedKey("version"); -} - -syncer::ModelTypeSet BraveProfileSyncServiceImpl::GetPreferredDataTypes() - const { - // Force DEVICE_INFO type to have nudge cycle each time to fetch - // Brave sync devices. - // Will be picked up by ProfileSyncService::ConfigureDataTypeManager - return Union(ProfileSyncService::GetPreferredDataTypes(), - {syncer::DEVICE_INFO}); -} - -std::unique_ptr -BraveProfileSyncServiceImpl::PrepareResolvedPreferences( - const RecordsList& records) { - auto sync_devices = brave_sync_prefs_->GetSyncDevices(); - auto records_and_existing_objects = - std::make_unique(); - - for (const SyncRecordPtr& record : records) { - auto resolved_record = std::make_unique(); - resolved_record->first = jslib::SyncRecord::Clone(*record); - auto* device = sync_devices->GetByObjectId(record->objectId); - if (device) - resolved_record->second = PrepareResolvedDevice(device, record->action); - records_and_existing_objects->emplace_back(std::move(resolved_record)); - } - return records_and_existing_objects; -} - -void BraveProfileSyncServiceImpl::OnGetExistingObjects( - const std::string& category_name, - std::unique_ptr records, - const base::Time& last_record_time_stamp, - const bool is_truncated) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // TODO(bridiver) - what do we do with is_truncated ? - // It appears to be ignored in b-l - if (category_name == kBookmarks) { - DCHECK(model_->loaded()); - if (!IsTimeEmpty(last_record_time_stamp)) { - brave_sync_prefs_->SetLatestRecordTime(last_record_time_stamp); - } - auto records_and_existing_objects = - std::make_unique(); - CreateResolveList(*records.get(), records_and_existing_objects.get()); - brave_sync_client_->SendResolveSyncRecords( - category_name, std::move(records_and_existing_objects)); - } else if (category_name == kPreferences) { - if (!tools::IsTimeEmpty(last_record_time_stamp)) { - brave_sync_prefs_->SetLatestDeviceRecordTime(last_record_time_stamp); - } - auto existing_records = PrepareResolvedPreferences(*records.get()); - brave_sync_client_->SendResolveSyncRecords(category_name, - std::move(existing_records)); - } -} - -void BraveProfileSyncServiceImpl::OnResolvedSyncRecords( - const std::string& category_name, - std::unique_ptr records) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (category_name == jslib_const::kPreferences) { - OnResolvedPreferences(*records.get()); - } else if (category_name == kBookmarks) { - for (auto& record : *records) { - if (IsOtherBookmarksFolder(record.get())) { - bool pass_to_syncer = false; - ProcessOtherBookmarksFolder(record.get(), &pass_to_syncer); - if (!pass_to_syncer) { - // We don't process "Other Bookmarks" folder in syncer when - // "Other Bookmaks" doesn't need to be remapped. - std::move(record); - continue; - } - } - ProcessOtherBookmarksChildren(record.get()); - LoadSyncEntityInfo(record.get()); - // We have to cache records when this function is triggered during - // non-PollCycle (ex. compaction update) and wait for next available poll - // cycle to have valid get_record_cb_ - if (!pending_received_records_) - pending_received_records_ = std::make_unique(); - pending_received_records_->push_back(std::move(record)); - } - - // Send records to syncer - if (get_record_cb_) { - backend_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&DoDispatchGetRecordsCallback, - std::move(get_record_cb_), - std::move(pending_received_records_))); - } - SignalWaitableEvent(); - } else if (category_name == kHistorySites) { - NOTIMPLEMENTED(); - } -} - -void BraveProfileSyncServiceImpl::OnDeletedSyncUser() { - NOTIMPLEMENTED(); -} - -void BraveProfileSyncServiceImpl::OnDeleteSyncSiteSettings() { - NOTIMPLEMENTED(); -} - -void BraveProfileSyncServiceImpl::OnSaveBookmarksBaseOrder( - const std::string& order) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!order.empty()); - brave_sync_prefs_->SetBookmarksBaseOrder(order); - OnSyncReady(); -} - -void BraveProfileSyncServiceImpl::OnCompactComplete( - const std::string& category) { - if (category == kBookmarks) - brave_sync_prefs_->SetLastCompactTimeBookmarks(base::Time::Now()); -} - -void BraveProfileSyncServiceImpl::OnRecordsSent( - const std::string& category, - std::unique_ptr records) { - if (category == kBookmarks) { - for (auto& record : *records) { - // Remove Acked sent records - brave_sync_prefs_->RemoveFromRecordsToResend(record->objectId); - } - } else if (category == kPreferences && pending_self_reset_) { - ResetSyncInternal(); - pending_self_reset_ = false; - } -} - -syncer::SyncService::DisableReasonSet -BraveProfileSyncServiceImpl::GetDisableReasons() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - // legacy sync only support bookmark sync so we have to wait for migration - // complete before enable sync engine - if (IsBraveSyncEnabled() && - brave_sync_prefs_->GetMigratedBookmarksVersion() >= 2) - return syncer::SyncService::DisableReasonSet(); - // kSyncManaged is set by Brave so it will contain - // DISABLE_REASON_ENTERPRISE_POLICY and - // SaveCardBubbleControllerImpl::ShouldShowSignInPromo will return false. - return ProfileSyncService::GetDisableReasons(); -} - -CoreAccountInfo BraveProfileSyncServiceImpl::GetAuthenticatedAccountInfo() - const { - return GetDummyAccountInfo(); -} - -bool BraveProfileSyncServiceImpl::IsAuthenticatedAccountPrimary() const { - return true; -} - -void BraveProfileSyncServiceImpl::OnConnectionChanged( - network::mojom::ConnectionType type) { - if (type == network::mojom::ConnectionType::CONNECTION_NONE) - SignalWaitableEvent(); -} - -void BraveProfileSyncServiceImpl::Shutdown() { - SignalWaitableEvent(); - syncer::ProfileSyncService::Shutdown(); -} - -void BraveProfileSyncServiceImpl::NotifySyncSetupError( - const std::string& error) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (auto& observer : BraveSyncService::observers_) - observer.OnSyncSetupError(this, error); -} - -void BraveProfileSyncServiceImpl::NotifySyncStateChanged() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (auto& observer : BraveSyncService::observers_) - observer.OnSyncStateChanged(this); -} - -void BraveProfileSyncServiceImpl::NotifyHaveSyncWords( - const std::string& sync_words) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (auto& observer : BraveSyncService::observers_) - observer.OnHaveSyncWords(this, sync_words); -} - -void BraveProfileSyncServiceImpl::ResetSyncInternal() { - SignalWaitableEvent(); - brave_sync_prefs_->Clear(); - - brave_sync_ready_ = false; - - ProfileSyncService::GetUserSettings()->SetSyncRequested(false); - ProfileSyncService::StopAndClear(); - - // brave sync doesn't support pause sync so treating every new sync chain as - // first time setup - syncer::SyncPrefs sync_prefs(sync_client_->GetPrefService()); - sync_prefs.SetLastSyncedTime(base::Time()); -} - -void BraveProfileSyncServiceImpl::SetPermanentNodesOrder( - const std::string& base_order) { - DCHECK(model_); - DCHECK(model_->loaded()); - DCHECK(!base_order.empty()); - std::string order; - model_->bookmark_bar_node()->GetMetaInfo("order", &order); - if (order.empty()) { - tools::AsMutable(model_->bookmark_bar_node()) - ->SetMetaInfo("order", base_order + "1"); - } - order.clear(); - model_->other_node()->GetMetaInfo("order", &order); - if (order.empty()) { - tools::AsMutable(model_->other_node())->SetMetaInfo("order", - tools::kOtherNodeOrder); - } - brave_sync_prefs_->SetMigratedBookmarksVersion(2); -} - -// static -bool BraveProfileSyncServiceImpl::MigrateDuplicatedBookmarksObjectIds( - bool sync_enabled, - Profile* profile, - BookmarkModel* model) { - if (!sync_enabled) { - return false; - } - - DCHECK(model); - DCHECK(model->loaded()); - - int migrated_version = profile->GetPrefs()->GetInteger( - prefs::kDuplicatedBookmarksMigrateVersion); - - if (migrated_version >= 2) { - return true; - } - - // Copying bookmarks through brave://bookmarks page could duplicate brave sync - // metadata, which caused crash during chromium sync run - // Go through nodes and re-create those ones who have duplicated object_id - ObjectIdToNodes object_id_nodes; - FillObjectsMap(model->root_node(), &object_id_nodes); - ClearDuplicatedNodes(&object_id_nodes, model); - - profile->GetPrefs()->SetInteger(prefs::kDuplicatedBookmarksMigrateVersion, 2); - return true; -} - -std::unique_ptr -BraveProfileSyncServiceImpl::BookmarkNodeToSyncBookmark( - const bookmarks::BookmarkNode* node) { - if (node->is_permanent_node() || !node->parent()) - return std::unique_ptr(); - - auto record = std::make_unique(); - record->deviceId = brave_sync_prefs_->GetThisDeviceId(); - record->objectData = jslib_const::SyncObjectData_BOOKMARK; - - auto bookmark = std::make_unique(); - bookmark->site.location = node->url().spec(); - bookmark->site.title = base::UTF16ToUTF8(node->GetTitledUrlNodeTitle()); - bookmark->site.customTitle = base::UTF16ToUTF8(node->GetTitle()); - // bookmark->site.lastAccessedTime - ignored - bookmark->site.creationTime = node->date_added(); - bookmark->site.favicon = node->icon_url() ? node->icon_url()->spec() : ""; - bookmark->isFolder = node->type() != bookmarks::BookmarkNode::URL; - bookmark->hideInToolbar = node->parent() == model_->other_node(); - - std::string object_id; - node->GetMetaInfo("object_id", &object_id); - record->objectId = object_id; - - std::string parent_object_id; - node->parent()->GetMetaInfo("object_id", &parent_object_id); - bookmark->parentFolderObjectId = parent_object_id; - - std::string order; - node->GetMetaInfo("order", &order); - DCHECK(!order.empty()); - bookmark->order = order; - - std::string sync_timestamp; - node->GetMetaInfo("sync_timestamp", &sync_timestamp); - DCHECK(!sync_timestamp.empty()); - - record->syncTimestamp = base::Time::FromJsTime(std::stod(sync_timestamp)); - - record->action = jslib::SyncRecord::Action::A_UPDATE; - - AddSyncEntityInfo(bookmark.get(), node, "version"); - AddSyncEntityInfo(bookmark.get(), node, "position_in_parent"); - - record->SetBookmark(std::move(bookmark)); - - return record; -} - -void BraveProfileSyncServiceImpl::SaveSyncEntityInfo( - const jslib::SyncRecord* record) { - auto* node = FindByObjectId(model_, record->objectId); - // no need to save for DELETE - if (node) { - auto& bookmark = record->GetBookmark(); - for (auto& meta_info : bookmark.metaInfo) { - if (meta_info.key == "version") { - // Synchronize version meta info with CommitResponse - int64_t version; - bool result = base::StringToInt64(meta_info.value, &version); - DCHECK(result); - tools::AsMutable(node) - ->SetMetaInfo(meta_info.key, std::to_string(++version)); - } else { - tools::AsMutable(node) - ->SetMetaInfo(meta_info.key, meta_info.value); - } - } - } -} - -void BraveProfileSyncServiceImpl::LoadSyncEntityInfo( - jslib::SyncRecord* record) { - auto* bookmark = record->mutable_bookmark(); - if (!bookmark->metaInfo.empty()) - return; - auto* node = FindByObjectId(model_, record->objectId); - if (node) { - AddSyncEntityInfo(bookmark, node, "position_in_parent"); - AddSyncEntityInfo(bookmark, node, "version"); - } else { // Assign base version metainfo for remotely created record - MetaInfo metaInfo; - metaInfo.key = "version"; - metaInfo.value = "0"; - bookmark->metaInfo.push_back(metaInfo); - } -} - -bool BraveProfileSyncServiceImpl::IsOtherBookmarksFolder( - const jslib::SyncRecord* record) const { - auto bookmark = record->GetBookmark(); - if (!bookmark.isFolder) - return false; - - std::string other_node_object_id; - if (model_->other_node()->GetMetaInfo("object_id", &other_node_object_id) && - record->objectId == other_node_object_id) - return true; - - if (bookmark.order == tools::kOtherNodeOrder && - bookmark.site.title == tools::kOtherNodeName && - bookmark.site.customTitle == tools::kOtherNodeName) { - return true; - } - - return false; -} - -void BraveProfileSyncServiceImpl::ProcessOtherBookmarksFolder( - const jslib::SyncRecord* record, - bool* pass_to_syncer) { - std::string other_node_object_id; - // Save object_id for late joined desktop to catch up with current id - // iteration - if (!model_->other_node()->GetMetaInfo("object_id", &other_node_object_id) && - record->action == jslib::SyncRecord::Action::A_CREATE) { - tools::AsMutable(model_->other_node())->SetMetaInfo("object_id", - record->objectId); - } else { - // Out-of-date desktop will poll remote records before commiting local - // changes so we won't get old iteration id. That is why we always take - // remote id when it is different than what we have to catch up with current - // iteration - if (other_node_object_id != record->objectId) { - tools::AsMutable(model_->other_node())->SetMetaInfo("object_id", - record->objectId); - } - // DELETE won't reach here, because [DELETE, null] => [] in - // resolve-sync-objects but children records will go through. And we don't - // need to regenerate new object id for it. - - // Handle MOVE, RENAME - // REORDER (move under same parent) will be ignored - // Update will be resolved as Create because [UPDATE, null] => [CREATE] - auto bookmark = record->GetBookmark(); - if ((bookmark.order != tools::kOtherNodeOrder && - !bookmark.parentFolderObjectId.empty()) || - bookmark.site.title != tools::kOtherNodeName || - bookmark.site.customTitle != tools::kOtherNodeName) { - // Generate next iteration object id from current object_id which will be - // used to mapped normal folder - tools::AsMutable( - model_->other_node()) - ->SetMetaInfo("object_id", - tools::GenerateObjectIdForOtherNode( - other_node_object_id)); - *pass_to_syncer = true; - - // Add records to move direct children of other_node to this new folder - // with existing object id of the old "Other Bookmarks" folder - auto records_to_send = std::make_unique(); - for (size_t i = 0; i < model_->other_node()->children().size(); ++i) { - auto sync_record = - BookmarkNodeToSyncBookmark(model_->other_node()->children()[i].get()); - sync_record->mutable_bookmark()->parentFolderObjectId = - record->objectId; - sync_record->mutable_bookmark()->hideInToolbar = false; - sync_record->mutable_bookmark()->order = - bookmark.order + "." + std::to_string(i + 1); - LoadSyncEntityInfo(sync_record.get()); - - auto record_to_send = SyncRecord::Clone(*sync_record); - - // Append changes to remote records - if (!pending_received_records_) - pending_received_records_ = std::make_unique(); - pending_received_records_->push_back(std::move(sync_record)); - - // Send changes to other desktops - records_to_send->push_back(std::move(record_to_send)); - } - SendSyncRecords(jslib_const::SyncRecordType_BOOKMARKS, - std::move(records_to_send)); - } - } -} - -void BraveProfileSyncServiceImpl::ProcessOtherBookmarksChildren( - jslib::SyncRecord* record) { - std::string other_node_object_id; - if (model_->other_node()->GetMetaInfo("object_id", &other_node_object_id) && - record->GetBookmark().parentFolderObjectId == other_node_object_id) { - record->mutable_bookmark()->hideInToolbar = true; - } -} -void BraveProfileSyncServiceImpl::CheckOtherBookmarkRecord( - jslib::SyncRecord* record) { - if (!IsOtherBookmarksFolder(record)) - return; - // Check if record has latest object id before sending - std::string other_node_object_id; - if (!model_->other_node()->GetMetaInfo("object_id", &other_node_object_id)) { - // first iteration - other_node_object_id = tools::GenerateObjectIdForOtherNode(std::string()); - tools::AsMutable(model_->other_node())->SetMetaInfo("object_id", - other_node_object_id); - } - DCHECK(!other_node_object_id.empty()); - if (record->objectId != other_node_object_id) - record->objectId = other_node_object_id; -} - -void BraveProfileSyncServiceImpl::CheckOtherBookmarkChildRecord( - jslib::SyncRecord* record) { - if (record->GetBookmark().hideInToolbar && - record->GetBookmark().parentFolderObjectId.empty()) { - std::string other_node_object_id; - model_->other_node()->GetMetaInfo("object_id", &other_node_object_id); - DCHECK(!other_node_object_id.empty()); - record->mutable_bookmark()->parentFolderObjectId = other_node_object_id; - } -} - -void BraveProfileSyncServiceImpl::CreateResolveList( - const std::vector>& records, - SyncRecordAndExistingList* records_and_existing_objects) { - DCHECK(model_); - DCHECK(model_->loaded()); - const auto& this_device_id = brave_sync_prefs_->GetThisDeviceId(); - for (const auto& record : records) { - // Ignore records from ourselves to avoid mess on merge - if (record->deviceId == this_device_id) { - continue; - } - auto resolved_record = std::make_unique(); - resolved_record->first = SyncRecord::Clone(*record); - auto* node = FindByObjectId(model_, record->objectId); - if (node) { - resolved_record->second = BookmarkNodeToSyncBookmark(node); - } - - records_and_existing_objects->push_back(std::move(resolved_record)); - } -} - -bool BraveProfileSyncServiceImpl::IsSQSReady() const { - // During 70 sec after device connected to chain use start_at parameter - // of empty to force fetch from S3. - // We need this to handle the case: - // 1) deviceB connected to chain, created own queues - // 2) deviceB made the first fetch from S3, got the records and set own - // non-empty latest_bookmark_record_time, so the next fetches would - // be done through SQS - // 3) deviceA sends record - // 4) lambda enumerates queues and could not discover queues from deviceB, - // because there is gap ~10~30 sec - // 5) record does not arrive to queue of deviceB and is lost for deviceB - // Any possibility of duplication will be eliminated by alreadySeenFromS3 - // checks in brave_sync/extension/brave-sync/lib/s3Helper.js. - // Default Chromium fetch interval is 60 sec. - // So during 70 sec after device connected to chain we forcing use S3ю - if (tools::IsTimeEmpty(this_device_created_time_) || - (base::Time::Now() - this_device_created_time_).InSeconds() >= 70u) { - return true; - } else { - return false; - } -} - -void BraveProfileSyncServiceImpl::FetchSyncRecords(const bool bookmarks, - const bool history, - const bool preferences, - int max_records) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(bookmarks || history || preferences); - if (!(bookmarks || history || preferences)) { - return; - } - - std::vector category_names; - if (history) { - category_names.push_back(kHistorySites); // "HISTORY_SITES"; - } - if (bookmarks) { - category_names.push_back(kBookmarks); // "BOOKMARKS"; - - base::Time last_compact_time = - brave_sync_prefs_->GetLastCompactTimeBookmarks(); - if (tools::IsTimeEmpty(last_compact_time) || - base::Time::Now() - last_compact_time > - base::TimeDelta::FromDays(kCompactPeriodInDays)) { - brave_sync_client_->SendCompact(kBookmarks); - } - } - if (preferences) { - category_names.push_back(kPreferences); // "PREFERENCES"; - } - - base::Time start_at_time = - IsSQSReady() ? brave_sync_prefs_->GetLatestRecordTime() : base::Time(); - - brave_sync_client_->SendFetchSyncRecords(category_names, start_at_time, - max_records); -} - -void BraveProfileSyncServiceImpl::SendCreateDevice() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - std::string device_name = brave_sync_prefs_->GetThisDeviceName(); - std::string object_id = tools::GenerateObjectId(); - brave_sync_prefs_->SetThisDeviceObjectId(object_id); - std::string device_id = brave_sync_prefs_->GetThisDeviceId(); - std::string device_id_v2 = brave_sync_prefs_->GetThisDeviceIdV2(); - DCHECK(!device_id_v2.empty()); - - SendDeviceSyncRecord(SyncRecord::Action::A_CREATE, device_name, device_id, - device_id_v2, object_id); -} - -void BraveProfileSyncServiceImpl::SendDeleteDevice() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - std::string device_name = brave_sync_prefs_->GetThisDeviceName(); - std::string object_id = brave_sync_prefs_->GetThisDeviceObjectId(); - std::string device_id = brave_sync_prefs_->GetThisDeviceId(); - std::string device_id_v2 = brave_sync_prefs_->GetThisDeviceIdV2(); - if (object_id.empty()) { - auto sync_devices = brave_sync_prefs_->GetSyncDevices(); - std::vector devices = - sync_devices->GetByDeviceId(device_id); - for (auto* device : devices) { - if (device) { - object_id = device->object_id_; - } - SendDeviceSyncRecord(SyncRecord::Action::A_DELETE, device_name, device_id, - device_id_v2, object_id); - } - DCHECK(!object_id.empty()); - } else { - DCHECK(!device_id_v2.empty()); - - SendDeviceSyncRecord(SyncRecord::Action::A_DELETE, device_name, device_id, - device_id_v2, object_id); - } -} - -void BraveProfileSyncServiceImpl::SendDeviceSyncRecord( - const int action, - const std::string& device_name, - const std::string& device_id, - const std::string& device_id_v2, - const std::string& object_id) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - RecordsListPtr records = CreateDeviceRecord( - device_name, object_id, static_cast(action), - device_id, device_id_v2); - SendSyncRecords(SyncRecordType_PREFERENCES, std::move(records)); -} - -void BraveProfileSyncServiceImpl::OnResolvedPreferences( - const RecordsList& records) { - const std::string this_device_object_id = - brave_sync_prefs_->GetThisDeviceObjectId(); - const std::string this_device_id_v2 = - brave_sync_prefs_->GetThisDeviceIdV2(); - bool this_device_deleted = false; - - auto sync_devices = brave_sync_prefs_->GetSyncDevices(); - for (const auto& record : records) { - DCHECK(record->has_device() || record->has_sitesetting()); - if (record->has_device()) { - bool actually_merged = false; - auto& device = record->GetDevice(); - sync_devices->Merge(SyncDevice(record->GetDevice().name, record->objectId, - record->deviceId, device.deviceIdV2, - record->syncTimestamp.ToJsTime()), - record->action, &actually_merged); - // We check object id here specifically because device which doesn't have - // device id v2 also doesn't have this object id stored. So we use this - // trait for migration. - this_device_deleted = - this_device_deleted || - (record->objectId == this_device_object_id && - device.deviceIdV2 == this_device_id_v2 && - record->action == SyncRecord::Action::A_DELETE && actually_merged); - } - } // for each device - - brave_sync_prefs_->SetSyncDevices(*sync_devices); - if (this_device_deleted) { - ResetSyncInternal(); - } -} - -void BraveProfileSyncServiceImpl::OnBraveSyncPrefsChanged( - const std::string& pref) { - if (pref == prefs::kSyncEnabled) { - brave_sync_client_->OnSyncEnabledChanged(); - RecordSyncStateP3A(); - } else if (pref == prefs::kSyncDeviceList) { - RecordSyncStateP3A(); - } - NotifySyncStateChanged(); -} - -#if BUILDFLAG(ENABLE_EXTENSIONS) -BraveSyncClient* BraveProfileSyncServiceImpl::GetBraveSyncClient() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return brave_sync_client_.get(); -} -#endif - -bool BraveProfileSyncServiceImpl::IsBraveSyncEnabled() const { - return brave_sync_prefs_->GetSyncEnabled(); -} - -void BraveProfileSyncServiceImpl::FetchDevices() { - DCHECK(sync_client_); - brave_sync_prefs_->SetLastFetchTime(base::Time::Now()); - - base::Time start_at_time = - IsSQSReady() ? brave_sync_prefs_->GetLatestDeviceRecordTime() - : base::Time(); - - brave_sync_client_->SendFetchSyncRecords( - {brave_sync::jslib_const::kPreferences}, start_at_time, 1000); -} - -void BraveProfileSyncServiceImpl::OnPollSyncCycle(GetRecordsCallback cb, - base::WaitableEvent* wevent) { - if (!brave_sync_prefs_->GetSyncEnabled()) - return; - - if (IsTimeEmpty(brave_sync_prefs_->GetLastFetchTime())) { - SendCreateDevice(); - this_device_created_time_ = base::Time::Now(); - } - if (send_device_id_v2_update_) { - // Because device id might get duplicated and we didn't save object id for - // this device so there is no way to send update to propagate device id v2, - // We have to delete previous device records by device id and create a new - // one. - SendDeleteDevice(); - SendCreateDevice(); - send_device_id_v2_update_ = false; - } - - FetchDevices(); - - if (!brave_sync_ready_) { - wevent->Signal(); - return; - } - - get_record_cb_ = std::move(cb); - wevent_ = wevent; - - const bool bookmarks = brave_sync_prefs_->GetSyncBookmarksEnabled(); - const bool history = brave_sync_prefs_->GetSyncHistoryEnabled(); - const bool preferences = brave_sync_prefs_->GetSyncSiteSettingsEnabled(); - FetchSyncRecords(bookmarks, history, preferences, 1000); - ResendSyncRecords(jslib_const::SyncRecordType_BOOKMARKS); -} - -void BraveProfileSyncServiceImpl::SignalWaitableEvent() { - std::move(get_record_cb_); - if (wevent_ && !wevent_->IsSignaled()) { - wevent_->Signal(); - wevent_ = nullptr; - } -} - -BraveSyncService* BraveProfileSyncServiceImpl::GetSyncService() const { - return static_cast( - const_cast(this)); -} - -void BraveProfileSyncServiceImpl::SendSyncRecords( - const std::string& category_name, - RecordsListPtr records) { - DCHECK(brave_sync_client_); - brave_sync_client_->SendSyncRecords(category_name, *records); - if (category_name == kBookmarks) { - DCHECK(model_->loaded()); - for (auto& record : *records) { - SaveSyncEntityInfo(record.get()); - std::unique_ptr meta = - std::make_unique(); - meta->SetInteger("send_retry_number", 0); - meta->SetDouble("sync_timestamp", record->syncTimestamp.ToJsTime()); - brave_sync_prefs_->AddToRecordsToResend(record->objectId, - std::move(meta)); - } - } -} - -void BraveProfileSyncServiceImpl::ResendSyncRecords( - const std::string& category_name) { - if (category_name == kBookmarks) { - RecordsListPtr records = std::make_unique(); - std::vector records_to_resend = - brave_sync_prefs_->GetRecordsToResend(); - if (records_to_resend.empty()) - return; - - DCHECK(model_); - DCHECK(model_->loaded()); - - for (auto& object_id : records_to_resend) { - auto* node = FindByObjectId(model_, object_id); - - // Check resend interval - const base::DictionaryValue* meta = - brave_sync_prefs_->GetRecordToResendMeta(object_id); - DCHECK(meta); - int current_retry_number = kMaxSendRetries; - meta->GetInteger("send_retry_number", ¤t_retry_number); - DCHECK_GE(current_retry_number, 0); - double sync_timestamp = 0; - meta->GetDouble("sync_timestamp", &sync_timestamp); - DCHECK(!base::Time::FromJsTime(sync_timestamp).is_null()); - - if ((base::Time::Now() - base::Time::FromJsTime(sync_timestamp)) < - GetRetryExponentialWaitAmount(current_retry_number)) - continue; - - // Increase retry number - if (++current_retry_number > kMaxSendRetries) - current_retry_number = kMaxSendRetries; - std::unique_ptr new_meta = - base::DictionaryValue::From( - std::make_unique(meta->Clone())); - new_meta->SetInteger("send_retry_number", current_retry_number); - new_meta->SetDouble("sync_timestamp", base::Time::Now().ToJsTime()); - brave_sync_prefs_->SetRecordToResendMeta(object_id, std::move(new_meta)); - - if (node) { - records->push_back(BookmarkNodeToSyncBookmark(node)); - } else { - records->push_back( - CreateDeleteBookmarkByObjectId(brave_sync_prefs_.get(), object_id)); - } - } - if (!records->empty()) - brave_sync_client_->SendSyncRecords(category_name, *records); - } -} - -// static -base::TimeDelta BraveProfileSyncServiceImpl::GetRetryExponentialWaitAmount( - int retry_number) { - DCHECK_LE(retry_number, kMaxSendRetries); - - if (retry_number > kMaxSendRetries) { - retry_number = kMaxSendRetries; - } - return base::TimeDelta::FromMinutes(kExponentialWaits[retry_number]); -} - -// static -std::vector -BraveProfileSyncServiceImpl::GetExponentialWaitsForTests() { - return kExponentialWaits; -} - -void BraveProfileSyncServiceImpl::RecordSyncStateP3A() const { - int result = 0; - if (brave_sync_prefs_->GetSyncEnabled()) { - unsigned long device_count = // NOLINT - static_cast( // NOLINT - brave_sync_prefs_->GetSyncDevices()->size()); - // Answers are zero-based. - result = std::min(device_count, 3UL) - 1UL; - } - UMA_HISTOGRAM_EXACT_LINEAR("Brave.Sync.Status", result, 2); -} - -} // namespace brave_sync diff --git a/components/brave_sync/brave_profile_sync_service_impl.h b/components/brave_sync/brave_profile_sync_service_impl.h deleted file mode 100644 index 3258950c0642..000000000000 --- a/components/brave_sync/brave_profile_sync_service_impl.h +++ /dev/null @@ -1,350 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_PROFILE_SYNC_SERVICE_IMPL_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_PROFILE_SYNC_SERVICE_IMPL_H_ - -#include -#include -#include -#include - -#include "brave/components/brave_sync/brave_sync_service.h" -#include "brave/components/brave_sync/client/brave_sync_client.h" -#include "brave/components/brave_sync/jslib_messages_fwd.h" -#include "brave/components/brave_sync/public/brave_profile_sync_service.h" -#include "components/bookmarks/browser/bookmark_model.h" -#include "components/bookmarks/browser/bookmark_model_observer.h" -#include "components/prefs/pref_change_registrar.h" -#include "components/sync/driver/profile_sync_service.h" -#include "services/network/public/cpp/network_connection_tracker.h" - -FORWARD_DECLARE_TEST(BraveSyncServiceTest, BookmarkAdded); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, BookmarkDeleted); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, GetSyncWords); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, GetSeed); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnBraveSyncPrefsChanged); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnDeleteDevice); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnDeleteDeviceWhenOneDevice); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnDeleteDeviceWhenSelfDeleted); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnResetSync); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnResetSyncWhenOffline); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, ClientOnGetInitData); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnGetInitData); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnSaveBookmarksBaseOrder); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnSyncPrefsChanged); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnSyncDebug); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, StartSyncNonDeviceRecords); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnSyncReadyNewToSync); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, OnGetExistingObjects); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, - OnSetupSyncHaveCode_Reset_SetupAgain); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, ExponentialResend); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, GetDevicesWithFetchSyncRecords); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, SendCompact); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, SetSyncEnabled); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, SetSyncDisabled); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, IsSyncReadyOnNewProfile); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, SetThisDeviceCreatedTime); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, InitialFetchesStartWithZero); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, DeviceIdV2Migration); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, DeviceIdV2MigrationDupDeviceId); -FORWARD_DECLARE_TEST(BraveSyncServiceTestDelayedLoadModel, - OnSyncReadyModelNotYetLoaded); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, IsOtherBookmarksFolder); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, ProcessOtherBookmarksFolder); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, ProcessOtherBookmarksChildren); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, CheckOtherBookmarkRecord); -FORWARD_DECLARE_TEST(BraveSyncServiceTest, CheckOtherBookmarkChildRecord); - -class BraveSyncServiceTest; - -namespace bookmarks { -class BookmarkModel; -class BookmarkNode; -} // namespace bookmarks - -namespace brave_sync { -namespace prefs { -class Prefs; -} // namespace prefs - -using bookmarks::BookmarkModel; -using bookmarks::BookmarkNode; - -class BraveProfileSyncServiceImpl - : public BraveProfileSyncService, - public BraveSyncService, - public network::NetworkConnectionTracker::NetworkConnectionObserver, - public SyncMessageHandler, - public bookmarks::BookmarkModelObserver { - public: - explicit BraveProfileSyncServiceImpl(Profile* profile, - InitParams init_params); - - ~BraveProfileSyncServiceImpl() override; - - // BraveSyncService implementation - void OnSetupSyncHaveCode(const std::string& sync_words, - const std::string& device_name) override; - void OnSetupSyncNewToSync(const std::string& device_name) override; - void OnDeleteDevice(const std::string& device_id_v2) override; - void OnResetSync() override; - void GetSettingsAndDevices( - const GetSettingsAndDevicesCallback& callback) override; - void GetSyncWords() override; - std::string GetSeed() override; - void OnSetSyncEnabled(const bool sync_this_device) override; - void OnSetSyncBookmarks(const bool sync_bookmarks) override; - void OnSetSyncBrowsingHistory(const bool sync_browsing_history) override; - void OnSetSyncSavedSiteSettings(const bool sync_saved_site_settings) override; - - // SyncMessageHandler implementation - void BackgroundSyncStarted(bool startup) override; - void BackgroundSyncStopped(bool shutdown) override; - void OnSyncDebug(const std::string& message) override; - void OnSyncSetupError(const std::string& error) override; - void OnGetInitData(const std::string& sync_version) override; - void OnSaveInitData(const brave_sync::Uint8Array& seed, - const brave_sync::Uint8Array& device_id, - const std::string& device_id_v2) override; - void OnSyncReady() override; - void OnGetExistingObjects(const std::string& category_name, - std::unique_ptr records, - const base::Time& last_record_time_stamp, - const bool is_truncated) override; - void OnResolvedSyncRecords( - const std::string& category_name, - std::unique_ptr records) override; - void OnDeletedSyncUser() override; - void OnDeleteSyncSiteSettings() override; - void OnSaveBookmarksBaseOrder(const std::string& order) override; - void OnCompactComplete(const std::string& category_name) override; - void OnRecordsSent( - const std::string& category_name, - std::unique_ptr records) override; - - // syncer::SyncService implementation - syncer::SyncService::DisableReasonSet GetDisableReasons() const override; - CoreAccountInfo GetAuthenticatedAccountInfo() const override; - bool IsAuthenticatedAccountPrimary() const override; - - // NetworkConnectionTracker::NetworkConnectionObserver implementation. - void OnConnectionChanged(network::mojom::ConnectionType type) override; - - // KeyedService implementation. This must be called exactly - // once (before this object is destroyed). - void Shutdown() override; - - // bookmarks::BookmarkModelObserver implementation - void BookmarkModelLoaded(BookmarkModel* model, bool ids_reassigned) override; - - void BookmarkNodeMoved(BookmarkModel* model, - const BookmarkNode* old_parent, - size_t old_index, - const BookmarkNode* new_parent, - size_t new_index) override {} - - void BookmarkNodeAdded(BookmarkModel* model, - const BookmarkNode* parent, - size_t index) override {} - - void BookmarkNodeRemoved( - BookmarkModel* model, - const BookmarkNode* parent, - size_t old_index, - const BookmarkNode* node, - const std::set& no_longer_bookmarked) override {} - - void BookmarkNodeChanged(BookmarkModel* model, - const BookmarkNode* node) override {} - - void BookmarkNodeFaviconChanged(BookmarkModel* model, - const BookmarkNode* node) override {} - - void BookmarkNodeChildrenReordered(BookmarkModel* model, - const BookmarkNode* node) override {} - - void BookmarkAllUserNodesRemoved( - BookmarkModel* model, - const std::set& removed_urls) override {} - -#if BUILDFLAG(ENABLE_EXTENSIONS) - BraveSyncClient* GetBraveSyncClient() override; -#endif - - static void AddNonClonedBookmarkKeys(BookmarkModel* model); - - bool IsBraveSyncEnabled() const override; - - syncer::ModelTypeSet GetPreferredDataTypes() const override; - - void OnNudgeSyncCycle(brave_sync::RecordsListPtr records_list) override; - void OnPollSyncCycle(brave_sync::GetRecordsCallback cb, - base::WaitableEvent* wevent) override; - - BraveSyncService* GetSyncService() const override; - - static bool MigrateDuplicatedBookmarksObjectIds(bool sync_enabled, - Profile* profile, - BookmarkModel* model); - - private: - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, BookmarkAdded); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, BookmarkDeleted); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, GetSyncWords); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, GetSeed); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnBraveSyncPrefsChanged); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnDeleteDevice); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnDeleteDeviceWhenOneDevice); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - OnDeleteDeviceWhenSelfDeleted); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnResetSync); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnResetSyncWhenOffline); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, ClientOnGetInitData); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnSaveBookmarksBaseOrder); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnGetInitData); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnSyncPrefsChanged); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnSyncDebug); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, StartSyncNonDeviceRecords); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnSyncReadyNewToSync); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, OnGetExistingObjects); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - OnSetupSyncHaveCode_Reset_SetupAgain); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, ExponentialResend); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - GetDevicesWithFetchSyncRecords); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, SendCompact); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, SetSyncEnabled); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, SetSyncDisabled); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, IsSyncReadyOnNewProfile); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, SetThisDeviceCreatedTime); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, InitialFetchesStartWithZero); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, DeviceIdV2Migration); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - DeviceIdV2MigrationDupDeviceId); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTestDelayedLoadModel, - OnSyncReadyModelNotYetLoaded); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - IsOtherBookmarksFolder); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - ProcessOtherBookmarksFolder); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - ProcessOtherBookmarksChildren); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - CheckOtherBookmarkRecord); - FRIEND_TEST_ALL_PREFIXES(::BraveSyncServiceTest, - CheckOtherBookmarkChildRecord); - - friend class ::BraveSyncServiceTest; - - void SignalWaitableEvent(); - void FetchSyncRecords(const bool bookmarks, - const bool history, - const bool preferences, - int max_records); - void FetchDevices(); - void SendCreateDevice(); - void SendDeleteDevice(); - void SendDeviceSyncRecord(const int action, - const std::string& device_name, - const std::string& device_id, - const std::string& device_id_v2, - const std::string& object_id); - void OnResolvedPreferences(const brave_sync::RecordsList& records); - void OnBraveSyncPrefsChanged(const std::string& pref); - void NotifySyncSetupError(const std::string& error); - void NotifySyncStateChanged(); - void NotifyHaveSyncWords(const std::string& sync_words); - - void ResetSyncInternal(); - - void SetPermanentNodesOrder(const std::string& base_order); - - std::unique_ptr BookmarkNodeToSyncBookmark( - const bookmarks::BookmarkNode* node); - // These SyncEntityInfo is for legacy device who doesn't send meta info for - // sync entity - void SaveSyncEntityInfo(const jslib::SyncRecord* record); - void LoadSyncEntityInfo(jslib::SyncRecord* record); - - bool IsOtherBookmarksFolder(const jslib::SyncRecord* record) const; - // Handling "Other Bookmarks" remote records - void ProcessOtherBookmarksFolder(const jslib::SyncRecord* record, - bool* pass_to_syncer); - // Handling direct children of "Other Bookmarks" remote records - void ProcessOtherBookmarksChildren(jslib::SyncRecord* record); - // Check and correct info before sending records - void CheckOtherBookmarkRecord(jslib::SyncRecord* record); - void CheckOtherBookmarkChildRecord(jslib::SyncRecord* record); - - void CreateResolveList( - const std::vector>& records, - SyncRecordAndExistingList* records_and_existing_objects); - std::unique_ptr PrepareResolvedPreferences( - const RecordsList& records); - - void SendSyncRecords(const std::string& category_name, - RecordsListPtr records); - void ResendSyncRecords(const std::string& category_name); - - void RecordSyncStateP3A() const; - - bool IsSQSReady() const; - - // Method to be run right after bookmark model will be loaded - void OnSyncReadyBookmarksModelLoaded(); - - static base::TimeDelta GetRetryExponentialWaitAmount(int retry_number); - static std::vector GetExponentialWaitsForTests(); - static const std::vector kExponentialWaits; - static const int kMaxSendRetries; - static const int kCompactPeriodInDays = 7; - static constexpr int GetCompactPeriodInDaysForTests() { - return kCompactPeriodInDays; - } - - std::unique_ptr brave_sync_prefs_; - - // True if we have received SyncReady from JS lib - // This is used only to prevent out of sequence invocation of OnSaveInitData - // and prevent double invocation of OnSyncReady - bool brave_sync_ready_ = false; - - // Prevent two sequential calls OnSetupSyncHaveCode or OnSetupSyncNewToSync - // while being initializing - bool brave_sync_initializing_ = false; - - bool send_device_id_v2_update_ = false; - - Uint8Array seed_; - - brave_sync::GetRecordsCallback get_record_cb_; - base::WaitableEvent* wevent_ = nullptr; - - // Registrar used to monitor the brave_profile prefs. - PrefChangeRegistrar brave_pref_change_registrar_; - - bookmarks::BookmarkModel* model_ = nullptr; - - std::unique_ptr brave_sync_client_; - - std::unique_ptr pending_received_records_; - // Time when current device sent CREATE device record - base::Time this_device_created_time_; - - bool pending_self_reset_ = false; - - bool is_model_loaded_observer_set_ = false; - - // Used to ensure that certain operations are performed on the sequence that - // this object was created on. - SEQUENCE_CHECKER(sequence_checker_); - - DISALLOW_COPY_AND_ASSIGN(BraveProfileSyncServiceImpl); -}; -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_PROFILE_SYNC_SERVICE_IMPL_H_ diff --git a/patches/chrome-browser-sync-profile_sync_service_factory.cc.patch b/patches/chrome-browser-sync-profile_sync_service_factory.cc.patch deleted file mode 100644 index 2131c00e7fc3..000000000000 --- a/patches/chrome-browser-sync-profile_sync_service_factory.cc.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/chrome/browser/sync/profile_sync_service_factory.cc b/chrome/browser/sync/profile_sync_service_factory.cc -index b250bbb79abbd9c881284a2762d6b741fd6edd1b..3efa096e4e94edc4b26fc06cb1d3218f2046a7fa 100644 ---- a/chrome/browser/sync/profile_sync_service_factory.cc -+++ b/chrome/browser/sync/profile_sync_service_factory.cc -@@ -269,7 +269,7 @@ KeyedService* ProfileSyncServiceFactory::BuildServiceInstanceFor( - } - - auto pss = -- std::make_unique(std::move(init_params)); -+ BraveBuildServiceInstanceFor(profile, std::move(init_params)); - - #if defined(OS_WIN) - if (!local_sync_backend_enabled) diff --git a/patches/components-sync-base-BUILD.gn.patch b/patches/components-sync-base-BUILD.gn.patch deleted file mode 100644 index e19623ae8e9c..000000000000 --- a/patches/components-sync-base-BUILD.gn.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/base/BUILD.gn b/components/sync/base/BUILD.gn -index d35449062388b7155c584546ce4a8e98296c138f..04284d36c42665af1afbfa2d97db2fea484e9978 100644 ---- a/components/sync/base/BUILD.gn -+++ b/components/sync/base/BUILD.gn -@@ -80,6 +80,7 @@ jumbo_static_library("base") { - ] - deps = [ - "//base:i18n", -+ "//brave/components/brave_sync:public", - "//components/os_crypt", - "//components/pref_registry", - "//components/prefs", diff --git a/patches/components-sync-driver-glue-sync_engine_backend.cc.patch b/patches/components-sync-driver-glue-sync_engine_backend.cc.patch deleted file mode 100644 index 9b2b26d1bad0..000000000000 --- a/patches/components-sync-driver-glue-sync_engine_backend.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/driver/glue/sync_engine_backend.cc b/components/sync/driver/glue/sync_engine_backend.cc -index 9dd41584040da490fe5e298ea5732a7fd1276845..308ac46b0e8843d16de7ad450764be845c7edfb2 100644 ---- a/components/sync/driver/glue/sync_engine_backend.cc -+++ b/components/sync/driver/glue/sync_engine_backend.cc -@@ -383,6 +383,7 @@ void SyncEngineBackend::DoInitialize(SyncEngine::InitParams params) { - args.birthday = params.birthday; - args.bag_of_chips = params.bag_of_chips; - args.sync_status_observers.push_back(this); -+ BRAVE_SYNC_ENGINE_BACKEND_DO_INITIALIZE - sync_manager_->Init(&args); - base::trace_event::MemoryDumpManager::GetInstance() - ->RegisterDumpProviderWithSequencedTaskRunner( diff --git a/patches/components-sync-driver-glue-sync_engine_impl.h.patch b/patches/components-sync-driver-glue-sync_engine_impl.h.patch deleted file mode 100644 index d505a8637a06..000000000000 --- a/patches/components-sync-driver-glue-sync_engine_impl.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/driver/glue/sync_engine_impl.h b/components/sync/driver/glue/sync_engine_impl.h -index 9d900d5b9219a8cecb02aa6ae9555ccac375ac5d..403696d12411c39ebc6ecc0d82b3e5c719e11d75 100644 ---- a/components/sync/driver/glue/sync_engine_impl.h -+++ b/components/sync/driver/glue/sync_engine_impl.h -@@ -225,6 +225,7 @@ class SyncEngineImpl : public SyncEngine, public InvalidationHandler { - - base::WeakPtrFactory weak_ptr_factory_{this}; - -+ BRAVE_SYNC_ENGINE_IMPL_H - DISALLOW_COPY_AND_ASSIGN(SyncEngineImpl); - }; - diff --git a/patches/components-sync-driver-profile_sync_service.cc.patch b/patches/components-sync-driver-profile_sync_service.cc.patch deleted file mode 100644 index 11f59b29f954..000000000000 --- a/patches/components-sync-driver-profile_sync_service.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc -index 44a6eb15256323c76a10dcd6c412e228ae822e60..c76f70ddc3ad115051eb1f30c6bd84b7edd97319 100644 ---- a/components/sync/driver/profile_sync_service.cc -+++ b/components/sync/driver/profile_sync_service.cc -@@ -617,6 +617,7 @@ void ProfileSyncService::StartUpSlowEngineComponents() { - create_http_post_provider_factory_cb_, MakeUserAgentForSync(channel_), - url_loader_factory_->Clone(), network_time_update_callback_); - params.authenticated_account_id = authenticated_account_info.account_id; -+ BRAVE_PROFILE_SYNC_SERVICE_START_UP_SLOW_ENGINE_COMPONENTS - if (!base::FeatureList::IsEnabled(switches::kSyncE2ELatencyMeasurement)) { - invalidation::InvalidationService* invalidator = - sync_client_->GetInvalidationService(); diff --git a/patches/components-sync-driver-profile_sync_service.h.patch b/patches/components-sync-driver-profile_sync_service.h.patch deleted file mode 100644 index e53ed26da36f..000000000000 --- a/patches/components-sync-driver-profile_sync_service.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/driver/profile_sync_service.h b/components/sync/driver/profile_sync_service.h -index b71429377b2068f103656834068a079fded3822d..2072bb06f5cf782664d31a610b901c5ee57a6156 100644 ---- a/components/sync/driver/profile_sync_service.h -+++ b/components/sync/driver/profile_sync_service.h -@@ -521,6 +521,7 @@ class ProfileSyncService : public SyncService, - - base::WeakPtrFactory weak_factory_{this}; - -+ BRAVE_PROFILE_SYNC_SERVICE_H - DISALLOW_COPY_AND_ASSIGN(ProfileSyncService); - }; - diff --git a/patches/components-sync-engine-sync_engine.h.patch b/patches/components-sync-engine-sync_engine.h.patch deleted file mode 100644 index 7e7604da11bf..000000000000 --- a/patches/components-sync-engine-sync_engine.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine/sync_engine.h b/components/sync/engine/sync_engine.h -index 322cbdaaadcb455baab2c19a273e96e129f0b819..cdaa6788bbea7a41c2c454f58339adf616d3d645 100644 ---- a/components/sync/engine/sync_engine.h -+++ b/components/sync/engine/sync_engine.h -@@ -79,6 +79,7 @@ class SyncEngine : public ModelTypeConfigurer { - - // Define the polling interval. Must not be zero. - base::TimeDelta poll_interval; -+ BRAVE_SYNC_ENGINE_INIT_PARAMS_H - - private: - DISALLOW_COPY_AND_ASSIGN(InitParams); diff --git a/patches/components-sync-engine-sync_manager.h.patch b/patches/components-sync-engine-sync_manager.h.patch deleted file mode 100644 index 230d013fc4e8..000000000000 --- a/patches/components-sync-engine-sync_manager.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine/sync_manager.h b/components/sync/engine/sync_manager.h -index dda74a6b330b84d67e8dac386f9aa5ea1548aded..2eda3885bb0257a3128e585ca3ab4ccc982dbe4c 100644 ---- a/components/sync/engine/sync_manager.h -+++ b/components/sync/engine/sync_manager.h -@@ -256,6 +256,7 @@ class SyncManager { - std::string cache_guid; - std::string birthday; - std::string bag_of_chips; -+ BRAVE_SYNC_MANAGER_INIT_ARGS_H - - // List of observers to be added to AllStatus. - std::vector sync_status_observers; diff --git a/patches/components-sync-engine_impl-commit.cc.patch b/patches/components-sync-engine_impl-commit.cc.patch deleted file mode 100644 index 5b3d3ea79821..000000000000 --- a/patches/components-sync-engine_impl-commit.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/commit.cc b/components/sync/engine_impl/commit.cc -index 76a01993d12cccfbdd97c9252ba757428682dbb3..2d323d1feba598bad86fa49d040fb4c3c29fab38 100644 ---- a/components/sync/engine_impl/commit.cc -+++ b/components/sync/engine_impl/commit.cc -@@ -132,6 +132,7 @@ SyncerError Commit::PostAndProcessResponse( - sync_pb::ClientToServerResponse response; - const SyncerError post_result = SyncerProtoUtil::PostClientToServerMessage( - message_, &response, cycle, nullptr); -+ BRAVE_COMMIT_POST_AND_PROCESS_RESPONSE - TRACE_EVENT_END0("sync", "PostCommit"); - - // TODO(rlarocque): Use result that includes errors captured later? diff --git a/patches/components-sync-engine_impl-cycle-sync_cycle.h.patch b/patches/components-sync-engine_impl-cycle-sync_cycle.h.patch deleted file mode 100644 index 19818194d25e..000000000000 --- a/patches/components-sync-engine_impl-cycle-sync_cycle.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/cycle/sync_cycle.h b/components/sync/engine_impl/cycle/sync_cycle.h -index 0971b6014231f8046eca9202840acc6167960057..6f7adf18b33be49f18469026838cbd9ad64bb8c5 100644 ---- a/components/sync/engine_impl/cycle/sync_cycle.h -+++ b/components/sync/engine_impl/cycle/sync_cycle.h -@@ -79,6 +79,7 @@ class SyncCycle { - - // Called when server requests a migration. - virtual void OnReceivedMigrationRequest(ModelTypeSet types) = 0; -+ BRAVE_SYNC_CYCLE_DELEGATE_H - - protected: - virtual ~Delegate() {} diff --git a/patches/components-sync-engine_impl-get_updates_processor.cc.patch b/patches/components-sync-engine_impl-get_updates_processor.cc.patch deleted file mode 100644 index 5a7bc7251f2a..000000000000 --- a/patches/components-sync-engine_impl-get_updates_processor.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/get_updates_processor.cc b/components/sync/engine_impl/get_updates_processor.cc -index 0b0e5423569f053b8694a994587141709d1dd59a..fe931cbee8d1ba29a6c98c9fbfd1a14b47492428 100644 ---- a/components/sync/engine_impl/get_updates_processor.cc -+++ b/components/sync/engine_impl/get_updates_processor.cc -@@ -237,6 +237,7 @@ SyncerError GetUpdatesProcessor::ExecuteDownloadUpdates( - - SyncerError result = SyncerProtoUtil::PostClientToServerMessage( - *msg, &update_response, cycle, &partial_failure_data_types); -+ result = ApplyBraveRecords(&update_response, request_types, std::move(brave_records_)); - - DVLOG(2) << SyncerProtoUtil::ClientToServerResponseDebugString( - update_response); diff --git a/patches/components-sync-engine_impl-get_updates_processor.h.patch b/patches/components-sync-engine_impl-get_updates_processor.h.patch deleted file mode 100644 index 2382643845b6..000000000000 --- a/patches/components-sync-engine_impl-get_updates_processor.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/get_updates_processor.h b/components/sync/engine_impl/get_updates_processor.h -index c5560ec8113670c57f80245199031732f5795f23..f883a3aa1251dab8cd2ae07c467cbe42a1ebd089 100644 ---- a/components/sync/engine_impl/get_updates_processor.h -+++ b/components/sync/engine_impl/get_updates_processor.h -@@ -96,6 +96,7 @@ class GetUpdatesProcessor { - - const GetUpdatesDelegate& delegate_; - -+ BRAVE_GET_UPDATES_PROCESSOR_H - DISALLOW_COPY_AND_ASSIGN(GetUpdatesProcessor); - }; - diff --git a/patches/components-sync-engine_impl-process_updates_util.cc.patch b/patches/components-sync-engine_impl-process_updates_util.cc.patch deleted file mode 100644 index d39b45d16480..000000000000 --- a/patches/components-sync-engine_impl-process_updates_util.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/process_updates_util.cc b/components/sync/engine_impl/process_updates_util.cc -index 938f9a5ca2d2dd1602c80e6e032e6e5299a0f01f..78cfcaab4fd983cbbec63904fe765d1464f1b612 100644 ---- a/components/sync/engine_impl/process_updates_util.cc -+++ b/components/sync/engine_impl/process_updates_util.cc -@@ -202,6 +202,7 @@ void ProcessUpdate(const sync_pb::SyncEntity& update, - // change the ID now, after we're sure that the update can succeed. - if (local_id != server_id) { - DCHECK(!update.deleted()); -+ BRAVE_PROCESS_UPDATE - ChangeEntryIDAndUpdateChildren(trans, &target_entry, server_id); - // When IDs change, versions become irrelevant. Forcing BASE_VERSION - // to zero would ensure that this update gets applied, but would indicate diff --git a/patches/components-sync-engine_impl-sync_manager_impl.cc.patch b/patches/components-sync-engine_impl-sync_manager_impl.cc.patch deleted file mode 100644 index 7a58ee69c9a9..000000000000 --- a/patches/components-sync-engine_impl-sync_manager_impl.cc.patch +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/components/sync/engine_impl/sync_manager_impl.cc b/components/sync/engine_impl/sync_manager_impl.cc -index 477dca4f7b12921e1b931a4f87fce55a841f5d33..de84116803c38db496a846686c55dd24f8da404a 100644 ---- a/components/sync/engine_impl/sync_manager_impl.cc -+++ b/components/sync/engine_impl/sync_manager_impl.cc -@@ -364,8 +364,9 @@ void SyncManagerImpl::Init(InitArgs* args) { - args->poll_interval); - scheduler_ = args->engine_components_factory->BuildScheduler( - name_, cycle_context_.get(), args->cancelation_signal, -- args->enable_local_sync_backend); -+ true); - -+ BRAVE_SYNC_MANAGER_IMPL_INIT - scheduler_->Start(SyncScheduler::CONFIGURATION_MODE, base::Time()); - - initialized_ = true; diff --git a/patches/components-sync-engine_impl-sync_scheduler_impl.cc.patch b/patches/components-sync-engine_impl-sync_scheduler_impl.cc.patch deleted file mode 100644 index 9ed5d194f2c9..000000000000 --- a/patches/components-sync-engine_impl-sync_scheduler_impl.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/sync_scheduler_impl.cc b/components/sync/engine_impl/sync_scheduler_impl.cc -index 73d82300993fce2707b3d2455c0e3c60eaccd893..b1fc19bd50e6949bb3c1e2cc4d51234e780482f2 100644 ---- a/components/sync/engine_impl/sync_scheduler_impl.cc -+++ b/components/sync/engine_impl/sync_scheduler_impl.cc -@@ -687,6 +687,7 @@ void SyncSchedulerImpl::TryCanaryJob() { - } - - void SyncSchedulerImpl::TrySyncCycleJob() { -+ BRAVE_SYNC_SCHEDULER_IMPL_TRY_SYNC_CYCLE_JOB - // Post call to TrySyncCycleJobImpl on current sequence. Later request for - // access token will be here. - base::SequencedTaskRunnerHandle::Get()->PostTask( diff --git a/patches/components-sync-engine_impl-sync_scheduler_impl.h.patch b/patches/components-sync-engine_impl-sync_scheduler_impl.h.patch deleted file mode 100644 index ce32c24890d3..000000000000 --- a/patches/components-sync-engine_impl-sync_scheduler_impl.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/sync_scheduler_impl.h b/components/sync/engine_impl/sync_scheduler_impl.h -index 3dd41b315c1b2c141688bc4c971ba79f04bf20ee..837dbbaf433970b0aaeb0bd7a3c4bdab7997e08f 100644 ---- a/components/sync/engine_impl/sync_scheduler_impl.h -+++ b/components/sync/engine_impl/sync_scheduler_impl.h -@@ -88,6 +88,7 @@ class SyncSchedulerImpl : public SyncScheduler { - // tests. - void ForceShortNudgeDelayForTest(); - -+ BRAVE_SYNC_SCHEDULER_IMPL_H_ - private: - enum JobPriority { - // Non-canary jobs respect exponential backoff. diff --git a/patches/components-sync-engine_impl-syncer.cc.patch b/patches/components-sync-engine_impl-syncer.cc.patch deleted file mode 100644 index 5e9f6423031e..000000000000 --- a/patches/components-sync-engine_impl-syncer.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/syncer.cc b/components/sync/engine_impl/syncer.cc -index dd151d52a357a8e60672f71f50389fcb6293233d..8c1a4a81c38040ca02d6b0ec69c449ff61c1ae0a 100644 ---- a/components/sync/engine_impl/syncer.cc -+++ b/components/sync/engine_impl/syncer.cc -@@ -109,6 +109,7 @@ bool Syncer::DownloadAndApplyUpdates(ModelTypeSet* request_types, - Difference(*request_types, requested_commit_only_types); - GetUpdatesProcessor get_updates_processor( - cycle->context()->model_type_registry()->update_handler_map(), delegate); -+ get_updates_processor.AddBraveRecords(std::move(brave_records_)); - SyncerError download_result; - do { - download_result = diff --git a/patches/components-sync-engine_impl-syncer.h.patch b/patches/components-sync-engine_impl-syncer.h.patch deleted file mode 100644 index 519a01303369..000000000000 --- a/patches/components-sync-engine_impl-syncer.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/engine_impl/syncer.h b/components/sync/engine_impl/syncer.h -index b48b59370102b768c4fcbfe921b8d07da6d2fd42..bde5fbacf2aa2b933e3d9aa168cbc5fadce26e32 100644 ---- a/components/sync/engine_impl/syncer.h -+++ b/components/sync/engine_impl/syncer.h -@@ -92,6 +92,7 @@ class Syncer { - // Whether the syncer is in the middle of a sync attempt. - bool is_syncing_; - -+ BRAVE_SYNCER_H - DISALLOW_COPY_AND_ASSIGN(Syncer); - }; - diff --git a/patches/components-sync-engine_impl-syncer_proto_util.cc.patch b/patches/components-sync-engine_impl-syncer_proto_util.cc.patch deleted file mode 100644 index 1538abc6496c..000000000000 --- a/patches/components-sync-engine_impl-syncer_proto_util.cc.patch +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/components/sync/engine_impl/syncer_proto_util.cc b/components/sync/engine_impl/syncer_proto_util.cc -index 25d77685283b20d8206720739f094a271362ec0b..10478e1b82d5e79e2d3a7c6579305816d471cf4c 100644 ---- a/components/sync/engine_impl/syncer_proto_util.cc -+++ b/components/sync/engine_impl/syncer_proto_util.cc -@@ -396,6 +396,7 @@ base::TimeDelta SyncerProtoUtil::GetThrottleDelay( - void SyncerProtoUtil::AddRequiredFieldsToClientToServerMessage( - const SyncCycle* cycle, - sync_pb::ClientToServerMessage* msg) { -+ return; - DCHECK(msg); - SetProtocolVersion(msg); - const std::string birthday = cycle->context()->birthday(); -@@ -415,6 +416,7 @@ SyncerError SyncerProtoUtil::PostClientToServerMessage( - ClientToServerResponse* response, - SyncCycle* cycle, - ModelTypeSet* partial_failure_data_types) { -+ return SyncerError(SyncerError::SYNCER_OK); - DCHECK(response); - DCHECK(msg.has_protocol_version()); - DCHECK(msg.has_store_birthday() || !IsBirthdayRequired(msg)); diff --git a/patches/components-sync-syncable-write_transaction.cc.patch b/patches/components-sync-syncable-write_transaction.cc.patch deleted file mode 100644 index 4b25c62fbfe2..000000000000 --- a/patches/components-sync-syncable-write_transaction.cc.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/syncable/write_transaction.cc b/components/sync/syncable/write_transaction.cc -index 00b248a93830bbafae831d46d1089a0844c57805..f2dfcd72d90ec73d84180fd91a8db6c0270fb033 100644 ---- a/components/sync/syncable/write_transaction.cc -+++ b/components/sync/syncable/write_transaction.cc -@@ -28,6 +28,7 @@ WriteTransaction::WriteTransaction(const base::Location& from_here, - } - - WriteTransaction::~WriteTransaction() { -+ BRAVE_WRITE_TRANSACTION - delete transaction_; - } - diff --git a/patches/components-sync-syncable-write_transaction.h.patch b/patches/components-sync-syncable-write_transaction.h.patch deleted file mode 100644 index fd11ad582ffc..000000000000 --- a/patches/components-sync-syncable-write_transaction.h.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/components/sync/syncable/write_transaction.h b/components/sync/syncable/write_transaction.h -index 3d0a353ac09b1dcbfab0d5afc3345d78eb4ee8bd..b53e56bc0c43a43da32bd736eb86368e3bebec87 100644 ---- a/components/sync/syncable/write_transaction.h -+++ b/components/sync/syncable/write_transaction.h -@@ -56,6 +56,7 @@ class WriteTransaction : public BaseTransaction { - SyncChangeProcessor::ContextRefreshStatus refresh_status, - const std::string& context); - -+ BRAVE_WRITE_TRANSACTION_H_ - protected: - WriteTransaction() {} - diff --git a/patches/components-sync_bookmarks-bookmark_remote_updates_handler.cc.patch b/patches/components-sync_bookmarks-bookmark_remote_updates_handler.cc.patch deleted file mode 100644 index 46e683557bce..000000000000 --- a/patches/components-sync_bookmarks-bookmark_remote_updates_handler.cc.patch +++ /dev/null @@ -1,24 +0,0 @@ -diff --git a/components/sync_bookmarks/bookmark_remote_updates_handler.cc b/components/sync_bookmarks/bookmark_remote_updates_handler.cc -index 30a54904dfff162acef31ce5ea160740d299e617..e1342f9302b5761028bd1d29352cde3e7afb7d03 100644 ---- a/components/sync_bookmarks/bookmark_remote_updates_handler.cc -+++ b/components/sync_bookmarks/bookmark_remote_updates_handler.cc -@@ -158,6 +158,7 @@ void ApplyRemoteUpdate( - // Compute index information before updating the |tracker|. - const size_t old_index = size_t{old_parent->GetIndexOf(node)}; - const size_t new_index = -+ BRAVE_APPLY_REMOTE_UPDATE - ComputeChildNodeIndex(new_parent, update_entity.unique_position, tracker); - tracker->Update(tracked_entity, update.response_version, - update_entity.modification_time, -@@ -532,9 +533,11 @@ BookmarkRemoteUpdatesHandler::ProcessCreate( - LogProblematicBookmark(RemoteBookmarkUpdateError::kParentNotFolder); - return nullptr; - } -+ BRAVE_PROCESS_CREATE_1 - const bookmarks::BookmarkNode* bookmark_node = - CreateBookmarkNodeFromSpecifics( - update_entity.specifics.bookmark(), parent_node, -+ BRAVE_PROCESS_CREATE_2 - ComputeChildNodeIndex(parent_node, update_entity.unique_position, - bookmark_tracker_), - update_entity.is_folder, bookmark_model_, favicon_service_); From b0e7c55556f1e4012027bc92b7f59efaee76056c Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Wed, 26 Feb 2020 15:07:40 -0700 Subject: [PATCH 02/79] Remove sync-internals redirect Enable sync by default in flags Don't set kSyncManaged --- browser/brave_content_browser_client.cc | 8 -------- browser/brave_profile_prefs.cc | 3 --- components/brave_sync/features.cc | 2 +- 3 files changed, 1 insertion(+), 12 deletions(-) diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index e33e4c348236..cb3e7747e95e 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -415,14 +415,6 @@ GURL BraveContentBrowserClient::GetEffectiveURL( // [static] bool BraveContentBrowserClient::HandleURLOverrideRewrite(GURL* url, content::BrowserContext* browser_context) { - // redirect sync-internals - if (url->host() == chrome::kChromeUISyncInternalsHost || - url->host() == chrome::kChromeUISyncHost) { - GURL::Replacements replacements; - replacements.SetHostStr(chrome::kChromeUISyncHost); - *url = url->ReplaceComponents(replacements); - return true; - } // no special win10 welcome page if (url->host() == chrome::kChromeUIWelcomeHost) { diff --git a/browser/brave_profile_prefs.cc b/browser/brave_profile_prefs.cc index 4d7fd9281bb8..785ef129ee38 100644 --- a/browser/brave_profile_prefs.cc +++ b/browser/brave_profile_prefs.cc @@ -186,9 +186,6 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { prefs::kNetworkPredictionOptions, base::Value(chrome_browser_net::NETWORK_PREDICTION_NEVER)); - // Make sync managed to dsiable some UI after password saving. - registry->SetDefaultPrefValue(syncer::prefs::kSyncManaged, base::Value(true)); - // Disable cloud print // Cloud Print: Don't allow this browser to act as Cloud Print server registry->SetDefaultPrefValue(prefs::kCloudPrintProxyEnabled, diff --git a/components/brave_sync/features.cc b/components/brave_sync/features.cc index 4d96ea912aaa..6f66f703d2cd 100644 --- a/components/brave_sync/features.cc +++ b/components/brave_sync/features.cc @@ -10,7 +10,7 @@ namespace brave_sync { namespace features { -const base::Feature kBraveSync{"BraveSync", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kBraveSync{"BraveSync", base::FEATURE_ENABLED_BY_DEFAULT}; } // namespace features } // namespace brave_sync From cc5f8f42354e9046635208dabec97208a7b536e0 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Thu, 27 Feb 2020 11:22:01 -0700 Subject: [PATCH 03/79] Make local server code load from disk every time when handling GetUpdatesRequest so that we can have different processes running local backend use same local backend dir --- ...ine_impl-loopback_server-loopback_server.cc.patch | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 patches/components-sync-engine_impl-loopback_server-loopback_server.cc.patch diff --git a/patches/components-sync-engine_impl-loopback_server-loopback_server.cc.patch b/patches/components-sync-engine_impl-loopback_server-loopback_server.cc.patch new file mode 100644 index 000000000000..ce971b52cd1c --- /dev/null +++ b/patches/components-sync-engine_impl-loopback_server-loopback_server.cc.patch @@ -0,0 +1,12 @@ +diff --git a/components/sync/engine_impl/loopback_server/loopback_server.cc b/components/sync/engine_impl/loopback_server/loopback_server.cc +index ff1a357065c4d056c70285740d942e02c4235f34..c3e53d919236df21e052991d838f6ce19f1921ae 100644 +--- a/components/sync/engine_impl/loopback_server/loopback_server.cc ++++ b/components/sync/engine_impl/loopback_server/loopback_server.cc +@@ -385,6 +385,7 @@ bool LoopbackServer::HandleGetUpdatesRequest( + const std::string& invalidator_client_id, + sync_pb::GetUpdatesResponse* response, + std::vector* datatypes_to_migrate) { ++ LoadStateFromFile(persistent_file_); + response->set_changes_remaining(0); + + bool is_initial_bookmark_sync = false; From 1c07eba525832ac0b62d3edfb088727c55edd3a8 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Fri, 28 Feb 2020 11:32:03 -0800 Subject: [PATCH 04/79] overrides IsCreditCardMigrationEnabled and ShouldManagePasswordsinGooglePasswordManager --- .../ui/passwords/manage_passwords_view_utils.cc | 12 ++++++++++++ .../autofill/core/browser/autofill_experiments.cc | 10 ++++++++++ 2 files changed, 22 insertions(+) create mode 100644 chromium_src/chrome/browser/ui/passwords/manage_passwords_view_utils.cc diff --git a/chromium_src/chrome/browser/ui/passwords/manage_passwords_view_utils.cc b/chromium_src/chrome/browser/ui/passwords/manage_passwords_view_utils.cc new file mode 100644 index 000000000000..5dfda7198518 --- /dev/null +++ b/chromium_src/chrome/browser/ui/passwords/manage_passwords_view_utils.cc @@ -0,0 +1,12 @@ +/* Copyright (c) 2020 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#define ShouldManagePasswordsinGooglePasswordManager \ + ShouldManagePasswordsinGooglePasswordManager_ChromiumImpl +#include "../../../../../../chrome/browser/ui/passwords/manage_passwords_view_utils.cc" +#undef ShouldManagePasswordsinGooglePasswordManager +bool ShouldManagePasswordsinGooglePasswordManager(Profile* profile) { + return false; +} diff --git a/chromium_src/components/autofill/core/browser/autofill_experiments.cc b/chromium_src/components/autofill/core/browser/autofill_experiments.cc index 991f0632a691..1b8958467d58 100644 --- a/chromium_src/components/autofill/core/browser/autofill_experiments.cc +++ b/chromium_src/components/autofill/core/browser/autofill_experiments.cc @@ -14,6 +14,7 @@ class SyncService; namespace autofill { class LogManager; +class PersonalDataManager; bool IsCreditCardUploadEnabled(const PrefService* pref_service, const syncer::SyncService* sync_service, const std::string& user_email, @@ -21,8 +22,17 @@ bool IsCreditCardUploadEnabled(const PrefService* pref_service, LogManager* log_manager) { return false; } +bool IsCreditCardMigrationEnabled(PersonalDataManager* personal_data_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + bool is_test_mode, + LogManager* log_manager) { + return false; +} } // namespace autofill #define IsCreditCardUploadEnabled IsCreditCardUploadEnabled_ChromiumImpl +#define IsCreditCardMigrationEnabled IsCreditCardMigrationEnabled_ChromiumImpl #include "../../../../../../components/autofill/core/browser/autofill_experiments.cc" #undef IsCreditCardUploadEnabled +#undef IsCreditCardMigrationEnabled From a945ddf82ba309f79d20b879654c195771a22865 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Tue, 3 Mar 2020 17:42:34 -0800 Subject: [PATCH 05/79] Add sync controls to brave sync page using existing elements to avoid duplicate logic enforce custom passphrase Integrate sync code flow Add view code and fix sync status update --- .../settings/brave_settings_overrides.js | 3 +- .../brave_sync_browser_proxy.html | 2 - .../brave_sync_browser_proxy.js | 20 - .../brave_sync_page/brave_sync_control.html | 81 ++++ .../brave_sync_page/brave_sync_control.js | 258 +++++++++++ .../brave_sync_page/brave_sync_page.html | 31 +- .../brave_sync_page/brave_sync_page.js | 58 ++- .../brave_sync_page/brave_sync_subpage.html | 84 ++++ .../brave_sync_page/brave_sync_subpage.js | 403 ++++++++++++++++++ .../resources/settings/settings_resources.grd | 6 +- .../ui/webui/settings/people_handler.cc | 45 ++ .../ui/webui/settings/people_handler.h | 10 + ...gs-people_page-sync_browser_proxy.js.patch | 32 ++ ...ettings-people_page-sync_controls.js.patch | 21 + ...-ui-webui-settings-people_handler.cc.patch | 42 ++ ...r-ui-webui-settings-people_handler.h.patch | 12 + 16 files changed, 1062 insertions(+), 46 deletions(-) delete mode 100644 browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.html delete mode 100644 browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.js create mode 100644 browser/resources/settings/brave_sync_page/brave_sync_control.html create mode 100644 browser/resources/settings/brave_sync_page/brave_sync_control.js create mode 100644 browser/resources/settings/brave_sync_page/brave_sync_subpage.html create mode 100644 browser/resources/settings/brave_sync_page/brave_sync_subpage.js create mode 100644 chromium_src/chrome/browser/ui/webui/settings/people_handler.cc create mode 100644 chromium_src/chrome/browser/ui/webui/settings/people_handler.h create mode 100644 patches/chrome-browser-resources-settings-people_page-sync_browser_proxy.js.patch create mode 100644 patches/chrome-browser-resources-settings-people_page-sync_controls.js.patch create mode 100644 patches/chrome-browser-ui-webui-settings-people_handler.cc.patch create mode 100644 patches/chrome-browser-ui-webui-settings-people_handler.h.patch diff --git a/browser/resources/settings/brave_settings_overrides.js b/browser/resources/settings/brave_settings_overrides.js index b2a6b1c3cec5..bbbbbb88af2a 100644 --- a/browser/resources/settings/brave_settings_overrides.js +++ b/browser/resources/settings/brave_settings_overrides.js @@ -282,6 +282,7 @@ BravePatching.RegisterPolymerTemplateModifications({ r.SOCIAL_BLOCKING = r.BASIC.createSection('/socialBlocking', 'socialBlocking') r.EXTENSIONS = r.BASIC.createSection('/extensions', 'extensions') r.BRAVE_SYNC = r.BASIC.createSection('/braveSync', 'braveSync') + r.BRAVE_SYNC_SETUP = r.BRAVE_SYNC.createChild('/braveSync/setup'); r.BRAVE_HELP_TIPS = r.BASIC.createSection('/braveHelpTips', 'braveHelpTips') r.BRAVE_NEW_TAB = r.BASIC.createSection('/newTab', 'newTab') if (!r.SITE_SETTINGS) { @@ -337,7 +338,7 @@ BravePatching.RegisterPolymerTemplateModifications({ sectionSync.setAttribute('if', '[[showPage_(pageVisibility.braveSync)]]') sectionSync.innerHTML = ` - + ` const sectionShields = document.createElement('template') diff --git a/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.html b/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.html deleted file mode 100644 index bff4ad058a78..000000000000 --- a/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.html +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.js b/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.js deleted file mode 100644 index ae8da540dfbc..000000000000 --- a/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.js +++ /dev/null @@ -1,20 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - - cr.define('settings', function() { - /** @interface */ - class DefaultBraveSyncBrowserProxy {} - - /** - * @implements {settings.DefaultBraveSyncBrowserProxy} - */ - class DefaultBraveSyncBrowserProxyImpl {} - - cr.addSingletonGetter(DefaultBraveSyncBrowserProxyImpl); - - return { - DefaultBraveSyncBrowserProxy, - DefaultBraveSyncBrowserProxyImpl - }; -}); diff --git a/browser/resources/settings/brave_sync_page/brave_sync_control.html b/browser/resources/settings/brave_sync_page/brave_sync_control.html new file mode 100644 index 000000000000..e8264234cf14 --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_control.html @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/browser/resources/settings/brave_sync_page/brave_sync_control.js b/browser/resources/settings/brave_sync_page/brave_sync_control.js new file mode 100644 index 000000000000..473729d2c3bf --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_control.js @@ -0,0 +1,258 @@ +// Copyright 2018 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. +/** + * @fileoverview + * 'settings-sync-account-section' is the settings page containing sign-in + * settings. + */ +cr.exportPath('settings'); + +/** @const {number} */ +settings.MAX_SIGNIN_PROMO_IMPRESSION = 10; + +Polymer({ + is: 'settings-brave-sync-control', + + behaviors: [ + WebUIListenerBehavior, + PrefsBehavior, + settings.RouteObserverBehavior, + ], + + properties: { + /** + * Preferences state. + */ + prefs: { + type: Object, + notify: true, + }, + + /** + * The current sync status, supplied by parent element. + * @type {!settings.SyncStatus} + */ + syncStatus: Object, + + + // This property should be set by the parent only and should not change + // after the element is created. + embeddedInSubpage: { + type: Boolean, + reflectToAttribute: true, + }, + + // This property should be set by the parent only and should not change + // after the element is created. + hideButtons: { + type: Boolean, + value: false, + reflectToAttribute: true, + }, + + /** @private */ + showSetupButtons_: { + type: Boolean, + computed: 'computeShowSetupButtons_(' + + 'hideButtons, syncStatus.firstSetupInProgress)', + }, + + /** @private */ + viewSyncCodeOnly_: { + type: Boolean, + computed: 'computeViewSyncCodeOnly_(' + + 'syncStatus.firstSetupInProgress)', + }, + + passphrase: { + type: String, + value: '', + notify: true, + }, + + /** @private */ + showSyncCodeSetupDialog_: { + type: Boolean, + value: false, + }, + + /** @private */ + showHaveSyncCodeDialog_: { + type: Boolean, + value: false, + }, + }, + + /** @private {?settings.SyncBrowserProxy} */ + syncBrowserProxy_: null, + + created: function() { + this.syncBrowserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); + }, + + /** @protected */ + currentRouteChanged: function() { + if (settings.getCurrentRoute() != settings.routes.BRAVE_SYNC_SETUP) { + this.showSyncCodeSetupDialog_ = false; + this.showHaveSyncCodeDialog_ = false; + } + }, + + /** + * Returns the class of the sync icon. + * @return {string} + * @private + */ + getSyncIconStyle_: function() { + if (this.syncStatus.disabled) { + return 'sync-disabled'; + } + if (!this.syncStatus.hasError) { + return 'sync'; + } + // Specific error cases below. + if (this.syncStatus.hasUnrecoverableError) { + return 'sync-problem'; + } + if (this.syncStatus.statusAction == settings.StatusAction.REAUTHENTICATE) { + return 'sync-paused'; + } + return 'sync-problem'; + }, + + /** + * Returned value must match one of iron-icon's settings:(*) icon name. + * @return {string} + * @private + */ + getSyncIcon_: function() { + switch (this.getSyncIconStyle_()) { + case 'sync-problem': + return 'settings:sync-problem'; + case 'sync-paused': + return 'settings:sync-disabled'; + default: + return 'cr:sync'; + } + }, + + /** + * Determines if the sync button should be disabled in response to + * either a first setup flow or chrome sign-in being disabled. + * @return {boolean} + * @private + */ + shouldDisableSyncButton_: function() { + if (this.hideButtons || + !loadTimeData.getBoolean('privacySettingsRedesignEnabled')) { + // Maintain existing behaviour if hidden or flag disabled + return this.computeShowSetupButtons_(); + } + return !!this.syncStatus.firstSetupInProgress || + !this.getPref('signin.allowed_on_next_startup').value; + }, + + /** + * @return {boolean} + * @private + */ + shouldShowTurnOffButton_: function() { + return !this.hideButtons && !this.showSetupButtons_ && + !!this.syncStatus.signedIn; + }, + + + /** @private */ + onErrorButtonTap_: function() { + switch (this.syncStatus.statusAction) { + case settings.StatusAction.REAUTHENTICATE: + this.syncBrowserProxy_.startSignIn(); + break; + case settings.StatusAction.SIGNOUT_AND_SIGNIN: + if (this.syncStatus.domain) { + settings.navigateTo(settings.routes.SIGN_OUT); + } else { + // Silently sign the user out without deleting their profile and + // prompt them to sign back in. + this.syncBrowserProxy_.signOut(false); + this.syncBrowserProxy_.startSignIn(); + } + break; + case settings.StatusAction.UPGRADE_CLIENT: + settings.navigateTo(settings.routes.ABOUT); + break; + case settings.StatusAction.RETRIEVE_TRUSTED_VAULT_KEYS: + this.syncBrowserProxy_.startKeyRetrieval(); + break; + case settings.StatusAction.ENTER_PASSPHRASE: + case settings.StatusAction.CONFIRM_SYNC_SETTINGS: + default: + settings.navigateTo(settings.routes.SYNC); + } + }, + + /** + * @return {boolean} + * @private + */ + computeShowSetupButtons_: function() { + console.error(this.syncStatus); + // return true; + return !this.hideButtons && !!this.syncStatus.firstSetupInProgress; + }, + + /** + * @return {boolean} + * @private + */ + computeViewSyncCodeOnly_: function() { + return !this.syncStatus.firstSetupInProgress; + }, + + /** @private */ + onSetupCancel_: function() { + this.fire('sync-setup-done', false); + }, + + /** @private */ + onSetupConfirm_: function() { + if (!this.passphrase) { + this.passphrase = this.$$('#enterSyncCode').value; + console.error(this.passphrase); + } + this.fire('sync-setup-done', true); + }, + + /** @private */ + onSyncCodeSetupDialogClose_: function() { + this.showSyncCodeSetupDialog_ = false; + }, + + /** @private */ + onHaveSyncCodeDialogClose_: function() { + this.showHaveSyncCodeDialog_ = false; + }, + + /** @private */ + onSyncCodeSteupDialogCopy_: function() { + navigator.clipboard.writeText(this.$$('#syncCode').value); + }, + + /** @private */ + onStartANewSyncChain_: function() { + this.syncBrowserProxy_.getSyncCode().then((syncCode) => { + this.passphrase = syncCode; + }) + this.showSyncCodeSetupDialog_ = true; + Polymer.dom.flush(); + this.$$('#syncCodeSetup').showModal(); + }, + + /** @private */ + onHaveSyncCode_: function() { + this.showHaveSyncCodeDialog_ = true; + Polymer.dom.flush(); + this.$$('#haveSyncCode').showModal(); + }, +}); diff --git a/browser/resources/settings/brave_sync_page/brave_sync_page.html b/browser/resources/settings/brave_sync_page/brave_sync_page.html index cd55d4fa1bef..0c0766caca5e 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_page.html +++ b/browser/resources/settings/brave_sync_page/brave_sync_page.html @@ -1,10 +1,19 @@ + + - + + + + + + + + diff --git a/browser/resources/settings/brave_sync_page/brave_sync_page.js b/browser/resources/settings/brave_sync_page/brave_sync_page.js index 1d64d114374d..46f1c07d3f60 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_page.js +++ b/browser/resources/settings/brave_sync_page/brave_sync_page.js @@ -2,28 +2,46 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ - (function() { - 'use strict'; +/** + * 'settings-brave-sync-page' is the settings page containing brave's + * custom sync. + */ +Polymer({ + is: 'settings-brave-sync-page', - /** - * 'settings-brave-sync-page' is the settings page containing brave's - * custom sync. - */ - Polymer({ - is: 'settings-brave-sync-page', + behaviors: [I18nBehavior, WebUIListenerBehavior], - properties: {}, + properties: { + /** + * Preferences state. + */ + prefs: { + type: Object, + notify: true, + }, - /** @private {?settings.DefaultBraveSyncBrowserProxy} */ - browserProxy_: null, + /** + * The current sync status, supplied by SyncBrowserProxy. + * @type {?settings.SyncStatus} + */ + syncStatus: Object, - /** @override */ - created: function() { - this.browserProxy_ = settings.DefaultBraveSyncBrowserProxyImpl.getInstance(); - }, + /** + * Dictionary defining page visibility. + * @type {!PageVisibility} + */ + pageVisibility: Object, + }, - /** @override */ - ready: function() { - }, - }); - })(); + /** @override */ + attached: function() { + this.addWebUIListener('sync-settings-saved', () => { + }); + }, + /** @private */ + onSyncTap_: function() { + // Users can go to sync subpage regardless of sync status. + settings.navigateTo(settings.routes.BRAVE_SYNC_SETUP); + }, + +}); diff --git a/browser/resources/settings/brave_sync_page/brave_sync_subpage.html b/browser/resources/settings/brave_sync_page/brave_sync_subpage.html new file mode 100644 index 000000000000..36da6cfa3174 --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.html @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/browser/resources/settings/brave_sync_page/brave_sync_subpage.js b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js new file mode 100644 index 000000000000..07702bda28b8 --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js @@ -0,0 +1,403 @@ +// Copyright 2015 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. + +(function() { + +/** + * @fileoverview + * 'settings-sync-page' is the settings page containing sync settings. + */ +Polymer({ + is: 'settings-brave-sync-subpage', + + behaviors: [ + WebUIListenerBehavior, + settings.RouteObserverBehavior, + ], + + properties: { + /** + * Preferences state. + */ + prefs: { + type: Object, + notify: true, + }, + + /** @private */ + pages_: { + type: Object, + value: settings.PageStatus, + readOnly: true, + }, + + /** + * The current page status. Defaults to |CONFIGURE| such that the searching + * algorithm can search useful content when the page is not visible to the + * user. + * @private {?settings.PageStatus} + */ + pageStatus_: { + type: String, + value: settings.PageStatus.CONFIGURE, + }, + + /** + * Dictionary defining page visibility. + * @type {!PrivacyPageVisibility} + */ + pageVisibility: Object, + + /** + * The current sync preferences, supplied by SyncBrowserProxy. + * @type {settings.SyncPrefs|undefined} + */ + syncPrefs: { + type: Object, + }, + + /** @type {settings.SyncStatus} */ + syncStatus: { + type: Object, + }, + + /** + * The passphrase input field value. + * @private + */ + passphrase_: { + type: String, + value: '', + }, + + /** @private */ + syncSectionDisabled_: { + type: Boolean, + value: false, + computed: 'computeSyncSectionDisabled_(' + + 'syncStatus.disabled, ' + + 'syncStatus.hasError, syncStatus.statusAction, ' + + 'syncPrefs.trustedVaultKeysRequired)', + }, + + // + diceEnabled: Boolean, + // + + /** @private */ + showSetupCancelDialog_: { + type: Boolean, + value: false, + }, + }, + + /** @private {?settings.SyncBrowserProxy} */ + browserProxy_: null, + + /** + * The beforeunload callback is used to show the 'Leave site' dialog. This + * makes sure that the user has the chance to go back and confirm the sync + * opt-in before leaving. + * + * This property is non-null if the user is currently navigated on the sync + * settings route. + * + * @private {?Function} + */ + beforeunloadCallback_: null, + + /** + * The unload callback is used to cancel the sync setup when the user hits + * the browser back button after arriving on the page. + * Note: Cases like closing the tab or reloading don't need to be handled, + * because they are already caught in |PeopleHandler::~PeopleHandler| + * from the C++ code. + * + * @private {?Function} + */ + unloadCallback_: null, + + /** + * Whether the initial layout for collapsible sections has been computed. It + * is computed only once, the first time the sync status is updated. + * @private {boolean} + */ + collapsibleSectionsInitialized_: false, + + /** + * Whether the user decided to abort sync. + * @private {boolean} + */ + didAbort_: true, + + /** + * Whether the user confirmed the cancellation of sync. + * @private {boolean} + */ + setupCancelConfirmed_: false, + + /** @override */ + created: function() { + this.browserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); + }, + + /** @override */ + attached: function() { + this.addWebUIListener( + 'page-status-changed', this.handlePageStatusChanged_.bind(this)); + this.addWebUIListener( + 'sync-prefs-changed', this.handleSyncPrefsChanged_.bind(this)); + + if (settings.getCurrentRoute() == settings.routes.BRAVE_SYNC_SETUP) { + this.onNavigateToPage_(); + } + }, + + /** @override */ + detached: function() { + if (settings.routes.BRAVE_SYNC_SETUP.contains(settings.getCurrentRoute())) { + this.onNavigateAwayFromPage_(); + } + + if (this.beforeunloadCallback_) { + window.removeEventListener('beforeunload', this.beforeunloadCallback_); + this.beforeunloadCallback_ = null; + } + if (this.unloadCallback_) { + window.removeEventListener('unload', this.unloadCallback_); + this.unloadCallback_ = null; + } + }, + + /** + * Handler for when the sync state is pushed from the browser. + * @param {?settings.SyncStatus} syncStatus + * @private + */ + handleSyncStatus_: function(syncStatus) { + console.error(syncStatus); + this.syncStatus = syncStatus; + }, + + + /** + * @return {boolean} + * @private + */ + computeSyncSectionDisabled_: function() { + return this.syncStatus !== undefined && + (!!this.syncStatus.disabled || + (!!this.syncStatus.hasError && + this.syncStatus.statusAction !== + settings.StatusAction.ENTER_PASSPHRASE && + this.syncStatus.statusAction !== + settings.StatusAction.RETRIEVE_TRUSTED_VAULT_KEYS)); + }, + + /** @private */ + onSetupCancelDialogBack_: function() { + this.$$('#setupCancelDialog').cancel(); + chrome.metricsPrivate.recordUserAction( + 'Signin_Signin_CancelCancelAdvancedSyncSettings'); + }, + + /** @private */ + onSetupCancelDialogConfirm_: function() { + this.setupCancelConfirmed_ = true; + this.$$('#setupCancelDialog').close(); + settings.navigateTo(settings.routes.BASIC); + chrome.metricsPrivate.recordUserAction( + 'Signin_Signin_ConfirmCancelAdvancedSyncSettings'); + }, + + /** @private */ + onSetupCancelDialogClose_: function() { + this.showSetupCancelDialog_ = false; + }, + + /** @protected */ + currentRouteChanged: function() { + console.error(settings.getCurrentRoute()); + if (settings.getCurrentRoute() == settings.routes.BRAVE_SYNC_SETUP) { + this.onNavigateToPage_(); + return; + } + + if (settings.routes.BRAVE_SYNC_SETUP.contains(settings.getCurrentRoute())) { + return; + } + + const searchParams = settings.getQueryParameters().get('search'); + if (searchParams) { + // User navigated away via searching. Cancel sync without showing + // confirmation dialog. + this.onNavigateAwayFromPage_(); + return; + } + + const userActionCancelsSetup = this.syncStatus && + this.syncStatus.firstSetupInProgress && this.didAbort_; + if (userActionCancelsSetup && !this.setupCancelConfirmed_) { + chrome.metricsPrivate.recordUserAction( + 'Signin_Signin_BackOnAdvancedSyncSettings'); + // Show the 'Cancel sync?' dialog. + // Yield so that other |currentRouteChanged| observers are called, + // before triggering another navigation (and another round of observers + // firing). Triggering navigation from within an observer leads to some + // undefined behavior and runtime errors. + requestAnimationFrame(() => { + settings.navigateTo(settings.routes.BRAVE_SYNC_SETUP); + this.showSetupCancelDialog_ = true; + // Flush to make sure that the setup cancel dialog is attached. + Polymer.dom.flush(); + this.$$('#setupCancelDialog').showModal(); + }); + return; + } + + // Reset variable. + this.setupCancelConfirmed_ = false; + + this.onNavigateAwayFromPage_(); + }, + + /** + * @param {!settings.PageStatus} expectedPageStatus + * @return {boolean} + * @private + */ + isStatus_: function(expectedPageStatus) { + return expectedPageStatus == this.pageStatus_; + }, + + /** @private */ + onNavigateToPage_: function() { + assert(settings.getCurrentRoute() == settings.routes.BRAVE_SYNC_SETUP); + + this.browserProxy_.getSyncStatus().then( + this.handleSyncStatus_.bind(this)); + + if (this.beforeunloadCallback_) { + return; + } + + this.collapsibleSectionsInitialized_ = false; + + // Display loading page until the settings have been retrieved. + this.pageStatus_ = settings.PageStatus.SPINNER; + + this.browserProxy_.didNavigateToSyncPage(); + + this.beforeunloadCallback_ = event => { + // When the user tries to leave the sync setup, show the 'Leave site' + // dialog. + if (this.syncStatus && this.syncStatus.firstSetupInProgress) { + event.preventDefault(); + event.returnValue = ''; + + chrome.metricsPrivate.recordUserAction( + 'Signin_Signin_AbortAdvancedSyncSettings'); + } + }; + window.addEventListener('beforeunload', this.beforeunloadCallback_); + + this.unloadCallback_ = this.onNavigateAwayFromPage_.bind(this); + window.addEventListener('unload', this.unloadCallback_); + }, + + /** @private */ + onNavigateAwayFromPage_: function() { + if (!this.beforeunloadCallback_) { + return; + } + + // Reset the status to CONFIGURE such that the searching algorithm can + // search useful content when the page is not visible to the user. + this.pageStatus_ = settings.PageStatus.CONFIGURE; + + this.browserProxy_.didNavigateAwayFromSyncPage(this.didAbort_); + + window.removeEventListener('beforeunload', this.beforeunloadCallback_); + this.beforeunloadCallback_ = null; + + if (this.unloadCallback_) { + window.removeEventListener('unload', this.unloadCallback_); + this.unloadCallback_ = null; + } + }, + + /** + * Handler for when the sync preferences are updated. + * @private + */ + handleSyncPrefsChanged_: function(syncPrefs) { + this.syncPrefs = syncPrefs; + this.pageStatus_ = settings.PageStatus.CONFIGURE; + }, + + /** + * Called when the page status updates. + * @param {!settings.PageStatus} pageStatus + * @private + */ + handlePageStatusChanged_: function(pageStatus) { + console.error(pageStatus); + switch (pageStatus) { + case settings.PageStatus.SPINNER: + case settings.PageStatus.TIMEOUT: + case settings.PageStatus.CONFIGURE: + this.pageStatus_ = pageStatus; + return; + case settings.PageStatus.DONE: + if (settings.getCurrentRoute() == settings.routes.BRAVE_SYNC_SETUP) { + settings.navigateTo(settings.routes.PEOPLE); + } + return; + case settings.PageStatus.PASSPHRASE_FAILED: + if (this.pageStatus_ == this.pages_.CONFIGURE && this.syncPrefs && + this.syncPrefs.passphraseRequired) { + } + return; + } + + assertNotReached(); + }, + + /** + * @return {boolean} + * @private + */ + shouldShowSyncAccountControl_: function() { + return this.syncStatus !== undefined && + !!this.syncStatus.syncSystemEnabled; + }, + + /** + * @param {!CustomEvent} e The event passed from + * settings-sync-account-control. + * @private + */ + onSyncSetupDone_: function(e) { + if (e.detail) { + this.didAbort_ = false; + + this.syncPrefs.encryptAllData = true; + this.syncPrefs.setNewPassphrase = true; + this.syncPrefs.passphrase = this.passphrase_; + + if (this.syncPrefs.passphraseRequired) { + this.syncPrefs.setNewPassphrase = false; + } + this.browserProxy_.setSyncCode(this.passphrase_); + + this.browserProxy_.setSyncEncryption(this.syncPrefs) + .then(this.handlePageStatusChanged_.bind(this)); + } else { + this.setupCancelConfirmed_ = true; + } + settings.navigateTo(settings.routes.BRAVE_SYNC); + }, +}); + +})(); diff --git a/browser/resources/settings/settings_resources.grd b/browser/resources/settings/settings_resources.grd index 14cf2862c82c..ae4537f98a19 100644 --- a/browser/resources/settings/settings_resources.grd +++ b/browser/resources/settings/settings_resources.grd @@ -43,10 +43,12 @@ - - + + + + diff --git a/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc b/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc new file mode 100644 index 000000000000..b6ff93f1ffe1 --- /dev/null +++ b/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc @@ -0,0 +1,45 @@ +// TODO(darkdh): add deps +#include "brave/components/brave_sync/brave_sync_prefs.h" +#include "brave/components/brave_sync/crypto/crypto.h" + +#define BRAVE_REGISTER_MESSAGES \ + web_ui()->RegisterMessageCallback( \ + "SyncSetupSetSyncCode", \ + base::BindRepeating(&PeopleHandler::HandleSetSyncCode, \ + base::Unretained(this))); \ + web_ui()->RegisterMessageCallback( \ + "SyncPrefsDispatch", \ + base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, \ + base::Unretained(this))); + +#include "../../../../../../../chrome/browser/ui/webui/settings/people_handler.cc" +#undef BRAVE_REGISTER_MESSAGES + +namespace settings { + +void PeopleHandler::HandleGetSyncCode(const base::ListValue* args) { + AllowJavascript(); + + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + + std::string sync_code = + profile_->GetPrefs()->GetString(brave_sync::prefs::kSyncSeed); + if (sync_code.empty()) { + std::vector seed = brave_sync::crypto::GetSeed(); + sync_code = brave_sync::crypto::PassphraseFromBytes32(seed); + } + + ResolveJavascriptCallback(*callback_id, base::Value(sync_code)); +} + +void PeopleHandler::HandleSetSyncCode(const base::ListValue* args) { + CHECK_EQ(1U, args->GetSize()); + const base::Value* sync_code; + CHECK(args->Get(0, &sync_code)); + + profile_->GetPrefs()->SetString(brave_sync::prefs::kSyncSeed, + sync_code->GetString()); +} +} // namespace settings diff --git a/chromium_src/chrome/browser/ui/webui/settings/people_handler.h b/chromium_src/chrome/browser/ui/webui/settings/people_handler.h new file mode 100644 index 000000000000..e26d0344d345 --- /dev/null +++ b/chromium_src/chrome/browser/ui/webui/settings/people_handler.h @@ -0,0 +1,10 @@ + +#ifndef BRAVE_CHROMIUM_SRC_CHROME_BROWSER_UI_WEBUI_SETTINGS_PEOPLE_HANDLER_H_ +#define BRAVE_CHROMIUM_SRC_CHROME_BROWSER_UI_WEBUI_SETTINGS_PEOPLE_HANDLER_H_ +#define BRAVE_PEOPLE_HANDLER_H_ \ + void HandleGetSyncCode(const base::ListValue* args); \ + void HandleSetSyncCode(const base::ListValue* args); +#include "../../../../../../../chrome/browser/ui/webui/settings/people_handler.h" +#undef BRAVE_PEOPLE_HANDLER_H_ + +#endif // BRAVE_CHROMIUM_SRC_CHROME_BROWSER_UI_WEBUI_SETTINGS_PEOPLE_HANDLER_H_ diff --git a/patches/chrome-browser-resources-settings-people_page-sync_browser_proxy.js.patch b/patches/chrome-browser-resources-settings-people_page-sync_browser_proxy.js.patch new file mode 100644 index 000000000000..74d0f7418a40 --- /dev/null +++ b/patches/chrome-browser-resources-settings-people_page-sync_browser_proxy.js.patch @@ -0,0 +1,32 @@ +diff --git a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +index e9043c8a6a138d0f791c44a6c9018985eb5a6e02..fe874e3601125634f448a7ed65d3f6bb73353486 100644 +--- a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js ++++ b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +@@ -173,6 +173,10 @@ cr.define('settings', function() { + */ + getSyncStatus() {} + ++ getSyncCode() {} ++ ++ setSyncCode(syncCode) {} ++ + /** + * Gets a list of stored accounts. + * @return {!Promise>} +@@ -281,6 +285,16 @@ cr.define('settings', function() { + return cr.sendWithPromise('SyncSetupGetSyncStatus'); + } + ++ /** @override */ ++ getSyncCode() { ++ return cr.sendWithPromise('SyncSetupGetSyncCode'); ++ } ++ ++ /** @override */ ++ setSyncCode(syncCode) { ++ chrome.send('SyncSetupSetSyncCode', [syncCode]); ++ } ++ + /** @override */ + getStoredAccounts() { + return cr.sendWithPromise('SyncSetupGetStoredAccounts'); diff --git a/patches/chrome-browser-resources-settings-people_page-sync_controls.js.patch b/patches/chrome-browser-resources-settings-people_page-sync_controls.js.patch new file mode 100644 index 000000000000..5130b4f1aa8b --- /dev/null +++ b/patches/chrome-browser-resources-settings-people_page-sync_controls.js.patch @@ -0,0 +1,21 @@ +diff --git a/chrome/browser/resources/settings/people_page/sync_controls.js b/chrome/browser/resources/settings/people_page/sync_controls.js +index acccef1b831a6ae58b610c772366a1f531c2b23a..e6752f18b265646cb76b3f35ae0b483aee03d0f1 100644 +--- a/chrome/browser/resources/settings/people_page/sync_controls.js ++++ b/chrome/browser/resources/settings/people_page/sync_controls.js +@@ -76,7 +76,7 @@ Polymer({ + this.addWebUIListener( + 'sync-prefs-changed', this.handleSyncPrefsChanged_.bind(this)); + +- if (settings.getCurrentRoute() == settings.routes.SYNC_ADVANCED) { ++ if (settings.getCurrentRoute() == settings.routes.BRAVE_SYNC_SETUP) { + this.browserProxy_.didNavigateToSyncPage(); + } + }, +@@ -181,6 +181,7 @@ Polymer({ + * @private + */ + syncControlsHidden_: function() { ++ return false; + if (!this.syncStatus) { + // Show sync controls by default. + return false; diff --git a/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch b/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch new file mode 100644 index 000000000000..35084f59f0dd --- /dev/null +++ b/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch @@ -0,0 +1,42 @@ +diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc +index 6dc8e03ca5ac6e10a59708d75796fa99a24eada1..845e27f8d54912d026c6ab7b9143548943dabce7 100644 +--- a/chrome/browser/ui/webui/settings/people_handler.cc ++++ b/chrome/browser/ui/webui/settings/people_handler.cc +@@ -299,8 +299,8 @@ void PeopleHandler::RegisterMessages() { + base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( +- "SyncPrefsDispatch", +- base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, ++ "SyncSetupGetSyncCode", ++ base::BindRepeating(&PeopleHandler::HandleGetSyncCode, + base::Unretained(this))); + #if defined(OS_CHROMEOS) + web_ui()->RegisterMessageCallback( +@@ -337,6 +337,7 @@ void PeopleHandler::RegisterMessages() { + "SyncStartKeyRetrieval", + base::BindRepeating(&PeopleHandler::HandleStartKeyRetrieval, + base::Unretained(this))); ++ BRAVE_REGISTER_MESSAGES + } + + void PeopleHandler::OnJavascriptAllowed() { +@@ -896,8 +897,8 @@ std::unique_ptr PeopleHandler::GetSyncStatusDictionary() + sync_status->SetBoolean( + "firstSetupInProgress", + service && !disallowed_by_policy && service->IsSetupInProgress() && +- !service->GetUserSettings()->IsFirstSetupComplete() && +- identity_manager->HasPrimaryAccount()); ++ !service->GetUserSettings()->IsFirstSetupComplete()); ++ // identity_manager->HasPrimaryAccount()); + + const sync_ui_util::StatusLabels status_labels = + sync_ui_util::GetStatusLabels(profile_); +@@ -1045,6 +1046,7 @@ void PeopleHandler::MarkFirstSetupComplete() { + } + + bool PeopleHandler::IsProfileAuthNeededOrHasErrors() { ++ return false; + return !IdentityManagerFactory::GetForProfile(profile_) + ->HasPrimaryAccount() || + SigninErrorControllerFactory::GetForProfile(profile_)->HasError(); diff --git a/patches/chrome-browser-ui-webui-settings-people_handler.h.patch b/patches/chrome-browser-ui-webui-settings-people_handler.h.patch new file mode 100644 index 000000000000..d0fe4f86f337 --- /dev/null +++ b/patches/chrome-browser-ui-webui-settings-people_handler.h.patch @@ -0,0 +1,12 @@ +diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h +index 1573a3ce552a1e5abc4982d33aa1fad69e8faede..9d44c6440b9293a69dc8de648b4d8e007e4bc985 100644 +--- a/chrome/browser/ui/webui/settings/people_handler.h ++++ b/chrome/browser/ui/webui/settings/people_handler.h +@@ -167,6 +167,7 @@ class PeopleHandler : public SettingsPageUIHandler, + #endif + void HandleStartKeyRetrieval(const base::ListValue* args); + void HandleGetSyncStatus(const base::ListValue* args); ++ BRAVE_PEOPLE_HANDLER_H_ + + #if !defined(OS_CHROMEOS) + // Displays the GAIA login form. From 5948e48614b2d6d156ab80fa2d02b443338b8a83 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Tue, 31 Mar 2020 20:26:00 -0700 Subject: [PATCH 06/79] local server integration --- app/brave_main_delegate.cc | 2 +- .../brave_sync_page/brave_sync_control.js | 3 -- .../brave_sync_page/brave_sync_subpage.html | 4 +-- .../brave_sync_page/brave_sync_subpage.js | 3 -- .../ui/webui/settings/people_handler.cc | 19 +++++----- .../sync/driver/profile_sync_service.cc | 21 +++++++++++ ...-ui-webui-settings-people_handler.cc.patch | 24 ++++++------- ...-sync-driver-profile_sync_service.cc.patch | 36 +++++++++++++++++++ ...et-sync_server_connection_manager.cc.patch | 25 +++++++++++++ ...ync-engine_impl-sync_manager_impl.cc.patch | 13 +++++++ 10 files changed, 119 insertions(+), 31 deletions(-) create mode 100644 chromium_src/components/sync/driver/profile_sync_service.cc create mode 100644 patches/components-sync-driver-profile_sync_service.cc.patch create mode 100644 patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch create mode 100644 patches/components-sync-engine_impl-sync_manager_impl.cc.patch diff --git a/app/brave_main_delegate.cc b/app/brave_main_delegate.cc index 41ae221ac40c..ce9ed4a55b72 100644 --- a/app/brave_main_delegate.cc +++ b/app/brave_main_delegate.cc @@ -158,7 +158,7 @@ bool BraveMainDelegate::BasicStartupComplete(int* exit_code) { // Brave's sync protocol does not use the sync service url command_line.AppendSwitchASCII(switches::kSyncServiceURL, - "https://no-thanks.invalid"); + "http://localhost:8295/v2"); // Enabled features. std::unordered_set enabled_features = { diff --git a/browser/resources/settings/brave_sync_page/brave_sync_control.js b/browser/resources/settings/brave_sync_page/brave_sync_control.js index 473729d2c3bf..6a905d14d9a1 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_control.js +++ b/browser/resources/settings/brave_sync_page/brave_sync_control.js @@ -197,8 +197,6 @@ Polymer({ * @private */ computeShowSetupButtons_: function() { - console.error(this.syncStatus); - // return true; return !this.hideButtons && !!this.syncStatus.firstSetupInProgress; }, @@ -219,7 +217,6 @@ Polymer({ onSetupConfirm_: function() { if (!this.passphrase) { this.passphrase = this.$$('#enterSyncCode').value; - console.error(this.passphrase); } this.fire('sync-setup-done', true); }, diff --git a/browser/resources/settings/brave_sync_page/brave_sync_subpage.html b/browser/resources/settings/brave_sync_page/brave_sync_subpage.html index 36da6cfa3174..9c5600d1fcb0 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_subpage.html +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.html @@ -55,8 +55,8 @@

$i18n{sync}

- - + +
diff --git a/browser/resources/settings/brave_sync_page/brave_sync_subpage.js b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js index 07702bda28b8..0456641250e1 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_subpage.js +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js @@ -176,7 +176,6 @@ Polymer({ * @private */ handleSyncStatus_: function(syncStatus) { - console.error(syncStatus); this.syncStatus = syncStatus; }, @@ -218,7 +217,6 @@ Polymer({ /** @protected */ currentRouteChanged: function() { - console.error(settings.getCurrentRoute()); if (settings.getCurrentRoute() == settings.routes.BRAVE_SYNC_SETUP) { this.onNavigateToPage_(); return; @@ -342,7 +340,6 @@ Polymer({ * @private */ handlePageStatusChanged_: function(pageStatus) { - console.error(pageStatus); switch (pageStatus) { case settings.PageStatus.SPINNER: case settings.PageStatus.TIMEOUT: diff --git a/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc b/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc index b6ff93f1ffe1..8a3924866d0a 100644 --- a/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc @@ -2,16 +2,19 @@ #include "brave/components/brave_sync/brave_sync_prefs.h" #include "brave/components/brave_sync/crypto/crypto.h" -#define BRAVE_REGISTER_MESSAGES \ - web_ui()->RegisterMessageCallback( \ - "SyncSetupSetSyncCode", \ - base::BindRepeating(&PeopleHandler::HandleSetSyncCode, \ - base::Unretained(this))); \ - web_ui()->RegisterMessageCallback( \ - "SyncPrefsDispatch", \ - base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, \ +#define BRAVE_REGISTER_MESSAGES \ + web_ui()->RegisterMessageCallback( \ + "SyncSetupSetSyncCode", \ + base::BindRepeating(&PeopleHandler::HandleSetSyncCode, \ + base::Unretained(this))); \ + web_ui()->RegisterMessageCallback( \ + "SyncSetupGetSyncCode", \ + base::BindRepeating(&PeopleHandler::HandleGetSyncCode, \ base::Unretained(this))); +#define BRAVE_HANDLE_SHOW_SETUP_UI \ + profile_->GetPrefs()->SetBoolean(brave_sync::prefs::kSyncEnabled, true); + #include "../../../../../../../chrome/browser/ui/webui/settings/people_handler.cc" #undef BRAVE_REGISTER_MESSAGES diff --git a/chromium_src/components/sync/driver/profile_sync_service.cc b/chromium_src/components/sync/driver/profile_sync_service.cc new file mode 100644 index 000000000000..fc93c06dc9e7 --- /dev/null +++ b/chromium_src/components/sync/driver/profile_sync_service.cc @@ -0,0 +1,21 @@ +#include "brave/components/brave_sync/brave_sync_prefs.h" +#include "components/prefs/pref_service.h" + +namespace syncer { +const int64_t kBraveDefaultPollIntervalSeconds = 60; +} // namespace syncer + +#define BRAVE_SET_POLL_INTERVAL \ + sync_prefs_.SetPollInterval( \ + base::TimeDelta::FromSeconds(syncer::kBraveDefaultPollIntervalSeconds)); + +#define BRAVE_IS_SIGNED_IN \ + return sync_client_->GetPrefService()->GetBoolean( \ + brave_sync::prefs::kSyncEnabled); + +#define BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO \ + AccountInfo account_info; \ + account_info.account_id = CoreAccountId::FromString("dummy_account_id"); \ + return std::move(account_info); + +#include "../../../../../components/sync/driver/profile_sync_service.cc" diff --git a/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch b/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch index 35084f59f0dd..118014d36201 100644 --- a/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch +++ b/patches/chrome-browser-ui-webui-settings-people_handler.cc.patch @@ -1,18 +1,7 @@ diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc -index 6dc8e03ca5ac6e10a59708d75796fa99a24eada1..845e27f8d54912d026c6ab7b9143548943dabce7 100644 +index 6dc8e03ca5ac6e10a59708d75796fa99a24eada1..29393972bcac72094e938970da2f0df137319847 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc -@@ -299,8 +299,8 @@ void PeopleHandler::RegisterMessages() { - base::BindRepeating(&PeopleHandler::HandleGetSyncStatus, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( -- "SyncPrefsDispatch", -- base::BindRepeating(&PeopleHandler::HandleSyncPrefsDispatch, -+ "SyncSetupGetSyncCode", -+ base::BindRepeating(&PeopleHandler::HandleGetSyncCode, - base::Unretained(this))); - #if defined(OS_CHROMEOS) - web_ui()->RegisterMessageCallback( @@ -337,6 +337,7 @@ void PeopleHandler::RegisterMessages() { "SyncStartKeyRetrieval", base::BindRepeating(&PeopleHandler::HandleStartKeyRetrieval, @@ -21,14 +10,21 @@ index 6dc8e03ca5ac6e10a59708d75796fa99a24eada1..845e27f8d54912d026c6ab7b91435489 } void PeopleHandler::OnJavascriptAllowed() { -@@ -896,8 +897,8 @@ std::unique_ptr PeopleHandler::GetSyncStatusDictionary() +@@ -616,6 +617,7 @@ void PeopleHandler::HandleShowSetupUI(const base::ListValue* args) { + + syncer::SyncService* service = GetSyncService(); + ++ BRAVE_HANDLE_SHOW_SETUP_UI + if (service && !sync_blocker_) + sync_blocker_ = service->GetSetupInProgressHandle(); + +@@ -896,8 +898,7 @@ std::unique_ptr PeopleHandler::GetSyncStatusDictionary() sync_status->SetBoolean( "firstSetupInProgress", service && !disallowed_by_policy && service->IsSetupInProgress() && - !service->GetUserSettings()->IsFirstSetupComplete() && - identity_manager->HasPrimaryAccount()); + !service->GetUserSettings()->IsFirstSetupComplete()); -+ // identity_manager->HasPrimaryAccount()); const sync_ui_util::StatusLabels status_labels = sync_ui_util::GetStatusLabels(profile_); diff --git a/patches/components-sync-driver-profile_sync_service.cc.patch b/patches/components-sync-driver-profile_sync_service.cc.patch new file mode 100644 index 000000000000..be3d3063b682 --- /dev/null +++ b/patches/components-sync-driver-profile_sync_service.cc.patch @@ -0,0 +1,36 @@ +diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc +index f3956a3fcd7cbcfe74d81be242b2877075a9b189..01e951d44ea5bbda49a5fe5692991265fdc12470 100644 +--- a/components/sync/driver/profile_sync_service.cc ++++ b/components/sync/driver/profile_sync_service.cc +@@ -536,6 +536,7 @@ void ProfileSyncService::StartUpSlowEngineComponents() { + params.report_unrecoverable_error_function = + base::BindRepeating(ReportUnrecoverableError, channel_); + sync_prefs_.GetInvalidationVersions(¶ms.invalidation_versions); ++ BRAVE_SET_POLL_INTERVAL + params.poll_interval = sync_prefs_.GetPollInterval(); + if (params.poll_interval.is_zero()) { + params.poll_interval = +@@ -1214,6 +1215,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { + } + + bool ProfileSyncService::IsSignedIn() const { ++ BRAVE_IS_SIGNED_IN + // Sync is logged in if there is a non-empty account id. + return !GetAuthenticatedAccountInfo().account_id.empty(); + } +@@ -1726,6 +1728,7 @@ void ProfileSyncService::GetAllNodesForDebugging( + } + + CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { ++ BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!auth_manager_) { + // Some crashes on iOS (crbug.com/962384) suggest that ProfileSyncService +@@ -1738,6 +1741,7 @@ CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { + } + + bool ProfileSyncService::IsAuthenticatedAccountPrimary() const { ++ return true; + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!auth_manager_) { + // This is a precautionary check to be consistent with the check in diff --git a/patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch b/patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch new file mode 100644 index 000000000000..2e4c88fc03a0 --- /dev/null +++ b/patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch @@ -0,0 +1,25 @@ +diff --git a/components/sync/engine_impl/net/sync_server_connection_manager.cc b/components/sync/engine_impl/net/sync_server_connection_manager.cc +index c210064c1766a0dec727b58e93140b2e28406f4b..a6438b648dc7487e43039f3fa1490703f9795e10 100644 +--- a/components/sync/engine_impl/net/sync_server_connection_manager.cc ++++ b/components/sync/engine_impl/net/sync_server_connection_manager.cc +@@ -225,13 +225,13 @@ bool SyncServerConnectionManager::PostBufferToPath( + PostBufferParams* params, + const std::string& path, + const std::string& access_token) { +- if (access_token.empty()) { +- params->response.server_status = HttpResponse::SYNC_AUTH_ERROR; +- // Print a log to distinguish this "known failure" from others. +- DVLOG(1) << "ServerConnectionManager forcing SYNC_AUTH_ERROR due to missing" +- " access token"; +- return false; +- } ++ // if (access_token.empty()) { ++ // params->response.server_status = HttpResponse::SYNC_AUTH_ERROR; ++ // // Print a log to distinguish this "known failure" from others. ++ // DVLOG(1) << "ServerConnectionManager forcing SYNC_AUTH_ERROR due to missing" ++ // " access token"; ++ // return false; ++ // } + + if (cancelation_signal_->IsSignalled()) { + params->response.server_status = HttpResponse::CONNECTION_UNAVAILABLE; diff --git a/patches/components-sync-engine_impl-sync_manager_impl.cc.patch b/patches/components-sync-engine_impl-sync_manager_impl.cc.patch new file mode 100644 index 000000000000..a1340611ac3d --- /dev/null +++ b/patches/components-sync-engine_impl-sync_manager_impl.cc.patch @@ -0,0 +1,13 @@ +diff --git a/components/sync/engine_impl/sync_manager_impl.cc b/components/sync/engine_impl/sync_manager_impl.cc +index 9b153faac8199895d243a0db28fe382dba869f70..b7901f085b5f93bf5e841c86e96e8652eae310b3 100644 +--- a/components/sync/engine_impl/sync_manager_impl.cc ++++ b/components/sync/engine_impl/sync_manager_impl.cc +@@ -388,7 +388,7 @@ void SyncManagerImpl::Init(InitArgs* args) { + args->poll_interval); + scheduler_ = args->engine_components_factory->BuildScheduler( + name_, cycle_context_.get(), args->cancelation_signal, +- args->enable_local_sync_backend); ++ true); + + scheduler_->Start(SyncScheduler::CONFIGURATION_MODE, base::Time()); + From 1bc6a6ebfa9e1468e16d857f90359aad1cda46fb Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Mon, 6 Apr 2020 13:41:57 -0700 Subject: [PATCH 07/79] Add brave sync access token fetcher and consumer --- components/brave_sync/BUILD.gn | 6 + .../brave_sync/access_token_consumer.cc | 21 ++ components/brave_sync/access_token_consumer.h | 43 +++ components/brave_sync/access_token_fetcher.cc | 21 ++ components/brave_sync/access_token_fetcher.h | 36 ++ .../brave_sync/access_token_fetcher_impl.cc | 309 ++++++++++++++++++ .../brave_sync/access_token_fetcher_impl.h | 84 +++++ 7 files changed, 520 insertions(+) create mode 100644 components/brave_sync/access_token_consumer.cc create mode 100644 components/brave_sync/access_token_consumer.h create mode 100644 components/brave_sync/access_token_fetcher.cc create mode 100644 components/brave_sync/access_token_fetcher.h create mode 100644 components/brave_sync/access_token_fetcher_impl.cc create mode 100644 components/brave_sync/access_token_fetcher_impl.h diff --git a/components/brave_sync/BUILD.gn b/components/brave_sync/BUILD.gn index 72c837f50fa2..0f8cbd4beee8 100644 --- a/components/brave_sync/BUILD.gn +++ b/components/brave_sync/BUILD.gn @@ -126,6 +126,12 @@ source_set("public") { source_set("core") { sources = [ + "access_token_consumer.cc", + "access_token_consumer.h", + "access_token_fetcher.cc", + "access_token_fetcher.h", + "access_token_fetcher_impl.cc", + "access_token_fetcher_impl.h", "bookmark_order_util.cc", "bookmark_order_util.h", "brave_sync_service.cc", diff --git a/components/brave_sync/access_token_consumer.cc b/components/brave_sync/access_token_consumer.cc new file mode 100644 index 000000000000..f808efc0827e --- /dev/null +++ b/components/brave_sync/access_token_consumer.cc @@ -0,0 +1,21 @@ +#include "brave/components/brave_sync/access_token_consumer.h" + +namespace brave_sync { + +AccessTokenConsumer::TokenResponse::TokenResponse( + const std::string& access_token, + const base::Time& expiration_time, + const std::string& id_token) + : access_token(access_token), + expiration_time(expiration_time), + id_token(id_token) {} + +AccessTokenConsumer::~AccessTokenConsumer() {} + +void AccessTokenConsumer::OnGetTokenSuccess( + const TokenResponse& token_response) {} + +void AccessTokenConsumer::OnGetTokenFailure( + const std::string& error) {} + +} // namespace brave_sync diff --git a/components/brave_sync/access_token_consumer.h b/components/brave_sync/access_token_consumer.h new file mode 100644 index 000000000000..7e77ecf1b68a --- /dev/null +++ b/components/brave_sync/access_token_consumer.h @@ -0,0 +1,43 @@ +#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_CONSUMER_H_ +#define BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_CONSUMER_H_ + +#include "base/time/time.h" + +namespace brave_sync { + +class AccessTokenConsumer { + public: + // Structure representing information contained in access token. + struct TokenResponse { + TokenResponse() = default; + TokenResponse(const std::string& access_token, + const base::Time& expiration_time, + const std::string& id_token); + + // access token. + std::string access_token; + + // The date until which the |access_token| can be used. + // This value has a built-in safety margin, so it can be used as-is. + base::Time expiration_time; + + // Contains extra information regarding the user's currently registered + // services. + std::string id_token; + }; + + AccessTokenConsumer() = default; + virtual ~AccessTokenConsumer(); + + // Success callback. + virtual void OnGetTokenSuccess(const TokenResponse& token_response); + + // Failure callback. + // TODO(darkdh): define error messages + virtual void OnGetTokenFailure(const std::string& error); + + DISALLOW_COPY_AND_ASSIGN(AccessTokenConsumer); +}; + +} // namespace brave_sync +#endif // BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_CONSUMER_H_ diff --git a/components/brave_sync/access_token_fetcher.cc b/components/brave_sync/access_token_fetcher.cc new file mode 100644 index 000000000000..704ff4dea8ae --- /dev/null +++ b/components/brave_sync/access_token_fetcher.cc @@ -0,0 +1,21 @@ +#include "brave/components/brave_sync/access_token_fetcher.h" + +namespace brave_sync { + +AccessTokenFetcher::AccessTokenFetcher( + AccessTokenConsumer* consumer) + : consumer_(consumer) {} + +AccessTokenFetcher::~AccessTokenFetcher() {} + +void AccessTokenFetcher::FireOnGetTokenSuccess( + const AccessTokenConsumer::TokenResponse& token_response) { + consumer_->OnGetTokenSuccess(token_response); +} + +void AccessTokenFetcher::FireOnGetTokenFailure( + const std::string& error) { + consumer_->OnGetTokenFailure(error); +} + +} // namespace brave_sync diff --git a/components/brave_sync/access_token_fetcher.h b/components/brave_sync/access_token_fetcher.h new file mode 100644 index 000000000000..f6d8b8706489 --- /dev/null +++ b/components/brave_sync/access_token_fetcher.h @@ -0,0 +1,36 @@ +#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_FETCHER_H_ +#define BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_FETCHER_H_ + +#include "base/macros.h" +#include "base/time/time.h" +#include "brave/components/brave_sync/access_token_consumer.h" + +namespace brave_sync { + +class AccessTokenFetcher { + public: + explicit AccessTokenFetcher(AccessTokenConsumer* consumer); + virtual ~AccessTokenFetcher(); + + virtual void Start(const std::string& client_id, + const std::string& client_secret) = 0; + + // Cancels the current request and informs the consumer. + virtual void CancelRequest() = 0; + + protected: + // Fires |OnGetTokenSuccess| on |consumer_|. + void FireOnGetTokenSuccess( + const AccessTokenConsumer::TokenResponse& token_response); + + // Fires |OnGetTokenFailure| on |consumer_|. + void FireOnGetTokenFailure(const std::string& error); + private: + + AccessTokenConsumer* const consumer_; + + DISALLOW_COPY_AND_ASSIGN(AccessTokenFetcher); +}; + +} // namespace brave_sync +#endif // BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_FETCHER_H_ diff --git a/components/brave_sync/access_token_fetcher_impl.cc b/components/brave_sync/access_token_fetcher_impl.cc new file mode 100644 index 000000000000..69cd784f54fc --- /dev/null +++ b/components/brave_sync/access_token_fetcher_impl.cc @@ -0,0 +1,309 @@ +#include "brave/components/brave_sync/access_token_fetcher_impl.h" + +#include +#include +#include + +#include "base/bind.h" +#include "base/json/json_reader.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/time/time.h" +#include "base/values.h" +#include "net/base/escape.h" +#include "net/base/load_flags.h" +#include "net/base/net_errors.h" +#include "net/http/http_status_code.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "net/url_request/url_request_status.h" +#include "services/network/public/cpp/resource_request.h" +#include "services/network/public/cpp/resource_response.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/simple_url_loader.h" + +namespace brave_sync { + +namespace { +constexpr char kGetAccessTokenBodyFormat[] = + "client_id=%s&" + "client_secret=%s&" + "refresh_token=%s"; + +constexpr char kAccessTokenKey[] = "access_token"; +constexpr char kExpiresInKey[] = "expires_in"; +constexpr char kIdTokenKey[] = "id_token"; +constexpr char kErrorKey[] = "error"; + +static std::string CreateAuthError(int net_error) { + CHECK_NE(net_error, net::OK); + DLOG(WARNING) << "Server error: errno " + << net_error; + return net::ErrorToString(net_error); +} + +static std::unique_ptr CreateURLLoader( + const GURL& url, + const std::string& body) { + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("sync_access_token_fetcher", R"( + semantics { + sender: "Brave Sync Access Token Fetcher" + description: + "This request is used by the ProfileSyncService to fetch " + "access token for a sync chain" + trigger: + "This request can be triggered at any moment when + "ProfileSyncService requests an access token" + data: + "Brave Sync client id and secrect and refresh token" + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: + "This feature cannot be disabled in settings" + chrome_policy { + SigninAllowed { + policy_options {mode: MANDATORY} + SigninAllowed: false + } + } + })"); + + auto resource_request = std::make_unique(); + resource_request->url = url; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; + if (!body.empty()) + resource_request->method = "POST"; + + auto url_loader = network::SimpleURLLoader::Create( + std::move(resource_request), traffic_annotation); + + if (!body.empty()) + url_loader->AttachStringForUpload(body, + "application/x-www-form-urlencoded"); + + // We want to receive the body even on error, as it may contain the reason for + // failure. + url_loader->SetAllowHttpErrorResults(true); + + // Fetchers are sometimes cancelled because a network change was detected, + // especially at startup and after sign-in on ChromeOS. Retrying once should + // be enough in those cases; let the fetcher retry up to 3 times just in case. + // http://crbug.com/163710 + url_loader->SetRetryOptions( + 3, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); + + return url_loader; +} + +std::unique_ptr ParseGetAccessTokenResponse( + std::unique_ptr data) { + if (!data) + return nullptr; + + std::unique_ptr value = base::JSONReader::ReadDeprecated(*data); + if (!value.get() || value->type() != base::Value::Type::DICTIONARY) + value.reset(); + + return std::unique_ptr( + static_cast(value.release())); +} + +} // namespace + +AccessTokenFetcherImpl::AccessTokenFetcherImpl( + AccessTokenConsumer* consumer, + scoped_refptr url_loader_factory, + const std::string& refresh_token) + : AccessTokenFetcher(consumer), + url_loader_factory_(url_loader_factory), + refresh_token_(refresh_token), + state_(INITIAL) {} + +AccessTokenFetcherImpl::~AccessTokenFetcherImpl() {} + +void AccessTokenFetcherImpl::CancelRequest() { + url_loader_.reset(); +} + +void AccessTokenFetcherImpl::Start( + const std::string& client_id, + const std::string& client_secret) { + client_id_ = client_id; + client_secret_ = client_secret; + StartGetAccessToken(); +} + +void AccessTokenFetcherImpl::StartGetAccessToken() { + CHECK_EQ(INITIAL, state_); + state_ = GET_ACCESS_TOKEN_STARTED; + url_loader_ = + CreateURLLoader(MakeGetAccessTokenUrl(), + MakeGetAccessTokenBody(client_id_, client_secret_, + refresh_token_)); + // It's safe to use Unretained below as the |url_loader_| is owned by |this|. + url_loader_->DownloadToString( + url_loader_factory_.get(), + base::BindOnce(&AccessTokenFetcherImpl::OnURLLoadComplete, + base::Unretained(this)), + 1024 * 1024); +} + +void AccessTokenFetcherImpl::EndGetAccessToken( + std::unique_ptr response_body) { + CHECK_EQ(GET_ACCESS_TOKEN_STARTED, state_); + state_ = GET_ACCESS_TOKEN_DONE; + + bool net_failure = false; + int histogram_value; + if (url_loader_->NetError() == net::OK && url_loader_->ResponseInfo() && + url_loader_->ResponseInfo()->headers) { + histogram_value = url_loader_->ResponseInfo()->headers->response_code(); + } else { + histogram_value = url_loader_->NetError(); + net_failure = true; + } + if (net_failure) { + OnGetTokenFailure(CreateAuthError(histogram_value)); + return; + } + + int response_code = url_loader_->ResponseInfo()->headers->response_code(); + switch (response_code) { + case net::HTTP_OK: + break; + case net::HTTP_PROXY_AUTHENTICATION_REQUIRED: + NOTREACHED() << "HTTP 407 should be treated as a network error."; + // If this ever happens in production, we treat it as a temporary error as + // it is similar to a network error. + OnGetTokenFailure(net::ErrorToString(response_code)); + return; + case net::HTTP_FORBIDDEN: + // HTTP_FORBIDDEN (403) is treated as temporary error, because it may be + // '403 Rate Limit Exeeded.' + OnGetTokenFailure(net::ErrorToString(response_code)); + return; + case net::HTTP_BAD_REQUEST: { + // HTTP_BAD_REQUEST (400) usually contains error as per + // http://tools.ietf.org/html/rfc6749#section-5.2. + std::string gaia_error; + if (!ParseGetAccessTokenFailureResponse(std::move(response_body), + &gaia_error)) { + OnGetTokenFailure(net::ErrorToString(response_code)); + return; + } + + // ErrorCodesForHistogram access_error( + // ErrorToHistogramValue(gaia_error)); + // UMA_HISTOGRAM_ENUMERATION("Gaia.BadRequestTypeForAccessToken", + // access_error, + // OAUTH2_ACCESS_ERROR_COUNT); + + // OnGetTokenFailure( + // access_error == OAUTH2_ACCESS_ERROR_INVALID_GRANT + // ? GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( + // GoogleServiceAuthError::InvalidGaiaCredentialsReason:: + // CREDENTIALS_REJECTED_BY_SERVER) + // : GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR)); + return; + } + default: { + if (response_code >= net::HTTP_INTERNAL_SERVER_ERROR) { + // 5xx is always treated as transient. + OnGetTokenFailure(net::ErrorToString(response_code)); + } else { + // The other errors are treated as permanent error. + DLOG(ERROR) << "Unexpected persistent error: http_status=" + << response_code; + OnGetTokenFailure(net::ErrorToString(response_code)); + } + return; + } + } + + // The request was successfully fetched and it returned OK. + // Parse out the access token and the expiration time. + std::string access_token; + int expires_in; + std::string id_token; + if (!ParseGetAccessTokenSuccessResponse( + std::move(response_body), &access_token, &expires_in, &id_token)) { + DLOG(WARNING) << "Response doesn't match expected format"; + OnGetTokenFailure("Service Unavailable"); + return; + } + // The token will expire in |expires_in| seconds. Take a 10% error margin to + // prevent reusing a token too close to its expiration date. + OnGetTokenSuccess(AccessTokenConsumer::TokenResponse( + access_token, + base::Time::Now() + base::TimeDelta::FromSeconds(9 * expires_in / 10), + id_token)); +} + +void AccessTokenFetcherImpl::OnGetTokenSuccess( + const AccessTokenConsumer::TokenResponse& token_response) { + FireOnGetTokenSuccess(token_response); +} + +void AccessTokenFetcherImpl::OnGetTokenFailure( + const std::string& error) { + state_ = ERROR_STATE; + FireOnGetTokenFailure(error); +} + +void AccessTokenFetcherImpl::OnURLLoadComplete( + std::unique_ptr response_body) { + CHECK(state_ == GET_ACCESS_TOKEN_STARTED); + EndGetAccessToken(std::move(response_body)); +} + +// static +GURL AccessTokenFetcherImpl::MakeGetAccessTokenUrl() { + return GURL("http://localhost:8295/v2/auth"); +} + +// static +std::string AccessTokenFetcherImpl::MakeGetAccessTokenBody( + const std::string& client_id, + const std::string& client_secret, + const std::string& refresh_token) { + std::string enc_client_id = net::EscapeUrlEncodedData(client_id, true); + std::string enc_client_secret = + net::EscapeUrlEncodedData(client_secret, true); + std::string enc_refresh_token = + net::EscapeUrlEncodedData(refresh_token, true); + return base::StringPrintf(kGetAccessTokenBodyFormat, + enc_client_id.c_str(), + enc_client_secret.c_str(), + enc_refresh_token.c_str()); +} + +// static +bool AccessTokenFetcherImpl::ParseGetAccessTokenSuccessResponse( + std::unique_ptr response_body, + std::string* access_token, + int* expires_in, + std::string* id_token) { + CHECK(access_token); + std::unique_ptr value = + ParseGetAccessTokenResponse(std::move(response_body)); + if (!value) + return false; + // ID token field is optional. + value->GetString(kIdTokenKey, id_token); + return value->GetString(kAccessTokenKey, access_token) && + value->GetInteger(kExpiresInKey, expires_in); +} + +// static +bool AccessTokenFetcherImpl::ParseGetAccessTokenFailureResponse( + std::unique_ptr response_body, + std::string* error) { + CHECK(error); + std::unique_ptr value = + ParseGetAccessTokenResponse(std::move(response_body)); + return value ? value->GetString(kErrorKey, error) : false; +} + +} // namespace brave_sync diff --git a/components/brave_sync/access_token_fetcher_impl.h b/components/brave_sync/access_token_fetcher_impl.h new file mode 100644 index 000000000000..2bdcf54111ce --- /dev/null +++ b/components/brave_sync/access_token_fetcher_impl.h @@ -0,0 +1,84 @@ +#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_FETCHER_IMPL_H_ +#define BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_FETCHER_IMPL_H_ + +#include +#include +#include + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "brave/components/brave_sync/access_token_fetcher.h" +#include "brave/components/brave_sync/access_token_consumer.h" +#include "url/gurl.h" + +namespace network { +class SimpleURLLoader; +class SharedURLLoaderFactory; +} + +namespace brave_sync { + +class AccessTokenFetcherImpl : public AccessTokenFetcher { + public: + AccessTokenFetcherImpl( + AccessTokenConsumer* consumer, + scoped_refptr url_loader_factory, + const std::string& refresh_token); + ~AccessTokenFetcherImpl() override; + + // Implementation of AccessTokenFetcher + void Start(const std::string& client_id, + const std::string& client_secret) override; + + void CancelRequest() override; + + private: + enum State { + INITIAL, + GET_ACCESS_TOKEN_STARTED, + GET_ACCESS_TOKEN_DONE, + ERROR_STATE, + }; + + void OnURLLoadComplete(std::unique_ptr response_body); + + // Helper methods for the flow. + void StartGetAccessToken(); + void EndGetAccessToken(std::unique_ptr response_body); + + // Helper mehtods for reporting back results. + void OnGetTokenSuccess( + const AccessTokenConsumer::TokenResponse& token_response); + void OnGetTokenFailure(const std::string& error); + + // Other helpers. + static GURL MakeGetAccessTokenUrl(); + static std::string MakeGetAccessTokenBody( + const std::string& client_id, + const std::string& client_secret, + const std::string& refresh_token); + + static bool ParseGetAccessTokenSuccessResponse( + std::unique_ptr response_body, + std::string* access_token, + int* expires_in, + std::string* id_token); + + static bool ParseGetAccessTokenFailureResponse( + std::unique_ptr response_body, + std::string* error); + + // State that is set during construction. + scoped_refptr url_loader_factory_; + const std::string refresh_token_; + State state_; + + // While a fetch is in progress. + std::unique_ptr url_loader_; + std::string client_id_; + std::string client_secret_; + + DISALLOW_COPY_AND_ASSIGN(AccessTokenFetcherImpl); +}; +} // namespace brave_sync +#endif // BRAVE_COMPONENTS_BRAVE_SYNC_ACCESS_TOKEN_FETCHER_IMPL_H_ From a681e801dae2622c338c270cfc8382e789f403f5 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Tue, 7 Apr 2020 13:04:00 -0700 Subject: [PATCH 08/79] Integrate brave access token fetcher with SyncAuthManager --- .../sync/driver/profile_sync_service.cc | 7 +++++ .../sync/driver/sync_auth_manager.cc | 28 +++++++++++++++++++ .../sync/driver/sync_auth_manager.h | 18 ++++++++++++ ...-sync-driver-profile_sync_service.cc.patch | 19 +++++++++---- ...nts-sync-driver-sync_auth_manager.cc.patch | 12 ++++++++ ...ents-sync-driver-sync_auth_manager.h.patch | 22 +++++++++++++++ 6 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 chromium_src/components/sync/driver/sync_auth_manager.cc create mode 100644 chromium_src/components/sync/driver/sync_auth_manager.h create mode 100644 patches/components-sync-driver-sync_auth_manager.cc.patch create mode 100644 patches/components-sync-driver-sync_auth_manager.h.patch diff --git a/chromium_src/components/sync/driver/profile_sync_service.cc b/chromium_src/components/sync/driver/profile_sync_service.cc index fc93c06dc9e7..3edca879e2ab 100644 --- a/chromium_src/components/sync/driver/profile_sync_service.cc +++ b/chromium_src/components/sync/driver/profile_sync_service.cc @@ -18,4 +18,11 @@ const int64_t kBraveDefaultPollIntervalSeconds = 60; account_info.account_id = CoreAccountId::FromString("dummy_account_id"); \ return std::move(account_info); +#define BRAVE_PROFILE_SYNC_SERVICE \ + auth_manager_->CreateAccessTokenFetcher(url_loader_factory_); + #include "../../../../../components/sync/driver/profile_sync_service.cc" +#undef BRAVE_SET_POLL_INTERVAL +#undef BRAVE_IS_SIGNED_IN +#undef BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO +#undef BRAVE_PROFILE_SYNC_SERVICE diff --git a/chromium_src/components/sync/driver/sync_auth_manager.cc b/chromium_src/components/sync/driver/sync_auth_manager.cc new file mode 100644 index 000000000000..4cbaec4b6f6d --- /dev/null +++ b/chromium_src/components/sync/driver/sync_auth_manager.cc @@ -0,0 +1,28 @@ +#include "brave/chromium_src/components/sync/driver/sync_auth_manager.h" + +#define BRAVE_REQUEST_ACCESS_TOKEN \ + access_token_fetcher_->Start("ID", "SECRECT"); +#include "../../../../../components/sync/driver/sync_auth_manager.cc" +#undef BRAVE_REQUEST_ACCESS_TOKEN + +namespace syncer { + +void SyncAuthManager::CreateAccessTokenFetcher( + scoped_refptr url_loader_factory) { + access_token_fetcher_ = std::make_unique( + this, url_loader_factory, ""); +} +void SyncAuthManager::OnGetTokenSuccess( + const brave_sync::AccessTokenConsumer::TokenResponse& token_response) { + access_token_ = token_response.access_token; + VLOG(1) << "Got Token: " << access_token_; + SetLastAuthError(GoogleServiceAuthError::AuthErrorNone()); +} +void SyncAuthManager::OnGetTokenFailure(const std::string& error) { + LOG(ERROR) << __func__ << ": " << error; + // TODO(darkdh): SetLastAuthError + request_access_token_backoff_.InformOfRequest(false); + ScheduleAccessTokenRequest(); +} + +} // namespace syncer diff --git a/chromium_src/components/sync/driver/sync_auth_manager.h b/chromium_src/components/sync/driver/sync_auth_manager.h new file mode 100644 index 000000000000..efd71d95727d --- /dev/null +++ b/chromium_src/components/sync/driver/sync_auth_manager.h @@ -0,0 +1,18 @@ +#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_ +#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_ +#include "brave/components/brave_sync/access_token_consumer.h" +#include "brave/components/brave_sync/access_token_fetcher_impl.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#define BRAVE_SYNC_AUTH_MANAGER_H_ \ + void CreateAccessTokenFetcher( \ + scoped_refptr url_loader_factory); \ + void OnGetTokenSuccess( \ + const brave_sync::AccessTokenConsumer::TokenResponse& token_response) \ + override; \ + void OnGetTokenFailure(const std::string& error) override; \ + \ + private: \ + std::unique_ptr access_token_fetcher_; +#include "../../../../../components/sync/driver/sync_auth_manager.h" +#undef BRAVE_SYNC_AUTH_MANAGER_H_ +#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_ diff --git a/patches/components-sync-driver-profile_sync_service.cc.patch b/patches/components-sync-driver-profile_sync_service.cc.patch index be3d3063b682..d97c7a5e7614 100644 --- a/patches/components-sync-driver-profile_sync_service.cc.patch +++ b/patches/components-sync-driver-profile_sync_service.cc.patch @@ -1,8 +1,17 @@ diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc -index f3956a3fcd7cbcfe74d81be242b2877075a9b189..01e951d44ea5bbda49a5fe5692991265fdc12470 100644 +index f3956a3fcd7cbcfe74d81be242b2877075a9b189..5a239e458c61e8ee095484ebc97f064361cbe271 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc -@@ -536,6 +536,7 @@ void ProfileSyncService::StartUpSlowEngineComponents() { +@@ -193,6 +193,8 @@ ProfileSyncService::ProfileSyncService(InitParams init_params) + DCHECK(sync_client_); + DCHECK(IsLocalSyncEnabled() || identity_manager_ != nullptr); + ++ BRAVE_PROFILE_SYNC_SERVICE ++ + // If Sync is disabled via command line flag, then ProfileSyncService + // shouldn't be instantiated. + DCHECK(switches::IsSyncAllowedByFlag()); +@@ -536,6 +538,7 @@ void ProfileSyncService::StartUpSlowEngineComponents() { params.report_unrecoverable_error_function = base::BindRepeating(ReportUnrecoverableError, channel_); sync_prefs_.GetInvalidationVersions(¶ms.invalidation_versions); @@ -10,7 +19,7 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..01e951d44ea5bbda49a5fe5692991265 params.poll_interval = sync_prefs_.GetPollInterval(); if (params.poll_interval.is_zero()) { params.poll_interval = -@@ -1214,6 +1215,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { +@@ -1214,6 +1217,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { } bool ProfileSyncService::IsSignedIn() const { @@ -18,7 +27,7 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..01e951d44ea5bbda49a5fe5692991265 // Sync is logged in if there is a non-empty account id. return !GetAuthenticatedAccountInfo().account_id.empty(); } -@@ -1726,6 +1728,7 @@ void ProfileSyncService::GetAllNodesForDebugging( +@@ -1726,6 +1730,7 @@ void ProfileSyncService::GetAllNodesForDebugging( } CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { @@ -26,7 +35,7 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..01e951d44ea5bbda49a5fe5692991265 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!auth_manager_) { // Some crashes on iOS (crbug.com/962384) suggest that ProfileSyncService -@@ -1738,6 +1741,7 @@ CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { +@@ -1738,6 +1743,7 @@ CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { } bool ProfileSyncService::IsAuthenticatedAccountPrimary() const { diff --git a/patches/components-sync-driver-sync_auth_manager.cc.patch b/patches/components-sync-driver-sync_auth_manager.cc.patch new file mode 100644 index 000000000000..9fd3ca48002e --- /dev/null +++ b/patches/components-sync-driver-sync_auth_manager.cc.patch @@ -0,0 +1,12 @@ +diff --git a/components/sync/driver/sync_auth_manager.cc b/components/sync/driver/sync_auth_manager.cc +index 3287a32ed1ca6ed5aada26928592ad278f8046a6..5295f89e1ca16b63df3e67ba58d8195b5f0a10c2 100644 +--- a/components/sync/driver/sync_auth_manager.cc ++++ b/components/sync/driver/sync_auth_manager.cc +@@ -481,6 +481,7 @@ void SyncAuthManager::RequestAccessToken() { + // Finally, kick off a new access token fetch. + partial_token_status_.token_request_time = base::Time::Now(); + partial_token_status_.token_response_time = base::Time(); ++ BRAVE_REQUEST_ACCESS_TOKEN + ongoing_access_token_fetch_ = + identity_manager_->CreateAccessTokenFetcherForAccount( + sync_account_.account_info.account_id, kSyncOAuthConsumerName, diff --git a/patches/components-sync-driver-sync_auth_manager.h.patch b/patches/components-sync-driver-sync_auth_manager.h.patch new file mode 100644 index 000000000000..7815c4e82bd6 --- /dev/null +++ b/patches/components-sync-driver-sync_auth_manager.h.patch @@ -0,0 +1,22 @@ +diff --git a/components/sync/driver/sync_auth_manager.h b/components/sync/driver/sync_auth_manager.h +index 26598da09e0dfbac87c490b2bad104a931a75d95..4a28ab0adadbca33f97b7a9a7e6c2f260cac0b5c 100644 +--- a/components/sync/driver/sync_auth_manager.h ++++ b/components/sync/driver/sync_auth_manager.h +@@ -34,7 +34,8 @@ struct SyncCredentials; + // SyncAuthManager tracks the account to be used for Sync and its authentication + // state. Note that this account may or may not be the primary account (as per + // IdentityManager::GetPrimaryAccountInfo() etc). +-class SyncAuthManager : public signin::IdentityManager::Observer { ++class SyncAuthManager : public signin::IdentityManager::Observer, ++ public brave_sync::AccessTokenConsumer { + public: + // Called when the existence of an authenticated account changes. It's + // guaranteed that this is only called for going from "no account" to "have +@@ -120,6 +121,7 @@ class SyncAuthManager : public signin::IdentityManager::Observer { + bool IsRetryingAccessTokenFetchForTest() const; + void ResetRequestAccessTokenBackoffForTest(); + ++ BRAVE_SYNC_AUTH_MANAGER_H_ + private: + SyncAccountInfo DetermineAccountToUse() const; + From 93f957675106cd40a21ddfbfc4e9abb4067308cf Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Tue, 7 Apr 2020 16:44:27 -0700 Subject: [PATCH 09/79] Generate token request from brave sync seed remove base64 encode Fetch timestamp from server missing declaration --- .../sync/driver/profile_sync_service.cc | 18 +++- .../sync/driver/sync_auth_manager.cc | 82 ++++++++++++++++--- .../sync/driver/sync_auth_manager.h | 8 ++ .../brave_sync/access_token_consumer.cc | 4 + components/brave_sync/access_token_consumer.h | 4 + components/brave_sync/access_token_fetcher.cc | 8 ++ components/brave_sync/access_token_fetcher.h | 8 +- .../brave_sync/access_token_fetcher_impl.cc | 52 +++++++++++- .../brave_sync/access_token_fetcher_impl.h | 9 +- ...-sync-driver-profile_sync_service.cc.patch | 24 +++++- 10 files changed, 197 insertions(+), 20 deletions(-) diff --git a/chromium_src/components/sync/driver/profile_sync_service.cc b/chromium_src/components/sync/driver/profile_sync_service.cc index 3edca879e2ab..d8d7ac256daa 100644 --- a/chromium_src/components/sync/driver/profile_sync_service.cc +++ b/chromium_src/components/sync/driver/profile_sync_service.cc @@ -18,11 +18,25 @@ const int64_t kBraveDefaultPollIntervalSeconds = 60; account_info.account_id = CoreAccountId::FromString("dummy_account_id"); \ return std::move(account_info); -#define BRAVE_PROFILE_SYNC_SERVICE \ - auth_manager_->CreateAccessTokenFetcher(url_loader_factory_); +#define BRAVE_PROFILE_SYNC_SERVICE \ + auth_manager_->CreateAccessTokenFetcher( \ + url_loader_factory_); + +#define BRAVE_START_UP_SLOW_ENGINE_COMPONENTS \ + auth_manager_->DeriveSigningKeys( \ + sync_client_->GetPrefService()->GetString( \ + brave_sync::prefs::kSyncSeed)); + +#define BRAVE_ON_FIRST_SETUP_COMPLETE_PREF_CHANGE \ + if (is_first_setup_complete) \ + auth_manager_->DeriveSigningKeys( \ + sync_client_->GetPrefService()->GetString( \ + brave_sync::prefs::kSyncSeed)); #include "../../../../../components/sync/driver/profile_sync_service.cc" #undef BRAVE_SET_POLL_INTERVAL #undef BRAVE_IS_SIGNED_IN #undef BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO #undef BRAVE_PROFILE_SYNC_SERVICE +#undef BRAVE_START_UP_SLOW_ENGINE_COMPONENTS +#undef BRAVE_ON_FIRST_SETUP_COMPLETE_PREF_CHANGE diff --git a/chromium_src/components/sync/driver/sync_auth_manager.cc b/chromium_src/components/sync/driver/sync_auth_manager.cc index 4cbaec4b6f6d..1d09d9eae9ae 100644 --- a/chromium_src/components/sync/driver/sync_auth_manager.cc +++ b/chromium_src/components/sync/driver/sync_auth_manager.cc @@ -1,28 +1,90 @@ #include "brave/chromium_src/components/sync/driver/sync_auth_manager.h" -#define BRAVE_REQUEST_ACCESS_TOKEN \ - access_token_fetcher_->Start("ID", "SECRECT"); +#include "base/strings/string_number_conversions.h" +#include "brave/components/brave_sync/crypto/crypto.h" + +#define BRAVE_REQUEST_ACCESS_TOKEN \ + if (private_key_.empty() || public_key_.empty()) { \ + ScheduleAccessTokenRequest(); \ + return; \ + } \ + access_token_fetcher_->StartGetTimestamp(); #include "../../../../../components/sync/driver/sync_auth_manager.cc" #undef BRAVE_REQUEST_ACCESS_TOKEN namespace syncer { -void SyncAuthManager::CreateAccessTokenFetcher( +void SyncAuthManager::CreateAccessTokenFetcher( scoped_refptr url_loader_factory) { access_token_fetcher_ = std::make_unique( - this, url_loader_factory, ""); + this, url_loader_factory, ""); } -void SyncAuthManager::OnGetTokenSuccess( - const brave_sync::AccessTokenConsumer::TokenResponse& token_response) { - access_token_ = token_response.access_token; - VLOG(1) << "Got Token: " << access_token_; - SetLastAuthError(GoogleServiceAuthError::AuthErrorNone()); + +void SyncAuthManager::DeriveSigningKeys(const std::string& seed) { + if (seed.empty()) + return; + const std::vector HKDF_SALT = { + 72, 203, 156, 43, 64, 229, 225, 127, 214, 158, 50, 29, 130, + 186, 182, 207, 6, 108, 47, 254, 245, 71, 198, 109, 44, 108, + 32, 193, 221, 126, 119, 143, 112, 113, 87, 184, 239, 231, 230, + 234, 28, 135, 54, 42, 9, 243, 39, 30, 179, 147, 194, 211, + 212, 239, 225, 52, 192, 219, 145, 40, 95, 19, 142, 98}; + std::vector seed_bytes; + brave_sync::crypto::PassphraseToBytes32(seed, &seed_bytes); + brave_sync::crypto::DeriveSigningKeysFromSeed(seed_bytes, &HKDF_SALT, + &public_key_, &private_key_); +} + +void SyncAuthManager::OnGetTokenSuccess( + const brave_sync::AccessTokenConsumer::TokenResponse& token_response) { + access_token_ = token_response.access_token; + VLOG(1) << "Got Token: " << access_token_; + SetLastAuthError(GoogleServiceAuthError::AuthErrorNone()); } void SyncAuthManager::OnGetTokenFailure(const std::string& error) { LOG(ERROR) << __func__ << ": " << error; // TODO(darkdh): SetLastAuthError request_access_token_backoff_.InformOfRequest(false); ScheduleAccessTokenRequest(); -} +} + +void SyncAuthManager::OnGetTimestampSuccess(const std::string& ts) { + std::string client_id, client_secret, timestamp; + GenerateClientIdAndSecret(&client_id, &client_secret, ts, ×tamp); + access_token_fetcher_->Start(client_id, client_secret, timestamp); +} + +void SyncAuthManager::OnGetTimestampFailure(const std::string& error) { + LOG(ERROR) << __func__ << ": " << error; + // TODO(darkdh): SetLastAuthError + request_access_token_backoff_.InformOfRequest(false); + ScheduleAccessTokenRequest(); +} + +void SyncAuthManager::GenerateClientIdAndSecret( + std::string* client_id, + std::string* client_secret, + const std::string& server_timestamp, + std::string* timestamp) { + DCHECK(client_id); + DCHECK(client_secret); + + *client_id = base::HexEncode(public_key_.data(), public_key_.size()); + + *timestamp = + base::HexEncode(server_timestamp.data(), server_timestamp.size()); + + std::vector timestamp_bytes; + base::HexStringToBytes(*timestamp, ×tamp_bytes); + std::vector signature; + brave_sync::crypto::Sign(timestamp_bytes, private_key_, &signature); + DCHECK(brave_sync::crypto::Verify(timestamp_bytes, signature, public_key_)); + + *client_secret = base::HexEncode(signature.data(), signature.size()); + + VLOG(1) << "client_id= " << *client_id; + VLOG(1) << "client_secret= " << *client_secret; + VLOG(1) << "timestamp= " << *timestamp; +} } // namespace syncer diff --git a/chromium_src/components/sync/driver/sync_auth_manager.h b/chromium_src/components/sync/driver/sync_auth_manager.h index efd71d95727d..fa1e000453f5 100644 --- a/chromium_src/components/sync/driver/sync_auth_manager.h +++ b/chromium_src/components/sync/driver/sync_auth_manager.h @@ -6,12 +6,20 @@ #define BRAVE_SYNC_AUTH_MANAGER_H_ \ void CreateAccessTokenFetcher( \ scoped_refptr url_loader_factory); \ + void DeriveSigningKeys(const std::string& seed); \ void OnGetTokenSuccess( \ const brave_sync::AccessTokenConsumer::TokenResponse& token_response) \ override; \ void OnGetTokenFailure(const std::string& error) override; \ + void OnGetTimestampSuccess(const std::string& ts) override; \ + void OnGetTimestampFailure(const std::string& error) override; \ \ private: \ + void GenerateClientIdAndSecret( \ + std::string* client_id, std::string* client_secrect, \ + const std::string& server_timestamp, std::string* timestamp); \ + std::vector public_key_; \ + std::vector private_key_; \ std::unique_ptr access_token_fetcher_; #include "../../../../../components/sync/driver/sync_auth_manager.h" #undef BRAVE_SYNC_AUTH_MANAGER_H_ diff --git a/components/brave_sync/access_token_consumer.cc b/components/brave_sync/access_token_consumer.cc index f808efc0827e..19c4a3558d41 100644 --- a/components/brave_sync/access_token_consumer.cc +++ b/components/brave_sync/access_token_consumer.cc @@ -18,4 +18,8 @@ void AccessTokenConsumer::OnGetTokenSuccess( void AccessTokenConsumer::OnGetTokenFailure( const std::string& error) {} +void AccessTokenConsumer::OnGetTimestampSuccess(const std::string& ts) {} + +void AccessTokenConsumer::OnGetTimestampFailure(const std::string& error) {} + } // namespace brave_sync diff --git a/components/brave_sync/access_token_consumer.h b/components/brave_sync/access_token_consumer.h index 7e77ecf1b68a..8d80f6a57b2b 100644 --- a/components/brave_sync/access_token_consumer.h +++ b/components/brave_sync/access_token_consumer.h @@ -36,6 +36,10 @@ class AccessTokenConsumer { // TODO(darkdh): define error messages virtual void OnGetTokenFailure(const std::string& error); + virtual void OnGetTimestampSuccess(const std::string& ts); + + virtual void OnGetTimestampFailure(const std::string& error); + DISALLOW_COPY_AND_ASSIGN(AccessTokenConsumer); }; diff --git a/components/brave_sync/access_token_fetcher.cc b/components/brave_sync/access_token_fetcher.cc index 704ff4dea8ae..2698828b37ba 100644 --- a/components/brave_sync/access_token_fetcher.cc +++ b/components/brave_sync/access_token_fetcher.cc @@ -18,4 +18,12 @@ void AccessTokenFetcher::FireOnGetTokenFailure( consumer_->OnGetTokenFailure(error); } +void AccessTokenFetcher::FireOnGetTimestampSuccess(const std::string& ts) { + consumer_->OnGetTimestampSuccess(ts); +} + +void AccessTokenFetcher::FireOnGetTimestampFailure(const std::string& error) { + consumer_->OnGetTimestampFailure(error); +} + } // namespace brave_sync diff --git a/components/brave_sync/access_token_fetcher.h b/components/brave_sync/access_token_fetcher.h index f6d8b8706489..01e27942bc7e 100644 --- a/components/brave_sync/access_token_fetcher.h +++ b/components/brave_sync/access_token_fetcher.h @@ -13,7 +13,10 @@ class AccessTokenFetcher { virtual ~AccessTokenFetcher(); virtual void Start(const std::string& client_id, - const std::string& client_secret) = 0; + const std::string& client_secret, + const std::string& timestamp) = 0; + + virtual void StartGetTimestamp() = 0; // Cancels the current request and informs the consumer. virtual void CancelRequest() = 0; @@ -25,6 +28,9 @@ class AccessTokenFetcher { // Fires |OnGetTokenFailure| on |consumer_|. void FireOnGetTokenFailure(const std::string& error); + + void FireOnGetTimestampSuccess(const std::string& ts); + void FireOnGetTimestampFailure(const std::string& error); private: AccessTokenConsumer* const consumer_; diff --git a/components/brave_sync/access_token_fetcher_impl.cc b/components/brave_sync/access_token_fetcher_impl.cc index 69cd784f54fc..ebb038a08f4f 100644 --- a/components/brave_sync/access_token_fetcher_impl.cc +++ b/components/brave_sync/access_token_fetcher_impl.cc @@ -27,12 +27,14 @@ namespace { constexpr char kGetAccessTokenBodyFormat[] = "client_id=%s&" "client_secret=%s&" + "timestamp=%s&" "refresh_token=%s"; constexpr char kAccessTokenKey[] = "access_token"; constexpr char kExpiresInKey[] = "expires_in"; constexpr char kIdTokenKey[] = "id_token"; constexpr char kErrorKey[] = "error"; +constexpr char kTimestamp[] = "timestamp"; static std::string CreateAuthError(int net_error) { CHECK_NE(net_error, net::OK); @@ -125,23 +127,38 @@ AccessTokenFetcherImpl::~AccessTokenFetcherImpl() {} void AccessTokenFetcherImpl::CancelRequest() { url_loader_.reset(); + ts_url_loader_.reset(); } void AccessTokenFetcherImpl::Start( const std::string& client_id, - const std::string& client_secret) { + const std::string& client_secret, + const std::string& timestamp) { client_id_ = client_id; client_secret_ = client_secret; + timestamp_ = timestamp; StartGetAccessToken(); } +void AccessTokenFetcherImpl::StartGetTimestamp() { + ts_url_loader_ = + CreateURLLoader(GURL("http://localhost:8295/v2/timestamp"), + ""); + // It's safe to use Unretained below as the |url_loader_| is owned by |this|. + ts_url_loader_->DownloadToString( + url_loader_factory_.get(), + base::BindOnce(&AccessTokenFetcherImpl::OnTimestampLoadComplete, + base::Unretained(this)), + 1024 * 1024); +} + void AccessTokenFetcherImpl::StartGetAccessToken() { CHECK_EQ(INITIAL, state_); state_ = GET_ACCESS_TOKEN_STARTED; url_loader_ = CreateURLLoader(MakeGetAccessTokenUrl(), MakeGetAccessTokenBody(client_id_, client_secret_, - refresh_token_)); + timestamp_, refresh_token_)); // It's safe to use Unretained below as the |url_loader_| is owned by |this|. url_loader_->DownloadToString( url_loader_factory_.get(), @@ -258,6 +275,33 @@ void AccessTokenFetcherImpl::OnURLLoadComplete( EndGetAccessToken(std::move(response_body)); } +void AccessTokenFetcherImpl::OnTimestampLoadComplete( + std::unique_ptr response_body) { + bool net_failure = false; + int histogram_value; + if (ts_url_loader_->NetError() == net::OK && ts_url_loader_->ResponseInfo() && + ts_url_loader_->ResponseInfo()->headers) { + histogram_value = ts_url_loader_->ResponseInfo()->headers->response_code(); + } else { + histogram_value = ts_url_loader_->NetError(); + net_failure = true; + } + if (net_failure) { + FireOnGetTimestampFailure(CreateAuthError(histogram_value)); + return; + } + std::unique_ptr value = + ParseGetAccessTokenResponse(std::move(response_body)); + if (!value) + return; + std::string timestamp; + if (!value->GetString(kTimestamp, ×tamp)) { + FireOnGetTimestampFailure("Unable to parse timestamp"); + return; + } + FireOnGetTimestampSuccess(timestamp); +} + // static GURL AccessTokenFetcherImpl::MakeGetAccessTokenUrl() { return GURL("http://localhost:8295/v2/auth"); @@ -267,15 +311,19 @@ GURL AccessTokenFetcherImpl::MakeGetAccessTokenUrl() { std::string AccessTokenFetcherImpl::MakeGetAccessTokenBody( const std::string& client_id, const std::string& client_secret, + const std::string& timestamp, const std::string& refresh_token) { std::string enc_client_id = net::EscapeUrlEncodedData(client_id, true); std::string enc_client_secret = net::EscapeUrlEncodedData(client_secret, true); + std::string enc_timestamp = + net::EscapeUrlEncodedData(timestamp, true); std::string enc_refresh_token = net::EscapeUrlEncodedData(refresh_token, true); return base::StringPrintf(kGetAccessTokenBodyFormat, enc_client_id.c_str(), enc_client_secret.c_str(), + enc_timestamp.c_str(), enc_refresh_token.c_str()); } diff --git a/components/brave_sync/access_token_fetcher_impl.h b/components/brave_sync/access_token_fetcher_impl.h index 2bdcf54111ce..878e8ce6d809 100644 --- a/components/brave_sync/access_token_fetcher_impl.h +++ b/components/brave_sync/access_token_fetcher_impl.h @@ -28,7 +28,10 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { // Implementation of AccessTokenFetcher void Start(const std::string& client_id, - const std::string& client_secret) override; + const std::string& client_secret, + const std::string& timestamp) override; + + void StartGetTimestamp() override; void CancelRequest() override; @@ -41,6 +44,7 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { }; void OnURLLoadComplete(std::unique_ptr response_body); + void OnTimestampLoadComplete(std::unique_ptr response_body); // Helper methods for the flow. void StartGetAccessToken(); @@ -56,6 +60,7 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { static std::string MakeGetAccessTokenBody( const std::string& client_id, const std::string& client_secret, + const std::string& timestamp, const std::string& refresh_token); static bool ParseGetAccessTokenSuccessResponse( @@ -75,8 +80,10 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { // While a fetch is in progress. std::unique_ptr url_loader_; + std::unique_ptr ts_url_loader_; std::string client_id_; std::string client_secret_; + std::string timestamp_; DISALLOW_COPY_AND_ASSIGN(AccessTokenFetcherImpl); }; diff --git a/patches/components-sync-driver-profile_sync_service.cc.patch b/patches/components-sync-driver-profile_sync_service.cc.patch index d97c7a5e7614..1a850dff4d4f 100644 --- a/patches/components-sync-driver-profile_sync_service.cc.patch +++ b/patches/components-sync-driver-profile_sync_service.cc.patch @@ -1,5 +1,5 @@ diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc -index f3956a3fcd7cbcfe74d81be242b2877075a9b189..5a239e458c61e8ee095484ebc97f064361cbe271 100644 +index f3956a3fcd7cbcfe74d81be242b2877075a9b189..b94592f82c6853b5a1a72a411c7e67e3e79d9c4b 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc @@ -193,6 +193,8 @@ ProfileSyncService::ProfileSyncService(InitParams init_params) @@ -19,7 +19,15 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..5a239e458c61e8ee095484ebc97f0643 params.poll_interval = sync_prefs_.GetPollInterval(); if (params.poll_interval.is_zero()) { params.poll_interval = -@@ -1214,6 +1217,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { +@@ -543,6 +546,7 @@ void ProfileSyncService::StartUpSlowEngineComponents() { + } + + if (!IsLocalSyncEnabled()) { ++ BRAVE_START_UP_SLOW_ENGINE_COMPONENTS + auth_manager_->ConnectionOpened(); + } + +@@ -1214,6 +1218,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { } bool ProfileSyncService::IsSignedIn() const { @@ -27,7 +35,15 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..5a239e458c61e8ee095484ebc97f0643 // Sync is logged in if there is a non-empty account id. return !GetAuthenticatedAccountInfo().account_id.empty(); } -@@ -1726,6 +1730,7 @@ void ProfileSyncService::GetAllNodesForDebugging( +@@ -1519,6 +1524,7 @@ void ProfileSyncService::OnFirstSetupCompletePrefChange( + bool is_first_setup_complete) { + if (engine_ && engine_->IsInitialized()) { + ReconfigureDatatypeManager(/*bypass_setup_in_progress_check=*/false); ++ BRAVE_ON_FIRST_SETUP_COMPLETE_PREF_CHANGE + } + } + +@@ -1726,6 +1732,7 @@ void ProfileSyncService::GetAllNodesForDebugging( } CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { @@ -35,7 +51,7 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..5a239e458c61e8ee095484ebc97f0643 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!auth_manager_) { // Some crashes on iOS (crbug.com/962384) suggest that ProfileSyncService -@@ -1738,6 +1743,7 @@ CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { +@@ -1738,6 +1745,7 @@ CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { } bool ProfileSyncService::IsAuthenticatedAccountPrimary() const { From cf883e724eb99f5f936e1baa0ba05e1766a8d58e Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Wed, 8 Apr 2020 19:03:41 -0700 Subject: [PATCH 10/79] Refine get access token flow --- .../brave_sync_page/brave_sync_subpage.js | 11 -- .../sync/driver/profile_sync_service.cc | 25 ++-- .../sync/driver/sync_auth_manager.cc | 53 +++++---- .../sync/driver/sync_auth_manager.h | 7 +- .../brave_sync/access_token_consumer.cc | 7 +- components/brave_sync/access_token_consumer.h | 7 +- components/brave_sync/access_token_fetcher.cc | 10 +- components/brave_sync/access_token_fetcher.h | 4 +- .../brave_sync/access_token_fetcher_impl.cc | 109 +++++++++++++----- .../brave_sync/access_token_fetcher_impl.h | 7 +- ...-sync-driver-profile_sync_service.cc.patch | 36 +++--- ...nts-sync-driver-sync_auth_manager.cc.patch | 12 +- ...et-sync_server_connection_manager.cc.patch | 25 ---- 13 files changed, 176 insertions(+), 137 deletions(-) delete mode 100644 patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch diff --git a/browser/resources/settings/brave_sync_page/brave_sync_subpage.js b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js index 0456641250e1..2b46f03ce678 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_subpage.js +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js @@ -378,18 +378,7 @@ Polymer({ onSyncSetupDone_: function(e) { if (e.detail) { this.didAbort_ = false; - - this.syncPrefs.encryptAllData = true; - this.syncPrefs.setNewPassphrase = true; - this.syncPrefs.passphrase = this.passphrase_; - - if (this.syncPrefs.passphraseRequired) { - this.syncPrefs.setNewPassphrase = false; - } this.browserProxy_.setSyncCode(this.passphrase_); - - this.browserProxy_.setSyncEncryption(this.syncPrefs) - .then(this.handlePageStatusChanged_.bind(this)); } else { this.setupCancelConfirmed_ = true; } diff --git a/chromium_src/components/sync/driver/profile_sync_service.cc b/chromium_src/components/sync/driver/profile_sync_service.cc index d8d7ac256daa..e422dbdc5b7c 100644 --- a/chromium_src/components/sync/driver/profile_sync_service.cc +++ b/chromium_src/components/sync/driver/profile_sync_service.cc @@ -13,14 +13,9 @@ const int64_t kBraveDefaultPollIntervalSeconds = 60; return sync_client_->GetPrefService()->GetBoolean( \ brave_sync::prefs::kSyncEnabled); -#define BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO \ - AccountInfo account_info; \ - account_info.account_id = CoreAccountId::FromString("dummy_account_id"); \ - return std::move(account_info); - -#define BRAVE_PROFILE_SYNC_SERVICE \ - auth_manager_->CreateAccessTokenFetcher( \ - url_loader_factory_); +#define BRAVE_PROFILE_SYNC_SERVICE \ + auth_manager_->CreateAccessTokenFetcher( \ + url_loader_factory_, sync_service_url_); #define BRAVE_START_UP_SLOW_ENGINE_COMPONENTS \ auth_manager_->DeriveSigningKeys( \ @@ -33,10 +28,22 @@ const int64_t kBraveDefaultPollIntervalSeconds = 60; sync_client_->GetPrefService()->GetString( \ brave_sync::prefs::kSyncSeed)); +#define BRAVE_ON_ENGINE_INITIALIZED \ + std::string sync_code = \ + sync_client_->GetPrefService()->GetString(brave_sync::prefs::kSyncSeed); \ + GetUserSettings()->EnableEncryptEverything(); \ + if (GetUserSettings()->IsPassphraseRequired()) { \ + if (!GetUserSettings()->SetDecryptionPassphrase(sync_code)) \ + LOG(ERROR) << "Set decryption passphrase failed"; \ + } else { \ + if (!GetUserSettings()->IsUsingSecondaryPassphrase()) \ + GetUserSettings()->SetEncryptionPassphrase(sync_code); \ + } + #include "../../../../../components/sync/driver/profile_sync_service.cc" #undef BRAVE_SET_POLL_INTERVAL #undef BRAVE_IS_SIGNED_IN -#undef BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO #undef BRAVE_PROFILE_SYNC_SERVICE #undef BRAVE_START_UP_SLOW_ENGINE_COMPONENTS #undef BRAVE_ON_FIRST_SETUP_COMPLETE_PREF_CHANGE +#undef BRAVE_ON_ENGINE_INITIALIZED diff --git a/chromium_src/components/sync/driver/sync_auth_manager.cc b/chromium_src/components/sync/driver/sync_auth_manager.cc index 1d09d9eae9ae..935e04e3fc3c 100644 --- a/chromium_src/components/sync/driver/sync_auth_manager.cc +++ b/chromium_src/components/sync/driver/sync_auth_manager.cc @@ -3,24 +3,36 @@ #include "base/strings/string_number_conversions.h" #include "brave/components/brave_sync/crypto/crypto.h" -#define BRAVE_REQUEST_ACCESS_TOKEN \ - if (private_key_.empty() || public_key_.empty()) { \ - ScheduleAccessTokenRequest(); \ - return; \ - } \ +#define BRAVE_REQUEST_ACCESS_TOKEN \ + VLOG(1) << __func__; \ + if (private_key_.empty() || public_key_.empty()) { \ + request_access_token_backoff_.InformOfRequest(false); \ + ScheduleAccessTokenRequest(); \ + return; \ + } \ access_token_fetcher_->StartGetTimestamp(); + +#define BRAVE_DETERMINE_ACCOUNT_TO_USE \ + AccountInfo account_info; \ + account_info.account_id = CoreAccountId::FromString("dummy_account_id"); \ + account_info.email = "dummy@brave.com"; \ + SyncAccountInfo account(account_info, true); \ + return account; #include "../../../../../components/sync/driver/sync_auth_manager.cc" #undef BRAVE_REQUEST_ACCESS_TOKEN +#undef BRAVE_DETERMINE_ACCOUNT_TO_USE namespace syncer { void SyncAuthManager::CreateAccessTokenFetcher( - scoped_refptr url_loader_factory) { + scoped_refptr url_loader_factory, + const GURL& sync_service_url) { access_token_fetcher_ = std::make_unique( - this, url_loader_factory, ""); + this, url_loader_factory, sync_service_url, ""); } void SyncAuthManager::DeriveSigningKeys(const std::string& seed) { + VLOG(1) << __func__ << " seed=" << seed; if (seed.empty()) return; const std::vector HKDF_SALT = { @@ -37,28 +49,29 @@ void SyncAuthManager::DeriveSigningKeys(const std::string& seed) { void SyncAuthManager::OnGetTokenSuccess( const brave_sync::AccessTokenConsumer::TokenResponse& token_response) { - access_token_ = token_response.access_token; - VLOG(1) << "Got Token: " << access_token_; - SetLastAuthError(GoogleServiceAuthError::AuthErrorNone()); + AccessTokenFetched(GoogleServiceAuthError(GoogleServiceAuthError::NONE), + signin::AccessTokenInfo(token_response.access_token, + token_response.expiration_time, + token_response.id_token)); + VLOG(1) << __func__ << " Token: " << access_token_; } -void SyncAuthManager::OnGetTokenFailure(const std::string& error) { - LOG(ERROR) << __func__ << ": " << error; - // TODO(darkdh): SetLastAuthError - request_access_token_backoff_.InformOfRequest(false); - ScheduleAccessTokenRequest(); + +void SyncAuthManager::OnGetTokenFailure(const GoogleServiceAuthError& error) { + LOG(ERROR) << __func__ << ": " << error.error_message(); + AccessTokenFetched(error, signin::AccessTokenInfo()); } void SyncAuthManager::OnGetTimestampSuccess(const std::string& ts) { + VLOG(1) << __func__ << " Timestamp: " << ts; std::string client_id, client_secret, timestamp; GenerateClientIdAndSecret(&client_id, &client_secret, ts, ×tamp); access_token_fetcher_->Start(client_id, client_secret, timestamp); } -void SyncAuthManager::OnGetTimestampFailure(const std::string& error) { - LOG(ERROR) << __func__ << ": " << error; - // TODO(darkdh): SetLastAuthError - request_access_token_backoff_.InformOfRequest(false); - ScheduleAccessTokenRequest(); +void SyncAuthManager::OnGetTimestampFailure( + const GoogleServiceAuthError& error) { + LOG(ERROR) << __func__ << ": " << error.error_message(); + AccessTokenFetched(error, signin::AccessTokenInfo()); } void SyncAuthManager::GenerateClientIdAndSecret( diff --git a/chromium_src/components/sync/driver/sync_auth_manager.h b/chromium_src/components/sync/driver/sync_auth_manager.h index fa1e000453f5..f56eca0c2957 100644 --- a/chromium_src/components/sync/driver/sync_auth_manager.h +++ b/chromium_src/components/sync/driver/sync_auth_manager.h @@ -5,14 +5,15 @@ #include "services/network/public/cpp/shared_url_loader_factory.h" #define BRAVE_SYNC_AUTH_MANAGER_H_ \ void CreateAccessTokenFetcher( \ - scoped_refptr url_loader_factory); \ + scoped_refptr url_loader_factory, \ + const GURL& sync_service_url); \ void DeriveSigningKeys(const std::string& seed); \ void OnGetTokenSuccess( \ const brave_sync::AccessTokenConsumer::TokenResponse& token_response) \ override; \ - void OnGetTokenFailure(const std::string& error) override; \ + void OnGetTokenFailure(const GoogleServiceAuthError& error) override; \ void OnGetTimestampSuccess(const std::string& ts) override; \ - void OnGetTimestampFailure(const std::string& error) override; \ + void OnGetTimestampFailure(const GoogleServiceAuthError& error) override; \ \ private: \ void GenerateClientIdAndSecret( \ diff --git a/components/brave_sync/access_token_consumer.cc b/components/brave_sync/access_token_consumer.cc index 19c4a3558d41..e2ab79b93d0b 100644 --- a/components/brave_sync/access_token_consumer.cc +++ b/components/brave_sync/access_token_consumer.cc @@ -16,10 +16,11 @@ void AccessTokenConsumer::OnGetTokenSuccess( const TokenResponse& token_response) {} void AccessTokenConsumer::OnGetTokenFailure( - const std::string& error) {} + const GoogleServiceAuthError& error) {} void AccessTokenConsumer::OnGetTimestampSuccess(const std::string& ts) {} -void AccessTokenConsumer::OnGetTimestampFailure(const std::string& error) {} +void AccessTokenConsumer::OnGetTimestampFailure( + const GoogleServiceAuthError& error) {} -} // namespace brave_sync +} // namespace brave_sync diff --git a/components/brave_sync/access_token_consumer.h b/components/brave_sync/access_token_consumer.h index 8d80f6a57b2b..214b12584e04 100644 --- a/components/brave_sync/access_token_consumer.h +++ b/components/brave_sync/access_token_consumer.h @@ -3,6 +3,8 @@ #include "base/time/time.h" +class GoogleServiceAuthError; + namespace brave_sync { class AccessTokenConsumer { @@ -33,12 +35,11 @@ class AccessTokenConsumer { virtual void OnGetTokenSuccess(const TokenResponse& token_response); // Failure callback. - // TODO(darkdh): define error messages - virtual void OnGetTokenFailure(const std::string& error); + virtual void OnGetTokenFailure(const GoogleServiceAuthError& error); virtual void OnGetTimestampSuccess(const std::string& ts); - virtual void OnGetTimestampFailure(const std::string& error); + virtual void OnGetTimestampFailure(const GoogleServiceAuthError& error); DISALLOW_COPY_AND_ASSIGN(AccessTokenConsumer); }; diff --git a/components/brave_sync/access_token_fetcher.cc b/components/brave_sync/access_token_fetcher.cc index 2698828b37ba..d99753afa274 100644 --- a/components/brave_sync/access_token_fetcher.cc +++ b/components/brave_sync/access_token_fetcher.cc @@ -2,8 +2,7 @@ namespace brave_sync { -AccessTokenFetcher::AccessTokenFetcher( - AccessTokenConsumer* consumer) +AccessTokenFetcher::AccessTokenFetcher(AccessTokenConsumer* consumer) : consumer_(consumer) {} AccessTokenFetcher::~AccessTokenFetcher() {} @@ -14,7 +13,7 @@ void AccessTokenFetcher::FireOnGetTokenSuccess( } void AccessTokenFetcher::FireOnGetTokenFailure( - const std::string& error) { + const GoogleServiceAuthError& error) { consumer_->OnGetTokenFailure(error); } @@ -22,8 +21,9 @@ void AccessTokenFetcher::FireOnGetTimestampSuccess(const std::string& ts) { consumer_->OnGetTimestampSuccess(ts); } -void AccessTokenFetcher::FireOnGetTimestampFailure(const std::string& error) { +void AccessTokenFetcher::FireOnGetTimestampFailure( + const GoogleServiceAuthError& error) { consumer_->OnGetTimestampFailure(error); } -} // namespace brave_sync +} // namespace brave_sync diff --git a/components/brave_sync/access_token_fetcher.h b/components/brave_sync/access_token_fetcher.h index 01e27942bc7e..e8fec5fd0024 100644 --- a/components/brave_sync/access_token_fetcher.h +++ b/components/brave_sync/access_token_fetcher.h @@ -27,10 +27,10 @@ class AccessTokenFetcher { const AccessTokenConsumer::TokenResponse& token_response); // Fires |OnGetTokenFailure| on |consumer_|. - void FireOnGetTokenFailure(const std::string& error); + void FireOnGetTokenFailure(const GoogleServiceAuthError& error); void FireOnGetTimestampSuccess(const std::string& ts); - void FireOnGetTimestampFailure(const std::string& error); + void FireOnGetTimestampFailure(const GoogleServiceAuthError& error); private: AccessTokenConsumer* const consumer_; diff --git a/components/brave_sync/access_token_fetcher_impl.cc b/components/brave_sync/access_token_fetcher_impl.cc index ebb038a08f4f..de2d3530f57c 100644 --- a/components/brave_sync/access_token_fetcher_impl.cc +++ b/components/brave_sync/access_token_fetcher_impl.cc @@ -10,6 +10,7 @@ #include "base/strings/stringprintf.h" #include "base/time/time.h" #include "base/values.h" +#include "google_apis/gaia/google_service_auth_error.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" @@ -36,11 +37,45 @@ constexpr char kIdTokenKey[] = "id_token"; constexpr char kErrorKey[] = "error"; constexpr char kTimestamp[] = "timestamp"; -static std::string CreateAuthError(int net_error) { +constexpr char kAuthSuffix[] = "v2/auth"; +constexpr char kTimestampSuffix[] = "v2/timestamp"; + +// Enumerated constants for logging server responses on 400 errors, matching +// RFC 6749. +enum OAuth2ErrorCodesForHistogram { + OAUTH2_ACCESS_ERROR_INVALID_REQUEST = 0, + OAUTH2_ACCESS_ERROR_INVALID_CLIENT, + OAUTH2_ACCESS_ERROR_INVALID_GRANT, + OAUTH2_ACCESS_ERROR_UNAUTHORIZED_CLIENT, + OAUTH2_ACCESS_ERROR_UNSUPPORTED_GRANT_TYPE, + OAUTH2_ACCESS_ERROR_INVALID_SCOPE, + OAUTH2_ACCESS_ERROR_UNKNOWN, + OAUTH2_ACCESS_ERROR_COUNT +}; + +OAuth2ErrorCodesForHistogram OAuth2ErrorToHistogramValue( + const std::string& error) { + if (error == "invalid_request") + return OAUTH2_ACCESS_ERROR_INVALID_REQUEST; + else if (error == "invalid_client") + return OAUTH2_ACCESS_ERROR_INVALID_CLIENT; + else if (error == "invalid_grant") + return OAUTH2_ACCESS_ERROR_INVALID_GRANT; + else if (error == "unauthorized_client") + return OAUTH2_ACCESS_ERROR_UNAUTHORIZED_CLIENT; + else if (error == "unsupported_grant_type") + return OAUTH2_ACCESS_ERROR_UNSUPPORTED_GRANT_TYPE; + else if (error == "invalid_scope") + return OAUTH2_ACCESS_ERROR_INVALID_SCOPE; + + return OAUTH2_ACCESS_ERROR_UNKNOWN; +} + +static GoogleServiceAuthError CreateAuthError(int net_error) { CHECK_NE(net_error, net::OK); DLOG(WARNING) << "Server error: errno " << net_error; - return net::ErrorToString(net_error); + return GoogleServiceAuthError::FromConnectionError(net_error); } static std::unique_ptr CreateURLLoader( @@ -99,7 +134,7 @@ static std::unique_ptr CreateURLLoader( return url_loader; } -std::unique_ptr ParseGetAccessTokenResponse( +std::unique_ptr ParseServerResponse( std::unique_ptr data) { if (!data) return nullptr; @@ -117,9 +152,11 @@ std::unique_ptr ParseGetAccessTokenResponse( AccessTokenFetcherImpl::AccessTokenFetcherImpl( AccessTokenConsumer* consumer, scoped_refptr url_loader_factory, + const GURL& sync_service_url, const std::string& refresh_token) : AccessTokenFetcher(consumer), url_loader_factory_(url_loader_factory), + sync_service_url_(sync_service_url), refresh_token_(refresh_token), state_(INITIAL) {} @@ -142,7 +179,7 @@ void AccessTokenFetcherImpl::Start( void AccessTokenFetcherImpl::StartGetTimestamp() { ts_url_loader_ = - CreateURLLoader(GURL("http://localhost:8295/v2/timestamp"), + CreateURLLoader(MakeGetTimestampUrl(), ""); // It's safe to use Unretained below as the |url_loader_| is owned by |this|. ts_url_loader_->DownloadToString( @@ -194,12 +231,14 @@ void AccessTokenFetcherImpl::EndGetAccessToken( NOTREACHED() << "HTTP 407 should be treated as a network error."; // If this ever happens in production, we treat it as a temporary error as // it is similar to a network error. - OnGetTokenFailure(net::ErrorToString(response_code)); + OnGetTokenFailure( + GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); return; case net::HTTP_FORBIDDEN: // HTTP_FORBIDDEN (403) is treated as temporary error, because it may be // '403 Rate Limit Exeeded.' - OnGetTokenFailure(net::ErrorToString(response_code)); + OnGetTokenFailure( + GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); return; case net::HTTP_BAD_REQUEST: { // HTTP_BAD_REQUEST (400) usually contains error as per @@ -207,33 +246,34 @@ void AccessTokenFetcherImpl::EndGetAccessToken( std::string gaia_error; if (!ParseGetAccessTokenFailureResponse(std::move(response_body), &gaia_error)) { - OnGetTokenFailure(net::ErrorToString(response_code)); + OnGetTokenFailure( + GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR)); return; } - - // ErrorCodesForHistogram access_error( - // ErrorToHistogramValue(gaia_error)); - // UMA_HISTOGRAM_ENUMERATION("Gaia.BadRequestTypeForAccessToken", - // access_error, - // OAUTH2_ACCESS_ERROR_COUNT); - - // OnGetTokenFailure( - // access_error == OAUTH2_ACCESS_ERROR_INVALID_GRANT - // ? GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( - // GoogleServiceAuthError::InvalidGaiaCredentialsReason:: - // CREDENTIALS_REJECTED_BY_SERVER) - // : GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR)); + OAuth2ErrorCodesForHistogram access_error( + OAuth2ErrorToHistogramValue(gaia_error)); + + OnGetTokenFailure( + access_error == OAUTH2_ACCESS_ERROR_INVALID_GRANT + ? GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( + GoogleServiceAuthError::InvalidGaiaCredentialsReason:: + CREDENTIALS_REJECTED_BY_SERVER) + : GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR)); return; } default: { if (response_code >= net::HTTP_INTERNAL_SERVER_ERROR) { // 5xx is always treated as transient. - OnGetTokenFailure(net::ErrorToString(response_code)); + OnGetTokenFailure(GoogleServiceAuthError( + GoogleServiceAuthError::SERVICE_UNAVAILABLE)); } else { // The other errors are treated as permanent error. DLOG(ERROR) << "Unexpected persistent error: http_status=" << response_code; - OnGetTokenFailure(net::ErrorToString(response_code)); + OnGetTokenFailure( + GoogleServiceAuthError::FromInvalidGaiaCredentialsReason( + GoogleServiceAuthError::InvalidGaiaCredentialsReason:: + CREDENTIALS_REJECTED_BY_SERVER)); } return; } @@ -247,7 +287,8 @@ void AccessTokenFetcherImpl::EndGetAccessToken( if (!ParseGetAccessTokenSuccessResponse( std::move(response_body), &access_token, &expires_in, &id_token)) { DLOG(WARNING) << "Response doesn't match expected format"; - OnGetTokenFailure("Service Unavailable"); + OnGetTokenFailure( + GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); return; } // The token will expire in |expires_in| seconds. Take a 10% error margin to @@ -264,7 +305,7 @@ void AccessTokenFetcherImpl::OnGetTokenSuccess( } void AccessTokenFetcherImpl::OnGetTokenFailure( - const std::string& error) { + const GoogleServiceAuthError& error) { state_ = ERROR_STATE; FireOnGetTokenFailure(error); } @@ -277,6 +318,7 @@ void AccessTokenFetcherImpl::OnURLLoadComplete( void AccessTokenFetcherImpl::OnTimestampLoadComplete( std::unique_ptr response_body) { + state_ = INITIAL; bool net_failure = false; int histogram_value; if (ts_url_loader_->NetError() == net::OK && ts_url_loader_->ResponseInfo() && @@ -288,23 +330,30 @@ void AccessTokenFetcherImpl::OnTimestampLoadComplete( } if (net_failure) { FireOnGetTimestampFailure(CreateAuthError(histogram_value)); + state_ = ERROR_STATE; return; } std::unique_ptr value = - ParseGetAccessTokenResponse(std::move(response_body)); + ParseServerResponse(std::move(response_body)); if (!value) return; std::string timestamp; if (!value->GetString(kTimestamp, ×tamp)) { - FireOnGetTimestampFailure("Unable to parse timestamp"); + DLOG(WARNING) << "Response doesn't match expected format"; + FireOnGetTimestampFailure( + GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); + state_ = ERROR_STATE; return; } FireOnGetTimestampSuccess(timestamp); } -// static GURL AccessTokenFetcherImpl::MakeGetAccessTokenUrl() { - return GURL("http://localhost:8295/v2/auth"); + return sync_service_url_.Resolve(kAuthSuffix); +} + +GURL AccessTokenFetcherImpl::MakeGetTimestampUrl() { + return sync_service_url_.Resolve(kTimestampSuffix); } // static @@ -335,7 +384,7 @@ bool AccessTokenFetcherImpl::ParseGetAccessTokenSuccessResponse( std::string* id_token) { CHECK(access_token); std::unique_ptr value = - ParseGetAccessTokenResponse(std::move(response_body)); + ParseServerResponse(std::move(response_body)); if (!value) return false; // ID token field is optional. @@ -350,7 +399,7 @@ bool AccessTokenFetcherImpl::ParseGetAccessTokenFailureResponse( std::string* error) { CHECK(error); std::unique_ptr value = - ParseGetAccessTokenResponse(std::move(response_body)); + ParseServerResponse(std::move(response_body)); return value ? value->GetString(kErrorKey, error) : false; } diff --git a/components/brave_sync/access_token_fetcher_impl.h b/components/brave_sync/access_token_fetcher_impl.h index 878e8ce6d809..6b1bc0ec1f1c 100644 --- a/components/brave_sync/access_token_fetcher_impl.h +++ b/components/brave_sync/access_token_fetcher_impl.h @@ -23,6 +23,7 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { AccessTokenFetcherImpl( AccessTokenConsumer* consumer, scoped_refptr url_loader_factory, + const GURL& sync_service_url, const std::string& refresh_token); ~AccessTokenFetcherImpl() override; @@ -53,10 +54,11 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { // Helper mehtods for reporting back results. void OnGetTokenSuccess( const AccessTokenConsumer::TokenResponse& token_response); - void OnGetTokenFailure(const std::string& error); + void OnGetTokenFailure(const GoogleServiceAuthError& error); // Other helpers. - static GURL MakeGetAccessTokenUrl(); + GURL MakeGetAccessTokenUrl(); + GURL MakeGetTimestampUrl(); static std::string MakeGetAccessTokenBody( const std::string& client_id, const std::string& client_secret, @@ -75,6 +77,7 @@ class AccessTokenFetcherImpl : public AccessTokenFetcher { // State that is set during construction. scoped_refptr url_loader_factory_; + GURL sync_service_url_; const std::string refresh_token_; State state_; diff --git a/patches/components-sync-driver-profile_sync_service.cc.patch b/patches/components-sync-driver-profile_sync_service.cc.patch index 1a850dff4d4f..ac43013b9fd1 100644 --- a/patches/components-sync-driver-profile_sync_service.cc.patch +++ b/patches/components-sync-driver-profile_sync_service.cc.patch @@ -1,5 +1,5 @@ diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc -index f3956a3fcd7cbcfe74d81be242b2877075a9b189..b94592f82c6853b5a1a72a411c7e67e3e79d9c4b 100644 +index f3956a3fcd7cbcfe74d81be242b2877075a9b189..a5bc7e9864f06f68d9ef71dd3aaa1def8c844c6b 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc @@ -193,6 +193,8 @@ ProfileSyncService::ProfileSyncService(InitParams init_params) @@ -27,7 +27,15 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..b94592f82c6853b5a1a72a411c7e67e3 auth_manager_->ConnectionOpened(); } -@@ -1214,6 +1218,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { +@@ -940,6 +944,7 @@ void ProfileSyncService::OnEngineInitialized( + } + } + ++ BRAVE_ON_ENGINE_INITIALIZED + NotifyObservers(); + } + +@@ -1214,6 +1219,7 @@ void ProfileSyncService::TriggerRefresh(const ModelTypeSet& types) { } bool ProfileSyncService::IsSignedIn() const { @@ -35,27 +43,11 @@ index f3956a3fcd7cbcfe74d81be242b2877075a9b189..b94592f82c6853b5a1a72a411c7e67e3 // Sync is logged in if there is a non-empty account id. return !GetAuthenticatedAccountInfo().account_id.empty(); } -@@ -1519,6 +1524,7 @@ void ProfileSyncService::OnFirstSetupCompletePrefChange( +@@ -1517,6 +1523,7 @@ void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) { + + void ProfileSyncService::OnFirstSetupCompletePrefChange( bool is_first_setup_complete) { ++ BRAVE_ON_FIRST_SETUP_COMPLETE_PREF_CHANGE if (engine_ && engine_->IsInitialized()) { ReconfigureDatatypeManager(/*bypass_setup_in_progress_check=*/false); -+ BRAVE_ON_FIRST_SETUP_COMPLETE_PREF_CHANGE } - } - -@@ -1726,6 +1732,7 @@ void ProfileSyncService::GetAllNodesForDebugging( - } - - CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { -+ BRAVE_GET_AUTHENTICATED_ACCOUNT_INFO - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!auth_manager_) { - // Some crashes on iOS (crbug.com/962384) suggest that ProfileSyncService -@@ -1738,6 +1745,7 @@ CoreAccountInfo ProfileSyncService::GetAuthenticatedAccountInfo() const { - } - - bool ProfileSyncService::IsAuthenticatedAccountPrimary() const { -+ return true; - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!auth_manager_) { - // This is a precautionary check to be consistent with the check in diff --git a/patches/components-sync-driver-sync_auth_manager.cc.patch b/patches/components-sync-driver-sync_auth_manager.cc.patch index 9fd3ca48002e..b3b622d1e2a6 100644 --- a/patches/components-sync-driver-sync_auth_manager.cc.patch +++ b/patches/components-sync-driver-sync_auth_manager.cc.patch @@ -1,8 +1,16 @@ diff --git a/components/sync/driver/sync_auth_manager.cc b/components/sync/driver/sync_auth_manager.cc -index 3287a32ed1ca6ed5aada26928592ad278f8046a6..5295f89e1ca16b63df3e67ba58d8195b5f0a10c2 100644 +index 3287a32ed1ca6ed5aada26928592ad278f8046a6..7e7f4d0a1dad502d5734e1cf6b1053714f3fe14b 100644 --- a/components/sync/driver/sync_auth_manager.cc +++ b/components/sync/driver/sync_auth_manager.cc -@@ -481,6 +481,7 @@ void SyncAuthManager::RequestAccessToken() { +@@ -410,6 +410,7 @@ void SyncAuthManager::ResetRequestAccessTokenBackoffForTest() { + + SyncAccountInfo SyncAuthManager::DetermineAccountToUse() const { + DCHECK(registered_for_auth_notifications_); ++ BRAVE_DETERMINE_ACCOUNT_TO_USE + return syncer::DetermineAccountToUse(identity_manager_); + } + +@@ -481,6 +482,7 @@ void SyncAuthManager::RequestAccessToken() { // Finally, kick off a new access token fetch. partial_token_status_.token_request_time = base::Time::Now(); partial_token_status_.token_response_time = base::Time(); diff --git a/patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch b/patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch deleted file mode 100644 index 2e4c88fc03a0..000000000000 --- a/patches/components-sync-engine_impl-net-sync_server_connection_manager.cc.patch +++ /dev/null @@ -1,25 +0,0 @@ -diff --git a/components/sync/engine_impl/net/sync_server_connection_manager.cc b/components/sync/engine_impl/net/sync_server_connection_manager.cc -index c210064c1766a0dec727b58e93140b2e28406f4b..a6438b648dc7487e43039f3fa1490703f9795e10 100644 ---- a/components/sync/engine_impl/net/sync_server_connection_manager.cc -+++ b/components/sync/engine_impl/net/sync_server_connection_manager.cc -@@ -225,13 +225,13 @@ bool SyncServerConnectionManager::PostBufferToPath( - PostBufferParams* params, - const std::string& path, - const std::string& access_token) { -- if (access_token.empty()) { -- params->response.server_status = HttpResponse::SYNC_AUTH_ERROR; -- // Print a log to distinguish this "known failure" from others. -- DVLOG(1) << "ServerConnectionManager forcing SYNC_AUTH_ERROR due to missing" -- " access token"; -- return false; -- } -+ // if (access_token.empty()) { -+ // params->response.server_status = HttpResponse::SYNC_AUTH_ERROR; -+ // // Print a log to distinguish this "known failure" from others. -+ // DVLOG(1) << "ServerConnectionManager forcing SYNC_AUTH_ERROR due to missing" -+ // " access token"; -+ // return false; -+ // } - - if (cancelation_signal_->IsSignalled()) { - params->response.server_status = HttpResponse::CONNECTION_UNAVAILABLE; From 7ab37ec50888a01b8c5480e583145933e27b5295 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Thu, 9 Apr 2020 17:58:02 -0700 Subject: [PATCH 11/79] Cleanup sync v1 code --- app/brave_command_ids.h | 2 +- brave_paks.gni | 11 - browser/BUILD.gn | 2 - .../brave_autocomplete_provider_client.cc | 29 - .../brave_autocomplete_provider_client.h | 26 - ...e_autocomplete_provider_client_unittest.cc | 56 - ...rave_content_browser_client_browsertest.cc | 37 - .../brave_content_browser_client_unittest.cc | 11 - browser/brave_profile_prefs_browsertest.cc | 2 - browser/brave_scheme_load_browsertest.cc | 5 - browser/extensions/BUILD.gn | 15 - browser/extensions/api/brave_sync_api.cc | 201 -- browser/extensions/api/brave_sync_api.h | 83 - .../extensions/api/brave_sync_event_router.cc | 138 -- .../extensions/api/brave_sync_event_router.h | 67 - ...ve_component_extension_resource_manager.cc | 15 - .../extensions/brave_extension_provider.cc | 3 +- browser/ui/BUILD.gn | 18 - .../ui/brave_browser_command_controller.cc | 18 +- ..._browser_command_controller_browsertest.cc | 29 - browser/ui/brave_pages.cc | 6 - browser/ui/brave_pages.h | 1 - browser/ui/toolbar/brave_app_menu_model.cc | 28 - .../brave_app_menu_model_browsertest.cc | 44 - .../webui/brave_web_ui_controller_factory.cc | 15 - browser/ui/webui/sync/sync_ui.cc | 273 --- browser/ui/webui/sync/sync_ui.h | 21 - .../autocomplete_classifier_factory.cc | 3 - .../chrome/browser/browser_about_handler.cc | 7 - .../whitelist.cc | 3 - .../render_view_context_menu.cc | 4 +- .../chrome/browser/ui/browser_navigator.cc | 1 - .../ui/omnibox/chrome_omnibox_client.cc | 10 - common/extensions/api/BUILD.gn | 5 - common/extensions/api/brave_sync.json | 450 ----- common/extensions/extension_constants.cc | 1 - common/extensions/extension_constants.h | 1 - common/extensions/whitelist.cc | 1 - common/webui_url_constants.cc | 3 - common/webui_url_constants.h | 3 - components/brave_sync/BUILD.gn | 151 -- components/brave_sync/bookmark_order_util.cc | 176 -- components/brave_sync/bookmark_order_util.h | 23 - .../bookmark_order_util_unittest.cc | 115 -- components/brave_sync/brave_sync_prefs.cc | 231 +-- components/brave_sync/brave_sync_prefs.h | 78 +- components/brave_sync/brave_sync_service.cc | 23 - components/brave_sync/brave_sync_service.h | 69 - .../brave_sync/brave_sync_service_observer.h | 25 - .../brave_sync/brave_sync_service_unittest.cc | 1761 ----------------- .../brave_sync/client/brave_sync_client.h | 97 - .../client/brave_sync_client_impl.cc | 203 -- .../client/brave_sync_client_impl.h | 103 - components/brave_sync/client/client_data.cc | 15 - components/brave_sync/client/client_data.h | 30 - .../brave_sync/client/client_ext_impl_data.cc | 338 ---- .../brave_sync/client/client_ext_impl_data.h | 51 - components/brave_sync/jslib_const.cc | 33 - components/brave_sync/jslib_const.h | 38 - components/brave_sync/jslib_messages.cc | 244 --- components/brave_sync/jslib_messages.h | 181 -- components/brave_sync/jslib_messages_fwd.h | 51 - .../public/brave_profile_sync_service.h | 38 - components/brave_sync/resources.grd | 23 - components/brave_sync/settings.cc | 17 - components/brave_sync/settings.h | 31 - components/brave_sync/sync_devices.cc | 221 --- components/brave_sync/sync_devices.h | 61 - components/brave_sync/syncer_helper.cc | 111 -- components/brave_sync/syncer_helper.h | 30 - .../brave_sync/syncer_helper_unittest.cc | 619 ------ components/brave_sync/test_util.cc | 152 -- components/brave_sync/test_util.h | 93 - components/brave_sync/tools.cc | 82 - components/brave_sync/tools.h | 43 - components/brave_sync/values_conv.cc | 154 -- components/brave_sync/values_conv.h | 39 - test/BUILD.gn | 8 - 78 files changed, 37 insertions(+), 7369 deletions(-) delete mode 100644 browser/autocomplete/brave_autocomplete_provider_client.cc delete mode 100644 browser/autocomplete/brave_autocomplete_provider_client.h delete mode 100644 browser/autocomplete/brave_autocomplete_provider_client_unittest.cc delete mode 100644 browser/extensions/api/brave_sync_api.cc delete mode 100644 browser/extensions/api/brave_sync_api.h delete mode 100644 browser/extensions/api/brave_sync_event_router.cc delete mode 100644 browser/extensions/api/brave_sync_event_router.h delete mode 100644 browser/ui/webui/sync/sync_ui.cc delete mode 100644 browser/ui/webui/sync/sync_ui.h delete mode 100644 chromium_src/chrome/browser/ui/omnibox/chrome_omnibox_client.cc delete mode 100644 common/extensions/api/brave_sync.json delete mode 100644 components/brave_sync/bookmark_order_util.cc delete mode 100644 components/brave_sync/bookmark_order_util.h delete mode 100644 components/brave_sync/bookmark_order_util_unittest.cc delete mode 100644 components/brave_sync/brave_sync_service.cc delete mode 100644 components/brave_sync/brave_sync_service.h delete mode 100644 components/brave_sync/brave_sync_service_observer.h delete mode 100644 components/brave_sync/brave_sync_service_unittest.cc delete mode 100644 components/brave_sync/client/brave_sync_client.h delete mode 100644 components/brave_sync/client/brave_sync_client_impl.cc delete mode 100644 components/brave_sync/client/brave_sync_client_impl.h delete mode 100644 components/brave_sync/client/client_data.cc delete mode 100644 components/brave_sync/client/client_data.h delete mode 100644 components/brave_sync/client/client_ext_impl_data.cc delete mode 100644 components/brave_sync/client/client_ext_impl_data.h delete mode 100644 components/brave_sync/jslib_const.cc delete mode 100644 components/brave_sync/jslib_const.h delete mode 100644 components/brave_sync/jslib_messages.cc delete mode 100644 components/brave_sync/jslib_messages.h delete mode 100644 components/brave_sync/jslib_messages_fwd.h delete mode 100644 components/brave_sync/public/brave_profile_sync_service.h delete mode 100644 components/brave_sync/resources.grd delete mode 100644 components/brave_sync/settings.cc delete mode 100644 components/brave_sync/settings.h delete mode 100644 components/brave_sync/sync_devices.cc delete mode 100644 components/brave_sync/sync_devices.h delete mode 100644 components/brave_sync/syncer_helper.cc delete mode 100644 components/brave_sync/syncer_helper.h delete mode 100644 components/brave_sync/syncer_helper_unittest.cc delete mode 100644 components/brave_sync/test_util.cc delete mode 100644 components/brave_sync/test_util.h delete mode 100644 components/brave_sync/tools.cc delete mode 100644 components/brave_sync/tools.h delete mode 100644 components/brave_sync/values_conv.cc delete mode 100644 components/brave_sync/values_conv.h diff --git a/app/brave_command_ids.h b/app/brave_command_ids.h index 8a2ac38c8480..bad56a349f94 100644 --- a/app/brave_command_ids.h +++ b/app/brave_command_ids.h @@ -15,7 +15,7 @@ #define IDC_NEW_TOR_CONNECTION_FOR_SITE 56002 #define IDC_NEW_OFFTHERECORD_WINDOW_TOR 56003 #define IDC_CONTENT_CONTEXT_OPENLINKTOR 56004 -#define IDC_SHOW_BRAVE_SYNC 56005 +// #define IDC_SHOW_BRAVE_SYNC 56005 #define IDC_SHOW_BRAVE_WALLET 56006 #define IDC_ADD_NEW_PROFILE 56007 #define IDC_OPEN_GUEST_PROFILE 56008 diff --git a/brave_paks.gni b/brave_paks.gni index 5f1b2f8399ad..b0870eb69743 100644 --- a/brave_paks.gni +++ b/brave_paks.gni @@ -4,7 +4,6 @@ import("//brave/components/brave_ads/browser/buildflags/buildflags.gni") import("//brave/components/brave_rewards/browser/buildflags/buildflags.gni") -import("//brave/components/brave_sync/buildflags/buildflags.gni") import("//brave/components/brave_webtorrent/browser/buildflags/buildflags.gni") import("//brave/components/speedreader/buildflags.gni") import("//build/config/locales.gni") @@ -105,16 +104,6 @@ template("brave_extra_paks") { ] } - if (enable_brave_sync) { - sources += [ - "$root_gen_dir/brave/components/brave_sync/brave_sync_resources.pak", - ] - - deps += [ - "//brave/components/brave_sync:resources", - ] - } - if (enable_brave_webtorrent) { sources += [ "$root_gen_dir/brave/components/brave_webtorrent/brave_webtorrent_resources.pak", diff --git a/browser/BUILD.gn b/browser/BUILD.gn index 9e57f46feb41..1f93966ca9ea 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -29,8 +29,6 @@ source_set("browser_process") { ] sources = [ - "autocomplete/brave_autocomplete_provider_client.cc", - "autocomplete/brave_autocomplete_provider_client.h", "autocomplete/brave_autocomplete_scheme_classifier.cc", "autocomplete/brave_autocomplete_scheme_classifier.h", "brave_shields/ad_block_pref_service_factory.cc", diff --git a/browser/autocomplete/brave_autocomplete_provider_client.cc b/browser/autocomplete/brave_autocomplete_provider_client.cc deleted file mode 100644 index eb7c62a84199..000000000000 --- a/browser/autocomplete/brave_autocomplete_provider_client.cc +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/autocomplete/brave_autocomplete_provider_client.h" - -#include "base/strings/utf_string_conversions.h" -#include "brave/common/webui_url_constants.h" -#include "chrome/common/webui_url_constants.h" - -BraveAutocompleteProviderClient::BraveAutocompleteProviderClient( - Profile* profile) : ChromeAutocompleteProviderClient(profile) { -} - -BraveAutocompleteProviderClient::~BraveAutocompleteProviderClient() { -} - -std::vector BraveAutocompleteProviderClient::GetBuiltinURLs() { - std::vector v = - ChromeAutocompleteProviderClient::GetBuiltinURLs(); - auto it = std::find(v.begin(), v.end(), - base::ASCIIToUTF16(chrome::kChromeUISyncInternalsHost)); - DCHECK(it != v.end()); - if (it != v.end()) { - *it = base::ASCIIToUTF16(kBraveUISyncHost); - } - return v; -} diff --git a/browser/autocomplete/brave_autocomplete_provider_client.h b/browser/autocomplete/brave_autocomplete_provider_client.h deleted file mode 100644 index dfe437b1852d..000000000000 --- a/browser/autocomplete/brave_autocomplete_provider_client.h +++ /dev/null @@ -1,26 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_AUTOCOMPLETE_BRAVE_AUTOCOMPLETE_PROVIDER_CLIENT_H_ -#define BRAVE_BROWSER_AUTOCOMPLETE_BRAVE_AUTOCOMPLETE_PROVIDER_CLIENT_H_ - -#include -#include - -#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h" - -class BraveAutocompleteProviderClient - : public ChromeAutocompleteProviderClient { - public: - explicit BraveAutocompleteProviderClient(Profile* profile); - ~BraveAutocompleteProviderClient() override; - - std::vector GetBuiltinURLs() override; - - private: - DISALLOW_COPY_AND_ASSIGN(BraveAutocompleteProviderClient); -}; - -#endif // BRAVE_BROWSER_AUTOCOMPLETE_BRAVE_AUTOCOMPLETE_PROVIDER_CLIENT_H_ diff --git a/browser/autocomplete/brave_autocomplete_provider_client_unittest.cc b/browser/autocomplete/brave_autocomplete_provider_client_unittest.cc deleted file mode 100644 index 16bcb5182088..000000000000 --- a/browser/autocomplete/brave_autocomplete_provider_client_unittest.cc +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/autocomplete/brave_autocomplete_provider_client.h" - -#include -#include -#include - -#include "base/strings/utf_string_conversions.h" -#include "brave/common/webui_url_constants.h" -#include "chrome/browser/prefs/browser_prefs.h" -#include "chrome/common/webui_url_constants.h" -#include "chrome/test/base/testing_profile.h" -#include "components/sync_preferences/testing_pref_service_syncable.h" -#include "content/public/test/fake_service_worker_context.h" -#include "content/public/test/browser_task_environment.h" -#include "testing/gtest/include/gtest/gtest.h" - -class BraveAutocompleteProviderClientUnitTest : public testing::Test { - public: - void SetUp() override { - profile_ = CreateProfile(); - client_ = - std::make_unique(profile_.get()); - } - - bool BuiltinExists(const base::string16& builtin) { - std::vector v = client_->GetBuiltinURLs(); - auto it = std::find(v.begin(), v.end(), builtin); - return it != v.end(); - } - - private: - std::unique_ptr CreateProfile() { - TestingProfile::Builder builder; - auto prefs = - std::make_unique(); - RegisterUserProfilePrefs(prefs->registry()); - builder.SetPrefService(std::move(prefs)); - return builder.Build(); - } - - content::BrowserTaskEnvironment task_environment_; - std::unique_ptr profile_; - std::unique_ptr client_; -}; - -TEST_F(BraveAutocompleteProviderClientUnitTest, - SyncURLSuggestedNotSyncInternal) { - ASSERT_FALSE( - BuiltinExists(base::ASCIIToUTF16(chrome::kChromeUISyncInternalsHost))); - ASSERT_TRUE(BuiltinExists(base::ASCIIToUTF16(kBraveUISyncHost))); -} diff --git a/browser/brave_content_browser_client_browsertest.cc b/browser/brave_content_browser_client_browsertest.cc index aa9dc4de21d1..ea3688a29d85 100644 --- a/browser/brave_content_browser_client_browsertest.cc +++ b/browser/brave_content_browser_client_browsertest.cc @@ -13,7 +13,6 @@ #include "brave/common/pref_names.h" #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_service.h" @@ -27,7 +26,6 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/prefs/pref_service.h" -#include "components/sync/driver/sync_driver_switches.h" #include "content/public/browser/navigation_entry.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" @@ -163,10 +161,6 @@ IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, CanLoadCustomBravePages) { "rewards", #endif }; -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (switches::IsSyncAllowedByFlag()) - pages.push_back(chrome::kChromeUISyncHost); -#endif std::vector schemes { "brave://", @@ -217,37 +211,6 @@ IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, CanLoadAboutHost) { } } -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, - RewriteChromeSyncInternals) { - std::vector schemes { - "brave://", - "chrome://", - }; - - for (const std::string& scheme : schemes) { - content::WebContents* contents = - browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL( - browser(), GURL(scheme + chrome::kChromeUISyncInternalsHost)); - if (switches::IsSyncAllowedByFlag()) - ASSERT_TRUE(WaitForLoadStop(contents)); - else - ASSERT_FALSE(WaitForLoadStop(contents)); - - EXPECT_STREQ(base::UTF16ToUTF8(browser()->location_bar_model() - ->GetFormattedFullURL()).c_str(), - "brave://sync"); - EXPECT_STREQ(contents->GetController().GetLastCommittedEntry() - ->GetVirtualURL().spec().c_str(), - "chrome://sync/"); - EXPECT_STREQ(contents->GetController().GetLastCommittedEntry() - ->GetURL().spec().c_str(), - "chrome://sync/"); - } -} -#endif - IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, RewriteMagnetURLURLBar) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); diff --git a/browser/brave_content_browser_client_unittest.cc b/browser/brave_content_browser_client_unittest.cc index 1921505442f2..3c3388c72dc6 100644 --- a/browser/brave_content_browser_client_unittest.cc +++ b/browser/brave_content_browser_client_unittest.cc @@ -78,17 +78,6 @@ TEST_F(BraveWalleBrowserClientUnitTest, using BraveContentBrowserClientTest = testing::Test; -TEST_F(BraveContentBrowserClientTest, ResolvesSync) { - GURL url("chrome://sync-internals/"); - ASSERT_TRUE(BraveContentBrowserClient::HandleURLOverrideRewrite( - &url, nullptr)); - ASSERT_STREQ(url.spec().c_str(), "chrome://sync/"); - - GURL url2("chrome://sync/"); - ASSERT_TRUE(BraveContentBrowserClient::HandleURLOverrideRewrite( - &url2, nullptr)); -} - TEST_F(BraveContentBrowserClientTest, ResolvesWelcomePage) { GURL url("chrome://welcome/"); ASSERT_TRUE( diff --git a/browser/brave_profile_prefs_browsertest.cc b/browser/brave_profile_prefs_browsertest.cc index 58ea8b98b1d7..d7c053b3f601 100644 --- a/browser/brave_profile_prefs_browsertest.cc +++ b/browser/brave_profile_prefs_browsertest.cc @@ -120,8 +120,6 @@ IN_PROC_BROWSER_TEST_F(BraveProfilePrefsBrowserTest, prefs::kSafeBrowsingExtendedReportingOptInAllowed)); EXPECT_FALSE(browser()->profile()->GetPrefs()->GetBoolean( prefs::kSearchSuggestEnabled)); - EXPECT_TRUE(browser()->profile()->GetPrefs()->GetBoolean( - syncer::prefs::kSyncManaged)); EXPECT_EQ(browser()->profile()->GetPrefs()->GetInteger( prefs::kNetworkPredictionOptions), chrome_browser_net::NETWORK_PREDICTION_NEVER); diff --git a/browser/brave_scheme_load_browsertest.cc b/browser/brave_scheme_load_browsertest.cc index 47c67b40df90..4e03f0868c6e 100644 --- a/browser/brave_scheme_load_browsertest.cc +++ b/browser/brave_scheme_load_browsertest.cc @@ -250,11 +250,6 @@ IN_PROC_BROWSER_TEST_F(BraveSchemeLoadBrowserTest, TestURLIsNotLoadedInPrivateWindow("brave://settings"); } -IN_PROC_BROWSER_TEST_F(BraveSchemeLoadBrowserTest, - SyncPageIsNotAllowedInPrivateWindow) { - TestURLIsNotLoadedInPrivateWindow("brave://sync"); -} - IN_PROC_BROWSER_TEST_F(BraveSchemeLoadBrowserTest, RewardsPageIsNotAllowedInPrivateWindow) { TestURLIsNotLoadedInPrivateWindow("brave://rewards"); diff --git a/browser/extensions/BUILD.gn b/browser/extensions/BUILD.gn index c1c219170a18..48a542735159 100644 --- a/browser/extensions/BUILD.gn +++ b/browser/extensions/BUILD.gn @@ -1,7 +1,6 @@ import("//brave/browser/tor/buildflags/buildflags.gni") import("//brave/components/binance/browser/buildflags/buildflags.gni") import("//brave/components/brave_rewards/browser/buildflags/buildflags.gni") -import("//brave/components/brave_sync/buildflags/buildflags.gni") import("//brave/components/brave_wallet/browser/buildflags/buildflags.gni") import("//brave/components/brave_wayback_machine/buildflags/buildflags.gni") import("//brave/components/brave_webtorrent/browser/buildflags/buildflags.gni") @@ -112,20 +111,6 @@ source_set("extensions") { "//brave/components/brave_rewards/resources/extension:static_resources", ] } - if (enable_brave_sync) { - sources += [ - "api/brave_sync_api.cc", - "api/brave_sync_api.h", - "api/brave_sync_event_router.cc", - "api/brave_sync_event_router.h", - ] - - deps += [ - "//brave/components/brave_sync", - "//brave/components/brave_sync:generated_resources", - "//brave/components/brave_sync:static_resources", - ] - } if (enable_brave_webtorrent) { deps += [ "//brave/components/brave_webtorrent/browser", diff --git a/browser/extensions/api/brave_sync_api.cc b/browser/extensions/api/brave_sync_api.cc deleted file mode 100644 index b4960052f2cd..000000000000 --- a/browser/extensions/api/brave_sync_api.cc +++ /dev/null @@ -1,201 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/extensions/api/brave_sync_api.h" - -#include -#include -#include -#include - -#include "brave/common/extensions/api/brave_sync.h" -#include "brave/components/brave_sync/brave_sync_service.h" -#include "brave/components/brave_sync/client/brave_sync_client.h" -#include "brave/components/brave_sync/client/client_ext_impl_data.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/public/brave_profile_sync_service.h" -#include "brave/components/brave_sync/values_conv.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" - -using brave_sync::BraveProfileSyncService; -using brave_sync::BraveSyncService; -using content::BrowserContext; - -namespace extensions { -namespace api { - -namespace { - -BraveProfileSyncService* GetProfileSyncService( - BrowserContext* browser_context) { - return static_cast( - ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile( - Profile::FromBrowserContext(browser_context))); -} - -BraveSyncService* GetSyncService(BrowserContext* browser_context) { - return GetProfileSyncService(browser_context)->GetSyncService(); -} - -} // namespace -ExtensionFunction::ResponseAction BraveSyncGetInitDataFunction::Run() { - std::unique_ptr params( - brave_sync::GetInitData::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient()->sync_message_handler()->OnGetInitData( - params->sync_version); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncSyncSetupErrorFunction::Run() { - std::unique_ptr params( - brave_sync::SyncSetupError::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient()->sync_message_handler()->OnSyncSetupError( - params->error); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncSyncDebugFunction::Run() { - std::unique_ptr params( - brave_sync::SyncDebug::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient()->sync_message_handler()->OnSyncDebug( - params->message); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncSaveInitDataFunction::Run() { - std::unique_ptr params( - brave_sync::SaveInitData::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient()->sync_message_handler()->OnSaveInitData( - params->seed ? *params->seed : std::vector(), - params->device_id ? *params->device_id : std::vector(), - params->device_id_v2 ? *params->device_id_v2 : std::string()); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncSyncReadyFunction::Run() { - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient()->sync_message_handler()->OnSyncReady(); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncGetExistingObjectsFunction::Run() { - std::unique_ptr params( - brave_sync::GetExistingObjects::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - auto records = std::make_unique>(); - ::brave_sync::ConvertSyncRecords(params->records, records.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient() - ->sync_message_handler() - ->OnGetExistingObjects( - params->category_name, std::move(records), - base::Time::FromJsTime(params->last_record_timestamp), - params->is_truncated); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncResolvedSyncRecordsFunction::Run() { - std::unique_ptr params( - brave_sync::ResolvedSyncRecords::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - auto records = std::make_unique>(); - ::brave_sync::ConvertSyncRecords(params->records, records.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient() - ->sync_message_handler() - ->OnResolvedSyncRecords(params->category_name, std::move(records)); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -BraveSyncSaveBookmarksBaseOrderFunction::Run() { - std::unique_ptr params( - brave_sync::SaveBookmarksBaseOrder::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient() - ->sync_message_handler() - ->OnSaveBookmarksBaseOrder(params->order); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -BraveSyncOnCompactCompleteFunction::Run() { - std::unique_ptr params( - brave_sync::OnCompactComplete::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient() - ->sync_message_handler() - ->OnCompactComplete(params->category_name); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -BraveSyncOnRecordsSentFunction::Run() { - std::unique_ptr params( - brave_sync::OnRecordsSent::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - auto records = std::make_unique>(); - ::brave_sync::ConvertSyncRecords(params->records, records.get()); - - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient() - ->sync_message_handler() - ->OnRecordsSent(params->category_name, std::move(records)); - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction BraveSyncExtensionInitializedFunction::Run() { - // Also inform sync client extension started - BraveSyncService* sync_service = GetSyncService(browser_context()); - DCHECK(sync_service); - sync_service->GetBraveSyncClient()->OnExtensionInitialized(); - - return RespondNow(NoArguments()); -} - -} // namespace api -} // namespace extensions diff --git a/browser/extensions/api/brave_sync_api.h b/browser/extensions/api/brave_sync_api.h deleted file mode 100644 index c3ff66630ef5..000000000000 --- a/browser/extensions/api/brave_sync_api.h +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_EXTENSIONS_API_BRAVE_SYNC_API_H_ -#define BRAVE_BROWSER_EXTENSIONS_API_BRAVE_SYNC_API_H_ - -#include "extensions/browser/extension_function.h" - -namespace extensions { -namespace api { - -class BraveSyncGetInitDataFunction : public ExtensionFunction { - ~BraveSyncGetInitDataFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.getInitData", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncSyncSetupErrorFunction : public ExtensionFunction { - ~BraveSyncSyncSetupErrorFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.syncSetupError", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncSyncDebugFunction : public ExtensionFunction { - ~BraveSyncSyncDebugFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.syncDebug", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncSaveInitDataFunction : public ExtensionFunction { - ~BraveSyncSaveInitDataFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.saveInitData", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncSyncReadyFunction : public ExtensionFunction { - ~BraveSyncSyncReadyFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.syncReady", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncGetExistingObjectsFunction : public ExtensionFunction { - ~BraveSyncGetExistingObjectsFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.getExistingObjects", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncResolvedSyncRecordsFunction : public ExtensionFunction { - ~BraveSyncResolvedSyncRecordsFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.resolvedSyncRecords", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncSaveBookmarksBaseOrderFunction : public ExtensionFunction { - ~BraveSyncSaveBookmarksBaseOrderFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.saveBookmarksBaseOrder", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncOnCompactCompleteFunction : public ExtensionFunction { - ~BraveSyncOnCompactCompleteFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.onCompactComplete", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncOnRecordsSentFunction : public ExtensionFunction { - ~BraveSyncOnRecordsSentFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.onRecordsSent", UNKNOWN) - ResponseAction Run() override; -}; - -class BraveSyncExtensionInitializedFunction : public ExtensionFunction { - ~BraveSyncExtensionInitializedFunction() override {} - DECLARE_EXTENSION_FUNCTION("braveSync.extensionInitialized", UNKNOWN) - ResponseAction Run() override; -}; - -} // namespace api -} // namespace extensions - -#endif // BRAVE_BROWSER_EXTENSIONS_API_BRAVE_SYNC_API_H_ diff --git a/browser/extensions/api/brave_sync_event_router.cc b/browser/extensions/api/brave_sync_event_router.cc deleted file mode 100644 index da2579f12ffe..000000000000 --- a/browser/extensions/api/brave_sync_event_router.cc +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/extensions/api/brave_sync_event_router.h" - -#include -#include - -#include "brave/common/extensions/api/brave_sync.h" -#include "chrome/browser/profiles/profile.h" -#include "extensions/browser/extension_event_histogram_value.h" - -using extensions::api::brave_sync::RecordAndExistingObject; - -namespace extensions { - -BraveSyncEventRouter::BraveSyncEventRouter(Profile* profile) : - event_router_(EventRouter::Get(profile)) { -} - -BraveSyncEventRouter::~BraveSyncEventRouter() {} - -void BraveSyncEventRouter::GotInitData( - const brave_sync::Uint8Array& seed, - const brave_sync::Uint8Array& device_id, - const extensions::api::brave_sync::Config& config, - const std::string& device_id_v2) { - const std::vector arg_seed(seed.begin(), seed.end()); - const std::vector arg_device_id(device_id.begin(), device_id.end()); - - std::unique_ptr args( - extensions::api::brave_sync::OnGotInitData::Create(arg_seed, - arg_device_id, config, - device_id_v2) - .release()); - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::OnGotInitData::kEventName, - std::move(args))); - event_router_->BroadcastEvent(std::move(event)); -} - -void BraveSyncEventRouter::FetchSyncRecords( - const std::vector& category_names, - const base::Time& startAt, - const int max_records) { - std::unique_ptr args( - extensions::api::brave_sync::OnFetchSyncRecords::Create(category_names, - startAt.ToJsTime(), static_cast(max_records)) - .release()); - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::OnFetchSyncRecords::kEventName, - std::move(args))); - event_router_->BroadcastEvent(std::move(event)); -} - -void BraveSyncEventRouter::ResolveSyncRecords( - const std::string& category_name, - const std::vector& records_and_existing_objects) { - for (const auto & entry : records_and_existing_objects) { - DCHECK(!entry.server_record.object_data.empty()); - DCHECK(!entry.local_record || - (entry.local_record->object_data == "bookmark" || - entry.local_record->object_data == "device" || - entry.local_record->object_data == "historySite" || - entry.local_record->object_data == "siteSetting")); - } - - std::unique_ptr args( - extensions::api::brave_sync::OnResolveSyncRecords::Create( - category_name, - records_and_existing_objects).release()); - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::OnResolveSyncRecords::kEventName, - std::move(args))); - - event_router_->BroadcastEvent(std::move(event)); -} - -void BraveSyncEventRouter::SendSyncRecords( - const std::string& category_name, - const std::vector& records) { - std::unique_ptr args( - extensions::api::brave_sync::OnSendSyncRecords::Create( - category_name, - records).release()); - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::OnSendSyncRecords::kEventName, - std::move(args))); - - event_router_->BroadcastEvent(std::move(event)); -} - -void BraveSyncEventRouter::SendGetBookmarksBaseOrder( - const std::string& device_id, - const std::string& platform) { - std::unique_ptr args( - extensions::api::brave_sync::OnSendGetBookmarksBaseOrder::Create( - device_id, platform).release()); - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::OnSendGetBookmarksBaseOrder::kEventName, - std::move(args))); - - event_router_->BroadcastEvent(std::move(event)); -} - -void BraveSyncEventRouter::SendCompact( - const std::string& category_name) { - std::unique_ptr args( - extensions::api::brave_sync::SendCompact::Create( - category_name).release()); - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::SendCompact::kEventName, - std::move(args))); - - event_router_->BroadcastEvent(std::move(event)); -} - -void BraveSyncEventRouter::LoadClient() { - std::unique_ptr args( - extensions::api::brave_sync::OnLoadClient::Create() - .release()); - - std::unique_ptr event( - new Event(extensions::events::FOR_TEST, - extensions::api::brave_sync::OnLoadClient::kEventName, - std::move(args))); - event_router_->BroadcastEvent(std::move(event)); -} - -} // namespace extensions diff --git a/browser/extensions/api/brave_sync_event_router.h b/browser/extensions/api/brave_sync_event_router.h deleted file mode 100644 index 9ab409ee8dd8..000000000000 --- a/browser/extensions/api/brave_sync_event_router.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_EXTENSIONS_API_BRAVE_SYNC_EVENT_ROUTER_H_ -#define BRAVE_BROWSER_EXTENSIONS_API_BRAVE_SYNC_EVENT_ROUTER_H_ - -#include -#include -#include "extensions/browser/event_router.h" - -class Profile; - -namespace extensions { -namespace api { -namespace brave_sync { -struct SyncRecord; -struct Config; -struct RecordAndExistingObject; -} // namespace brave_sync -} // namespace api -} // namespace extensions - -using extensions::api::brave_sync::RecordAndExistingObject; - -namespace brave_sync { -using Uint8Array = std::vector; -} - -namespace extensions { - -class BraveSyncEventRouter { - public: - explicit BraveSyncEventRouter(Profile* profile); - ~BraveSyncEventRouter(); - - void GotInitData(const brave_sync::Uint8Array& seed, - const brave_sync::Uint8Array& device_id, - const extensions::api::brave_sync::Config& config, - const std::string& device_id_v2); - - void FetchSyncRecords( - const std::vector& category_names, - const base::Time& startAt, - const int max_records); - - void ResolveSyncRecords(const std::string &category_name, - const std::vector& records_and_existing_objects); - - void SendSyncRecords(const std::string& category_name, - const std::vector& records); - - void SendGetBookmarksBaseOrder(const std::string& device_id, - const std::string& platform); - - void SendCompact(const std::string& category_name); - - void LoadClient(); - - private: - EventRouter* event_router_; -}; - -} // namespace extensions - -#endif // BRAVE_BROWSER_EXTENSIONS_API_BRAVE_SYNC_EVENT_ROUTER_H_ diff --git a/browser/extensions/brave_component_extension_resource_manager.cc b/browser/extensions/brave_component_extension_resource_manager.cc index a034b38ca85d..a5011af83414 100644 --- a/browser/extensions/brave_component_extension_resource_manager.cc +++ b/browser/extensions/brave_component_extension_resource_manager.cc @@ -8,7 +8,6 @@ #include "brave/components/brave_extension/grit/brave_extension_generated_map.h" #include "brave/components/brave_extension/grit/brave_extension_resources_map.h" #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/brave_webtorrent/grit/brave_webtorrent_generated_map.h" #include "brave/components/brave_webtorrent/grit/brave_webtorrent_resources_map.h" @@ -17,11 +16,6 @@ #include "brave/components/brave_rewards/resources/extension/grit/brave_rewards_panel_generated_map.h" #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "brave/components/brave_sync/grit/brave_sync_generated_map.h" -#include "brave/components/brave_sync/grit/brave_sync_resources_map.h" -#endif - namespace extensions { BraveComponentExtensionResourceManager:: @@ -42,15 +36,6 @@ BraveComponentExtensionResourceManager() { kBraveRewardsPanelGenerated, kBraveRewardsPanelGeneratedSize); #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - AddComponentResourceEntries( - kBraveSyncResources, - kBraveSyncResourcesSize); - - AddComponentResourceEntries( - kBraveSyncGenerated, - kBraveSyncGeneratedSize); -#endif AddComponentResourceEntries( kBraveWebtorrentResources, diff --git a/browser/extensions/brave_extension_provider.cc b/browser/extensions/brave_extension_provider.cc index ebef3ad13cee..f37b7622bcfa 100644 --- a/browser/extensions/brave_extension_provider.cc +++ b/browser/extensions/brave_extension_provider.cc @@ -73,8 +73,7 @@ bool BraveExtensionProvider::UserMayLoad(const Extension* extension, bool BraveExtensionProvider::MustRemainInstalled(const Extension* extension, base::string16* error) const { return extension->id() == brave_extension_id || - extension->id() == brave_rewards_extension_id || - extension->id() == brave_sync_extension_id; + extension->id() == brave_rewards_extension_id; } } // namespace extensions diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index 45cbeb701afb..7099fccef85f 100644 --- a/browser/ui/BUILD.gn +++ b/browser/ui/BUILD.gn @@ -1,7 +1,6 @@ import("//brave/browser/translate/buildflags/buildflags.gni") import("//brave/build/config.gni") import("//brave/components/brave_rewards/browser/buildflags/buildflags.gni") -import("//brave/components/brave_sync/buildflags/buildflags.gni") import("//brave/components/brave_wallet/browser/buildflags/buildflags.gni") import("//brave/components/brave_wayback_machine/buildflags/buildflags.gni") import("//brave/components/speedreader/buildflags.gni") @@ -43,13 +42,6 @@ source_set("ui") { "webui/brave_webui_source.h", ] - if (enable_brave_sync) { - sources += [ - "webui/sync/sync_ui.cc", - "webui/sync/sync_ui.h", - ] - } - if (!is_android) { sources += [ "bookmark/brave_bookmark_tab_helper.cc", @@ -204,7 +196,6 @@ source_set("ui") { "//brave/components/brave_rewards/browser", "//brave/components/brave_rewards/resources", "//brave/components/brave_shields/browser", - "//brave/components/brave_sync/buildflags:buildflags", "//brave/components/brave_wallet/browser/buildflags:buildflags", "//brave/components/brave_wayback_machine:buildflags", "//brave/components/brave_welcome_ui:generated_resources", @@ -239,15 +230,6 @@ source_set("ui") { ] } - if (enable_brave_sync) { - deps += [ - "//brave/components/brave_sync", - "//brave/components/brave_sync:generated_resources", - "//brave/components/brave_sync:static_resources", - "//components/sync/driver:driver", - ] - } - if (enable_brave_wayback_machine) { deps += [ "//brave/components/brave_wayback_machine" ] diff --git a/browser/ui/brave_browser_command_controller.cc b/browser/ui/brave_browser_command_controller.cc index 41f089e87baf..6b9ff1c8ae1e 100644 --- a/browser/ui/brave_browser_command_controller.cc +++ b/browser/ui/brave_browser_command_controller.cc @@ -14,7 +14,6 @@ #include "brave/browser/ui/browser_commands.h" #include "brave/common/pref_names.h" #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/brave_wallet/browser/buildflags/buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/profiles/profile.h" @@ -23,10 +22,6 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/prefs/pref_service.h" -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "components/sync/driver/sync_driver_switches.h" -#endif - namespace { bool IsBraveCommands(int id) { @@ -102,7 +97,7 @@ bool BraveBrowserCommandController::UpdateCommandEnabled(int id, bool state) { } void BraveBrowserCommandController::InitBraveCommandState() { - // Sync & Rewards pages doesn't work on tor(guest) session. + // Rewards pages doesn't work on tor(guest) session. // They also doesn't work on private window but they are redirected // to normal window in this case. const bool is_guest_session = browser_->profile()->IsGuestSession(); @@ -112,10 +107,6 @@ void BraveBrowserCommandController::InitBraveCommandState() { #endif #if BUILDFLAG(BRAVE_WALLET_ENABLED) UpdateCommandForBraveWallet(); -#endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (switches::IsSyncAllowedByFlag()) - UpdateCommandForBraveSync(); #endif } UpdateCommandForBraveAdblock(); @@ -150,10 +141,6 @@ void BraveBrowserCommandController::UpdateCommandForTor() { } #endif -void BraveBrowserCommandController::UpdateCommandForBraveSync() { - UpdateCommandEnabled(IDC_SHOW_BRAVE_SYNC, true); -} - void BraveBrowserCommandController::UpdateCommandForBraveWallet() { UpdateCommandEnabled(IDC_SHOW_BRAVE_WALLET, true); } @@ -200,9 +187,6 @@ bool BraveBrowserCommandController::ExecuteBraveCommandWithDisposition( case IDC_NEW_TOR_CONNECTION_FOR_SITE: brave::NewTorConnectionForSite(browser_); break; - case IDC_SHOW_BRAVE_SYNC: - brave::ShowBraveSync(browser_); - break; case IDC_SHOW_BRAVE_WALLET: brave::ShowBraveWallet(browser_); break; diff --git a/browser/ui/brave_browser_command_controller_browsertest.cc b/browser/ui/brave_browser_command_controller_browsertest.cc index aaeeaf2766f3..8ce47efcea59 100644 --- a/browser/ui/brave_browser_command_controller_browsertest.cc +++ b/browser/ui/brave_browser_command_controller_browsertest.cc @@ -10,7 +10,6 @@ #include "brave/browser/ui/brave_browser_command_controller.h" #include "brave/browser/ui/browser_commands.h" #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/brave_wallet/browser/buildflags/buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/chrome_notification_types.h" @@ -19,7 +18,6 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/test/base/in_process_browser_test.h" -#include "components/sync/driver/sync_driver_switches.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" @@ -53,15 +51,6 @@ IN_PROC_BROWSER_TEST_F(BraveBrowserCommandControllerTest, command_controller->IsCommandEnabled(IDC_NEW_OFFTHERECORD_WINDOW_TOR)); #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (switches::IsSyncAllowedByFlag()) - EXPECT_TRUE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); - else - EXPECT_FALSE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); -#else - EXPECT_FALSE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); -#endif - #if BUILDFLAG(BRAVE_WALLET_ENABLED) EXPECT_TRUE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_WALLET)); #else @@ -89,13 +78,6 @@ IN_PROC_BROWSER_TEST_F(BraveBrowserCommandControllerTest, command_controller->IsCommandEnabled(IDC_NEW_OFFTHERECORD_WINDOW_TOR)); #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (switches::IsSyncAllowedByFlag()) - EXPECT_TRUE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); - else - EXPECT_FALSE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); -#endif - #if BUILDFLAG(BRAVE_WALLET_ENABLED) EXPECT_TRUE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_WALLET)); #endif @@ -136,10 +118,6 @@ IN_PROC_BROWSER_TEST_F(BraveBrowserCommandControllerTest, command_controller->IsCommandEnabled(IDC_NEW_OFFTHERECORD_WINDOW_TOR)); #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - EXPECT_FALSE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); -#endif - #if BUILDFLAG(BRAVE_WALLET_ENABLED) EXPECT_FALSE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_WALLET)); #endif @@ -177,13 +155,6 @@ IN_PROC_BROWSER_TEST_F(BraveBrowserCommandControllerTest, command_controller->IsCommandEnabled(IDC_NEW_OFFTHERECORD_WINDOW_TOR)); #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (switches::IsSyncAllowedByFlag()) - EXPECT_TRUE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); - else - EXPECT_FALSE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_SYNC)); -#endif - #if BUILDFLAG(BRAVE_WALLET_ENABLED) EXPECT_TRUE(command_controller->IsCommandEnabled(IDC_SHOW_BRAVE_WALLET)); #endif diff --git a/browser/ui/brave_pages.cc b/browser/ui/brave_pages.cc index 4c0ad3777d58..0b41e1c57313 100644 --- a/browser/ui/brave_pages.cc +++ b/browser/ui/brave_pages.cc @@ -34,12 +34,6 @@ void ShowWebcompatReporter(Browser* browser) { OpenWebcompatReporterDialog(web_contents); } -void ShowBraveSync(Browser* browser) { - ShowSingletonTabOverwritingNTP( - browser, - GetSingletonTabNavigateParams(browser, GURL(kBraveUISyncURL))); -} - void ShowBraveWallet(Browser* browser) { ShowSingletonTabOverwritingNTP( browser, diff --git a/browser/ui/brave_pages.h b/browser/ui/brave_pages.h index 4a5f499bb186..1f50c81f56b9 100644 --- a/browser/ui/brave_pages.h +++ b/browser/ui/brave_pages.h @@ -13,7 +13,6 @@ namespace brave { void ShowBraveAdblock(Browser* browser); void ShowWebcompatReporter(Browser* browser); void ShowBraveRewards(Browser* browser); -void ShowBraveSync(Browser* browser); void ShowBraveWallet(Browser* browser); void ShowExtensionSettings(Browser* browser); diff --git a/browser/ui/toolbar/brave_app_menu_model.cc b/browser/ui/toolbar/brave_app_menu_model.cc index b8376bed7c15..3963bf234687 100644 --- a/browser/ui/toolbar/brave_app_menu_model.cc +++ b/browser/ui/toolbar/brave_app_menu_model.cc @@ -76,13 +76,6 @@ void BraveAppMenuModel::InsertBraveMenuItems() { IDS_SHOW_BRAVE_WALLET); } - // Insert sync menu - if (IsCommandIdEnabled(IDC_SHOW_BRAVE_SYNC)) { - InsertItemWithStringIdAt(GetIndexOfBraveSyncItem(), - IDC_SHOW_BRAVE_SYNC, - IDS_SHOW_BRAVE_SYNC); - } - // Insert adblock menu at last. Assumed this is always enabled. DCHECK(IsCommandIdEnabled(IDC_SHOW_BRAVE_ADBLOCK)); InsertItemWithStringIdAt(GetIndexOfBraveAdBlockItem(), @@ -110,10 +103,6 @@ void BraveAppMenuModel::InsertBraveMenuItems() { int BraveAppMenuModel::GetIndexOfBraveAdBlockItem() const { // Insert as a last item in second section. int adblock_item_index = -1; - adblock_item_index = GetIndexOfCommandId(IDC_SHOW_BRAVE_SYNC); - if (adblock_item_index != -1) - return adblock_item_index + 1; - adblock_item_index = GetIndexOfCommandId(IDC_MANAGE_EXTENSIONS); if (adblock_item_index != -1) return adblock_item_index + 1; @@ -143,20 +132,3 @@ int BraveAppMenuModel::GetIndexOfBraveRewardsItem() const { DCHECK_NE(-1, rewards_index) << "No download item"; return rewards_index; } - -int BraveAppMenuModel::GetIndexOfBraveSyncItem() const { - // Insert sync menu under extensions menu. If extensions menu is not - // available, check above items. - int sync_index = -1; - sync_index = GetIndexOfCommandId(IDC_MANAGE_EXTENSIONS); - if (sync_index != -1) - return sync_index + 1; - - sync_index = GetIndexOfCommandId(IDC_SHOW_BRAVE_WALLET); - if (sync_index != -1) - return sync_index + 1; - - sync_index = GetIndexOfCommandId(IDC_SHOW_DOWNLOADS); - DCHECK_NE(-1, sync_index) << "No download item"; - return sync_index + 1; -} diff --git a/browser/ui/toolbar/brave_app_menu_model_browsertest.cc b/browser/ui/toolbar/brave_app_menu_model_browsertest.cc index 2eb93b8e80bf..749dbcb18f56 100644 --- a/browser/ui/toolbar/brave_app_menu_model_browsertest.cc +++ b/browser/ui/toolbar/brave_app_menu_model_browsertest.cc @@ -13,7 +13,6 @@ #include "brave/browser/ui/brave_browser_command_controller.h" #include "brave/browser/ui/browser_commands.h" #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/brave_wallet/browser/buildflags/buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/chrome_notification_types.h" @@ -23,7 +22,6 @@ #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/test/base/in_process_browser_test.h" -#include "components/sync/driver/sync_driver_switches.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" @@ -78,9 +76,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { IDC_SHOW_BRAVE_WALLET, #endif IDC_MANAGE_EXTENSIONS, -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - IDC_SHOW_BRAVE_SYNC, -#endif IDC_SHOW_BRAVE_ADBLOCK, IDC_ADD_NEW_PROFILE, IDC_OPEN_GUEST_PROFILE, @@ -89,16 +84,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { std::vector commands_disabled_for_normal_profile = { IDC_NEW_TOR_CONNECTION_FOR_SITE, }; -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (!switches::IsSyncAllowedByFlag()) { - commands_in_order_for_normal_profile.erase( - std::remove(commands_in_order_for_normal_profile.begin(), - commands_in_order_for_normal_profile.end(), - IDC_SHOW_BRAVE_SYNC), - commands_in_order_for_normal_profile.end()); - commands_disabled_for_normal_profile.push_back(IDC_SHOW_BRAVE_SYNC); - } -#endif CheckCommandsAreInOrderInMenuModel(browser(), commands_in_order_for_normal_profile); CheckCommandsAreDisabledInMenuModel(browser(), @@ -121,9 +106,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { IDC_SHOW_BRAVE_WALLET, #endif IDC_MANAGE_EXTENSIONS, -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - IDC_SHOW_BRAVE_SYNC, -#endif IDC_SHOW_BRAVE_ADBLOCK, IDC_ADD_NEW_PROFILE, IDC_OPEN_GUEST_PROFILE, @@ -133,16 +115,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { IDC_NEW_TOR_CONNECTION_FOR_SITE, IDC_RECENT_TABS_MENU, }; -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (!switches::IsSyncAllowedByFlag()) { - commands_in_order_for_private_profile.erase( - std::remove(commands_in_order_for_private_profile.begin(), - commands_in_order_for_private_profile.end(), - IDC_SHOW_BRAVE_SYNC), - commands_in_order_for_private_profile.end()); - commands_disabled_for_private_profile.push_back(IDC_SHOW_BRAVE_SYNC); - } -#endif CheckCommandsAreInOrderInMenuModel(private_browser, commands_in_order_for_private_profile); CheckCommandsAreDisabledInMenuModel(private_browser, @@ -187,9 +159,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { IDC_SHOW_BRAVE_WALLET, #endif IDC_MANAGE_EXTENSIONS, -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - IDC_SHOW_BRAVE_SYNC, -#endif IDC_ADD_NEW_PROFILE, IDC_OPEN_GUEST_PROFILE, }; @@ -224,9 +193,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { IDC_SHOW_DOWNLOADS, #if BUILDFLAG(BRAVE_WALLET_ENABLED) IDC_SHOW_BRAVE_WALLET, -#endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - IDC_SHOW_BRAVE_SYNC, #endif IDC_SHOW_BRAVE_ADBLOCK, IDC_ADD_NEW_PROFILE, @@ -236,16 +202,6 @@ IN_PROC_BROWSER_TEST_F(BraveAppMenuBrowserTest, MenuOrderTest) { std::vector commands_disabled_for_tor_profile = { IDC_RECENT_TABS_MENU, }; -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - if (!switches::IsSyncAllowedByFlag()) { - commands_in_order_for_tor_profile.erase( - std::remove(commands_in_order_for_tor_profile.begin(), - commands_in_order_for_tor_profile.end(), - IDC_SHOW_BRAVE_SYNC), - commands_in_order_for_tor_profile.end()); - commands_disabled_for_tor_profile.push_back(IDC_SHOW_BRAVE_SYNC); - } -#endif CheckCommandsAreInOrderInMenuModel(tor_browser, commands_in_order_for_tor_profile); CheckCommandsAreDisabledInMenuModel(tor_browser, diff --git a/browser/ui/webui/brave_web_ui_controller_factory.cc b/browser/ui/webui/brave_web_ui_controller_factory.cc index 2c3eaff8b52b..1f0adf5dfd4d 100644 --- a/browser/ui/webui/brave_web_ui_controller_factory.cc +++ b/browser/ui/webui/brave_web_ui_controller_factory.cc @@ -16,7 +16,6 @@ #include "brave/common/pref_names.h" #include "brave/common/webui_url_constants.h" #include "brave/components/brave_rewards/browser/buildflags/buildflags.h" -#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/brave_wallet/browser/buildflags/buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" @@ -38,11 +37,6 @@ #include "brave/browser/ui/webui/brave_wallet_ui.h" #endif -#if BUILDFLAG(ENABLE_BRAVE_SYNC) -#include "brave/browser/ui/webui/sync/sync_ui.h" -#include "components/sync/driver/sync_driver_switches.h" -#endif - using content::WebUI; using content::WebUIController; @@ -70,11 +64,6 @@ WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { } else if (host == kWalletHost) { return new BraveWalletUI(web_ui, url.host()); #endif // BUILDFLAG(BRAVE_WALLET_ENABLED) -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - } else if (host == kBraveUISyncHost && - switches::IsSyncAllowedByFlag()) { - return new SyncUI(web_ui, url.host()); -#endif // BUILDFLAG(ENABLE_BRAVE_SYNC) #if BUILDFLAG(BRAVE_REWARDS_ENABLED) } else if (host == kRewardsPageHost) { return new BraveRewardsPageUI(web_ui, url.host()); @@ -114,10 +103,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, #endif url.host_piece() == kWelcomeHost || url.host_piece() == chrome::kChromeUIWelcomeURL || -#if BUILDFLAG(ENABLE_BRAVE_SYNC) - (url.host_piece() == kBraveUISyncHost && - switches::IsSyncAllowedByFlag()) || -#endif url.host_piece() == chrome::kChromeUINewTabHost || url.host_piece() == chrome::kChromeUISettingsHost) { return &NewWebUI; diff --git a/browser/ui/webui/sync/sync_ui.cc b/browser/ui/webui/sync/sync_ui.cc deleted file mode 100644 index 53aa0ad1680c..000000000000 --- a/browser/ui/webui/sync/sync_ui.cc +++ /dev/null @@ -1,273 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/ui/webui/sync/sync_ui.h" - -#include -#include - -#include "base/bind.h" -#include "base/memory/weak_ptr.h" -#include "brave/common/webui_url_constants.h" -#include "brave/components/brave_sync/brave_sync_service.h" -#include "brave/components/brave_sync/brave_sync_service_observer.h" -#include "brave/components/brave_sync/grit/brave_sync_generated_map.h" -#include "brave/components/brave_sync/grit/brave_sync_resources.h" -#include "brave/components/brave_sync/public/brave_profile_sync_service.h" -#include "brave/components/brave_sync/settings.h" -#include "brave/components/brave_sync/sync_devices.h" -#include "brave/components/brave_sync/values_conv.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/web_ui_message_handler.h" - -using content::WebUIMessageHandler; - -namespace { - -// The handler for Javascript messages for Brave about: pages -class SyncUIDOMHandler : public WebUIMessageHandler, - public brave_sync::BraveSyncServiceObserver { - public: - SyncUIDOMHandler(); - ~SyncUIDOMHandler() override; - - void Init(); - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - private: - void SetupSyncHaveCode(const base::ListValue* args); - void SetupSyncNewToSync(const base::ListValue* args); - void PageLoaded(const base::ListValue* args); - void NeedSyncWords(const base::ListValue* args); - void NeedSyncQRcode(const base::ListValue* args); - void SyncBookmarks(const base::ListValue* args); - void SyncBrowsingHistory(const base::ListValue* args); - void SyncSavedSiteSettings(const base::ListValue* args); - void DeleteDevice(const base::ListValue* args); - void ResetSync(const base::ListValue* args); - - void OnSyncSetupError(brave_sync::BraveSyncService* sync_service, - const std::string& error) override; - void OnSyncStateChanged(brave_sync::BraveSyncService *sync_service) override; - void OnHaveSyncWords(brave_sync::BraveSyncService *sync_service, - const std::string& sync_words) override; - - // this should grab actual data from controller and update the page - void LoadSyncSettingsView(); - - // Move to observer - void GetSettingsAndDevicesComplete( - std::unique_ptr settings, - std::unique_ptr devices); - - brave_sync::BraveSyncService* sync_service_ = nullptr; // NOT OWNED - - base::WeakPtrFactory weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(SyncUIDOMHandler); -}; - -SyncUIDOMHandler::SyncUIDOMHandler() : weak_ptr_factory_(this) {} - -SyncUIDOMHandler::~SyncUIDOMHandler() { - if (sync_service_) - sync_service_->RemoveObserver(this); -} - -void SyncUIDOMHandler::RegisterMessages() { - this->web_ui()->RegisterMessageCallback("setupSyncHaveCode", - base::Bind(&SyncUIDOMHandler::SetupSyncHaveCode, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("setupSyncNewToSync", - base::Bind(&SyncUIDOMHandler::SetupSyncNewToSync, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("pageLoaded", - base::Bind(&SyncUIDOMHandler::PageLoaded, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("needSyncWords", - base::Bind(&SyncUIDOMHandler::NeedSyncWords, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("needSyncQRcode", - base::Bind(&SyncUIDOMHandler::NeedSyncQRcode, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("syncBookmarks", - base::Bind(&SyncUIDOMHandler::SyncBookmarks, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("syncBrowsingHistory", - base::Bind(&SyncUIDOMHandler::SyncBrowsingHistory, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("syncSavedSiteSettings", - base::Bind(&SyncUIDOMHandler::SyncSavedSiteSettings, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("deleteDevice", - base::Bind(&SyncUIDOMHandler::DeleteDevice, - base::Unretained(this))); - - this->web_ui()->RegisterMessageCallback("resetSync", - base::Bind(&SyncUIDOMHandler::ResetSync, - base::Unretained(this))); -} - -void SyncUIDOMHandler::Init() { - Profile* profile = Profile::FromWebUI(web_ui()); - auto* profile_sync_service = - static_cast( - ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile( - profile)); - - sync_service_ = profile_sync_service->GetSyncService(); - if (sync_service_) - sync_service_->AddObserver(this); -} - -void SyncUIDOMHandler::SetupSyncHaveCode(const base::ListValue* args) { - DCHECK(sync_service_); - std::string sync_words, device_name; - if (!args->GetString(0, &sync_words) || !args->GetString(1, &device_name)) - // TODO(bridiver) - does this need to report an error? - return; - - sync_service_->OnSetupSyncHaveCode(sync_words, device_name); -} - -void SyncUIDOMHandler::SetupSyncNewToSync(const base::ListValue* args) { - DCHECK(sync_service_); - std::string sync_words, device_name; - if (!args->GetString(0, &device_name)) - // TODO(bridiver) - does this need to report an error? - return; - - sync_service_->OnSetupSyncNewToSync(device_name); -} - -void SyncUIDOMHandler::PageLoaded(const base::ListValue* args) { - DCHECK(sync_service_); - LoadSyncSettingsView(); -} - -void SyncUIDOMHandler::NeedSyncWords(const base::ListValue* args) { - DCHECK(sync_service_); - sync_service_->GetSyncWords(); -} - -void SyncUIDOMHandler::NeedSyncQRcode(const base::ListValue* args) { - DCHECK(sync_service_); - std::string seed = sync_service_->GetSeed(); - web_ui()->CallJavascriptFunctionUnsafe( - "sync_ui_exports.haveSeedForQrCode", base::Value(seed)); -} - -void SyncUIDOMHandler::SyncBookmarks(const base::ListValue* args) { - DCHECK(sync_service_); - bool new_value; - if (!args->GetBoolean(0, &new_value)) - // TODO(bridiver) - does this need to report an error? - return; - - sync_service_->OnSetSyncBookmarks(new_value); -} - -void SyncUIDOMHandler::SyncBrowsingHistory(const base::ListValue* args) { - DCHECK(sync_service_); - bool new_value; - if (!args->GetBoolean(0, &new_value)) - // TODO(bridiver) - does this need to report an error? - return; - - sync_service_->OnSetSyncBrowsingHistory(new_value); -} - -void SyncUIDOMHandler::SyncSavedSiteSettings(const base::ListValue* args) { - DCHECK(sync_service_); - bool new_value; - if (!args->GetBoolean(0, &new_value)) - // TODO(bridiver) - does this need to report an error? - return; - - sync_service_->OnSetSyncSavedSiteSettings(new_value); -} - -void SyncUIDOMHandler::DeleteDevice(const base::ListValue* args) { - DCHECK(sync_service_); - std::string device_id_v2; - if (!args->GetString(0, &device_id_v2)) { - DCHECK(false) << "[Brave Sync] could not get device id v2"; - return; - } - - sync_service_->OnDeleteDevice(device_id_v2); -} - -void SyncUIDOMHandler::ResetSync(const base::ListValue* args) { - DCHECK(sync_service_); - sync_service_->OnResetSync(); -} - -void SyncUIDOMHandler::OnSyncSetupError( - brave_sync::BraveSyncService* sync_service, - const std::string& error) { - - web_ui()->CallJavascriptFunctionUnsafe( - "sync_ui_exports.syncSetupError", base::Value(error)); -} - -void SyncUIDOMHandler::OnSyncStateChanged( - brave_sync::BraveSyncService *sync_service) { - LoadSyncSettingsView(); -} - -void SyncUIDOMHandler::LoadSyncSettingsView() { - sync_service_->GetSettingsAndDevices( - base::Bind(&SyncUIDOMHandler::GetSettingsAndDevicesComplete, - weak_ptr_factory_.GetWeakPtr())); -} - -void SyncUIDOMHandler::GetSettingsAndDevicesComplete( - std::unique_ptr settings, - std::unique_ptr devices) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - std::unique_ptr bv_devices = devices->ToValueArrOnly(); - std::unique_ptr bv_settings = - brave_sync::BraveSyncSettingsToValue(settings.get()); - web_ui()->CallJavascriptFunctionUnsafe( - "sync_ui_exports.showSettings", *bv_settings, *bv_devices); -} - -void SyncUIDOMHandler::OnHaveSyncWords( - brave_sync::BraveSyncService *sync_service, - const std::string& sync_words) { - web_ui()->CallJavascriptFunctionUnsafe( - "sync_ui_exports.haveSyncWords", base::Value(sync_words)); -} - -} // namespace - -SyncUI::SyncUI(content::WebUI* web_ui, const std::string& name) - : BasicUI(web_ui, name, - kBraveSyncGenerated, - kBraveSyncGeneratedSize, - Profile::FromWebUI(web_ui)->IsOffTheRecord() ? - IDR_BRAVE_SYNC_DISABLED_HTML : IDR_BRAVE_SYNC_HTML) { - auto handler_owner = std::make_unique(); - SyncUIDOMHandler* handler = handler_owner.get(); - web_ui->AddMessageHandler(std::move(handler_owner)); - handler->Init(); -} - -SyncUI::~SyncUI() { -} diff --git a/browser/ui/webui/sync/sync_ui.h b/browser/ui/webui/sync/sync_ui.h deleted file mode 100644 index 47e02bd058dd..000000000000 --- a/browser/ui/webui/sync/sync_ui.h +++ /dev/null @@ -1,21 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_UI_WEBUI_SYNC_I_SYNC_UI_H_ -#define BRAVE_BROWSER_UI_WEBUI_SYNC_I_SYNC_UI_H_ - -#include - -#include "brave/browser/ui/webui/basic_ui.h" - -class SyncUI : public BasicUI { -public: - SyncUI(content::WebUI* web_ui, const std::string& host); - ~SyncUI() override; - -private: - DISALLOW_COPY_AND_ASSIGN(SyncUI); -}; - -#endif //BRAVE_BROWSER_UI_WEBUI_SYNC_I_SYNC_UI_H_ diff --git a/chromium_src/chrome/browser/autocomplete/autocomplete_classifier_factory.cc b/chromium_src/chrome/browser/autocomplete/autocomplete_classifier_factory.cc index 25b589e00e6a..a0140ae6c9a7 100644 --- a/chromium_src/chrome/browser/autocomplete/autocomplete_classifier_factory.cc +++ b/chromium_src/chrome/browser/autocomplete/autocomplete_classifier_factory.cc @@ -3,13 +3,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "brave/browser/autocomplete/brave_autocomplete_provider_client.h" #include "brave/browser/autocomplete/brave_autocomplete_scheme_classifier.h" #include "components/omnibox/browser/autocomplete_classifier.h" #include "components/omnibox/browser/autocomplete_controller.h" -#define ChromeAutocompleteProviderClient BraveAutocompleteProviderClient #define ChromeAutocompleteSchemeClassifier BraveAutocompleteSchemeClassifier #include "../../../../../chrome/browser/autocomplete/autocomplete_classifier_factory.cc" #undef ChromeAutocompleteSchemeClassifier -#undef ChromeAutocompleteProviderClient diff --git a/chromium_src/chrome/browser/browser_about_handler.cc b/chromium_src/chrome/browser/browser_about_handler.cc index 054f10cf9864..3615484687fa 100644 --- a/chromium_src/chrome/browser/browser_about_handler.cc +++ b/chromium_src/chrome/browser/browser_about_handler.cc @@ -14,13 +14,6 @@ bool FixupBrowserAboutURL(GURL* url, content::BrowserContext* browser_context) { bool result = FixupBrowserAboutURL_ChromiumImpl(url, browser_context); - // redirect sync-internals - if (url->host() == chrome::kChromeUISyncInternalsHost) { - GURL::Replacements replacements; - replacements.SetHostStr(chrome::kChromeUISyncHost); - *url = url->ReplaceComponents(replacements); - } - if (url->SchemeIs(kBraveUIScheme)) { GURL::Replacements replacements; replacements.SetSchemeStr(content::kChromeUIScheme); diff --git a/chromium_src/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc b/chromium_src/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc index cb73fc8268f5..29c8310dd570 100644 --- a/chromium_src/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc +++ b/chromium_src/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc @@ -12,7 +12,6 @@ #include "brave/components/brave_extension/grit/brave_extension.h" #include "components/grit/brave_components_resources.h" #include "brave/components/brave_rewards/resources/extension/grit/brave_rewards_extension_resources.h" -#include "brave/components/brave_sync/grit/brave_sync_resources.h" #include "brave/components/brave_webtorrent/grit/brave_webtorrent_resources.h" namespace extensions { @@ -21,7 +20,6 @@ namespace extensions { const char* const kAllowed[] = { brave_extension_id, brave_rewards_extension_id, - brave_sync_extension_id, ethereum_remote_client_extension_id, brave_webtorrent_extension_id }; @@ -39,7 +37,6 @@ namespace extensions { // Please keep the list in alphabetical order. case IDR_BRAVE_EXTENSION: case IDR_BRAVE_REWARDS: - case IDR_BRAVE_SYNC_EXTENSION: case IDR_BRAVE_WEBTORRENT: return true; } diff --git a/chromium_src/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chromium_src/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 58063bc00024..bd93c36ea817 100644 --- a/chromium_src/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chromium_src/chrome/browser/renderer_context_menu/render_view_context_menu.cc @@ -4,12 +4,12 @@ #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" -#include "brave/browser/autocomplete/brave_autocomplete_provider_client.h" #include "brave/browser/autocomplete/brave_autocomplete_scheme_classifier.h" #include "brave/browser/profiles/profile_util.h" #include "brave/browser/tor/buildflags.h" #include "brave/browser/translate/buildflags/buildflags.h" #include "brave/browser/renderer_context_menu/brave_spelling_options_submenu_observer.h" +#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h" #include "components/omnibox/browser/autocomplete_classifier.h" #include "components/omnibox/browser/autocomplete_controller.h" @@ -28,7 +28,7 @@ GURL GetSelectionNavigationURL(Profile* profile, const base::string16& text) { AutocompleteMatch match; AutocompleteClassifier classifier( std::make_unique( - std::make_unique(profile), + std::make_unique(profile), AutocompleteClassifier::DefaultOmniboxProviders()), std::make_unique(profile)); classifier.Classify(text, false, false, diff --git a/chromium_src/chrome/browser/ui/browser_navigator.cc b/chromium_src/chrome/browser/ui/browser_navigator.cc index eb73964aafe0..e204555dcf86 100644 --- a/chromium_src/chrome/browser/ui/browser_navigator.cc +++ b/chromium_src/chrome/browser/ui/browser_navigator.cc @@ -55,7 +55,6 @@ void MaybeHandleInParent(NavigateParams* params, bool allow_in_incognito) { bool IsHostAllowedInIncognitoBraveImpl(const base::StringPiece& host) { if (host == kWalletHost || host == kRewardsPageHost || - host == kBraveUISyncHost || host == chrome::kChromeUISyncInternalsHost) { return false; } diff --git a/chromium_src/chrome/browser/ui/omnibox/chrome_omnibox_client.cc b/chromium_src/chrome/browser/ui/omnibox/chrome_omnibox_client.cc deleted file mode 100644 index 37b498b88d50..000000000000 --- a/chromium_src/chrome/browser/ui/omnibox/chrome_omnibox_client.cc +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/autocomplete/brave_autocomplete_provider_client.h" - -#define ChromeAutocompleteProviderClient BraveAutocompleteProviderClient -#include "../../../../../../chrome/browser/ui/omnibox/chrome_omnibox_client.cc" -#undef ChromeAutocompleteProviderClient - diff --git a/common/extensions/api/BUILD.gn b/common/extensions/api/BUILD.gn index f47663be92f0..454ee67ad8d5 100644 --- a/common/extensions/api/BUILD.gn +++ b/common/extensions/api/BUILD.gn @@ -1,5 +1,4 @@ import("//brave/components/binance/browser/buildflags/buildflags.gni") -import("//brave/components/brave_sync/buildflags/buildflags.gni") import("//brave/components/brave_wallet/browser/buildflags/buildflags.gni") import("//brave/components/brave_together/buildflags/buildflags.gni") import("//tools/grit/grit_rule.gni") @@ -62,10 +61,6 @@ brave_extensions_api_schema_sources = [ "rewards_notifications.json", ] -if (enable_brave_sync) { - brave_extensions_api_schema_sources += [ "brave_sync.json" ] -} - if (brave_wallet_enabled) { brave_extensions_api_schema_sources += [ "brave_wallet.json" ] } diff --git a/common/extensions/api/brave_sync.json b/common/extensions/api/brave_sync.json deleted file mode 100644 index 9a582f180c6d..000000000000 --- a/common/extensions/api/brave_sync.json +++ /dev/null @@ -1,450 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -[ - { - "namespace": "braveSync", - "description": "Use the chrome.braveSync API to provide the interaction .", - "compiler_options": { - "implemented_in": "brave/browser/extensions/api/brave_sync_api.h" - }, - "types": [ - { - "id": "Bytes", - "type": "array", "items": {"type": "integer", "minimum": 0, "maximum" : 255 } - }, - { - "id": "Config", - "type": "object", - "description": "Config passed to got-init-data", - "properties": { - "apiVersion" : { - "type": "string", - "description": "version of API" - }, - "serverUrl" : { - "type": "string", - "description": "url of the server" - }, - "debug" : { - "type": "boolean", - "description": "whether sync lib produces debug messages" - } - } - }, - { - "id": "Site", - "type": "object", - "description": "Represents site entity", - "properties": { - "location" : {"type" : "string", "description" : "url of site"}, - "title" : {"type" : "string", "description" : "title of site"}, - "customTitle" : {"type" : "string", "description" : "custom title of site"}, - "lastAccessedTime" : {"type" : "number", "description" : "last accessed time"}, - "creationTime" : {"type" : "number", "description" : "creation time"}, - "favicon" : {"type" : "string", "description" : "url of favicon"} - } - }, - { - "id": "MetaInfo", - "type": "object", - "description": "Represents metaInfo entity", - "properties": { - "key" : {"type" : "string", "description" : "key of meta info"}, - "value" : {"type" : "string", "description" : "value of meta info"} - } - }, - { - "id": "Bookmark", - "type": "object", - "description": "Represents bookmark entity", - "properties": { - "site" : {"$ref" : "Site"}, - "isFolder" : {"type": "boolean"}, - "parentFolderObjectId" : {"type" : "binary", "optional": true}, - "parentFolderObjectIdStr" : {"type" : "string", "optional": true}, - "fields" : { "type": "array", "items": {"type": "string" }, "optional": true }, - "hideInToolbar" : {"type": "boolean", "optional": true}, - "order" : {"type": "string", "optional": true}, - "metaInfo" : { "type": "array", "items": {"$ref" : "MetaInfo" }, "optional": true } - } - }, - { - "id": "SiteSetting", - "type": "object", - "description": "Represents site settings", - "properties": { - "hostPattern" : {"type": "string"}, - "zoomLevel" : {"type": "number", "optional": true}, - "shieldsUp" : {"type": "boolean", "optional": true}, - "adControl" : {"type": "string", "optional": true}, - "cookieControl" : {"type": "string", "optional": true}, - "safeBrowsing" : {"type": "boolean", "optional": true}, - "noScript" : {"type": "boolean", "optional": true}, - "httpsEverywhere" : {"type": "boolean", "optional": true}, - "fingerprintingProtection" : {"type": "boolean", "optional": true}, - "ledgerPayments" : {"type": "boolean", "optional": true}, - "ledgerPaymentsShown" : {"type": "boolean", "optional": true}, - "fields" : { "type": "array", "items": {"type": "string" }, "optional": true } - } - }, - { - "id": "Device", - "type": "object", - "description": "Represents sync device", - "properties": { - "name" : {"type": "string"}, - "deviceIdV2" : {"type": "string"} - } - }, - { - "id": "SyncRecord", - "type": "object", - "description": "Record representing sync entity", - "properties": { - "action" : { - "type": "integer", - "description": "action code" - }, - "deviceId" : { - "type": "binary", - "description": "device id" - }, - "objectId" : { - "type": "binary", - "description": "object id" - }, - // "deviceIdStr", "objectIdStr" and "parentFolderObjectIdStr" are - // workaround because js lib uses UInt8Array type for ids, - // and there is no appropriate conversion - "deviceIdStr" : { - "type": "string", - "description": "device id", - "optional": true - }, - "objectIdStr" : { - "type": "string", - "description": "object id", - "optional": true - }, - "objectData": { - "type": "string", - "description": "may be bookmark|device|historySite|siteSetting" - }, - "syncTimestamp": { - "type": "number", - "description": "time when record was synced", - "optional": true - }, - "bookmark" : { - "$ref": "Bookmark", - "optional": true, - "description": "bookmark info" - }, - "historySite" : { - "$ref": "Site", - "optional": true, - "description": "history info" - }, - "siteSetting" : { - "$ref": "SiteSetting", - "optional": true, - "description": "site setting" - }, - "device" : { - "$ref": "Device", - "optional": true, - "description": "synced device info" - } - }, - "oneOf": [ - { "required": [ "bookmark"] }, - { "required": [ "history_site"] }, - { "required": [ "site_setting"] }, - { "required": [ "device"] } - ] - }, - { - "id": "RecordAndExistingObject", - "type": "object", - "description": "represents pair of sync record and sync record with existing object", - "properties": { - "serverRecord" : { - "$ref": "SyncRecord", - "description": "original sync record" - }, - "localRecord" : { - "$ref": "SyncRecord", - "description": "existing sync record", - "optional": true - } - } - } - ], - "events": [ - { - "name": "onGotInitData", - "type": "function", - "description": "Browser sends init data to sync js", - "parameters": [ - { - "$ref": "Bytes", - "name": "seed", - "optional": true - }, - { - "$ref": "Bytes", - "name": "device_id", - "optional": true - }, - { - "$ref": "Config", - "name": "config" - }, - { - "type": "string", - "name": "device_id_v2", - "optional": true - } - ] - }, - { - "name": "onFetchSyncRecords", - "type": "function", - "description": "sent to fetch sync records after a given start time from the sync server", - "parameters": [ - { - "type": "array", "items": {"type": "string"}, - "name": "categoryNames" - }, - { - "type": "number", - "name": "startAt" - }, - { - "type": "number", - "name": "maxRecords" - } - ] - }, - { - "name": "onResolveSyncRecords", - "type": "function", - "description": "Browser sends resolve records.", - "parameters": [ - { - "type": "string", - "name": "categoryName" - }, - { - "type": "array", "items": {"$ref": "RecordAndExistingObject"}, - "name": "recordsAndExistingObjects" - } - ] - }, - { - "name": "onSendSyncRecords", - "type": "function", - "description": "Browser sends this to the js sync library with the data that needs to be synced.", - "parameters": [ - { - "type": "string", - "name": "categoryName" - }, - { - "type": "array", "items": {"$ref": "SyncRecord"}, - "name": "records" - } - ] - }, - { - "name": "onSendGetBookmarksBaseOrder", - "type": "function", - "description": "Browser sends this to get base bookmarks order for the particular device.", - "parameters": [ - { - "type": "string", - "name": "deviceId" - }, - { - "type": "string", - "name": "platform" - } - ] - }, - { - "name": "sendCompact", - "type": "function", - "description": "Browser sends this to compact records of a category", - "parameters": [ - { - "type": "string", - "name": "categoryName" - } - ] - }, - { - "name": "onLoadClient", - "type": "function", - "description": "Browser informs extension page to load js sync library.", - "parameters": [] - } - ], - "functions": [ - { - "name": "extensionInitialized", - "type": "function", - "description": "Notifies extension has registered all listeners", - "parameters": [] - }, - { - "name": "getInitData", - "type": "function", - "description": "Emits the version of sync that is currently running", - "parameters": [ - { - "type": "string", - "name": "syncVersion" - }, - { - "type": "function", - "name": "callback", - "optional": true, - "parameters": [ - { - "name": "callback_arg1", - "type": "integer" - } - ] - } - ] - }, - { - "name": "syncSetupError", - "type": "function", - "description": "Indicates that a fatal error occurred during sync setup, meaning that sync is not running", - "parameters": [ - { - "type": "string", - "name": "error" - } - ] - }, - { - "name": "syncDebug", - "type": "function", - "description": "Used for debugging in environments where the webview console output is not easily accessible", - "parameters": [ - { - "type": "string", - "name": "message" - } - ] - }, - { - "name": "syncReady", - "type": "function", - "description": "Sent when sync has finished initialization", - "parameters": [] - }, - { - "name": "saveInitData", - "type": "function", - "description": "Browser must save values in persistent storage if non-empty", - "parameters": [ - { - "type": "binary", - "name": "seed", - "optional": true - }, - { - "type": "binary", - "name": "device_id", - "optional": true - }, - { - "type": "string", - "name": "device_id_v2", - "optional": true - } - ] - }, - { - "name": "getExistingObjects", - "type": "function", - "description": "Browser should resolve this records and answer with `resolve-sync-records`", - "parameters": [ - { - "type": "string", - "name": "category_name" - }, - { - "type": "array", "items": {"$ref": "SyncRecord"}, - "name": "records" - }, - { - "type": "number", - "name": "last_record_timestamp" - }, - { - "type": "boolean", - "name": "is_truncated" - } - ] - }, - { - "name": "resolvedSyncRecords", - "type": "function", - "description": "Browser must update its local values with the resolved sync records", - "parameters": [ - { - "type": "string", - "name": "category_name" - }, - { - "type": "array", "items": {"$ref": "SyncRecord"}, - "name": "records" - } - ] - }, - { - "name": "saveBookmarksBaseOrder", - "type": "function", - "description": "Browser must save bookmarks base order", - "parameters": [ - { - "type": "string", - "name": "order" - } - ] - }, - { - "name": "onCompactComplete", - "type": "function", - "description": "Notify browser that compaction for category is done", - "parameters": [ - { - "type": "string", - "name": "category_name" - } - ] - }, - { - "name": "onRecordsSent", - "type": "function", - "description": "Notify browser that records are successfully uploaded", - "parameters": [ - { - "type": "string", - "name": "category_name" - }, - { - "type": "array", "items": {"$ref": "SyncRecord"}, - "name": "records" - } - ] - } - ] - } -] diff --git a/common/extensions/extension_constants.cc b/common/extensions/extension_constants.cc index d1a3fb1c9387..6cca76cbfd70 100644 --- a/common/extensions/extension_constants.cc +++ b/common/extensions/extension_constants.cc @@ -10,7 +10,6 @@ const char brave_rewards_extension_id[] = "jidkidbbcafjabdphckchenhfomhnfma"; const char brave_webtorrent_extension_id[] = "lgjmpdmojkpocjcopdikifhejkkjglho"; const char hangouts_extension_id[] = "nkeimhogjdpnpccoofpliimaahmaaome"; const char widevine_extension_id[] = "oimompecagnajdejgnnjijobebaeigek"; -const char brave_sync_extension_id[] = "nomlkjnggnifocmealianaaiobmebgil"; const char crl_set_extension_id[] = "hfnkpimlhhgieaddgfemjhofmfblmnib"; const char ethereum_remote_client_extension_id[] = diff --git a/common/extensions/extension_constants.h b/common/extensions/extension_constants.h index 2e1ab11f07db..3b097de9d75f 100644 --- a/common/extensions/extension_constants.h +++ b/common/extensions/extension_constants.h @@ -11,7 +11,6 @@ extern const char brave_rewards_extension_id[]; extern const char brave_webtorrent_extension_id[]; extern const char hangouts_extension_id[]; extern const char widevine_extension_id[]; -extern const char brave_sync_extension_id[]; extern const char crl_set_extension_id[]; extern const char ethereum_remote_client_extension_id[]; diff --git a/common/extensions/whitelist.cc b/common/extensions/whitelist.cc index 76e6dc2c4b29..0f8196704238 100644 --- a/common/extensions/whitelist.cc +++ b/common/extensions/whitelist.cc @@ -16,7 +16,6 @@ const std::vector kVettedExtensions{ brave_extension_id, brave_rewards_extension_id, - brave_sync_extension_id, brave_webtorrent_extension_id, crl_set_extension_id, ethereum_remote_client_extension_id, diff --git a/common/webui_url_constants.cc b/common/webui_url_constants.cc index 7d59940e76b6..6c1dab2c4f16 100644 --- a/common/webui_url_constants.cc +++ b/common/webui_url_constants.cc @@ -14,13 +14,10 @@ const char kWelcomeHost[] = "welcome"; const char kWelcomeJS[] = "brave_welcome.js"; const char kTipHost[] = "tip"; const char kBraveNewTabJS[] = "brave_new_tab.js"; -const char kBraveUISyncHost[] = "sync"; -const char kBraveSyncJS[] = "brave_sync.js"; const char kBraveUIRewardsURL[] = "chrome://rewards/"; const char kBraveUIAdblockURL[] = "chrome://adblock/"; const char kBraveUIWebcompatReporterURL[] = "chrome://webcompat/"; const char kBraveUITipURL[] = "chrome://tip/"; -const char kBraveUISyncURL[] = "chrome://sync/"; const char kBraveUIWalletURL[] = "chrome://wallet/"; const char kExtensionSettingsURL[] = "brave://settings/extensions"; const char kWalletHost[] = "wallet"; diff --git a/common/webui_url_constants.h b/common/webui_url_constants.h index 4df5724784fe..d42df9e69277 100644 --- a/common/webui_url_constants.h +++ b/common/webui_url_constants.h @@ -15,14 +15,11 @@ extern const char kWelcomeHost[]; extern const char kWelcomeJS[]; extern const char kTipHost[]; extern const char kBraveNewTabJS[]; -extern const char kBraveUISyncHost[]; -extern const char kBraveSyncJS[]; extern const char kBraveUIRewardsURL[]; extern const char kBraveUIAdblockURL[]; extern const char kBraveUIWebcompatReporterURL[]; extern const char kBraveUITipHost[]; extern const char kBraveUITipURL[]; -extern const char kBraveUISyncURL[]; extern const char kBraveUIWalletURL[]; extern const char kBraveUIWalletURL[]; extern const char kExtensionSettingsURL[]; diff --git a/components/brave_sync/BUILD.gn b/components/brave_sync/BUILD.gn index 0f8cbd4beee8..46d83db1732f 100644 --- a/components/brave_sync/BUILD.gn +++ b/components/brave_sync/BUILD.gn @@ -14,69 +14,10 @@ config("brave_sync_config") { ] } -if (enable_brave_sync) { - source_set("js_sync_lib_impl") { - sources = [ - "client/brave_sync_client.h", - "client/brave_sync_client_impl.cc", - "client/brave_sync_client_impl.h", - "client/client_data.cc", - "client/client_data.h", - "client/client_ext_impl_data.cc", - "client/client_ext_impl_data.h", - ] - - configs += [ ":brave_sync_config" ] - deps = [ - ":core", - ":crypto", - ":jslib_messages", - ":prefs", - ":public", - ":static_resources", - "//base", - "//brave/common:common", - "//chrome/common", - "//components/bookmarks/browser", - "//components/bookmarks/common", - "//components/keyed_service/content", - "//components/keyed_service/core", - "//components/pref_registry", - "//components/prefs", - "//components/signin/public/identity_manager", - "//components/sync:rest_of_sync", - "//components/sync/driver:driver", - "//content/public/browser", - "//extensions/browser", - "//net", - "//services/network/public/cpp", - "//ui/base", - ] - } -} - -source_set("jslib_messages") { - sources = [ - "jslib_const.cc", - "jslib_const.h", - "jslib_messages.cc", - "jslib_messages.h", - "jslib_messages_fwd.h", - ] - - deps = [ - "//base", - ] -} - source_set("prefs") { sources = [ "brave_sync_prefs.cc", "brave_sync_prefs.h", - "settings.cc", - "settings.h", - "sync_devices.cc", - "sync_devices.h", ] deps = [ @@ -113,17 +54,6 @@ source_set("features") { ] } -source_set("public") { - sources = [ - "public/brave_profile_sync_service.h", - ] - - deps = [ - ":core", - "buildflags", - ] -} - source_set("core") { sources = [ "access_token_consumer.cc", @@ -132,33 +62,19 @@ source_set("core") { "access_token_fetcher.h", "access_token_fetcher_impl.cc", "access_token_fetcher_impl.h", - "bookmark_order_util.cc", - "bookmark_order_util.h", - "brave_sync_service.cc", - "brave_sync_service.h", - "syncer_helper.cc", - "syncer_helper.h", - "tools.cc", - "tools.h", - "values_conv.cc", - "values_conv.h", ] deps = [ ":crypto", ":features", - ":jslib_messages", ":prefs", "//base", - "//components/bookmarks/browser", "//crypto", - "//extensions/buildflags", ] } source_set("brave_sync") { sources = [ - "brave_sync_service_observer.h", ] deps = [ @@ -166,71 +82,4 @@ source_set("brave_sync") { "buildflags", "//base", ] - - if (enable_brave_sync) { - deps += [ ":js_sync_lib_impl" ] - } -} - -pack_web_resources("generated_resources") { - resource_name = "brave_sync" - output_dir = "$root_gen_dir/brave/components/brave_sync" - deps = [ - "ui", - ] -} - -grit("static_resources") { - source = "resources.grd" - outputs = [ - "grit/brave_sync_resources_map.cc", - "grit/brave_sync_resources_map.h", - "grit/brave_sync_resources.h", - "brave_sync_static.pak", - ] - - deps = [] - - grit_flags = [ - "-E", - "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir), - ] - - # fix paths so we don't have to do this - resource_ids = "" - - output_dir = "$root_gen_dir/brave/components/brave_sync" -} - -repack("resources") { - deps = [ - ":generated_resources", - ":static_resources", - ] - - sources = [ - "$root_gen_dir/brave/components/brave_sync/brave_sync_generated.pak", - "$root_gen_dir/brave/components/brave_sync/brave_sync_static.pak", - ] - - output = "$root_gen_dir/brave/components/brave_sync/brave_sync_resources.pak" -} - -if (enable_brave_sync) { - source_set("testutil") { - testonly = true - - deps = [ - ":brave_sync", - "//base", - "//chrome/test:test_support", - "//content/public/browser", - "//testing/gtest", - ] - - sources = [ - "test_util.cc", - "test_util.h", - ] - } } diff --git a/components/brave_sync/bookmark_order_util.cc b/components/brave_sync/bookmark_order_util.cc deleted file mode 100644 index 30fa629f9c88..000000000000 --- a/components/brave_sync/bookmark_order_util.cc +++ /dev/null @@ -1,176 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/bookmark_order_util.h" - -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" - -namespace brave_sync { - -namespace { - -bool CompareOrder(const std::vector& vec_left, - const std::vector& vec_right) { - // Use C++ stdlib - return std::lexicographical_compare(vec_left.begin(), vec_left.end(), - vec_right.begin(), vec_right.end()); -} - -} // namespace - -std::vector OrderToIntVect(const std::string& s) { - std::vector vec_s = SplitString( - s, - ".", - base::WhitespaceHandling::TRIM_WHITESPACE, - base::SplitResult::SPLIT_WANT_NONEMPTY); - std::vector vec_int; - vec_int.reserve(vec_s.size()); - for (size_t i = 0; i < vec_s.size(); ++i) { - int output = 0; - bool b = base::StringToInt(vec_s[i], &output); - CHECK(b); - CHECK_GE(output, 0); - vec_int.emplace_back(output); - } - return vec_int; -} - -std::string ToOrderString(const std::vector& vec_int) { - std::string ret; - for (size_t i = 0; i < vec_int.size(); ++i) { - if (vec_int[i] < 0) { - return ""; - } - ret += std::to_string(vec_int[i]); - if (i != vec_int.size() - 1) { - ret += "."; - } - } - return ret; -} - -bool CompareOrder(const std::string& left, const std::string& right) { - // Return: true if left < right - // Split each and compare as int vectors - std::vector vec_left = OrderToIntVect(left); - std::vector vec_right = OrderToIntVect(right); - - return CompareOrder(vec_left, vec_right); -} - -namespace { - -std::string GetNextOrderFromPrevOrder(std::vector* vec_prev) { - DCHECK_GT(vec_prev->size(), 2u); - int last_number = vec_prev->at(vec_prev->size() - 1); - DCHECK_GT(last_number, 0); - if (last_number <= 0) { - return ""; - } else { - vec_prev->at(vec_prev->size() - 1)++; - return ToOrderString(*vec_prev); - } -} - -std::string GetPrevOrderFromNextOrder(std::vector* vec_next) { - DCHECK_GT(vec_next->size(), 2u); - int last_number = vec_next->at(vec_next->size() - 1); - DCHECK_GT(last_number, 0); - vec_next->resize(vec_next->size() - 1); - if (last_number <= 0) { - return ""; - } else if (last_number == 1) { - return ToOrderString(*vec_next) + ".0.1"; - } else { - vec_next->push_back(last_number - 1); - return ToOrderString(*vec_next); - } -} - -} // namespace - -// Inspired by https://github.com/brave/sync/blob/staging/client/bookmarkUtil.js -std::string GetOrder(const std::string& prev, - const std::string& next, - const std::string& parent) { - if (prev.empty() && next.empty()) { - DCHECK(!parent.empty()); - return parent + ".1"; - } else if (!prev.empty() && next.empty()) { - std::vector vec_prev = OrderToIntVect(prev); - DCHECK_GT(vec_prev.size(), 2u); - // Just increase the last number, as we don't have next - return GetNextOrderFromPrevOrder(&vec_prev); - } else if (prev.empty() && !next.empty()) { - std::vector vec_next = OrderToIntVect(next); - DCHECK_GT(vec_next.size(), 2u); - // Just decrease the last number or substitute with 0.1, - // as we don't have prev - return GetPrevOrderFromNextOrder(&vec_next); - } else { - DCHECK(!prev.empty() && !next.empty()); - std::vector vec_prev = OrderToIntVect(prev); - DCHECK_GT(vec_prev.size(), 2u); - std::vector vec_next = OrderToIntVect(next); - DCHECK_GT(vec_next.size(), 2u); - DCHECK(CompareOrder(prev, next)); - - // Assume prev looks as a.b.c.d - // result candidates are: - // a.b.c.(d+1) - // a.b.c.d.1 - // a.b.c.d.0.1 - // a.b.c.d.0.0.1 - // ... - // each of them is greater than prev - - // Length of result in worse case can be one segment longer - // than length of next - // And result should be < next - - std::vector vec_result; - vec_result = vec_prev; - vec_result[vec_result.size() - 1]++; - - // Case a.b.c.(d+1) - DCHECK(CompareOrder(vec_prev, vec_result)); - if (CompareOrder(vec_result, vec_next)) { - return ToOrderString(vec_result); - } - - vec_result = vec_prev; - vec_result.push_back(1); - // Case a.b.c.d.1 - DCHECK(CompareOrder(vec_prev, vec_result)); - if (CompareOrder(vec_result, vec_next)) { - return ToOrderString(vec_result); - } - - size_t insert_at = vec_prev.size(); - size_t try_until_size = vec_next.size() + 1; - // Cases a.b.c.d.0....0.1 - while (vec_result.size() < try_until_size) { - vec_result.insert(vec_result.begin() + insert_at, 0); - DCHECK(CompareOrder(vec_prev, vec_result)); - if (CompareOrder(vec_result, vec_next)) { - return ToOrderString(vec_result); - } - } - - NOTREACHED() << "[BraveSync] " << __func__ << " prev=" << prev - << " next=" << next << " terminated with " - << ToOrderString(vec_result); - } - - NOTREACHED() << "[BraveSync] " << __func__ - << " condition is not handled prev.empty()=" << prev.empty() - << " next.empty()=" << next.empty(); - - return ""; -} - -} // namespace brave_sync diff --git a/components/brave_sync/bookmark_order_util.h b/components/brave_sync/bookmark_order_util.h deleted file mode 100644 index 6a9d9504f695..000000000000 --- a/components/brave_sync/bookmark_order_util.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_BOOKMARK_ORDER_UTIL_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_BOOKMARK_ORDER_UTIL_H_ - -#include -#include - -namespace brave_sync { - - std::vector OrderToIntVect(const std::string& s); - std::string ToOrderString(const std::vector& vec_int); - bool CompareOrder(const std::string& left, const std::string& right); - std::string GetOrder(const std::string& prev, - const std::string& next, - const std::string& parent); - - } // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_BOOKMARK_ORDER_UTIL_H_ diff --git a/components/brave_sync/bookmark_order_util_unittest.cc b/components/brave_sync/bookmark_order_util_unittest.cc deleted file mode 100644 index 98a911177262..000000000000 --- a/components/brave_sync/bookmark_order_util_unittest.cc +++ /dev/null @@ -1,115 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/bookmark_order_util.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace brave_sync { - -TEST(BookmarkOrderUtilTest, OrderToIntVect_EmptyString) { - std::vector result = OrderToIntVect(""); - EXPECT_TRUE(result.empty()); -} - -TEST(BookmarkOrderUtilTest, OrderToIntVect_SingleValue) { - std::vector result = OrderToIntVect("1"); - ASSERT_EQ(result.size(), 1u); - EXPECT_EQ(result.at(0), 1); -} - -TEST(BookmarkOrderUtilTest, OrderToIntVect_TypicalValue) { - std::vector result = OrderToIntVect("1.7.4"); - ASSERT_EQ(result.size(), 3u); - EXPECT_EQ(result.at(0), 1); - EXPECT_EQ(result.at(1), 7); - EXPECT_EQ(result.at(2), 4); -} - -TEST(BookmarkOrderUtilTest, OrderToIntVect_WrongValue) { - std::vector result = OrderToIntVect(".."); - EXPECT_TRUE(result.empty()); -} - -TEST(BookmarkOrderUtilTest, OrderToIntVect_SemiWrongValue) { - std::vector result = OrderToIntVect(".5."); - ASSERT_EQ(result.size(), 1u); - EXPECT_EQ(result.at(0), 5); -} - -TEST(BookmarkOrderUtilTest, ToOrderString) { - EXPECT_EQ(ToOrderString({}), ""); - EXPECT_EQ(ToOrderString({1}), "1"); - EXPECT_EQ(ToOrderString({1, 2, 3}), "1.2.3"); - EXPECT_EQ(ToOrderString({-1, 2, 3}), ""); -} - -TEST(BookmarkOrderUtilTest, CompareOrder) { - EXPECT_FALSE(CompareOrder("", "")); - EXPECT_TRUE(CompareOrder("1", "2")); - EXPECT_TRUE(CompareOrder("1", "1.1")); - EXPECT_TRUE(CompareOrder("1.1", "2.234.1")); - EXPECT_TRUE(CompareOrder("2.234.1", "63.17.1.45.2")); - - EXPECT_FALSE(CompareOrder("2", "1")); - EXPECT_TRUE(CompareOrder("2", "11")); - EXPECT_FALSE(CompareOrder("11", "2")); - - EXPECT_TRUE(CompareOrder("1.7.0.1", "1.7.1")); - EXPECT_TRUE(CompareOrder("1.7.0.1", "1.7.0.2")); - EXPECT_FALSE(CompareOrder("1.7.0.2", "1.7.0.1")); - - EXPECT_TRUE(CompareOrder("2.0.8", "2.0.8.0.1")); - EXPECT_TRUE(CompareOrder("2.0.8.0.1", "2.0.8.1")); - - EXPECT_TRUE(CompareOrder("2.0.8", "2.0.8.0.0.1")); - EXPECT_TRUE(CompareOrder("2.0.8.0.0.1", "2.0.8.0.1")); - - EXPECT_TRUE(CompareOrder("2.0.8.10", "2.0.8.10.1")); - EXPECT_TRUE(CompareOrder("2.0.8.10.1", "2.0.8.11.1")); - - EXPECT_TRUE(CompareOrder("2.0.0.1", "2.0.1")); - - EXPECT_TRUE(CompareOrder("2.5.6.3", "2.5.7.8.2")); - EXPECT_TRUE(CompareOrder("2.5.6.3", "2.5.6.4")); - EXPECT_TRUE(CompareOrder("2.5.6.4", "2.5.7.8.2")); - - EXPECT_TRUE(CompareOrder("2.0.8.10", "2.0.8.11")); - EXPECT_TRUE(CompareOrder("2.0.8.11", "2.0.8.11.1")); -} - -TEST(BookmarkOrderUtilTest, GetOrder) { - // Ported from - // https://github.com/brave/sync/blob/staging/test/client/bookmarkUtil.js - EXPECT_EQ(GetOrder("", "2.0.1", ""), "2.0.0.1"); - - EXPECT_EQ(GetOrder("", "2.0.9", ""), "2.0.8"); - EXPECT_EQ(GetOrder("2.0.8", "", ""), "2.0.9"); - EXPECT_EQ(GetOrder("2.0.8", "2.0.9", ""), "2.0.8.1"); - - EXPECT_EQ(GetOrder("2.0.8", "2.0.8.1", ""), "2.0.8.0.1"); - EXPECT_EQ(GetOrder("2.0.8", "2.0.8.0.1", ""), "2.0.8.0.0.1"); - EXPECT_EQ(GetOrder("2.0.8", "2.0.8.0.0.1", ""), "2.0.8.0.0.0.1"); - - EXPECT_EQ(GetOrder("2.0.8.1", "2.0.9", ""), "2.0.8.2"); - EXPECT_EQ(GetOrder("2.0.8.1", "2.0.10", ""), "2.0.8.2"); - EXPECT_EQ(GetOrder("2.0.8.10", "2.0.8.15", ""), "2.0.8.11"); - - EXPECT_EQ(GetOrder("2.0.8.10", "2.0.8.15.1", ""), "2.0.8.11"); - EXPECT_EQ(GetOrder("2.0.8.10", "2.0.8.11.1", ""), "2.0.8.11"); - - EXPECT_EQ(GetOrder("2.0.8.11", "2.0.8.11.1", ""), "2.0.8.11.0.1"); - - EXPECT_EQ(GetOrder("2.0.8.10.0.1", "2.0.8.15.1", ""), "2.0.8.10.0.2"); - EXPECT_EQ(GetOrder("", "", "2.0.9"), "2.0.9.1"); - - EXPECT_EQ(GetOrder("2.5.6.3", "2.5.7.8.2", ""), "2.5.6.4"); - EXPECT_EQ(GetOrder("2.5.6.35", "2.5.7.8.2", ""), "2.5.6.36"); - - EXPECT_EQ(GetOrder("1.1.1.2", "1.1.1.2.1", ""), "1.1.1.2.0.1"); - EXPECT_EQ(GetOrder("1.1.1.2.1", "1.1.1.3", ""), "1.1.1.2.2"); -} - -} // namespace brave_sync diff --git a/components/brave_sync/brave_sync_prefs.cc b/components/brave_sync/brave_sync_prefs.cc index b3b0c6838a41..346524d440cc 100644 --- a/components/brave_sync/brave_sync_prefs.cc +++ b/components/brave_sync/brave_sync_prefs.cc @@ -7,8 +7,6 @@ #include -#include "brave/components/brave_sync/settings.h" -#include "brave/components/brave_sync/sync_devices.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" @@ -16,15 +14,35 @@ void MigrateBraveSyncPrefs(PrefService* prefs) { prefs->ClearPref(brave_sync::prefs::kSyncPrevSeed); prefs->ClearPref(brave_sync::prefs::kDuplicatedBookmarksRecovered); + prefs->ClearPref(brave_sync::prefs::kSyncDeviceId); + prefs->ClearPref(brave_sync::prefs::kSyncDeviceIdV2); + prefs->ClearPref(brave_sync::prefs::kSyncDeviceObjectId); + prefs->ClearPref(brave_sync::prefs::kSyncDeviceName); + prefs->ClearPref(brave_sync::prefs::kSyncEnabled); + prefs->ClearPref(brave_sync::prefs::kSyncBookmarksEnabled); + prefs->ClearPref(brave_sync::prefs::kSyncBookmarksBaseOrder); + prefs->ClearPref(brave_sync::prefs::kSyncSiteSettingsEnabled); + prefs->ClearPref(brave_sync::prefs::kSyncHistoryEnabled); + prefs->ClearPref(brave_sync::prefs::kSyncLatestRecordTime); + prefs->ClearPref(brave_sync::prefs::kSyncLatestDeviceRecordTime); + prefs->ClearPref(brave_sync::prefs::kSyncLastFetchTime); + prefs->ClearPref(brave_sync::prefs::kSyncDeviceList); + prefs->ClearPref(brave_sync::prefs::kSyncApiVersion); + prefs->ClearPref(brave_sync::prefs::kSyncMigrateBookmarksVersion); + prefs->ClearPref(brave_sync::prefs::kSyncRecordsToResend); + prefs->ClearPref(brave_sync::prefs::kSyncRecordsToResendMeta); } namespace brave_sync { namespace prefs { +const char kSyncSeed[] = "brave_sync.seed"; + +// Deprecated +// ============================================================================ const char kSyncDeviceId[] = "brave_sync.device_id"; const char kSyncDeviceIdV2[] = "brave_sync.device_id_v2"; const char kSyncDeviceObjectId[] = "brave_sync.device_object_id"; -const char kSyncSeed[] = "brave_sync.seed"; const char kSyncPrevSeed[] = "brave_sync.previous_seed"; const char kSyncDeviceName[] = "brave_sync.device_name"; const char kSyncBookmarksBaseOrder[] = "brave_sync.bookmarks_base_order"; @@ -48,14 +66,18 @@ const char kDuplicatedBookmarksRecovered[] = "brave_sync_duplicated_bookmarks_recovered"; const char kDuplicatedBookmarksMigrateVersion[] = "brave_sync_duplicated_bookmarks_migrate_version"; +// ============================================================================ Prefs::Prefs(PrefService* pref_service) : pref_service_(pref_service) {} void Prefs::RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { + registry->RegisterStringPref(prefs::kSyncSeed, std::string()); + +// Deprecated +// ============================================================================ registry->RegisterStringPref(prefs::kSyncDeviceId, std::string()); registry->RegisterStringPref(prefs::kSyncDeviceIdV2, std::string()); registry->RegisterStringPref(prefs::kSyncDeviceObjectId, std::string()); - registry->RegisterStringPref(prefs::kSyncSeed, std::string()); registry->RegisterStringPref(prefs::kSyncPrevSeed, std::string()); registry->RegisterStringPref(prefs::kSyncDeviceName, std::string()); registry->RegisterStringPref(prefs::kSyncBookmarksBaseOrder, std::string()); @@ -90,149 +112,6 @@ void Prefs::SetSeed(const std::string& seed) { pref_service_->SetString(kSyncSeed, seed); } -std::string Prefs::GetThisDeviceId() const { - return pref_service_->GetString(kSyncDeviceId); -} - -void Prefs::SetThisDeviceId(const std::string& device_id) { - DCHECK(!device_id.empty()); - pref_service_->SetString(kSyncDeviceId, device_id); -} - -std::string Prefs::GetThisDeviceIdV2() const { - return pref_service_->GetString(kSyncDeviceIdV2); -} - -void Prefs::SetThisDeviceIdV2(const std::string& device_id_v2) { - if (!device_id_v2.empty()) - pref_service_->SetString(kSyncDeviceIdV2, device_id_v2); -} - -std::string Prefs::GetThisDeviceObjectId() const { - return pref_service_->GetString(kSyncDeviceObjectId); -} - -void Prefs::SetThisDeviceObjectId(const std::string& device_object_id) { - DCHECK(!device_object_id.empty()); - pref_service_->SetString(kSyncDeviceObjectId, device_object_id); -} - -std::string Prefs::GetThisDeviceName() const { - return pref_service_->GetString(kSyncDeviceName); -} - -void Prefs::SetThisDeviceName(const std::string& device_name) { - DCHECK(!device_name.empty()); - pref_service_->SetString(kSyncDeviceName, device_name); -} -std::string Prefs::GetBookmarksBaseOrder() { - return pref_service_->GetString(kSyncBookmarksBaseOrder); -} -void Prefs::SetBookmarksBaseOrder(const std::string& order) { - pref_service_->SetString(kSyncBookmarksBaseOrder, order); -} - -bool Prefs::GetSyncEnabled() const { - return pref_service_->GetBoolean(kSyncEnabled); -} - -void Prefs::SetSyncEnabled(const bool sync_this_device) { - pref_service_->SetBoolean(kSyncEnabled, sync_this_device); -} - -bool Prefs::GetSyncBookmarksEnabled() const { - return pref_service_->GetBoolean(kSyncBookmarksEnabled); -} - -void Prefs::SetSyncBookmarksEnabled(const bool sync_bookmarks_enabled) { - pref_service_->SetBoolean(kSyncBookmarksEnabled, sync_bookmarks_enabled); -} - -bool Prefs::GetSyncSiteSettingsEnabled() const { - return pref_service_->GetBoolean(kSyncSiteSettingsEnabled); -} - -void Prefs::SetSyncSiteSettingsEnabled(const bool sync_site_settings_enabled) { - pref_service_->SetBoolean( - kSyncSiteSettingsEnabled, sync_site_settings_enabled); -} - -bool Prefs::GetSyncHistoryEnabled() const { - return pref_service_->GetBoolean(kSyncHistoryEnabled); -} - -void Prefs::SetSyncHistoryEnabled(const bool sync_history_enabled) { - pref_service_->SetBoolean(kSyncHistoryEnabled, sync_history_enabled); -} - -std::unique_ptr Prefs::GetBraveSyncSettings() const { - auto settings = std::make_unique(); - - settings->this_device_name_ = GetThisDeviceName(); - settings->this_device_id_ = GetThisDeviceId(); - settings->this_device_id_v2_ = GetThisDeviceIdV2(); - settings->sync_this_device_ = GetSyncEnabled(); - settings->sync_bookmarks_ = GetSyncBookmarksEnabled(); - settings->sync_settings_ = GetSyncSiteSettingsEnabled(); - settings->sync_history_ = GetSyncHistoryEnabled(); - - settings->sync_configured_ = - !GetSeed().empty() && !GetThisDeviceName().empty(); - - return settings; -} - -void Prefs::SetLatestRecordTime(const base::Time &time) { - pref_service_->SetTime(kSyncLatestRecordTime, time); -} - -base::Time Prefs::GetLatestRecordTime() { - return pref_service_->GetTime(kSyncLatestRecordTime); -} -void Prefs::SetLatestDeviceRecordTime(const base::Time& time) { - pref_service_->SetTime(kSyncLatestDeviceRecordTime, time); -} -base::Time Prefs::GetLatestDeviceRecordTime() { - return pref_service_->GetTime(kSyncLatestDeviceRecordTime); -} - -void Prefs::SetLastFetchTime(const base::Time &time) { - pref_service_->SetTime(kSyncLastFetchTime, time); -} - -base::Time Prefs::GetLastFetchTime() { - return pref_service_->GetTime(kSyncLastFetchTime); -} - -void Prefs::SetLastCompactTimeBookmarks(const base::Time &time) { - pref_service_->SetTime(kSyncLastCompactTimeBookmarks, time); -} - -base::Time Prefs::GetLastCompactTimeBookmarks() { - return pref_service_->GetTime(kSyncLastCompactTimeBookmarks); -} - -std::unique_ptr Prefs::GetSyncDevices() { - auto existing_sync_devices = std::make_unique(); - std::string json_device_list = pref_service_->GetString(kSyncDeviceList); - if (!json_device_list.empty()) - existing_sync_devices->FromJson(json_device_list); - - return existing_sync_devices; -} - -void Prefs::SetSyncDevices(const SyncDevices& devices) { - pref_service_->SetString(kSyncDeviceList, devices.ToJson()); -} - -std::string Prefs::GetApiVersion() { - return pref_service_->GetString(kSyncApiVersion); -} - -void Prefs::SetApiVersion(const std::string& api_version) { - pref_service_->SetString(kSyncApiVersion, api_version); -} - int Prefs::GetMigratedBookmarksVersion() { return pref_service_->GetInteger(kSyncMigrateBookmarksVersion); } @@ -241,66 +120,8 @@ void Prefs::SetMigratedBookmarksVersion(const int migrate_bookmarks) { pref_service_->SetInteger(kSyncMigrateBookmarksVersion, migrate_bookmarks); } -std::vector Prefs::GetRecordsToResend() const { - std::vector result; - const base::Value* records = pref_service_->GetList(kSyncRecordsToResend); - for (const base::Value& record : records->GetList()) { - result.push_back(record.GetString()); - } - return result; -} - -void Prefs::AddToRecordsToResend(const std::string& object_id, - std::unique_ptr meta) { - ListPrefUpdate list_update(pref_service_, kSyncRecordsToResend); - list_update->Append(base::Value(object_id)); - SetRecordToResendMeta(object_id, std::move(meta)); -} - -void Prefs::RemoveFromRecordsToResend(const std::string& object_id) { - ListPrefUpdate list_update(pref_service_, kSyncRecordsToResend); - list_update->EraseListValue(base::Value(object_id)); - DictionaryPrefUpdate dict_update(pref_service_, kSyncRecordsToResendMeta); - dict_update->RemoveKey(object_id); -} - -const base::DictionaryValue* Prefs::GetRecordToResendMeta( - const std::string& object_id) const { - const base::DictionaryValue* dict = - pref_service_->GetDictionary(kSyncRecordsToResendMeta); - const base::DictionaryValue* meta = nullptr; - const base::Value* meta_value = dict->FindDictKey(object_id); - if (meta_value) { - meta_value->GetAsDictionary(&meta); - } - return meta; -} - -void Prefs::SetRecordToResendMeta(const std::string& object_id, - std::unique_ptr meta) { - DictionaryPrefUpdate dict_update(pref_service_, kSyncRecordsToResendMeta); - dict_update->SetDictionary(object_id, std::move(meta)); -} - void Prefs::Clear() { - pref_service_->ClearPref(kSyncDeviceId); - pref_service_->ClearPref(kSyncDeviceIdV2); - pref_service_->ClearPref(kSyncDeviceObjectId); pref_service_->ClearPref(kSyncSeed); - pref_service_->ClearPref(kSyncDeviceName); - pref_service_->ClearPref(kSyncEnabled); - pref_service_->ClearPref(kSyncBookmarksEnabled); - pref_service_->ClearPref(kSyncBookmarksBaseOrder); - pref_service_->ClearPref(kSyncSiteSettingsEnabled); - pref_service_->ClearPref(kSyncHistoryEnabled); - pref_service_->ClearPref(kSyncLatestRecordTime); - pref_service_->ClearPref(kSyncLatestDeviceRecordTime); - pref_service_->ClearPref(kSyncLastFetchTime); - pref_service_->ClearPref(kSyncDeviceList); - pref_service_->ClearPref(kSyncApiVersion); - pref_service_->ClearPref(kSyncMigrateBookmarksVersion); - pref_service_->ClearPref(kSyncRecordsToResend); - pref_service_->ClearPref(kSyncRecordsToResendMeta); } } // namespace prefs diff --git a/components/brave_sync/brave_sync_prefs.h b/components/brave_sync/brave_sync_prefs.h index 7c7d7e4bde83..518e473a029c 100644 --- a/components/brave_sync/brave_sync_prefs.h +++ b/components/brave_sync/brave_sync_prefs.h @@ -27,53 +27,32 @@ void MigrateBraveSyncPrefs(PrefService* prefs); namespace brave_sync { -class Settings; -class SyncDevices; - namespace prefs { +// Stored as bip39 keywords +extern const char kSyncSeed[]; -// String of device id. Supposed to be an integer +// Deprecated +// ============================================================================ extern const char kSyncDeviceId[]; extern const char kSyncDeviceIdV2[]; -// String of 32 comma separated bytes -// like "145,58,125,111,85,164,236,38,204,67,40,31,182,114,14,152,242,..." -extern const char kSyncSeed[]; -// For storing previous seed after reset. It won't be cleared by Clear() -// Now is deprecated. +extern const char kSyncDeviceObjectId[]; extern const char kSyncPrevSeed[]; -// String of current device namefor sync extern const char kSyncDeviceName[]; -// The initial bookmarks order, in a format of -// "<1(desktop)|2(mobile)>.."> extern const char kSyncBookmarksBaseOrder[]; -// Boolean, whether sync is enabled for the current device -// If true, then sync is enabled and running -// If false, then sync is not enabled or not running (disabled after enabling, -// but seed and device id are configured) extern const char kSyncEnabled[]; extern const char kSyncBookmarksEnabled[]; extern const char kSyncSiteSettingsEnabled[]; extern const char kSyncHistoryEnabled[]; -// The latest time of synced bookmark record, field 'syncTimestamp' extern const char kSyncLatestRecordTime[]; -// The latest time of synced device record extern const char kSyncLatestDeviceRecordTime[]; -// The time of latest fetch records operation extern const char kSyncLastFetchTime[]; -// the list of all known sync devices -// TODO(bridiver) - this should be a dictionary - not raw json extern const char kSyncDeviceList[]; -// the sync api version from the server extern const char kSyncApiVersion[]; -// The version of bookmarks state: 0,1,... . -// Current to migrate to is 2. extern const char kSyncMigrateBookmarksVersion[]; -// Cached object_id list for unconfirmed records extern const char kSyncRecordsToResend[]; -// Meta info of kSyncRecordsToResend extern const char kSyncRecordsToResendMeta[]; -// Flag indicates we had recovered duplicated bookmarks object ids (deprecated) extern const char kDuplicatedBookmarksRecovered[]; +// ============================================================================ // Version indicates had recovered duplicated bookmarks object ids: // 2 - we had migrated object ids @@ -87,55 +66,10 @@ class Prefs { std::string GetSeed() const; void SetSeed(const std::string& seed); - std::string GetThisDeviceId() const; - void SetThisDeviceId(const std::string& device_id); - std::string GetThisDeviceIdV2() const; - void SetThisDeviceIdV2(const std::string& device_id_v2); - std::string GetThisDeviceObjectId() const; - void SetThisDeviceObjectId(const std::string& device_object_id); - std::string GetThisDeviceName() const; - void SetThisDeviceName(const std::string& device_name); - std::string GetBookmarksBaseOrder(); - void SetBookmarksBaseOrder(const std::string& order); - - bool GetSyncEnabled() const; - void SetSyncEnabled(const bool sync_this_device); - bool GetSyncBookmarksEnabled() const; - void SetSyncBookmarksEnabled(const bool sync_bookmarks_enabled); - bool GetSyncSiteSettingsEnabled() const; - void SetSyncSiteSettingsEnabled(const bool sync_site_settings); - bool GetSyncHistoryEnabled() const; - void SetSyncHistoryEnabled(const bool sync_history_enabled); - - void SetLatestRecordTime(const base::Time &time); - base::Time GetLatestRecordTime(); - void SetLatestDeviceRecordTime(const base::Time& time); - base::Time GetLatestDeviceRecordTime(); - void SetLastFetchTime(const base::Time &time); - base::Time GetLastFetchTime(); - void SetLastCompactTimeBookmarks(const base::Time &time); - base::Time GetLastCompactTimeBookmarks(); - - std::unique_ptr GetSyncDevices(); - void SetSyncDevices(const SyncDevices& sync_devices); - - std::string GetApiVersion(); - void SetApiVersion(const std::string& api_version); - - std::unique_ptr GetBraveSyncSettings() const; int GetMigratedBookmarksVersion(); void SetMigratedBookmarksVersion(const int); - std::vector GetRecordsToResend() const; - void AddToRecordsToResend(const std::string& object_id, - std::unique_ptr meta); - void RemoveFromRecordsToResend(const std::string& object_id); - const base::DictionaryValue* GetRecordToResendMeta( - const std::string& object_id) const; - void SetRecordToResendMeta(const std::string& object_id, - std::unique_ptr meta); - void Clear(); private: diff --git a/components/brave_sync/brave_sync_service.cc b/components/brave_sync/brave_sync_service.cc deleted file mode 100644 index a196be76303f..000000000000 --- a/components/brave_sync/brave_sync_service.cc +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/brave_sync_service.h" - -#include "brave/components/brave_sync/brave_sync_service_observer.h" - -namespace brave_sync { - -BraveSyncService::BraveSyncService() {} -BraveSyncService::~BraveSyncService() {} - -void BraveSyncService::AddObserver(BraveSyncServiceObserver* observer) { - observers_.AddObserver(observer); -} - -void BraveSyncService::RemoveObserver(BraveSyncServiceObserver* observer) { - observers_.RemoveObserver(observer); -} - -} // namespace brave_sync diff --git a/components/brave_sync/brave_sync_service.h b/components/brave_sync/brave_sync_service.h deleted file mode 100644 index 75d894422c8b..000000000000 --- a/components/brave_sync/brave_sync_service.h +++ /dev/null @@ -1,69 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_SERVICE_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_SERVICE_H_ - -#include -#include - -#include "base/macros.h" -#include "base/observer_list.h" -#include "extensions/buildflags/buildflags.h" - -class Profile; - -namespace brave_sync { - -class BraveSyncClient; -class BraveSyncServiceObserver; -class Settings; -class SyncDevices; - -class BraveSyncService { - public: - BraveSyncService(); - virtual ~BraveSyncService(); - - typedef base::Callback, - std::unique_ptr)> - GetSettingsAndDevicesCallback; - - virtual void OnSetupSyncHaveCode( - const std::string& sync_words, - const std::string& device_name) = 0; - virtual void OnSetupSyncNewToSync(const std::string& device_name) = 0; - virtual void OnDeleteDevice(const std::string& device_id_v2) = 0; - virtual void OnResetSync() = 0; - virtual void GetSettingsAndDevices( - const GetSettingsAndDevicesCallback& callback) = 0; - - virtual void GetSyncWords() = 0; - virtual std::string GetSeed() = 0; - - virtual void OnSetSyncEnabled(const bool enabled) = 0; - virtual void OnSetSyncBookmarks(const bool sync_bookmarks) = 0; - virtual void OnSetSyncBrowsingHistory(const bool sync_browsing_history) = 0; - virtual void OnSetSyncSavedSiteSettings( - const bool sync_saved_site_settings) = 0; - - void AddObserver(BraveSyncServiceObserver* observer); - void RemoveObserver(BraveSyncServiceObserver* observer); - -#if BUILDFLAG(ENABLE_EXTENSIONS) - virtual BraveSyncClient* GetBraveSyncClient() = 0; -#endif - - - protected: - base::ObserverList observers_; - - private: - DISALLOW_COPY_AND_ASSIGN(BraveSyncService); -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_SERVICE_H_ diff --git a/components/brave_sync/brave_sync_service_observer.h b/components/brave_sync/brave_sync_service_observer.h deleted file mode 100644 index e016c89631a5..000000000000 --- a/components/brave_sync/brave_sync_service_observer.h +++ /dev/null @@ -1,25 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_SERVICE_OBSERVER_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_SERVICE_OBSERVER_H_ - -namespace brave_sync { - -class BraveSyncService; - -class BraveSyncServiceObserver : public base::CheckedObserver { - public: - ~BraveSyncServiceObserver() override {} - - virtual void OnSyncSetupError(BraveSyncService* sync_service, - const std::string& error) {} - virtual void OnSyncStateChanged(BraveSyncService* sync_service) {} - virtual void OnHaveSyncWords(BraveSyncService* sync_service, - const std::string& sync_words) {} -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_SERVICE_OBSERVER_H_ diff --git a/components/brave_sync/brave_sync_service_unittest.cc b/components/brave_sync/brave_sync_service_unittest.cc deleted file mode 100644 index fcd971abef71..000000000000 --- a/components/brave_sync/brave_sync_service_unittest.cc +++ /dev/null @@ -1,1761 +0,0 @@ -/* Copyright 2016 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include -#include -#include - -#include "base/files/scoped_temp_dir.h" -#include "base/strings/utf_string_conversions.h" -#include "brave/components/brave_sync/brave_profile_sync_service_impl.h" -#include "brave/components/brave_sync/brave_sync_prefs.h" -#include "brave/components/brave_sync/brave_sync_service.h" -#include "brave/components/brave_sync/brave_sync_service_observer.h" -#include "brave/components/brave_sync/client/brave_sync_client_impl.h" -#include "brave/components/brave_sync/client/client_ext_impl_data.h" -#include "brave/components/brave_sync/features.h" -#include "brave/components/brave_sync/jslib_const.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/settings.h" -#include "brave/components/brave_sync/sync_devices.h" -#include "brave/components/brave_sync/test_util.h" -#include "brave/components/brave_sync/tools.h" -#include "brave/components/brave_sync/values_conv.h" -#include "chrome/browser/bookmarks/bookmark_model_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" -#include "components/bookmarks/browser/bookmark_model.h" -#include "components/bookmarks/browser/bookmark_utils.h" -#include "components/bookmarks/test/test_bookmark_client.h" -#include "components/prefs/pref_service.h" -#include "components/sync/base/pref_names.h" -#include "content/public/browser/network_service_instance.h" -#include "content/public/test/browser_task_environment.h" -#include "net/base/network_interfaces.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -// npm run test -- brave_unit_tests --filter=BraveSyncServiceTest.* - -// BraveSyncClient::methods -// Name | Covered -//------------------------------------ -// SetSyncToBrowserHandler | -// GetSyncToBrowserHandler | -// SendGotInitData | OnGetInitData -// SendFetchSyncRecords | -// SendResolveSyncRecords | -// SendSyncRecords | -// SendDeleteSyncUser | -// SendDeleteSyncCategory | -// SendGetBookmarksBaseOrder| -// OnExtensionInitialized | - -// BraveSyncService::methods -// Name | Covered -//------------------------------------- -// OnSetupSyncHaveCode | + -// OnSetupSyncNewToSync | + -// OnDeleteDevice | + -// OnResetSync | + -// GetSettingsAndDevices | + -// GetSyncWords | + -// GetSeed | + -// OnSetSyncEnabled | + -// OnSetSyncBookmarks | + -// OnSetSyncBrowsingHistory | + -// OnSetSyncSavedSiteSettings| + -// AddObserver | +, SetUp -// RemoveObserver | +, Teardown -// GetSyncClient | +, SetUp - -// BraveSyncService SyncMessageHandler overrides -// Name | Covered -//------------------------------------- -// BackgroundSyncStarted | N/A -// BackgroundSyncStopped | + -// OnSyncDebug | + -// OnSyncSetupError | Need UI handler -// OnGetInitData | + -// OnSaveInitData | BraveSyncServiceTest.GetSeed -// OnSyncReady | + -// OnGetExistingObjects | + -// OnResolvedSyncRecords | N/A -// OnDeletedSyncUser | N/A -// OnDeleteSyncSiteSettings | N/A -// OnSaveBookmarksBaseOrder | + -// OnResolvedHistorySites | N/A -// OnResolvedPreferences | BraveSyncServiceTest.OnDeleteDevice, -// | BraveSyncServiceTest.OnResetSync -// OnBraveSyncPrefsChanged | + - -using bookmarks::BookmarkModel; -using brave_sync::BraveProfileSyncServiceImpl; -using brave_sync::BraveSyncService; -using brave_sync::BraveSyncServiceObserver; -using brave_sync::MockBraveSyncClient; -using brave_sync::RecordsList; -using brave_sync::RecordsListPtr; -using brave_sync::SimpleBookmarkSyncRecord; -using brave_sync::SimpleDeviceRecord; -using brave_sync::SimpleFolderSyncRecord; -using brave_sync::jslib_const::kBookmarks; -using brave_sync::jslib_const::kPreferences; -using brave_sync::jslib::SyncRecord; -using brave_sync::tools::AsMutable; -using brave_sync::tools::GenerateObjectId; -using brave_sync::tools::GenerateObjectIdForOtherNode; -using brave_sync::tools::kOtherNodeName; -using brave_sync::tools::kOtherNodeOrder; -using testing::_; -using testing::AtLeast; - -namespace { - -const bookmarks::BookmarkNode* GetSingleNodeByUrl( - bookmarks::BookmarkModel* model, - const std::string& url) { - std::vector nodes; - model->GetNodesByURL(GURL(url), &nodes); - size_t nodes_size = nodes.size(); - CHECK_EQ(nodes_size, 1u); - const bookmarks::BookmarkNode* node = nodes.at(0); - return node; -} - -bool DevicesContains(brave_sync::SyncDevices* devices, - const std::string& id, - const std::string& id_v2, - const std::string& name) { - DCHECK(devices); - for (const auto& device : devices->devices_) { - if (device.device_id_ == id && device.name_ == name && - device.device_id_v2_ == id_v2) { - return true; - } - } - return false; -} - -MATCHER_P3(ContainsDeviceRecord, - action, - name, - device_id_v2, - "contains device sync record with params") { - for (const auto& record : arg) { - if (record->has_device()) { - const auto& device = record->GetDevice(); - if (record->action == action && device.name == name && - device.deviceIdV2 == device_id_v2) { - return true; - } - } - } - return false; -} - -MATCHER_P(MatchBookmarksRecords, - records, - "Match bookmark sync records") { - if (arg.size() != records->size()) - return false; - for (size_t i = 0; i < arg.size(); ++i) { - if (!arg.at(i)->has_bookmark() || !records->at(i)->has_bookmark()) - return false; - if (!arg.at(i)->Matches(*records->at(i).get())) - return false; - } - return true; -} - -base::TimeDelta g_overridden_time_delta; -base::Time g_overridden_now; - -std::unique_ptr OverrideForTimeDelta( - base::TimeDelta overridden_time_delta, - const base::Time& now = base::subtle::TimeNowIgnoringOverride()) { - g_overridden_time_delta = overridden_time_delta; - g_overridden_now = now; - return std::make_unique( - []() { return g_overridden_now + g_overridden_time_delta; }, nullptr, - nullptr); -} - -} // namespace - -class MockBraveSyncServiceObserver : public BraveSyncServiceObserver { - public: - MockBraveSyncServiceObserver() {} - - MOCK_METHOD2(OnSyncSetupError, void(BraveSyncService*, const std::string&)); - MOCK_METHOD1(OnSyncStateChanged, void(BraveSyncService*)); - MOCK_METHOD2(OnHaveSyncWords, void(BraveSyncService*, const std::string&)); -}; - -class BraveSyncServiceTest : public testing::Test { - public: - BraveSyncServiceTest() {} - ~BraveSyncServiceTest() override {} - - protected: - void SetUp() override { - EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); - // register the factory - - profile_ = brave_sync::CreateBraveSyncProfile(temp_dir_.GetPath()); - EXPECT_TRUE(profile_.get() != NULL); - - sync_prefs_ = std::make_unique(profile_->GetPrefs()); - - SetBookmarkModelFactory(); - - model_ = BookmarkModelFactory::GetForBrowserContext( - Profile::FromBrowserContext(profile_.get())); - EXPECT_NE(model(), nullptr); - - sync_client_ = new MockBraveSyncClient(); - brave_sync::BraveSyncClientImpl::set_for_testing(sync_client_); - - sync_service_ = static_cast( - ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile( - profile())); - - EXPECT_EQ(sync_client_, sync_service_->GetBraveSyncClient()); - - observer_.reset(new MockBraveSyncServiceObserver); - sync_service_->BraveSyncService::AddObserver(observer_.get()); - EXPECT_TRUE(sync_service_ != NULL); - } - - void TearDown() override { - sync_service_->BraveSyncService::RemoveObserver(observer_.get()); - // this will also trigger a shutdown of the brave sync service - sync_service_->Shutdown(); - sync_prefs_.reset(); - profile_.reset(); - } - - virtual void SetBookmarkModelFactory() { - // TODO(bridiver) - this is temporary until some changes are made to - // to bookmark_change_processor to allow `set_for_testing` like - // BraveSyncClient - BookmarkModelFactory::GetInstance()->SetTestingFactory( - profile(), - base::BindRepeating(&brave_sync::BuildFakeBookmarkModelForTests)); - } - - Profile* profile() { return profile_.get(); } - BraveProfileSyncServiceImpl* sync_service() { return sync_service_; } - MockBraveSyncClient* sync_client() { return sync_client_; } - BookmarkModel* model() { return model_; } - MockBraveSyncServiceObserver* observer() { return observer_.get(); } - brave_sync::prefs::Prefs* brave_sync_prefs() { - return sync_service_->brave_sync_prefs_.get(); - } - syncer::SyncPrefs* sync_prefs() { return sync_prefs_.get(); } - - // Common part of OnResetSync and OnResetSyncWhenOffline tests - void VerifyResetDone(); - - private: - // Need this as a very first member to run tests in UI thread - // When this is set, class should not install any other MessageLoops, like - // base::test::ScopedTaskEnvironment - content::BrowserTaskEnvironment task_environment_; - std::unique_ptr profile_; - BraveProfileSyncServiceImpl* sync_service_; - MockBraveSyncClient* sync_client_; - BookmarkModel* model_; // Not owns - std::unique_ptr sync_prefs_; - std::unique_ptr observer_; - - base::ScopedTempDir temp_dir_; -}; - -class BraveSyncServiceTestDelayedLoadModel : public BraveSyncServiceTest { - public: - void SetBookmarkModelFactory() override { - BookmarkModelFactory::GetInstance()->SetTestingFactory( - profile(), - base::BindRepeating(&BraveSyncServiceTestDelayedLoadModel::BuildModel, - base::Unretained(this))); - } - void ModelDoneLoading() { - model()->DoneLoading(std::move(bookmark_load_details_)); - } - - private: - std::unique_ptr BuildModel(content::BrowserContext* context) { - using bookmarks::BookmarkClient; - using bookmarks::BookmarkLoadDetails; - using bookmarks::BookmarkModel; - using bookmarks::TestBookmarkClient; - std::unique_ptr client(new TestBookmarkClient()); - BookmarkClient* client_ptr = client.get(); - std::unique_ptr bookmark_model( - new BookmarkModel(std::move(client))); - bookmark_load_details_ = std::make_unique(client_ptr); - bookmark_load_details_->LoadManagedNode(); - bookmark_load_details_->CreateUrlIndex(); - // By intent don't call BookmarkModel::DoneLoading - return bookmark_model; - } - std::unique_ptr bookmark_load_details_; -}; - -TEST_F(BraveSyncServiceTest, SetSyncEnabled) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - sync_service()->OnSetSyncEnabled(true); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - EXPECT_FALSE(sync_service()->brave_sync_ready_); -} - -TEST_F(BraveSyncServiceTest, SetSyncDisabled) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnSetSyncEnabled(true); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnSetSyncEnabled(false); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - EXPECT_FALSE(sync_service()->brave_sync_ready_); -} - -TEST_F(BraveSyncServiceTest, IsSyncReadyOnNewProfile) { - EXPECT_FALSE(sync_service()->brave_sync_ready_); -} - -const char kTestWords1[] = - "absurd avoid scissors anxiety gather lottery category door " - "army half long cage bachelor another expect people blade " - "school educate curtain scrub monitor lady beyond"; - -TEST_F(BraveSyncServiceTest, OnSetupSyncHaveCode) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - // Expecting sync state changed twice: for enabled state and for device name - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - sync_service()->OnSetupSyncHaveCode(kTestWords1, "test_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); -} - -TEST_F(BraveSyncServiceTest, OnSetupSyncHaveCodeIncorrectCode) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(0); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(0); - EXPECT_CALL(*observer(), - OnSyncSetupError(sync_service(), "ERR_SYNC_WRONG_WORDS")) - .Times(1); - sync_service()->OnSetupSyncHaveCode("wrong code", "test_device"); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); -} - -TEST_F(BraveSyncServiceTest, OnSetupSyncHaveCodeEmptyCode) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(0); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(0); - EXPECT_CALL(*observer(), - OnSyncSetupError(sync_service(), "ERR_SYNC_WRONG_WORDS")) - .Times(1); - sync_service()->OnSetupSyncHaveCode("", "test_device"); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); -} - -TEST_F(BraveSyncServiceTest, OnSetupSyncHaveCodeEmptyDeviceName) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - // Expecting sync state changed twice: for enabled state and for device name - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - sync_service()->OnSetupSyncHaveCode(kTestWords1, ""); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - EXPECT_EQ( - profile()->GetPrefs()->GetString(brave_sync::prefs::kSyncDeviceName), - net::GetHostName()); -} - -TEST_F(BraveSyncServiceTest, OnSetupSyncNewToSync) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - // Expecting sync state changed twice: for enabled state and for device name - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - sync_service()->OnSetupSyncNewToSync("test_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); -} - -TEST_F(BraveSyncServiceTest, OnSetupSyncNewToSyncEmptyDeviceName) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - // Expecting sync state changed twice: for enabled state and for device name - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - sync_service()->OnSetupSyncNewToSync(""); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - EXPECT_EQ( - profile()->GetPrefs()->GetString(brave_sync::prefs::kSyncDeviceName), - net::GetHostName()); -} - -TEST_F(BraveSyncServiceTest, GetSettingsAndDevices) { - // The test absorbs OnSetupSyncNewToSync test - auto callback1 = - base::BindRepeating([](std::unique_ptr settings, - std::unique_ptr devices) { - EXPECT_TRUE(settings->this_device_name_.empty()); - EXPECT_TRUE(settings->this_device_id_.empty()); - EXPECT_FALSE(settings->sync_configured_); - EXPECT_FALSE(settings->sync_this_device_); - EXPECT_FALSE(settings->sync_bookmarks_); - EXPECT_FALSE(settings->sync_settings_); - EXPECT_FALSE(settings->sync_history_); - EXPECT_EQ(devices->size(), 0u); - }); - - sync_service()->GetSettingsAndDevices(callback1); - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - // Expecting sync state changed twice: for enabled state and for device name - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - sync_service()->OnSetupSyncNewToSync("test_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - auto callback2 = - base::BindRepeating([](std::unique_ptr settings, - std::unique_ptr devices) { - // Other fields may be switched later - EXPECT_EQ(settings->this_device_name_, "test_device"); - EXPECT_TRUE(settings->sync_this_device_); - }); - sync_service()->GetSettingsAndDevices(callback2); -} - -TEST_F(BraveSyncServiceTest, GetSyncWords) { - brave_sync_prefs()->SetSeed( - "247,124,20,15,38,187,78,131,12,125,165,67,221,207,143,120,166,118,77," - "107,128,115,21,66,254,154,99,38,205,220,244,245"); - std::string words = - "wash thing adult estate reject dose cradle regret duck unveil toilet " - "vanish guess chase puppy attack best blood pledge shock holiday unveil " - "stable ring"; - EXPECT_CALL(*observer(), OnHaveSyncWords(sync_service(), words)).Times(1); - sync_service()->GetSyncWords(); -} - -TEST_F(BraveSyncServiceTest, SyncSetupError) { - EXPECT_CALL(*observer(), OnSyncSetupError(sync_service(), _)).Times(1); - sync_service()->OnSetupSyncHaveCode("", ""); -} - -TEST_F(BraveSyncServiceTest, GetSeed) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())) - .Times(AtLeast(2)); - sync_service()->OnSetupSyncNewToSync("test_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - // Service gets seed from client via BraveSyncServiceImpl::OnSaveInitData - const auto binary_seed = brave_sync::Uint8Array(16, 77); - - const std::string device_id_v2 = "beef12"; - sync_service()->OnSaveInitData(binary_seed, {0}, device_id_v2); - std::string expected_seed = brave_sync::StrFromUint8Array(binary_seed); - EXPECT_EQ(sync_service()->GetSeed(), expected_seed); - EXPECT_EQ(brave_sync_prefs()->GetThisDeviceIdV2(), device_id_v2); -} - -TEST_F(BraveSyncServiceTest, OnDeleteDevice) { - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "beef01", - "device1")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "2", "beef02", - "device2")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "3", "beef03", - "device3")); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnResolvedPreferences(records); - - brave_sync_prefs()->SetThisDeviceId("1"); - brave_sync_prefs()->SetThisDeviceIdV2("beef01"); - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "1", "beef01", "device1")); - EXPECT_TRUE(DevicesContains(devices.get(), "2", "beef02", "device2")); - EXPECT_TRUE(DevicesContains(devices.get(), "3", "beef03", "device3")); - - EXPECT_CALL(*sync_client(), - SendSyncRecords(kPreferences, - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "device3", "beef03"))) - .Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, _, _)); - sync_service()->OnDeleteDevice("beef03"); - - RecordsList resolved_records; - auto resolved_record = SyncRecord::Clone(*records.at(2)); - resolved_record->action = SyncRecord::Action::A_DELETE; - resolved_records.push_back(std::move(resolved_record)); - - // Emulate we have twice the same delete device record to ensure we - // don't have failed DCHECK in debug build - auto resolved_record2 = SyncRecord::Clone(*records.at(2)); - resolved_record2->action = SyncRecord::Action::A_DELETE; - resolved_records.push_back(std::move(resolved_record2)); - - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnResolvedPreferences(resolved_records); - - auto devices_final = brave_sync_prefs()->GetSyncDevices(); - EXPECT_TRUE(DevicesContains(devices_final.get(), "1", "beef01", "device1")); - EXPECT_TRUE(DevicesContains(devices_final.get(), "2", "beef02", "device2")); - EXPECT_FALSE(DevicesContains(devices_final.get(), "3", "beef03", "device3")); -} - -TEST_F(BraveSyncServiceTest, OnDeleteDeviceWhenOneDevice) { - const std::string object_id_1 = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 1"; - const std::string object_id_2 = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 2"; - brave_sync_prefs()->SetThisDeviceId("1"); - brave_sync_prefs()->SetThisDeviceObjectId(object_id_1); - brave_sync_prefs()->SetThisDeviceIdV2("beef01"); - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id_1, "1", - "beef01", "device1")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id_2, "2", - "beef02", "device2")); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnResolvedPreferences(records); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "1", "beef01", "device1")); - EXPECT_TRUE(DevicesContains(devices.get(), "2", "beef02", "device2")); - - EXPECT_CALL(*sync_client(), SendSyncRecords).Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, _, _)); - sync_service()->OnDeleteDevice("beef02"); - - RecordsList resolved_records; - auto resolved_record = SyncRecord::Clone(*records.at(1)); - resolved_record->action = SyncRecord::Action::A_DELETE; - resolved_records.push_back(std::move(resolved_record)); - // Expecting to be called one time to set the new devices list - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - - EXPECT_CALL(*sync_client(), SendSyncRecords).Times(0); - - // Still enabled - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(0); - - sync_service()->OnResolvedPreferences(resolved_records); - - auto devices_semi_final = brave_sync_prefs()->GetSyncDevices(); - EXPECT_FALSE(DevicesContains(devices_semi_final.get(), "2", "beef02", - "device2")); - EXPECT_TRUE(DevicesContains(devices_semi_final.get(), "1", "beef01", - "device1")); -} - -TEST_F(BraveSyncServiceTest, OnDeleteDeviceWhenSelfDeleted) { - const std::string object_id_1 = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 1"; - const std::string object_id_2 = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 2"; - brave_sync_prefs()->SetThisDeviceId("1"); - brave_sync_prefs()->SetThisDeviceObjectId(object_id_1); - brave_sync_prefs()->SetThisDeviceIdV2("beef01"); - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - brave_sync_prefs()->SetSyncEnabled(true); - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id_1, "1", - "beef01", "device1")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id_2, "2", - "beef02", "device2")); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnResolvedPreferences(records); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "1", "beef01", "device1")); - EXPECT_TRUE(DevicesContains(devices.get(), "2", "beef02", "device2")); - - EXPECT_CALL(*sync_client(), - SendSyncRecords(kPreferences, - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "device1", "beef01"))) - .Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, _, _)); - sync_service()->OnDeleteDevice("beef01"); - - // Enabled->Disabled - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - RecordsList resolved_records; - auto resolved_record = SyncRecord::Clone(*records.at(0)); - resolved_record->action = SyncRecord::Action::A_DELETE; - resolved_records.push_back(std::move(resolved_record)); - // If you have to modify .Times(3) to another value, double re-check - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(3); - sync_service()->OnResolvedPreferences(resolved_records); - - EXPECT_FALSE(brave_sync_prefs()->GetSyncEnabled()); - - auto devices_final = brave_sync_prefs()->GetSyncDevices(); - EXPECT_FALSE(DevicesContains(devices_final.get(), "1", "beef01", "device1")); - EXPECT_FALSE(DevicesContains(devices_final.get(), "2", "beef02", "device2")); -} - -void BraveSyncServiceTest::VerifyResetDone() { - EXPECT_TRUE(profile() - ->GetPrefs() - ->GetString(brave_sync::prefs::kSyncDeviceId) - .empty()); - EXPECT_TRUE( - profile()->GetPrefs()->GetString(brave_sync::prefs::kSyncSeed).empty()); - EXPECT_TRUE(profile() - ->GetPrefs() - ->GetString(brave_sync::prefs::kSyncDeviceName) - .empty()); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncBookmarksEnabled)); - EXPECT_TRUE(profile() - ->GetPrefs() - ->GetString(brave_sync::prefs::kSyncBookmarksBaseOrder) - .empty()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncSiteSettingsEnabled)); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncHistoryEnabled)); - EXPECT_TRUE(profile() - ->GetPrefs() - ->GetTime(brave_sync::prefs::kSyncLatestRecordTime) - .is_null()); - EXPECT_TRUE(profile() - ->GetPrefs() - ->GetTime(brave_sync::prefs::kSyncLastFetchTime) - .is_null()); - EXPECT_TRUE(profile() - ->GetPrefs() - ->GetString(brave_sync::prefs::kSyncDeviceList) - .empty()); - EXPECT_EQ( - profile()->GetPrefs()->GetString(brave_sync::prefs::kSyncApiVersion), - "0"); - - EXPECT_FALSE(sync_service()->brave_sync_ready_); - - EXPECT_FALSE(sync_prefs()->IsSyncRequested()); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(syncer::prefs::kSyncBookmarks)); -} - -TEST_F(BraveSyncServiceTest, OnResetSync) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(AtLeast(1)); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())) - .Times(AtLeast(3)); - sync_service()->OnSetupSyncNewToSync("this_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - const std::string object_id_0 = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 0"; - const std::string object_id_1 = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 1"; - brave_sync_prefs()->SetThisDeviceId("0"); - brave_sync_prefs()->SetThisDeviceObjectId(object_id_0); - brave_sync_prefs()->SetThisDeviceIdV2("beef00"); - - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id_0, "0", - "beef00", "this_device")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id_1, "1", - "beef01", "device1")); - - sync_service()->OnResolvedPreferences(records); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "0", "beef00", "this_device")); - EXPECT_TRUE(DevicesContains(devices.get(), "1", "beef01", "device1")); - - EXPECT_CALL(*sync_client(), - SendSyncRecords(kPreferences, - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "this_device", "beef00"))) - .Times(1); - - EXPECT_CALL(*sync_client(), SendFetchSyncRecords); - sync_service()->OnResetSync(); - RecordsList resolved_records; - auto resolved_record = SyncRecord::Clone(*records.at(0)); - resolved_record->action = SyncRecord::Action::A_DELETE; - resolved_records.push_back(std::move(resolved_record)); - - sync_service()->OnResolvedPreferences(resolved_records); - - auto devices_final = brave_sync_prefs()->GetSyncDevices(); - EXPECT_FALSE(DevicesContains(devices_final.get(), "0", "beef00", - "this_device")); - EXPECT_FALSE(DevicesContains(devices_final.get(), "1", "beef01", - "device1")); - - VerifyResetDone(); -} - -TEST_F(BraveSyncServiceTest, OnResetSyncWhenOffline) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(AtLeast(1)); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())) - .Times(AtLeast(3)); - sync_service()->OnSetupSyncNewToSync("this_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - brave_sync_prefs()->SetThisDeviceId("0"); - brave_sync_prefs()->SetThisDeviceIdV2("beef00"); - - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "0", "beef00", - "this_device")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "beef01", - "device1")); - - sync_service()->OnResolvedPreferences(records); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "0", "beef00", "this_device")); - EXPECT_TRUE(DevicesContains(devices.get(), "1", "beef01", "device1")); - - EXPECT_CALL(*sync_client(), - SendSyncRecords(kPreferences, - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "this_device", "beef00"))) - .Times(1); - - EXPECT_CALL(*sync_client(), SendFetchSyncRecords); - EXPECT_FALSE(sync_service()->pending_self_reset_); - sync_service()->OnResetSync(); - EXPECT_TRUE(sync_service()->pending_self_reset_); - - auto recordsSent = std::make_unique(); - sync_service()->OnRecordsSent(kPreferences, std::move(recordsSent)); - EXPECT_FALSE(sync_service()->pending_self_reset_); - - auto devices_final = brave_sync_prefs()->GetSyncDevices(); - EXPECT_FALSE(DevicesContains(devices_final.get(), "0", "beef00", - "this_device")); - EXPECT_FALSE(DevicesContains(devices_final.get(), "1", "beef01", - "device1")); - - VerifyResetDone(); -} - -TEST_F(BraveSyncServiceTest, OnSetSyncBookmarks) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncBookmarksEnabled)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(1); - sync_service()->OnSetSyncBookmarks(true); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(syncer::prefs::kSyncBookmarks)); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncBookmarksEnabled)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(1); - sync_service()->OnSetSyncBookmarks(false); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncBookmarksEnabled)); - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(syncer::prefs::kSyncBookmarks)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(0); - sync_service()->OnSetSyncBookmarks(false); -} - -TEST_F(BraveSyncServiceTest, OnSetSyncBrowsingHistory) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncHistoryEnabled)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(1); - sync_service()->OnSetSyncBrowsingHistory(true); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncHistoryEnabled)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(1); - sync_service()->OnSetSyncBrowsingHistory(false); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncHistoryEnabled)); -} - -TEST_F(BraveSyncServiceTest, OnSetSyncSavedSiteSettings) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncSiteSettingsEnabled)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(1); - sync_service()->OnSetSyncSavedSiteSettings(true); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncSiteSettingsEnabled)); - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(1); - sync_service()->OnSetSyncSavedSiteSettings(false); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - brave_sync::prefs::kSyncSiteSettingsEnabled)); -} - -TEST_F(BraveSyncServiceTest, OnGetInitData) { - EXPECT_CALL(*sync_client(), SendGotInitData).Times(1); - sync_service()->OnGetInitData("v1.4.2"); -} - -TEST_F(BraveSyncServiceTest, OnSaveBookmarksBaseOrder) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - // kSyncEnabled and kSyncBookmarksEnabled - EXPECT_CALL(*observer(), OnSyncStateChanged).Times(2); - sync_service()->OnSetSyncEnabled(true); - sync_service()->OnSaveBookmarksBaseOrder("1.1."); - EXPECT_EQ(profile()->GetPrefs()->GetString( - brave_sync::prefs::kSyncBookmarksBaseOrder), - "1.1."); - // Permanent node order - std::string order; - model()->bookmark_bar_node()->GetMetaInfo("order", &order); - EXPECT_EQ(order, "1.1.1"); - order.clear(); - model()->other_node()->GetMetaInfo("order", &order); - EXPECT_EQ(order, kOtherNodeOrder); - EXPECT_EQ(brave_sync_prefs()->GetMigratedBookmarksVersion(), 2); -} - -TEST_F(BraveSyncServiceTest, OnBraveSyncPrefsChanged) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged); - sync_service()->OnBraveSyncPrefsChanged(brave_sync::prefs::kSyncEnabled); -} - -void OnGetRecordsStub(std::unique_ptr records) {} - -TEST_F(BraveSyncServiceTest, SetThisDeviceCreatedTime) { - EXPECT_TRUE(brave_sync::tools::IsTimeEmpty( - sync_service()->this_device_created_time_)); - - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged); - brave_sync_prefs()->SetSyncEnabled(true); - brave_sync_prefs()->SetThisDeviceId("1"); - brave_sync_prefs()->SetThisDeviceIdV2("beef01"); - - brave_sync::GetRecordsCallback on_get_records = - base::BindOnce(&OnGetRecordsStub); - base::WaitableEvent we; - EXPECT_CALL(*sync_client(), SendSyncRecords(kPreferences, _)); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords); - sync_service()->OnPollSyncCycle(std::move(on_get_records), &we); - - EXPECT_FALSE(brave_sync::tools::IsTimeEmpty( - sync_service()->this_device_created_time_)); -} - -TEST_F(BraveSyncServiceTest, OnSyncReadyNewToSync) { - sync_prefs()->SetSyncRequested(false); - EXPECT_CALL(*observer(), OnSyncStateChanged); - EXPECT_CALL(*sync_client(), SendGetBookmarksBaseOrder).Times(1); - sync_service()->OnSyncReady(); - - // simulate OnSaveBookmarksBaseOrder - profile()->GetPrefs()->SetString(brave_sync::prefs::kSyncBookmarksBaseOrder, - "1.1."); - sync_service()->OnSyncReady(); - EXPECT_TRUE(sync_prefs()->IsSyncRequested()); - - // We want to have Chromium syncer bookmarks be enabled from begin to avoid - // reaching BookmarkModelAssociator::AssociateModels - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(syncer::prefs::kSyncBookmarks)); -} - -TEST_F(BraveSyncServiceTestDelayedLoadModel, OnSyncReadyModelNotYetLoaded) { - EXPECT_NE(sync_service()->model_, nullptr); - EXPECT_FALSE(model()->loaded()); - profile()->GetPrefs()->SetString(brave_sync::prefs::kSyncBookmarksBaseOrder, - "1.1."); - - EXPECT_FALSE(sync_service()->is_model_loaded_observer_set_); - sync_service()->OnSyncReady(); - EXPECT_TRUE(sync_service()->is_model_loaded_observer_set_); - EXPECT_CALL(*observer(), OnSyncStateChanged); - ModelDoneLoading(); - - // This pref is enabled in observer, check wether the observer job done - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(syncer::prefs::kSyncBookmarks)); -} - -TEST_F(BraveSyncServiceTest, OnGetExistingObjects) { - EXPECT_CALL(*sync_client(), SendResolveSyncRecords).Times(1); - - auto records = std::make_unique(); - sync_service()->OnGetExistingObjects(kBookmarks, - std::move(records), base::Time(), false); -} - -TEST_F(BraveSyncServiceTest, GetPreferredDataTypes) { - // Make sure GetPreferredDataTypes contains DEVICE_INFO which is needed for - // brave device record polling - EXPECT_TRUE(sync_service()->GetPreferredDataTypes().Has(syncer::DEVICE_INFO)); -} - -TEST_F(BraveSyncServiceTest, GetDisableReasons) { - sync_prefs()->SetManagedForTest(true); - EXPECT_TRUE(sync_service()->GetDisableReasons().Has( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY) && - sync_service()->GetDisableReasons().Has( - syncer::SyncService::DISABLE_REASON_USER_CHOICE)); - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnSetSyncEnabled(true); - EXPECT_TRUE(sync_service()->GetDisableReasons().Has( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY) && - sync_service()->GetDisableReasons().Has( - syncer::SyncService::DISABLE_REASON_USER_CHOICE)); - brave_sync_prefs()->SetMigratedBookmarksVersion(2); - EXPECT_TRUE(sync_service()->GetDisableReasons().Empty()); - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnSetSyncEnabled(false); - EXPECT_TRUE(sync_service()->HasDisableReason( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)); -} - -TEST_F(BraveSyncServiceTest, OnSetupSyncHaveCode_Reset_SetupAgain) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - // Expecting sync state changed twice: for enabled state and for device name - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - sync_service()->OnSetupSyncHaveCode(kTestWords1, "test_device"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - brave_sync::Uint8Array seed = {1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16}; - brave_sync::Uint8Array device_id = {0}; - const std::string device_id_v2 = "beef00"; - sync_service()->OnSaveInitData(seed, device_id, device_id_v2); - - const std::string object_id = "0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 0"; - brave_sync_prefs()->SetThisDeviceObjectId(object_id); - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, object_id, "0", "beef00", - "this_device")); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnResolvedPreferences(records); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - ASSERT_EQ(devices->size(), 1u); - EXPECT_TRUE(DevicesContains(devices.get(), "0", "beef00", "this_device")); - EXPECT_CALL(*sync_client(), - SendSyncRecords(kPreferences, - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "this_device", "beef00"))) - .Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords); - sync_service()->OnResetSync(); - - // Actual kSyncEnabled will go to false after receiving confirmation of - // this_device DELETE - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - // Emulating resolved with DELETE - records.at(0)->action = SyncRecord::Action::A_DELETE; - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - // Sync state is changed 4 times: - // 1) we do save updated devices list - // 2,3,4) we do ResetSyncInternal() which clears this device name, - // sync enabled and devices list - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(4); - sync_service()->OnResolvedPreferences(records); - - EXPECT_FALSE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(2); - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - sync_service()->OnSetupSyncHaveCode( - "anxiety path library anxiety gather lottery category door army half " - "long cage bachelor another expect people blade school " - "educate curtain scrub monitor lady arctic", - "test_device"); - - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); -} - -TEST_F(BraveSyncServiceTest, ExponentialResend) { - bookmarks::AddIfNotBookmarked(model(), GURL("https://a.com/"), - base::ASCIIToUTF16("A.com")); - // Explicitly set sync_timestamp, object_id and order because it is supposed - // to be set in syncer - auto* node = GetSingleNodeByUrl(model(), "https://a.com/"); - model()->SetNodeMetaInfo(node, "sync_timestamp", - std::to_string(base::Time::Now().ToJsTime())); - const char* record_a_object_id = - "121, 194, 37, 61, 199, 11, 166, 234, " - "214, 197, 45, 215, 241, 206, 219, 130"; - model()->SetNodeMetaInfo(node, "object_id", record_a_object_id); - const char* record_a_order = "1.1.1.1"; - model()->SetNodeMetaInfo(node, "order", record_a_order); - - brave_sync_prefs()->SetThisDeviceId("1"); - std::unique_ptr records = std::make_unique(); - records->push_back(SimpleBookmarkSyncRecord( - SyncRecord::Action::A_CREATE, record_a_object_id, "https://a.com/", - "A.com - title", record_a_order, "", - brave_sync_prefs()->GetThisDeviceId())); - - EXPECT_CALL(*sync_client(), SendSyncRecords(kBookmarks, _)).Times(1); - sync_service()->SendSyncRecords(kBookmarks, std::move(records)); - - EXPECT_EQ(brave_sync_prefs()->GetRecordsToResend().size(), 1u); - const base::DictionaryValue* meta = - brave_sync_prefs()->GetRecordToResendMeta(record_a_object_id); - int send_retry_number = -1; - meta->GetInteger("send_retry_number", &send_retry_number); - EXPECT_EQ(send_retry_number, 0); - double sync_timestamp = -1; - meta->GetDouble("sync_timestamp", &sync_timestamp); - EXPECT_NE(sync_timestamp, -1); - - int expected_send_retry_number = 0; - - static const std::vector exponential_waits = - brave_sync::BraveProfileSyncServiceImpl::GetExponentialWaitsForTests(); - const int max_send_retries = exponential_waits.size() - 1; - std::set should_sent_at; - size_t current_sum = 0; - for (size_t j = 0; j < exponential_waits.size(); ++j) { - current_sum += exponential_waits[j]; - should_sent_at.insert(current_sum); - } - should_sent_at.insert(current_sum + exponential_waits.back()); - auto contains = [](const std::set& set, int val) { - return set.find(val) != set.end(); - }; - // Following statemets are correct only if - // kExponentialWaits is {10, 20, 40, 80} - EXPECT_TRUE(contains(should_sent_at, 10)); - EXPECT_TRUE(contains(should_sent_at, 30)); - EXPECT_TRUE(contains(should_sent_at, 70)); - EXPECT_TRUE(contains(should_sent_at, 150)); - // emulate the wait time after reaching maximum retry - EXPECT_TRUE(contains(should_sent_at, 230)); - for (size_t i = 0; i <= 231 + 1; ++i) { - auto time_override = OverrideForTimeDelta(base::TimeDelta::FromMinutes(i)); - bool is_send_expected = contains(should_sent_at, i); - int expect_call_times = is_send_expected ? 1 : 0; - EXPECT_CALL(*sync_client(), SendSyncRecords(kBookmarks, _)) - .Times(expect_call_times); - sync_service()->ResendSyncRecords(kBookmarks); - - if (is_send_expected) { - if (++expected_send_retry_number > max_send_retries) - expected_send_retry_number = max_send_retries; - send_retry_number = -1; - meta = brave_sync_prefs()->GetRecordToResendMeta(record_a_object_id); - meta->GetInteger("send_retry_number", &send_retry_number); - EXPECT_EQ(send_retry_number, expected_send_retry_number); - } - } - - // resolve to confirm records - std::unique_ptr sent_records = std::make_unique(); - sent_records->push_back(SimpleBookmarkSyncRecord( - SyncRecord::Action::A_CREATE, record_a_object_id, "https://a.com/", - "A.com", "1.1.1.1", "", brave_sync_prefs()->GetThisDeviceId())); - auto timestamp_resolve = base::Time::Now(); - sent_records->at(0)->syncTimestamp = timestamp_resolve; - sync_service()->OnRecordsSent(kBookmarks, std::move(sent_records)); - - EXPECT_EQ(brave_sync_prefs()->GetRecordsToResend().size(), 0u); - EXPECT_EQ(brave_sync_prefs()->GetRecordToResendMeta(record_a_object_id), - nullptr); -} - -TEST_F(BraveSyncServiceTest, GetDevicesWithFetchSyncRecords) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged).Times(1); - EXPECT_CALL(*observer(), OnSyncStateChanged); - brave_sync_prefs()->SetSyncEnabled(true); - brave_sync_prefs()->SetThisDeviceId("1"); - brave_sync_prefs()->SetThisDeviceIdV2("beef01"); - - // Expecting SendFetchSyncRecords will be invoked - // after sync_service()->OnPollSyncCycle - EXPECT_EQ(brave_sync_prefs()->GetLastFetchTime(), base::Time()); - EXPECT_EQ(brave_sync_prefs()->GetLatestDeviceRecordTime(), base::Time()); - - using brave_sync::tools::IsTimeEmpty; - EXPECT_TRUE(IsTimeEmpty(sync_service()->this_device_created_time_)); - - brave_sync::GetRecordsCallback on_get_records = - base::BindOnce(&OnGetRecordsStub); - base::WaitableEvent we; - EXPECT_CALL(*sync_client(), SendSyncRecords("PREFERENCES", _)); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, base::Time(), _)); - sync_service()->OnPollSyncCycle(std::move(on_get_records), &we); - EXPECT_FALSE(IsTimeEmpty(sync_service()->this_device_created_time_)); - - // Emulate we received this device - auto records = std::make_unique(); - records->push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "beef01", - "device1")); - auto device1_timestamp = records->back()->syncTimestamp; - EXPECT_CALL(*sync_client(), SendResolveSyncRecords(kPreferences, _)).Times(1); - sync_service()->OnGetExistingObjects(kPreferences, std::move(records), - device1_timestamp, false); - - EXPECT_NE(brave_sync_prefs()->GetLastFetchTime(), base::Time()); - EXPECT_EQ(brave_sync_prefs()->GetLatestDeviceRecordTime(), device1_timestamp); - - // We have moved records into OnGetExistingObjects, so fill again - records = std::make_unique(); - records->push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "beef01", - "device1")); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())).Times(1); - sync_service()->OnResolvedSyncRecords(kPreferences, std::move(records)); - - EXPECT_FALSE(IsTimeEmpty(sync_service()->this_device_created_time_)); - - // Less than 70 seconds have passed, we should fetch with empty start_at - { - auto time_override = OverrideForTimeDelta(base::TimeDelta::FromSeconds(65)); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, base::Time(), _)) - .Times(1); - sync_service()->FetchDevices(); - } - - // More than 70 seconds have passed, we should fetch with non-empty start_at - { - auto time_override = OverrideForTimeDelta(base::TimeDelta::FromSeconds(75)); - EXPECT_CALL(*sync_client(), - SendFetchSyncRecords(_, base::Time(device1_timestamp), _)) - .Times(1); - sync_service()->FetchDevices(); - } -} - -TEST_F(BraveSyncServiceTest, SendCompact) { - EXPECT_EQ(brave_sync_prefs()->GetLastCompactTimeBookmarks(), base::Time()); - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords).Times(1); - sync_service()->FetchSyncRecords(true, false, true, 1000); - // timestamp is not writtend until we get CompactedSyncCategory - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords).Times(1); - sync_service()->FetchSyncRecords(true, false, true, 1000); - sync_service()->OnCompactComplete(kBookmarks); - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(0); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords).Times(1); - sync_service()->FetchSyncRecords(true, false, true, 1000); - { - auto time_override = OverrideForTimeDelta(base::TimeDelta::FromDays( - sync_service()->GetCompactPeriodInDaysForTests())); - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords).Times(1); - sync_service()->FetchSyncRecords(true, false, true, 1000); - sync_service()->OnCompactComplete(kBookmarks); - } - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(0); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords).Times(1); - sync_service()->FetchSyncRecords(true, false, true, 1000); -} - -TEST_F(BraveSyncServiceTest, MigratePrevSeed) { - profile()->GetPrefs()->SetString(brave_sync::prefs::kSyncPrevSeed, "1,2,3"); - MigrateBraveSyncPrefs(profile()->GetPrefs()); - EXPECT_EQ(profile()->GetPrefs()->GetString(brave_sync::prefs::kSyncPrevSeed), - ""); -} - -TEST_F(BraveSyncServiceTest, InitialFetchesStartWithZero) { - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, base::Time(), _)) - .Times(1); - sync_service()->FetchSyncRecords(true, false, false, 1000); - - const auto latest_bookmark_record_time = base::Time::Now(); - brave_sync_prefs()->SetLatestRecordTime(latest_bookmark_record_time); - sync_service()->this_device_created_time_ = base::Time::Now(); - - EXPECT_CALL(*sync_client(), SendCompact(kBookmarks)).Times(1); - EXPECT_CALL(*sync_client(), SendFetchSyncRecords(_, base::Time(), _)) - .Times(1); - sync_service()->FetchSyncRecords(true, false, false, 1000); - sync_service()->OnCompactComplete(kBookmarks); - - // Prior 70 sec we should use null start_at and after we should use - // the latest record time - { - auto time_override = OverrideForTimeDelta(base::TimeDelta::FromSeconds(71)); - EXPECT_CALL(*sync_client(), - SendFetchSyncRecords(_, latest_bookmark_record_time, _)) - .Times(1); - sync_service()->FetchSyncRecords(true, false, false, 1000); - } -} - -TEST_F(BraveSyncServiceTest, DeviceIdV2Migration) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())) - .Times(AtLeast(2)); - sync_service()->OnSetupSyncNewToSync("device0"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - // Service gets seed from client via BraveSyncServiceImpl::OnSaveInitData - const auto binary_seed = brave_sync::Uint8Array(16, 77); - - // emulate device without device id v2 - sync_service()->OnSaveInitData(binary_seed, {0}, ""); - std::string expected_seed = brave_sync::StrFromUint8Array(binary_seed); - EXPECT_EQ(sync_service()->GetSeed(), expected_seed); - EXPECT_EQ(brave_sync_prefs()->GetThisDeviceIdV2(), ""); - - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "0", "", - "device0")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "", - "device1")); - sync_service()->OnResolvedPreferences(records); - brave_sync_prefs()->SetLastFetchTime(base::Time::Now()); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "0", "", "device0")); - EXPECT_TRUE(DevicesContains(devices.get(), "1", "", "device1")); - - const std::string device_id_v2 = "beef00"; - // sync library will call SAVE_INIT_DATA to propagate device id v2 - sync_service()->OnSaveInitData(binary_seed, {0}, device_id_v2); - EXPECT_EQ(brave_sync_prefs()->GetThisDeviceIdV2(), device_id_v2); - - EXPECT_CALL(*sync_client(), - SendSyncRecords("PREFERENCES", - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "device0", device_id_v2))) - .Times(1); - EXPECT_CALL(*sync_client(), - SendSyncRecords("PREFERENCES", - ContainsDeviceRecord(SyncRecord::Action::A_CREATE, - "device0", device_id_v2))) - .Times(1); - - base::WaitableEvent we; - brave_sync::GetRecordsCallback on_get_records = - base::BindOnce(&OnGetRecordsStub); - sync_service()->OnPollSyncCycle(std::move(on_get_records), &we); -} - -TEST_F(BraveSyncServiceTest, DeviceIdV2MigrationDupDeviceId) { - EXPECT_CALL(*sync_client(), OnSyncEnabledChanged); - EXPECT_CALL(*observer(), OnSyncStateChanged(sync_service())) - .Times(AtLeast(2)); - sync_service()->OnSetupSyncHaveCode(kTestWords1, "device1"); - EXPECT_TRUE( - profile()->GetPrefs()->GetBoolean(brave_sync::prefs::kSyncEnabled)); - - // Service gets seed from client via BraveSyncServiceImpl::OnSaveInitData - const auto binary_seed = brave_sync::Uint8Array(16, 77); - - // emulate device with dup device id and without device id v2 - sync_service()->OnSaveInitData(binary_seed, {1}, ""); - std::string expected_seed = brave_sync::StrFromUint8Array(binary_seed); - EXPECT_EQ(sync_service()->GetSeed(), expected_seed); - EXPECT_EQ(brave_sync_prefs()->GetThisDeviceIdV2(), ""); - - RecordsList records; - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "0", "", - "device0")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "", - "device1")); - records.push_back( - SimpleDeviceRecord(SyncRecord::Action::A_CREATE, "", "1", "", - "device2")); - sync_service()->OnResolvedPreferences(records); - brave_sync_prefs()->SetLastFetchTime(base::Time::Now()); - - auto devices = brave_sync_prefs()->GetSyncDevices(); - - EXPECT_TRUE(DevicesContains(devices.get(), "0", "", "device0")); - EXPECT_TRUE(DevicesContains(devices.get(), "1", "", "device1")); - EXPECT_TRUE(DevicesContains(devices.get(), "1", "", "device2")); - - const std::string device_id_v2 = "beef01"; - // sync library will call SAVE_INIT_DATA to propagate device id v2 - sync_service()->OnSaveInitData(binary_seed, {1}, device_id_v2); - EXPECT_EQ(brave_sync_prefs()->GetThisDeviceIdV2(), device_id_v2); - - // It will send DELETE record twice because two device records has same device - // id - EXPECT_CALL(*sync_client(), - SendSyncRecords("PREFERENCES", - ContainsDeviceRecord(SyncRecord::Action::A_DELETE, - "device1", device_id_v2))) - .Times(2); - EXPECT_CALL(*sync_client(), - SendSyncRecords("PREFERENCES", - ContainsDeviceRecord(SyncRecord::Action::A_CREATE, - "device1", device_id_v2))) - .Times(1); - - base::WaitableEvent we; - brave_sync::GetRecordsCallback on_get_records = - base::BindOnce(&OnGetRecordsStub); - sync_service()->OnPollSyncCycle(std::move(on_get_records), &we); -} - -TEST_F(BraveSyncServiceTest, IsOtherBookmarksFolder) { - AsMutable(model()->other_node()) - ->SetMetaInfo("object_id", GenerateObjectIdForOtherNode(std::string())); - auto record_matches_id = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, GenerateObjectIdForOtherNode(std::string()), - "", "", "", "", false, ""); - EXPECT_TRUE(sync_service()->IsOtherBookmarksFolder(record_matches_id.get())); - - auto record_matches_traits = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, GenerateObjectIdForOtherNode("123"), - kOtherNodeName, kOtherNodeOrder, "", "", false, kOtherNodeName); - EXPECT_TRUE(sync_service() - ->IsOtherBookmarksFolder(record_matches_traits.get())); - - auto record_not_match1 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, GenerateObjectIdForOtherNode("123"), - kOtherNodeName, "", "", "", false, kOtherNodeName); - EXPECT_FALSE(sync_service() - ->IsOtherBookmarksFolder(record_not_match1.get())); - - auto record_not_match2 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, GenerateObjectIdForOtherNode("123"), - "What Bookmarks", kOtherNodeOrder, "", "", false, kOtherNodeName); - EXPECT_FALSE(sync_service() - ->IsOtherBookmarksFolder(record_not_match2.get())); - - auto record_not_match3 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, GenerateObjectIdForOtherNode("123"), - kOtherNodeName, kOtherNodeOrder, "", "", false, "No Bookmarks"); - EXPECT_FALSE(sync_service() - ->IsOtherBookmarksFolder(record_not_match3.get())); - - auto record_not_folder = SimpleBookmarkSyncRecord( - SyncRecord::Action::A_CREATE, GenerateObjectIdForOtherNode(std::string()), - "", "", "", "", "", false); - EXPECT_FALSE(sync_service() - ->IsOtherBookmarksFolder(record_not_folder.get())); -} - -TEST_F(BraveSyncServiceTest, ProcessOtherBookmarksFolder) { - const std::string object_id_iter1 = - GenerateObjectIdForOtherNode(std::string()); - auto record1 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, object_id_iter1, - kOtherNodeName, kOtherNodeOrder, "", "", false, kOtherNodeName); - EXPECT_TRUE(sync_service()->IsOtherBookmarksFolder(record1.get())); - - bool pass_to_syncer = false; - sync_service()->ProcessOtherBookmarksFolder(record1.get(), &pass_to_syncer); - EXPECT_FALSE(pass_to_syncer); - std::string other_node_object_id; - model()->other_node()->GetMetaInfo("object_id", &other_node_object_id); - EXPECT_EQ(other_node_object_id, object_id_iter1); - - const std::string object_id_iter2 = - GenerateObjectIdForOtherNode(object_id_iter1); - // Now we emulate our object id is out-dated, need to catch up with current - // one - auto record2 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, object_id_iter2, - kOtherNodeName, kOtherNodeOrder, "", "", false, kOtherNodeName); - EXPECT_TRUE(sync_service()->IsOtherBookmarksFolder(record2.get())); - - pass_to_syncer = false; - sync_service()->ProcessOtherBookmarksFolder(record2.get(), &pass_to_syncer); - EXPECT_FALSE(pass_to_syncer); - other_node_object_id = ""; - model()->other_node()->GetMetaInfo("object_id", &other_node_object_id); - EXPECT_EQ(other_node_object_id, object_id_iter2); - - // Prepare children of other_node() - const bookmarks::BookmarkNode* folder_a = - model()->AddFolder(model()->other_node(), 0, base::ASCIIToUTF16("A")); - const bookmarks::BookmarkNode* bookmark_a1 = - model()->AddURL(model()->other_node(), 1, base::ASCIIToUTF16("A1"), - GURL("https://a1.com")); - const std::string folder_a_object_id = GenerateObjectId(); - const std::string bookmark_a1_object_id = GenerateObjectId(); - AsMutable(folder_a)->SetMetaInfo("object_id", folder_a_object_id); - AsMutable(bookmark_a1)->SetMetaInfo("object_id", bookmark_a1_object_id); - AsMutable(folder_a)->SetMetaInfo("order", - std::string(kOtherNodeOrder) + ".1"); - AsMutable(bookmark_a1)->SetMetaInfo("order", - std::string(kOtherNodeOrder) + ".2"); - AsMutable(folder_a) - ->SetMetaInfo("sync_timestamp", - std::to_string(base::Time::Now().ToJsTime())); - AsMutable(bookmark_a1) - ->SetMetaInfo("sync_timestamp", - std::to_string(base::Time::Now().ToJsTime())); - - // Prepare a folder for "Other Bookmarks" to move to - const bookmarks::BookmarkNode* folder_b = - model()->AddFolder(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("B")); - const std::string folder_b_object_id = GenerateObjectId(); - AsMutable(folder_b)->SetMetaInfo("object_id", folder_b_object_id); - AsMutable(folder_b)->SetMetaInfo("order", "1.0.1.1"); - AsMutable(folder_b) - ->SetMetaInfo("sync_timestamp", - std::to_string(base::Time::Now().ToJsTime())); - // ========================================================================== - // Emulate MOVE - const std::string object_id_iter3 = - GenerateObjectIdForOtherNode(object_id_iter2); - auto record3 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, object_id_iter2, - kOtherNodeName, "1.0.1.1.1", folder_b_object_id, "", - false, kOtherNodeName); - EXPECT_TRUE(sync_service()->IsOtherBookmarksFolder(record3.get())); - - auto record_a = SimpleFolderSyncRecord( - SyncRecord::Action::A_UPDATE, folder_a_object_id, - "A", "1.0.1.1.1.1", object_id_iter2, "", - false, "A"); - - auto record_a1 = SimpleBookmarkSyncRecord( - SyncRecord::Action::A_UPDATE, bookmark_a1_object_id, "https://a1.com/", - "A1", "1.0.1.1.1.2", object_id_iter2, "", false); - - // Expect sending updates - auto record_a_to_send = SyncRecord::Clone(*record_a); - auto record_a1_to_send = SyncRecord::Clone(*record_a1); - RecordsListPtr records_to_send = std::make_unique(); - records_to_send->push_back(std::move(record_a_to_send)); - records_to_send->push_back(std::move(record_a1_to_send)); - EXPECT_CALL(*sync_client(), - SendSyncRecords(kBookmarks, - MatchBookmarksRecords( - std::move(records_to_send.get())))) - .Times(1); - - pass_to_syncer = false; - sync_service()->ProcessOtherBookmarksFolder(record3.get(), &pass_to_syncer); - EXPECT_TRUE(pass_to_syncer); - other_node_object_id = ""; - model()->other_node()->GetMetaInfo("object_id", &other_node_object_id); - EXPECT_EQ(other_node_object_id, object_id_iter3); - - // Move folder A to "Other Bookmark" folder under folder B - EXPECT_EQ(sync_service()->pending_received_records_->size(), 2u); - EXPECT_TRUE(sync_service()->pending_received_records_->at(0) - ->GetBookmark().Matches(record_a->GetBookmark())); - EXPECT_TRUE(sync_service()->pending_received_records_->at(1) - ->GetBookmark().Matches(record_a1->GetBookmark())); - // ========================================================================== - // Emulate RENAME - sync_service()->pending_received_records_->clear(); - const std::string object_id_iter4 = - GenerateObjectIdForOtherNode(object_id_iter3); - const std::string new_other_node_name = "Mother Bookmarks"; - auto record4 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, object_id_iter3, - new_other_node_name, kOtherNodeOrder, "", "", - false, new_other_node_name); - EXPECT_TRUE(sync_service()->IsOtherBookmarksFolder(record4.get())); - - record_a = SimpleFolderSyncRecord( - SyncRecord::Action::A_UPDATE, folder_a_object_id, - "A", std::string(kOtherNodeOrder) + ".1", object_id_iter3, "", - false, "A"); - record_a1 = SimpleBookmarkSyncRecord( - SyncRecord::Action::A_UPDATE, bookmark_a1_object_id, "https://a1.com/", - "A1", std::string(kOtherNodeOrder) + ".2", object_id_iter3, "", false); - - // Expect sending updates - record_a_to_send = SyncRecord::Clone(*record_a); - record_a1_to_send = SyncRecord::Clone(*record_a1); - records_to_send = std::make_unique(); - records_to_send->push_back(std::move(record_a_to_send)); - records_to_send->push_back(std::move(record_a1_to_send)); - EXPECT_CALL(*sync_client(), - SendSyncRecords(kBookmarks, - MatchBookmarksRecords( - std::move(records_to_send.get())))) - .Times(1); - - pass_to_syncer = false; - sync_service()->ProcessOtherBookmarksFolder(record4.get(), &pass_to_syncer); - EXPECT_TRUE(pass_to_syncer); - other_node_object_id = ""; - model()->other_node()->GetMetaInfo("object_id", &other_node_object_id); - EXPECT_EQ(other_node_object_id, object_id_iter4); - - // Move folder A to "Mother Bookmark" folder - EXPECT_EQ(sync_service()->pending_received_records_->size(), 2u); - EXPECT_TRUE(sync_service()->pending_received_records_->at(0) - ->GetBookmark().Matches(record_a->GetBookmark())); - EXPECT_TRUE(sync_service()->pending_received_records_->at(1) - ->GetBookmark().Matches(record_a1->GetBookmark())); - // ========================================================================== - // Emulate REORDER (which will be ignored) - sync_service()->pending_received_records_->clear(); - auto record5 = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, object_id_iter4, - kOtherNodeName, "1.0.1.2", "", "", - false, kOtherNodeName); - EXPECT_TRUE(sync_service()->IsOtherBookmarksFolder(record5.get())); - - EXPECT_CALL(*sync_client(), SendSyncRecords(kBookmarks, _)).Times(0); - - pass_to_syncer = false; - sync_service()->ProcessOtherBookmarksFolder(record5.get(), &pass_to_syncer); - EXPECT_FALSE(pass_to_syncer); - other_node_object_id = ""; - model()->other_node()->GetMetaInfo("object_id", &other_node_object_id); - EXPECT_EQ(other_node_object_id, object_id_iter4); - - EXPECT_EQ(sync_service()->pending_received_records_->size(), 0u); -} - -TEST_F(BraveSyncServiceTest, ProcessOtherBookmarksChildren) { - AsMutable(model()->other_node()) - ->SetMetaInfo("object_id", GenerateObjectIdForOtherNode(std::string())); - auto record_a = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, "", - "A", std::string(kOtherNodeOrder) + ".1", - GenerateObjectIdForOtherNode(std::string()), "", - false, "A"); - EXPECT_FALSE(record_a->GetBookmark().hideInToolbar); - sync_service()->ProcessOtherBookmarksChildren(record_a.get()); - EXPECT_TRUE(record_a->GetBookmark().hideInToolbar); - - auto record_a1 = SimpleBookmarkSyncRecord( - SyncRecord::Action::A_CREATE, "", "https://a1.com/", - "A1", "1.1.1.1", "", "", false); - EXPECT_FALSE(record_a1->GetBookmark().hideInToolbar); - sync_service()->ProcessOtherBookmarksChildren(record_a1.get()); - EXPECT_FALSE(record_a1->GetBookmark().hideInToolbar); -} - -TEST_F(BraveSyncServiceTest, CheckOtherBookmarkRecord) { - const std::string object_id_iter1 = - GenerateObjectIdForOtherNode(std::string()); - const std::string object_id_iter2 = - GenerateObjectIdForOtherNode(object_id_iter1); - // No object id for other_node yet - auto record = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, "", - kOtherNodeName, kOtherNodeOrder, "", "", - false, kOtherNodeName); - std::string other_node_object_id; - EXPECT_FALSE(model()->other_node()->GetMetaInfo("object_id", - &other_node_object_id)); - sync_service()->CheckOtherBookmarkRecord(record.get()); - EXPECT_TRUE(model()->other_node()->GetMetaInfo("object_id", - &other_node_object_id)); - EXPECT_EQ(other_node_object_id, object_id_iter1); - EXPECT_EQ(record->objectId, other_node_object_id); - - // Object id is out-dated - record = SimpleFolderSyncRecord( - SyncRecord::Action::A_CREATE, object_id_iter1, - kOtherNodeName, kOtherNodeOrder, "", "", - false, kOtherNodeName); - AsMutable(model()->other_node()) - ->SetMetaInfo("object_id", object_id_iter2); - sync_service()->CheckOtherBookmarkRecord(record.get()); - EXPECT_EQ(record->objectId, object_id_iter2); -} - -TEST_F(BraveSyncServiceTest, CheckOtherBookmarkChildRecord) { - const std::string object_id_iter1 = - GenerateObjectIdForOtherNode(std::string()); - AsMutable(model()->other_node()) - ->SetMetaInfo("object_id", object_id_iter1); - auto record_a1 = SimpleBookmarkSyncRecord( - SyncRecord::Action::A_CREATE, "", "https://a1.com/", - "A1", std::string(kOtherNodeOrder) + ".1" , "", "", true); - EXPECT_TRUE(record_a1->GetBookmark().parentFolderObjectId.empty()); - sync_service()->CheckOtherBookmarkChildRecord(record_a1.get()); - EXPECT_EQ(record_a1->GetBookmark().parentFolderObjectId, object_id_iter1); -} - -TEST_F(BraveSyncServiceTest, AddNonClonedBookmarkKeys) { - sync_service()->AddNonClonedBookmarkKeys(model()); - const bookmarks::BookmarkNode* bookmark_a1 = - model()->AddURL(model()->other_node(), 0, base::ASCIIToUTF16("A1"), - GURL("https://a1.com")); - - AsMutable(bookmark_a1)->SetMetaInfo("object_id", "object_id_value"); - AsMutable(bookmark_a1)->SetMetaInfo("order", "order_value"); - AsMutable(bookmark_a1)->SetMetaInfo("sync_timestamp", "sync_timestamp_value"); - AsMutable(bookmark_a1)->SetMetaInfo("version", "version_value"); - - model()->Copy(bookmark_a1, model()->other_node(), 1); - - const bookmarks::BookmarkNode* bookmark_copy = - model()->other_node()->children().at(1).get(); - - std::string meta_object_id; - EXPECT_FALSE(bookmark_copy->GetMetaInfo("object_id", &meta_object_id)); - EXPECT_TRUE(meta_object_id.empty()); - std::string meta_order; - EXPECT_FALSE(bookmark_copy->GetMetaInfo("order", &meta_order)); - EXPECT_TRUE(meta_order.empty()); - std::string meta_sync_timestamp; - EXPECT_FALSE( - bookmark_copy->GetMetaInfo("sync_timestamp", &meta_sync_timestamp)); - EXPECT_TRUE(meta_sync_timestamp.empty()); - std::string meta_version; - EXPECT_FALSE(bookmark_copy->GetMetaInfo("version", &meta_version)); - EXPECT_TRUE(meta_version.empty()); -} - -namespace { - -void SetBraveMeta(const bookmarks::BookmarkNode* node, - const std::string& object_id, - const std::string& order, - const std::string& sync_timestamp, - const std::string& version) { - bookmarks::BookmarkNode* mutable_node = AsMutable(node); - mutable_node->SetMetaInfo("object_id", object_id); - mutable_node->SetMetaInfo("order", order); - mutable_node->SetMetaInfo("sync_timestamp", sync_timestamp); - mutable_node->SetMetaInfo("version", version); -} - -void GetAllNodes(const bookmarks::BookmarkNode* parent, - std::set* all_nodes) { - for (size_t i = 0; i < parent->children().size(); ++i) { - const bookmarks::BookmarkNode* current_child = parent->children()[i].get(); - all_nodes->insert(current_child); - if (current_child->is_folder()) { - GetAllNodes(current_child, all_nodes); - } - } -} - -} // namespace - -TEST_F(BraveSyncServiceTest, MigrateDuplicatedBookmarksObjectIds) { - AsMutable(model()->other_node())->SetMetaInfo("order", kOtherNodeOrder); - - const bookmarks::BookmarkNode* bookmark_a1 = - model()->AddURL(model()->other_node(), 0, base::ASCIIToUTF16("A1"), - GURL("https://a1.com")); - - SetBraveMeta(bookmark_a1, "object_id_value", "255.255.255.3", - "sync_timestamp_value", "version_value"); - - model()->Copy(bookmark_a1, model()->other_node(), 1); - - model()->Copy(bookmark_a1, model()->other_node(), 2); - - const bookmarks::BookmarkNode* folder_f1 = - model()->AddFolder(model()->other_node(), 3, base::ASCIIToUTF16("F1")); - SetBraveMeta(folder_f1, "object_id_value", "255.255.255.5", - "sync_timestamp_value", "version_value"); - - const bookmarks::BookmarkNode* bookmark_b1 = model()->AddURL( - folder_f1, 0, base::ASCIIToUTF16("B1"), GURL("https://b1.com")); - SetBraveMeta(bookmark_b1, "object_id_value", "255.255.255.5.1", - "sync_timestamp_value", "version_value"); - - model()->Copy(folder_f1, model()->other_node(), 4); - model()->Copy(folder_f1, model()->other_node(), 5); - model()->Move(model()->other_node()->children()[5].get(), folder_f1, 0); - - std::set all_nodes; - GetAllNodes(model()->other_node(), &all_nodes); - for (const bookmarks::BookmarkNode* node : all_nodes) { - // Verify fields after copying - std::string meta_object_id; - EXPECT_TRUE(node->GetMetaInfo("object_id", &meta_object_id)); - EXPECT_EQ(meta_object_id, "object_id_value"); - std::string meta_sync_timestamp; - EXPECT_TRUE(node->GetMetaInfo("sync_timestamp", &meta_sync_timestamp)); - EXPECT_EQ(meta_sync_timestamp, "sync_timestamp_value"); - std::string meta_version; - EXPECT_TRUE(node->GetMetaInfo("version", &meta_version)); - EXPECT_EQ(meta_version, "version_value"); - - // Simulate all bookmarks don`t have added time, as a worse case, - // but happened on live profile - AsMutable(node)->set_date_added(base::Time()); - } - - sync_service()->AddNonClonedBookmarkKeys(model()); - - // Do the migration - bool result = - BraveProfileSyncServiceImpl::MigrateDuplicatedBookmarksObjectIds( - true, - profile(), - model()); - EXPECT_TRUE(result); - - // All the bookmarks after migration must not have sync meta info - all_nodes.clear(); - GetAllNodes(model()->other_node(), &all_nodes); - for (const bookmarks::BookmarkNode* bookmark : all_nodes) { - std::string migrated_object_id; - std::string migrated_order; - std::string migrated_sync_timestamp; - std::string migrated_version; - EXPECT_FALSE(bookmark->GetMetaInfo("object_id", &migrated_object_id)); - EXPECT_FALSE(bookmark->GetMetaInfo("order", &migrated_order)); - EXPECT_FALSE( - bookmark->GetMetaInfo("sync_timestamp", &migrated_sync_timestamp)); - EXPECT_FALSE(bookmark->GetMetaInfo("version", &migrated_version)); - } -} - -TEST_F(BraveSyncServiceTest, SyncDisabledMigrateDuplicatedBookmarksObjectIds) { - AsMutable(model()->other_node())->SetMetaInfo("order", kOtherNodeOrder); - - const bookmarks::BookmarkNode* bookmark_a1 = - model()->AddURL(model()->other_node(), 0, base::ASCIIToUTF16("A1"), - GURL("https://a1.com")); - - SetBraveMeta(bookmark_a1, "object_id_value", "255.255.255.3", - "sync_timestamp_value", "version_value"); - - model()->Copy(bookmark_a1, model()->other_node(), 1); - - model()->Copy(bookmark_a1, model()->other_node(), 2); - - // Do the migration - bool result = - BraveProfileSyncServiceImpl::MigrateDuplicatedBookmarksObjectIds( - false, - profile(), - model()); - - // Should return false, because sync is disable - // Migration will be a no-op - EXPECT_FALSE(result); -} diff --git a/components/brave_sync/client/brave_sync_client.h b/components/brave_sync/client/brave_sync_client.h deleted file mode 100644 index 1b8fdc034836..000000000000 --- a/components/brave_sync/client/brave_sync_client.h +++ /dev/null @@ -1,97 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_BRAVE_SYNC_CLIENT_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_BRAVE_SYNC_CLIENT_H_ - -#include -#include -#include - -#include "components/keyed_service/core/keyed_service.h" -#include "brave/components/brave_sync/client/client_data.h" -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -namespace base { -class Time; -} - -class Profile; - -namespace brave_sync { - -class SyncMessageHandler { - public: - virtual void BackgroundSyncStarted(bool startup) = 0; - virtual void BackgroundSyncStopped(bool shutdown) = 0; - - // SYNC_DEBUG - virtual void OnSyncDebug(const std::string &message) = 0; - // SYNC_SETUP_ERROR - virtual void OnSyncSetupError(const std::string &error) = 0; - // GET_INIT_DATA - virtual void OnGetInitData(const std::string &sync_version) = 0; - // SAVE_INIT_DATA - virtual void OnSaveInitData(const Uint8Array& seed, - const Uint8Array& device_id, - const std::string& device_id_v2) = 0; - // SYNC_READY - virtual void OnSyncReady() = 0; - // GET_EXISTING_OBJECTS - virtual void OnGetExistingObjects(const std::string &category_name, - std::unique_ptr records, - const base::Time &last_record_time_stamp, const bool is_truncated) = 0; - // RESOLVED_SYNC_RECORDS - virtual void OnResolvedSyncRecords(const std::string &category_name, - std::unique_ptr records) = 0; - // DELETED_SYNC_USER - virtual void OnDeletedSyncUser() = 0; - // DELETE_SYNC_SITE_SETTINGS - virtual void OnDeleteSyncSiteSettings() = 0; - // SAVE_BOOKMARKS_BASE_ORDER - virtual void OnSaveBookmarksBaseOrder(const std::string& order) = 0; - // COMOACTED_SYNC_CATEGORY - virtual void OnCompactComplete(const std::string& category_name) = 0; - virtual void OnRecordsSent(const std::string &category_name, - std::unique_ptr records) = 0; -}; - -class BraveSyncClient { - public: - static BraveSyncClient* Create(SyncMessageHandler* handler, - Profile* profile); - virtual ~BraveSyncClient() = default; - - // BraveSync to Browser messages - virtual SyncMessageHandler* sync_message_handler() = 0; - - virtual void SendGotInitData(const Uint8Array& seed, - const Uint8Array& device_id, - const client_data::Config& config, - const std::string& device_id_v2) = 0; - virtual void SendFetchSyncRecords( - const std::vector &category_names, - const base::Time &startAt, - const int max_records) = 0; - virtual void SendResolveSyncRecords( - const std::string &category_name, - std::unique_ptr list) = 0; - virtual void SendSyncRecords(const std::string &category_name, - const RecordsList &records) = 0; - virtual void SendDeleteSyncUser() = 0; - virtual void SendDeleteSyncCategory(const std::string &category_name) = 0; - virtual void SendGetBookmarksBaseOrder(const std::string &device_id, - const std::string &platform) = 0; - // COMPACT_SYNC_CATEGORY - virtual void SendCompact(const std::string& category_name) = 0; - - virtual void OnExtensionInitialized() = 0; - - virtual void OnSyncEnabledChanged() = 0; -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_BRAVE_SYNC_CLIENT_H_ diff --git a/components/brave_sync/client/brave_sync_client_impl.cc b/components/brave_sync/client/brave_sync_client_impl.cc deleted file mode 100644 index 0f5700dfb013..000000000000 --- a/components/brave_sync/client/brave_sync_client_impl.cc +++ /dev/null @@ -1,203 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/client/brave_sync_client_impl.h" - -#include -#include -#include - -#include "base/logging.h" -#include "base/one_shot_event.h" -#include "brave/browser/extensions/api/brave_sync_event_router.h" -#include "brave/common/extensions/api/brave_sync.h" -#include "brave/common/extensions/extension_constants.h" -#include "brave/components/brave_sync/brave_sync_prefs.h" -#include "brave/components/brave_sync/client/client_ext_impl_data.h" -#include "brave/components/brave_sync/grit/brave_sync_resources.h" -#include "chrome/browser/extensions/component_loader.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/profiles/profile.h" -#include "content/public/browser/browser_thread.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_system.h" - -namespace brave_sync { - -BraveSyncClient* brave_sync_client_for_testing_; - -// static -void BraveSyncClientImpl::set_for_testing(BraveSyncClient* sync_client) { - brave_sync_client_for_testing_ = sync_client; -} - -// static -BraveSyncClient* BraveSyncClient::Create(SyncMessageHandler* handler, - Profile* profile) { - if (brave_sync_client_for_testing_) - return brave_sync_client_for_testing_; - - return new BraveSyncClientImpl(handler, profile); -} - -BraveSyncClientImpl::BraveSyncClientImpl(SyncMessageHandler* handler, - Profile* profile) - : handler_(handler), - profile_(profile), - sync_prefs_(new brave_sync::prefs::Prefs(profile->GetPrefs())), - extension_loaded_(false), - brave_sync_event_router_(new extensions::BraveSyncEventRouter(profile)), - extension_registry_observer_(this) { - // Handle when the extension system is ready - extensions::ExtensionSystem::Get(profile)->ready().Post( - FROM_HERE, base::Bind(&BraveSyncClientImpl::OnExtensionSystemReady, - base::Unretained(this))); -} - -BraveSyncClientImpl::~BraveSyncClientImpl() {} - -SyncMessageHandler* BraveSyncClientImpl::sync_message_handler() { - return handler_; -} - -void BraveSyncClientImpl::SendGotInitData(const Uint8Array& seed, - const Uint8Array& device_id, - const client_data::Config& config, - const std::string& device_id_v2) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - extensions::api::brave_sync::Config config_extension; - ConvertConfig(config, &config_extension); - brave_sync_event_router_->GotInitData(seed, device_id, config_extension, - device_id_v2); -} - -void BraveSyncClientImpl::SendFetchSyncRecords( - const std::vector& category_names, - const base::Time& startAt, - const int max_records) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - brave_sync_event_router_->FetchSyncRecords(category_names, startAt, - max_records); -} - -void BraveSyncClientImpl::SendResolveSyncRecords( - const std::string& category_name, - std::unique_ptr records_and_existing_objects) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::vector - records_and_existing_objects_ext; - - ConvertResolvedPairs(*records_and_existing_objects, - &records_and_existing_objects_ext); - - brave_sync_event_router_->ResolveSyncRecords( - category_name, records_and_existing_objects_ext); -} - -void BraveSyncClientImpl::SendSyncRecords(const std::string& category_name, - const RecordsList& records) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::vector records_ext; - ConvertSyncRecordsFromLibToExt(records, &records_ext); - - brave_sync_event_router_->SendSyncRecords(category_name, records_ext); -} - -void BraveSyncClientImpl::SendDeleteSyncUser() { - NOTIMPLEMENTED(); -} - -void BraveSyncClientImpl::SendDeleteSyncCategory( - const std::string& category_name) { - NOTIMPLEMENTED(); -} - -void BraveSyncClientImpl::SendGetBookmarksBaseOrder( - const std::string& device_id, - const std::string& platform) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - brave_sync_event_router_->SendGetBookmarksBaseOrder(device_id, platform); -} - -void BraveSyncClientImpl::SendCompact( - const std::string& category_name) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - brave_sync_event_router_->SendCompact(category_name); -} - -void BraveSyncClientImpl::OnExtensionInitialized() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(extension_loaded_); - if (extension_loaded_) - brave_sync_event_router_->LoadClient(); -} - -void BraveSyncClientImpl::OnSyncEnabledChanged() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (sync_prefs_->GetSyncEnabled()) { - LoadOrUnloadExtension(true); - } else { - LoadOrUnloadExtension(false); - } -} - -void BraveSyncClientImpl::OnExtensionReady( - content::BrowserContext* browser_context, - const extensions::Extension* extension) { - if (extension->id() == brave_sync_extension_id) { - DCHECK(handler_); - handler_->BackgroundSyncStarted(true); - } -} - -void BraveSyncClientImpl::OnExtensionLoaded( - content::BrowserContext* browser_context, - const extensions::Extension* extension) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (extension->id() == brave_sync_extension_id) { - extension_loaded_ = true; - } -} - -void BraveSyncClientImpl::OnExtensionUnloaded( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UnloadedExtensionReason reason) { - if (extension->id() == brave_sync_extension_id) { - extension_loaded_ = false; - DCHECK(handler_); - handler_->BackgroundSyncStopped(true); - } -} - -void BraveSyncClientImpl::LoadOrUnloadExtension(bool load) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::FilePath brave_sync_extension_path(FILE_PATH_LITERAL("")); - brave_sync_extension_path = - brave_sync_extension_path.Append(FILE_PATH_LITERAL("brave_sync")); - extensions::ExtensionSystem* system = - extensions::ExtensionSystem::Get(profile_); - extensions::ComponentLoader* component_loader = - system->extension_service()->component_loader(); - if (load) { - component_loader->Add(IDR_BRAVE_SYNC_EXTENSION, brave_sync_extension_path); - } else { - // Remove by root path doesn't have effect, using extension id instead - // component_loader->Remove(brave_sync_extension_path); - component_loader->Remove(brave_sync_extension_id); - } -} - -void BraveSyncClientImpl::OnExtensionSystemReady() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // observe changes in extension system - extension_registry_observer_.Add(ExtensionRegistry::Get(profile_)); - DCHECK(!extension_loaded_); - if (sync_prefs_->GetSyncEnabled()) { - LoadOrUnloadExtension(true); - } -} - -} // namespace brave_sync diff --git a/components/brave_sync/client/brave_sync_client_impl.h b/components/brave_sync/client/brave_sync_client_impl.h deleted file mode 100644 index 24a1cd6146b3..000000000000 --- a/components/brave_sync/client/brave_sync_client_impl.h +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_BRAVE_SYNC_CLIENT_IMPL_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_BRAVE_SYNC_CLIENT_IMPL_H_ - -#include -#include -#include - -#include "brave/components/brave_sync/client/brave_sync_client.h" -#include "base/macros.h" -#include "base/scoped_observer.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_registry_observer.h" -#include "base/gtest_prod_util.h" - -class BraveSyncServiceTest; -class Profile; - -namespace extensions { -class BraveSyncEventRouter; -} - -namespace brave_sync { - -namespace prefs { -class Prefs; -} - -using extensions::Extension; -using extensions::ExtensionRegistry; -using extensions::ExtensionRegistryObserver; -using extensions::UnloadedExtensionReason; - -class BraveSyncClientImpl : public BraveSyncClient, - public ExtensionRegistryObserver { - public: - ~BraveSyncClientImpl() override; - - // BraveSyncClient overrides - - // BraveSync to Browser messages - SyncMessageHandler* sync_message_handler() override; - - // Browser to BraveSync messages - void SendGotInitData(const Uint8Array& seed, - const Uint8Array& device_id, - const client_data::Config& config, - const std::string& device_id_v2) override; - void SendFetchSyncRecords( - const std::vector &category_names, const base::Time &startAt, - const int max_records) override; - void SendResolveSyncRecords( - const std::string& category_name, - std::unique_ptr records) override; - void SendSyncRecords(const std::string& category_name, - const RecordsList &records) override; - void SendDeleteSyncUser() override; - void SendDeleteSyncCategory(const std::string& category_name) override; - void SendGetBookmarksBaseOrder(const std::string& device_id, - const std::string& platform) override; - void SendCompact(const std::string& category_name) override; - - private: - friend class BraveSyncClient; - friend class ::BraveSyncServiceTest; - static void set_for_testing(BraveSyncClient* sync_client); - - explicit BraveSyncClientImpl(SyncMessageHandler* handler, Profile* profile); - - void OnExtensionInitialized() override; - void OnSyncEnabledChanged() override; - - // ExtensionRegistryObserver: - void OnExtensionReady(content::BrowserContext* browser_context, - const extensions::Extension* extension) override; - void OnExtensionLoaded(content::BrowserContext* browser_context, - const Extension* extension) override; - void OnExtensionUnloaded(content::BrowserContext* browser_context, - const Extension* extension, - UnloadedExtensionReason reason) override; - void LoadOrUnloadExtension(bool load); - void OnExtensionSystemReady(); - - SyncMessageHandler* handler_; // not owned - Profile* profile_; // not owned - std::unique_ptr sync_prefs_; - bool extension_loaded_; - - std::unique_ptr brave_sync_event_router_; - - ScopedObserver - extension_registry_observer_; - - DISALLOW_COPY_AND_ASSIGN(BraveSyncClientImpl); -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_BRAVE_SYNC_CLIENT_IMPL_H_ diff --git a/components/brave_sync/client/client_data.cc b/components/brave_sync/client/client_data.cc deleted file mode 100644 index fb4d5b4a828e..000000000000 --- a/components/brave_sync/client/client_data.cc +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/client/client_data.h" - -namespace brave_sync { -namespace client_data { - -Config::Config() : debug(false) { -} - - -} // namespace client_data -} // namespace brave_sync diff --git a/components/brave_sync/client/client_data.h b/components/brave_sync/client/client_data.h deleted file mode 100644 index 79d2a07403b6..000000000000 --- a/components/brave_sync/client/client_data.h +++ /dev/null @@ -1,30 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_CLIENT_DATA_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_CLIENT_DATA_H_ - -#include - -namespace brave_sync { -namespace client_data { - -//typedef std::vector Uint8Array; -//using Uint8Array = std::vector; - -class Config { -public: - Config(); - // version of API - std::string api_version; - // url of the server - std::string server_url; - // whether sync lib produces debug messages - bool debug; -}; - -} // namespace client_data -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_CLIENT_DATA_H_ diff --git a/components/brave_sync/client/client_ext_impl_data.cc b/components/brave_sync/client/client_ext_impl_data.cc deleted file mode 100644 index 39d1692ccce7..000000000000 --- a/components/brave_sync/client/client_ext_impl_data.cc +++ /dev/null @@ -1,338 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/client/client_ext_impl_data.h" - -#include -#include - -#include "brave/common/extensions/api/brave_sync.h" -#include "brave/components/brave_sync/client/client_data.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/values_conv.h" - -namespace brave_sync { - -void ConvertConfig(const brave_sync::client_data::Config& config, - extensions::api::brave_sync::Config* config_extension) { - DCHECK(config_extension); - config_extension->api_version = config.api_version; - config_extension->server_url = config.server_url; - config_extension->debug = config.debug; -} - -std::unique_ptr FromExtSite( - const extensions::api::brave_sync::Site &ext_site) { - auto site = std::make_unique(); - - site->location = ext_site.location; - site->title = ext_site.title; - site->customTitle = ext_site.custom_title; - site->lastAccessedTime = base::Time::FromJsTime(ext_site.last_accessed_time); - site->creationTime = base::Time::FromJsTime(ext_site.creation_time); - site->favicon = ext_site.favicon; - - return site; -} - -std::unique_ptr FromExtDevice( - const extensions::api::brave_sync::Device &ext_device) { - auto device = std::make_unique(); - device->name = ext_device.name; - device->deviceIdV2 = ext_device.device_id_v2; - return device; -} - -std::unique_ptr FromExtSiteSetting( - const extensions::api::brave_sync::SiteSetting &ext_site_setting) { - auto site_setting = std::make_unique(); - - site_setting->hostPattern = ext_site_setting.host_pattern; - - #define CHECK_AND_ASSIGN(FIELDNAME_LIB, FIELDNAME_EXT) \ - if (ext_site_setting.FIELDNAME_EXT) { \ - site_setting->FIELDNAME_LIB = *ext_site_setting.FIELDNAME_EXT; \ - } - CHECK_AND_ASSIGN(zoomLevel, zoom_level); - CHECK_AND_ASSIGN(shieldsUp, shields_up); - // site_setting-> = ext_site_setting.ad_control; - // site_setting-> = ext_site_setting.cookie_control; - CHECK_AND_ASSIGN(safeBrowsing, safe_browsing); - CHECK_AND_ASSIGN(noScript, no_script); - CHECK_AND_ASSIGN(httpsEverywhere, https_everywhere); - CHECK_AND_ASSIGN(fingerprintingProtection, fingerprinting_protection); - CHECK_AND_ASSIGN(ledgerPayments, ledger_payments); - CHECK_AND_ASSIGN(ledgerPaymentsShown, ledger_payments_shown); - #undef CHECK_AND_ASSIGN - - return site_setting; -} - -std::unique_ptr> FromExtMetaInfo( - const std::vector& ext_meta_info) { - auto meta_info = std::make_unique>(); - - for (auto& ext_meta : ext_meta_info) { - brave_sync::jslib::MetaInfo meta; - meta.key = ext_meta.key; - meta.value = ext_meta.value; - meta_info->push_back(meta); - } - - return meta_info; -} - -std::unique_ptr FromExtBookmark( - const extensions::api::brave_sync::Bookmark &ext_bookmark) { - auto bookmark = std::make_unique(); - - bookmark->site = std::move(*FromExtSite(ext_bookmark.site)); - - bookmark->isFolder = ext_bookmark.is_folder; - if (ext_bookmark.parent_folder_object_id) { - bookmark->parentFolderObjectId = - StrFromUnsignedCharArray(*ext_bookmark.parent_folder_object_id); - } - if (ext_bookmark.fields) { - bookmark->fields = *ext_bookmark.fields; - } - if (ext_bookmark.hide_in_toolbar) { - bookmark->hideInToolbar = *ext_bookmark.hide_in_toolbar; - } - if (ext_bookmark.order) { - bookmark->order = *ext_bookmark.order; - } - if (ext_bookmark.meta_info) { - bookmark->metaInfo = std::move(*FromExtMetaInfo(*ext_bookmark.meta_info)); - } - - return bookmark; -} - -std::unique_ptr FromLibSite( - const jslib::Site &lib_site) { - auto ext_site = std::make_unique(); - - ext_site->location = lib_site.location; - ext_site->title = lib_site.title; - ext_site->custom_title = lib_site.customTitle; - ext_site->last_accessed_time = 0; // lib_site.lastAccessedTime.ToJsTime(); - ext_site->creation_time = 0; // lib_site.creationTime.ToJsTime(); - ext_site->favicon = lib_site.favicon; - - return ext_site; -} - -std::unique_ptr> -FromLibMetaInfo(const std::vector& lib_metaInfo) { - auto ext_meta_info = - std::make_unique>(); - - for (auto& metaInfo : lib_metaInfo) { - auto meta_info = std::make_unique(); - meta_info->key = metaInfo.key; - meta_info->value = metaInfo.value; - ext_meta_info->push_back(std::move(*meta_info)); - } - - return ext_meta_info; -} - -std::unique_ptr FromLibBookmark( - const jslib::Bookmark &lib_bookmark) { - auto ext_bookmark = std::make_unique(); - - ext_bookmark->site = std::move(*FromLibSite(lib_bookmark.site)); - - ext_bookmark->is_folder = lib_bookmark.isFolder; - if (!lib_bookmark.parentFolderObjectId.empty()) { - ext_bookmark->parent_folder_object_id.reset( - new std::vector( - UCharVecFromString(lib_bookmark.parentFolderObjectId))); - ext_bookmark->parent_folder_object_id_str.reset( - new std::string(lib_bookmark.parentFolderObjectId)); - } - - if (!lib_bookmark.fields.empty()) { - ext_bookmark->fields.reset( - new std::vector(lib_bookmark.fields)); - } - - ext_bookmark->hide_in_toolbar.reset(new bool(lib_bookmark.hideInToolbar)); - - ext_bookmark->order.reset(new std::string(lib_bookmark.order)); - - if (!lib_bookmark.metaInfo.empty()) { - ext_bookmark->meta_info = FromLibMetaInfo(lib_bookmark.metaInfo); - } - - return ext_bookmark; -} - -std::unique_ptr FromLibSiteSetting( - const jslib::SiteSetting &lib_site_setting) { - auto ext_site_setting = - std::make_unique(); - - ext_site_setting->host_pattern = lib_site_setting.hostPattern; - - ext_site_setting->zoom_level.reset(new double(lib_site_setting.zoomLevel)); - ext_site_setting->shields_up.reset(new bool (lib_site_setting.shieldsUp)); - // ext_site_setting->ad_control = lib_site_setting.adControl; - // ext_site_setting->cookie_control = lib_site_setting.cookieControl; - ext_site_setting->safe_browsing.reset( - new bool(lib_site_setting.safeBrowsing)); - ext_site_setting->no_script.reset(new bool(lib_site_setting.noScript)); - ext_site_setting->https_everywhere.reset( - new bool(lib_site_setting.httpsEverywhere)); - ext_site_setting->fingerprinting_protection.reset( - new bool(lib_site_setting.fingerprintingProtection)); - ext_site_setting->ledger_payments.reset( - new bool(lib_site_setting.ledgerPayments)); - ext_site_setting->ledger_payments_shown.reset( - new bool(lib_site_setting.ledgerPaymentsShown)); - if (!lib_site_setting.fields.empty()) { - ext_site_setting->fields.reset( - new std::vector(lib_site_setting.fields)); - } - - return ext_site_setting; -} - -std::unique_ptr FromLibDevice( - const jslib::Device &lib_device) { - auto ext_device = std::make_unique(); - ext_device->name = lib_device.name; - ext_device->device_id_v2 = lib_device.deviceIdV2; - return ext_device; -} - -std::unique_ptr FromLibSyncRecord( - const brave_sync::SyncRecordPtr& lib_record) { - DCHECK(lib_record); - std::unique_ptr ext_record = std::make_unique(); - - ext_record->action = static_cast(lib_record->action); - ext_record->device_id = UCharVecFromString(lib_record->deviceId); - ext_record->object_id = UCharVecFromString(lib_record->objectId); - - // Workaround, because properties device_id and object_id somehow are empty - // in js code after passing Browser=>Extension - ext_record->device_id_str.reset(new std::string(lib_record->deviceId)); - ext_record->object_id_str.reset(new std::string(lib_record->objectId)); - - ext_record->object_data = lib_record->objectData; - ext_record->sync_timestamp.reset( - new double(lib_record->syncTimestamp.ToJsTime())); - if (lib_record->has_bookmark()) { - ext_record->bookmark = FromLibBookmark(lib_record->GetBookmark()); - } else if (lib_record->has_historysite()) { - ext_record->history_site = FromLibSite(lib_record->GetHistorySite()); - } else if (lib_record->has_sitesetting()) { - ext_record->site_setting = FromLibSiteSetting(lib_record->GetSiteSetting()); - } else if (lib_record->has_device()) { - ext_record->device = FromLibDevice(lib_record->GetDevice()); - } - - return ext_record; -} - -brave_sync::SyncRecordPtr FromExtSyncRecord(const SyncRecord& ext_record) { - brave_sync::SyncRecordPtr record = - std::make_unique(); - - record->action = ConvertEnum( - ext_record.action, brave_sync::jslib::SyncRecord::Action::A_MIN, - brave_sync::jslib::SyncRecord::Action::A_MAX, - brave_sync::jslib::SyncRecord::Action::A_INVALID); - - record->deviceId = StrFromUnsignedCharArray(ext_record.device_id); - record->objectId = StrFromUnsignedCharArray(ext_record.object_id); - record->objectData = ext_record.object_data; - if (ext_record.sync_timestamp) { - record->syncTimestamp = base::Time::FromJsTime(*ext_record.sync_timestamp); - } - - DCHECK((ext_record.bookmark && - !ext_record.history_site && - !ext_record.site_setting && !ext_record.device) || - (!ext_record.bookmark && ext_record.history_site && - !ext_record.site_setting && - !ext_record.device) || - (!ext_record.bookmark && - !ext_record.history_site && - ext_record.site_setting && - !ext_record.device) || - (!ext_record.bookmark && - !ext_record.history_site && - !ext_record.site_setting && - ext_record.device)); - - if (ext_record.bookmark) { - std::unique_ptr bookmark = - FromExtBookmark(*ext_record.bookmark); - record->SetBookmark(std::move(bookmark)); - } else if (ext_record.history_site) { - std::unique_ptr history_site = - FromExtSite(*ext_record.history_site); - record->SetHistorySite(std::move(history_site)); - } else if (ext_record.site_setting) { - std::unique_ptr site_setting = - FromExtSiteSetting(*ext_record.site_setting); - record->SetSiteSetting(std::move(site_setting)); - } else if (ext_record.device) { - std::unique_ptr device = - FromExtDevice(*ext_record.device); - record->SetDevice(std::move(device)); - } - return record; -} - -void ConvertSyncRecords( - const std::vector& ext_records, - std::vector* records) { - DCHECK(records); - DCHECK(records->empty()); - - for (const auto& ext_record : ext_records) { - brave_sync::SyncRecordPtr record = FromExtSyncRecord(ext_record); - records->emplace_back(std::move(record)); - } -} - -void ConvertResolvedPairs( - const SyncRecordAndExistingList& records_and_existing_objects, - std::vector* records_and_existing_objects_ext) { - DCHECK(records_and_existing_objects_ext); - DCHECK(records_and_existing_objects_ext->empty()); - - for (const SyncRecordAndExistingPtr &src : records_and_existing_objects) { - DCHECK(src->first.get() != nullptr); - std::unique_ptr dest = - std::make_unique(); - - dest->server_record = std::move(*FromLibSyncRecord(src->first)); - - if (src->second) { - dest->local_record = FromLibSyncRecord(src->second); - } - - records_and_existing_objects_ext->emplace_back(std::move(*dest)); - } -} - -void ConvertSyncRecordsFromLibToExt( - const std::vector& records, - std::vector* records_extension) { - DCHECK(records_extension); - DCHECK(records_extension->empty()); - - for (const brave_sync::SyncRecordPtr &src : records) { - std::unique_ptr dest = FromLibSyncRecord(src); - records_extension->emplace_back(std::move(*dest)); - } -} - -} // namespace brave_sync diff --git a/components/brave_sync/client/client_ext_impl_data.h b/components/brave_sync/client/client_ext_impl_data.h deleted file mode 100644 index 2e5beaeef119..000000000000 --- a/components/brave_sync/client/client_ext_impl_data.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_CLIENT_EXT_IMPL_DATA_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_CLIENT_EXT_IMPL_DATA_H_ - -#include -#include - -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -namespace extensions { -namespace api { -namespace brave_sync { -struct Config; -struct SyncRecord; -struct RecordAndExistingObject; -} -} -} - -namespace brave_sync { -namespace client_data { -class Config; -} -} - -namespace brave_sync { - -using extensions::api::brave_sync::RecordAndExistingObject; -using extensions::api::brave_sync::SyncRecord; - -void ConvertConfig(const brave_sync::client_data::Config& config, - extensions::api::brave_sync::Config* config_extension); - -void ConvertSyncRecords(const std::vector& records_extension, - std::vector* records); - -void ConvertResolvedPairs( - const SyncRecordAndExistingList& records_and_existing_objects, - std::vector* records_and_existing_objects_ext); - -void ConvertSyncRecordsFromLibToExt( - const std::vector& records, - std::vector* records_extension); - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_CLIENT_CLIENT_EXT_IMPL_DATA_H_ diff --git a/components/brave_sync/jslib_const.cc b/components/brave_sync/jslib_const.cc deleted file mode 100644 index c301a22d3eac..000000000000 --- a/components/brave_sync/jslib_const.cc +++ /dev/null @@ -1,33 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "brave/components/brave_sync/jslib_const.h" - -namespace brave_sync { - -namespace jslib_const { - -const char kBookmarks[] = "BOOKMARKS"; -const char kHistorySites[] = "HISTORY_SITES"; -const char kPreferences[] = "PREFERENCES"; - - -const char DEVICES_NAMES[] = "devicesNames"; - -const char CREATE_RECORD[] = "0"; -const char UPDATE_RECORD[] = "1"; -const char DELETE_RECORD[] = "2"; - -const char SyncObjectData_BOOKMARK[] = "bookmark"; -const char SyncObjectData_HISTORY_SITE[] = "historySite"; -const char SyncObjectData_SITE_SETTING[] = "siteSetting"; -const char SyncObjectData_DEVICE[] = "device"; - -const char SyncRecordType_BOOKMARKS[] = "BOOKMARKS"; -const char SyncRecordType_HISTORY[] = "HISTORY_SITES"; -const char SyncRecordType_PREFERENCES[] = "PREFERENCES"; - - -} // jslib_const - -} // namespace brave_sync diff --git a/components/brave_sync/jslib_const.h b/components/brave_sync/jslib_const.h deleted file mode 100644 index dd3e776ede3e..000000000000 --- a/components/brave_sync/jslib_const.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_JSLIB_CONST_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_JSLIB_CONST_H_ - -namespace brave_sync { - -namespace jslib_const { - -extern const char kBookmarks[]; -extern const char kHistorySites[]; -extern const char kPreferences[]; - -const int kActionCreate = 0; -const int kActionUpdate = 1; -const int kActionDelete = 2; - -extern const char DEVICES_NAMES[]; - -extern const char CREATE_RECORD[]; -extern const char UPDATE_RECORD[]; -extern const char DELETE_RECORD[]; - -extern const char SyncObjectData_BOOKMARK[]; -extern const char SyncObjectData_HISTORY_SITE[]; -extern const char SyncObjectData_SITE_SETTING[]; -extern const char SyncObjectData_DEVICE[]; - -extern const char SyncRecordType_BOOKMARKS[]; -extern const char SyncRecordType_HISTORY[]; -extern const char SyncRecordType_PREFERENCES[]; - -} // jslib_const - -} // namespace brave_sync - -#endif //BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_JSLIB_CONST_H_ diff --git a/components/brave_sync/jslib_messages.cc b/components/brave_sync/jslib_messages.cc deleted file mode 100644 index 599bd8075813..000000000000 --- a/components/brave_sync/jslib_messages.cc +++ /dev/null @@ -1,244 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/jslib_messages.h" - -#include -#include - -#include "brave/components/brave_sync/jslib_const.h" -#include "brave/components/brave_sync/values_conv.h" -#include "base/logging.h" -#include "base/values.h" - -namespace brave_sync { - -namespace jslib { - -Site::Site() = default; - -Site::Site(const Site& site) { - location = site.location; - title = site.title; - customTitle = site.customTitle; - creationTime = site.creationTime; - favicon = site.favicon; -} - -Site::~Site() = default; - -std::unique_ptr Site::Clone(const Site& site) { - return std::make_unique(site); -} - -bool Site::Matches(const Site& site) const { - if (location == site.location && - title == site.title && - customTitle == site.customTitle && - favicon == site.favicon) - return true; - return false; -} - -std::string Site::TryGetNonEmptyTitle() const { - return !title.empty() ? title : customTitle; -} - -MetaInfo::MetaInfo() = default; - -MetaInfo::MetaInfo(const MetaInfo& metaInfo) { - key = metaInfo.key; - value = metaInfo.value; -} - -MetaInfo::~MetaInfo() = default; - -std::unique_ptr MetaInfo::Clone(const MetaInfo& metaInfo) { - return std::make_unique(metaInfo); -} - -Bookmark::Bookmark() : isFolder(false), hideInToolbar(false) {} - -Bookmark::Bookmark(const Bookmark& bookmark) { - site = bookmark.site; - isFolder = bookmark.isFolder; - parentFolderObjectId = bookmark.parentFolderObjectId; - fields = bookmark.fields; - hideInToolbar = bookmark.hideInToolbar; - order = bookmark.order; - metaInfo = bookmark.metaInfo; -} - -Bookmark::~Bookmark() = default; - -std::unique_ptr Bookmark::Clone(const Bookmark& bookmark) { - return std::make_unique(bookmark); -} - -bool Bookmark::Matches(const Bookmark& bookmark) const { - if (site.Matches(bookmark.site) && - isFolder == bookmark.isFolder && - parentFolderObjectId == bookmark.parentFolderObjectId && - hideInToolbar == bookmark.hideInToolbar && - order == bookmark.order) - return true; - return false; -} - -SiteSetting::SiteSetting() : zoomLevel(1.0f), shieldsUp(true), - adControl(SiteSetting::AdControl::ADC_INVALID), - cookieControl(SiteSetting::CookieControl::CC_INVALID), - safeBrowsing(true), noScript(false), httpsEverywhere(true), - fingerprintingProtection(false), ledgerPayments(false), - ledgerPaymentsShown(false) {} - -SiteSetting::~SiteSetting() = default; - -std::unique_ptr SiteSetting::Clone( - const SiteSetting& site_setting) { - auto ret_val = std::make_unique(); - ret_val->hostPattern = site_setting.hostPattern; - ret_val->zoomLevel = site_setting.zoomLevel; - ret_val->shieldsUp = site_setting.shieldsUp; - ret_val->adControl = site_setting.adControl; - ret_val->cookieControl = site_setting.cookieControl; - ret_val->safeBrowsing = site_setting.safeBrowsing; - ret_val->noScript = site_setting.noScript; - ret_val->httpsEverywhere = site_setting.httpsEverywhere; - ret_val->fingerprintingProtection = site_setting.fingerprintingProtection; - ret_val->ledgerPayments = site_setting.ledgerPayments; - ret_val->ledgerPaymentsShown = site_setting.ledgerPaymentsShown; - ret_val->fields = site_setting.fields; - return ret_val; -} - -Device::Device() = default; - -Device::~Device() = default; - -std::unique_ptr Device::Clone(const Device& device) { - auto ret_val = std::make_unique(); - ret_val->name = device.name; - ret_val->deviceIdV2 = device.deviceIdV2; - return ret_val; -} - -SyncRecord::SyncRecord() : action(SyncRecord::Action::A_INVALID) {} - -SyncRecord::~SyncRecord() = default; - -std::unique_ptr SyncRecord::Clone(const SyncRecord& record) { - auto ret_val = std::make_unique(); - - ret_val->action = record.action; - ret_val->deviceId = record.deviceId; - ret_val->objectId = record.objectId; - ret_val->objectData = record.objectData; - if (record.has_bookmark()) { - ret_val->SetBookmark(Bookmark::Clone(record.GetBookmark())); - } else if (record.has_historysite()) { - ret_val->SetHistorySite(Site::Clone(record.GetHistorySite())); - } else if (record.has_sitesetting()) { - ret_val->SetSiteSetting(SiteSetting::Clone(record.GetSiteSetting())); - } else if (record.has_device()) { - ret_val->SetDevice(Device::Clone(record.GetDevice())); - } - - ret_val->syncTimestamp = record.syncTimestamp; - - return ret_val; -} - -bool SyncRecord::has_bookmark() const { - return bookmark_ != nullptr; -} - -bool SyncRecord::has_historysite() const { - return history_site_ != nullptr; -} - -bool SyncRecord::has_sitesetting() const { - return site_setting_ != nullptr; -} - -bool SyncRecord::has_device() const { - return device_ != nullptr; -} - -const Bookmark& SyncRecord::GetBookmark() const { - DCHECK(has_bookmark()); - return *bookmark_.get(); -} - -const Site& SyncRecord::GetHistorySite() const { - DCHECK(has_historysite()); - return *history_site_.get(); -} - -const SiteSetting& SyncRecord::GetSiteSetting() const { - DCHECK(has_sitesetting()); - return *site_setting_.get(); -} - -const Device& SyncRecord::GetDevice() const { - DCHECK(has_device()); - return *device_.get(); -} - -Bookmark* SyncRecord::mutable_bookmark() { - DCHECK(has_bookmark()); - return bookmark_.get(); -} - -bool SyncRecord::Matches(const SyncRecord& record) const { - if (action == record.action && deviceId == record.deviceId && - objectId == record.objectId && objectData == record.objectData && - has_bookmark() == record.has_bookmark() && - has_historysite() == record.has_historysite() && - has_sitesetting() == record.has_sitesetting() && - has_device() == record.has_device()) { - if (objectData == jslib_const::SyncObjectData_BOOKMARK) - return GetBookmark().Matches(record.GetBookmark()); - return true; - } - return false; -} - -void SyncRecord::SetBookmark(std::unique_ptr bookmark) { - DCHECK(!has_bookmark() && !has_historysite() && !has_sitesetting() && - !has_device()); - bookmark_ = std::move(bookmark); -} - -void SyncRecord::SetHistorySite(std::unique_ptr history_site) { - DCHECK(!has_bookmark() && !has_historysite() && !has_sitesetting() && - !has_device()); - history_site_ = std::move(history_site); -} - -void SyncRecord::SetSiteSetting(std::unique_ptr site_setting) { - DCHECK(!has_bookmark() && !has_historysite() && !has_sitesetting() && - !has_device()); - site_setting_ = std::move(site_setting); -} - -void SyncRecord::SetDevice(std::unique_ptr device) { - DCHECK(!has_bookmark() && !has_historysite() && !has_sitesetting() && - !has_device()); - device_ = std::move(device); -} - -std::ostream& operator<<(std::ostream& out, const Site& site) { - out << "location=" << site.location << ", "; - out << "title=" << site.title << ", "; - out << "customTitle=" << site.customTitle << ", "; - out << "creationTime=" << site.creationTime << ", "; - out << "favicon=" << site.favicon; - return out; -} - -} // namespace jslib - -} // namespace brave_sync diff --git a/components/brave_sync/jslib_messages.h b/components/brave_sync/jslib_messages.h deleted file mode 100644 index 0dd67991dc1c..000000000000 --- a/components/brave_sync/jslib_messages.h +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_JSLIB_MESSAGES_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_JSLIB_MESSAGES_H_ - -#include -#include -#include - -#include "base/time/time.h" - -namespace brave_sync { - -namespace jslib { - -// Simple C++ structures to work with messages from sync lib -// Since it is not possible to use sync lib C++ protobuf generated by reasons: -// 1) Chromium everywhere uses `syntax = "proto2";`, -// sync-lib - `syntax = "proto3";` -// 2) forcing to use version 3 makes to have a deps -// "//third_party/protobuf:protobuf_full" : -// marked `Do not use in Chrome code.` in src/third_party/protobuf/BUILD.gn -// 3) even with a depth of a deps "//third_party/protobuf:protobuf_full" -// there are questions how to convert json -> protobuf class, -// not all of fields were converted - -class Site { - public: - Site(); - Site(const Site& site); - ~Site(); - static std::unique_ptr Clone(const Site& site); - - // Ignore creationTime - bool Matches(const Site& site) const; - - std::string TryGetNonEmptyTitle() const; - - std::string location; - std::string title; - std::string customTitle; - base::Time lastAccessedTime; - base::Time creationTime; - std::string favicon; -}; - -class MetaInfo { - public: - MetaInfo(); - MetaInfo(const MetaInfo& metaInfo); - ~MetaInfo(); - static std::unique_ptr Clone(const MetaInfo& metaInfo); - - std::string key; - std::string value; -}; - -class Bookmark { - public: - Bookmark(); - Bookmark(const Bookmark& bookmark); - ~Bookmark(); - static std::unique_ptr Clone(const Bookmark& bookmark); - - // Ignore fields and metaInfo - bool Matches(const Bookmark& bookmark) const; - - Site site; - bool isFolder; - std::string parentFolderObjectId; // bytes - std::vector fields; - bool hideInToolbar; - std::string order; - std::vector metaInfo; -}; - -class SiteSetting { - public: - SiteSetting(); - ~SiteSetting(); - static std::unique_ptr Clone(const SiteSetting& site_setting); - - std::string hostPattern; - double zoomLevel; - bool shieldsUp; - enum AdControl { - ADC_INVALID = -1, - SHOW_BRAVE_ADS = 0, - BLOCK_ADS = 1, - ALLOW_ADS_AND_TRACKING = 2, - ADC_MIN = SHOW_BRAVE_ADS, - ADC_MAX = ALLOW_ADS_AND_TRACKING, - }; - enum CookieControl { - CC_INVALID = -1, - BLOCK_THIRD_PARTY_COOKIE = 0, - ALLOW_ALL_COOKIES = 1, - BLOCK_ALL_COOKIES = 2, - CC_MIN = BLOCK_THIRD_PARTY_COOKIE, - CC_MAX = BLOCK_ALL_COOKIES, - }; - AdControl adControl; - CookieControl cookieControl; - bool safeBrowsing; - bool noScript; - bool httpsEverywhere; - bool fingerprintingProtection; - bool ledgerPayments; - bool ledgerPaymentsShown; - std::vector fields; -}; - -class Device { - public: - Device(); - ~Device(); - static std::unique_ptr Clone(const Device& device); - std::string name; - std::string deviceIdV2; -}; - - -class SyncRecord { - public: - SyncRecord(); - ~SyncRecord(); - - static std::unique_ptr Clone(const SyncRecord& record); - - enum Action { - A_INVALID = -1, - A_CREATE = 0, - A_UPDATE = 1, - A_DELETE = 2, - A_MIN = A_CREATE, - A_MAX = A_DELETE, - }; - - Action action; - std::string deviceId; // bytes - std::string objectId; // bytes - - std::string objectData; - - bool has_bookmark() const; - bool has_historysite() const; - bool has_sitesetting() const; - bool has_device() const; - const Bookmark& GetBookmark() const; - const Site& GetHistorySite() const; - const SiteSetting& GetSiteSetting() const; - const Device& GetDevice() const; - Bookmark* mutable_bookmark(); - - // Ignore syncTimestamp, history, site_setting and device - bool Matches(const SyncRecord& record) const; - - void SetBookmark(std::unique_ptr bookmark); - void SetHistorySite(std::unique_ptr history_site); - void SetSiteSetting(std::unique_ptr site_setting); - void SetDevice(std::unique_ptr device); - - base::Time syncTimestamp; - - private: - std::unique_ptr bookmark_; - std::unique_ptr history_site_; - std::unique_ptr site_setting_; - std::unique_ptr device_; -}; - -std::ostream& operator<<(std::ostream& out, const Site& site); - -} // namespace jslib - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_JSLIB_MESSAGES_H_ diff --git a/components/brave_sync/jslib_messages_fwd.h b/components/brave_sync/jslib_messages_fwd.h deleted file mode 100644 index 181848bcbf06..000000000000 --- a/components/brave_sync/jslib_messages_fwd.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_JSLIB_MESSAGES_FWD_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_JSLIB_MESSAGES_FWD_H_ - -#include -#include -#include - -#include "base/callback.h" -#include "base/synchronization/waitable_event.h" -#include "build/build_config.h" - -// TODO(darkdh): forward declaration with unique_ptr on Windows -#if defined(OS_WIN) -#include "brave/components/brave_sync/jslib_messages.h" -#else -namespace brave_sync { -namespace jslib { -class SyncRecord; -} -} -#endif - -namespace syncer { -class Syncer; -} // namespace syncer - -namespace brave_sync { - -typedef std::unique_ptr SyncRecordPtr; -typedef std::vector RecordsList; -typedef std::unique_ptr RecordsListPtr; -typedef std::pair SyncRecordAndExisting; -typedef std::unique_ptr SyncRecordAndExistingPtr; -typedef std::vector SyncRecordAndExistingList; - -using Uint8Array = std::vector; -using GetRecordsCallback = - base::OnceCallback)>; -using NudgeSyncCycleDelegate = base::RepeatingCallback; -using PollSyncCycleDelegate = - base::RepeatingCallback; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_JSLIB_MESSAGES_FWD_H_ diff --git a/components/brave_sync/public/brave_profile_sync_service.h b/components/brave_sync/public/brave_profile_sync_service.h deleted file mode 100644 index 983b424b1ff8..000000000000 --- a/components/brave_sync/public/brave_profile_sync_service.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_PUBLIC_BRAVE_PROFILE_SYNC_SERVICE_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_PUBLIC_BRAVE_PROFILE_SYNC_SERVICE_H_ - -#include - -#include "brave/components/brave_sync/jslib_messages_fwd.h" -#include "components/sync/driver/profile_sync_service.h" - -namespace base { -class WaitableEvent; -} - -namespace brave_sync { - -class BraveSyncService; - -class BraveProfileSyncService : public syncer::ProfileSyncService { - public: - explicit BraveProfileSyncService(InitParams init_params) - : syncer::ProfileSyncService(std::move(init_params)) {} - ~BraveProfileSyncService() override {} - - virtual bool IsBraveSyncEnabled() const = 0; - virtual void OnNudgeSyncCycle(brave_sync::RecordsListPtr records_list) = 0; - virtual void OnPollSyncCycle(brave_sync::GetRecordsCallback cb, - base::WaitableEvent* wevent) = 0; - - virtual BraveSyncService* GetSyncService() const = 0; -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_PUBLIC_BRAVE_PROFILE_SYNC_SERVICE_H_ diff --git a/components/brave_sync/resources.grd b/components/brave_sync/resources.grd deleted file mode 100644 index 82b3a00c0b05..000000000000 --- a/components/brave_sync/resources.grd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/components/brave_sync/settings.cc b/components/brave_sync/settings.cc deleted file mode 100644 index 3146d258bf60..000000000000 --- a/components/brave_sync/settings.cc +++ /dev/null @@ -1,17 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/settings.h" - -namespace brave_sync { - -Settings::Settings() : - sync_this_device_(false), - sync_bookmarks_(false), - sync_settings_(false), - sync_history_(false), - sync_configured_(false) { -} - -} // namespace brave_sync diff --git a/components/brave_sync/settings.h b/components/brave_sync/settings.h deleted file mode 100644 index 95a882a618d0..000000000000 --- a/components/brave_sync/settings.h +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_SETTINGS_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_SETTINGS_H_ - -#include - -namespace brave_sync { - -class Settings { - public: - Settings(); - std::string this_device_name_; - std::string this_device_id_; - std::string this_device_id_v2_; - bool sync_this_device_; - bool sync_bookmarks_; - bool sync_settings_; - bool sync_history_; - - // sync_configured_ may be true, but sync_this_device_==false - // So sync is suspended - bool sync_configured_; -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_SETTINGS_H_ diff --git a/components/brave_sync/sync_devices.cc b/components/brave_sync/sync_devices.cc deleted file mode 100644 index 19dca2322be2..000000000000 --- a/components/brave_sync/sync_devices.cc +++ /dev/null @@ -1,221 +0,0 @@ -/* Copyright 2016 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/sync_devices.h" - -#include - -#include "base/json/json_writer.h" -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "base/values.h" -#include "brave/components/brave_sync/jslib_const.h" - -namespace brave_sync { - -SyncDevice::SyncDevice() : - last_active_ts_(0) { -} - -SyncDevice::SyncDevice(const SyncDevice& other) = default; - -SyncDevice::SyncDevice(const std::string& name, - const std::string& object_id, - const std::string& device_id, - const std::string& device_id_v2, - const double last_active_ts) - : name_(name), - object_id_(object_id), - device_id_(device_id), - device_id_v2_(device_id_v2), - last_active_ts_(last_active_ts) {} - -SyncDevice& SyncDevice::operator=(const SyncDevice&) & = default; - -SyncDevice::~SyncDevice() = default; - -std::unique_ptr SyncDevice::ToValue() const { - auto val_sync_device = - std::make_unique(base::Value::Type::DICTIONARY); - - val_sync_device->SetKey("name", base::Value(name_)); - val_sync_device->SetKey("object_id", base::Value(object_id_)); - val_sync_device->SetKey("device_id", base::Value(device_id_)); - val_sync_device->SetKey("device_id_v2", base::Value(device_id_v2_)); - val_sync_device->SetKey("last_active", base::Value(last_active_ts_)); - - return val_sync_device; -} - -SyncDevices::SyncDevices() = default; -SyncDevices::~SyncDevices() = default; - -std::string SyncDevices::ToJson() const { - // devices_ => base::Value => json - std::string json; - bool result = base::JSONWriter::WriteWithOptions( - *this->ToValue(), - 0, - &json); - - DCHECK(result); - return json; -} - -std::unique_ptr SyncDevices::ToValue() const { - auto val_sync_device = - std::make_unique(base::Value::Type::DICTIONARY); - - auto arr_devices = std::make_unique(base::Value::Type::LIST); - for (const SyncDevice &device : devices_) { - arr_devices->Append(std::move(*device.ToValue())); - } - - val_sync_device->SetKey("devices", std::move(*arr_devices)); - - return val_sync_device; -} - -std::unique_ptr SyncDevices::ToValueArrOnly() const { - auto arr_devices = std::make_unique(base::Value::Type::LIST); - for (const SyncDevice &device : devices_) { - arr_devices->Append(std::move(*device.ToValue())); - } - - return arr_devices; -} - -void SyncDevices::FromJson(const std::string& str_json) { - if (str_json.empty()) { - devices_.clear(); - return; - } - - // JSON ==> Value - base::JSONReader::ValueWithError value_with_error = - base::JSONReader::ReadAndReturnValueWithError( - str_json, base::JSONParserOptions::JSON_PARSE_RFC); - base::Optional& records_v = value_with_error.value; - - DCHECK(records_v); - if (!records_v) { - return; - } - - devices_.clear(); - const base::Value* pv_arr = records_v->FindKey("devices"); - CHECK(pv_arr->is_list()); - for (const base::Value &val : pv_arr->GetList()) { - std::string name = val.FindKey("name")->GetString(); - std::string object_id = val.FindKey("object_id")->GetString(); - std::string device_id = val.FindKey("device_id")->GetString(); - std::string device_id_v2; - const base::Value* device_id_value = val.FindKey("device_id_v2"); - if (device_id_value) - device_id_v2 = device_id_value->GetString(); - double last_active = 0; - const base::Value *v_last_active = val.FindKey("last_active"); - if (v_last_active->is_double()) { - last_active = v_last_active->GetDouble(); - } else { - LOG(WARNING) << "SyncDevices::FromJson: last_active is not a double"; - } - - devices_.push_back( - SyncDevice(name, object_id, device_id, device_id_v2, last_active)); - } -} - -void SyncDevices::Merge(const SyncDevice& device, - int action, - bool* actually_merged) { - *actually_merged = false; - auto existing_it = std::find_if(std::begin(devices_), - std::end(devices_), - [device](const SyncDevice &cur_dev) { - return cur_dev.object_id_ == device.object_id_; - }); - - switch (action) { - case jslib_const::kActionCreate: { - if (existing_it == std::end(devices_)) { - devices_.push_back(device); - *actually_merged = true; - } else { - // ignoring create, already have device - } - break; - } - case jslib_const::kActionUpdate: { - DCHECK(existing_it != std::end(devices_)); - *existing_it = device; - *actually_merged = true; - break; - } - case jslib_const::kActionDelete: { - // Sync js lib does not merge several DELETE records into one, - // at this point existing_it can be equal to std::end(devices_) - if (existing_it != std::end(devices_)) { - devices_.erase(existing_it); - *actually_merged = true; - } else { - // ignoring delete, already deleted - } - break; - } - } -} - -SyncDevice* SyncDevices::GetByObjectId(const std::string &object_id) { - for (auto& device : devices_) { - if (device.object_id_ == object_id) { - return &device; - } - } - - return nullptr; -} - -std::vector SyncDevices::GetByDeviceId( - const std::string& device_id) { - std::vector devices; - for (const auto& device : devices_) { - if (device.device_id_ == device_id) { - devices.push_back(&device); - } - } - - return devices; -} - -const SyncDevice* SyncDevices::GetByDeviceIdV2( - const std::string& device_id_v2) { - for (const auto& device : devices_) { - if (device.device_id_v2_ == device_id_v2) { - return &device; - } - } - - return nullptr; -} - -void SyncDevices::DeleteByObjectId(const std::string &object_id) { - auto existing_it = - std::find_if(std::begin(devices_), - std::end(devices_), - [object_id](const SyncDevice &dev) { - return dev.object_id_ == object_id; - }); - - if (existing_it != std::end(devices_)) { - devices_.erase(existing_it); - } else { - // TODO(bridiver) - is this correct? - NOTREACHED(); - } -} - -} // namespace brave_sync diff --git a/components/brave_sync/sync_devices.h b/components/brave_sync/sync_devices.h deleted file mode 100644 index c64945989aef..000000000000 --- a/components/brave_sync/sync_devices.h +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_SYNC_DEVICES_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_SYNC_DEVICES_H_ - -#include -#include -#include - -namespace base { -class Value; -} // namespace base - -namespace brave_sync { - -class SyncDevice { - public: - SyncDevice(); - SyncDevice(const SyncDevice& other); - SyncDevice(const std::string& name, - const std::string& object_id, - const std::string& device_id, - const std::string& device_id_v2, - const double last_active_ts); - SyncDevice& operator=(const SyncDevice&) &; - ~SyncDevice(); - - std::unique_ptr ToValue() const; - - std::string name_; - std::string object_id_; - std::string device_id_; - std::string device_id_v2_; - double last_active_ts_; -}; - -class SyncDevices { - public: - SyncDevices(); - ~SyncDevices(); - std::vector devices_; - std::unique_ptr ToValue() const; - std::unique_ptr ToValueArrOnly() const; - std::string ToJson() const; - size_t size() const { return devices_.size(); } - void FromJson(const std::string& str_json); - void Merge(const SyncDevice& device, int action, bool* actually_merged); - - // deprecated. only used for migration and backward compatibility - std::vector GetByDeviceId(const std::string& device_id); - const SyncDevice* GetByDeviceIdV2(const std::string& device_id_v2); - SyncDevice* GetByObjectId(const std::string& object_id); - void DeleteByObjectId(const std::string& object_id); -}; - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_SYNC_DEVICES_H_ diff --git a/components/brave_sync/syncer_helper.cc b/components/brave_sync/syncer_helper.cc deleted file mode 100644 index 3d2c87e401b8..000000000000 --- a/components/brave_sync/syncer_helper.cc +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/syncer_helper.h" - -#include "base/strings/string_number_conversions.h" -#include "brave/components/brave_sync/bookmark_order_util.h" -#include "brave/components/brave_sync/tools.h" -#include "components/bookmarks/browser/bookmark_node.h" - -namespace brave_sync { -namespace { - -void SetOrder(const bookmarks::BookmarkNode* node, - const std::string& parent_order) { - DCHECK(!parent_order.empty()); - int index = node->parent()->GetIndexOf(node); - - bookmarks::BookmarkNode* parent = tools::AsMutable(node->parent()); - - auto* prev_node = index == 0 ? nullptr : parent->children()[index - 1].get(); - auto* next_node = static_cast(index) == parent->children().size() - 1 - ? nullptr - : parent->children()[index + 1].get(); - - std::string prev_order; - std::string next_order; - if (prev_node) - prev_node->GetMetaInfo("order", &prev_order); - - if (next_node) - next_node->GetMetaInfo("order", &next_order); - - std::string order = - brave_sync::GetOrder(prev_order, next_order, parent_order); - tools::AsMutable(node)->SetMetaInfo("order", order); -} - -} // namespace - -size_t GetIndex(const bookmarks::BookmarkNode* parent, - const std::string& order, - const std::string& object_id) { - DCHECK(!order.empty()); - DCHECK(!object_id.empty()); - for (size_t i = 0; i < parent->children().size(); ++i) { - const bookmarks::BookmarkNode* child = parent->children()[i].get(); - // Same order and same object id (case when child is equal to target node) - // will be skipped - std::string child_order; - child->GetMetaInfo("order", &child_order); - if (!child_order.empty() && - brave_sync::CompareOrder(order, child_order)) { - return i; - } else if (order == child_order) { - std::string child_object_id; - child->GetMetaInfo("object_id", &child_object_id); - if (object_id < child_object_id) { - return i; - } - } - } - return parent->children().size(); -} - -size_t GetIndex(const bookmarks::BookmarkNode* parent, - const bookmarks::BookmarkNode* node) { - std::string order; - node->GetMetaInfo("order", &order); - std::string object_id; - node->GetMetaInfo("object_id", &object_id); - - return GetIndex(parent, order, object_id); -} - -void AddBraveMetaInfo(const bookmarks::BookmarkNode* node) { - std::string parent_order; - node->parent()->GetMetaInfo("order", &parent_order); - SetOrder(node, parent_order); - - std::string object_id; - node->GetMetaInfo("object_id", &object_id); - // newly created node - if (object_id.empty()) { - object_id = tools::GenerateObjectId(); - } - tools::AsMutable(node)->SetMetaInfo("object_id", object_id); - - std::string parent_object_id; - // other_node object id will be empty for the first time, it will be - // generated before sending commits - node->parent()->GetMetaInfo("object_id", &parent_object_id); - tools::AsMutable(node)->SetMetaInfo("parent_object_id", parent_object_id); - - std::string sync_timestamp; - node->GetMetaInfo("sync_timestamp", &sync_timestamp); - if (sync_timestamp.empty()) { - sync_timestamp = std::to_string(base::Time::Now().ToJsTime()); - tools::AsMutable(node)->SetMetaInfo("sync_timestamp", sync_timestamp); - } - DCHECK(!sync_timestamp.empty()); - // Set other_node to have same sync_timestamp as least added child - if (node->parent()->type() == bookmarks::BookmarkNode::OTHER_NODE) { - tools::AsMutable(node->parent()) - ->SetMetaInfo("sync_timestamp", sync_timestamp); - } -} - -} // namespace brave_sync diff --git a/components/brave_sync/syncer_helper.h b/components/brave_sync/syncer_helper.h deleted file mode 100644 index 6739ef40b950..000000000000 --- a/components/brave_sync/syncer_helper.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_SYNCER_HELPER_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_SYNCER_HELPER_H_ - -#include -#include - -namespace bookmarks { -class BookmarkNode; -} // namespace bookmarks - -namespace brave_sync { - -// Get index to insert by comparing order or object_id of the node -size_t GetIndex(const bookmarks::BookmarkNode* parent, - const std::string& order, - const std::string& object_id); - -size_t GetIndex(const bookmarks::BookmarkNode* parent, - const bookmarks::BookmarkNode* node); - -void AddBraveMetaInfo(const bookmarks::BookmarkNode* node); - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_SYNCER_HELPER_H_ diff --git a/components/brave_sync/syncer_helper_unittest.cc b/components/brave_sync/syncer_helper_unittest.cc deleted file mode 100644 index 439878f6b7b8..000000000000 --- a/components/brave_sync/syncer_helper_unittest.cc +++ /dev/null @@ -1,619 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include -#include -#include -#include - -#include "base/files/scoped_temp_dir.h" -#include "base/guid.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "brave/components/brave_sync/syncer_helper.h" -#include "brave/components/brave_sync/test_util.h" -#include "chrome/browser/bookmarks/bookmark_model_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "components/bookmarks/browser/bookmark_model.h" -#include "components/bookmarks/browser/bookmark_utils.h" -#include "components/bookmarks/common/bookmark_pref_names.h" -#include "components/bookmarks/test/test_bookmark_client.h" -#include "components/prefs/pref_service.h" -#include "content/public/test/browser_task_environment.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; -using testing::AtLeast; - -using bookmarks::BookmarkClient; -using bookmarks::BookmarkModel; -using bookmarks::BookmarkNode; - -namespace brave_sync { - -namespace { - -// |node| is near the end in parent -void RepositionRespectOrder(bookmarks::BookmarkModel* bookmark_model, - const bookmarks::BookmarkNode* node) { - const bookmarks::BookmarkNode* parent = node->parent(); - int index = GetIndex(parent, node); - bookmark_model->Move(node, parent, index); -} - -} // namespace - -class SyncerHelperTest : public testing::Test { - public: - SyncerHelperTest() {} - ~SyncerHelperTest() override {} - - protected: - void SetUp() override { - EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); - - profile_ = CreateBraveSyncProfile(temp_dir_.GetPath()); - EXPECT_TRUE(profile_.get() != NULL); - - BookmarkModelFactory::GetInstance()->SetTestingFactory( - profile_.get(), base::BindRepeating(&BuildFakeBookmarkModelForTests)); - - model_ = BookmarkModelFactory::GetForBrowserContext( - Profile::FromBrowserContext(profile_.get())); - - EXPECT_NE(bookmark_client(), nullptr); - EXPECT_NE(model(), nullptr); - - // SetPermanentNodesOrder - model_->SetNodeMetaInfo(model_->bookmark_bar_node(), "order", "1.0.1"); - - model_->SetNodeMetaInfo(model_->other_node(), "order", "1.0.2"); - } - - void TearDown() override { profile_.reset(); } - - BookmarkClient* bookmark_client() { return model_->client(); } - BookmarkModel* model() { return model_; } - - private: - // Need this as a very first member to run tests in UI thread - // When this is set, class should not install any other MessageLoops, like - // base::test::ScopedTaskEnvironment - content::BrowserTaskEnvironment task_environment_; - - BookmarkModel* model_; // Not owns - std::unique_ptr profile_; - base::ScopedTempDir temp_dir_; -}; - -TEST_F(SyncerHelperTest, AddBraveMetaInfoCreateOrUpdate) { - std::string order; - std::string sync_timestamp; - const auto* folder1 = model()->AddFolder(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("Folder1")); - AddBraveMetaInfo(folder1); - folder1->GetMetaInfo("order", &order); - EXPECT_EQ(order, "1.0.1.1"); - std::string folder1_id; - folder1->GetMetaInfo("object_id", &folder1_id); - EXPECT_TRUE(!folder1_id.empty()); - std::string folder1_parent_id; - folder1->GetMetaInfo("parent_object_id", &folder1_parent_id); - EXPECT_TRUE(folder1_parent_id.empty()); - folder1->GetMetaInfo("sync_timestamp", &sync_timestamp); - EXPECT_TRUE(!sync_timestamp.empty()); - - const auto* node_a = model()->AddURL( - folder1, 0, base::ASCIIToUTF16("A.com - title"), GURL("https://a.com/")); - order.clear(); - sync_timestamp.clear(); - AddBraveMetaInfo(node_a); - node_a->GetMetaInfo("order", &order); - EXPECT_EQ(order, "1.0.1.1.1"); - std::string node_a_id; - node_a->GetMetaInfo("object_id", &node_a_id); - EXPECT_TRUE(!node_a_id.empty()); - std::string node_a_parent_id; - node_a->GetMetaInfo("parent_object_id", &node_a_parent_id); - EXPECT_EQ(node_a_parent_id, folder1_id); - node_a->GetMetaInfo("sync_timestamp", &sync_timestamp); - EXPECT_TRUE(!sync_timestamp.empty()); - - // Update - order.clear(); - node_a_id.clear(); - node_a_parent_id.clear(); - model()->SetURL(node_a, GURL("https://a-m.com/")); - AddBraveMetaInfo(node_a); - node_a->GetMetaInfo("order", &order); - EXPECT_EQ(order, "1.0.1.1.1"); - node_a->GetMetaInfo("object_id", &node_a_id); - EXPECT_TRUE(!node_a_id.empty()); - node_a->GetMetaInfo("parent_object_id", &node_a_parent_id); - EXPECT_EQ(node_a_parent_id, folder1_id); - std::string new_sync_timestamp; - node_a->GetMetaInfo("sync_timestamp", &new_sync_timestamp); - EXPECT_EQ(new_sync_timestamp, sync_timestamp); -} - -TEST_F(SyncerHelperTest, AddBraveMetaInfoNodeMoved) { - const auto* folder1 = model()->AddFolder(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("Folder1")); - AddBraveMetaInfo(folder1); - const auto* node_a = model()->AddURL( - folder1, 0, base::ASCIIToUTF16("A.com - title"), GURL("https://a.com/")); - AddBraveMetaInfo(node_a); - model()->Move(node_a, model()->bookmark_bar_node(), 1); - AddBraveMetaInfo(node_a); - - std::string order; - node_a->GetMetaInfo("order", &order); - EXPECT_EQ(order, "1.0.1.2"); - std::string node_a_id; - node_a->GetMetaInfo("object_id", &node_a_id); - EXPECT_TRUE(!node_a_id.empty()); - std::string node_a_parent_id; - node_a->GetMetaInfo("parent_object_id", &node_a_parent_id); - EXPECT_TRUE(node_a_parent_id.empty()); - std::string sync_timestamp; - node_a->GetMetaInfo("sync_timestamp", &sync_timestamp); - EXPECT_TRUE(!sync_timestamp.empty()); -} - -TEST_F(SyncerHelperTest, AddBraveMetaInfoNodeChildrenReordered) { - const auto* node_a = model()->AddURL(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("A.com - title"), - GURL("https://a.com/")); - AddBraveMetaInfo(node_a); - const auto* node_b = model()->AddURL(model()->bookmark_bar_node(), 1, - base::ASCIIToUTF16("B.com - title"), - GURL("https://b.com/")); - AddBraveMetaInfo(node_b); - const auto* node_c = model()->AddURL(model()->bookmark_bar_node(), 2, - base::ASCIIToUTF16("C.com - title"), - GURL("https://c.com/")); - AddBraveMetaInfo(node_c); - - // Expecting to have initially: - // 'Bookmarks Bar' 1.0.1 - // |-A.com 1.0.1.1 - // |-B.com 1.0.1.2 - // |-C.com 1.0.1.3 - - std::string order_a; - std::string order_b; - std::string order_c; - node_a->GetMetaInfo("order", &order_a); - EXPECT_EQ(order_a, "1.0.1.1"); - node_b->GetMetaInfo("order", &order_b); - EXPECT_EQ(order_b, "1.0.1.2"); - node_c->GetMetaInfo("order", &order_c); - EXPECT_EQ(order_c, "1.0.1.3"); - - model()->Move(node_c, model()->bookmark_bar_node(), 0); - AddBraveMetaInfo(node_c); - - // After move to have: - // 'Bookmarks Bar' 1.0.1 - // |-C.com 1.0.1.0.1 - // |-A.com 1.0.1.1 - // |-B.com 1.0.1.2 - - order_a.clear(); - order_b.clear(); - order_c.clear(); - - node_a->GetMetaInfo("order", &order_a); - EXPECT_EQ(order_a, "1.0.1.1"); - node_b->GetMetaInfo("order", &order_b); - EXPECT_EQ(order_b, "1.0.1.2"); - node_c->GetMetaInfo("order", &order_c); - EXPECT_EQ(order_c, "1.0.1.0.1"); -} - -TEST_F(SyncerHelperTest, AddBraveMetaInfoNodeMovedReordered) { - const auto* node_a = model()->AddURL(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("A.com - title"), - GURL("https://a.com/")); - AddBraveMetaInfo(node_a); - const auto* folder1 = model()->AddFolder(model()->bookmark_bar_node(), 1, - base::ASCIIToUTF16("Folder1")); - AddBraveMetaInfo(folder1); - const auto* node_b = model()->AddURL( - folder1, 0, base::ASCIIToUTF16("B.com - title"), GURL("https://b.com/")); - AddBraveMetaInfo(node_b); - const auto* node_c = model()->AddURL( - folder1, 1, base::ASCIIToUTF16("C.com - title"), GURL("https://c.com/")); - AddBraveMetaInfo(node_c); - - // Expecting here to have: - // 'Bookmarks Bar' 1.0.1 - // |-A.com 1.0.1.1 - // |-Folder1 1.0.1.2 - // |-B.com 1.0.1.2.1 - // |-C.com 1.0.1.2.2 - - std::string order_a; - std::string order_b; - std::string order_c; - std::string order_folder1; - node_a->GetMetaInfo("order", &order_a); - EXPECT_EQ(order_a, "1.0.1.1"); - node_b->GetMetaInfo("order", &order_b); - EXPECT_EQ(order_b, "1.0.1.2.1"); - node_c->GetMetaInfo("order", &order_c); - EXPECT_EQ(order_c, "1.0.1.2.2"); - folder1->GetMetaInfo("order", &order_folder1); - EXPECT_EQ(order_folder1, "1.0.1.2"); - - model()->Move(node_a, folder1, 0); - AddBraveMetaInfo(node_a); - - order_a.clear(); - order_b.clear(); - order_c.clear(); - order_folder1.clear(); - - // After move expecting have: - // 'Bookmarks Bar' 1.0.1 (kept) - // |-Folder1 1.0.1.2 (kept) - // |-A.com 1.0.1.2.0.1 (re-calculated) - // |-B.com 1.0.1.2.1 (kept) - // |-C.com 1.0.1.2.2 (kept) - - node_a->GetMetaInfo("order", &order_a); - EXPECT_EQ(order_a, "1.0.1.2.0.1"); - node_b->GetMetaInfo("order", &order_b); - EXPECT_EQ(order_b, "1.0.1.2.1"); - node_c->GetMetaInfo("order", &order_c); - EXPECT_EQ(order_c, "1.0.1.2.2"); - folder1->GetMetaInfo("order", &order_folder1); - EXPECT_EQ(order_folder1, "1.0.1.2"); -} - -TEST_F(SyncerHelperTest, GetIndexInPermanentNodes) { - BookmarkNode node(/*id=*/0, base::GenerateGUID(), GURL("https://brave.com")); - node.SetMetaInfo("object_id", "notused"); - node.SetMetaInfo("order", "1.0.1.1"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 0u); - - node.SetMetaInfo("order", "1.0.2.1"); - EXPECT_EQ(GetIndex(model()->other_node(), &node), 0u); - - const auto* node_a = - model()->AddURL(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("a.com"), GURL("https://a.com/")); - model()->SetNodeMetaInfo(node_a, "object_id", "notused"); - // compare device id - model()->SetNodeMetaInfo(node_a, "order", "1.1.1.1"); - node.SetMetaInfo("order", "1.0.1.1"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 0u); - model()->SetNodeMetaInfo(node_a, "order", "1.0.1.1"); - node.SetMetaInfo("order", "1.1.1.1"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 1u); - - // compare platform id - model()->SetNodeMetaInfo(node_a, "order", "2.0.1.1"); - node.SetMetaInfo("order", "1.0.1.1"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 0u); - model()->SetNodeMetaInfo(node_a, "order", "1.0.1.1"); - node.SetMetaInfo("order", "2.0.1.1"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 1u); -} - -TEST_F(SyncerHelperTest, GetIndexMoreChildren) { - for (int i = 0; i < 10; ++i) { - const auto* node_a = - model()->AddURL(model()->bookmark_bar_node(), i, - base::ASCIIToUTF16("a.com"), GURL("https://a.com/")); - std::string order = "1.1.1." + base::NumberToString(i == 9 ? i + 2 : i + 1); - model()->SetNodeMetaInfo(node_a, "order", order); - model()->SetNodeMetaInfo(node_a, "object_id", "notused"); - } - // inserted as first child - BookmarkNode node(/*id=*/9, base::GenerateGUID(), GURL("https://brave.com")); - node.SetMetaInfo("object_id", "notused"); - node.SetMetaInfo("order", "1.0.1.10"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 0u); - // inserted as 10th child - node.SetMetaInfo("order", "1.1.1.10"); - EXPECT_EQ(GetIndex(model()->bookmark_bar_node(), &node), 9u); -} - -TEST_F(SyncerHelperTest, GetIndexInFolder) { - const auto* folder1 = model()->AddFolder(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("Folder1")); - model()->SetNodeMetaInfo(folder1, "order", "1.0.1.1"); - BookmarkNode node(/*id=*/1, base::GenerateGUID(), GURL("https://brave.com")); - node.SetMetaInfo("object_id", "notused"); - node.SetMetaInfo("order", "1.0.1.1.1"); - EXPECT_EQ(GetIndex(folder1, &node), 0u); - - // appended at the end - const auto* node_a = model()->AddURL(folder1, 0, base::ASCIIToUTF16("a.com"), - GURL("https://a.com/")); - model()->SetNodeMetaInfo(node_a, "order", "1.0.1.1.1"); - model()->SetNodeMetaInfo(node_a, "object_id", "notused"); - node.SetMetaInfo("order", "1.0.1.1.2"); - EXPECT_EQ(GetIndex(folder1, &node), 1u); -} - -TEST_F(SyncerHelperTest, SameOrderBookmarksSordetByObjectIdFull3) { - // This test emulates folowing STR - // 1. on device A create bookmarks A1.com and A2.com - // 2. on device B create bookmarks B1.com and B2.com - // 3. create sync chain on device A and connect device B with a codephrase - // 4. wait for bookmarks will be synchronized between device A and B - // 5. on device A in Add bookmark dialog enter Name A3.com, URL A3.com, - // but dont press Save button - // 6. repeat pt 5 on device B, for B3.com - // 7. press Save button on devices A and B - // Expected bookmarks on devices A and B are sorted in the same way - const auto* node_a1 = - model()->AddURL(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("A1.com"), GURL("https://a1.com/")); - AddBraveMetaInfo(node_a1); - const auto* node_a2 = - model()->AddURL(model()->bookmark_bar_node(), 1, - base::ASCIIToUTF16("A2.com"), GURL("https://a2.com/")); - AddBraveMetaInfo(node_a2); - const auto* node_b1 = - model()->AddURL(model()->bookmark_bar_node(), 2, - base::ASCIIToUTF16("B1.com"), GURL("https://b1.com/")); - AddBraveMetaInfo(node_b1); - const auto* node_b2 = - model()->AddURL(model()->bookmark_bar_node(), 3, - base::ASCIIToUTF16("B2.com"), GURL("https://b2.com/")); - AddBraveMetaInfo(node_b2); - - // Expect b1 and b2 no need to move - uint64_t index_to_move_b1 = - GetIndex(model()->bookmark_bar_node(), node_b1); - // Expecting index for Move operation 3, after Move position of node will be 2 - EXPECT_EQ(index_to_move_b1, 3u); - RepositionRespectOrder(model(), node_b1); - auto title_at_2 = model()->bookmark_bar_node()->children()[2]->GetTitle(); - EXPECT_EQ(title_at_2, base::ASCIIToUTF16("B1.com")); - - uint64_t index_to_move_b2 = - GetIndex(model()->bookmark_bar_node(), node_b2); - // Expecting index for Move operation 4, after Move position of node will be 3 - EXPECT_EQ(index_to_move_b2, 4u); - RepositionRespectOrder(model(), node_b2); - auto title_at_3 = model()->bookmark_bar_node()->children()[3]->GetTitle(); - EXPECT_EQ(title_at_3, base::ASCIIToUTF16("B2.com")); - - const auto* node_a3 = - model()->AddURL(model()->bookmark_bar_node(), 4, - base::ASCIIToUTF16("A3.com"), GURL("https://a3.com/")); - AddBraveMetaInfo(node_a3); - const auto* node_b3 = - model()->AddURL(model()->bookmark_bar_node(), 5, - base::ASCIIToUTF16("B3.com"), GURL("https://b3.com/")); - AddBraveMetaInfo(node_b3); - const auto* node_c3 = - model()->AddURL(model()->bookmark_bar_node(), 6, - base::ASCIIToUTF16("C3.com"), GURL("https://c3.com/")); - AddBraveMetaInfo(node_c3); - - std::string a3_order; - node_a3->GetMetaInfo("order", &a3_order); - EXPECT_TRUE(!a3_order.empty()); - - std::string a3_object_id; - node_a3->GetMetaInfo("object_id", &a3_object_id); - EXPECT_TRUE(!a3_object_id.empty()); - - // Emulating nodes a3, b3, and c3 have the same order - const_cast(node_b3)->SetMetaInfo("order", a3_order); - const_cast(node_c3)->SetMetaInfo("order", a3_order); - - // Expecting sorting of same order bookmarks by object_id - // object_id is 16 comma and spaces separated values of 16 uint8 - // Will assign these object ids to make RepositionRespectOrder do sorting: - // C3 A3 B3 - // "..." < 1,2,3 < "@@@" - ASSERT_TRUE("..." < a3_object_id && a3_object_id < "@@@"); - const_cast(node_b3)->SetMetaInfo("object_id", "@@@"); - const_cast(node_c3)->SetMetaInfo("object_id", "..."); - - // 0 1 2 3 4 5 6 - // A1 A2 B1 B2 A3(1,2,3) B3(@@@) C3(...) - auto title_at_4 = model()->bookmark_bar_node()->children()[4]->GetTitle(); - EXPECT_EQ(title_at_4, base::ASCIIToUTF16("A3.com")); - auto title_at_5 = model()->bookmark_bar_node()->children()[5]->GetTitle(); - EXPECT_EQ(title_at_5, base::ASCIIToUTF16("B3.com")); - auto title_at_6 = model()->bookmark_bar_node()->children()[6]->GetTitle(); - EXPECT_EQ(title_at_6, base::ASCIIToUTF16("C3.com")); - - RepositionRespectOrder(model(), node_b3); - // 0 1 2 3 4 5 6 - // A1 A2 B1 B2 A3(1,2,3) C3(...) B3(@@@) - // node B3 gone after C3 because "..." < "@@@" - title_at_4 = model()->bookmark_bar_node()->children()[4]->GetTitle(); - EXPECT_EQ(title_at_4, base::ASCIIToUTF16("A3.com")); - title_at_5 = model()->bookmark_bar_node()->children()[5]->GetTitle(); - EXPECT_EQ(title_at_5, base::ASCIIToUTF16("C3.com")); - title_at_6 = model()->bookmark_bar_node()->children()[6]->GetTitle(); - EXPECT_EQ(title_at_6, base::ASCIIToUTF16("B3.com")); - - RepositionRespectOrder(model(), node_c3); - // 0 1 2 3 4 5 6 - // A1 A2 B1 B2 C3(...) A3(1,2,3) B3(@@@) - // node C3 moved to the correct position - - title_at_4 = model()->bookmark_bar_node()->children()[4]->GetTitle(); - EXPECT_EQ(title_at_4, base::ASCIIToUTF16("C3.com")); - title_at_5 = model()->bookmark_bar_node()->children()[5]->GetTitle(); - EXPECT_EQ(title_at_5, base::ASCIIToUTF16("A3.com")); - title_at_6 = model()->bookmark_bar_node()->children()[6]->GetTitle(); - EXPECT_EQ(title_at_6, base::ASCIIToUTF16("B3.com")); -} - -TEST_F(SyncerHelperTest, RemoteUpdatesHandlerNeedsMoveBookmark) { - // Emulating such STR - // 1) Device A - // [0] interia.pl 1.0.1.1 - // [1] youtube.com 1.0.1.2 - // 2) Device B does change order: - // [0] youtube.com 1.0.1.2 - // [1] interia.pl 1.0.1.3 - // 3) Device A falls into - // [0] interia.pl 1.0.1.3 - // [1] youtube.com 1.0.1.2 - // 4) Device A wants to know a new index for Move operation on interia.pl, - // which is expected to be 2 - - const auto* node_interia_pl = model()->AddURL( - model()->bookmark_bar_node(), 0, base::ASCIIToUTF16("interia.pl"), - GURL("https://interia.pl/")); - AddBraveMetaInfo(node_interia_pl); - const auto* node_youtube_com = model()->AddURL( - model()->bookmark_bar_node(), 1, base::ASCIIToUTF16("youtube.com"), - GURL("https://youtube.com/")); - AddBraveMetaInfo(node_youtube_com); - - std::string interia_pl_order; - node_interia_pl->GetMetaInfo("order", &interia_pl_order); - EXPECT_EQ(interia_pl_order, "1.0.1.1"); - - std::string youtube_com_order; - node_youtube_com->GetMetaInfo("order", &youtube_com_order); - EXPECT_EQ(youtube_com_order, "1.0.1.2"); - - const_cast(node_interia_pl)->SetMetaInfo("order", "1.0.1.3"); - int index = GetIndex(model()->bookmark_bar_node(), node_interia_pl); - EXPECT_EQ(index, 2); - - RepositionRespectOrder(model(), node_interia_pl); - auto title_at_1 = model()->bookmark_bar_node()->children()[1]->GetTitle(); - EXPECT_EQ(title_at_1, base::ASCIIToUTF16("interia.pl")); -} - -TEST_F(SyncerHelperTest, RemoteUpdatesHandlerKeepBookmarkPosition) { - // Emulating such STR - // 1) Device A - // [0] interia.pl 1.0.1.1 - // [1] youtube.com 1.0.1.2 - // 2) Device B doesn't change order - // 3) Device A falls into - // [0] interia.pl 1.0.1.1 - // [1] youtube.com 1.0.1.2 - // 4) Device A wants to know a new index for Move operation on interia.pl, - // which is expected to be 1, and after Move operation interia.pl will be on - // the position 0 - - const auto* node_interia_pl = model()->AddURL( - model()->bookmark_bar_node(), 0, base::ASCIIToUTF16("interia.pl"), - GURL("https://interia.pl/")); - AddBraveMetaInfo(node_interia_pl); - const auto* node_youtube_com = model()->AddURL( - model()->bookmark_bar_node(), 1, base::ASCIIToUTF16("youtube.com"), - GURL("https://youtube.com/")); - AddBraveMetaInfo(node_youtube_com); - - std::string interia_pl_order; - node_interia_pl->GetMetaInfo("order", &interia_pl_order); - EXPECT_EQ(interia_pl_order, "1.0.1.1"); - - std::string youtube_com_order; - node_youtube_com->GetMetaInfo("order", &youtube_com_order); - EXPECT_EQ(youtube_com_order, "1.0.1.2"); - - int index = GetIndex(model()->bookmark_bar_node(), node_interia_pl); - // Expecting index for Move operation 1, after Move position of node will be 0 - EXPECT_EQ(index, 1); - - RepositionRespectOrder(model(), node_interia_pl); - auto title_at_0 = model()->bookmark_bar_node()->children()[0]->GetTitle(); - EXPECT_EQ(title_at_0, base::ASCIIToUTF16("interia.pl")); -} - -TEST_F(SyncerHelperTest, RemoteUpdatesHandlerBookmarkPositionAmong4) { - // Emulating STR we need to move bookmark in the middle - // 1) Device A - // [0] A.com 1.0.1.1 - // [1] B.com 1.0.1.2 - // [2] C.com 1.0.1.3 - // [3] D.com 1.0.1.4 - - // 2) Device B does change order: - // [0] A.com 1.0.1.1 - // [1] C.com 1.0.1.3 - // [2] B.com 1.0.1.3.1 - // [3] D.com 1.0.1.4 - - // 3) Device A falls into - // [0] A.com 1.0.1.1 - // [1] B.com 1.0.1.3.1 - // [2] C.com 1.0.1.3 - // [3] D.com 1.0.1.4 - - // 4) Device A wants to know a new index for Move on node B.com, - // which is expected to be 3 counting the target node is still in original - // position, it will be 2 after move - - // 5) After move we have on device A - // [0] A.com 1.0.1.1 - // [1] C.com 1.0.1.3 - // [2] B.com 1.0.1.3.1 - // [3] D.com 1.0.1.4 - - const auto* node_a = - model()->AddURL(model()->bookmark_bar_node(), 0, - base::ASCIIToUTF16("A.com"), GURL("https://a.com/")); - AddBraveMetaInfo(node_a); - const auto* node_b = - model()->AddURL(model()->bookmark_bar_node(), 1, - base::ASCIIToUTF16("B.com"), GURL("https://b.com/")); - AddBraveMetaInfo(node_b); - const auto* node_c = - model()->AddURL(model()->bookmark_bar_node(), 2, - base::ASCIIToUTF16("C.com"), GURL("https://c.com/")); - AddBraveMetaInfo(node_c); - const auto* node_d = - model()->AddURL(model()->bookmark_bar_node(), 3, - base::ASCIIToUTF16("D.com"), GURL("https://d.com/")); - AddBraveMetaInfo(node_d); - - std::string a_order; - node_a->GetMetaInfo("order", &a_order); - EXPECT_TRUE(!a_order.empty()); - EXPECT_EQ(a_order, "1.0.1.1"); - - std::string b_order; - node_b->GetMetaInfo("order", &b_order); - EXPECT_TRUE(!b_order.empty()); - EXPECT_EQ(b_order, "1.0.1.2"); - - std::string c_order; - node_c->GetMetaInfo("order", &c_order); - EXPECT_TRUE(!b_order.empty()); - EXPECT_EQ(c_order, "1.0.1.3"); - - std::string d_order; - node_d->GetMetaInfo("order", &d_order); - EXPECT_TRUE(!d_order.empty()); - EXPECT_EQ(d_order, "1.0.1.4"); - - const_cast(node_b)->SetMetaInfo("order", "1.0.1.3.1"); - int index = GetIndex(model()->bookmark_bar_node(), node_b); - // Expecting index for Move operation 3, after Move position of node will be 2 - EXPECT_EQ(index, 3); - - RepositionRespectOrder(model(), node_b); - - auto title_at_0 = model()->bookmark_bar_node()->children()[0]->GetTitle(); - EXPECT_EQ(title_at_0, base::ASCIIToUTF16("A.com")); - auto title_at_1 = model()->bookmark_bar_node()->children()[1]->GetTitle(); - EXPECT_EQ(title_at_1, base::ASCIIToUTF16("C.com")); - auto title_at_2 = model()->bookmark_bar_node()->children()[2]->GetTitle(); - EXPECT_EQ(title_at_2, base::ASCIIToUTF16("B.com")); - auto title_at_3 = model()->bookmark_bar_node()->children()[3]->GetTitle(); - EXPECT_EQ(title_at_3, base::ASCIIToUTF16("D.com")); -} - -} // namespace brave_sync diff --git a/components/brave_sync/test_util.cc b/components/brave_sync/test_util.cc deleted file mode 100644 index 8d2ce12e9f0e..000000000000 --- a/components/brave_sync/test_util.cc +++ /dev/null @@ -1,152 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/test_util.h" - -#include - -#include "base/files/file_util.h" -#include "base/strings/utf_string_conversions.h" -#include "brave/components/brave_sync/tools.h" -#include "brave/components/brave_sync/values_conv.h" -#include "chrome/browser/prefs/browser_prefs.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" -#include "chrome/test/base/testing_profile.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "components/bookmarks/browser/bookmark_model.h" -#include "components/bookmarks/test/test_bookmark_client.h" -#include "components/sync_preferences/pref_service_mock_factory.h" -#include "components/sync_preferences/testing_pref_service_syncable.h" - -namespace brave_sync { - -MockBraveSyncClient::MockBraveSyncClient() {} - -MockBraveSyncClient::~MockBraveSyncClient() {} - -std::unique_ptr CreateBraveSyncProfile(const base::FilePath& path) { - ProfileSyncServiceFactory::GetInstance(); - - sync_preferences::PrefServiceMockFactory factory; - auto registry = base::MakeRefCounted(); - std::unique_ptr prefs( - factory.CreateSyncable(registry.get())); - RegisterUserProfilePrefs(registry.get()); - - TestingProfile::Builder profile_builder; - profile_builder.SetPrefService(std::move(prefs)); - profile_builder.SetPath(path); - return profile_builder.Build(); -} - -std::unique_ptr BuildFakeBookmarkModelForTests( - content::BrowserContext* context) { - using bookmarks::BookmarkModel; - using bookmarks::TestBookmarkClient; - // Don't need context, unless we have more than one profile - std::unique_ptr client(new TestBookmarkClient()); - std::unique_ptr model( - TestBookmarkClient::CreateModelWithClient(std::move(client))); - return model; -} - -SyncRecordPtr SimpleBookmarkSyncRecord(const int action, - const std::string& object_id, - const std::string& location, - const std::string& title, - const std::string& order, - const std::string& parent_object_id, - const std::string& device_id, - const bool hide_in_toolbar) { - auto record = std::make_unique(); - record->action = ConvertEnum(action, - brave_sync::jslib::SyncRecord::Action::A_MIN, - brave_sync::jslib::SyncRecord::Action::A_MAX, - brave_sync::jslib::SyncRecord::Action::A_INVALID); - - record->deviceId = device_id; - record->objectId = object_id.empty() ? tools::GenerateObjectId() : object_id; - record->objectData = "bookmark"; - - record->syncTimestamp = base::Time::Now(); - - auto bookmark = std::make_unique(); - - bookmark->isFolder = false; - // empty parentFolderObjectId means child of some permanent node - bookmark->parentFolderObjectId = parent_object_id; - bookmark->hideInToolbar = hide_in_toolbar; - bookmark->order = order; - - bookmark->site.location = location; - bookmark->site.title = title; - bookmark->site.customTitle = title; - - record->SetBookmark(std::move(bookmark)); - - return record; -} - -SyncRecordPtr SimpleFolderSyncRecord( - const int action, - const std::string& object_id, - const std::string& title, - const std::string& order, - const std::string& parent_object_id, - const std::string& device_id, - const bool hide_in_toolbar, - const std::string& custom_title) { - auto record = std::make_unique(); - record->action = ConvertEnum(action, - brave_sync::jslib::SyncRecord::Action::A_MIN, - brave_sync::jslib::SyncRecord::Action::A_MAX, - brave_sync::jslib::SyncRecord::Action::A_INVALID); - - record->deviceId = device_id; - record->objectId = object_id.empty() ? tools::GenerateObjectId() : object_id; - record->objectData = "bookmark"; - - record->syncTimestamp = base::Time::Now(); - - auto bookmark = std::make_unique(); - - bookmark->isFolder = true; - bookmark->parentFolderObjectId = parent_object_id; - bookmark->hideInToolbar = hide_in_toolbar; - bookmark->order = order; - - bookmark->site.title = title; - bookmark->site.customTitle = custom_title; - - record->SetBookmark(std::move(bookmark)); - - return record; -} - -SyncRecordPtr SimpleDeviceRecord( - const int action, - const std::string& object_id, - const std::string& device_id, - const std::string& device_id_v2, - const std::string& name) { - auto record = std::make_unique(); - record->action = ConvertEnum(action, - brave_sync::jslib::SyncRecord::Action::A_MIN, - brave_sync::jslib::SyncRecord::Action::A_MAX, - brave_sync::jslib::SyncRecord::Action::A_INVALID); - record->deviceId = device_id; - record->objectId = object_id.empty() ? tools::GenerateObjectId() : object_id; - record->objectData = "device"; - record->syncTimestamp = base::Time::Now(); - - auto device = std::make_unique(); - device->name = name; - device->deviceIdV2 = device_id_v2; - record->SetDevice(std::move(device)); - - return record; -} - -} // namespace brave_sync diff --git a/components/brave_sync/test_util.h b/components/brave_sync/test_util.h deleted file mode 100644 index ceca7bb73405..000000000000 --- a/components/brave_sync/test_util.h +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_TEST_UTIL_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_TEST_UTIL_H_ - -#include -#include -#include - -#include "base/files/file_path.h" -#include "brave/components/brave_sync/client/brave_sync_client.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -class KeyedService; -class Profile; - -namespace bookmarks { -class BookmarkPermanentNode; -} - -namespace content { -class BrowserContext; -} - -namespace brave_sync { - -class MockBraveSyncClient : public BraveSyncClient { - public: - MockBraveSyncClient(); - ~MockBraveSyncClient() override; - - MOCK_METHOD0(sync_message_handler, SyncMessageHandler*()); - MOCK_METHOD4(SendGotInitData, - void(const Uint8Array& seed, - const Uint8Array& device_id, - const client_data::Config& config, - const std::string& device_id_v2)); - MOCK_METHOD3(SendFetchSyncRecords, void( - const std::vector& category_names, const base::Time& startAt, - const int max_records)); - MOCK_METHOD2(SendResolveSyncRecords, void(const std::string& category_name, - std::unique_ptr list)); - MOCK_METHOD2(SendSyncRecords, - void(const std::string& category_name, - const RecordsList& records)); - MOCK_METHOD0(SendDeleteSyncUser, void()); - MOCK_METHOD1(SendDeleteSyncCategory, void(const std::string& category_name)); - MOCK_METHOD2(SendGetBookmarksBaseOrder, void(const std::string& device_id, - const std::string& platform)); - MOCK_METHOD0(OnExtensionInitialized, void()); - MOCK_METHOD0(OnSyncEnabledChanged, void()); - MOCK_METHOD1(SendCompact, void(const std::string& category_name)); -}; - -std::unique_ptr CreateBraveSyncProfile(const base::FilePath& path); - -std::unique_ptr BuildFakeBookmarkModelForTests( - content::BrowserContext* context); - -SyncRecordPtr SimpleBookmarkSyncRecord(const int action, - const std::string& object_id, - const std::string& location, - const std::string& title, - const std::string& order, - const std::string& parent_object_id, - const std::string& device_id, - const bool hide_in_toolbar = true); - -SyncRecordPtr SimpleFolderSyncRecord( - const int action, - const std::string& object_id, - const std::string& title, - const std::string& order, - const std::string& parent_object_id, - const std::string& device_id, - const bool hide_in_toolbar, - const std::string& custom_title); - -SyncRecordPtr SimpleDeviceRecord( - const int action, - const std::string& object_id, - const std::string& device_id, - const std::string& device_id_v2, - const std::string& name); - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_TEST_UTIL_H_ diff --git a/components/brave_sync/tools.cc b/components/brave_sync/tools.cc deleted file mode 100644 index 73e1bbd0bba4..000000000000 --- a/components/brave_sync/tools.cc +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/tools.h" - -#include -#include - -#include "base/strings/string_util.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "crypto/random.h" -#include "crypto/sha2.h" - -namespace brave_sync { - -namespace tools { - -const char kOtherNodeOrder[] = "255.255.255"; -const char kOtherNodeName[] = "Other Bookmarks"; -const size_t kIdSize = 16; -const char kOtherBookmarksObjectIdSeed[] = "other_bookmarks_object_id"; - -namespace { -std::string PrintObjectId(uint8_t* bytes) { - std::stringstream ss; - for (size_t i = 0; i < kIdSize; ++i) { - const uint8_t& byte = bytes[i]; - ss << std::dec << static_cast(byte); - if (i != kIdSize - 1) { - ss << ", "; - } - } - return ss.str(); -} -} // namespace - -std::string GenerateObjectId() { - // 16 random 8-bit unsigned numbers - uint8_t bytes[kIdSize]; - crypto::RandBytes(bytes, sizeof(bytes)); - return PrintObjectId(bytes); -} - -std::string GenerateObjectIdForOtherNode(const std::string old_id) { - uint8_t bytes[kIdSize]; - const std::string input = - old_id.empty() ? kOtherBookmarksObjectIdSeed : old_id; - // Take first 16 bytes - crypto::SHA256HashString(input, bytes, sizeof(bytes)); - return PrintObjectId(bytes); -} - -std::string GetPlatformName() { -#if defined(OS_ANDROID) - const std::string platform = "android"; -#elif defined(OS_WIN) - const std::string platform = "windows"; -#elif defined(OS_LINUX) - const std::string platform = "linux"; -#elif defined(OS_MACOSX) - const std::string platform = "macosx"; -#elif defined(OS_IOS) - const std::string platform = "ios"; -#endif - return platform; -} - -bool IsTimeEmpty(const base::Time& time) { - return time.is_null() || base::checked_cast(time.ToJsTime()) == 0; -} - -// Get mutable node to prevent BookmarkMetaInfoChanged from being triggered -bookmarks::BookmarkNode* AsMutable(const bookmarks::BookmarkNode* node) { - return const_cast(node); -} - -} // namespace tools - -} // namespace brave_sync diff --git a/components/brave_sync/tools.h b/components/brave_sync/tools.h deleted file mode 100644 index b7a56960a06c..000000000000 --- a/components/brave_sync/tools.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_TOOLS_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_TOOLS_H_ - -#include - -namespace base { -class Time; -} // namespace base - -namespace bookmarks { -class BookmarkNode; -} - -namespace brave_sync { - -namespace tools { - -extern const char kOtherNodeOrder[]; -extern const char kOtherNodeName[]; - -std::string GenerateObjectId(); - -// If old_id is empty, it would use default seed as first iteration, in future -// iteration, caller has to provide previous used id so we can have determined -// generated object id -std::string GenerateObjectIdForOtherNode(const std::string old_id); - -std::string GetPlatformName(); - -bool IsTimeEmpty(const base::Time &time); - -bookmarks::BookmarkNode* AsMutable(const bookmarks::BookmarkNode* node); - -} // namespace tools - -} // namespace brave_sync - -#endif // BRAVE_COMPONENTS_BRAVE_SYNC_TOOLS_H_ diff --git a/components/brave_sync/values_conv.cc b/components/brave_sync/values_conv.cc deleted file mode 100644 index f2c1041ecdc1..000000000000 --- a/components/brave_sync/values_conv.cc +++ /dev/null @@ -1,154 +0,0 @@ -/* Copyright 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_sync/values_conv.h" -#include "base/logging.h" -#include "base/numerics/safe_conversions.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/values.h" -#include "brave/components/brave_sync/jslib_const.h" -#include "brave/components/brave_sync/jslib_messages.h" -#include "brave/components/brave_sync/settings.h" -#include "brave/components/brave_sync/sync_devices.h" -#include "components/bookmarks/browser/bookmark_node.h" - -namespace brave_sync { - -using base::Value; - -std::unique_ptr BraveSyncSettingsToValue( - brave_sync::Settings* brave_sync_settings) { - CHECK(brave_sync_settings); - auto result = std::make_unique(Value::Type::DICTIONARY); - - result->SetKey("this_device_name", - Value(brave_sync_settings->this_device_name_)); - result->SetKey("this_device_id", Value(brave_sync_settings->this_device_id_)); - result->SetKey("this_device_id_v2", - Value(brave_sync_settings->this_device_id_v2_)); - result->SetKey("sync_this_device", - Value(brave_sync_settings->sync_this_device_)); - result->SetKey("sync_bookmarks", Value(brave_sync_settings->sync_bookmarks_)); - result->SetKey("sync_settings", Value(brave_sync_settings->sync_settings_)); - result->SetKey("sync_history", Value(brave_sync_settings->sync_history_)); - - result->SetKey("sync_configured", - Value(brave_sync_settings->sync_configured_)); - - return result; -} - -template -TEnum ConvertEnum(const int ival, TEnum min, TEnum max, TEnum def) { - DCHECK(ival >= min && ival <= max) - << " Unexpected enum value " << ival << " Should be between or include " - << min << " and " << max; - if (ival < min && ival > max) { - return def; - } - - return static_cast(ival); -} - -template jslib::SiteSetting::AdControl -ConvertEnum(const int ival, - jslib::SiteSetting::AdControl, - jslib::SiteSetting::AdControl, - jslib::SiteSetting::AdControl); - -template jslib::SiteSetting::CookieControl ConvertEnum< - jslib::SiteSetting::CookieControl>(const int ival, - jslib::SiteSetting::CookieControl, - jslib::SiteSetting::CookieControl, - jslib::SiteSetting::CookieControl); - -template jslib::SyncRecord::Action ConvertEnum( - const int ival, - jslib::SyncRecord::Action, - jslib::SyncRecord::Action, - jslib::SyncRecord::Action); - -template -TEnum ExtractEnum(const base::Value* val, - const std::string& fileld_name, - TEnum min, - TEnum max, - TEnum def) { - DCHECK(val); - DCHECK(!fileld_name.empty()); - DCHECK(val->is_dict()); - - const base::Value* int_value = - val->FindKeyOfType(fileld_name, base::Value::Type::INTEGER); - DCHECK(int_value); - if (!int_value) { - return def; - } - - int ival = int_value->GetInt(); - return ConvertEnum(ival, min, max, def); -} - -template jslib::SiteSetting::AdControl -ExtractEnum(const base::Value* val, - const std::string& fileld_name, - jslib::SiteSetting::AdControl, - jslib::SiteSetting::AdControl, - jslib::SiteSetting::AdControl); - -template jslib::SiteSetting::CookieControl ExtractEnum< - jslib::SiteSetting::CookieControl>(const base::Value* val, - const std::string& fileld_name, - jslib::SiteSetting::CookieControl, - jslib::SiteSetting::CookieControl, - jslib::SiteSetting::CookieControl); - -template jslib::SyncRecord::Action ExtractEnum( - const base::Value* val, - const std::string& fileld_name, - jslib::SyncRecord::Action, - jslib::SyncRecord::Action, - jslib::SyncRecord::Action); - -std::string StrFromUint8Array(const Uint8Array& arr) { - std::string result; - for (size_t i = 0; i < arr.size(); ++i) { - result += base::NumberToString(static_cast(arr.at(i))); - if (i != arr.size() - 1) { - result += ", "; - } - } - return result; -} - -std::string StrFromUnsignedCharArray(const std::vector& vec) { - return StrFromUint8Array(vec); -} - -Uint8Array Uint8ArrayFromString(const std::string& data_string) { - return UCharVecFromString(data_string); -} - -std::vector UCharVecFromString(const std::string& data_string) { - std::vector splitted = - SplitString(data_string, ", ", base::WhitespaceHandling::TRIM_WHITESPACE, - base::SplitResult::SPLIT_WANT_NONEMPTY); - - std::vector result; - result.reserve(splitted.size()); - - for (size_t i = 0; i < splitted.size(); ++i) { - int output = 0; - bool b = base::StringToInt(splitted[i], &output); - CHECK(b); - CHECK(output >= 0 && output <= 255); - result.emplace_back(static_cast(output)); - } - - return result; -} - -} // namespace brave_sync diff --git a/components/brave_sync/values_conv.h b/components/brave_sync/values_conv.h deleted file mode 100644 index 5e87abf69bf9..000000000000 --- a/components/brave_sync/values_conv.h +++ /dev/null @@ -1,39 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_VALUES_CONV_H_ -#define BRAVE_COMPONENTS_BRAVE_SYNC_VALUES_CONV_H_ - -#include -#include -#include - -#include -#include "brave/components/brave_sync/jslib_messages_fwd.h" - -namespace base { - class Value; -} - -namespace brave_sync { - -class Settings; - -std::unique_ptr BraveSyncSettingsToValue(brave_sync::Settings *brave_sync_settings); - -template -TEnum ExtractEnum(const base::Value *val, const std::string &fileld_name, - TEnum min, TEnum max, TEnum def); - -template -TEnum ConvertEnum(const int val, TEnum min, TEnum max, TEnum def); - -std::string StrFromUint8Array(const Uint8Array &arr); -std::string StrFromUnsignedCharArray(const std::vector &vec); -Uint8Array Uint8ArrayFromString(const std::string &data_string); -std::vector UCharVecFromString(const std::string &data_string); - -} // namespace brave_sync - -#endif //BRAVE_COMPONENTS_BRAVE_SYNC_VALUES_CONV_H_ diff --git a/test/BUILD.gn b/test/BUILD.gn index 6825b9e78226..4c4544b546c5 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -213,7 +213,6 @@ test("brave_unit_tests") { "../utility/importer/chrome_importer_unittest.cc", # TODO(samartnik): this should work on Android, we will review it once unit tests are set up on CI - "//brave/browser/autocomplete/brave_autocomplete_provider_client_unittest.cc", "//brave/browser/autoplay/autoplay_permission_context_unittest.cc", "//brave/components/brave_shields/browser/brave_shields_util_unittest.cc", "//brave/components/omnibox/browser/fake_autocomplete_provider_client.cc", @@ -328,14 +327,7 @@ test("brave_unit_tests") { if (enable_brave_sync) { sources += [ - "//brave/components/brave_sync/bookmark_order_util_unittest.cc", - "//brave/components/brave_sync/brave_sync_service_unittest.cc", "//brave/components/brave_sync/crypto/crypto_unittest.cc", - "//brave/components/brave_sync/syncer_helper_unittest.cc", - ] - - deps += [ - "//brave/components/brave_sync:testutil", ] } From f7a4340ac14e15d024f448fec105d22f0ba1ad3b Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Thu, 9 Apr 2020 18:05:28 -0700 Subject: [PATCH 12/79] add missing deps for access token fetcher --- components/brave_sync/BUILD.gn | 11 ++++++++++- patches/components-sync-base-BUILD.gn.patch | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 patches/components-sync-base-BUILD.gn.patch diff --git a/components/brave_sync/BUILD.gn b/components/brave_sync/BUILD.gn index 46d83db1732f..988abc5bf8eb 100644 --- a/components/brave_sync/BUILD.gn +++ b/components/brave_sync/BUILD.gn @@ -21,7 +21,9 @@ source_set("prefs") { ] deps = [ + "//base", "//components/prefs", + "//components/pref_registry", ] } @@ -32,6 +34,7 @@ source_set("crypto") { ] deps = [ + "//base", "//brave/vendor/bat-native-tweetnacl:tweetnacl", "//brave/vendor/bip39wally-core-native:bip39wally-core", "//crypto", @@ -69,7 +72,13 @@ source_set("core") { ":features", ":prefs", "//base", - "//crypto", + # Only for google_service_auth_error.h + "//google_apis:google_apis", + "//net:net", + "//net/traffic_annotation", + "//services/network/public/cpp:cpp_base", + "//services/network/public/cpp:cpp", + "//url:url", ] } diff --git a/patches/components-sync-base-BUILD.gn.patch b/patches/components-sync-base-BUILD.gn.patch new file mode 100644 index 000000000000..95c90a50d058 --- /dev/null +++ b/patches/components-sync-base-BUILD.gn.patch @@ -0,0 +1,12 @@ +diff --git a/components/sync/base/BUILD.gn b/components/sync/base/BUILD.gn +index d35449062388b7155c584546ce4a8e98296c138f..7de39ee7b93ebd370cfc4d8d112aa827869b9dae 100644 +--- a/components/sync/base/BUILD.gn ++++ b/components/sync/base/BUILD.gn +@@ -80,6 +80,7 @@ jumbo_static_library("base") { + ] + deps = [ + "//base:i18n", ++ "//brave/components/brave_sync", + "//components/os_crypt", + "//components/pref_registry", + "//components/prefs", From 20d0f96eaf349fe231b17d10de10af259d059462 Mon Sep 17 00:00:00 2001 From: Anthony Tseng Date: Tue, 14 Apr 2020 22:33:22 -0700 Subject: [PATCH 13/79] Sync UI cleanup --- app/brave_generated_resources.grd | 70 +++++- .../brave_sync_page/brave_sync_control.html | 100 +++++++-- .../brave_sync_page/brave_sync_control.js | 203 ++++++------------ .../brave_sync_page/brave_sync_page.html | 10 +- .../brave_sync_page/brave_sync_page.js | 8 +- .../brave_sync_page/brave_sync_subpage.html | 14 +- .../brave_sync_page/brave_sync_subpage.js | 27 +-- browser/ui/webui/brave_webui_source.cc | 75 ------- .../ui/webui/settings/people_handler.cc | 22 +- .../settings_localized_strings_provider.cc | 48 ++++- components/brave_sync/brave_sync_prefs.cc | 2 +- components/brave_sync/brave_sync_prefs.h | 2 +- .../resources/brave_components_strings.grd | 76 ------- ...-ui-webui-settings-people_handler.cc.patch | 27 ++- 14 files changed, 328 insertions(+), 356 deletions(-) diff --git a/app/brave_generated_resources.grd b/app/brave_generated_resources.grd index e195f1e918b6..ab25a23cd0b3 100644 --- a/app/brave_generated_resources.grd +++ b/app/brave_generated_resources.grd @@ -469,8 +469,74 @@ By installing this extension, you are agreeing to the Google Widevine Terms of U Sync - - Access Sync via + + Start using sync + + + Sync Manager + + + Sync Settings + + + Sync Setup + + + To start, you will need Brave installed on all the devices you plan to sync. To chain them together, start a sync chain that you will use to securely link all of your devices together. + + + Start a new Sync Chain + + + I have a Sync Code + + + View Sync Code + + + Phone/Tablet + + + Computer + + + Sync Chain QR Code + + + On your mobile device, navigate to Brave Sync in the Settings panel and click the button + + + “Scan Sync Code”. + + + Use your camera to scan the QR Code below. + + + Sync Chain Code + + + On your target computer, navigate to Brave Sync in settings and click the button + + + “I have a Sync Code”. + + + Enter the sync chain code words shown below. Treat this code like a password. If someone gets ahold of it, they can read and modify your synced data. + + + Enter a sync code + + + Type your supplied sync chain code words into the form below. + + + Add New Device + + + Choose Device Type + + + Choose the type of device you would like to sync to. diff --git a/browser/resources/settings/brave_sync_page/brave_sync_control.html b/browser/resources/settings/brave_sync_page/brave_sync_control.html index e8264234cf14..d19e91c2be88 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_control.html +++ b/browser/resources/settings/brave_sync_page/brave_sync_control.html @@ -24,52 +24,114 @@ } -