Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 8990f29f authored by vince-bourgmayer's avatar vince-bourgmayer
Browse files

make better initializer service

parent ac99365d
Loading
Loading
Loading
Loading
+3 −5
Original line number Diff line number Diff line
@@ -8,7 +8,6 @@

package io.eelo.drive.receivers;

import android.accounts.AccountManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -18,8 +17,7 @@ import android.util.Log;
import io.eelo.drive.database.DbHelper;
import io.eelo.drive.services.InitializerService;
import io.eelo.drive.utils.AppConstants;
import io.eelo.drive.utils.CommonUtils;
import io.eelo.drive.utils.JobUtils;

/**
 * @author Vincent Bourgmayer
 */
@@ -31,14 +29,14 @@ public class PackageEventReceiver extends BroadcastReceiver {
        if(intent.getAction().equals(Intent.ACTION_MY_PACKAGE_REPLACED)) {
            SharedPreferences pref = context.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
            //reinitialized the app each time
            pref.edit().putBoolean(AppConstants.INITIALIZERSERVICE_HAS_RUN, false).apply();
            pref.edit().putBoolean(AppConstants.INITIALIZATION_HAS_BEEN_DONE, false).apply();
            context.startService(new Intent(context, InitializerService.class));

            DbHelper dbHelper = new DbHelper(context);
            dbHelper.getWritableDatabase().close(); //Force upgrade of db.


            /*if (!pref.getBoolean(AppConstants.INITIALIZERSERVICE_HAS_RUN, false)) {
            /*if (!pref.getBoolean(AppConstants.INITIALIZATION_HAS_BEEN_DONE, false)) {
                context.startService(new Intent(context, InitializerService.class));
            } else if(CommonUtils.getAccount( pref.getString(AccountManager.KEY_ACCOUNT_NAME,""),
                        pref.getString(AccountManager.KEY_ACCOUNT_TYPE, ""),
+134 −93
Original line number Diff line number Diff line
@@ -55,87 +55,95 @@ public class InitializerService extends Service implements OnRemoteOperationList
    private OwnCloudClient mCloudClient;
    private Handler mHandler;
    private Account mAccount;
    private boolean isAccountFromPref;
    private int restartFolderCreationCounter =0;

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate()");
        super.onCreate();
        this.mHandler = new Handler();
        this.mSyncedFolders = new ArrayList<>();
        this.existingRemoteFolderCounter = 0;

        //JobUtils.scheduleInitializerJob(getApplicationContext());
    }

    @Override
    public int onStartCommand( Intent intent, int flags, int startId ) {
        Log.i(TAG, "onStartCommand(...)");
        //Get account
        isAccountFromPref = true;
        SharedPreferences prefs = this.getSharedPreferences( AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE );

        if(!prefs.getBoolean(AppConstants.INITIALIZERSERVICE_HAS_RUN, false) ) {

        if( prefs.getBoolean( AppConstants.INITIALIZATION_HAS_BEEN_DONE, false ) ) {
            //JobUtils.scheduleScannerJob(this, 120000);
            Log.w(TAG, "Initializer has already been run");
            stopSelf(); //@TODO, do not keep it when you'll enable initializer job because, it will kill running process at the same time.
        }else{
            String accountName = prefs.getString( AccountManager.KEY_ACCOUNT_NAME, "" );
            String accountType = prefs.getString( AccountManager.KEY_ACCOUNT_TYPE, "" );

            if ( accountName.isEmpty() && accountType.isEmpty() && intent.getExtras() != null ) {
                isAccountFromPref = false;

                accountName = intent.getExtras().getString( AccountManager.KEY_ACCOUNT_NAME, "" );
                accountType = intent.getExtras().getString( AccountManager.KEY_ACCOUNT_TYPE, "" );
            }

            if(!accountName.isEmpty() ) {
                mAccount = CommonUtils.getAccount(accountName, accountType, AccountManager.get(this));
                //Get OwnCloudlient
                if (mAccount != null) {
                    CommonUtils.getOwnCloudClient(mAccount, getApplicationContext(), this);
                //If data come from intent, store them into pref because there aren't stored
                prefs.edit().putString( AccountManager.KEY_ACCOUNT_NAME, accountName )
                        .putString( AccountManager.KEY_ACCOUNT_TYPE, accountType )
                        .apply();
            }

            if(accountName.isEmpty() ) {
                Log.w(TAG, "Account's name not found. Neither in shared prefs nor in intent's extras");
                //JobUtils.stopScheduledJob(getApplicationContext(), JobUtils.InitializerJobId);
                stopSelf();
            }else{
                Log.w(TAG, "account's name not found. Neither in shared prefs nor in intent's extras");
            }
                this.mAccount = CommonUtils.getAccount( accountName, accountType, AccountManager.get(this) );
                //Get OwnCloudlient
                if (this.mAccount != null) {
                    CommonUtils.getOwnCloudClient( this.mAccount, getApplicationContext(), this);
                }else {
            JobUtils.scheduleScannerJob(this, 120000);
            Log.w(TAG, "Initializer has already been run");
                    Log.w(TAG, "Got account is invalid.");
                    //JobUtils.stopScheduledJob(getApplicationContext(), JobUtils.initializerJobID);
                    stopSelf();
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * Got DAV's client
     * @param result
     */
    @Override
    public void onOCClientReceived(Object result) {
        Log.i(TAG, "ocOCClientReceived");
        existingRemoteFolderCounter = 0;

        try {
            this.mCloudClient = (OwnCloudClient) result;
        if (mCloudClient != null) {
            Log.d(TAG, mCloudClient.getBaseUri().toString());
            if (!isAccountFromPref) {
                SharedPreferences settings = getApplicationContext().getSharedPreferences(
                        AppConstants.SHARED_PREFERENCE_NAME,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = settings.edit();
                edit.putString(AccountManager.KEY_ACCOUNT_NAME, this.mAccount.name);
                edit.putString(AccountManager.KEY_ACCOUNT_TYPE, this.mAccount.type);
                edit.apply();
        }catch(Exception e){
            Log.e(TAG, e.toString() );
            stopSelf();
        }

        Log.d(TAG, mCloudClient.getBaseUri().toString());

        //Get categories of element to sync
        List<String> mSyncCategories = new ArrayList<>();

        if (CommonUtils.isMediaSyncEnabled(mAccount)) {
            mSyncCategories.addAll(Arrays.asList(MEDIA_SYNCABLE_CATEGORIES));
            } else {
                Log.w(TAG, "ContentResolver.getSyncAutomatically(account, '" + MEDIASYNC_PROVIDER_AUTHORITY + "') return false");
        }

        if (CommonUtils.isSettingsSyncEnabled(mAccount)) {
            mSyncCategories.addAll(Arrays.asList(SETTINGS_SYNCABLE_CATEGORIES));
            } else {
                Log.w(TAG, "ContentResolver.getSyncAutomatically(account, '" + SETTINGSYNC_PROVIDER_AUTHORITY + "') return false");
        }

        //Get SyncedFolders
        getInitialSyncedFolders(mSyncCategories);
            startFolderCreation();
        }

        this.existingRemoteFolderCounter = 0;

        CreateNextRemoteFolder();
        }

    /**
@@ -144,7 +152,9 @@ public class InitializerService extends Service implements OnRemoteOperationList
     */
    private void getInitialSyncedFolders( List<String> categories){
        Log.i(TAG, "getInitialSyncedFolders");

        this.mSyncedFolders = new ArrayList<>();

        for(int i=-1, size = categories.size(); ++i < size;){
            final String DEVICE_SPECIFIC_PATH = PATH_SEPARATOR+"Devices"+PATH_SEPARATOR+ Build.BRAND+"_"+ Build.MODEL+"_"
                    + Build.SERIAL;
@@ -181,14 +191,20 @@ public class InitializerService extends Service implements OnRemoteOperationList
                    String remoteFolderPath = DEVICE_SPECIFIC_PATH+"/rom_settings/";
                    mSyncedFolders.add( new SyncedFolder(categories.get(i), "/data/system/users/0/", remoteFolderPath, true, false, true, false) );
                    try{
                        String appListPath = getFilesDir().getCanonicalPath()+PATH_SEPARATOR;
                        mSyncedFolders.add( new SyncedFolder(categories.get(i), appListPath, remoteFolderPath+"app_list/", true, false, true, false) );
                        mSyncedFolders.add( new SyncedFolder(
                                categories.get(i),
                        getFilesDir().getCanonicalPath()+PATH_SEPARATOR,
                        remoteFolderPath+"app_list/",
                                true,
                                false,
                                true,
                                false) );
                    }catch (Exception e){ Log.e(TAG, e.toString()); }

                    break;
            }
        }
    }

    private String getExternalFolder(String directory){
        return CommonUtils.getLocalPath(Environment.getExternalStoragePublicDirectory(directory))+ PATH_SEPARATOR;
    }
@@ -196,13 +212,34 @@ public class InitializerService extends Service implements OnRemoteOperationList
    /**
     * Start to createSyncedFolder in the cloud
     */
    private void startFolderCreation(){
        int currentRemoteFolderIndex = existingRemoteFolderCounter;
        if(currentRemoteFolderIndex >= this.mSyncedFolders.size() || mSyncedFolders.isEmpty() ){
            Log.e(TAG, "startFolderCreation, currentRemoteFolderIndex >= mSyncedFolders.size || mSyncedFolders is empty");
    private void CreateNextRemoteFolder(){
        this.restartFolderCreationCounter = 0;

        if( this.mSyncedFolders == null || this.mSyncedFolders.isEmpty() ){
            //JobUtils.stopScheduledJob(getApplicationContext(), JobUtils.InitializerJobId);
            this.stopSelf();
        }

        //It means that there are still folders to create
        if( this.existingRemoteFolderCounter < this.mSyncedFolders.size() ){

            if( this.mHandler == null ) this.mHandler = new Handler();

            CreateInitialRemoteFolderOperation createFolderOperation =
                    new CreateInitialRemoteFolderOperation(
                        this.mSyncedFolders.get( this.existingRemoteFolderCounter ),
                            true,
                            this);

            createFolderOperation.execute(this.mCloudClient, this, this.mHandler);

        }else if(this.existingRemoteFolderCounter ==  this.mSyncedFolders.size() ){

            doLastStep();

        }else{
            CreateInitialRemoteFolderOperation initializeRemoteFolderOperation = new CreateInitialRemoteFolderOperation(mSyncedFolders.get(currentRemoteFolderIndex),  true, this);
            initializeRemoteFolderOperation.execute(this.mCloudClient, this, mHandler);
            Log.e(TAG, "this.existingRemoteFolderCounter : "+this.existingRemoteFolderCounter+" > this.mSyncedFolders.size() : "+this.mSyncedFolders.size() );
            this.stopSelf();
        }
    }

@@ -210,20 +247,27 @@ public class InitializerService extends Service implements OnRemoteOperationList
    public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
        Log.i(TAG, "onRemoteOperationFinish()");
        if(operation instanceof CreateInitialRemoteFolderOperation){

            if(result.isSuccess() || result.getCode() == RemoteOperationResult.ResultCode.FOLDER_ALREADY_EXISTS){
                existingRemoteFolderCounter++;
                areRemoteFolderReady();
                this.existingRemoteFolderCounter+=1;
                CreateNextRemoteFolder();

            }else if( result.getHttpCode() == 423 || result.getHttpCode() == 409){//file locked or conflict in result
                Log.e( TAG, result.getLogMessage() );
                if( restartFolderCreationCounter < 3) {
                    Log.e(TAG, " restart operation");
                    operation.execute(mCloudClient, this, mHandler);
                    restartFolderCreationCounter++;

                if( this.restartFolderCreationCounter < 3) {
                    Log.w( TAG, " restart operation" );
                    operation.execute( this.mCloudClient, this, this.mHandler );
                    this.restartFolderCreationCounter+=1;

                }else{
                    Log.w(TAG, "Remote folder's creation failed due to conflict with server");
                    Log.e(TAG, "Remote folder's creation failed due to conflict with server");
                    stopSelf();
                }

            }else{
                Log.e(TAG, result.getLogMessage()+" "+result.getHttpCode() );
                stopSelf();
            }
        }
    }
@@ -232,25 +276,22 @@ public class InitializerService extends Service implements OnRemoteOperationList
    /**
     * Function to check if all remote folder have been created
     **/
    private void areRemoteFolderReady(){
        Log.i(TAG, "areRemoteFolderReady()");
        if(this.mSyncedFolders != null && !this.mSyncedFolders.isEmpty() ){
            if(existingRemoteFolderCounter ==  this.mSyncedFolders.size()){
                JobUtils.scheduleScannerJob(this, 120000);
                SharedPreferences settings = getApplicationContext().getSharedPreferences(
                        AppConstants.SHARED_PREFERENCE_NAME,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = settings.edit();
                edit.putBoolean(AppConstants.INITIALIZERSERVICE_HAS_RUN, true)
    private void doLastStep(){
        Log.i(TAG, "doLastStep()");

        getApplicationContext().getSharedPreferences( AppConstants.SHARED_PREFERENCE_NAME,
                Context.MODE_PRIVATE )
                .edit()
                .putBoolean(AppConstants.INITIALIZATION_HAS_BEEN_DONE, true)
                .putInt( INITIALFOLDERS_NUMBER, mSyncedFolders.size() )
                .apply();

        //all folder have been created
        JobUtils.scheduleScannerJob(this, 120000);

        //JobUtils.stopScheduledJob(appContext, JobUtils.InitializerJobId);
        stopSelf();
            }else {
                startFolderCreation();
            }
        } else {
            Log.e(TAG, "mSyncedFolders is empty or null");
        }

    }

    @Override
@@ -259,7 +300,7 @@ public class InitializerService extends Service implements OnRemoteOperationList
        this.mHandler = null;
        this.mAccount = null;
        this.mCloudClient = null;
        this.mSyncedFolders.clear();
        if(this.mSyncedFolders != null) this.mSyncedFolders.clear();
        this.mSyncedFolders = null;
    }

+2 −3
Original line number Diff line number Diff line
@@ -10,7 +10,6 @@ package io.eelo.drive.services;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
@@ -52,7 +51,7 @@ import io.eelo.drive.utils.CommonUtils;
import io.eelo.drive.utils.IGetOCClient;

import static com.owncloud.android.lib.resources.files.FileUtils.PATH_SEPARATOR;
import static io.eelo.drive.utils.AppConstants.INITIALIZERSERVICE_HAS_RUN;
import static io.eelo.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE;


/**
@@ -129,7 +128,7 @@ public class ObserverService extends Service implements OnRemoteOperationListene

        SharedPreferences prefs = this.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);

        if (prefs.getBoolean(INITIALIZERSERVICE_HAS_RUN, false)) {
        if (prefs.getBoolean(INITIALIZATION_HAS_BEEN_DONE, false)) {

            String accountName = prefs.getString(AccountManager.KEY_ACCOUNT_NAME, "");
            String accountType = prefs.getString(AccountManager.KEY_ACCOUNT_TYPE, "");
+2 −5
Original line number Diff line number Diff line
@@ -9,8 +9,6 @@
package io.eelo.drive.services;

import android.accounts.AccountManager;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
@@ -20,7 +18,6 @@ import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;
import java.nio.file.Files;

import io.eelo.drive.database.DbHelper;
import io.eelo.drive.utils.AppConstants;
@@ -28,7 +25,7 @@ import io.eelo.drive.utils.CommonUtils;
import io.eelo.drive.utils.JobUtils;

import static io.eelo.drive.utils.AppConstants.INITIALFOLDERS_NUMBER;
import static io.eelo.drive.utils.AppConstants.INITIALIZERSERVICE_HAS_RUN;
import static io.eelo.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE;
/**
 * @author Vincent Bourgmayer
 * Service which stop others, remove DB, clear sharedPrefs and unregister ScreenOffReceiver
@@ -74,7 +71,7 @@ public class ResetService extends Service {
                    //4. clear prefs
                    prefs.edit().remove(AccountManager.KEY_ACCOUNT_NAME)
                            .remove(AccountManager.KEY_ACCOUNT_TYPE)
                            .putBoolean(INITIALIZERSERVICE_HAS_RUN, false)
                            .putBoolean(INITIALIZATION_HAS_BEEN_DONE, false)
                            .remove(INITIALFOLDERS_NUMBER)
                            .apply();

+1 −1
Original line number Diff line number Diff line
@@ -19,7 +19,7 @@ public abstract class AppConstants {
    public static final String  MEDIASYNC_PROVIDER_AUTHORITY ="io.eelo.drive.providers.MediasSyncProvider";
    public static final String  SETTINGSYNC_PROVIDER_AUTHORITY ="io.eelo.drive.providers.SettingsSyncProvider";

    public static final String INITIALIZERSERVICE_HAS_RUN="initService_has_run";
    public static final String INITIALIZATION_HAS_BEEN_DONE ="initService_has_run";
    public static final String INITIALFOLDERS_NUMBER="initial_folder_number";
    public static final String APPLICATIONS_LIST_FILE_NAME = "packages_list.csv";
    public static final String APPLICATIONS_LIST_FILE_NAME_TMP = "tmp_packages_list.csv";
Loading