diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 24ae33d015af..2206b02cb329 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -49,3 +49,8 @@ components/brave_wallet/ @bbondy @ryanml # Brave Referrals Service components/brave_referrals/browser/brave_referrals_service* @simonhong + +# Brave Sync +components/brave_sync/ @darkdh +components/sync/driver/ @darkdh +chromium_src/components/sync/ @darkdh diff --git a/android/java/org/chromium/chrome/browser/preferences/BravePrefServiceBridge.java b/android/java/org/chromium/chrome/browser/preferences/BravePrefServiceBridge.java index 5b8706860f54..68b38225d2ce 100644 --- a/android/java/org/chromium/chrome/browser/preferences/BravePrefServiceBridge.java +++ b/android/java/org/chromium/chrome/browser/preferences/BravePrefServiceBridge.java @@ -84,26 +84,6 @@ public long getDataSaved(Profile profile) { return BravePrefServiceBridgeJni.get().getDataSaved(profile); } - public String getSyncDeviceId() { - return BravePrefServiceBridgeJni.get().getSyncDeviceId(); - } - - public void setSyncDeviceName(String deviceName) { - BravePrefServiceBridgeJni.get().setSyncDeviceName(deviceName); - } - - public String getSyncDeviceName() { - return BravePrefServiceBridgeJni.get().getSyncDeviceName(); - } - - public void setSyncSeed(String seed) { - BravePrefServiceBridgeJni.get().setSyncSeed(seed); - } - - public String getSyncSeed() { - return BravePrefServiceBridgeJni.get().getSyncSeed(); - } - /** * @param whether SafetyNet check failed. */ @@ -233,14 +213,6 @@ interface Natives { void setOldAdsBlockedCount(Profile profile, long count); void setOldHttpsUpgradesCount(Profile profile, long count); - String getSyncDeviceId(); - - void setSyncDeviceName(String deviceName); - String getSyncDeviceName(); - - void setSyncSeed(String seed); - String getSyncSeed(); - void setSafetynetCheckFailed(boolean value); boolean getSafetynetCheckFailed(); diff --git a/app/brave_command_ids.h b/app/brave_command_ids.h index 8a2ac38c8480..c2449b166c61 100644 --- a/app/brave_command_ids.h +++ b/app/brave_command_ids.h @@ -15,7 +15,6 @@ #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_WALLET 56006 #define IDC_ADD_NEW_PROFILE 56007 #define IDC_OPEN_GUEST_PROFILE 56008 diff --git a/app/brave_generated_resources.grd b/app/brave_generated_resources.grd index e195f1e918b6..74f259cbc266 100644 --- a/app/brave_generated_resources.grd +++ b/app/brave_generated_resources.grd @@ -469,8 +469,126 @@ By installing this extension, you are agreeing to the Google Widevine Terms of U Sync - - Access Sync via + + Start using sync + + + Sync Setup + + + To start, you will need Brave installed on all the devices you plan to sync. Then, securely link them together with a sync code. + + + Manage your synced devices + + + Sync Manager + + + Sync Settings + + + Manage what information you would like to sync between devices. These settings only affect this device. + + + Device List + + + The device list below includes all devices in your sync chain. Each device can be managed from any other device. + + + Device Name + + + $1my-computer-1 (This Device) + + + Last Active + + + Sync Setup + + + Word count: $124 + + + Copied! + + + 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. + + + View QR Code + + + Enter a sync code + + + Type your supplied sync chain code words into the form below. + + + Add New Device + + + Choose Device Type + + + Which type of device would you like to sync to? + + + Invalid sync code, please check and try again. + + + Leave Sync Chain + + + If you reset Sync, you will have to re-enter a sync code from another device in order to sync with it. Are you sure you want to proceed? + + + + Brave Sync has been upgraded and requires setup + + + Begin Setup diff --git a/app/brave_main_delegate.cc b/app/brave_main_delegate.cc index 41ae221ac40c..05b198ad975e 100644 --- a/app/brave_main_delegate.cc +++ b/app/brave_main_delegate.cc @@ -49,6 +49,20 @@ #include "components/dom_distiller/core/dom_distiller_switches.h" #endif +namespace { +// staging "https://sync-v2.bravesoftware.com/v2" can be overriden by +// switches::kSyncServiceURL manually +#if defined(OFFICIAL_BUILD) +// production +const char kBraveSyncServiceURL[] = "https://sync-v2.brave.com/v2"; +#else +// For local server development "http://localhost:8295/v2 can also be overriden +// by switches::kSyncServiceURL +// dev +const char kBraveSyncServiceURL[] = "https://sync-v2.brave.software/v2"; +#endif +} // namespace + #if !defined(CHROME_MULTIPLE_DLL_BROWSER) base::LazyInstance::DestructorAtExit g_brave_content_renderer_client = LAZY_INSTANCE_INITIALIZER; @@ -158,7 +172,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"); + kBraveSyncServiceURL); // Enabled features. std::unordered_set enabled_features = { 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..36681a44f82a 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", @@ -134,6 +132,7 @@ source_set("browser_process") { "//brave/components/brave_referrals/browser", "//brave/components/brave_shields/browser", "//brave/components/brave_shields/common", + "//brave/components/brave_sync", "//brave/components/brave_wallet/browser/buildflags", "//brave/components/brave_wayback_machine:buildflags", "//brave/components/brave_webtorrent/browser/buildflags", diff --git a/browser/android/preferences/brave_pref_service_bridge.cc b/browser/android/preferences/brave_pref_service_bridge.cc index ed15fd35531a..d212cb1ce75c 100644 --- a/browser/android/preferences/brave_pref_service_bridge.cc +++ b/browser/android/preferences/brave_pref_service_bridge.cc @@ -181,42 +181,6 @@ void JNI_BravePrefServiceBridge_SetOldHttpsUpgradesCount(JNIEnv* env, count + profile->GetPrefs()->GetUint64(kHttpsUpgrades)); } -ScopedJavaLocalRef JNI_BravePrefServiceBridge_GetSyncDeviceId( - JNIEnv* env) { - return ConvertUTF8ToJavaString(env, - GetOriginalProfile()->GetPrefs()->GetString( - brave_sync::prefs::kSyncDeviceId)); -} - -void JNI_BravePrefServiceBridge_SetSyncDeviceName( - JNIEnv* env, - const JavaParamRef& deviceName) { - return GetOriginalProfile()->GetPrefs()->SetString( - brave_sync::prefs::kSyncDeviceName, - ConvertJavaStringToUTF8(env, deviceName)); -} - -ScopedJavaLocalRef JNI_BravePrefServiceBridge_GetSyncDeviceName( - JNIEnv* env) { - return ConvertUTF8ToJavaString(env, - GetOriginalProfile()->GetPrefs()->GetString( - brave_sync::prefs::kSyncDeviceName)); -} - -void JNI_BravePrefServiceBridge_SetSyncSeed( - JNIEnv* env, - const JavaParamRef& seed) { - return GetOriginalProfile()->GetPrefs()->SetString( - brave_sync::prefs::kSyncSeed, ConvertJavaStringToUTF8(env, seed)); -} - -ScopedJavaLocalRef JNI_BravePrefServiceBridge_GetSyncSeed( - JNIEnv* env) { - return ConvertUTF8ToJavaString(env, - GetOriginalProfile()->GetPrefs()->GetString( - brave_sync::prefs::kSyncSeed)); -} - void JNI_BravePrefServiceBridge_SetSafetynetCheckFailed( JNIEnv* env, jboolean value) { 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_browser_main_parts.cc b/browser/brave_browser_main_parts.cc index 6e24a2a9a678..2b1720ed26cc 100644 --- a/browser/brave_browser_main_parts.cc +++ b/browser/brave_browser_main_parts.cc @@ -9,6 +9,7 @@ #include "brave/browser/browsing_data/brave_clear_browsing_data.h" #include "brave/browser/tor/buildflags.h" #include "brave/common/pref_names.h" +#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/brave_sync/features.h" #include "chrome/common/chrome_features.h" #include "components/prefs/pref_service.h" @@ -30,6 +31,7 @@ #if !defined(OS_ANDROID) #include "brave/browser/infobars/brave_confirm_p3a_infobar_delegate.h" #include "brave/browser/infobars/crypto_wallets_infobar_delegate.h" +#include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/infobars/infobar_service.h" #include "content/public/browser/web_contents.h" @@ -39,6 +41,13 @@ #include "chrome/browser/browser_process.h" #endif +#if BUILDFLAG(ENABLE_BRAVE_SYNC) && !defined(OS_ANDROID) +#include "brave/browser/infobars/sync_v2_migrate_infobar_delegate.h" +#include "components/sync/driver/sync_service.h" +#include "components/sync/driver/sync_user_settings.h" +#include "chrome/browser/sync/profile_sync_service_factory.h" +#endif + void BraveBrowserMainParts::PostBrowserStart() { ChromeBrowserMainParts::PostBrowserStart(); @@ -83,6 +92,15 @@ void BraveBrowserMainParts::PostBrowserStart() { if (infobar_service) { BraveConfirmP3AInfoBarDelegate::Create( infobar_service, g_browser_process->local_state()); +#if BUILDFLAG(ENABLE_BRAVE_SYNC) + auto* sync_service = ProfileSyncServiceFactory::IsSyncAllowed(profile()) + ? ProfileSyncServiceFactory::GetForProfile(profile()) + : nullptr; + const bool is_v2_user = sync_service && + sync_service->GetUserSettings()->IsFirstSetupComplete(); + SyncV2MigrateInfoBarDelegate::Create(infobar_service, is_v2_user, + profile(), browser); +#endif // BUILDFLAG(ENABLE_BRAVE_SYNC) } } } diff --git a/browser/brave_browser_process_impl.cc b/browser/brave_browser_process_impl.cc index ae93c08bc1ba..b1077146683f 100644 --- a/browser/brave_browser_process_impl.cc +++ b/browser/brave_browser_process_impl.cc @@ -28,6 +28,8 @@ #include "brave/components/brave_shields/browser/https_everywhere_service.h" #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" +#include "brave/components/brave_sync/buildflags/buildflags.h" +#include "brave/components/brave_sync/network_time_helper.h" #include "brave/components/ntp_background_images/browser/features.h" #include "brave/components/ntp_background_images/browser/ntp_background_images_service.h" #include "brave/components/p3a/buildflags.h" @@ -196,6 +198,11 @@ void BraveBrowserProcessImpl::StartBraveServices() { #endif // Now start the local data files service, which calls all observers. local_data_files_service()->Start(); + +#if BUILDFLAG(ENABLE_BRAVE_SYNC) + brave_sync::NetworkTimeHelper::GetInstance() + ->SetNetworkTimeTracker(g_browser_process->network_time_tracker()); +#endif } brave_shields::AdBlockService* BraveBrowserProcessImpl::ad_block_service() { diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index e33e4c348236..8c47271d6736 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -415,11 +415,11 @@ 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) { + + if (url->host() == chrome::kChromeUISyncHost) { GURL::Replacements replacements; - replacements.SetHostStr(chrome::kChromeUISyncHost); + replacements.SetHostStr(chrome::kChromeUISettingsHost); + replacements.SetPathStr(kBraveSyncPath); *url = url->ReplaceComponents(replacements); return true; } diff --git a/browser/brave_content_browser_client_browsertest.cc b/browser/brave_content_browser_client_browsertest.cc index aa9dc4de21d1..f4543b841e87 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://", @@ -216,10 +210,8 @@ IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, CanLoadAboutHost) { "chrome://chrome-urls/"); } } - -#if BUILDFLAG(ENABLE_BRAVE_SYNC) IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, - RewriteChromeSyncInternals) { + RewriteChromeSync) { std::vector schemes { "brave://", "chrome://", @@ -227,26 +219,22 @@ IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, 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)); + browser()->tab_strip_model()->GetActiveWebContents(); + ui_test_utils::NavigateToURL(browser(), + GURL(scheme + chrome::kChromeUISyncHost)); + ASSERT_TRUE(WaitForLoadStop(contents)); EXPECT_STREQ(base::UTF16ToUTF8(browser()->location_bar_model() - ->GetFormattedFullURL()).c_str(), + ->GetFormattedFullURL()).c_str(), "brave://sync"); EXPECT_STREQ(contents->GetController().GetLastCommittedEntry() - ->GetVirtualURL().spec().c_str(), + ->GetVirtualURL().spec().c_str(), "chrome://sync/"); EXPECT_STREQ(contents->GetController().GetLastCommittedEntry() - ->GetURL().spec().c_str(), - "chrome://sync/"); + ->GetURL().spec().c_str(), + "chrome://settings/braveSync"); } } -#endif IN_PROC_BROWSER_TEST_F(BraveContentBrowserClientTest, RewriteMagnetURLURLBar) { content::WebContents* contents = diff --git a/browser/brave_content_browser_client_unittest.cc b/browser/brave_content_browser_client_unittest.cc index 1921505442f2..e8fb2b78d11c 100644 --- a/browser/brave_content_browser_client_unittest.cc +++ b/browser/brave_content_browser_client_unittest.cc @@ -79,14 +79,14 @@ 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 url("chrome://sync/"); + ASSERT_TRUE( + BraveContentBrowserClient::HandleURLOverrideRewrite(&url, nullptr)); + ASSERT_STREQ(url.spec().c_str(), "chrome://settings/braveSync"); GURL url2("chrome://sync/"); - ASSERT_TRUE(BraveContentBrowserClient::HandleURLOverrideRewrite( - &url2, nullptr)); + ASSERT_TRUE( + BraveContentBrowserClient::HandleURLOverrideRewrite(&url2, nullptr)); } TEST_F(BraveContentBrowserClientTest, ResolvesWelcomePage) { diff --git a/browser/brave_profile_prefs.cc b/browser/brave_profile_prefs.cc index 4d7fd9281bb8..f9286c10e7ce 100644 --- a/browser/brave_profile_prefs.cc +++ b/browser/brave_profile_prefs.cc @@ -101,7 +101,7 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { brave_rewards::prefs::kHideBraveRewardsButton, false); - brave_sync::prefs::Prefs::RegisterProfilePrefs(registry); + brave_sync::Prefs::RegisterProfilePrefs(registry); // TODO(shong): Migrate this to local state also and guard in ENABLE_WIDEVINE. // We don't need to display "don't ask widevine prompt option" in settings @@ -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/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/infobars/BUILD.gn b/browser/infobars/BUILD.gn index 0661ed99ef31..7152bca1e968 100644 --- a/browser/infobars/BUILD.gn +++ b/browser/infobars/BUILD.gn @@ -1,6 +1,7 @@ import("//build/config/features.gni") import("//brave/components/brave_wayback_machine/buildflags/buildflags.gni") import("//brave/components/brave_wallet/browser/buildflags/buildflags.gni") +import("//brave/components/brave_sync/buildflags/buildflags.gni") source_set("infobars") { sources = [ @@ -17,6 +18,7 @@ source_set("infobars") { deps = [ "//base", + "//brave/browser/ui", "//brave/common", "//brave/components/p3a", "//brave/app:brave_generated_resources_grit", @@ -40,4 +42,15 @@ source_set("infobars") { "//brave/components/brave_wayback_machine", ] } + + if (enable_brave_sync) { + sources += [ + "sync_v2_migrate_infobar_delegate.cc", + "sync_v2_migrate_infobar_delegate.h", + ] + + deps += [ + "//brave/components/brave_sync", + ] + } } diff --git a/browser/infobars/sync_v2_migrate_infobar_delegate.cc b/browser/infobars/sync_v2_migrate_infobar_delegate.cc new file mode 100644 index 000000000000..27300913bec3 --- /dev/null +++ b/browser/infobars/sync_v2_migrate_infobar_delegate.cc @@ -0,0 +1,115 @@ +// 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/. + +#include "brave/browser/infobars/sync_v2_migrate_infobar_delegate.h" + +#include +#include + +#include "base/feature_list.h" +#include "brave/browser/ui/brave_pages.h" +#include "brave/common/pref_names.h" +#include "brave/common/url_constants.h" +#include "brave/components/brave_sync/brave_sync_prefs.h" +#include "brave/components/brave_sync/features.h" +#include "brave/grit/brave_generated_resources.h" +#include "chrome/browser/infobars/infobar_service.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/chrome_pages.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/chromium_strings.h" +#include "components/infobars/core/infobar.h" +#include "components/prefs/pref_service.h" +#include "components/strings/grit/components_strings.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/views/vector_icons.h" + +// static +void SyncV2MigrateInfoBarDelegate::Create( + InfoBarService* infobar_service, bool is_v2_user, Profile* profile, + Browser* browser) { + // Show infobar if user had enabled sync v1 (even if they hadn't + // re-enabled it via the flag). + // Don't show infobar if: + // - sync flag is disabled + // - problem with local_state + // - user has setup sync v2 + // - dismissed notification (don't auto-dismiss) + const bool is_flag_enabled = + base::FeatureList::IsEnabled(brave_sync::features::kBraveSync); + if (!is_flag_enabled) { + return; + } + brave_sync::Prefs brave_sync_prefs(profile->GetPrefs()); + const bool was_v1_user = brave_sync_prefs.IsSyncV1Enabled(); + if (!was_v1_user) { + // Not v1 user + return; + } + const bool has_dismissed = brave_sync_prefs.IsSyncMigrateNoticeDismissed(); + if (has_dismissed) { + return; + } + if (is_v2_user) { + // Make sure this doesn't automatically show again if sync is turned off. + // TODO(petemill): Might be better to change a pref in an event handler + // rather than here. + brave_sync_prefs.SetDismissSyncMigrateNotice(true); + return; + } + // Show infobar + infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( + std::unique_ptr( + new SyncV2MigrateInfoBarDelegate(browser, profile)))); +} + +// Start class impl +SyncV2MigrateInfoBarDelegate::SyncV2MigrateInfoBarDelegate(Browser* browser, + Profile* profile) + : ConfirmInfoBarDelegate(), + profile_(profile), + browser_(browser) { +} + +SyncV2MigrateInfoBarDelegate::~SyncV2MigrateInfoBarDelegate() { +} + +infobars::InfoBarDelegate::InfoBarIdentifier +SyncV2MigrateInfoBarDelegate::GetIdentifier() const { + return SYNC_V2_MIGRATE_INFOBAR_DELEGATE; +} + +const gfx::VectorIcon& SyncV2MigrateInfoBarDelegate::GetVectorIcon() const { + return views::kInfoIcon; +} + +bool SyncV2MigrateInfoBarDelegate::ShouldExpire( + const NavigationDetails& details) const { + return false; +} + +void SyncV2MigrateInfoBarDelegate::InfoBarDismissed() { + brave_sync::Prefs brave_sync_prefs(profile_->GetPrefs()); + brave_sync_prefs.SetDismissSyncMigrateNotice(true); +} + +base::string16 SyncV2MigrateInfoBarDelegate::GetMessageText() const { + return l10n_util::GetStringUTF16(IDS_BRAVE_SYNC_V2_MIGRATE_INFOBAR_MESSAGE); +} + +int SyncV2MigrateInfoBarDelegate::GetButtons() const { + return BUTTON_OK; +} + +base::string16 SyncV2MigrateInfoBarDelegate::GetButtonLabel( + InfoBarButton button) const { + return l10n_util::GetStringUTF16(IDS_BRAVE_SYNC_V2_MIGRATE_INFOBAR_COMMAND); +} + +bool SyncV2MigrateInfoBarDelegate::Accept() { + brave::ShowSync(browser_); + return true; +} diff --git a/browser/infobars/sync_v2_migrate_infobar_delegate.h b/browser/infobars/sync_v2_migrate_infobar_delegate.h new file mode 100644 index 000000000000..b6dab364bff5 --- /dev/null +++ b/browser/infobars/sync_v2_migrate_infobar_delegate.h @@ -0,0 +1,49 @@ +// 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/. + +#ifndef BRAVE_BROWSER_INFOBARS_SYNC_V2_MIGRATE_INFOBAR_DELEGATE_H_ +#define BRAVE_BROWSER_INFOBARS_SYNC_V2_MIGRATE_INFOBAR_DELEGATE_H_ + +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "base/strings/string16.h" +#include "components/infobars/core/confirm_infobar_delegate.h" +#include "url/gurl.h" + +class Browser; +class InfoBarService; +class Profile; +class PrefService; + +namespace brave_sync { +class Prefs; +} // namespace brave_sync + +// An infobar that is run with a string, buttons, and a "Learn More" link. +class SyncV2MigrateInfoBarDelegate : public ConfirmInfoBarDelegate { + public: + static void Create(InfoBarService* infobar_service, bool is_v2_user, + Profile* profile, Browser* browser); + + private: + explicit SyncV2MigrateInfoBarDelegate(Browser* browser, Profile* profile); + ~SyncV2MigrateInfoBarDelegate() override; + + infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; + const gfx::VectorIcon& GetVectorIcon() const override; + bool ShouldExpire(const NavigationDetails& details) const override; + void InfoBarDismissed() override; + base::string16 GetMessageText() const override; + int GetButtons() const override; + base::string16 GetButtonLabel(InfoBarButton button) const override; + bool Accept() override; + + Profile* profile_; + Browser* browser_; + + DISALLOW_COPY_AND_ASSIGN(SyncV2MigrateInfoBarDelegate); +}; + +#endif // BRAVE_BROWSER_INFOBARS_SYNC_V2_MIGRATE_INFOBAR_DELEGATE_H_ diff --git a/browser/net/BUILD.gn b/browser/net/BUILD.gn index 6ffc9be77e35..541127fb8f18 100644 --- a/browser/net/BUILD.gn +++ b/browser/net/BUILD.gn @@ -3,15 +3,8 @@ import("//brave/components/brave_referrals/buildflags/buildflags.gni") import("//brave/components/brave_webtorrent/browser/buildflags/buildflags.gni") import("//build/config/features.gni") -declare_args() { - brave_services_key = "" -} - -defines = [] -if (brave_services_key != "") { - # Refer to the keyed API spec for more details about the Brave Services Key - defines += [ "BRAVE_SERVICES_KEY=\"$brave_services_key\"" ] -} +# Refer to the keyed API spec for more details about the Brave Services Key +defines = brave_service_key_defines source_set("net") { configs += [ "//brave/build/geolocation" ] diff --git a/browser/net/brave_system_request_handler.cc b/browser/net/brave_system_request_handler.cc index f2eca0361cd8..7658e729a018 100644 --- a/browser/net/brave_system_request_handler.cc +++ b/browser/net/brave_system_request_handler.cc @@ -13,13 +13,6 @@ #include "services/network/public/cpp/resource_request.h" #include "url/gurl.h" -#if !defined(BRAVE_SERVICES_KEY) -// Refer to the keyed API spec for more details about the Brave Services Key -#define BRAVE_SERVICES_KEY "dummytoken" -#endif - -const char kBraveServicesKeyHeader[] = "BraveServiceKey"; - namespace brave { std::string BraveServicesKeyForTesting() { diff --git a/browser/profiles/BUILD.gn b/browser/profiles/BUILD.gn index 2a52005846f7..1dc115934c25 100644 --- a/browser/profiles/BUILD.gn +++ b/browser/profiles/BUILD.gn @@ -28,6 +28,7 @@ source_set("profiles") { "//brave/common/tor", "//brave/components/brave_ads/browser", "//brave/components/brave_rewards/browser", + "//brave/components/brave_sync:prefs", "//brave/content:browser", "//chrome/common", "//components/gcm_driver:gcm_buildflags", diff --git a/browser/profiles/brave_bookmark_model_loaded_observer.cc b/browser/profiles/brave_bookmark_model_loaded_observer.cc index 2d1bf2eeb919..5e94eee9b2df 100644 --- a/browser/profiles/brave_bookmark_model_loaded_observer.cc +++ b/browser/profiles/brave_bookmark_model_loaded_observer.cc @@ -6,18 +6,11 @@ #include "brave/browser/profiles/brave_bookmark_model_loaded_observer.h" #include "brave/common/pref_names.h" -#include "brave/components/brave_sync/features.h" +#include "brave/components/brave_sync/brave_sync_prefs.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/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 +21,15 @@ 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 + brave_sync::Prefs brave_sync_prefs(profile_->GetPrefs()); + if (!brave_sync_prefs.IsSyncV1MetaInfoCleared()) { + BraveClearSyncV1MetaInfo(model); + brave_sync_prefs.SetSyncV1MetaInfoCleared(true); + } BookmarkModelLoadedObserver::BookmarkModelLoaded(model, ids_reassigned); } diff --git a/browser/profiles/brave_bookmark_model_loaded_observer_browsertest.cc b/browser/profiles/brave_bookmark_model_loaded_observer_browsertest.cc index 81122acef3e4..d17393d128c8 100644 --- a/browser/profiles/brave_bookmark_model_loaded_observer_browsertest.cc +++ b/browser/profiles/brave_bookmark_model_loaded_observer_browsertest.cc @@ -4,6 +4,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "brave/common/pref_names.h" +#include "brave/components/brave_sync/brave_sync_prefs.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -11,10 +12,8 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/prefs/pref_service.h" -using BraveBookmarkModelLoadedObserverBrowserTest = InProcessBrowserTest; - -// This test to mainly testing kOtherBookmarksMigrated, granular testing for -// migration is in BookmarkModelTest::BraveMigrateOtherNodeFolder +// This test to mainly testing whether migration only runs once, +// granular testing for is in BookmarkModelTest namespace { @@ -25,51 +24,100 @@ void CreateOtherBookmarksFolder(bookmarks::BookmarkModel* model) { model->AddFolder(other_node_folder, 0, base::ASCIIToUTF16("A")); } +void CreateBraveSyncV1MetaInfo(bookmarks::BookmarkModel* model) { + const bookmarks::BookmarkNode* node = model->AddURL( + model->bookmark_bar_node(), model->bookmark_bar_node()->children().size(), + base::ASCIIToUTF16("Brave"), GURL("https://brave.com")); + model->SetNodeMetaInfo(node, "object_id", "object_id_value"); +} + } // namespace +class BraveBookmarkModelLoadedObserverBrowserTest + : public InProcessBrowserTest { + public: + void SetUpOnMainThread() override { + profile_ = browser()->profile(); + bookmark_model_ = BookmarkModelFactory::GetForBrowserContext(profile_); + } + + PrefService* prefs() { return profile_->GetPrefs(); } + + bookmarks::BookmarkModel* bookmark_model() { return bookmark_model_; } + + private: + Profile* profile_; + bookmarks::BookmarkModel* bookmark_model_; +}; + IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, PRE_OtherBookmarksMigration) { - Profile* profile = browser()->profile(); - - profile->GetPrefs()->SetBoolean(kOtherBookmarksMigrated, false); + prefs()->SetBoolean(kOtherBookmarksMigrated, false); - bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForBrowserContext(profile); - CreateOtherBookmarksFolder(bookmark_model); + CreateOtherBookmarksFolder(bookmark_model()); } IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, OtherBookmarksMigration) { - Profile* profile = browser()->profile(); - EXPECT_TRUE(profile->GetPrefs()->GetBoolean(kOtherBookmarksMigrated)); + EXPECT_TRUE(prefs()->GetBoolean(kOtherBookmarksMigrated)); - bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForBrowserContext(profile); - - ASSERT_EQ(bookmark_model->other_node()->children().size(), 1u); - ASSERT_EQ(bookmark_model->bookmark_bar_node()->children().size(), 0u); + ASSERT_EQ(bookmark_model()->other_node()->children().size(), 1u); + ASSERT_EQ(bookmark_model()->bookmark_bar_node()->children().size(), 0u); } IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, PRE_NoOtherBookmarksMigration) { - Profile* profile = browser()->profile(); + prefs()->SetBoolean(kOtherBookmarksMigrated, true); - profile->GetPrefs()->SetBoolean(kOtherBookmarksMigrated, true); + CreateOtherBookmarksFolder(bookmark_model()); +} - bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForBrowserContext(profile); +IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, + NoOtherBookmarksMigration) { + EXPECT_TRUE(prefs()->GetBoolean(kOtherBookmarksMigrated)); - CreateOtherBookmarksFolder(bookmark_model); + ASSERT_EQ(bookmark_model()->other_node()->children().size(), 0u); + ASSERT_EQ(bookmark_model()->bookmark_bar_node()->children().size(), 1u); } IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, - NoOtherBookmarksMigration) { - Profile* profile = browser()->profile(); - EXPECT_TRUE(profile->GetPrefs()->GetBoolean(kOtherBookmarksMigrated)); + PRE_ClearSyncV1MetaInfo) { + brave_sync::Prefs brave_sync_prefs(prefs()); + brave_sync_prefs.SetSyncV1MetaInfoCleared(false); + + CreateBraveSyncV1MetaInfo(bookmark_model()); +} - bookmarks::BookmarkModel* bookmark_model = - BookmarkModelFactory::GetForBrowserContext(profile); +IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, + ClearSyncV1MetaInfo) { + brave_sync::Prefs brave_sync_prefs(prefs()); + EXPECT_TRUE(brave_sync_prefs.IsSyncV1MetaInfoCleared()); + + const bookmarks::BookmarkNode* node = + bookmark_model()->bookmark_bar_node()->children()[0].get(); + std::string object_id; + ASSERT_EQ(node->GetMetaInfoMap(), nullptr); + ASSERT_FALSE(node->GetMetaInfo("object_id", &object_id)); + ASSERT_TRUE(object_id.empty()); +} - ASSERT_EQ(bookmark_model->other_node()->children().size(), 0u); - ASSERT_EQ(bookmark_model->bookmark_bar_node()->children().size(), 1u); +IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, + PRE_NoClearSyncV1MetaInfo) { + brave_sync::Prefs brave_sync_prefs(prefs()); + brave_sync_prefs.SetSyncV1MetaInfoCleared(true); + + CreateBraveSyncV1MetaInfo(bookmark_model()); +} + +IN_PROC_BROWSER_TEST_F(BraveBookmarkModelLoadedObserverBrowserTest, + NoClearSyncV1MetaInfo) { + brave_sync::Prefs brave_sync_prefs(prefs()); + EXPECT_TRUE(brave_sync_prefs.IsSyncV1MetaInfoCleared()); + + const bookmarks::BookmarkNode* node = + bookmark_model()->bookmark_bar_node()->children()[0].get(); + std::string object_id; + ASSERT_NE(node->GetMetaInfoMap(), nullptr); + ASSERT_TRUE(node->GetMetaInfo("object_id", &object_id)); + ASSERT_EQ(object_id, "object_id_value"); } diff --git a/browser/resources/settings/brave_icons.html b/browser/resources/settings/brave_icons.html index b41d43db89bf..1eee1195d64b 100644 --- a/browser/resources/settings/brave_icons.html +++ b/browser/resources/settings/brave_icons.html @@ -75,6 +75,9 @@ + + + diff --git a/browser/resources/settings/brave_settings_overrides.js b/browser/resources/settings/brave_settings_overrides.js index b2a6b1c3cec5..f2094bfc193e 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 index bff4ad058a78..8ac2ab9c971b 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.html +++ b/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.html @@ -1,2 +1,2 @@ - + 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 index ae8da540dfbc..7cd3c96e09b3 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.js +++ b/browser/resources/settings/brave_sync_page/brave_sync_browser_proxy.js @@ -1,20 +1,36 @@ -/* 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/. */ +// 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/. - cr.define('settings', function() { - /** @interface */ - class DefaultBraveSyncBrowserProxy {} +// clang-format off +// #import {addSingletonGetter, sendWithPromise} from 'chrome://resources/js/cr.m.js'; +// clang-format on - /** - * @implements {settings.DefaultBraveSyncBrowserProxy} - */ - class DefaultBraveSyncBrowserProxyImpl {} +cr.define('settings', function() { - cr.addSingletonGetter(DefaultBraveSyncBrowserProxyImpl); + class BraveSyncBrowserProxy { + getSyncCode() { + return cr.sendWithPromise('SyncSetupGetSyncCode'); + } + getQRCode(syncCode) { + return cr.sendWithPromise('SyncGetQRCode', syncCode); + } + getDeviceList() { + return cr.sendWithPromise('SyncGetDeviceList'); + } + setSyncCode(syncCode) { + return cr.sendWithPromise('SyncSetupSetSyncCode', syncCode); + } + resetSyncChain() { + return cr.sendWithPromise('SyncSetupReset'); + } + } + cr.addSingletonGetter(BraveSyncBrowserProxy); + + // #cr_define_end return { - DefaultBraveSyncBrowserProxy, - DefaultBraveSyncBrowserProxyImpl + BraveSyncBrowserProxy, }; }); diff --git a/browser/resources/settings/brave_sync_page/brave_sync_code_dialog.html b/browser/resources/settings/brave_sync_page/brave_sync_code_dialog.html new file mode 100644 index 000000000000..4cd68acdda94 --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_code_dialog.html @@ -0,0 +1,300 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/browser/resources/settings/brave_sync_page/brave_sync_code_dialog.js b/browser/resources/settings/brave_sync_page/brave_sync_code_dialog.js new file mode 100644 index 000000000000..c7cf0beb0def --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_code_dialog.js @@ -0,0 +1,110 @@ +// 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/. + + (function() { + + /** + * @fileoverview + * 'settings-sync-page' is the settings page containing sync settings. + */ + Polymer({ + is: 'settings-brave-sync-code-dialog', + + behaviors: [ + I18nBehavior + ], + + properties: { + syncCode: { + type: String, + notify: true + }, + /** + * 'qr' | 'words' | 'choose' | 'input' + */ + codeType: { + type: String, + value: 'choose', + notify: true + }, + isInvalidSyncCode: { + type: Boolean, + value: false, + notify: true + }, + syncCodeWordCount_: { + type: Number, + computed: 'computeSyncCodeWordCount_(syncCode)' + }, + hasCopiedSyncCode_: { + type: Boolean, + value: false + }, + }, + + observers: [ + 'updateSyncCodeValidity_(syncCode)', + 'getQRCode_(syncCode, codeType)', + ], + + /** @private {?settings.BraveSyncBrowserProxy} */ + syncBrowserProxy_: null, + + created: function() { + this.syncBrowserProxy_ = settings.BraveSyncBrowserProxy.getInstance(); + }, + + updateSyncCodeValidity_: function() { + this.isInvalidSyncCode = false + }, + + computeSyncCodeWordCount_: function() { + if (!this.syncCode) { + return 0 + } + return this.syncCode.trim().split(' ').length + }, + + isCodeType: function(askingType) { + return (this.codeType === askingType) + }, + + handleClose_: function() { + this.codeType = null + }, + + handleChooseMobile_: function() { + this.codeType = 'qr' + }, + + handleChooseComputer_: function() { + this.codeType = 'words' + }, + + handleSyncCodeCopy_: function() { + window.clearTimeout(this.hasCopiedSyncCodeTimer_) + navigator.clipboard.writeText(this.syncCode) + this.hasCopiedSyncCode_ = true + this.hasCopiedSyncCodeTimer_ = window.setTimeout(() => { + this.hasCopiedSyncCode_ = false + }, 4000) + }, + + handleDone_: function() { + this.fire('done') + }, + + getQRCode_: async function() { + if (!this.syncCode || this.codeType !== 'qr') { + return + } + const data = await this.syncBrowserProxy_.getQRCode(this.syncCode) + this.$$('#qrCode').innerText = data + // TODO(petemill): generate a canvas / image + }, + + }); + + })(); diff --git a/browser/resources/settings/brave_sync_page/brave_sync_configure.html b/browser/resources/settings/brave_sync_page/brave_sync_configure.html new file mode 100644 index 000000000000..132a1bf786b8 --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_configure.html @@ -0,0 +1,151 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/browser/resources/settings/brave_sync_page/brave_sync_configure.js b/browser/resources/settings/brave_sync_page/brave_sync_configure.js new file mode 100644 index 000000000000..3c0edd59600f --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_configure.js @@ -0,0 +1,97 @@ +// 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/. + +/** + * @fileoverview + * 'settings-brave-sync-configure' is the set of controls which fetches, displays + * and updates the sync configuration. + */ +Polymer({ + is: 'settings-brave-sync-configure', + + behaviors: [ + I18nBehavior, + WebUIListenerBehavior, + ], + + properties: { + /** + * The current sync status, supplied by parent element. + * @type {!settings.SyncStatus} + */ + syncStatus: Object, + /** + * Configured sync code + */ + syncCode: { + type: String, + notify: true + }, + /** + * List of devices in sync chain + * @private + */ + deviceList_: Array, + /** + * Sync code dialog type. Can only have 1 at a time, so use a single property. + * 'qr' | 'words' | 'input' | 'choose' | null + * @private + */ + syncCodeDialogType_: String, + }, + + /** @private {?settings.SyncBrowserProxy} */ + browserProxy_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.BraveSyncBrowserProxy.getInstance(); + }, + + attached: async function() { + const [syncCode, deviceList] = await Promise.all([ + this.browserProxy_.getSyncCode(), + this.browserProxy_.getDeviceList() + ]) + this.syncCode = syncCode + this.addWebUIListener('device-info-changed', this.handleDeviceInfo_.bind(this)) + this.handleDeviceInfo_(deviceList) + }, + + handleDeviceInfo_: function(deviceList) { + console.log('got device list', deviceList) + this.deviceList_ = deviceList + }, + + getDeviceDisplayDate: function(device) { + const displayDate = new Date(0) + displayDate.setUTCSeconds(device.lastUpdatedTimestamp) + return displayDate.toDateString() + }, + + onViewSyncCode_: function() { + this.syncCodeDialogType_ = 'words' + }, + + onAddDevice_: function() { + this.syncCodeDialogType_ = 'choose' + }, + + onSyncCodeDialogDone_: function() { + this.syncCodeDialogType_ = null + }, + + onResetSyncChain_: async function() { + // TODO(petemill): translate message + const messageText = this.i18n('braveSyncResetConfirmation') + const shouldReset = confirm(messageText) + if (!shouldReset) { + return + } + await this.browserProxy_.resetSyncChain(); + const router = settings.Router.getInstance(); + router.navigateTo(router.getRoutes().BRAVE_SYNC); + } +}); 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..1bb1697ec6e7 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_page.html +++ b/browser/resources/settings/brave_sync_page/brave_sync_page.html @@ -1,20 +1,41 @@ - - + + + + + + + + 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..3c14c6327c6f 100644 --- a/browser/resources/settings/brave_sync_page/brave_sync_page.js +++ b/browser/resources/settings/brave_sync_page/brave_sync_page.js @@ -1,29 +1,96 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* 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/. */ - (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: { + /** + * The current sync status, supplied by SyncBrowserProxy. + * @type {?settings.SyncStatus} + */ + syncStatus_: Object, + syncLabel_: { + type: String, + computed: 'computeSyncLabel_(syncStatus_.firstSetupInProgress)' + }, + }, - /** @private {?settings.DefaultBraveSyncBrowserProxy} */ - browserProxy_: null, + /** @private {?settings.SyncBrowserProxy} */ + browserProxy_: null, + /** @private */ + braveBrowserProxy_: null, - /** @override */ - created: function() { - this.browserProxy_ = settings.DefaultBraveSyncBrowserProxyImpl.getInstance(); - }, + /** @override */ + created: function() { + this.browserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); + this.braveBrowserProxy_ = settings.BraveSyncBrowserProxy.getInstance(); + }, - /** @override */ - ready: function() { - }, - }); - })(); + /** @private */ + computeSyncLabel_() { + const isAlreadySetup = this.syncStatus_ !== undefined && + !this.syncStatus_.firstSetupInProgress; + const key = isAlreadySetup ? 'braveSyncManageActionLabel' : 'braveSyncSetupActionLabel'; + return I18nBehavior.i18n(key); + }, + + /** @override */ + attached: function() { + const onSyncStatus = this.handleSyncStatus_.bind(this) + this.browserProxy_.getSyncStatus().then(onSyncStatus); + this.addWebUIListener('sync-status-changed',onSyncStatus); + this.addWebUIListener( + 'sync-prefs-changed', this.handleSyncPrefsChanged_.bind(this)); + }, + + /** @private */ + onSyncTap_: function() { + // Users can go to sync subpage regardless of sync status. + const router = settings.Router.getInstance(); + router.navigateTo(router.getRoutes().BRAVE_SYNC_SETUP); + }, + + /** + * Handler for when the sync state is pushed from the browser. + * @param {?settings.SyncStatus} syncStatus + * @private + */ + handleSyncStatus_: function(syncStatus) { + console.debug('Sync Status Update', syncStatus) + this.syncStatus_ = syncStatus; + }, + + /** + * Handler for when the sync preferences are updated. + * @private + */ + handleSyncPrefsChanged_: async function(syncPrefs) { + // Enforce encryption + if (this.syncStatus_ && !this.syncStatus_.firstSetupInProgress) { + if (!syncPrefs.encryptAllData) { + const syncCode = await this.braveBrowserProxy_.getSyncCode() + syncPrefs.encryptAllData = true; + syncPrefs.setNewPassphrase = true; + syncPrefs.passphrase = syncCode; + await this.browserProxy_.setSyncEncryption(syncPrefs) + } else if (syncPrefs.passphraseRequired) { + const syncCode = await this.braveBrowserProxy_.getSyncCode() + syncPrefs.setNewPassphrase = false; + syncPrefs.passphrase = syncCode; + await this.browserProxy_.setSyncEncryption(syncPrefs) + } + } + }, +}); diff --git a/browser/resources/settings/brave_sync_page/brave_sync_setup.html b/browser/resources/settings/brave_sync_page/brave_sync_setup.html new file mode 100644 index 000000000000..d663567d23ea --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_setup.html @@ -0,0 +1,80 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/browser/resources/settings/brave_sync_page/brave_sync_setup.js b/browser/resources/settings/brave_sync_page/brave_sync_setup.js new file mode 100644 index 000000000000..71d1495508fd --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_setup.js @@ -0,0 +1,81 @@ +// 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/. + +/** + * @fileoverview + * 'brave-sync-setup' is the UI for starting or joining a sync chain + * settings. + */ +Polymer({ + is: 'settings-brave-sync-setup', + + properties: { + syncCode: { + type: String, + notify: true + }, + /** + * Sync code dialog type. Can only have 1 at a time, so use a single property. + * 'qr' | 'words' | 'input' | 'choose' | null + * @private + */ + syncCodeDialogType_: String, + isSubmittingSyncCode_: { + type: Boolean, + value: false, + }, + isGettingSyncCode_: { + type: Boolean, + value: false, + }, + isInvalidSyncCode_: { + type: Boolean, + value: false, + } + }, + + /** @private {?settings.BraveSyncBrowserProxy} */ + syncBrowserProxy_: null, + + created: function() { + this.syncBrowserProxy_ = settings.BraveSyncBrowserProxy.getInstance(); + }, + + handleStartSyncChain_: async function () { + this.isGettingSyncCode_ = true + const syncCode = await this.syncBrowserProxy_.getSyncCode() + this.isGettingSyncCode_ = false + this.syncCode = syncCode; + this.syncCodeDialogType_ = 'choose' + }, + + handleJoinSyncChain_: function () { + this.syncCode = undefined + this.syncCodeDialogType_ = 'input' + }, + + handleSyncCodeDialogDone_: function (e) { + this.submitSyncCode_() + }, + + submitSyncCode_: async function () { + this.isSubmittingSyncCode_ = true + const syncCodeToSubmit = this.syncCode || '' + let success = false + try { + success = await this.syncBrowserProxy_.setSyncCode(syncCodeToSubmit) + } catch (e) { + console.error("Error setting sync code") + success = false + } + this.isSubmittingSyncCode_ = false + if (!success) { + this.isInvalidSyncCode_ = true + } else { + this.syncCodeDialogType_ = undefined + this.fire('setup-success') + } + }, +}); 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..dde7424d1f35 --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.html @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + 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..8bae0e7ff08d --- /dev/null +++ b/browser/resources/settings/brave_sync_page/brave_sync_subpage.js @@ -0,0 +1,245 @@ +/* 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/. */ + +(function() { + +/** + * @fileoverview + * 'settings-sync-page' is the settings page containing sync settings. + */ +Polymer({ + is: 'settings-brave-sync-subpage', + + behaviors: [ + settings.RouteObserverBehavior, + ], + + properties: { + /** @private */ + pages_: { + type: Object, + value: settings.PageStatus, + readOnly: true, + }, + + /** + * Current page status + * 'configure' | 'setup' | 'spinner' + * @private + */ + pageStatus_: { + type: String, + value: 'configure', + }, + + /** + * The current sync preferences, supplied by SyncBrowserProxy. + * @type {settings.SyncPrefs|undefined} + */ + syncPrefs: { + type: Object, + }, + + /** @type {settings.SyncStatus} */ + syncStatus: { + type: Object, + }, + + /** @private */ + syncDisabledByAdmin_: { + type: Boolean, + value: false, + computed: 'computeSyncDisabledByAdmin_(syncStatus.managed)', + }, + + /** @private */ + syncSectionDisabled_: { + type: Boolean, + value: false, + computed: 'computeSyncSectionDisabled_(' + + 'syncStatus.disabled, ' + + 'syncStatus.hasError, syncStatus.statusAction, ' + + 'syncPrefs.trustedVaultKeysRequired)', + }, + }, + + observers: [ + 'updatePageStatus_(syncStatus.*)' + ], + + /** @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 user completed setup successfully. + * @private {boolean} + */ + setupSuccessful_: false, + + /** @override */ + created: function() { + this.browserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); + }, + + /** @override */ + attached: function() { + const router = settings.Router.getInstance(); + if (router.getCurrentRoute() == router.getRoutes().BRAVE_SYNC_SETUP) { + this.onNavigateToPage_(); + } + }, + + /** @override */ + detached: function() { + const router = settings.Router.getInstance(); + if (router.getRoutes().BRAVE_SYNC_SETUP.contains(router.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; + } + }, + + updatePageStatus_: function () { + const isFirstSetup = this.syncStatus && this.syncStatus.firstSetupInProgress + this.pageStatus_ = isFirstSetup ? 'setup' : 'configure' + }, + + /** + * @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)); + }, + + /** + * @return {boolean} + * @private + */ + computeSyncDisabledByAdmin_() { + return this.syncStatus != undefined && !!this.syncStatus.managed; + }, + + /** @protected */ + currentRouteChanged: function() { + const router = settings.Router.getInstance(); + if (router.getCurrentRoute() == router.getRoutes().BRAVE_SYNC_SETUP) { + this.onNavigateToPage_(); + return; + } + + if (router.getRoutes().BRAVE_SYNC_SETUP.contains(router.getCurrentRoute())) { + return; + } + + this.onNavigateAwayFromPage_(); + }, + + /** + * @param {!settings.PageStatus} expectedPageStatus + * @return {boolean} + * @private + */ + isStatus_: function(expectedPageStatus) { + return expectedPageStatus == this.pageStatus_; + }, + + /** @private */ + onNavigateToPage_: function() { + const router = settings.Router.getInstance(); + assert(router.getCurrentRoute() == router.getRoutes().BRAVE_SYNC_SETUP); + if (this.beforeunloadCallback_) { + return; + } + + // Triggers push of prefs to our handler + 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; + } + + this.browserProxy_.didNavigateAwayFromSyncPage(!this.setupSuccessful_); + + window.removeEventListener('beforeunload', this.beforeunloadCallback_); + this.beforeunloadCallback_ = null; + + if (this.unloadCallback_) { + window.removeEventListener('unload', this.unloadCallback_); + this.unloadCallback_ = null; + } + }, + + /** + * Called when setup is complete and sync code is set + * @private + */ + onSetupSuccess_: function() { + this.setupSuccessful_ = true + // This navigation causes the firstSetupInProgress flag to be marked as false + // via `didNavigateAwayFromSyncPage`. + const router = settings.Router.getInstance(); + if (router.getCurrentRoute() == router.getRoutes().BRAVE_SYNC_SETUP) { + router.navigateTo(router.getRoutes().BRAVE_SYNC); + } + }, +}); + +})(); diff --git a/components/brave_sync/ui/components/images/sync_computer.svg b/browser/resources/settings/brave_sync_page/device_computer.svg similarity index 100% rename from components/brave_sync/ui/components/images/sync_computer.svg rename to browser/resources/settings/brave_sync_page/device_computer.svg diff --git a/components/brave_sync/ui/components/images/sync_devices.svg b/browser/resources/settings/brave_sync_page/device_mobile.svg similarity index 100% rename from components/brave_sync/ui/components/images/sync_devices.svg rename to browser/resources/settings/brave_sync_page/device_mobile.svg diff --git a/components/brave_sync/ui/components/images/start_icon.svg b/browser/resources/settings/brave_sync_page/start_icon.svg similarity index 100% rename from components/brave_sync/ui/components/images/start_icon.svg rename to browser/resources/settings/brave_sync_page/start_icon.svg diff --git a/browser/resources/settings/settings_resources.grd b/browser/resources/settings/settings_resources.grd index 14cf2862c82c..9aea96177f9c 100644 --- a/browser/resources/settings/settings_resources.grd +++ b/browser/resources/settings/settings_resources.grd @@ -43,10 +43,21 @@ - + + + + + + + + + + + + diff --git a/browser/ui/BUILD.gn b/browser/ui/BUILD.gn index 45cbeb701afb..da09c004b7a5 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", @@ -94,6 +86,8 @@ source_set("ui") { "webui/settings/brave_import_data_handler.h", "webui/settings/brave_privacy_handler.cc", "webui/settings/brave_privacy_handler.h", + "webui/settings/brave_sync_handler.cc", + "webui/settings/brave_sync_handler.h", "webui/settings/default_brave_shields_handler.cc", "webui/settings/default_brave_shields_handler.h", ] @@ -204,7 +198,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 +232,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" ] @@ -260,6 +244,8 @@ source_set("ui") { deps += [ "//brave/app:brave_generated_resources_grit", "//brave/browser:version_info", + "//brave/components/brave_sync", + "//components/sync_device_info", "//third_party/blink/public/common", ] } 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..648b40b3ecf0 100644 --- a/browser/ui/brave_pages.cc +++ b/browser/ui/brave_pages.cc @@ -8,7 +8,9 @@ #include "brave/browser/webcompat_reporter/webcompat_reporter_dialog.h" #include "brave/common/webui_url_constants.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/singleton_tabs.h" +#include "chrome/common/webui_url_constants.h" #include "url/gurl.h" namespace brave { @@ -25,6 +27,13 @@ void ShowBraveAdblock(Browser* browser) { GetSingletonTabNavigateParams(browser, GURL(kBraveUIAdblockURL))); } +void ShowSync(Browser* browser) { + auto url = chrome::GetSettingsUrl(chrome::kSyncSetupSubPage); + ShowSingletonTabOverwritingNTP( + browser, + GetSingletonTabNavigateParams(browser, url)); +} + void ShowWebcompatReporter(Browser* browser) { content::WebContents* web_contents = browser->tab_strip_model()->GetActiveWebContents(); @@ -34,12 +43,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..854fb187bbd2 100644 --- a/browser/ui/brave_pages.h +++ b/browser/ui/brave_pages.h @@ -13,9 +13,9 @@ 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); +void ShowSync(Browser* browser); } // namespace brave 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_settings_ui.cc b/browser/ui/webui/brave_settings_ui.cc index 3aebf56f51e9..56935a2ab85e 100644 --- a/browser/ui/webui/brave_settings_ui.cc +++ b/browser/ui/webui/brave_settings_ui.cc @@ -17,6 +17,7 @@ #include "brave/browser/ui/webui/settings/brave_appearance_handler.h" #include "brave/browser/ui/webui/settings/brave_default_extensions_handler.h" #include "brave/browser/ui/webui/settings/brave_privacy_handler.h" +#include "brave/browser/ui/webui/settings/brave_sync_handler.h" #include "brave/browser/ui/webui/settings/default_brave_shields_handler.h" #include "brave/browser/version_info.h" #include "brave/components/brave_sync/buildflags/buildflags.h" @@ -44,6 +45,7 @@ BraveSettingsUI::BraveSettingsUI(content::WebUI* web_ui, web_ui->AddMessageHandler(std::make_unique()); web_ui->AddMessageHandler(std::make_unique()); web_ui->AddMessageHandler(std::make_unique()); + web_ui->AddMessageHandler(std::make_unique()); #if BUILDFLAG(ENABLE_SPARKLE) // Use sparkle's relaunch api for browser relaunch on update. web_ui->AddMessageHandler(std::make_unique()); 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/brave_webui_source.cc b/browser/ui/webui/brave_webui_source.cc index 51899d6277e3..aff5d8cb5f2b 100644 --- a/browser/ui/webui/brave_webui_source.cc +++ b/browser/ui/webui/brave_webui_source.cc @@ -697,81 +697,6 @@ void CustomizeWebUIHTMLSource(const std::string &name, { "tapNetworkLink", IDS_BRAVE_UI_TAP_NETWORK_LINK }, { "tapNetworkDisclaimer", IDS_BRAVE_UI_TAP_NETWORK_DISCLAIMER }, } - }, { - std::string("sync"), { - // Shared strings - { "remove", IDS_BRAVE_SYNC_SHARED_REMOVE_PARTIAL }, - { "copied", IDS_BRAVE_SYNC_SHARED_COPIED_TEXT }, - { "wordCount", IDS_BRAVE_SYNC_SHARED_WORD_COUNT_TEXT }, - { "ok", IDS_BRAVE_SYNC_SHARED_OK_BUTTON }, - { "cancel", IDS_BRAVE_SYNC_SHARED_CANCEL_BUTTON }, - { "cancelDeviceSyncing", IDS_BRAVE_SYNC_SHARED_CANCEL_SYNCING_TITLE }, - { "cancelDeviceSyncingButton", IDS_BRAVE_SYNC_SHARED_CANCEL_SYNCING_BUTTON }, // NOLINT - { "thisSyncChain", IDS_BRAVE_SYNC_SHARED_FROM_THIS_CHAIN_PARTIAL }, - { "lookingForDevice", IDS_BRAVE_SYNC_SCAN_CODE_LOOKING_FOR_DEVICE_BUTTON }, // NOLINT - { "viewSyncCode", IDS_BRAVE_SYNC_ENABLED_VIEW_CODE_BUTTON }, - // Enabled Content - { "braveSync", IDS_BRAVE_SYNC_ENABLED_BRAVE_TITLE }, - { "syncChainDevices", IDS_BRAVE_SYNC_ENABLED_DEVICES_CHAIN_TITLE }, - { "deviceName", IDS_BRAVE_SYNC_ENABLED_TABLE_DEVICE_NAME_TITLE }, - { "thisDevice", IDS_BRAVE_SYNC_ENABLED_TABLE_THIS_DEVICE_TEXT }, - { "addedOn", IDS_BRAVE_SYNC_ENABLED_TABLE_ADDED_ON_TITLE }, - { "addDevice", IDS_BRAVE_SYNC_ENABLED_ADD_DEVICE_BUTTON }, - { "settingsTitle", IDS_BRAVE_SYNC_ENABLED_SETTINGS_TITLE }, - { "settingsDescription", IDS_BRAVE_SYNC_ENABLED_SETTINGS_DESCRIPTION }, - { "settings", IDS_BRAVE_SYNC_ENABLED_TABLE_SETTINGS }, - { "bookmarks", IDS_BRAVE_SYNC_ENABLED_BOOKMARKS_LABEL }, - { "savedSiteSettings", IDS_BRAVE_SYNC_ENABLED_SITE_SETTINGS_LABEL }, - { "browsingHistory", IDS_BRAVE_SYNC_ENABLED_HISTORY_LABEL }, - { "leaveSyncChain", IDS_BRAVE_SYNC_ENABLED_LEAVE_CHAIN_BUTTON }, - // Disabled Content - { "syncTitle", IDS_BRAVE_SYNC_DISABLED_DESCRIPTION }, - { "syncDescription", IDS_BRAVE_SYNC_DISABLED_NEW_CHAIN_DESCRIPTION }, - { "startSyncChain", IDS_BRAVE_SYNC_DISABLED_START_NEW_CHAIN_BUTTON }, - { "enterSyncChainCode", IDS_BRAVE_SYNC_DISABLED_ENTER_CODE_BUTTON }, - // [modal] Enter Sync Code - { "enterSyncCode", IDS_BRAVE_SYNC_ENTER_CODE_TITLE }, - { "enterSyncCodeDescription", IDS_BRAVE_SYNC_ENTER_CODE_DESCRIPTION }, - { "confirmCode", IDS_BRAVE_SYNC_ENTER_CODE_CONFIRM_CODE_BUTTON }, - // [modal] Remove Main Device - { "thisDeviceRemovalDescription", IDS_BRAVE_SYNC_REMOVE_THIS_DEVICE_DESCRIPTION }, // NOLINT - { "joinSyncChain", IDS_BRAVE_SYNC_REMOVE_THIS_DEVICE_JOIN_CHAIN_INSTRUCTIONS }, // NOLINT - // [modal] Remove Other Device - { "otherDeviceRemovalDescription", IDS_BRAVE_SYNC_REMOVE_OTHER_DEVICE_DESCRIPTION }, // NOLINT - // [modal] Reset Sync - { "warning", IDS_BRAVE_SYNC_RESET_WARNING_TITLE }, - { "removing", IDS_BRAVE_SYNC_RESET_REMOVING_PARTIAL }, - { "deleteSyncChain", IDS_BRAVE_SYNC_RESET_DELETE_CHAIN_PARTIAL }, - { "deleteSyncDescription", IDS_BRAVE_SYNC_RESET_REMOVAL_INSTRUCTIONS }, - { "startSyncChainHowTo", IDS_BRAVE_SYNC_RESET_START_NEW_INSTRUCTIONS }, - { "areYouSure", IDS_BRAVE_SYNC_RESET_ARE_YOU_SURE_TITLE }, - // [modal] Scan Code - { "scanThisCode", IDS_BRAVE_SYNC_SCAN_CODE_TITLE }, - { "scanThisCodeHowToPartial1", IDS_BRAVE_SYNC_SCAN_CODE_DESCRIPTION_PARTIAL_1 }, // NOLINT - { "scanThisCodeHowToPartial2", IDS_BRAVE_SYNC_SCAN_CODE_DESCRIPTION_PARTIAL_2 }, // NOLINT - { "scanThisCodeHowToPartial3", IDS_BRAVE_SYNC_SCAN_CODE_DESCRIPTION_PARTIAL_3 }, // NOLINT - // [modal] View Code - { "chainCode", IDS_BRAVE_SYNC_VIEW_CODE_TITLE }, - { "chainCodeDescriptionPartial1", IDS_BRAVE_SYNC_VIEW_CODE_DESCRIPTION_PARTIAL_1 }, // NOLINT - { "chainCodeDescriptionPartial2", IDS_BRAVE_SYNC_VIEW_CODE_DESCRIPTION_PARTIAL_2 }, // NOLINT - { "chainCodeDescriptionPartial3", IDS_BRAVE_SYNC_VIEW_CODE_DESCRIPTION_PARTIAL_3 }, // NOLINT - { "useCameraInstead", IDS_BRAVE_SYNC_VIEW_CODE_USE_CAMERA_BUTTON }, - { "qrCode", IDS_BRAVE_SYNC_VIEW_CODE_QR_CODE }, - // [modal] Choose Device Type - { "letsSync", IDS_BRAVE_SYNC_CHOOSE_DEVICE_TITLE }, - { "chooseDeviceType", IDS_BRAVE_SYNC_CHOOSE_DEVICE_DESCRIPTION }, - { "phoneTablet", IDS_BRAVE_SYNC_CHOOSE_DEVICE_MOBILE_TITLE }, - { "computer", IDS_BRAVE_SYNC_CHOOSE_DEVICE_COMPUTER_TITLE }, - // errors - { "errorWrongCodeTitle", IDS_BRAVE_SYNC_ERROR_WRONG_CODE_TITLE }, - { "errorWrongCodeDescription", IDS_BRAVE_SYNC_ERROR_WRONG_CODE_DESCRIPTION }, // NOLINT - { "errorMissingDeviceNameTitle", IDS_BRAVE_SYNC_ERROR_MISSING_DEVICE_NAME_TITLE }, // NOLINT - { "errorMissingCodeTitle", IDS_BRAVE_SYNC_ERROR_MISSING_SYNC_CODE_TITLE }, // NOLINT - { "errorSyncInitFailedTitle", IDS_BRAVE_SYNC_ERROR_INIT_FAILED_TITLE }, - { "errorSyncInitFailedDescription", IDS_BRAVE_SYNC_ERROR_INIT_FAILED_DESCRIPTION }, // NOLINT - { "errorSyncRequiresCorrectTimeTitle", IDS_BRAVE_SYNC_REQUIRES_CORRECT_TIME_TITLE }, // NOLINT - { "errorSyncRequiresCorrectTimeDescription", IDS_BRAVE_SYNC_REQUIRES_CORRECT_TIME_DESCRIPTION }, // NOLINT - } }, { std::string("adblock"), { { "additionalFiltersTitle", IDS_ADBLOCK_ADDITIONAL_FILTERS_TITLE }, diff --git a/browser/ui/webui/settings/brave_sync_handler.cc b/browser/ui/webui/settings/brave_sync_handler.cc new file mode 100644 index 000000000000..d2f0593f774e --- /dev/null +++ b/browser/ui/webui/settings/brave_sync_handler.cc @@ -0,0 +1,217 @@ +// 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/. + +#include "brave/browser/ui/webui/settings/brave_sync_handler.h" + +#include +#include +#include + +#include "base/bind.h" +#include "base/containers/span.h" +#include "base/strings/string_number_conversions.h" +#include "brave/components/brave_sync/brave_sync_prefs.h" +#include "brave/components/brave_sync/crypto/crypto.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/sync/device_info_sync_service_factory.h" +#include "chrome/browser/sync/profile_sync_service_factory.h" +#include "components/sync/driver/sync_service.h" +#include "components/sync/driver/sync_user_settings.h" +#include "components/sync_device_info/device_info_sync_service.h" +#include "components/sync_device_info/device_info_tracker.h" +#include "components/sync_device_info/local_device_info_provider.h" +#include "content/public/browser/web_ui.h" + +namespace { + +std::string StrFromUint8Array(const std::vector& 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; +} + +} // namespace + +BraveSyncHandler::BraveSyncHandler() { } +BraveSyncHandler::~BraveSyncHandler() { } + +void BraveSyncHandler::RegisterMessages() { + profile_ = Profile::FromWebUI(web_ui()); + web_ui()->RegisterMessageCallback( + "SyncGetDeviceList", + base::BindRepeating(&BraveSyncHandler::HandleGetDeviceList, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncSetupSetSyncCode", + base::BindRepeating(&BraveSyncHandler::HandleSetSyncCode, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncSetupGetSyncCode", + base::BindRepeating(&BraveSyncHandler::HandleGetSyncCode, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncGetQRCode", + base::BindRepeating(&BraveSyncHandler::HandleGetQRCode, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "SyncSetupReset", base::BindRepeating(&BraveSyncHandler::HandleReset, + base::Unretained(this))); +} + +void BraveSyncHandler::OnJavascriptAllowed() { + syncer::DeviceInfoTracker* tracker = + DeviceInfoSyncServiceFactory::GetForProfile(profile_) + ->GetDeviceInfoTracker(); + DCHECK(tracker); + if (tracker) + device_info_tracker_observer_.Add(tracker); +} + +void BraveSyncHandler::OnJavascriptDisallowed() { + device_info_tracker_observer_.RemoveAll(); +} + +void BraveSyncHandler::OnDeviceInfoChange() { + if (IsJavascriptAllowed()) + FireWebUIListener("device-info-changed", GetSyncDeviceList()); +} + +void BraveSyncHandler::HandleGetDeviceList(const base::ListValue* args) { + AllowJavascript(); + const auto& list = args->GetList(); + CHECK_EQ(1U, list.size()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + + ResolveJavascriptCallback(*callback_id, GetSyncDeviceList()); +} + +void BraveSyncHandler::HandleGetSyncCode(const base::ListValue* args) { + AllowJavascript(); + + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + + brave_sync::Prefs brave_sync_prefs(profile_->GetPrefs()); + std::string sync_code = brave_sync_prefs.GetSeed(); + 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 BraveSyncHandler::HandleGetQRCode(const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(2U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + const base::Value* sync_code; + CHECK(args->Get(1, &sync_code)); + + std::vector seed; + if (!brave_sync::crypto::PassphraseToBytes32(sync_code->GetString(), &seed)) { + LOG(ERROR) << "invalid sync code"; + ResolveJavascriptCallback(*callback_id, base::Value(false)); + return; + } + + std::string seed_serialized = StrFromUint8Array(seed); + + // TODO(petemill): Use QRCodeGenerator + // const char* input_data_string = sync_code.c_str(); + // auto input_data = base::span( + // reinterpret_cast(input_data_string), + // strlen(input_data_string)); + // // Generate QR code data + // uint8_t qr_data_buf[QRCode::kInputBytes]; + // QRCodeGenerator generator; + // base::span code = + // generator.Generate(input_data); + ResolveJavascriptCallback(*callback_id, base::Value(seed_serialized)); + // ResolveJavascriptCallback(*callback_id, base::Value(false)); +} + +void BraveSyncHandler::HandleSetSyncCode(const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(2U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + const base::Value* sync_code; + CHECK(args->Get(1, &sync_code)); + + if (sync_code->GetString().empty()) { + LOG(ERROR) << "No sync code parameter provided!"; + RejectJavascriptCallback(*callback_id, base::Value(false)); + return; + } + + std::vector seed; + if (!brave_sync::crypto::PassphraseToBytes32(sync_code->GetString(), &seed)) { + LOG(ERROR) << "invalid sync code"; + RejectJavascriptCallback(*callback_id, base::Value(false)); + return; + } + brave_sync::Prefs brave_sync_prefs(profile_->GetPrefs()); + if (!brave_sync_prefs.SetSeed(sync_code->GetString())) { + ResolveJavascriptCallback(*callback_id, base::Value(false)); + return; + } + ResolveJavascriptCallback(*callback_id, base::Value(true)); +} + +void BraveSyncHandler::HandleReset(const base::ListValue* args) { + AllowJavascript(); + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + + auto* sync_service = GetSyncService(); + if (sync_service) { + sync_service->GetUserSettings()->SetSyncRequested(false); + sync_service->StopAndClear(); + } + brave_sync::Prefs brave_sync_prefs(profile_->GetPrefs()); + brave_sync_prefs.Clear(); + + // Sync prefs will be clear in ProfileSyncService::StopImpl + ResolveJavascriptCallback(*callback_id, base::Value()); +} + +syncer::SyncService* BraveSyncHandler::GetSyncService() const { + return ProfileSyncServiceFactory::IsSyncAllowed(profile_) + ? ProfileSyncServiceFactory::GetForProfile(profile_) + : nullptr; +} + +base::Value BraveSyncHandler::GetSyncDeviceList() { + AllowJavascript(); + auto* device_info_service = + DeviceInfoSyncServiceFactory::GetForProfile(profile_); + syncer::DeviceInfoTracker* tracker = + device_info_service->GetDeviceInfoTracker(); + DCHECK(tracker); + const syncer::DeviceInfo* local_device_info = device_info_service + ->GetLocalDeviceInfoProvider()->GetLocalDeviceInfo(); + + base::Value device_list(base::Value::Type::LIST); + + for (const auto& device : tracker->GetAllDeviceInfo()) { + auto device_value = base::Value::FromUniquePtrValue(device->ToValue()); + bool is_current_device = local_device_info + ? local_device_info->guid() == device->guid() + : false; + device_value.SetBoolKey("isCurrentDevice", is_current_device); + device_list.Append(std::move(device_value)); + } + return device_list; +} diff --git a/browser/ui/webui/settings/brave_sync_handler.h b/browser/ui/webui/settings/brave_sync_handler.h new file mode 100644 index 000000000000..922896df1942 --- /dev/null +++ b/browser/ui/webui/settings/brave_sync_handler.h @@ -0,0 +1,53 @@ +// 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/. + +#ifndef BRAVE_BROWSER_UI_WEBUI_SETTINGS_BRAVE_SYNC_HANDLER_H_ +#define BRAVE_BROWSER_UI_WEBUI_SETTINGS_BRAVE_SYNC_HANDLER_H_ + +#include "base/scoped_observer.h" +#include "base/values.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "components/sync_device_info/device_info_tracker.h" + +namespace syncer { +class SyncService; +} +class Profile; + +class BraveSyncHandler : public settings::SettingsPageUIHandler, + public syncer::DeviceInfoTracker::Observer { + public: + BraveSyncHandler(); + ~BraveSyncHandler() override; + + // syncer::DeviceInfoTracker::Observer + void OnDeviceInfoChange() override; + + private: + // SettingsPageUIHandler overrides: + void RegisterMessages() override; + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + // Custom message handlers: + void HandleGetDeviceList(const base::ListValue* args); + void HandleGetSyncCode(const base::ListValue* args); + void HandleSetSyncCode(const base::ListValue* args); + void HandleGetQRCode(const base::ListValue* args); + void HandleReset(const base::ListValue* args); + + base::Value GetSyncDeviceList(); + syncer::SyncService* GetSyncService() const; + + Profile* profile_ = nullptr; + + // Manages observer lifetimes. + ScopedObserver + device_info_tracker_observer_{this}; + + DISALLOW_COPY_AND_ASSIGN(BraveSyncHandler); +}; + +#endif // BRAVE_BROWSER_UI_WEBUI_SETTINGS_BRAVE_SYNC_HANDLER_H_ 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/build/config/brave_build.gni b/build/config/brave_build.gni index 6fec95b80c76..fcb2fc2f721b 100644 --- a/build/config/brave_build.gni +++ b/build/config/brave_build.gni @@ -4,5 +4,6 @@ import("//brave/brave_repack_locales.gni") import("//brave/build/config/compiler.gni") import("//brave/build/features.gni") +import("//brave/components/sync/driver/sources.gni") import("//brave/net/sources.gni") import("//brave/third_party/blink/renderer/includes.gni") diff --git a/build/features.gni b/build/features.gni index a85ec90fa669..e5202e2c48a1 100644 --- a/build/features.gni +++ b/build/features.gni @@ -1,8 +1,17 @@ declare_args() { brave_chromium_build = true brave_branding_path_component = "" + + brave_services_key = "" } if (brave_chromium_build && !is_ios) { brave_branding_path_component = "brave" } + +brave_service_key_defines = [] +if (brave_services_key != "") { + brave_service_key_defines += [ "BRAVE_SERVICES_KEY=\"$brave_services_key\"" ] +} else { + brave_service_key_defines += [ "BRAVE_SERVICES_KEY=\"dummytoken\"" ] +} diff --git a/chromium_src/chrome/browser/about_flags.cc b/chromium_src/chrome/browser/about_flags.cc index f4060d48a334..8e98f10a2e22 100644 --- a/chromium_src/chrome/browser/about_flags.cc +++ b/chromium_src/chrome/browser/about_flags.cc @@ -9,7 +9,7 @@ #include "brave/common/brave_features.h" #include "brave/common/pref_names.h" #include "brave/components/brave_shields/common/features.h" -#include "brave/components/brave_sync/features.h" +#include "brave/components/brave_sync/buildflags/buildflags.h" #include "brave/components/ntp_background_images/browser/features.h" #include "brave/components/speedreader/buildflags.h" #include "chrome/browser/profiles/profile.h" @@ -17,7 +17,6 @@ #include "components/prefs/pref_service.h" using brave_shields::features::kBraveAdblockCosmeticFiltering; -using brave_sync::features::kBraveSync; using ntp_background_images::features::kBraveNTPBrandedWallpaper; using ntp_background_images::features::kBraveNTPBrandedWallpaperDemo; using ntp_background_images::features::kBraveNTPSuperReferralWallpaper; @@ -35,6 +34,18 @@ using ntp_background_images::features::kBraveNTPSuperReferralWallpaper; #define SPEEDREADER_FEATURE_ENTRIES #endif +#if BUILDFLAG(ENABLE_BRAVE_SYNC) +#include "brave/components/brave_sync/features.h" + +#define BRAVE_SYNC_FEATURE_ENTRIES \ + {"brave-sync-v2", \ + flag_descriptions::kBraveSyncName, \ + flag_descriptions::kBraveSyncDescription, kOsDesktop, \ + FEATURE_VALUE_TYPE(brave_sync::features::kBraveSync)}, +#else +#define BRAVE_SYNC_FEATURE_ENTRIES +#endif + #define BRAVE_FEATURE_ENTRIES \ {"use-dev-updater-url", \ flag_descriptions::kUseDevUpdaterUrlName, \ @@ -53,10 +64,7 @@ using ntp_background_images::features::kBraveNTPSuperReferralWallpaper; flag_descriptions::kBraveAdblockCosmeticFilteringDescription, kOsAll, \ FEATURE_VALUE_TYPE(kBraveAdblockCosmeticFiltering)}, \ SPEEDREADER_FEATURE_ENTRIES \ - {"brave-sync", \ - flag_descriptions::kBraveSyncName, \ - flag_descriptions::kBraveSyncDescription, kOsDesktop, \ - FEATURE_VALUE_TYPE(kBraveSync)}, \ + BRAVE_SYNC_FEATURE_ENTRIES \ {"brave-super-referral", \ flag_descriptions::kBraveSuperReferralName, \ flag_descriptions::kBraveSuperReferralDescription, \ 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/flag_descriptions.cc b/chromium_src/chrome/browser/flag_descriptions.cc index ce60f2cc86ed..acf59816882b 100644 --- a/chromium_src/chrome/browser/flag_descriptions.cc +++ b/chromium_src/chrome/browser/flag_descriptions.cc @@ -27,8 +27,10 @@ const char kBraveAdblockCosmeticFilteringDescription[] = const char kBraveSpeedreaderName[] = "Enable SpeedReader"; const char kBraveSpeedreaderDescription[] = "Enables faster loading of simplified article-style web pages."; -const char kBraveSyncName[] = "Enable Brave Sync"; -const char kBraveSyncDescription[] = "Brave Sync is disabled by default"; +const char kBraveSyncName[] = "Enable Brave Sync v2"; +const char kBraveSyncDescription[] = + "Brave Sync v2 integrates with chromium sync engine with Brave specific " + "authentication flow and enforce client side encryption"; const char kBraveSuperReferralName[] = "Enable Brave Super Referral"; const char kBraveSuperReferralDescription[] = "Use custom theme for Brave Super Referral"; diff --git a/chromium_src/chrome/browser/prefs/browser_prefs.cc b/chromium_src/chrome/browser/prefs/browser_prefs.cc index e999301ce056..227e2996dcc9 100644 --- a/chromium_src/chrome/browser/prefs/browser_prefs.cc +++ b/chromium_src/chrome/browser/prefs/browser_prefs.cc @@ -45,8 +45,7 @@ void MigrateObsoleteProfilePrefs(Profile* profile) { // Added 11/2019. MigrateWidevinePrefs(profile); #endif - // Added 11/2019. - MigrateBraveSyncPrefs(profile->GetPrefs()); + brave_sync::MigrateBraveSyncPrefs(profile->GetPrefs()); // Added 12/2019. dark_mode::MigrateBraveDarkModePrefs(profile); 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/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/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/chrome_pages.cc b/chromium_src/chrome/browser/ui/chrome_pages.cc new file mode 100644 index 000000000000..27f1d1cceb39 --- /dev/null +++ b/chromium_src/chrome/browser/ui/chrome_pages.cc @@ -0,0 +1,25 @@ +/* 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/. */ + +// It has caller in the same file +#define BRAVE_GET_SETTINGS_URL \ +GURL GetSettingsUrl_ChromiumImpl(const std::string& sub_page) { +// BRAVE_GET_SETTINGS_URL + +#include "../../../../../chrome/browser/ui/chrome_pages.cc" + +#undef BRAVE_GET_SETTINGS_URL + +#include "brave/common/webui_url_constants.h" + +namespace chrome { + +GURL GetSettingsUrl(const std::string& sub_page) { + if (sub_page == chrome::kSyncSetupSubPage) + return chrome::GetSettingsUrl(kBraveSyncSetupPath); + return GetSettingsUrl_ChromiumImpl(sub_page); +} + +} // namespace chrome 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/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/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..1bcd6c8ace59 --- /dev/null +++ b/chromium_src/chrome/browser/ui/webui/settings/people_handler.cc @@ -0,0 +1,15 @@ +/* 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/. */ + +// IsSetupInProgress isn't accurate in brave sync flow especially for the first +// time setup, we rely on it to display setup dialog +#define BRAVE_GET_SYNC_STATUS_DICTIONARY \ + sync_status->SetBoolean( \ + "firstSetupInProgress", \ + service && !disallowed_by_policy && \ + !service->GetUserSettings()->IsFirstSetupComplete()); + +#include "../../../../../../../chrome/browser/ui/webui/settings/people_handler.cc" +#undef BRAVE_GET_SYNC_STATUS_DICTIONARY diff --git a/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 0cad859ad228..901a12d5bf06 100644 --- a/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chromium_src/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc @@ -145,8 +145,82 @@ void BraveAddCommonStrings(content::WebUIDataSource* html_source, IDS_SETTINGS_WEBRTC_POLICY_DISABLE_NON_PROXIED_UDP}, {"braveSync", IDS_SETTINGS_BRAVE_SYNC_TITLE}, - {"braveSyncLabel", - IDS_SETTINGS_BRAVE_SYNC_LINK_LABEL}, + {"braveSyncSetupActionLabel", + IDS_SETTINGS_BRAVE_SYNC_SETUP_ACTION_LABEL}, + {"braveSyncSetupTitle", + IDS_SETTINGS_BRAVE_SYNC_SETUP_TITLE}, + {"braveSyncSetupSubtitle", + IDS_SETTINGS_BRAVE_SYNC_SETUP_SUBTITLE}, + {"braveSyncManageActionLabel", + IDS_SETTINGS_BRAVE_SYNC_MANAGE_ACTION_LABEL}, + {"braveSyncWordCount", + IDS_SETTINGS_BRAVE_SYNC_WORD_COUNT}, + {"braveSyncCopied", + IDS_SETTINGS_BRAVE_SYNC_COPIED_TEXT}, + {"braveSyncManagerTitle", + IDS_SETTINGS_BRAVE_SYNC_MANAGER_TITLE}, + {"braveSyncSettingsTitle", + IDS_SETTINGS_BRAVE_SYNC_SETTINGS_TITLE}, + {"braveSyncSettingsSubtitle", + IDS_SETTINGS_BRAVE_SYNC_SETTINGS_SUBTITLE}, + {"braveSyncDeviceListTitle", + IDS_SETTINGS_BRAVE_SYNC_DEVICE_LIST_TITLE}, + {"braveSyncDeviceListSubtitle", + IDS_SETTINGS_BRAVE_SYNC_DEVICE_LIST_SUBTITLE}, + {"braveSyncDeviceListNameColumn", + IDS_SETTINGS_BRAVE_SYNC_DEVICE_LIST_NAME_COLUMN}, + {"braveSyncDeviceListNameThisDevice", + IDS_SETTINGS_BRAVE_SYNC_DEVICE_LIST_NAME_THIS_DEVICE}, + {"braveSyncDeviceListLastActiveColumn", + IDS_SETTINGS_BRAVE_SYNC_DEVICE_LIST_LAST_ACTIVE_COLUMN}, + {"braveSyncSetupTitle", + IDS_BRAVE_SYNC_SETUP_TITLE}, + {"braveSyncSetupDesc", + IDS_BRAVE_SYNC_SETUP_DESCRIPTION}, + {"braveSyncStartNewChain", + IDS_BRAVE_SYNC_START_NEW_CHAIN_BUTTON}, + {"braveSyncEnterCode", + IDS_BRAVE_SYNC_ENTER_CODE_BUTTON}, + {"braveSyncChooseDeviceMobileTitle", + IDS_BRAVE_SYNC_CHOOSE_DEVICE_MOBILE_TITLE}, + {"braveSyncChooseDeviceComputerTitle", + IDS_BRAVE_SYNC_CHOOSE_DEVICE_COMPUTER_TITLE}, + {"braveSyncScanCodeTitle", + IDS_BRAVE_SYNC_SCAN_CODE_TITLE}, + {"braveSyncScanCodeDesc1", + IDS_BRAVE_SYNC_SCAN_CODE_DESCRIPTION_PARTIAL_1}, + {"braveSyncScanCodeDesc2", + IDS_BRAVE_SYNC_SCAN_CODE_DESCRIPTION_PARTIAL_2}, + {"braveSyncScanCodeDesc3", + IDS_BRAVE_SYNC_SCAN_CODE_DESCRIPTION_PARTIAL_3}, + {"braveSyncViewCodeTitle", + IDS_BRAVE_SYNC_VIEW_CODE_TITLE}, + {"braveSyncViewCodeDesc1", + IDS_BRAVE_SYNC_VIEW_CODE_DESCRIPTION_PARTIAL_1}, + {"braveSyncViewCodeDesc2", + IDS_BRAVE_SYNC_VIEW_CODE_DESCRIPTION_PARTIAL_2}, + {"braveSyncViewCodeDesc3", + IDS_BRAVE_SYNC_VIEW_CODE_DESCRIPTION_PARTIAL_3}, + {"braveSyncViewCodeQRCodeButton", + IDS_BRAVE_SYNC_VIEW_CODE_QR_CODE_BUTTON}, + {"braveSyncEnterCodeTitle", + IDS_BRAVE_SYNC_ENTER_CODE_TITLE}, + {"braveSyncEnterCodeDesc", + IDS_BRAVE_SYNC_ENTER_CODE_DESCRIPTION}, + {"braveSyncViewCodeButton", + IDS_BRAVE_SYNC_VIEW_CODE_BUTTON}, + {"braveSyncAddDevice", + IDS_BRAVE_SYNC_ADD_DEVICE_BUTTON}, + {"braveSyncChooseDeviceTitle", + IDS_BRAVE_SYNC_CHOOSE_DEVICE_TITLE}, + {"braveSyncChooseDeviceDesc", + IDS_BRAVE_SYNC_CHOOSE_DEVICE_DESCRIPTION}, + {"braveSyncInvalidSyncCodeTitle", + IDS_BRAVE_SYNC_INVALID_SYNC_CODE_TITLE}, + {"braveSyncResetButton", + IDS_BRAVE_SYNC_RESET_BUTTON}, + {"braveSyncResetConfirmation", + IDS_BRAVE_SYNC_RESET_CONFIRMATION}, {"braveHelpTips", IDS_SETTINGS_HELP_TIPS}, {"braveHelpTipsWaybackMachineLabel", 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 diff --git a/chromium_src/components/bookmarks/browser/bookmark_model.cc b/chromium_src/components/bookmarks/browser/bookmark_model.cc index 6b946ed15c49..d6f360ef0fad 100644 --- a/chromium_src/components/bookmarks/browser/bookmark_model.cc +++ b/chromium_src/components/bookmarks/browser/bookmark_model.cc @@ -5,6 +5,8 @@ #include "../../../../../components/bookmarks/browser/bookmark_model.cc" +#include "ui/base/models/tree_node_iterator.h" + namespace bookmarks { // Move bookmarks under "Other Bookmarks" folder from @@ -15,11 +17,11 @@ void BraveMigrateOtherNodeFolder(BookmarkModel* model) { // Model must be loaded at this point if (!model->bookmark_bar_node()->children().size()) return; - const bookmarks::BookmarkNode* possible_other_node_folder = - model->bookmark_bar_node()->children().back().get(); + const BookmarkNode* possible_other_node_folder = + model->bookmark_bar_node()->children().back().get(); if (possible_other_node_folder->is_folder() && (possible_other_node_folder->GetTitledUrlNodeTitle() == - model->other_node()->GetTitledUrlNodeTitle())) { + model->other_node()->GetTitledUrlNodeTitle())) { size_t children_size = possible_other_node_folder->children().size(); for (size_t i = 0; i < children_size; ++i) { model->Move(possible_other_node_folder->children().front().get(), @@ -29,4 +31,35 @@ void BraveMigrateOtherNodeFolder(BookmarkModel* model) { } } +void BraveClearSyncV1MetaInfo(BookmarkModel* model) { + CHECK(model); + CHECK(model->loaded()); + model->BeginExtensiveChanges(); + ui::TreeNodeIterator iterator(model->root_node()); + while (iterator.has_next()) { + const BookmarkNode* node = iterator.Next(); + // Permanent node cannot trigger BookmarkModelObserver and we stored meta + // info in it + if (model->is_permanent_node(node)) { + const_cast(node)->SetMetaInfoMap( + BookmarkNode::MetaInfoMap()); + } + + model->DeleteNodeMetaInfo(node, "object_id"); + model->DeleteNodeMetaInfo(node, "order"); + model->DeleteNodeMetaInfo(node, "parent_object_id"); + model->DeleteNodeMetaInfo(node, "position_in_parent"); + model->DeleteNodeMetaInfo(node, "sync_timestamp"); + model->DeleteNodeMetaInfo(node, "version"); + + // These might exist if user uses v1 since the very beginning when we + // integrates with chromium sync + model->DeleteNodeMetaInfo(node, "originator_cache_guid"); + model->DeleteNodeMetaInfo(node, "originator_client_item_id"); + model->DeleteNodeMetaInfo(node, "mtime"); + model->DeleteNodeMetaInfo(node, "ctime"); + } + model->EndExtensiveChanges(); +} + } // namespace bookmarks diff --git a/chromium_src/components/bookmarks/browser/bookmark_model.h b/chromium_src/components/bookmarks/browser/bookmark_model.h index 0e927ae602cb..0084520ba030 100644 --- a/chromium_src/components/bookmarks/browser/bookmark_model.h +++ b/chromium_src/components/bookmarks/browser/bookmark_model.h @@ -16,6 +16,7 @@ class BraveSyncServiceTestDelayedLoadModel; namespace bookmarks { void BraveMigrateOtherNodeFolder(BookmarkModel* model); +void BraveClearSyncV1MetaInfo(BookmarkModel* model); } // namespace bookmarks #endif // BRAVE_CHROMIUM_SRC_COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_MODEL_H_ diff --git a/chromium_src/components/bookmarks/browser/bookmark_model_unittest.cc b/chromium_src/components/bookmarks/browser/bookmark_model_unittest.cc index afce42c2569a..f3a3a774c519 100644 --- a/chromium_src/components/bookmarks/browser/bookmark_model_unittest.cc +++ b/chromium_src/components/bookmarks/browser/bookmark_model_unittest.cc @@ -56,8 +56,8 @@ TEST_F(BookmarkModelTest, BraveMigrateOtherNodeFolderNotExist) { BraveMigrateOtherNodeFolder(model_.get()); ASSERT_EQ(model_->other_node()->children().size(), 0u); - const BookmarkNode* folder = - model_->AddFolder(model_->bookmark_bar_node(), 0, ASCIIToUTF16("Other B")); + const BookmarkNode* folder = model_->AddFolder(model_->bookmark_bar_node(), 0, + ASCIIToUTF16("Other B")); model_->AddURL(folder, 0, ASCIIToUTF16("B1"), GURL("https://B1.com")); BraveMigrateOtherNodeFolder(model_.get()); ASSERT_EQ(model_->bookmark_bar_node()->children().size(), 1u); @@ -71,4 +71,65 @@ TEST_F(BookmarkModelTest, BraveMigrateOtherNodeFolderNotExist) { ASSERT_EQ(model_->other_node()->children().size(), 0u); } +TEST_F(BookmarkModelTest, BraveClearSyncV1MetaInfo_PermanentNodes) { + AsMutable(model_->bookmark_bar_node())->SetMetaInfo("order", "1.0.1"); + AsMutable(model_->other_node())->SetMetaInfo("order", "1.0.2"); + + BraveClearSyncV1MetaInfo(model_.get()); + + ASSERT_EQ(model_->bookmark_bar_node()->GetMetaInfoMap(), nullptr); + ASSERT_EQ(model_->other_node()->GetMetaInfoMap(), nullptr); +} + +TEST_F(BookmarkModelTest, BraveClearSyncV1MetaInfo) { + BookmarkNode::MetaInfoMap meta_info_map; + meta_info_map["object_id"] = "object_id_value"; + meta_info_map["order"] = "order_value"; + meta_info_map["parent_object_id"] = "parent_object_id_value"; + meta_info_map["position_in_parent"] = "position_in_parent_value"; + meta_info_map["sync_timestamp"] = "sync_timestamp_value"; + meta_info_map["version"] = "version_value"; + meta_info_map["originator_cache_guid"] = "originator_cache_guid_value"; + meta_info_map["originator_client_item_id"] = + "originator_client_item_id_value"; + meta_info_map["mtime"] = "mtime_value"; + meta_info_map["ctime"] = "ctime_value"; + + // -- Bookmarks + // |-- A + // | |--A1.com + // |-- C1.com (The only node contains non related meta info) + // -- Other Bookmarks + // |-- B + // | |--B1.com + const BookmarkNode* folder_A = model_->AddFolder( + model_->bookmark_bar_node(), 0, ASCIIToUTF16("A"), &meta_info_map); + const BookmarkNode* bookmark_A1 = model_->AddURL( + folder_A, 0, ASCIIToUTF16("A1"), GURL("https://A1.com"), &meta_info_map); + const BookmarkNode* bookmark_C1 = model_->AddURL( + folder_A, 1, ASCIIToUTF16("C1"), GURL("https://C1.com"), &meta_info_map); + model_->SetNodeMetaInfo(bookmark_C1, "brave_meta", "brave_meta_value"); + const BookmarkNode* folder_B = model_->AddFolder( + model_->other_node(), 0, ASCIIToUTF16("B"), &meta_info_map); + const BookmarkNode* bookmark_B1 = model_->AddURL( + folder_A, 0, ASCIIToUTF16("B1"), GURL("https://B1.com"), &meta_info_map); + ASSERT_NE(folder_A->GetMetaInfoMap(), nullptr); + ASSERT_NE(bookmark_A1->GetMetaInfoMap(), nullptr); + ASSERT_NE(bookmark_C1->GetMetaInfoMap(), nullptr); + ASSERT_NE(folder_B->GetMetaInfoMap(), nullptr); + ASSERT_NE(bookmark_B1->GetMetaInfoMap(), nullptr); + + BraveClearSyncV1MetaInfo(model_.get()); + + ASSERT_EQ(folder_A->GetMetaInfoMap(), nullptr); + ASSERT_EQ(bookmark_A1->GetMetaInfoMap(), nullptr); + ASSERT_NE(bookmark_C1->GetMetaInfoMap(), nullptr); + ASSERT_EQ(folder_B->GetMetaInfoMap(), nullptr); + ASSERT_EQ(bookmark_B1->GetMetaInfoMap(), nullptr); + + std::string brave_meta; + ASSERT_TRUE(bookmark_C1->GetMetaInfo("brave_meta", &brave_meta)); + ASSERT_EQ(brave_meta, "brave_meta_value"); +} + } // namespace bookmarks diff --git a/chromium_src/components/infobars/core/infobar_delegate.h b/chromium_src/components/infobars/core/infobar_delegate.h index ae0126b8fae0..5541d2cdc841 100644 --- a/chromium_src/components/infobars/core/infobar_delegate.h +++ b/chromium_src/components/infobars/core/infobar_delegate.h @@ -9,7 +9,8 @@ #define BRAVE_INFOBAR_DELEGATE_IDENTIFIERS \ BRAVE_CONFIRM_P3A_INFOBAR_DELEGATE = 500, \ CRYPTO_WALLETS_INFOBAR_DELEGATE = 501, \ - WAYBACK_MACHINE_INFOBAR_DELEGATE = 502, + WAYBACK_MACHINE_INFOBAR_DELEGATE = 502, \ + SYNC_V2_MIGRATE_INFOBAR_DELEGATE = 503, #include "../../../../../components/infobars/core/infobar_delegate.h" 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 index 5b995a855e87..3294af74afa3 100644 --- a/chromium_src/components/sync/driver/profile_sync_service.cc +++ b/chromium_src/components/sync/driver/profile_sync_service.cc @@ -1,81 +1,49 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. +/* 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/. */ -#include "brave/chromium_src/components/sync/driver/profile_sync_service.h" +#include "brave/components/brave_sync/brave_sync_prefs.h" +#include "components/prefs/pref_service.h" + +#include "brave/components/sync/driver/brave_sync_auth_manager.h" + +#define BRAVE_PROFILE_SYNC_SERVICE \ + brave_sync_prefs_change_registrar_.Init(sync_client_->GetPrefService()); \ + brave_sync_prefs_change_registrar_.Add( \ + brave_sync::Prefs::GetSeedPath(), \ + base::Bind(&ProfileSyncService::OnBraveSyncPrefsChanged, \ + base::Unretained(this))); \ + brave_sync::Prefs brave_sync_prefs(sync_client_->GetPrefService()); \ + auth_manager_->DeriveSigningKeys(brave_sync_prefs.GetSeed()); \ + if (!brave_sync_prefs.IsSyncV1Migrated()) { \ + StopImpl(CLEAR_DATA); \ + brave_sync_prefs.SetSyncV1Migrated(true); \ + } -#include +#define BRAVE_D_PROFILE_SYNC_SERVICE \ + brave_sync_prefs_change_registrar_.RemoveAll(); -#include "brave/components/brave_sync/buildflags/buildflags.h" +#define SyncAuthManager BraveSyncAuthManager -#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" +#include "../../../../../components/sync/driver/profile_sync_service.cc" -using brave_sync::BraveProfileSyncService; -#endif +#undef BRAVE_PROFILE_SYNC_SERVICE +#undef BRAVE_D_PROFILE_SYNC_SERVICE +#undef SyncAuthManager 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); +void ProfileSyncService::OnBraveSyncPrefsChanged(const std::string& path) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (path == brave_sync::Prefs::GetSeedPath()) { + brave_sync::Prefs brave_sync_prefs(sync_client_->GetPrefService()); + const std::string seed = brave_sync_prefs.GetSeed(); + if (!seed.empty()) { + auth_manager_->DeriveSigningKeys(seed); + } else { + VLOG(1) << "Brave sync seed cleared"; + auth_manager_->ResetKeys(); + } } } -#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 index e516f8872b60..a7f0d9d209cc 100644 --- a/chromium_src/components/sync/driver/profile_sync_service.h +++ b/chromium_src/components/sync/driver/profile_sync_service.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. +/* 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/. */ @@ -6,14 +6,24 @@ #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 +#include "components/prefs/pref_change_registrar.h" +// Header guard to prevent Initialize from getting overriden in it +// ============================================================================ +#include "components/sync/base/sync_prefs.h" +#include "components/sync/driver/sync_service_crypto.h" +// ============================================================================ -#define BRAVE_PROFILE_SYNC_SERVICE_H \ - friend class brave_sync::BraveProfileSyncServiceImpl; + +#define BRAVE_PROFILE_SYNC_SERVICE_H_ \ + private: \ + PrefChangeRegistrar brave_sync_prefs_change_registrar_; + +#define Initialize \ + OnBraveSyncPrefsChanged(const std::string& path); \ + void Initialize #include "../../../../../components/sync/driver/profile_sync_service.h" -#undef BRAVE_PROFILE_SYNC_SERVICE_H +#undef BRAVE_PROFILE_SYNC_SERVICE_H_ +#undef Initialize #endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_PROFILE_SYNC_SERVICE_H_ 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..82fa997ebecc --- /dev/null +++ b/chromium_src/components/sync/driver/sync_auth_manager.h @@ -0,0 +1,27 @@ +/* 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/. */ + +#ifndef BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_ +#define BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_ + +namespace syncer { +class BraveSyncAuthManager; +} // namespace syncer + +// Header guard to prevent DetermineAccountToUse from getting overriden in it +#include "components/sync/driver/sync_auth_util.h" + +#define RequestAccessToken virtual RequestAccessToken +#define DetermineAccountToUse \ + DetermineAccountToUse_Unused() { return SyncAccountInfo(); } \ + friend BraveSyncAuthManager; \ + virtual SyncAccountInfo DetermineAccountToUse + +#include "../../../../../components/sync/driver/sync_auth_manager.h" + +#undef BRAVE_SYNC_AUTH_MANAGER_H_ +#undef RequestAccessToken +#undef DetermineAccountToUse +#endif // BRAVE_CHROMIUM_SRC_COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_ diff --git a/chromium_src/components/sync/driver/sync_stopped_reporter.cc b/chromium_src/components/sync/driver/sync_stopped_reporter.cc new file mode 100644 index 000000000000..d9ccbf00ed0d --- /dev/null +++ b/chromium_src/components/sync/driver/sync_stopped_reporter.cc @@ -0,0 +1,13 @@ +/* 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 BRAVE_REPORT_SYNC_STOPPED \ + std::string headers; \ + headers = "Authorization: Bearer " + access_token; \ + resource_request->headers.AddHeadersFromString(headers.c_str()); + +#include "../../../../../components/sync/driver/sync_stopped_reporter.cc" + +#undef BRAVE_REPORT_SYNC_STOPPED 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/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc b/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc index 54206e2eb848..dd9c1e43e7b6 100644 --- a/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc +++ b/chromium_src/net/tools/transport_security_state_generator/input_file_parsers.cc @@ -311,8 +311,12 @@ bool ParseJSON(base::StringPiece json, // Brave { "name": "download.brave.com", "mode": "force-https", "policy": "custom", "pins": "brave"}, { "name": "laptop-updates.brave.com", "mode": "force-https", "policy": "custom", "pins": "brave"}, + // TODO(darkdh): remove sync v1 endpoints when Android migrates to v2 { "name": "sync.brave.com", "mode": "force-https", "policy": "custom", "pins": "brave"}, { "name": "sync-staging.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "sync-v2.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "sync-v2.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, + { "name": "sync-v2.brave.software", "policy": "custom", "mode": "force-https", "pins": "brave"}, { "name": "p3a.brave.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, { "name": "p3a.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, { "name": "p3a-dev.bravesoftware.com", "policy": "custom", "mode": "force-https", "pins": "brave"}, 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/network_constants.cc b/common/network_constants.cc index 84a5de06ecc2..2f83cd867173 100644 --- a/common/network_constants.cc +++ b/common/network_constants.cc @@ -61,6 +61,7 @@ const char kCookieHeader[] = "Cookie"; const char kRefererHeader[] = "Referer"; const char kUserAgentHeader[] = "User-Agent"; const char kBravePartnerHeader[] = "X-Brave-Partner"; +const char kBraveServicesKeyHeader[] = "BraveServiceKey"; const char kBittorrentMimeType[] = "application/x-bittorrent"; const char kOctetStreamMimeType[] = "application/octet-stream"; diff --git a/common/network_constants.h b/common/network_constants.h index c542c375ea65..e3a30e0e1f28 100644 --- a/common/network_constants.h +++ b/common/network_constants.h @@ -42,6 +42,7 @@ extern const char kCookieHeader[]; extern const char kRefererHeader[]; extern const char kUserAgentHeader[]; extern const char kBravePartnerHeader[]; +extern const char kBraveServicesKeyHeader[]; extern const char kBittorrentMimeType[]; extern const char kOctetStreamMimeType[]; diff --git a/common/webui_url_constants.cc b/common/webui_url_constants.cc index 7d59940e76b6..049e3967841d 100644 --- a/common/webui_url_constants.cc +++ b/common/webui_url_constants.cc @@ -14,13 +14,12 @@ 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"; +const char kBraveSyncPath[] = "braveSync"; +const char kBraveSyncSetupPath[] = "braveSync/setup"; diff --git a/common/webui_url_constants.h b/common/webui_url_constants.h index 4df5724784fe..a6487b757619 100644 --- a/common/webui_url_constants.h +++ b/common/webui_url_constants.h @@ -15,17 +15,16 @@ 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[]; extern const char kWalletHost[]; +extern const char kBraveSyncPath[]; +extern const char kBraveSyncSetupPath[]; #endif // BRAVE_COMMON_WEBUI_URL_CONSTANTS_H_ diff --git a/components/brave_sync/BUILD.gn b/components/brave_sync/BUILD.gn index 8cb90e479992..8cc6ad9361c1 100644 --- a/components/brave_sync/BUILD.gn +++ b/components/brave_sync/BUILD.gn @@ -14,78 +14,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", - "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 = [ - "//components/prefs", - ] -} - source_set("crypto") { sources = [ "crypto/crypto.cc", @@ -93,6 +21,7 @@ source_set("crypto") { ] deps = [ + "//base", "//brave/vendor/bat-native-tweetnacl:tweetnacl", "//brave/vendor/bip39wally-core-native:bip39wally-core", "//crypto", @@ -112,121 +41,46 @@ source_set("features") { deps = [ "//base", + "buildflags", ] } -source_set("public") { +source_set("network_time_helper") { sources = [ - "public/brave_profile_sync_service.h", + "network_time_helper.cc", + "network_time_helper.h", ] deps = [ - ":core", - "buildflags", + "//base", + "//components/network_time", ] } -source_set("core") { +source_set("prefs") { sources = [ - "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", + "brave_sync_prefs.cc", + "brave_sync_prefs.h", ] deps = [ - ":crypto", - ":features", - ":jslib_messages", - ":prefs", "//base", - "//components/bookmarks/browser", - "//crypto", - "//extensions/buildflags", + "//components/os_crypt", + "//components/prefs", + "//components/pref_registry", ] } source_set("brave_sync") { sources = [ - "brave_sync_service_observer.h", ] deps = [ - ":core", + ":crypto", + ":features", + ":network_time_helper", + ":prefs", "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_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/components/brave_sync/brave_sync_prefs.cc b/components/brave_sync/brave_sync_prefs.cc index b3b0c6838a41..53286255b8f4 100644 --- a/components/brave_sync/brave_sync_prefs.cc +++ b/components/brave_sync/brave_sync_prefs.cc @@ -7,28 +7,35 @@ #include -#include "brave/components/brave_sync/settings.h" -#include "brave/components/brave_sync/sync_devices.h" +#include "base/base64.h" +#include "components/os_crypt/os_crypt.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -void MigrateBraveSyncPrefs(PrefService* prefs) { - prefs->ClearPref(brave_sync::prefs::kSyncPrevSeed); - prefs->ClearPref(brave_sync::prefs::kDuplicatedBookmarksRecovered); -} - namespace brave_sync { -namespace prefs { - +namespace { + +// Stored as bip39 keywords (encrypted) +const char kSyncV2Seed[] = "brave_sync_v2.seed"; +// Indicate whether migration has been done from v1 to v2 +const char kSyncV1Migrated[] = "brave_sync_v2.v1_migrated"; +// Indicate all meta info set in V1 has been stripped in +// BraveBookmarkModelLoadedObserver +const char kSyncV1MetaInfoCleared[] = "brave_sync_v2.v1_meta_info_cleared"; +// Has dismissed message about migration to sync v2 +const char kSyncV2MigrateNoticeDismissed[] = + "brave_sync_v2.migrate_notice_dismissed"; +// Deprecated +// ============================================================================ +const char kSyncSeed[] = "brave_sync.seed"; +const char kSyncEnabled[] = "brave_sync.enabled"; 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"; -const char kSyncEnabled[] = "brave_sync.enabled"; const char kSyncBookmarksEnabled[] = "brave_sync.bookmarks_enabled"; const char kSyncSiteSettingsEnabled[] = "brave_sync.site_settings_enabled"; const char kSyncHistoryEnabled[] = "brave_sync.history_enabled"; @@ -48,260 +55,139 @@ const char kDuplicatedBookmarksRecovered[] = "brave_sync_duplicated_bookmarks_recovered"; const char kDuplicatedBookmarksMigrateVersion[] = "brave_sync_duplicated_bookmarks_migrate_version"; +// ============================================================================ +} // namespace Prefs::Prefs(PrefService* pref_service) : pref_service_(pref_service) {} -void Prefs::RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { - 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()); +Prefs::~Prefs() {} - registry->RegisterBooleanPref(prefs::kSyncEnabled, false); - registry->RegisterBooleanPref(prefs::kSyncBookmarksEnabled, false); - registry->RegisterBooleanPref(prefs::kSyncSiteSettingsEnabled, false); - registry->RegisterBooleanPref(prefs::kSyncHistoryEnabled, false); - - registry->RegisterTimePref(prefs::kSyncLatestRecordTime, base::Time()); - registry->RegisterTimePref(prefs::kSyncLatestDeviceRecordTime, base::Time()); - registry->RegisterTimePref(prefs::kSyncLastFetchTime, base::Time()); - registry->RegisterTimePref(prefs::kSyncLastCompactTimeBookmarks, +// static +void Prefs::RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { + registry->RegisterStringPref(kSyncV2Seed, std::string()); + registry->RegisterBooleanPref(kSyncV1Migrated, false); + registry->RegisterBooleanPref(kSyncV1MetaInfoCleared, false); + registry->RegisterBooleanPref(kSyncV2MigrateNoticeDismissed, false); + +// Deprecated +// ============================================================================ + registry->RegisterStringPref(kSyncSeed, std::string()); + registry->RegisterBooleanPref(kSyncEnabled, false); + registry->RegisterStringPref(kSyncDeviceId, std::string()); + registry->RegisterStringPref(kSyncDeviceIdV2, std::string()); + registry->RegisterStringPref(kSyncDeviceObjectId, std::string()); + registry->RegisterStringPref(kSyncPrevSeed, std::string()); + registry->RegisterStringPref(kSyncDeviceName, std::string()); + registry->RegisterStringPref(kSyncBookmarksBaseOrder, std::string()); + registry->RegisterBooleanPref(kSyncBookmarksEnabled, false); + registry->RegisterBooleanPref(kSyncSiteSettingsEnabled, false); + registry->RegisterBooleanPref(kSyncHistoryEnabled, false); + registry->RegisterTimePref(kSyncLatestRecordTime, base::Time()); + registry->RegisterTimePref(kSyncLatestDeviceRecordTime, base::Time()); + registry->RegisterTimePref(kSyncLastFetchTime, base::Time()); + registry->RegisterTimePref(kSyncLastCompactTimeBookmarks, base::Time()); - - registry->RegisterStringPref(prefs::kSyncDeviceList, std::string()); - registry->RegisterStringPref(prefs::kSyncApiVersion, std::string("0")); - registry->RegisterIntegerPref(prefs::kSyncMigrateBookmarksVersion, 0); - - registry->RegisterListPref(prefs::kSyncRecordsToResend); - registry->RegisterDictionaryPref(prefs::kSyncRecordsToResendMeta); + registry->RegisterStringPref(kSyncDeviceList, std::string()); + registry->RegisterStringPref(kSyncApiVersion, std::string("0")); + registry->RegisterIntegerPref(kSyncMigrateBookmarksVersion, 0); + registry->RegisterListPref(kSyncRecordsToResend); + registry->RegisterDictionaryPref(kSyncRecordsToResendMeta); registry->RegisterBooleanPref(kDuplicatedBookmarksRecovered, false); - registry->RegisterIntegerPref(prefs::kDuplicatedBookmarksMigrateVersion, 0); -} - -std::string Prefs::GetSeed() const { - return pref_service_->GetString(kSyncSeed); -} - -void Prefs::SetSeed(const std::string& seed) { - DCHECK(!seed.empty()); - pref_service_->SetString(kSyncSeed, seed); -} - -std::string Prefs::GetThisDeviceId() const { - return pref_service_->GetString(kSyncDeviceId); + registry->RegisterIntegerPref(kDuplicatedBookmarksMigrateVersion, 0); } -void Prefs::SetThisDeviceId(const std::string& device_id) { - DCHECK(!device_id.empty()); - pref_service_->SetString(kSyncDeviceId, device_id); +// static +std::string Prefs::GetSeedPath() { + return kSyncV2Seed; } -std::string Prefs::GetThisDeviceIdV2() const { - return pref_service_->GetString(kSyncDeviceIdV2); +std::string Prefs::GetSeed() const { + const std::string encoded_seed = pref_service_->GetString(kSyncV2Seed); + std::string encrypted_seed; + if (!base::Base64Decode(encoded_seed, &encrypted_seed)) { + LOG(ERROR) << "base64 decode sync seed failure"; + return std::string(); + } + std::string seed; + if (!OSCrypt::DecryptString(encrypted_seed, &seed)) { + LOG(ERROR) << "Decrypt sync seed failure"; + return std::string(); + } + return seed; } -void Prefs::SetThisDeviceIdV2(const std::string& device_id_v2) { - if (!device_id_v2.empty()) - pref_service_->SetString(kSyncDeviceIdV2, device_id_v2); +bool Prefs::SetSeed(const std::string& seed) { + DCHECK(!seed.empty()); + std::string encrypted_seed; + if (!OSCrypt::EncryptString(seed, &encrypted_seed)) { + LOG(ERROR) << "Encrypt sync seed failure"; + return false; + } + // String stored in prefs has to be UTF8 string so we use base64 to encode it. + std::string encoded_seed; + base::Base64Encode(encrypted_seed, &encoded_seed); + pref_service_->SetString(kSyncV2Seed, encoded_seed); + return true; } -std::string Prefs::GetThisDeviceObjectId() const { - return pref_service_->GetString(kSyncDeviceObjectId); +bool Prefs::IsSyncV1Migrated() const { + return pref_service_->GetBoolean(kSyncV1Migrated); } -void Prefs::SetThisDeviceObjectId(const std::string& device_object_id) { - DCHECK(!device_object_id.empty()); - pref_service_->SetString(kSyncDeviceObjectId, device_object_id); +void Prefs::SetSyncV1Migrated(bool is_migrated) { + pref_service_->SetBoolean(kSyncV1Migrated, is_migrated); } -std::string Prefs::GetThisDeviceName() const { - return pref_service_->GetString(kSyncDeviceName); +bool Prefs::IsSyncV1MetaInfoCleared() const { + return pref_service_->GetBoolean(kSyncV1MetaInfoCleared); } -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); +void Prefs::SetSyncV1MetaInfoCleared(bool is_cleared) { + pref_service_->SetBoolean(kSyncV1MetaInfoCleared, is_cleared); } -bool Prefs::GetSyncEnabled() const { +bool Prefs::IsSyncV1Enabled() 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::IsSyncMigrateNoticeDismissed() const { + return pref_service_->GetBoolean(kSyncV2MigrateNoticeDismissed); } -bool Prefs::GetSyncSiteSettingsEnabled() const { - return pref_service_->GetBoolean(kSyncSiteSettingsEnabled); +void Prefs::SetDismissSyncMigrateNotice(bool is_dismissed) { + pref_service_->SetBoolean(kSyncV2MigrateNoticeDismissed, is_dismissed); } -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); -} - -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(kSyncV2Seed); } -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); +void MigrateBraveSyncPrefs(PrefService* prefs) { + // Added 11/2019 + prefs->ClearPref(kSyncPrevSeed); + + // Added 05/2020 + prefs->ClearPref(kSyncSeed); + // Clear this prefs after almost every users have migrated to sync v2 + // prefs->ClearPref(kSyncEnabled); + prefs->ClearPref(kDuplicatedBookmarksRecovered); + prefs->ClearPref(kSyncDeviceId); + prefs->ClearPref(kSyncDeviceIdV2); + prefs->ClearPref(kSyncDeviceObjectId); + prefs->ClearPref(kSyncDeviceName); + prefs->ClearPref(kSyncBookmarksEnabled); + prefs->ClearPref(kSyncBookmarksBaseOrder); + prefs->ClearPref(kSyncSiteSettingsEnabled); + prefs->ClearPref(kSyncHistoryEnabled); + prefs->ClearPref(kSyncLatestRecordTime); + prefs->ClearPref(kSyncLatestDeviceRecordTime); + prefs->ClearPref(kSyncLastFetchTime); + prefs->ClearPref(kSyncDeviceList); + prefs->ClearPref(kSyncApiVersion); + prefs->ClearPref(kSyncMigrateBookmarksVersion); + prefs->ClearPref(kSyncRecordsToResend); + prefs->ClearPref(kSyncRecordsToResendMeta); + prefs->ClearPref(kDuplicatedBookmarksMigrateVersion); } -} // namespace prefs } // namespace brave_sync diff --git a/components/brave_sync/brave_sync_prefs.h b/components/brave_sync/brave_sync_prefs.h index 7c7d7e4bde83..ded0c155d49c 100644 --- a/components/brave_sync/brave_sync_prefs.h +++ b/components/brave_sync/brave_sync_prefs.h @@ -23,129 +23,42 @@ namespace user_prefs { class PrefRegistrySyncable; } -void MigrateBraveSyncPrefs(PrefService* prefs); - namespace brave_sync { -class Settings; -class SyncDevices; - -namespace prefs { - -// String of device id. Supposed to be an integer -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 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 -extern const char kDuplicatedBookmarksMigrateVersion[]; - class Prefs { public: explicit Prefs(PrefService* pref_service); + virtual ~Prefs(); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); + static std::string GetSeedPath(); + 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); + bool SetSeed(const std::string& seed); + + bool IsSyncV1Migrated() const; + void SetSyncV1Migrated(bool is_migrated); + + bool IsSyncV1MetaInfoCleared() const; + void SetSyncV1MetaInfoCleared(bool is_cleared); + + // It is only used to read whether sync v1 was enabled before upgrading + bool IsSyncV1Enabled() const; + + bool IsSyncMigrateNoticeDismissed() const; + void SetDismissSyncMigrateNotice(bool is_dismissed); void Clear(); private: - // May be null. - PrefService* pref_service_; + PrefService* const pref_service_; DISALLOW_COPY_AND_ASSIGN(Prefs); }; -} // namespace prefs +void MigrateBraveSyncPrefs(PrefService* prefs); + } // namespace brave_sync #endif // BRAVE_COMPONENTS_BRAVE_SYNC_BRAVE_SYNC_PREFS_H_ 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/buildflags/buildflags.gni b/components/brave_sync/buildflags/buildflags.gni index abdd976fe05a..6021b9001aeb 100755 --- a/components/brave_sync/buildflags/buildflags.gni +++ b/components/brave_sync/buildflags/buildflags.gni @@ -1,6 +1,8 @@ +import("//brave/build/config.gni") import("//build/config/features.gni") -import("//extensions/buildflags/buildflags.gni") declare_args() { - enable_brave_sync = enable_extensions + enable_brave_sync = + brave_channel == "development" || + brave_channel == "nightly" } 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/crypto/crypto.cc b/components/brave_sync/crypto/crypto.cc index d4aa715234c3..fb1ff974e7ab 100644 --- a/components/brave_sync/crypto/crypto.cc +++ b/components/brave_sync/crypto/crypto.cc @@ -39,13 +39,14 @@ std::vector HKDFSha512(const std::vector& ikm, void DeriveSigningKeysFromSeed(const std::vector& seed, const std::vector* salt, + const std::vector* info, std::vector* public_key, std::vector* private_key) { DCHECK(public_key); DCHECK(private_key); - const std::vector info = {0}; + DCHECK(info); std::vector output = - HKDFSha512(seed, salt, &info, DEFAULT_SEED_SIZE); + HKDFSha512(seed, salt, info, DEFAULT_SEED_SIZE); public_key->resize(ED25519_PUBLIC_KEY_LEN); private_key->resize(ED25519_PRIVATE_KEY_LEN); ED25519_keypair_from_seed(public_key->data(), private_key->data(), diff --git a/components/brave_sync/crypto/crypto.h b/components/brave_sync/crypto/crypto.h index ca906146486b..aca58da3f90f 100644 --- a/components/brave_sync/crypto/crypto.h +++ b/components/brave_sync/crypto/crypto.h @@ -26,6 +26,7 @@ std::vector HKDFSha512(const std::vector& ikm, // Derives an Ed25519 keypair given a random seed and an optional HKDF salt void DeriveSigningKeysFromSeed(const std::vector& seed, const std::vector* salt, + const std::vector* info, std::vector* public_key, std::vector* private_key); diff --git a/components/brave_sync/crypto/crypto_unittest.cc b/components/brave_sync/crypto/crypto_unittest.cc index f4516eb4cda7..0c50cd7bfc0d 100644 --- a/components/brave_sync/crypto/crypto_unittest.cc +++ b/components/brave_sync/crypto/crypto_unittest.cc @@ -134,7 +134,8 @@ TEST(CryptoTest, Ed25519KeyDerivation) { &seed); std::vector public_key = {}; std::vector private_key = {}; - DeriveSigningKeysFromSeed(seed, &HKDF_SALT, &public_key, &private_key); + std::vector info = {0}; + DeriveSigningKeysFromSeed(seed, &HKDF_SALT, &info, &public_key, &private_key); EXPECT_EQ("f58ca446f0c33ee7e8e9874466da442b2e764afd77ad46034bdff9e01f9b87d4", base::ToLowerASCII( base::HexEncode(public_key.data(), public_key.size()))); diff --git a/components/brave_sync/features.cc b/components/brave_sync/features.cc index 4d96ea912aaa..77f97056d6c4 100644 --- a/components/brave_sync/features.cc +++ b/components/brave_sync/features.cc @@ -6,11 +6,16 @@ #include "brave/components/brave_sync/features.h" #include "base/feature_list.h" +#include "brave/components/brave_sync/buildflags/buildflags.h" namespace brave_sync { namespace features { +#if BUILDFLAG(ENABLE_BRAVE_SYNC) +const base::Feature kBraveSync{"BraveSync", base::FEATURE_ENABLED_BY_DEFAULT}; +#else const base::Feature kBraveSync{"BraveSync", base::FEATURE_DISABLED_BY_DEFAULT}; +#endif } // namespace features } // namespace brave_sync 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/network_time_helper.cc b/components/brave_sync/network_time_helper.cc new file mode 100644 index 000000000000..3f7aba6d90b7 --- /dev/null +++ b/components/brave_sync/network_time_helper.cc @@ -0,0 +1,58 @@ +/* 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/. */ + +#include "brave/components/brave_sync/network_time_helper.h" + +#include + +#include "base/sequence_checker.h" +#include "base/task/post_task.h" +#include "components/network_time/network_time_tracker.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" + +namespace brave_sync { + +// static +NetworkTimeHelper* NetworkTimeHelper::GetInstance() { + return base::Singleton::get(); +} + +NetworkTimeHelper::NetworkTimeHelper() {} +NetworkTimeHelper::~NetworkTimeHelper() {} + +void NetworkTimeHelper::SetNetworkTimeTracker( + network_time::NetworkTimeTracker* tracker) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + network_time_tracker_ = tracker; +} + +void NetworkTimeHelper::GetNetworkTime(GetNetworkTimeCallback cb) { + if (!network_time_for_test_.is_null()) { + std::move(cb).Run(network_time_for_test_); + return; + } + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&NetworkTimeHelper::GetNetworkTimeOnUIThread, + weak_ptr_factory_.GetWeakPtr(), std::move(cb))); +} + +void NetworkTimeHelper::SetNetworkTimeForTest(const base::Time& time) { + network_time_for_test_ = time; +} + +void NetworkTimeHelper::GetNetworkTimeOnUIThread(GetNetworkTimeCallback cb) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + base::Time time; + if (!network_time_tracker_ || + network_time_tracker_->GetNetworkTime(&time, nullptr) != + network_time::NetworkTimeTracker::NETWORK_TIME_AVAILABLE) { + VLOG(1) << "Network time not available, using local time"; + time = base::Time::Now(); + } + std::move(cb).Run(time); +} + +} // namespace brave_sync diff --git a/components/brave_sync/network_time_helper.h b/components/brave_sync/network_time_helper.h new file mode 100644 index 000000000000..813497a4f547 --- /dev/null +++ b/components/brave_sync/network_time_helper.h @@ -0,0 +1,54 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_SYNC_NETWORK_TIME_HELPER_H_ +#define BRAVE_COMPONENTS_BRAVE_SYNC_NETWORK_TIME_HELPER_H_ + +#include "base/callback.h" +#include "base/memory/singleton.h" +#include "base/memory/weak_ptr.h" +#include "base/time/time.h" + +namespace network_time { +class NetworkTimeTracker; +} // namespace network_time + +namespace brave_sync { + +class NetworkTimeHelper { + public: + using GetNetworkTimeCallback = base::OnceCallback; + + static NetworkTimeHelper* GetInstance(); + + NetworkTimeHelper(); + virtual ~NetworkTimeHelper(); + + void SetNetworkTimeTracker(network_time::NetworkTimeTracker* tracker); + + void GetNetworkTime(GetNetworkTimeCallback cb); + + void SetNetworkTimeForTest(const base::Time& time); + + private: + friend struct base::DefaultSingletonTraits; + + void GetNetworkTimeOnUIThread(GetNetworkTimeCallback cb); + + base::Time network_time_for_test_; + + SEQUENCE_CHECKER(sequence_checker_); + + // Not owned + network_time::NetworkTimeTracker* network_time_tracker_ = nullptr; + + base::WeakPtrFactory weak_ptr_factory_{this}; + + DISALLOW_COPY_AND_ASSIGN(NetworkTimeHelper); +}; + +} // namespace brave_sync + +#endif // BRAVE_COMPONENTS_BRAVE_SYNC_NETWORK_TIME_HELPER_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/ui/BUILD.gn b/components/brave_sync/ui/BUILD.gn deleted file mode 100644 index 990a4e336d8f..000000000000 --- a/components/brave_sync/ui/BUILD.gn +++ /dev/null @@ -1,9 +0,0 @@ -import("//brave/components/common/typescript.gni") - -transpile_web_ui("ui") { - entry_points = [ - ["brave_sync", rebase_path("brave_sync.tsx")] - ] - - resource_name = "brave_sync" -} diff --git a/components/brave_sync/ui/actions/sync_actions.ts b/components/brave_sync/ui/actions/sync_actions.ts deleted file mode 100644 index 5af8dba748bd..000000000000 --- a/components/brave_sync/ui/actions/sync_actions.ts +++ /dev/null @@ -1,128 +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/. */ - -import { action } from 'typesafe-actions' - -// Constants -import { types } from '../constants/sync_types' - -/** - * Dispatches a message telling the back-end that sync page has loaded - */ -export const onPageLoaded = () => { - return action(types.SYNC_ON_PAGE_LOADED) -} - -/** - * Action dispatched by the back-end with useful information - * about devices and settings synced - * @param {Sync.SettingsFromBackEnd} settings - the sync settings information - * @param {Sync.DevicesFromBackEnd} devices - the sync original devices information - */ -export const onShowSettings = (settings: Sync.SettingsFromBackEnd, devices: Sync.DevicesFromBackEnd) => { - return action(types.SYNC_ON_SHOW_SETTINGS, { settings, devices }) -} - -/** - * Action dispatched by the back-end when sync words are available - * for use in the front-end - */ -export const onHaveSyncWords = (syncWords: string) => { - return action(types.SYNC_ON_HAVE_SYNC_WORDS, { syncWords }) -} - -/** - * Action dispatched by the back-end containing the seed needed - * to request the QR code - * @param {string} seed - The seed used by the QR code generator - */ -export const onHaveSeedForQrCode = (seed: string) => { - return action(types.SYNC_ON_HAVE_SEED_FOR_QR_CODE, { seed }) -} - -/** - * Dispatches a message telling the back-end that a new device setup - * was requested by the user - * @param {string} thisDeviceName - The newly synced device name - */ -export const onSetupNewToSync = (thisDeviceName: string) => { - return action(types.SYNC_ON_SETUP_NEW_TO_SYNC, { thisDeviceName }) -} - -export const onGenerateQRCodeImageSource = (imageSource: string) => { - return action(types.SYNC_ON_GENERATE_QR_CODE_IMAGE_SOURCE, { imageSource }) -} - -/** - * Dispatches a message telling the back-end that the user removed a given device - * @param {number} id - The device ID V2 - * @param {string} deviceName - The device name - */ -export const onRemoveDevice = (idv2: number, deviceName: string) => { - return action(types.SYNC_ON_REMOVE_DEVICE, { idv2, deviceName }) -} - -/** - * Dispatches a message telling the back-end that user has reset Sync - */ -export const onSyncReset = () => { - return action(types.SYNC_ON_RESET) -} - -/** - * Dispatches a message telling the back-end that user toggled the bookmarks sync - * @param {boolean} shouldEnable - Whether or not it should sync the bookmarks - */ -export const onSyncBookmarks = (shouldEnable: boolean) => { - return action(types.SYNC_BOOKMARKS, { shouldEnable }) -} - -/** - * Dispatches a message telling the back-end that user toggled the site settings sync - * @param {boolean} shouldEnable - Whether or not it should sync the site settings - */ -export const onSyncSavedSiteSettings = (shouldEnable: boolean) => { - return action(types.SYNC_SAVED_SITE_SETTINGS, { shouldEnable }) -} - -/** - * Dispatches a message telling the back-end that user toggled the browsing history sync - * @param {boolean} shouldEnable - Whether or not it should sync browsing history - */ -export const onSyncBrowsingHistory = (shouldEnable: boolean) => { - return action(types.SYNC_BROWSING_HISTORY, { shouldEnable }) -} - -/** - * Setup another device by informing the sync words needed to connect. - * Triggered by the initial Sync action "I have an existing Sync code" - * @param {string} syncWords - The sync words needed to find the new device - * @param {string} deviceName - The new device name - */ -export const onSetupSyncHaveCode = (syncWords: string, deviceName: string) => { - return action(types.SYNC_SETUP_SYNC_HAVE_CODE, { syncWords, deviceName }) -} - -/** - * Dispatched by the back-end when Sync encountered an error - * @param {SetupErrorType} error - the error message - */ -export const onSyncSetupError = (error: Sync.SetupErrorType) => { - return action(types.SYNC_SETUP_ERROR, { error }) -} - -/** - * Reset the Sync Error - */ -export const clearSyncSetupError = () => { - return action(types.SYNC_CLEAR_SETUP_ERROR) -} - -/** - * Dispatched by the back-end to inform useful log messages for debugging purposes - * @param {string} message - the log message - */ -export const onLogMessage = (message: string) => { - return action(types.SYNC_ON_LOG_MESSAGE, { message }) -} diff --git a/components/brave_sync/ui/brave_sync.html b/components/brave_sync/ui/brave_sync.html deleted file mode 100644 index 4552662c94a5..000000000000 --- a/components/brave_sync/ui/brave_sync.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - Sync - - - - - - - - - - -
- - diff --git a/components/brave_sync/ui/brave_sync.tsx b/components/brave_sync/ui/brave_sync.tsx deleted file mode 100644 index d4ede215fc33..000000000000 --- a/components/brave_sync/ui/brave_sync.tsx +++ /dev/null @@ -1,77 +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/. */ - -import * as React from 'react' -import { render } from 'react-dom' -import { Provider } from 'react-redux' - -// Components -import App from './containers/app' - -// Utils -import store from './store' -import { ThemeProvider } from 'brave-ui/theme' -import Theme from 'brave-ui/theme/brave-default' -import { getActions as getUtilActions, setActions } from './helpers' -import * as syncActions from './actions/sync_actions' -import { bindActionCreators } from 'redux' - -window.cr.define('sync_ui_exports', function () { - 'use strict' - - function initialize () { - render( - - - - - , - document.getElementById('root') - ) - window.i18nTemplate.process(window.document, window.loadTimeData) - } - - function getActions () { - const actions: any = getUtilActions() - if (actions) { - return actions - } - const newActions = bindActionCreators(syncActions, store.dispatch.bind(store)) - setActions(newActions) - return newActions - } - - function showSettings (settings: any, devices: any) { - getActions().onShowSettings(settings, devices) - } - - function haveSyncWords (syncWords: string) { - getActions().onHaveSyncWords(syncWords) - } - - function haveSeedForQrCode (seed: string) { - getActions().onHaveSeedForQrCode(seed) - } - - // TODO, AB: should be removed - // for testing purposes - function logMessage (message: string) { - getActions().onLogMessage(message) - } - - function syncSetupError (error: Sync.SetupErrorType) { - getActions().onSyncSetupError(error) - } - - return { - initialize, - showSettings, - haveSyncWords, - haveSeedForQrCode, - logMessage, - syncSetupError - } -}) - -document.addEventListener('DOMContentLoaded', window.sync_ui_exports.initialize) diff --git a/components/brave_sync/ui/brave_sync_disabled.html b/components/brave_sync/ui/brave_sync_disabled.html deleted file mode 100644 index cdd159e1a7bf..000000000000 --- a/components/brave_sync/ui/brave_sync_disabled.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - Sync(Disabled) - - - Sync in tor(guest) window is disabled. - - diff --git a/components/brave_sync/ui/components/grid/index.ts b/components/brave_sync/ui/components/grid/index.ts deleted file mode 100644 index 2adfce0c28bd..000000000000 --- a/components/brave_sync/ui/components/grid/index.ts +++ /dev/null @@ -1,53 +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/. */ - -import styled from 'brave-ui/theme' - -export const SectionBlock = styled<{}, 'section'>('section')` - margin: 15px 0 40px; -` - -export const EnabledContentButtonGrid = styled<{}, 'footer'>('footer')` - display: grid; - grid-template-columns: 1fr; - grid-template-rows: 1fr; - grid-gap: 5px; - margin: 10px 5px 0; -` - -export const SettingsToggleGrid = styled<{}, 'footer'>('footer')` - display: grid; - grid-template-columns: auto 1fr; - grid-template-rows: 1fr; - grid-gap: 5px; - align-items: center; - margin: 15px 0 0; -` - -export const DisabledContentButtonGrid = styled<{}, 'footer'>('footer')` - display: grid; - grid-template-columns: 1fr 1fr; - grid-template-rows: 1fr; - grid-gap: 10px; - margin: 15px 0 0; -` - -interface TableGridProps { - isDeviceTable?: boolean -} - -export const TableGrid = styled('div')` - align-items: center; - display: grid; - grid-template-columns: ${p => p.isDeviceTable ? '1fr' : '200px auto'}; - grid-template-rows: auto; - grid-gap: ${p => p.isDeviceTable ? '0' : '50px'}; -` - -export const TableButtonGrid = styled<{}, 'div'>('div')` - display: grid; - grid-template-rows: auto; - grid-gap: 15px; - grid-template-columns: 2fr 1fr 1fr; -` diff --git a/components/brave_sync/ui/components/images/add_icon.svg b/components/brave_sync/ui/components/images/add_icon.svg deleted file mode 100644 index cedf5ac78f00..000000000000 --- a/components/brave_sync/ui/components/images/add_icon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/components/brave_sync/ui/components/images/default_icon.svg b/components/brave_sync/ui/components/images/default_icon.svg deleted file mode 100644 index 6ecc798afbef..000000000000 --- a/components/brave_sync/ui/components/images/default_icon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/components/brave_sync/ui/components/images/desktop_icon.png b/components/brave_sync/ui/components/images/desktop_icon.png deleted file mode 100644 index 2284b85f4b04..000000000000 Binary files a/components/brave_sync/ui/components/images/desktop_icon.png and /dev/null differ diff --git a/components/brave_sync/ui/components/images/index.ts b/components/brave_sync/ui/components/images/index.ts deleted file mode 100644 index bdabc55f71c2..000000000000 --- a/components/brave_sync/ui/components/images/index.ts +++ /dev/null @@ -1,49 +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/. */ - -import styled from 'brave-ui/theme' - -import StartImageUrl from './start_icon.svg' -import DefaultImageUrl from './default_icon.svg' -import AddImageUrl from './add_icon.svg' -import RemoveImageUrl from './remove_icon.svg' -import DesktopImageUrl from './sync_computer.svg' -import MobileImageUrl from './sync_devices.svg' -import MobileHandImageUrl from './sync_hand.svg' - -const iconStyles = ` - margin-top: 3px; - height: 60px; -` - -const deviceStyles = ` - margin-bottom: 10px; - height: 100px; -` - -export const SyncStartIcon = styled<{}, 'img'>('img').attrs({ src: StartImageUrl })` - max-width: 100%; -` -export const SyncDefaultIcon = styled<{}, 'img'>('img').attrs({ src: DefaultImageUrl })`${iconStyles}` -export const SyncAddIcon = styled<{}, 'img'>('img').attrs({ src: AddImageUrl })`${iconStyles}` -export const SyncRemoveIcon = styled<{}, 'img'>('img').attrs({ src: RemoveImageUrl })`${iconStyles}` -export const SyncDesktopIcon = styled<{}, 'img'>('img').attrs({ src: DesktopImageUrl })`${deviceStyles}` -export const SyncMobileIcon = styled<{}, 'img'>('img').attrs({ src: MobileImageUrl })`${deviceStyles}` -export const SyncMobilePicture = styled<{}, 'img'>('img').attrs({ src: MobileHandImageUrl })` - max-width: 100%; - height: 150px; - display: block; -` - -interface QRCodeProps { - size: 'normal' | 'small' -} - -export const QRCode = styled('img')` - display: block; - width: 200px; - padding: 30px; - border: 1px solid #C8C8D5; - max-width: 100%; -` diff --git a/components/brave_sync/ui/components/images/mobile_icon.png b/components/brave_sync/ui/components/images/mobile_icon.png deleted file mode 100644 index 4b52934dda48..000000000000 Binary files a/components/brave_sync/ui/components/images/mobile_icon.png and /dev/null differ diff --git a/components/brave_sync/ui/components/images/mobile_picture.png b/components/brave_sync/ui/components/images/mobile_picture.png deleted file mode 100644 index 65e656e2bec8..000000000000 Binary files a/components/brave_sync/ui/components/images/mobile_picture.png and /dev/null differ diff --git a/components/brave_sync/ui/components/images/remove_icon.svg b/components/brave_sync/ui/components/images/remove_icon.svg deleted file mode 100644 index ff07652edf49..000000000000 --- a/components/brave_sync/ui/components/images/remove_icon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/components/brave_sync/ui/components/images/sync_hand.svg b/components/brave_sync/ui/components/images/sync_hand.svg deleted file mode 100644 index 9d2542fdc38a..000000000000 --- a/components/brave_sync/ui/components/images/sync_hand.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/components/brave_sync/ui/components/index.ts b/components/brave_sync/ui/components/index.ts deleted file mode 100644 index b569f9bb99e5..000000000000 --- a/components/brave_sync/ui/components/index.ts +++ /dev/null @@ -1,42 +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/. */ - -export { Title, SubTitle, Paragraph, SwitchLabel, Link, Bold } from './text' -export { - DisabledContent, - EnabledContent, - Main, - SyncCard, - SyncCardContent, - TableRowId, - TableRowDevice, - TableRowRemove, - TableRowRemoveButton, - TableRowToggleButton -} from './misc' -export { - SectionBlock, - SettingsToggleGrid, - EnabledContentButtonGrid, - DisabledContentButtonGrid, - TableGrid, - TableButtonGrid -} from './grid' -export { - ModalHeader, - ModalTitle, - ModalSubTitle, - ModalContent, - TwoColumnButtonGrid, - OneColumnButtonGrid, - DeviceGrid, - DeviceContainer, - ViewSyncCodeGrid, - ScanGrid, - QRCodeContainer, - ThreeColumnButtonGrid, - ThreeColumnButtonGridCol1, - ThreeColumnButtonGridCol2 -} from './modal' -export { Toggle } from './toggle' diff --git a/components/brave_sync/ui/components/misc/index.tsx b/components/brave_sync/ui/components/misc/index.tsx deleted file mode 100644 index 14c4623bb316..000000000000 --- a/components/brave_sync/ui/components/misc/index.tsx +++ /dev/null @@ -1,71 +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/. */ - -import * as React from 'react' -import styled from 'brave-ui/theme' -import Card, { CardProps } from 'brave-ui/components/layout/card' - -export const DisabledContent = styled<{}, 'div'>('div')` - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - height: inherit; - background-color: #efeff0; -` - -export const EnabledContent = styled<{}, 'div'>('div')` - height: inherit; - background-color: #efeff0; -` - -export const Main = styled<{}, 'main'>('main')` - font-family: ${p => p.theme.fontFamily.body}; - color: ${p => p.theme.color.defaultControl}; - padding: 50px 15px; - max-width: 830px; - margin: auto; -` - -export const SyncCard: React.FC = (props) => - - -export const SyncCardContent = styled('div')` - padding: 60px 80px; -` - -export const TableRowId = styled<{}, 'span'>('span')` - width: 5ch; - text-align: center; - display: block; -` - -export const TableRowDevice = styled<{}, 'span'>('span')` - max-width: 30ch; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - display: block; -` - -export const TableRowRemove = styled<{}, 'span'>('span')` - display: block; - text-align: center; -` - -export const TableRowRemoveButton = styled<{}, 'button'>('button')` - text-align: center; - padding: 0; - border: 0; - background: transparent; - cursor: pointer; - display: block; - margin: auto; - width: 24px; -` - -export const TableRowToggleButton = styled<{}, 'span'>('span')` - float: right; - margin: 9px; -` diff --git a/components/brave_sync/ui/components/modal/index.ts b/components/brave_sync/ui/components/modal/index.ts deleted file mode 100644 index 4e943cc8d9cb..000000000000 --- a/components/brave_sync/ui/components/modal/index.ts +++ /dev/null @@ -1,121 +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/. */ - -import styled from 'brave-ui/theme' -import Heading from 'brave-ui/components/text/heading' - -export const ModalHeader = styled<{}, 'header'>('header')` - margin-bottom: 8px; -` - -export const ModalTitle = styled(Heading)` - font-weight: 500; - font-size: 24px; - margin: 0 0 4px; - line-height: 1.6; -` - -interface ModalSubTitleProps { - highlight?: boolean -} - -export const ModalSubTitle = styled('span')` - display: block; - font-size: 18px; - line-height: 1.6; - color: ${p => p.highlight && '#ff0000'} -` - -export const ModalContent = styled<{}, 'div'>('div')` - margin-bottom: -12px; -` - -export const OneColumnButtonGrid = styled<{}, 'div'>('div')` - display: flex; - justify-content: flex-end; -` - -export const TwoColumnButtonGrid = styled<{}, 'footer'>('footer')` - display: grid; - align-items: center; - grid-template-columns: 1fr auto; - grid-gap: 15px; - margin-top: 20px; -` - -export const ThreeColumnButtonGrid = styled<{}, 'div'>('div')` - display: grid; - grid-template-columns: 1fr auto auto; - grid-gap: 15px; - margin-top: 20px; - align-items: center; -` - -export const ThreeColumnButtonGridCol1 = styled<{}, 'div'>('div')` - display: grid; - align-items: center; - grid-template-columns: auto; -` - -export const ThreeColumnButtonGridCol2 = styled<{}, 'div'>('div')` - display: grid; - align-items: center; - grid-template-columns: auto auto; - grid-gap: 15px; -` - -export const DeviceGrid = styled<{}, 'div'>('div')` - display: grid; - grid-template-columns: 1fr 1fr; - grid-template-rows: 1fr; - grid-gap: 30px; - height: 220px; - margin: auto; - align-items: center; - justify-content: center; -` - -export const DeviceContainer = styled<{}, 'a'>('a')` - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - height: 100%; - border: 1px solid #C8C8D5; - border-radius: 6px; - cursor: pointer; -` - -export const ScanGrid = styled<{}, 'div'>('div')` - display: grid; - height: 100%; - grid-template-columns: 1fr 1fr; - grid-template-rows: 1fr; - margin: 25px auto; - grid-gap: 30px; - align-items: center; - width: fit-content; -` - -export const QRCodeContainer = styled<{}, 'div'>('div')` - display: flex; - flex-direction: column; - align-items: center; - width: 120px; - img { - max-width: 100%; - } -` - -export const ViewSyncCodeGrid = styled<{}, 'div'>('div')` - display: grid; - height: 100%; - grid-template-columns: 2fr 1fr; - grid-template-rows: 1fr; - grid-gap: 16px; - margin: 0 0 25px; - img { - max-width: 80%; - } -` diff --git a/components/brave_sync/ui/components/text/index.ts b/components/brave_sync/ui/components/text/index.ts deleted file mode 100644 index d7cca22dc57c..000000000000 --- a/components/brave_sync/ui/components/text/index.ts +++ /dev/null @@ -1,49 +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/. */ - -import styled from 'brave-ui/theme' -import Heading from 'brave-ui/components/text/heading' - -export const Title = styled(Heading)` - font-weight: 600; - font-size: 24px; - margin: 0 0 4px 0; - line-height: 1.6; -` - -export const SubTitle = styled(Heading)` - font-weight: 600; - font-size: 20px; - margin: 16px 0 12px 0; -` - -export const Paragraph = styled<{}, 'p'>('p')` - font-size: 16px; - font-weight: 300; - line-height: 1.75; - margin: 0; - font-family: ${p => p.theme.fontFamily.body}; - padding: 0 0 12px 0; -` - -export const Link = styled<{}, 'a'>(Paragraph.withComponent('a') as any)` - color: ${p => p.theme.color.subtle}; - padding: 0; - text-decoration: none; - cursor: pointer; - display: inline; -` - -export const Bold = styled<{}, 'b'>('b')` - font-weight: 600; -` - -export const SwitchLabel = styled<{}, 'label'>('label')` - font-family: ${p => p.theme.fontFamily.body}; - color: ${p => p.theme.color.defaultControlActive}; - font-size: 14px; - font-weight: 400; - letter-spacing: normal; - margin: 0 12px; -` diff --git a/components/brave_sync/ui/components/toggle/index.tsx b/components/brave_sync/ui/components/toggle/index.tsx deleted file mode 100644 index 92dfe40cd9ee..000000000000 --- a/components/brave_sync/ui/components/toggle/index.tsx +++ /dev/null @@ -1,80 +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/. */ - -import * as React from 'react' -import { StyledWrapper, StyledSlider, StyledBullet, StyleToggle, StyledCheckbox } from './style' - -export interface Props { - testId?: string - checked?: boolean - disabled?: boolean - onChange?: (e: any) => void - id?: string - readOnly?: boolean - autoFocus?: boolean - size: 'large' | 'small' - colorType?: 'dark' | 'light' | 'default' -} - -export interface ToggleState { - checked?: boolean -} - -export class Toggle extends React.PureComponent { - static defaultProps = { - checked: false, - size: 'small', - type: 'default', - disabled: false - } - - constructor (props: Props) { - super(props) - this.state = { checked: props.checked } - this.handleChange = this.handleChange.bind(this) - } - - componentWillReceiveProps (nextProps: Props) { - if ('checked' in nextProps) { - this.setState({ checked: nextProps.checked }) - } - } - - handleChange (e: any) { - const { props } = this - if (props.disabled) { - return - } - if (!('checked' in props)) { - this.setState({ checked: e.target.checked }) - } - - if (props.onChange) { - props.onChange({ target: { checked: e.target.checked } }) - } - } - - render () { - const { id, testId, readOnly, disabled, autoFocus, size, colorType } = this.props - const { checked } = this.state - - return ( - - - - - - - - ) - } -} diff --git a/components/brave_sync/ui/components/toggle/style.ts b/components/brave_sync/ui/components/toggle/style.ts deleted file mode 100644 index 7f7c2e34a4eb..000000000000 --- a/components/brave_sync/ui/components/toggle/style.ts +++ /dev/null @@ -1,76 +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/. */ - -import styled, { css } from 'brave-ui/theme' -import { Props } from './index' -import palette from 'brave-ui/theme/colors' - -export const StyledCheckbox = styled<{}, 'input'>('input')` - -webkit-appearance: none; - position: absolute; - z-index: 99999999; - width: 100%; - height: 100%; - top: 0; - left: 0; - outline-offset: -3px; - outline-color: ${palette.orange400}; - outline-width: 2px; -` - -export const StyledWrapper = styled('div')` - box-sizing: border-box; - display: flex; - position: relative; -` - -export const StyleToggle = styled('div')` - box-sizing: border-box; - position: relative; - display: block; - height: ${(p) => p.size === 'small' ? '16px' : '24px'}; - width: ${(p) => p.size === 'small' ? '28px' : '40px'}; - ${(p) => p.disabled - ? css` - pointer-events: none; - animation: none; - ` : '' - }; -` - -export const StyledSlider = styled('label')` - box-sizing: border-box; - background: ${(p) => p.disabled ? 'rgba(246,246,250,0.1)' : '#C4C7C9'}; - height: ${(p) => p.size === 'small' ? '6px' : '8px'}; - margin-top: ${(p) => p.size === 'small' ? '5px' : '8px'}; - width: 100%; - border-radius: 3px; - display: block; -` - -const transform = (p: Props) => { - let x = p.size === 'small' ? '12px' : '20px' - let y = p.size === 'small' ? '3px' : '4px' - - if (!p.checked) { - x = '-1px' - } - - return { x, y } -} - -const transformBullet = (p: Props) => `${transform(p).x}, calc(-50% - ${transform(p).y})` - -export const StyledBullet = styled('label')` - box-sizing: border-box; - position: relative; - border-radius: 50%; - transition: all .4s ease; - transform: ${p => `translate(${transformBullet(p)})`}; - width: ${p => p.size === 'small' ? '16px' : '20px'}; - height: ${p => p.size === 'small' ? '16px' : '20px'}; - background-color: ${p => p.disabled && 'rgba(235,236,240,0.8)' || p.checked ? '#fb542b' : '#ebecf0'}; - display: block; - box-shadow: 0 3px 3px rgba(0,0,0,0.05); -` diff --git a/components/brave_sync/ui/constants/sync_types.ts b/components/brave_sync/ui/constants/sync_types.ts deleted file mode 100644 index b08758d0f6cc..000000000000 --- a/components/brave_sync/ui/constants/sync_types.ts +++ /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/. */ - -export const enum types { - SYNC_ON_PAGE_LOADED = '@@sync/SYNC_ON_PAGE_LOADED', - SYNC_ON_SHOW_SETTINGS = '@@sync/SYNC_ON_SHOW_SETTINGS', - SYNC_ON_HAVE_SYNC_WORDS = '@@sync/SYNC_ON_HAVE_SYNC_WORDS', - SYNC_ON_HAVE_SEED_FOR_QR_CODE = '@@sync/SYNC_ON_HAVE_SEED_FOR_QR_CODE', - SYNC_ON_SETUP_NEW_TO_SYNC = '@@sync/SYNC_ON_SETUP_NEW_TO_SYNC', - SYNC_ON_GENERATE_QR_CODE_IMAGE_SOURCE = '@@sync/SYNC_ON_GENERATE_QR_CODE_IMAGE_SOURCE', - SYNC_ON_REMOVE_DEVICE = '@@sync/SYNC_ON_REMOVE_DEVICE', - SYNC_ON_RESET = '@@sync/SYNC_ON_RESET', - SYNC_BOOKMARKS = '@@sync/SYNC_BOOKMARKS', - SYNC_SAVED_SITE_SETTINGS = '@@sync/SYNC_SAVED_SITE_SETTINGS', - SYNC_BROWSING_HISTORY = '@@sync/SYNC_BROWSING_HISTORY', - SYNC_SETUP_SYNC_HAVE_CODE = '@@sync/SYNC_SETUP_SYNC_HAVE_CODE', - SYNC_SETUP_ERROR = '@@sync/SYNC_SETUP_ERROR', - SYNC_CLEAR_SETUP_ERROR = '@@sync/SYNC_CLEAR_SETUP_ERROR', - SYNC_ON_LOG_MESSAGE = '@@sync/SYNC_ON_LOG_MESSAGE' -} diff --git a/components/brave_sync/ui/containers/app.tsx b/components/brave_sync/ui/containers/app.tsx deleted file mode 100644 index 9e02e91e1389..000000000000 --- a/components/brave_sync/ui/containers/app.tsx +++ /dev/null @@ -1,62 +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/. */ - -import * as React from 'react' -import { bindActionCreators, Dispatch } from 'redux' -import { connect } from 'react-redux' - -// Component groups -import DisabledContent from './disabledContent' -import EnabledContent from './enabledContent' - -// Utils -import * as syncActions from '../actions/sync_actions' - -// Assets -require('../../../../ui/webui/resources/fonts/muli.css') -require('../../../../ui/webui/resources/fonts/poppins.css') -require('emptykit.css') - -interface Props { - syncData: Sync.State - actions: any -} - -export class SyncPage extends React.PureComponent { - componentDidMount () { - // Inform the back-end that Sync can be loaded - this.props.actions.onPageLoaded() - } - - render () { - const { syncData, actions } = this.props - - if (!syncData) { - return null - } - - return ( -
- { - syncData.isSyncConfigured - ? - : - } -
- ) - } -} - -export const mapStateToProps = (state: Sync.ApplicationState) => ({ - syncData: state.syncData -}) - -export const mapDispatchToProps = (dispatch: Dispatch) => ({ - actions: bindActionCreators(syncActions, dispatch) -}) - -export default connect( - mapStateToProps, - mapDispatchToProps -)(SyncPage) diff --git a/components/brave_sync/ui/containers/commonDialogs/areYouSure.tsx b/components/brave_sync/ui/containers/commonDialogs/areYouSure.tsx deleted file mode 100644 index 3550bff5fef5..000000000000 --- a/components/brave_sync/ui/containers/commonDialogs/areYouSure.tsx +++ /dev/null @@ -1,35 +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/. */ - -import * as React from 'react' - -// Components -import { AlertBox } from 'brave-ui' - -// Feature-specific components -import { Title } from '../../components' - -// Utils -import { getLocale } from '../../../../common/locale' - -interface Props { - onClickOk: () => void - onClickCancel: () => void -} - -export default class AreYouSure extends React.PureComponent { - render () { - const { onClickOk, onClickCancel } = this.props - return ( - - {getLocale('areYouSure')} - - ) - } -} diff --git a/components/brave_sync/ui/containers/disabledContent.tsx b/components/brave_sync/ui/containers/disabledContent.tsx deleted file mode 100644 index eef5a08c99f0..000000000000 --- a/components/brave_sync/ui/containers/disabledContent.tsx +++ /dev/null @@ -1,115 +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/. */ - -import * as React from 'react' - -// Components -import { Button } from 'brave-ui' -import { LoaderIcon } from 'brave-ui/components/icons' - -// Component-specific components -import { - Main, - Title, - DisabledContentButtonGrid, - TableGrid, - Paragraph, - SyncCard, - SyncCardContent, - DisabledContent -} from '../components' - -import { SyncStartIcon } from '../components/images' - -// Modals -import EnterSyncCodeModal from './modals/enterSyncCode' - -// Utils -import { getLocale } from '../../../common/locale' - -interface Props { - syncData: Sync.State - actions: any -} - -interface State { - newToSync: boolean - existingSyncCode: boolean -} - -export default class SyncDisabledContent extends React.PureComponent { - constructor (props: Props) { - super(props) - this.state = { - newToSync: false, - existingSyncCode: false - } - } - - onClickNewSyncChainButton = () => { - this.setState({ newToSync: !this.state.newToSync }) - // once the screen is rendered, create a sync chain. - // this allow us to request the qr code and sync words immediately - const { thisDeviceName } = this.props.syncData - if (thisDeviceName === '') { - this.props.actions.onSetupNewToSync('') - } - } - - onClickEnterSyncChainCodeButton = () => { - this.setState({ existingSyncCode: !this.state.existingSyncCode }) - } - - render () { - const { actions, syncData } = this.props - const { newToSync, existingSyncCode } = this.state - - if (!syncData) { - return null - } - - return ( - -
- { - existingSyncCode - ? - : null - } - - - - -
- {getLocale('syncTitle')} - {getLocale('syncDescription')} - -
-
-
-
-
-
- ) - } -} diff --git a/components/brave_sync/ui/containers/enabledContent.tsx b/components/brave_sync/ui/containers/enabledContent.tsx deleted file mode 100644 index fd6779108b77..000000000000 --- a/components/brave_sync/ui/containers/enabledContent.tsx +++ /dev/null @@ -1,335 +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/. */ - -import * as React from 'react' - -// Components -import { Button, AlertBox } from 'brave-ui' -import { CloseCircleIcon } from 'brave-ui/components/icons' -import Table, { Cell, Row } from 'brave-ui/components/dataTables/table' - -// Feature-specific components -import { - Main, - Title, - Paragraph, - SectionBlock, - SubTitle, - TableRowDevice, - TableRowRemove, - TableRowRemoveButton, - TableRowToggleButton, - TableGrid, - TableButtonGrid, - EnabledContent, - SyncCardContent, - SyncCard, - Toggle -} from '../components' - -// Modals -import RemoveDeviceModal from './modals/removeDevice' -import ViewSyncCodeModal from './modals/viewSyncCode' -import ScanCodeModal from './modals/scanCode' -import DeviceTypeModal from './modals/deviceType' -import ResetSyncModal from './modals/resetSync' - -// Utils -import { getLocale } from '../../../common/locale' - -interface Props { - syncData: Sync.State - actions: any -} - -interface State { - removeDevice: boolean - viewSyncCode: boolean - scanCode: boolean - addDevice: boolean - resetSync: boolean - deviceToRemoveName: string | undefined - deviceToRemoveId: string | undefined -} - -export default class SyncEnabledContent extends React.PureComponent { - constructor (props: Props) { - super(props) - this.state = { - removeDevice: false, - viewSyncCode: false, - scanCode: false, - addDevice: false, - resetSync: false, - deviceToRemoveName: '', - deviceToRemoveId: '' - } - } - - componentDidMount () { - this.shouldShowAddDeviceModal() - } - - componentDidUpdate (prevProps: Props) { - if ( - prevProps.syncData.devices.length !== - this.props.syncData.devices.length - ) { - // if devices length changed, users either added - // or removed a device. again, check if they are less than 2 - // so we can remind them again to add a new device - this.shouldShowAddDeviceModal() - } - } - - shouldShowAddDeviceModal = () => { - const { syncData } = this.props - const hasLessThanTwoDevices: boolean = syncData.devices.length < 2 - // if only one device is found, remind the user - // at every page refresh to add a new device - this.setState({ addDevice: hasLessThanTwoDevices }) - } - - getDevicesRows = (devices?: any): Row[] | undefined => { - if (!devices) { - return - } - - return devices.map((device: any): Row => { - const cell: Row = { - content: [ - { content: ( - - {device.name} { - device.id_v2 === this.props.syncData.thisDeviceIdV2 ? getLocale('thisDevice') : null - } - - )}, - { content: device.lastActive }, - { - content: ( - - - - ) - } - ] - } - return cell - }) - } - - get devicesHeader (): Cell[] { - return [ - { content: {getLocale('deviceName')} }, - { content: getLocale('addedOn') }, - { content: {getLocale('remove')} } - ] - } - - get settingsHeader (): Cell[] { - return [ - { content: {getLocale('settings')} }, - { content: '' } - ] - } - - get settingsRows (): Row[] { - return [ - { - content: [ - { content: getLocale('bookmarks') }, - { content: ( - - - - ) } - ] - } - ] - } - - onClickRemoveDeviceButton = (event: React.MouseEvent) => { - if (!event || !event.currentTarget || !event.currentTarget.dataset) { - return - } - const target = event.currentTarget as HTMLButtonElement - this.setState({ - deviceToRemoveName: target.dataset.name, - deviceToRemoveId: target.dataset.idv2, - removeDevice: true - }) - } - - onClickCancelRemoveDeviceButton = () => { - this.setState({ removeDevice: !this.state.removeDevice }) - } - - onUserNoticedError = () => { - this.props.actions.clearSyncSetupError() - } - - onClickCancelChildModals = () => { - this.setState({ scanCode: false, viewSyncCode: false }) - } - - onClickViewSyncCodeButton = () => { - this.setState({ scanCode: false, viewSyncCode: true }) - } - - onClickScanCodeButton = () => { - this.setState({ scanCode: true, viewSyncCode: false }) - } - - onClickAddDeviceButton = () => { - this.setState({ addDevice: !this.state.addDevice }) - } - - onClickResetSyncButton = () => { - this.setState({ resetSync: !this.state.resetSync }) - } - - onSyncBookmarks = (event: React.ChangeEvent) => { - this.props.actions.onSyncBookmarks(event.target.checked) - } - - render () { - const { actions, syncData } = this.props - const { - removeDevice, - viewSyncCode, - scanCode, - addDevice, - resetSync, - deviceToRemoveName, - deviceToRemoveId - } = this.state - - if (!syncData) { - return null - } - - return ( - -
- { - syncData.error === 'ERR_SYNC_INIT_FAILED' - ? - {getLocale('errorSyncInitFailedTitle')} - {getLocale('errorSyncInitFailedDescription')} - - : null - } - { - syncData.error === 'ERR_SYNC_REQUIRES_CORRECT_TIME' - ? - {getLocale('errorSyncRequiresCorrectTimeTitle')} - {getLocale('errorSyncRequiresCorrectTimeDescription')} - - : null - } - { - removeDevice - ? ( - - ) - : null - } - { - viewSyncCode - ? ( - - ) : null - } - { - scanCode - ? ( - - ) : null - } - { - addDevice - ? - : null - } - { - resetSync - ? - : null - } - - - {getLocale('braveSync')} - {getLocale('syncChainDevices')} - - - - Device list is empty -
- -
-