From 3f4d1c0761bd52f45f9d218a642b4355858e4e5b Mon Sep 17 00:00:00 2001 From: AlexeyBarabash Date: Wed, 13 May 2020 18:15:42 +0300 Subject: [PATCH] WIP - some sync v2 operations work on Android: - lots of traces needs to be removed; - can create sync chain; - can display QR code or codewords allowing other devices to connect to the sync chain; - can connect to existing sync chain by codewords or QR code; - doesn't migrate (clean out) Android sync v1 data yet; - doesn't allow to choose categories through UI yet; - requires to redo the reverted brave-core PR #5096 --- .../chrome/browser/BraveSyncWorker.java | 134 +++++- .../settings/BraveSyncScreensPreference.java | 445 ++++++++++++------ browser/android/brave_sync_worker.cc | 217 ++++++++- browser/android/brave_sync_worker.h | 39 +- 4 files changed, 691 insertions(+), 144 deletions(-) diff --git a/android/java/org/chromium/chrome/browser/BraveSyncWorker.java b/android/java/org/chromium/chrome/browser/BraveSyncWorker.java index 96ce4136710a..bf0a38a39fa3 100755 --- a/android/java/org/chromium/chrome/browser/BraveSyncWorker.java +++ b/android/java/org/chromium/chrome/browser/BraveSyncWorker.java @@ -16,6 +16,7 @@ import android.util.JsonToken; import android.webkit.JavascriptInterface; +import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -106,7 +107,7 @@ public class BraveSyncWorker { private static final String DEVICES_NAMES = "devicesNames"; private static final String ORPHAN_BOOKMARKS = "orphanBookmarks"; private static final String THIS_DEVICE_OBJECT_ID = "thisDeviceObjectId"; - public static final int NICEWARE_WORD_COUNT = 16; + //public static final int NICEWARE_WORD_COUNT = 16; public static final int BIP39_WORD_COUNT = 24; private SyncThread mSyncThread; @@ -148,6 +149,36 @@ public class BraveSyncWorker { private String mBulkBookmarkOperations = ""; private String mLatestFetchRequest = ""; + + private long mNativeBraveSyncWorker; + + @CalledByNative + private void setNativePtr(long nativePtr) { +Log.e(TAG, "[BraveSync] BraveSyncWorker.Init nativePtr=" + nativePtr); + assert mNativeBraveSyncWorker == 0; + mNativeBraveSyncWorker = nativePtr; + } + + private void Init() { +Log.e(TAG, "[BraveSync] BraveSyncWorker.Init mNativeBraveSyncWorker=" + mNativeBraveSyncWorker); + if (mNativeBraveSyncWorker == 0) { + nativeInit(); + } + } + + @Override + protected void finalize() { + Destroy(); + } + + private void Destroy() { + if (mNativeBraveSyncWorker != 0) { + nativeDestroy(mNativeBraveSyncWorker); + mNativeBraveSyncWorker = 0; + } + } + + enum NotSyncedRecordsOperation { GetItems, AddItems, DeleteItems } @@ -435,6 +466,10 @@ public BraveSyncWorker(Context context) { mSharedPreferences = ContextUtils.getAppSharedPreferences(); mSyncIsReady = new SyncIsReady(); mSendSyncDataThread = new SendSyncDataThread(); + +Log.e(TAG, "[BraveSync] BraveSyncWorker.CTOR"); + Init(); + if (null != mSendSyncDataThread) { mSendSyncDataThread.start(); } @@ -2941,7 +2976,7 @@ public void cryptoOutputCodeWords(String result) { String[] codeWords = result.replace('\"', ' ').trim().split(" "); - if (NICEWARE_WORD_COUNT != codeWords.length && BIP39_WORD_COUNT != codeWords.length) { + if (/*NICEWARE_WORD_COUNT != codeWords.length && */BIP39_WORD_COUNT != codeWords.length) { Log.e(TAG, "Incorrect number of code words"); if (null != mSyncScreensObserver) { mSyncScreensObserver.onSyncError("Incorrect number of code words"); @@ -2962,6 +2997,81 @@ public void cryptoOutputError(String error) { } } +// public void createNewChain() { +// //mSyncScreensObserver; +// Log.e(TAG, "[BraveSync] createNewChain 000 - before nativeGetSyncCode mNativeBraveSyncWorker="+mNativeBraveSyncWorker); +// //nativeGetSyncCode2(); +// String codeWords = nativeGetSyncCodeWords(mNativeBraveSyncWorker); +// Log.e(TAG, "[BraveSync] createNewChain 001 codeWords="+codeWords); +// +// //public void onSeedReceived(String seed, boolean fromCodeWords, boolean afterInitialization); +// String seedHex = nativeGetSeedHexFromWords(codeWords); +// Log.e(TAG, "[BraveSync] createNewChain 002 mSyncScreensObserver="+mSyncScreensObserver); +// mSyncScreensObserver.onSeedReceived(seedHex, false, true); +// Log.e(TAG, "[BraveSync] createNewChain 003"); +// +// //public void onCodeWordsReceived(String[] codeWords); +// String[] codeWordsArray = codeWords.split(" "); // TODO, AB: don't split +// Log.e(TAG, "[BraveSync] createNewChain 004"); +// mSyncScreensObserver.onCodeWordsReceived(codeWordsArray); +// Log.e(TAG, "[BraveSync] createNewChain 005"); +// } + + //private String mCodephrase; + public String GetCodephrase2() { + // if (mCodephrase == null || mCodephrase.isEmpty()) { + // mCodephrase = nativeGetSyncCodeWords(mNativeBraveSyncWorker); + // } + String codephrase = nativeGetSyncCodeWords(mNativeBraveSyncWorker); +Log.e(TAG, "[BraveSync] GetCodephrase codephrase="+codephrase); + return codephrase; + } +// public void InvalidateCodephrase() { +// Log.e(TAG, "[BraveSync] InvalidateCodephrase 000"); +// mCodephrase = null; +// } + public void SaveCodephrase(String codephrase) { +Log.e(TAG, "[BraveSync] SaveCodephrase codephrase="+codephrase); + nativeSaveCodeWords(mNativeBraveSyncWorker, codephrase); + } + public String GetSeedHex(String codephrase) { + // if (mCodephrase == null || mCodephrase.isEmpty()) { + // mCodephrase = nativeGetSyncCodeWords(mNativeBraveSyncWorker); + // } +Log.e(TAG, "[BraveSync] GetSeedHex codephrase="+codephrase); +Log.e(TAG, "[BraveSync] GetSeedHex hex="+nativeGetSeedHexFromWords(codephrase)); + return nativeGetSeedHexFromWords(codephrase); + } + + public void InitScreensObserver(BraveSyncScreensObserver syncScreensObserver) { + mSyncScreensObserver = syncScreensObserver; + } + + public void HandleShowSetupUI() { +Log.e(TAG, "[BraveSync] HandleShowSetupUI 000"); + nativeHandleShowSetupUI(mNativeBraveSyncWorker); + } + + public boolean IsFirstSetupComplete() { +Log.e(TAG, "[BraveSync] IsFirstSetupComplete 000"); + return nativeIsFirstSetupComplete(mNativeBraveSyncWorker); + } + + // TODO(alexeybarabash): rename + public void OnDidClosePage() { +Log.e(TAG, "[BraveSync] OnDidClosePage 000"); + nativeOnDidClosePage(mNativeBraveSyncWorker); + } + + public void HandleReset() { +Log.e(TAG, "[BraveSync] HandleReset 000"); + nativeHandleReset(mNativeBraveSyncWorker); + } + + // public boolean IsCodephraseValid(String codepharse) { + // return nativeIsCodephraseValid(codepharse); + // } + public void InitJSWebView(BraveSyncScreensObserver syncScreensObserver) { try { synchronized (mSyncIsReady) { @@ -3174,4 +3284,24 @@ private boolean SyncHasBeenSetup() { private native void nativeDeleteByLocalId(String localId); private native void nativeClear(); private native void nativeResetSync(String key); + + private native void nativeInit(); + private native void nativeDestroy(long nativeBraveSyncWorker); + + //private native void nativeCreateSyncChain(); + private native String nativeGetSyncCodeWords(long nativeBraveSyncWorker); + private native void nativeHandleShowSetupUI(long nativeBraveSyncWorker); + + private native String nativeGetSeedHexFromWords(String passphrase); + //private native void nativeGetSyncCode2(); + private native void nativeSaveCodeWords(long nativeBraveSyncWorker, String passphrase); + + private native void nativeOnDidClosePage(long nativeBraveSyncWorker); + + private native boolean nativeIsFirstSetupComplete(long nativeBraveSyncWorker); + + private native void nativeHandleReset(long nativeBraveSyncWorker); + + //private native boolean nativeIsCodephraseValid(String codepharse); + } diff --git a/android/java/org/chromium/chrome/browser/settings/BraveSyncScreensPreference.java b/android/java/org/chromium/chrome/browser/settings/BraveSyncScreensPreference.java index 3e8915aa03ee..e9815bdbec84 100644 --- a/android/java/org/chromium/chrome/browser/settings/BraveSyncScreensPreference.java +++ b/android/java/org/chromium/chrome/browser/settings/BraveSyncScreensPreference.java @@ -70,7 +70,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.BraveActivity; import org.chromium.chrome.browser.BraveRewardsHelper; -//import org.chromium.chrome.browser.BraveSyncWorker; +import org.chromium.chrome.browser.BraveSyncWorker; + // TODO(sergz): Uncomment when we fully migrate on sync v2. Had a headache // that pref calls should be called from UI thread only. It would lead // to significant changes in the current javascript based BraveSyncWorker @@ -89,10 +90,12 @@ import java.io.IOException; import java.lang.Runnable; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Timer; import java.util.TimerTask; + /** * Settings fragment that allows to control Sync functionality. */ @@ -191,6 +194,10 @@ public void onConfigurationChanged(Configuration newConfig) { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onCreateView"); + + InvalidateCodephrase(); + if (ensureCameraPermission()) { createCameraSource(true, false); } @@ -237,6 +244,7 @@ public void onRequestPermissionsResult(int requestCode, @Override public void onActivityCreated(Bundle savedInstanceState) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onActivityCreated savedInstanceState=" + savedInstanceState); getActivity().setTitle(R.string.sign_in_sync); // mDeviceName = BravePrefServiceBridge.getInstance().getSyncDeviceName(); @@ -274,114 +282,138 @@ public void run() { } @Override - public void onSeedReceived(String seed, boolean fromCodeWords, boolean afterInitialization) { - // try { - // if (fromCodeWords) { - // assert !afterInitialization; - // if (!isBarCodeValid(seed, false)) { - // showEndDialog(getResources().getString(R.string.sync_device_failure)); - // } - // //Log.i(TAG, "!!!received seed == " + seed); + public void onSeedReceived(/*String seedObs, */String seedHex, boolean fromCodeWords, boolean afterInitialization) { + Log.e(TAG, "onSeedReceived 000 seedHex=" + seedHex + " fromCodeWords="+fromCodeWords+" afterInitialization="+afterInitialization); +//onSeedReceived 000 seed=null fromCodeWords=false afterInitialization=true + try { + if (fromCodeWords) { +Log.e(TAG, "onSeedReceived 101"); + assert !afterInitialization; + + if (!isBarCodeValid(seedHex, true)) { +Log.e(TAG, "onSeedReceived 102"); + showEndDialog(getResources().getString(R.string.sync_device_failure)); + } +Log.e(TAG, "onSeedReceived 103"); + Log.i(TAG, "!!!received seedHex == " + seedHex); +// Below how it acts on DT + // HandleShowSetupUI => Prefs::SetSyncEnabled + // => brave_sync::prefs::Prefs::GetSeed() + // + // => HandleSetSyncCode + // + + + + // // Save seed and deviceId in preferences // SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences(BraveSyncWorker.PREF_NAME, 0); // SharedPreferences.Editor editor = sharedPref.edit(); // editor.putString(BraveSyncWorker.PREF_SEED, seed); // editor.apply(); - // if (null == getActivity()) { - // return; - // } - // getActivity().runOnUiThread(new Runnable() { - // @Override - // public void run() { - // cancelTimeoutTimer(); - // BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); - // // if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { - // // mainActivity.mBraveSyncWorker.SetSyncEnabled(true); - // // mainActivity.mBraveSyncWorker.InitSync(true, false); - // // } - // setAppropriateView(); - // } - // }); - // } else if (afterInitialization) { - // assert !fromCodeWords; - // if (null != seed && !seed.isEmpty()) { - // if ((null != mScrollViewAddMobileDevice) && (View.VISIBLE == mScrollViewAddMobileDevice.getVisibility())) { - // String[] seeds = seed.split(","); - // if (seeds.length != 32) { - // Log.e(TAG, "Incorrect seed for QR code"); - // } - // String qrData = ""; - // for (String s : seeds) { - // String hex = Integer.toHexString(Integer.parseInt(s.trim(), 10)); - // if (hex.length() == 1) { - // hex = "0" + hex; - // } - // qrData += hex; - // } - // final String qrDataFinal = qrData; - // //Log.i(TAG, "Generate QR with data: " + qrDataFinal); - // new Thread(new Runnable() { - // @Override - // public void run() { - // // Generate QR code - // BitMatrix result; - // try { - // result = new MultiFormatWriter().encode(qrDataFinal, BarcodeFormat.QR_CODE, WIDTH, WIDTH, null); - // } catch (WriterException e) { - // Log.e(TAG, "QR code unsupported format: " + e); - // return; - // } - // int w = result.getWidth(); - // int h = result.getHeight(); - // int[] pixels = new int[w * h]; - // for (int y = 0; y < h; y++) { - // int offset = y * w; - // for (int x = 0; x < w; x++) { - // pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; - // } - // } - // Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); - // bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h); - // getActivity().runOnUiThread(new Runnable() { - // @Override - // public void run() { - // cancelTimeoutTimer(); - // BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); - // if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { - // mainActivity.mBraveSyncWorker.SetSyncEnabled(true); - // } - // mQRCodeImage.setImageBitmap(bitmap); - // mQRCodeImage.invalidate(); - // } - // }); - // } - // }).start(); - // } else if ((null != mScrollViewAddLaptop) && (View.VISIBLE == mScrollViewAddLaptop.getVisibility())) { - // if (null == getActivity()) { - // return; - // } - // getActivity().runOnUiThread(new Runnable() { - // @Override - // public void run() { - // BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); - // if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { - // mainActivity.mBraveSyncWorker.GetCodeWords(); - // } - // } - // }); - // } - // } - // } else { - // Log.e(TAG, "Unknown flag on receiving seed"); - // assert false; - // } - // } catch(Exception exc) { - // Log.e(TAG, "onSeedReceived exception: " + exc); - // } + if (null == getActivity()) { + return; + } + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + //cancelTimeoutTimer(); + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { + // mainActivity.mBraveSyncWorker.SetSyncEnabled(true); + // mainActivity.mBraveSyncWorker.InitSync(true, false); + + //mainActivity.mBraveSyncWorker.SaveCodephrase(); + mainActivity.mBraveSyncWorker.SaveCodephrase(GetCodephrase()); + mainActivity.mBraveSyncWorker.OnDidClosePage(); + } + setAppropriateView(); + } + }); + } else if (afterInitialization) { +Log.e(TAG, "onSeedReceived 002"); + assert !fromCodeWords; + //if (null != seed && !seed.isEmpty()) { + if (null != seedHex && !seedHex.isEmpty()) { +Log.e(TAG, "onSeedReceived 003 mScrollViewAddMobileDevice="+mScrollViewAddMobileDevice); + if ((null != mScrollViewAddMobileDevice) && (View.VISIBLE == mScrollViewAddMobileDevice.getVisibility())) { + // String[] seeds = seed.split(","); + // if (seeds.length != 32) { + // Log.e(TAG, "Incorrect seed for QR code"); + // } + // String qrData = ""; + // for (String s : seeds) { + // String hex = Integer.toHexString(Integer.parseInt(s.trim(), 10)); + // if (hex.length() == 1) { + // hex = "0" + hex; + // } + // qrData += hex; + // } + final String qrDataFinal = seedHex; + //Log.i(TAG, "Generate QR with data: " + qrDataFinal); + new Thread(new Runnable() { + @Override + public void run() { + // Generate QR code + BitMatrix result; + try { + result = new MultiFormatWriter().encode(qrDataFinal, BarcodeFormat.QR_CODE, WIDTH, WIDTH, null); + } catch (WriterException e) { + Log.e(TAG, "QR code unsupported format: " + e); + return; + } + int w = result.getWidth(); + int h = result.getHeight(); + int[] pixels = new int[w * h]; + for (int y = 0; y < h; y++) { + int offset = y * w; + for (int x = 0; x < w; x++) { + pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; + } + } + Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); + bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h); + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { +// cancelTimeoutTimer(); + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { + mainActivity.mBraveSyncWorker.SetSyncEnabled(true); + } + mQRCodeImage.setImageBitmap(bitmap); + mQRCodeImage.invalidate(); + } + }); + } + }).start(); + } else if ((null != mScrollViewAddLaptop) && (View.VISIBLE == mScrollViewAddLaptop.getVisibility())) { + if (null == getActivity()) { + return; + } + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { + mainActivity.mBraveSyncWorker.GetCodeWords(); + } + } + }); + } + } + } else { + Log.e(TAG, "Unknown flag on receiving seed"); + assert false; + } + } catch(Exception exc) { + Log.e(TAG, "onSeedReceived exception: " + exc); + } } @Override public void onCodeWordsReceived(String[] codeWords) { + Log.e(TAG, "onCodeWordsReceived 000 codeWords=" + Arrays.toString(codeWords)); try { if (null == getActivity()) { return; @@ -398,6 +430,7 @@ public void run() { for (int i = 0; i < codeWords.length; i++) { words = words + " " + codeWords[i].trim(); } +Log.e(TAG, "onCodeWordsReceived words=" + words); mBraveSyncAddDeviceCodeWords.setText(words.trim()); } }); @@ -523,8 +556,11 @@ public boolean shouldLoadDevices() { } }; } - mainActivity.mBraveSyncWorker.InitJSWebView(mSyncScreensObserver); + //mainActivity.mBraveSyncWorker.InitJSWebView(mSyncScreensObserver); //mainActivity.mBraveSyncWorker.InitV2(mSyncScreensObserver); + mainActivity.mBraveSyncWorker.InitScreensObserver(mSyncScreensObserver); + + mainActivity.mBraveSyncWorker.HandleShowSetupUI(); } // TODO(sergz): Uncomment sync service impl when we fully migrate on sync v2 // Initialize mSyncServiceObserver @@ -731,15 +767,23 @@ public boolean shouldLoadDevices() { } private void setAppropriateView() { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.setAppropriateView 000"); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); getActivity().setTitle(R.string.sync_category_title); // String seed = BravePrefServiceBridge.getInstance().getSyncSeed(); // SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences(BraveSyncWorker.PREF_NAME, 0); // String seed = sharedPref.getString(BraveSyncWorker.PREF_SEED, null); - String seed = null; - //Log.i(TAG, "setAppropriateView: seed == " + seed); - if (null == seed || seed.isEmpty()) { + //String seed = null; + // String seed = GetCodephrase(); + // Log.i(TAG, "setAppropriateView: seed == " + seed); + // IsFirstSetupComplete + // + // if (null == seed || seed.isEmpty()) { + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); // TODO, AB pull out from rewards + boolean firstSetupComplete = mainActivity.mBraveSyncWorker.IsFirstSetupComplete(); +Log.e(TAG, "[BraveSync] setAppropriateView firstSetupComplete="+firstSetupComplete); + if (!firstSetupComplete) { if (null != mCameraSourcePreview) { mCameraSourcePreview.stop(); } @@ -796,6 +840,7 @@ private void setSyncText(String title, String message, TextView textView) { /** OnClickListener for the clear button. We show an alert dialog to confirm the action */ @Override public void onClick(View v) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onClick"); if ((getActivity() == null) || (v != mScanChainCodeButton && v != mStartNewChainButton && v != mEnterCodeWordsButton && v != mDoneButton && v != mDoneLaptopButton && v != mUseCameraButton && v != mConfirmCodeWordsButton && v != mMobileButton && v != mLaptopButton @@ -805,21 +850,29 @@ public void onClick(View v) { if (mScanChainCodeButton == v) { showAddDeviceNameDialog(false /*createNewChain*/); } else if (mStartNewChainButton == v) { +Log.e(TAG, "[BraveSync] mStartNewChainButton"); // Creating a new chain showAddDeviceNameDialog(true /*createNewChain*/); } else if (mMobileButton == v) { +Log.e(TAG, "[BraveSync] mMobileButton"); setAddMobileDeviceLayout(); } else if (mLaptopButton == v) { +Log.e(TAG, "[BraveSync] mLaptopButton"); setAddLaptopLayout(); } else if (mDoneButton == v) { +Log.e(TAG, "[BraveSync] mDoneButton"); setSyncDoneLayout(); } else if (mDoneLaptopButton == v) { +Log.e(TAG, "[BraveSync] mDoneLaptopButton"); setSyncDoneLayout(); } else if (mUseCameraButton == v) { +Log.e(TAG, "[BraveSync] mUseCameraButton"); setJoinExistingChainLayout(); } else if (mQRCodeButton == v) { +Log.e(TAG, "[BraveSync] mQRCodeButton"); setAddMobileDeviceLayout(); } else if (mCodeWordsButton == v) { +Log.e(TAG, "[BraveSync] mCodeWordsButton"); setAddLaptopLayout(); } else if (mPasteButton == v) { if (null != mCodeWords) { @@ -837,14 +890,53 @@ public void onClick(View v) { Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.brave_sync_copied_text), Toast.LENGTH_LONG).show(); } } else if (mConfirmCodeWordsButton == v) { +;;; +Log.e(TAG, "[BraveSync] mConfirmCodeWordsButton"); BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); String[] words = mCodeWords.getText().toString().trim().replace(" ", " ").replace("\n", " ").split(" "); - // if (BraveSyncWorker.NICEWARE_WORD_COUNT != words.length && BraveSyncWorker.BIP39_WORD_COUNT != words.length) { - // if (null != mSyncScreensObserver) { - // mSyncScreensObserver.onSyncError(getResources().getString(R.string.brave_sync_word_count_error)); - // } - // return; - // } + if (/*BraveSyncWorker.NICEWARE_WORD_COUNT != words.length && */BraveSyncWorker.BIP39_WORD_COUNT != words.length) { +Log.e(TAG, "[BraveSync] mConfirmCodeWordsButton - wrong words count"); + if (null != mSyncScreensObserver) { + mSyncScreensObserver.onSyncError(getResources().getString(R.string.brave_sync_word_count_error)); + } + return; + } +//24 words for now + // + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { + String hexString = mainActivity.mBraveSyncWorker.GetSeedHex(String.join(" ", words)); +Log.e(TAG, "[BraveSync] mConfirmCodeWordsButton - hexString="+hexString); + if (hexString == null || hexString.isEmpty()) { +Log.e(TAG, "[BraveSync] mConfirmCodeWordsButton - wrong codephrase"); + if (null != mSyncScreensObserver) { + mSyncScreensObserver.onSyncError( + "The codeprase is wrong" // TODO(AB): pull into translated string + //getResources().getString(R.string.brave_sync_word_count_error) + ); + } + return; + } + } + + // Need to open a new activity assuming all is good + // BraveSyncWorker.GetNumber => javascript:getBytesFromWords => + // => class JsObjectWordsToBytes cryptoOutput => + // => mSyncScreensObserver.onSeedReceived + // + // String seedHex, boolean fromCodeWords, boolean afterInitialization + // mSyncScreensObserver.onSeedReceived(seedHex, true, false); + mCodephrase = String.join(" ", words); +Log.e(TAG, "[BraveSync] mConfirmCodeWordsButton - mCodephrase="+mCodephrase); + String seedHex = mainActivity.mBraveSyncWorker.GetSeedHex(GetCodephrase()); + if (null == seedHex || seedHex.isEmpty()) { +// startTimeoutTimerWithPopup(getResources().getString(R.string.brave_sync_loading_data_title)); + // Init to receive new seed +// mainActivity.mBraveSyncWorker.InitSync(true, true); + } else { + //String seedHex, boolean fromCodeWords, boolean afterInitialization + mSyncScreensObserver.onSeedReceived(seedHex, true, false); + } + // if (null != mainActivity && null != mainActivity.mBraveSyncWorker && null != words) { // for (int i = 0; i < words.length; i++) { // words[i] = words[i].trim(); @@ -912,15 +1004,23 @@ public void onTextChanged(CharSequence s, int start, int before, int count) { }); } } else if (mRemoveDeviceButton == v) { +Log.e(TAG, "[BraveSync] mRemoveDeviceButton"); + //BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + //mainActivity.mBraveSyncWorker.HandleReset(); + //deleteDeviceDialog(deviceToDelete.mDeviceName, deviceToDelete.mDeviceId, deviceToDelete.mObjectId, mRemoveDeviceButton); + deleteDeviceDialog("This device", "-1", "???", mRemoveDeviceButton); } else if (mAddDeviceButton == v) { +Log.e(TAG, "[BraveSync] mAddDeviceButton"); setNewChainLayout(); } else if (mCancelLoadingButton == v) { +Log.e(TAG, "[BraveSync] mCancelLoadingButton"); cancelLoadingResetAndBack(); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onCheckedChanged isChecked="+isChecked); if ((getActivity() == null) || (buttonView != mSyncSwitchBookmarks)) { Log.w(TAG, "Unknown button"); return; @@ -1045,6 +1145,7 @@ private void startCameraSource() throws SecurityException { @Override public void onResume() { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onResume"); super.onResume(); try { if (null != mCameraSourcePreview && View.GONE != mScrollViewSyncChainCode.getVisibility()) { @@ -1069,6 +1170,7 @@ public boolean onOptionsItemSelected(MenuItem item) { @Override public void onPause() { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onPause"); super.onPause(); if (mCameraSourcePreview != null) { mCameraSourcePreview.stop(); @@ -1079,6 +1181,7 @@ public void onPause() { @Override public void onDestroy() { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onDestroy"); super.onDestroy(); if (mCameraSourcePreview != null) { mCameraSourcePreview.release(); @@ -1086,27 +1189,34 @@ public void onDestroy() { } private boolean isBarCodeValid(String barcode, boolean hexValue) { +Log.e(TAG, "isBarCodeValid 000"); +Log.e(TAG, "isBarCodeValid barcode="+barcode); +Log.e(TAG, "isBarCodeValid hexValue="+hexValue); +Log.e(TAG, "isBarCodeValid barcode.length()="+barcode.length()); if (hexValue && barcode.length() != 64) { +Log.e(TAG, "isBarCodeValid 001 return false"); return false; } else if (!hexValue) { String[] split = barcode.split(","); if (split.length != 32) { +Log.e(TAG, "isBarCodeValid 002 return false"); return false; } } - +Log.e(TAG, "isBarCodeValid 003 return true"); return true; } @Override public void onDetectedQrCode(Barcode barcode) { +Log.e(TAG, "onDetectedQrCode 000"); if (barcode != null) { //Log.i(TAG, "!!!code == " + barcode.displayValue); final String barcodeValue = barcode.displayValue; +Log.e(TAG, "onDetectedQrCode barcodeValue="+barcodeValue); if (!isBarCodeValid(barcodeValue, true)) { showEndDialog(getResources().getString(R.string.brave_sync_device_failure)); showMainSyncScrypt(); - return; } String[] barcodeString = barcodeValue.replaceAll("..(?!$)", "$0 ").split(" "); @@ -1117,6 +1227,15 @@ public void onDetectedQrCode(Barcode barcode) { } seed += String.valueOf(Integer.parseInt(barcodeString[i], 16)); } +Log.e(TAG, "onDetectedQrCode seed="+seed); + + String seedHex = barcodeValue; +Log.e(TAG, "onDetectedQrCode seedHex="+seedHex); + +// String seedHex, boolean fromCodeWords, boolean afterInitialization +mSyncScreensObserver.onSeedReceived(seedHex, true, false); +;;; + //Log.i(TAG, "!!!seed == " + seed); // Save seed and deviceId in preferences // BravePrefServiceBridge.getInstance().setSyncSeed(seed); @@ -1127,6 +1246,7 @@ public void onDetectedQrCode(Barcode barcode) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { +Log.e(TAG, "onDetectedQrCode runOnUiThread.run 000"); BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); // if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { // mainActivity.mBraveSyncWorker.SetSyncEnabled(true); @@ -1144,6 +1264,7 @@ public void run() { } private void showEndDialog(String message) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.showEndDialog message="+message); AlertDialog.Builder alert = new AlertDialog.Builder(getActivity(), R.style.Theme_Chromium_AlertDialog); if (null == alert) { return; @@ -1172,6 +1293,7 @@ public void onClick(DialogInterface dialog, int button) { // } private void showAddDeviceNameDialog(boolean createNewChain) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.showAddDeviceNameDialog createNewChain="+createNewChain); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.add_sync_device_name_dialog, null); @@ -1191,7 +1313,14 @@ public void onClick(DialogInterface dialog, int button) { // SharedPreferences.Editor editor = sharedPref.edit(); // editor.putString(BraveSyncWorker.PREF_SYNC_DEVICE_NAME, mDeviceName); // editor.apply(); +Log.e(TAG, "[BraveSync] showAddDeviceNameDialog mDeviceName="+mDeviceName); +Log.e(TAG, "[BraveSync] showAddDeviceNameDialog createNewChain="+createNewChain); if (createNewChain) { +// BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); +// if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { +// mainActivity.mBraveSyncWorker.createNewChain(); +// } +GetCodephrase(); setNewChainLayout(); } else { setJoinExistingChainLayout(); @@ -1224,6 +1353,7 @@ public void onShow(DialogInterface dialog) { } private void deleteDeviceDialog(String deviceName, String deviceId, String deviceObjectId, View v) { +Log.e(TAG, "[BraveSync] deleteDeviceDialog 000 deviceName=" + deviceName); AlertDialog.Builder alert = new AlertDialog.Builder(getActivity(), R.style.Theme_Chromium_AlertDialog); if (null == alert) { return; @@ -1232,8 +1362,9 @@ private void deleteDeviceDialog(String deviceName, String deviceId, String devic @Override public void onClick(DialogInterface dialog, int button) { if (button == AlertDialog.BUTTON_POSITIVE) { +Log.e(TAG, "[BraveSync] deleteDeviceDialog.onClick BUTTON_POSITIVE"); BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); - // if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { // new Thread() { // @Override // public void run() { @@ -1241,9 +1372,17 @@ public void onClick(DialogInterface dialog, int button) { // mainActivity.mBraveSyncWorker.InterruptSyncSleep(); // } // }.start(); - // v.setEnabled(false); + + // Would go into DeviceResolver => ResetSync => mSyncScreensObserver.onResetSync(); + + mainActivity.mBraveSyncWorker.HandleReset(); + //v.setEnabled(false); - AB: revert this when have the device list + + mSyncScreensObserver.onResetSync(); + + // startTimeoutTimerWithPopup(getResources().getString(R.string.brave_sync_delete_sent)); - // } + } // TODO(sergz): Uncomment sync service impl when we fully migrate on sync v2 // if (null != mSyncService) { // new Thread() { @@ -1302,6 +1441,7 @@ private void setJoinExistingChainLayout() { } private void setNewChainLayout() { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.setNewChainLayout"); getActivity().setTitle(R.string.brave_sync_start_new_chain); if (null != mScrollViewSyncInitial) { mScrollViewSyncInitial.setVisibility(View.GONE); @@ -1335,6 +1475,26 @@ private void cancelLoadingResetAndBack() { // } } + private String mCodephrase; + public String GetCodephrase() { + if (mCodephrase == null || mCodephrase.isEmpty()) { + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); +Log.e(TAG, "[BraveSync] GetCodephrase - ask mainActivity.mBraveSyncWorker"); + mCodephrase = mainActivity.mBraveSyncWorker.GetCodephrase2(); +Log.e(TAG, "[BraveSync] GetCodephrase 003"); + } +Log.e(TAG, "[BraveSync] GetCodephrase mCodephrase="+mCodephrase); + String[] codeWordsArray = mCodephrase.split(" "); // TODO, AB: don't split +Log.e(TAG, "[BraveSync] GetCodephrase 004"); + mSyncScreensObserver.onCodeWordsReceived(codeWordsArray); +Log.e(TAG, "[BraveSync] GetCodephrase 005"); + return mCodephrase; + } + public void InvalidateCodephrase() { +Log.e(TAG, "[BraveSync] InvalidateCodephrase 000"); + mCodephrase = null; + } + private void setAddMobileDeviceLayout() { getActivity().setTitle(R.string.brave_sync_btn_mobile); if (null != mBraveSyncTextViewAddMobileDevice) { @@ -1379,23 +1539,28 @@ public void run() { // } // } - // BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); - // if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { - // SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences(BraveSyncWorker.PREF_NAME, 0); - // String seed = sharedPref.getString(BraveSyncWorker.PREF_SEED, null); - // if (null == seed || seed.isEmpty()) { - // startTimeoutTimerWithPopup(getResources().getString(R.string.brave_sync_loading_data_title)); - // // Init to receive new seed - // mainActivity.mBraveSyncWorker.InitSync(true, true); - // } else { - // mSyncScreensObserver.onSeedReceived(seed, false, true); - // } - // } + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { + // SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences(BraveSyncWorker.PREF_NAME, 0); + // String seed = sharedPref.getString(BraveSyncWorker.PREF_SEED, null); + + //String seedHex = mainActivity.mBraveSyncWorker.GetSeedHex(); + String seedHex = mainActivity.mBraveSyncWorker.GetSeedHex(GetCodephrase()); + if (null == seedHex || seedHex.isEmpty()) { +// startTimeoutTimerWithPopup(getResources().getString(R.string.brave_sync_loading_data_title)); + // Init to receive new seed +// mainActivity.mBraveSyncWorker.InitSync(true, true); + } else { + //String seedHex, boolean fromCodeWords, boolean afterInitialization + mSyncScreensObserver.onSeedReceived(seedHex, false, true); + } + } } }); } private void setAddLaptopLayout() { +Log.e(TAG, "[BraveSync] setAddLaptopLayout 000"); getActivity().setTitle(R.string.brave_sync_btn_laptop); if (null != mBraveSyncTextViewAddLaptop) { setSyncText(getResources().getString(R.string.brave_sync_add_laptop_text_title), @@ -1431,17 +1596,22 @@ private void setAddLaptopLayout() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { +Log.e(TAG, "[BraveSync] setAddLaptopLayout.runOnUiThread.run 000"); BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); - if (null != mainActivity /*&& null != mainActivity.mBraveSyncWorker*/) { + if (null != mainActivity && null != mainActivity.mBraveSyncWorker) { // SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences(BraveSyncWorker.PREF_NAME, 0); // String seed = sharedPref.getString(BraveSyncWorker.PREF_SEED, null); - String seed = null; - if (null == seed || seed.isEmpty()) { + //String seedHex = null; +Log.e(TAG, "[BraveSync] setAddLaptopLayout.runOnUiThread.run GetCodephrase()="+GetCodephrase()); + String seedHex = mainActivity.mBraveSyncWorker.GetSeedHex(GetCodephrase()); +Log.e(TAG, "[BraveSync] setAddLaptopLayout.runOnUiThread.run seedHex="+seedHex); + if (null == seedHex || seedHex.isEmpty()) { //startTimeoutTimerWithPopup(getResources().getString(R.string.brave_sync_loading_data_title)); // Init to receive new seed //mainActivity.mBraveSyncWorker.InitSync(true, true); } else { - mSyncScreensObserver.onSeedReceived(seed, false, true); + //String seedHex, boolean fromCodeWords, boolean afterInitialization + mSyncScreensObserver.onSeedReceived(seedHex, false, true); } } // TODO(sergz): use service when we migrate to sync v2 @@ -1487,6 +1657,12 @@ private void dismissCancelLoadingButton() { } private void setSyncDoneLayout() { +Log.e(TAG, "[BraveSync] setSyncDoneLayout 000"); + BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + assert (null != mainActivity && null != mainActivity.mBraveSyncWorker); + mainActivity.mBraveSyncWorker.SaveCodephrase(GetCodephrase()); + mainActivity.mBraveSyncWorker.OnDidClosePage(); + getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); getActivity().setTitle(R.string.sync_category_title); if (null != mCameraSourcePreview) { @@ -1521,15 +1697,16 @@ private void setSyncDoneLayout() { // } // } if (null != mRemoveDeviceButton) { +Log.e(TAG, "[BraveSync] setSyncDoneLayout mRemoveDeviceButton.setVisibility(View.GONE)"); // It should become visible as soon as we get all devices info - mRemoveDeviceButton.setVisibility(View.GONE); +// mRemoveDeviceButton.setVisibility(View.GONE); - AB: want to see the buton to test LEAVE } // TODO(sergz): Uncomment sync service impl when we fully migrate on sync v2 // if (null != mSyncService) { // mBraveSyncTextDevicesTitle.setText(getResources().getString(R.string.brave_sync_loading_devices_title)); // } - BraveActivity mainActivity = BraveRewardsHelper.getBraveActivity(); + if (null != mainActivity/* && null != mainActivity.mBraveSyncWorker*/) { mBraveSyncTextDevicesTitle.setText(getResources().getString(R.string.brave_sync_loading_devices_title)); // mainActivity.mBraveSyncWorker.InterruptSyncSleep(); @@ -1596,6 +1773,7 @@ private Context getBaseApplicationContext() { // Handles 'Back' button. Returns true if it is handled, false otherwise. @Override public boolean onBackPressed() { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onBackPressed"); if ((View.VISIBLE == mScrollViewSyncChainCode.getVisibility()) || (View.VISIBLE == mScrollViewSyncStartChain.getVisibility())) { setAppropriateView(); @@ -1617,6 +1795,7 @@ public void onCreatePreferences(Bundle bundle, String s) {} @Override public void onGetSettingsAndDevices(ArrayList devices) { +Log.e(TAG, "[BraveSync] BraveSyncScreensPreference.onGetSettingsAndDevices"); try { if (null == getActivity()) { return; diff --git a/browser/android/brave_sync_worker.cc b/browser/android/brave_sync_worker.cc index 68fe228e09cd..1c624d68ece8 100644 --- a/browser/android/brave_sync_worker.cc +++ b/browser/android/brave_sync_worker.cc @@ -6,22 +6,38 @@ #include "brave/browser/android/brave_sync_worker.h" #include +//#include #include "base/android/jni_android.h" #include "base/android/jni_string.h" +#include "base/strings/string_number_conversions.h" + //#include "base/files/file_util.h" //#include "base/json/json_reader.h" -//#include "base/path_service.h" +#include "base/path_service.h" #include "brave/build/android/jni_headers/BraveSyncWorker_jni.h" -//#include "third_party/leveldatabase/src/include/leveldb/db.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/profiles/profile_manager.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/unified_consent/unified_consent_metrics.h" + +#include "third_party/leveldatabase/src/include/leveldb/db.h" + namespace chrome { namespace android { -//#define DB_FILE_NAME "brave_sync_db" +#define DB_FILE_NAME "brave_sync_db" // need this to clear V1 stuff on migrating -// leveldb::DB* g_level_db = nullptr; -// static std::mutex* g_pLevel_db_init_mutex = new std::mutex(); +leveldb::DB* g_level_db = nullptr; +static std::mutex* g_pLevel_db_init_mutex = new std::mutex(); // namespace { // @@ -43,13 +59,33 @@ namespace android { // // } // namespace -BraveSyncWorker::BraveSyncWorker(JNIEnv* env, jobject obj): - weak_java_shields_config_(env, obj) { +BraveSyncWorker::BraveSyncWorker(JNIEnv* env, + //jobject obj + const base::android::JavaRef& obj +): + weak_java_brave_sync_worker_(env, obj) { + DLOG(ERROR) << "[BraveSync] " << __func__ << " CTOR 000"; + + //Java_BraveSyncWorker_setNativePtr + Java_BraveSyncWorker_setNativePtr(env, obj, + reinterpret_cast(this)); + DLOG(ERROR) << "[BraveSync] " << __func__ << " CTOR done setNativePtr"; + profile_ = + ProfileManager::GetActiveUserProfile()->GetOriginalProfile(); + DLOG(ERROR) << "[BraveSync] " << __func__ << " profile_="<& jcaller) { + delete this; +} + + + // void CreateOpenDatabase() { // if (!g_pLevel_db_init_mutex) { // return; @@ -174,5 +210,172 @@ static void JNI_BraveSyncWorker_ResetSync(JNIEnv* env, // base::android::ConvertJavaStringToUTF8(key)); } +//static void JNI_BraveSyncWorker_nativeGetSyncCode +base::android::ScopedJavaLocalRef BraveSyncWorker::GetSyncCodeWords + (JNIEnv* env, + const base::android::JavaParamRef& jcaller) { +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000 profile_="<GetPrefs()); + std::string sync_code = brave_sync_prefs.GetSeed(); +DLOG(ERROR) << "[BraveSync] " << __func__ << " sync_code=" << sync_code; + if (sync_code.empty()) { + std::vector seed = brave_sync::crypto::GetSeed(); + sync_code = brave_sync::crypto::PassphraseFromBytes32(seed); +DLOG(ERROR) << "[BraveSync] " << __func__ << " sync_code=" << sync_code; + } + + return base::android::ConvertUTF8ToJavaString(env, sync_code); +} + +void BraveSyncWorker::SaveCodeWords(JNIEnv* env, + const base::android::JavaParamRef& jcaller, + const base::android::JavaParamRef& passphrase) { + std::string str_passphrase = base::android::ConvertJavaStringToUTF8(passphrase); +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000 str_passphrase="< seed; + if (!brave_sync::crypto::PassphraseToBytes32(str_passphrase, &seed)) { + LOG(ERROR) << "invalid sync code:" << str_passphrase; + // + return; + } + + brave_sync::prefs::Prefs brave_sync_prefs(profile_->GetPrefs()); + + brave_sync_prefs.SetSeed(str_passphrase); +} + +// see PeopleHandler::GetSyncService() +syncer::SyncService* BraveSyncWorker::GetSyncService() const { +DLOG(ERROR) << "[BraveSync] " << __func__ << " ProfileSyncServiceFactory::IsSyncAllowed(profile_)="<GetPrefs()); + if (!brave_sync_prefs.IsSyncV2Migrated()) { + service->StopAndClear(); + brave_sync_prefs.SetSyncV2Migrated(true); + } + brave_sync_prefs.SetSyncEnabled(true); + // } BRAVE_HANDLE_SHOW_SETUP_UI + + if (service) + service->GetUserSettings()->SetSyncRequested(true); + + // ?? PushSyncPrefs(); +} + +// PeopleHandler::MarkFirstSetupComplete +void BraveSyncWorker::MarkFirstSetupComplete() { +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000"; + syncer::SyncService* service = GetSyncService(); +DLOG(ERROR) << "[BraveSync] " << __func__ << " service="<GetUserSettings()->SetSyncRequested(true); + + // If the first-time setup is already complete, there's nothing else to do. + if (service->GetUserSettings()->IsFirstSetupComplete()) + return; +DLOG(ERROR) << "[BraveSync] " << __func__ << " 002"; + unified_consent::metrics::RecordSyncSetupDataTypesHistrogam( + service->GetUserSettings(), profile_->GetPrefs()); +DLOG(ERROR) << "[BraveSync] " << __func__ << " 003"; + // We're done configuring, so notify SyncService that it is OK to start + // syncing. + service->GetUserSettings()->SetFirstSetupComplete( + syncer::SyncFirstSetupCompleteSource::ADVANCED_FLOW_CONFIRM); + //FireWebUIListener("sync-settings-saved"); +DLOG(ERROR) << "[BraveSync] " << __func__ << " 004"; +} + +// PeopleHandler::OnDidClosePage // TODO, AB: rename +void BraveSyncWorker::OnDidClosePage(JNIEnv* env, + const base::android::JavaParamRef& jcaller) { +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000"; + MarkFirstSetupComplete(); +} + +bool BraveSyncWorker::IsFirstSetupComplete(JNIEnv* env, + const base::android::JavaParamRef& jcaller) { + syncer::SyncService* sync_service = GetSyncService(); + DLOG(ERROR) << "[BraveSync] " << __func__ << " will ret " << + (sync_service && sync_service->GetUserSettings()->IsFirstSetupComplete()); + return sync_service && + sync_service->GetUserSettings()->IsFirstSetupComplete(); +} + +void BraveSyncWorker::HandleReset(JNIEnv* env, + const base::android::JavaParamRef& jcaller) { + // PeopleHandler::HandleReset +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000"; + syncer::SyncService* sync_service = GetSyncService(); +DLOG(ERROR) << "[BraveSync] " << __func__ << " sync_service=" << sync_service; + if (sync_service) { + sync_service->GetUserSettings()->SetSyncRequested(false); + sync_service->StopAndClear(); + } + brave_sync::prefs::Prefs brave_sync_prefs(profile_->GetPrefs()); +DLOG(ERROR) << "[BraveSync] " << __func__ << " invoke brave_sync_prefs.Clear()"; + brave_sync_prefs.Clear(); + + // Sync prefs will be clear in ProfileSyncService::StopImpl +} + + +// static void JNI_BraveSyncWorker_GetSyncCode2( +// JNIEnv* env, +// const base::android::JavaParamRef& jcaller) { +// DLOG(ERROR) << "[BraveSync] " << __func__ << " 000"; +// } + +static void JNI_BraveSyncWorker_Init( + JNIEnv* env, + const base::android::JavaParamRef& jcaller) { +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000"; + new BraveSyncWorker(env, jcaller); +} + +base::android::ScopedJavaLocalRef JNI_BraveSyncWorker_GetSeedHexFromWords( + JNIEnv* env, + const base::android::JavaParamRef& jcaller, + const base::android::JavaParamRef& seed_words) { +DLOG(ERROR) << "[BraveSync] " << __func__ << " 000"; + std::string str_seed_words = base::android::ConvertJavaStringToUTF8( + seed_words); + DCHECK(!str_seed_words.empty()); +DLOG(ERROR) << "[BraveSync] " << __func__ << " str_seed_words="< bytes; + if (brave_sync::crypto::PassphraseToBytes32(str_seed_words, &bytes)) { + DCHECK_EQ(bytes.size(), 32u); + sync_code_hex = base::HexEncode(&bytes.at(0), bytes.size()); + } else { + DLOG(WARNING) << "[BraveSync] " << __func__ << + " PassphraseToBytes32 failed for " << str_seed_words; + } +DLOG(ERROR) << "[BraveSync] " << __func__ << " sync_code_hex="< #include "base/android/jni_weak_ref.h" +class Profile; + +namespace syncer { + class SyncService; +} + namespace chrome { namespace android { class BraveSyncWorker { public: - BraveSyncWorker(JNIEnv* env, jobject obj); + BraveSyncWorker(JNIEnv* env, + //jobject obj + const base::android::JavaRef& obj + ); ~BraveSyncWorker(); + void Destroy(JNIEnv* env, + const base::android::JavaParamRef& jcaller); + + base::android::ScopedJavaLocalRef GetSyncCodeWords(JNIEnv* env, + const base::android::JavaParamRef& jcaller); + + void SaveCodeWords(JNIEnv* env, + const base::android::JavaParamRef& jcaller, + const base::android::JavaParamRef& passphrase); + + void HandleShowSetupUI(JNIEnv* env, + const base::android::JavaParamRef& jcaller); + + void OnDidClosePage(JNIEnv* env, + const base::android::JavaParamRef& jcaller); + + bool IsFirstSetupComplete(JNIEnv* env, + const base::android::JavaParamRef& jcaller); + + void HandleReset(JNIEnv* env, + const base::android::JavaParamRef& jcaller); + private: - JavaObjectWeakGlobalRef weak_java_shields_config_; // shields? + syncer::SyncService* GetSyncService() const; + void MarkFirstSetupComplete(); + + JavaObjectWeakGlobalRef weak_java_brave_sync_worker_; + Profile* profile_ = nullptr; }; } // namespace android