11package com .omni .wallet .base ;
22
33
4+ import android .accounts .Account ;
5+ import android .app .Activity ;
46import android .app .ActivityManager ;
57import android .content .Context ;
8+ import android .content .Intent ;
9+ import android .os .Environment ;
10+ import android .support .annotation .NonNull ;
611import android .util .Log ;
712
13+ import com .google .android .gms .auth .api .signin .GoogleSignIn ;
14+ import com .google .android .gms .auth .api .signin .GoogleSignInClient ;
15+ import com .google .android .gms .auth .api .signin .GoogleSignInOptions ;
16+ import com .google .android .gms .common .api .Scope ;
17+ import com .google .android .gms .tasks .OnFailureListener ;
18+ import com .google .android .gms .tasks .OnSuccessListener ;
19+ import com .google .api .client .extensions .android .http .AndroidHttp ;
20+ import com .google .api .client .googleapis .extensions .android .gms .auth .GoogleAccountCredential ;
21+ import com .google .api .client .json .gson .GsonFactory ;
22+ import com .google .api .services .drive .Drive ;
23+ import com .google .api .services .drive .DriveScopes ;
24+ import com .omni .wallet .baselibrary .utils .LogUtils ;
25+ import com .omni .wallet .baselibrary .utils .StringUtils ;
26+ import com .omni .wallet .baselibrary .utils .ToastUtils ;
827import com .omni .wallet .common .ConstantInOB ;
28+ import com .omni .wallet .common .ConstantWithNetwork ;
929import com .omni .wallet .framelibrary .base .FrameBaseActivity ;
30+ import com .omni .wallet .framelibrary .entity .User ;
31+ import com .omni .wallet .utils .DriveServiceHelper ;
32+ import com .omni .wallet .utils .MoveCacheFileToFileObd ;
1033import com .omni .wallet .view .dialog .UnlockDialog ;
1134
35+ import java .io .File ;
36+ import java .util .Collections ;
1237import java .util .List ;
1338
1439/**
@@ -22,9 +47,12 @@ public abstract class AppBaseActivity extends FrameBaseActivity {
2247 private static boolean stopApp = false ;
2348 UnlockDialog mUnlockDialog ;
2449
25- private String getRunningActivityName (){
26- ActivityManager activityManager =(ActivityManager ) getSystemService (Context .ACTIVITY_SERVICE );
27- String runningActivity =activityManager .getRunningTasks (1 ).get (0 ).topActivity .getClassName ();
50+ private static final int REQUEST_CODE_SIGN_IN = 30 ;
51+ private DriveServiceHelper mDriveServiceHelper ;
52+
53+ public String getRunningActivityName () {
54+ ActivityManager activityManager = (ActivityManager ) getSystemService (Context .ACTIVITY_SERVICE );
55+ String runningActivity = activityManager .getRunningTasks (1 ).get (0 ).topActivity .getClassName ();
2856 return runningActivity ;
2957 }
3058
@@ -57,12 +85,11 @@ public boolean isRunningForeground() {
5785 return false ;
5886 }
5987
60-
61- @ Override
88+ @ Override
6289 protected void onStop () {
6390 super .onStop ();
6491 boolean isRunningSelf = isRunningForeground ();
65- if (!isRunningSelf ){
92+ if (!isRunningSelf ) {
6693 long stopTime = System .currentTimeMillis ();
6794 setStopTime (stopTime );
6895 setStopApp (true );
@@ -72,17 +99,17 @@ protected void onStop() {
7299 @ Override
73100 protected void onResume () {
74101 super .onResume ();
75- if (isStopApp ()){
102+ if (isStopApp ()) {
76103 long startTime = System .currentTimeMillis ();
77104 long stopTime = getStopTime ();
78105 long stopMills = startTime - stopTime ;
79106 setStopApp (false );
80- if (stopMills >= ConstantInOB .MINUTE_MILLIS * 5 ){
107+ if (stopMills >= ConstantInOB .MINUTE_MILLIS * 5 ) {
81108 String runningActivityName = getRunningActivityName ();
82- String [] runningActivityNameArr = runningActivityName .split ("\\ ." );
83- String name = runningActivityNameArr [5 ];
84- Log .e (TAG + "onResume: " , name );
85- switch (name ){
109+ String [] runningActivityNameArr = runningActivityName .split ("\\ ." );
110+ String name = runningActivityNameArr [5 ];
111+ Log .e (TAG + "onResume: " , name );
112+ switch (name ) {
86113 case "UnlockActivity" :
87114 case "backup" :
88115 case "recoverwallet" :
@@ -99,16 +126,167 @@ protected void onResume() {
99126 }
100127 }
101128 }
129+ }
130+
131+ public void autoBackupFiles () {
132+ File walletPath = new File (mContext .getExternalFilesDir (null ) + "/obd" + ConstantWithNetwork .getInstance (ConstantInOB .networkType ).getDownloadDirectory () + "wallet.db" );
133+ File channelPath = new File (mContext .getExternalFilesDir (null ) + "/obd" + ConstantWithNetwork .getInstance (ConstantInOB .networkType ).getDownloadChannelDirectory () + "channel.db" );
134+ String storagePath = Environment .getExternalStorageDirectory () + "/OBMainnetBackupFiles" ;
135+ File toWalletPath = new File (Environment .getExternalStorageDirectory () + "/OBMainnetBackupFiles/wallet.db" );
136+ File toChannelPath = new File (Environment .getExternalStorageDirectory () + "/OBMainnetBackupFiles/channel.db" );
137+ if (walletPath .exists () && channelPath .exists ()) {
138+ // 本地备份(Local backup)
139+ MoveCacheFileToFileObd .createDirs (storagePath );
140+ MoveCacheFileToFileObd .copyFile (walletPath , toWalletPath );
141+ MoveCacheFileToFileObd .copyFile (channelPath , toChannelPath );
142+ MoveCacheFileToFileObd .createFile (storagePath + "/address.txt" , User .getInstance ().getWalletAddress (mContext ));
143+ // Authenticate the user. For most apps, this should be done when the user performs an
144+ // action that requires Drive access rather than in onCreate.
145+ if (StringUtils .isEmpty (User .getInstance ().getGoogleAccountName (mContext ))) {
146+ requestSignIn ();
147+ } else {
148+ GoogleAccountCredential credential =
149+ GoogleAccountCredential .usingOAuth2 (
150+ this , Collections .singleton (DriveScopes .DRIVE_FILE ));
151+ credential .setSelectedAccount (new Account (User .getInstance ().getGoogleAccountName (mContext ), User .getInstance ().getGoogleAccountType (mContext )));
152+ Drive googleDriveService =
153+ new Drive .Builder (
154+ AndroidHttp .newCompatibleTransport (),
155+ new GsonFactory (),
156+ credential )
157+ .setApplicationName ("OB Wallet" )
158+ .build ();
159+
160+ // The DriveServiceHelper encapsulates all REST API and SAF functionality.
161+ // Its instantiation is required before handling any onClick actions.
162+ mDriveServiceHelper = new DriveServiceHelper (googleDriveService );
163+ createAddressFile ();
164+ }
165+ } else {
166+ ToastUtils .showToast (mContext , "The backup file does not exist" );
167+ }
168+ }
102169
170+ /**
171+ * Starts a sign-in activity using {@link #REQUEST_CODE_SIGN_IN}.
172+ */
173+ private void requestSignIn () {
174+ LogUtils .e (TAG , "Requesting sign-in" );
175+
176+ GoogleSignInOptions signInOptions =
177+ new GoogleSignInOptions .Builder (GoogleSignInOptions .DEFAULT_SIGN_IN )
178+ .requestEmail ()
179+ .requestScopes (new Scope (DriveScopes .DRIVE_FILE ))
180+ .build ();
181+ GoogleSignInClient client = GoogleSignIn .getClient (this , signInOptions );
182+
183+ // The result of the sign-in Intent is handled in onActivityResult.
184+ startActivityForResult (client .getSignInIntent (), REQUEST_CODE_SIGN_IN );
185+ }
186+
187+ @ Override
188+ public void onActivityResult (int requestCode , int resultCode , Intent resultData ) {
189+ switch (requestCode ) {
190+ case REQUEST_CODE_SIGN_IN :
191+ if (resultCode == Activity .RESULT_OK && resultData != null ) {
192+ handleSignInResult (resultData );
193+ }
194+ break ;
195+ }
196+
197+ super .onActivityResult (requestCode , resultCode , resultData );
198+ }
199+
200+ /**
201+ * Handles the {@code result} of a completed sign-in activity initiated from requestSignIn.
202+ */
203+ private void handleSignInResult (Intent result ) {
204+ GoogleSignIn .getSignedInAccountFromIntent (result )
205+ .addOnSuccessListener (googleAccount -> {
206+ LogUtils .e (TAG , "Signed in as " + googleAccount .getEmail ());
207+
208+ // Use the authenticated account to sign in to the Drive service.
209+ GoogleAccountCredential credential =
210+ GoogleAccountCredential .usingOAuth2 (
211+ this , Collections .singleton (DriveScopes .DRIVE_FILE ));
212+ credential .setSelectedAccount (googleAccount .getAccount ());
213+ User .getInstance ().setGoogleAccountName (mContext , googleAccount .getAccount ().name );
214+ User .getInstance ().setGoogleAccountType (mContext , googleAccount .getAccount ().type );
215+ Drive googleDriveService =
216+ new Drive .Builder (
217+ AndroidHttp .newCompatibleTransport (),
218+ new GsonFactory (),
219+ credential )
220+ .setApplicationName ("OB Wallet" )
221+ .build ();
222+
223+ // The DriveServiceHelper encapsulates all REST API and SAF functionality.
224+ // Its instantiation is required before handling any onClick actions.
225+ mDriveServiceHelper = new DriveServiceHelper (googleDriveService );
226+ createAddressFile ();
227+ })
228+ .addOnFailureListener (exception -> LogUtils .e (TAG , "Unable to sign in." , exception ));
229+ }
230+
231+ /**
232+ * Creates a new file via the Drive REST API.
233+ */
234+ private void createAddressFile () {
235+ if (mDriveServiceHelper != null ) {
236+ LogUtils .e (TAG , "Creating a address file." );
237+ mDriveServiceHelper .createFile (User .getInstance ().getWalletAddress (mContext ) + "_mainnet" )
238+ .addOnSuccessListener (fileId -> createWalletFile ())
239+ .addOnFailureListener (exception -> {
240+ LogUtils .e (TAG , "Couldn't create address file." , exception );
241+ });
242+ }
243+ }
244+
245+ private void createWalletFile () {
246+ if (mDriveServiceHelper != null ) {
247+ LogUtils .e (TAG , "Creating wallet file." );
248+ String filePath = mContext .getExternalFilesDir (null ) + "/obd" + ConstantWithNetwork .getInstance (ConstantInOB .networkType ).getDownloadDirectory () + "wallet.db" ;
249+ LogUtils .e (TAG , filePath );
250+ mDriveServiceHelper .createFile (filePath , "wallet_mainnet.db" ).addOnSuccessListener (new OnSuccessListener <String >() {
251+ @ Override
252+ public void onSuccess (String s ) {
253+ createChannelFile ();
254+ }
255+ }).addOnFailureListener (new OnFailureListener () {
256+ @ Override
257+ public void onFailure (@ NonNull Exception e ) {
258+ LogUtils .e (TAG , "Couldn't create wallet file." , e );
259+ }
260+ });
261+ }
262+ }
263+
264+ private void createChannelFile () {
265+ if (mDriveServiceHelper != null ) {
266+ LogUtils .e (TAG , "Creating channel file." );
267+ String filePath = mContext .getExternalFilesDir (null ) + "/obd" + ConstantWithNetwork .getInstance (ConstantInOB .networkType ).getDownloadChannelDirectory () + "channel.db" ;
268+ LogUtils .e (TAG , filePath );
269+ mDriveServiceHelper .createFile (filePath , "channel_mainnet.db" ).addOnSuccessListener (new OnSuccessListener <String >() {
270+ @ Override
271+ public void onSuccess (String s ) {
272+ LogUtils .e (TAG , "Channel fileId" + s );
273+ User .getInstance ().setAutoBackUp (mContext , true );
274+ }
275+ }).addOnFailureListener (new OnFailureListener () {
276+ @ Override
277+ public void onFailure (@ NonNull Exception e ) {
278+ LogUtils .e (TAG , "Couldn't create channel file." , e );
279+ }
280+ });
281+ }
103282 }
104283
105284 @ Override
106285 protected void onDestroy () {
107286 super .onDestroy ();
108287 setStopApp (false );
109- if (mUnlockDialog != null ){
288+ if (mUnlockDialog != null ) {
110289 mUnlockDialog .release ();
111290 }
112-
113291 }
114292}
0 commit comments