Parcourir la source

Merge pull request #2253 from nextcloud/improve-sync

Improve syncing code
Andy Scherzinger il y a 7 ans
Parent
commit
4b0b49f2af

+ 0 - 2
src/main/AndroidManifest.xml

@@ -255,8 +255,6 @@
         </receiver>
 
 
-        <service android:name=".services.observer.FileObserverService" />
-
         <activity
             android:name=".ui.activity.CopyToClipboardActivity"
             android:icon="@drawable/copy_link"

+ 3 - 2
src/main/java/com/owncloud/android/MainApp.java

@@ -159,7 +159,7 @@ public class MainApp extends MultiDexApplication {
             }
         }
 
-        initAutoUpload();
+        initSyncOperations();
         initContactsBackup();
         notificationChannels();
 
@@ -274,7 +274,7 @@ public class MainApp extends MultiDexApplication {
         }
     }
 
-    public static void initAutoUpload() {
+    public static void initSyncOperations() {
         updateToAutoUpload();
         cleanOldEntries();
         updateAutoUploadEntries();
@@ -292,6 +292,7 @@ public class MainApp extends MultiDexApplication {
 
         FilesSyncHelper.scheduleFilesSyncIfNeeded(mContext);
         FilesSyncHelper.restartJobsIfNeeded();
+        FilesSyncHelper.scheduleOfflineSyncIfNeeded();
 
         ReceiversHelper.registerNetworkChangeReceiver();
 

+ 2 - 16
src/main/java/com/owncloud/android/files/BootupBroadcastReceiver.java

@@ -27,7 +27,6 @@ import android.content.Intent;
 
 import com.owncloud.android.MainApp;
 import com.owncloud.android.lib.common.utils.Log_OC;
-import com.owncloud.android.services.observer.FileObserverService;
 
 
 /**
@@ -40,27 +39,14 @@ public class BootupBroadcastReceiver extends BroadcastReceiver {
 
     /**
      * Receives broadcast intent reporting that the system was just boot up.
-     *
-     * Starts {@link FileObserverService} to enable observation of favourite files.
-     *
+     **
      * @param   context     The context where the receiver is running.
      * @param   intent      The intent received.
      */
     @Override
     public void onReceive(Context context, Intent intent) {
         if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
-            Log_OC.d(TAG, "Starting file observer service...");
-            Intent initObservers = FileObserverService.makeInitIntent(context);
-
-            if (FileObserverService.shouldStart()) {
-                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
-                    context.startForegroundService(initObservers);
-                } else {
-                    context.startService(initObservers);
-                }
-            }
-
-            MainApp.initAutoUpload();
+            MainApp.initSyncOperations();
             MainApp.initContactsBackup();
         } else {
             Log_OC.d(TAG, "Getting wrong intent: " + intent.getAction());

+ 1 - 0
src/main/java/com/owncloud/android/jobs/FilesSyncJob.java

@@ -90,6 +90,7 @@ public class FilesSyncJob extends Job {
 
         // If we are in power save mode, better to postpone upload
         if (PowerUtils.isPowerSaveMode(context) && !overridePowerSaving) {
+            wakeLock.release();
             return Result.SUCCESS;
         }
 

+ 2 - 0
src/main/java/com/owncloud/android/jobs/NCJobCreator.java

@@ -39,6 +39,8 @@ public class NCJobCreator implements JobCreator {
                 return new AccountRemovalJob();
             case FilesSyncJob.TAG:
                 return new FilesSyncJob();
+            case OfflineSyncJob.TAG:
+                return new OfflineSyncJob();
             default:
                 return null;
         }

+ 155 - 0
src/main/java/com/owncloud/android/jobs/OfflineSyncJob.java

@@ -0,0 +1,155 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Mario Danic
+ * Copyright (C) 2018 Mario Danic
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.owncloud.android.jobs;
+
+import android.accounts.Account;
+import android.content.Context;
+import android.content.Intent;
+import android.database.Cursor;
+import android.os.Build;
+import android.os.PowerManager;
+import android.support.annotation.NonNull;
+
+import com.evernote.android.job.Job;
+import com.evernote.android.job.JobManager;
+import com.owncloud.android.MainApp;
+import com.owncloud.android.authentication.AccountUtils;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.db.ProviderMeta;
+import com.owncloud.android.lib.common.operations.RemoteOperationResult;
+import com.owncloud.android.operations.SynchronizeFileOperation;
+import com.owncloud.android.ui.activity.ConflictsResolveActivity;
+import com.owncloud.android.utils.ConnectivityUtils;
+import com.owncloud.android.utils.PowerUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+public class OfflineSyncJob extends Job {
+    public static final String TAG = "OfflineSyncJob";
+
+    private List<OfflineFile> offlineFileList = new ArrayList<>();
+
+    @NonNull
+    @Override
+    protected Result onRunJob(@NonNull Params params) {
+        final Context context = MainApp.getAppContext();
+
+        PowerManager.WakeLock wakeLock = null;
+        if (!PowerUtils.isPowerSaveMode(context) && !ConnectivityUtils.isInternetWalled(context)) {
+            Set<Job> jobs = JobManager.instance().getAllJobsForTag(TAG);
+            for (Job job : jobs) {
+                if (!job.isFinished() && !job.equals(this)) {
+                    return Result.SUCCESS;
+                }
+            }
+
+            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
+                PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
+                wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
+                wakeLock.acquire();
+            }
+
+            Cursor cursorOnKeptInSync = context.getContentResolver().query(
+                    ProviderMeta.ProviderTableMeta.CONTENT_URI,
+                    null,
+                    ProviderMeta.ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
+                    new String[]{String.valueOf(1)},
+                    null
+            );
+
+            if (cursorOnKeptInSync != null) {
+                if (cursorOnKeptInSync.moveToFirst()) {
+
+                    String localPath = "";
+                    String accountName = "";
+                    Account account = null;
+                    do {
+                        localPath = cursorOnKeptInSync.getString(cursorOnKeptInSync
+                                .getColumnIndex(ProviderMeta.ProviderTableMeta.FILE_STORAGE_PATH));
+                        accountName = cursorOnKeptInSync.getString(cursorOnKeptInSync
+                                .getColumnIndex(ProviderMeta.ProviderTableMeta.FILE_ACCOUNT_OWNER));
+
+                        account = new Account(accountName, MainApp.getAccountType());
+                        if (!AccountUtils.exists(account, context) || localPath == null || localPath.length() <= 0) {
+                            continue;
+                        }
+
+                        offlineFileList.add(new OfflineFile(localPath, account));
+
+                    } while (cursorOnKeptInSync.moveToNext());
+
+                }
+                cursorOnKeptInSync.close();
+            }
+
+            FileDataStorageManager storageManager;
+            for (OfflineFile offlineFile : offlineFileList) {
+                storageManager = new FileDataStorageManager(offlineFile.getAccount(), context.getContentResolver());
+                OCFile file = storageManager.getFileByLocalPath(offlineFile.getLocalPath());
+                SynchronizeFileOperation sfo =
+                        new SynchronizeFileOperation(file, null, offlineFile.getAccount(), true, context);
+                RemoteOperationResult result = sfo.execute(storageManager, context);
+                if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
+                    Intent i = new Intent(context, ConflictsResolveActivity.class);
+                    i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
+                    i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
+                    i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, offlineFile.getAccount());
+                    context.startActivity(i);
+                }
+            }
+
+            if (wakeLock != null) {
+                wakeLock.release();
+            }
+        }
+
+        return Result.SUCCESS;
+    }
+
+
+    private class OfflineFile {
+        private String localPath;
+        private Account account;
+
+        private OfflineFile(String localPath, Account account) {
+            this.localPath = localPath;
+            this.account = account;
+        }
+
+        public String getLocalPath() {
+            return localPath;
+        }
+
+        public void setLocalPath(String localPath) {
+            this.localPath = localPath;
+        }
+
+        public Account getAccount() {
+            return account;
+        }
+
+        public void setAccount(Account account) {
+            this.account = account;
+        }
+    }
+}

+ 0 - 425
src/main/java/com/owncloud/android/services/observer/FileObserverService.java

@@ -1,425 +0,0 @@
-/**
- *   ownCloud Android client application
- *
- *   @author David A. Velasco
- *   Copyright (C) 2012 Bartek Przybylski
- *   Copyright (C) 2016 ownCloud Inc.
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License version 2,
- *   as published by the Free Software Foundation.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package com.owncloud.android.services.observer;
-
-import android.accounts.Account;
-import android.app.Notification;
-import android.app.Service;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.database.Cursor;
-import android.graphics.BitmapFactory;
-import android.os.IBinder;
-import android.support.v4.app.NotificationCompat;
-
-import com.owncloud.android.MainApp;
-import com.owncloud.android.R;
-import com.owncloud.android.authentication.AccountUtils;
-import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
-import com.owncloud.android.files.services.FileDownloader;
-import com.owncloud.android.lib.common.utils.Log_OC;
-import com.owncloud.android.operations.SynchronizeFileOperation;
-import com.owncloud.android.ui.notifications.NotificationUtils;
-import com.owncloud.android.utils.FileStorageUtils;
-import com.owncloud.android.utils.ThemeUtils;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-
-/**
- * Service keeping a list of {@link FolderObserver} instances that watch for local
- * changes in favorite files (formerly known as kept-in-sync files) and try to
- * synchronize them with the OC server as soon as possible.
- * 
- * Tries to be alive as long as possible; that is the reason why stopSelf() is
- * never called.
- * 
- * It is expected that the system eventually kills the service when runs low of
- * memory. To minimize the impact of this, the service always returns
- * Service.START_STICKY, and the later restart of the service is explicitly
- * considered in {@link FileObserverService#onStartCommand(Intent, int, int)}.
- */
-public class FileObserverService extends Service {
-
-    public final static String MY_NAME = FileObserverService.class.getCanonicalName();
-    public final static String ACTION_START_OBSERVE = MY_NAME + ".action.START_OBSERVATION";
-    public final static String ACTION_ADD_OBSERVED_FILE = MY_NAME + ".action.ADD_OBSERVED_FILE";
-    public final static String ACTION_DEL_OBSERVED_FILE = MY_NAME + ".action.DEL_OBSERVED_FILE";
-
-    private final static String ARG_FILE = "ARG_FILE";
-    private final static String ARG_ACCOUNT = "ARG_ACCOUNT";
-
-    private static final int FOREGROUND_SERVICE_ID = 333;
-
-    private static final String TAG = FileObserverService.class.getSimpleName();
-
-    private Map<String, FolderObserver> mFolderObserversMap;
-    private DownloadCompletedReceiver mDownloadReceiver;
-
-    /**
-     * Factory method to create intents that allow to start an ACTION_START_OBSERVE command.
-     * 
-     * @param context   Android context of the caller component.
-     * @return          Intent that starts a command ACTION_START_OBSERVE when
-     *                  {@link Context#startService(Intent)} is called.
-     */
-    public static Intent makeInitIntent(Context context) {
-        Intent i = new Intent(context, FileObserverService.class);
-        i.setAction(ACTION_START_OBSERVE);
-        return i;
-    }
-
-    public static boolean shouldStart() {
-
-        // query for any favorite file in any OC account
-        Cursor cursorOnKeptInSync = MainApp.getAppContext().getContentResolver().query(
-                ProviderTableMeta.CONTENT_URI,
-                null,
-                ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
-                new String[]{String.valueOf(1)},
-                null
-        );
-
-        boolean returnValue = false;
-        if (cursorOnKeptInSync != null && cursorOnKeptInSync.moveToFirst()) {
-            returnValue = true;
-        }
-
-        if (cursorOnKeptInSync != null) {
-            cursorOnKeptInSync.close();
-        }
-
-        return returnValue;
-    }
-
-    /**
-     * Factory method to create intents that allow to start or stop the
-     * observance of a file.
-     * 
-     * @param context       Android context of the caller component.
-     * @param file          OCFile to start or stop to watch.
-     * @param account       OC account containing file.
-     * @param watchIt       'True' creates an intent to watch, 'false' an intent to stop watching.
-     * @return              Intent to start or stop the observance of a file through a call
-     *                      to {@link Context#startService(Intent)}.
-     */
-    public static Intent makeObservedFileIntent(
-            Context context, OCFile file, Account account, boolean watchIt) {
-        Intent intent = new Intent(context, FileObserverService.class);
-        intent.setAction(watchIt ? FileObserverService.ACTION_ADD_OBSERVED_FILE
-                : FileObserverService.ACTION_DEL_OBSERVED_FILE);
-        intent.putExtra(FileObserverService.ARG_FILE, file);
-        intent.putExtra(FileObserverService.ARG_ACCOUNT, account);
-        return intent;
-    }
-
-    /**
-     * Initialize the service. 
-     */
-    @Override
-    public void onCreate() {
-        Log_OC.d(TAG, "onCreate");
-        super.onCreate();
-
-        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
-            Notification notification = new NotificationCompat.Builder(this,
-                    NotificationUtils.NOTIFICATION_CHANNEL_FILE_OBSERVER)
-                    .setContentTitle(getResources().getString(R.string.notification_channel_file_observer_name))
-                    .setContentText(getResources().getString(R.string.notification_channel_file_observer_description))
-                    .setSmallIcon(R.drawable.notification_icon)
-                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.notification_icon))
-                    .setColor(ThemeUtils.primaryColor())
-                    .build();
-
-            startForeground(FOREGROUND_SERVICE_ID, notification);
-        }
-
-        mDownloadReceiver = new DownloadCompletedReceiver();
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(FileDownloader.getDownloadAddedMessage());
-        filter.addAction(FileDownloader.getDownloadFinishMessage());
-        registerReceiver(mDownloadReceiver, filter);
-
-        mFolderObserversMap = new HashMap<String, FolderObserver>();
-    }
-
-    /**
-     * Release resources.
-     */
-    @Override
-    public void onDestroy() {
-        Log_OC.d(TAG, "onDestroy - finishing observation of favorite files");
-
-        unregisterReceiver(mDownloadReceiver);
-
-        Iterator<FolderObserver> itOCFolder = mFolderObserversMap.values().iterator();
-        while (itOCFolder.hasNext()) {
-            itOCFolder.next().stopWatching();
-        }
-        mFolderObserversMap.clear();
-        mFolderObserversMap = null;
-
-        super.onDestroy();
-    }
-
-    /**
-     * This service cannot be bound.
-     */
-    @Override
-    public IBinder onBind(Intent intent) {
-        return null;
-    }
-
-    /**
-     * Handles requests to:
-     *  - (re)start watching                    (ACTION_START_OBSERVE)
-     *  - add an {@link OCFile} to be watched   (ATION_ADD_OBSERVED_FILE)
-     *  - stop observing an {@link OCFile}      (ACTION_DEL_OBSERVED_FILE) 
-     */
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        Log_OC.d(TAG, "Starting command " + intent);
-
-        if (intent == null || ACTION_START_OBSERVE.equals(intent.getAction())) {
-            // NULL occurs when system tries to restart the service after its
-            // process was killed
-            startObservation();
-            return Service.START_STICKY;
-
-        } else if (ACTION_ADD_OBSERVED_FILE.equals(intent.getAction())) {
-            OCFile file = intent.getParcelableExtra(ARG_FILE);
-            Account account = intent.getParcelableExtra(ARG_ACCOUNT);
-            addObservedFile(file, account);
-
-        } else if (ACTION_DEL_OBSERVED_FILE.equals(intent.getAction())) {
-            removeObservedFile(intent.getParcelableExtra(ARG_FILE),
-                    intent.getParcelableExtra(ARG_ACCOUNT));
-
-        } else {
-            Log_OC.e(TAG, "Unknown action received; ignoring it: " + intent.getAction());
-        }
-
-        return Service.START_STICKY;
-    }
-
-    
-    /**
-     * Read from the local database the list of files that must to be kept
-     * synchronized and starts observers to monitor local changes on them.
-     * 
-     * Updates the list of currently observed files if called multiple times.
-     */
-    private void startObservation() {
-        Log_OC.d(TAG, "Loading all kept-in-sync files from database to start watching them");
-
-        if (MainApp.getAppContext() == null) {
-            MainApp.setAppContext(getApplicationContext());
-        }
-
-        // query for any favorite file in any OC account
-        Cursor cursorOnKeptInSync = getContentResolver().query(
-                ProviderTableMeta.CONTENT_URI, 
-                null,
-                ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?", 
-                new String[] { String.valueOf(1) }, 
-                null
-        );
-
-        if (cursorOnKeptInSync != null) {
-
-            if (cursorOnKeptInSync.moveToFirst()) {
-
-                String localPath = "";
-                String accountName = "";
-                Account account = null;
-                do {
-                    localPath = cursorOnKeptInSync.getString(cursorOnKeptInSync
-                            .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
-                    accountName = cursorOnKeptInSync.getString(cursorOnKeptInSync
-                            .getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER));
-
-                    account = new Account(accountName, MainApp.getAccountType());
-                    if (!AccountUtils.exists(account, this) || localPath == null || localPath.length() <= 0) {
-                        continue;
-                    }
-                    
-                    addObservedFile(localPath, account);
-
-                } while (cursorOnKeptInSync.moveToNext());
-
-            }
-            cursorOnKeptInSync.close();
-        }
-
-        // service does not stopSelf() ; that way it tries to be alive forever
-
-    }
-
-    
-    /**
-     * Registers the local copy of a remote file to be observed for local
-     * changes, an automatically updated in the ownCloud server.
-     * 
-     * This method does NOT perform a {@link SynchronizeFileOperation} over the
-     * file.
-     * 
-     * @param file      Object representing a remote file which local copy must be observed.
-     * @param account   OwnCloud account containing file.
-     */
-    private void addObservedFile(OCFile file, Account account) {
-        Log_OC.v(TAG, "Adding a file to be watched");
-
-        if (file == null) {
-            Log_OC.e(TAG, "Trying to add a NULL file to observer");
-            return;
-        }
-        if (account == null) {
-            Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
-            return;
-        }
-
-        String localPath = file.getStoragePath();
-        if (localPath == null || localPath.length() <= 0) {
-            // file downloading or to be downloaded for the first time
-            localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
-        }
-        
-        addObservedFile(localPath, account);
-        
-    }
-
-    
-    
-    
-    /**
-     * Registers a local file to be observed for changes.
-     * 
-     * @param localPath     Absolute path in the local file system to the file to be observed.
-     * @param account       OwnCloud account associated to the local file.
-     */
-    private void addObservedFile(String localPath, Account account) {
-        File file = new File(localPath);
-        String parentPath = file.getParent();
-        FolderObserver observer = mFolderObserversMap.get(parentPath);
-        if (observer == null) {
-            observer = new FolderObserver(parentPath, account, getApplicationContext());
-            mFolderObserversMap.put(parentPath, observer);
-            Log_OC.d(TAG, "Observer added for parent folder " + parentPath + "/");
-        }
-        
-        observer.startWatching(file.getName());
-        Log_OC.d(TAG, "Added " + localPath + " to list of observed children");
-    }
-
-    
-    /**
-     * Unregisters the local copy of a remote file to be observed for local changes.
-     * 
-     * @param file      Object representing a remote file which local copy must be not 
-     *                  observed longer.
-     * @param account   OwnCloud account containing file.
-     */
-    private void removeObservedFile(OCFile file, Account account) {
-        Log_OC.v(TAG, "Removing a file from being watched");
-
-        if (file == null) {
-            Log_OC.e(TAG, "Trying to remove a NULL file");
-            return;
-        }
-        if (account == null) {
-            Log_OC.e(TAG, "Trying to add a file with a NULL account to observer");
-            return;
-        }
-
-        String localPath = file.getStoragePath();
-        if (localPath == null || localPath.length() <= 0) {
-            localPath = FileStorageUtils.getDefaultSavePathFor(account.name, file);
-        }
-
-        removeObservedFile(localPath);
-    }
-
-    
-    /**
-     * Unregisters a local file from being observed for changes.
-     * 
-     * @param localPath     Absolute path in the local file system to the target file.
-     */
-    private void removeObservedFile(String localPath) {
-        File file = new File(localPath);
-        String parentPath = file.getParent();
-        FolderObserver observer = mFolderObserversMap.get(parentPath);
-        if (observer != null) {
-            observer.stopWatching(file.getName());
-            if (observer.isEmpty()) {
-                mFolderObserversMap.remove(parentPath);
-                Log_OC.d(TAG, "Observer removed for parent folder " + parentPath + "/");
-            }
-        
-        } else {
-            Log_OC.d(TAG, "No observer to remove for path " + localPath);
-        }
-    }
-
-    
-    /**
-     * Private receiver listening to events broadcasted by the {@link FileDownloader} service.
-     * 
-     * Pauses and resumes the observance on registered files while being download,
-     * in order to avoid to unnecessary synchronizations.
-     */
-    private class DownloadCompletedReceiver extends BroadcastReceiver {
-
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            Log_OC.d(TAG, "Received broadcast intent " + intent);
-
-            File downloadedFile = new File(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
-            String parentPath = downloadedFile.getParent();
-            FolderObserver observer = mFolderObserversMap.get(parentPath);
-            if (observer != null) {
-                if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage())
-                        && downloadedFile.exists()) {
-                    // no matter if the download was successful or not; the
-                    // file could be down anyway due to a former download or upload
-                    observer.startWatching(downloadedFile.getName());
-                    Log_OC.d(TAG, "Resuming observance of " + downloadedFile.getAbsolutePath());
-
-                } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
-                    observer.stopWatching(downloadedFile.getName());
-                    Log_OC.d(TAG, "Pausing observance of " + downloadedFile.getAbsolutePath());
-                }
-
-            } else {
-                Log_OC.d(TAG, "No observer for path " + downloadedFile.getAbsolutePath());
-            }
-        }
-
-    }
-
-}

+ 0 - 216
src/main/java/com/owncloud/android/services/observer/FolderObserver.java

@@ -1,216 +0,0 @@
-/**
- *   ownCloud Android client application
- *
- *   @author David A. Velasco
- *   Copyright (C) 2016 ownCloud Inc.
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License version 2,
- *   as published by the Free Software Foundation.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package com.owncloud.android.services.observer;
-
-import android.accounts.Account;
-import android.content.Context;
-import android.content.Intent;
-import android.os.FileObserver;
-
-import com.owncloud.android.datamodel.FileDataStorageManager;
-import com.owncloud.android.datamodel.OCFile;
-import com.owncloud.android.lib.common.operations.RemoteOperationResult;
-import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
-import com.owncloud.android.lib.common.utils.Log_OC;
-import com.owncloud.android.operations.SynchronizeFileOperation;
-import com.owncloud.android.ui.activity.ConflictsResolveActivity;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Observer watching a folder to request the synchronization of kept-in-sync files
- * inside it.
- * 
- * Takes into account two possible update cases:
- *  - an editor directly updates the file;
- *  - an editor works on a temporary file, and later replaces the kept-in-sync file with the
- *  former.
- *  
- *  The second case requires to monitor the folder parent of the files, since a direct 
- *  {@link FileObserver} on it will not receive more events after the file is deleted to
- *  be replaced.
- */
-public class FolderObserver extends FileObserver {
-
-    private static final String TAG = FolderObserver.class.getSimpleName();
-
-    private static final int UPDATE_MASK = (
-            FileObserver.ATTRIB | FileObserver.MODIFY | 
-            FileObserver.MOVED_TO | FileObserver.CLOSE_WRITE
-    ); 
-    
-    private static final int IN_IGNORE = 32768;
-    /* 
-    private static int ALL_EVENTS_EVEN_THOSE_NOT_DOCUMENTED = 0x7fffffff;   // NEVER use 0xffffffff
-    */
-
-    private String mPath;
-    private Account mAccount;
-    private Context mContext;
-    private final Map<String, Boolean> mObservedChildren;
-
-    /**
-     * Constructor.
-     * 
-     * Initializes the observer to receive events about the update of the passed folder, and
-     * its children files.
-     * 
-     * @param path          Absolute path to the local folder to watch.
-     * @param account       OwnCloud account associated to the folder.
-     * @param context       Used to start an operation to synchronize the file, when needed.    
-     */
-    public FolderObserver(String path, Account account, Context context) {
-        super(path, UPDATE_MASK);
-        
-        if (path == null) {
-            throw new IllegalArgumentException("NULL path argument received");
-        }
-        if (account == null) {
-            throw new IllegalArgumentException("NULL account argument received");
-        }
-        if (context == null) {
-            throw new IllegalArgumentException("NULL context argument received");
-        }
-        
-        mPath = path;
-        mAccount = account;
-        mContext = context;
-        mObservedChildren = new HashMap<String, Boolean>();
-    }
-
-
-    /**
-     * Receives and processes events about updates of the monitor folder and its children files.
-     * 
-     * @param event     Kind of event occurred.
-     * @param path      Relative path of the file referred by the event.
-     */
-    @Override
-    public void onEvent(int event, String path) {
-        Log_OC.d(TAG, "Got event " + event + " on FOLDER " + mPath + " about "
-                + ((path != null) ? path : ""));
-        
-        boolean shouldSynchronize = false;
-        synchronized(mObservedChildren) {
-            if (path != null && path.length() > 0 && mObservedChildren.containsKey(path)) {
-                
-                if (    (((event & FileObserver.MODIFY) != 0) ||
-                        ((event & FileObserver.ATTRIB) != 0) ||
-                        ((event & FileObserver.MOVED_TO) != 0)) &&
-                        !mObservedChildren.get(path)) {
-
-                        mObservedChildren.put(path, Boolean.TRUE);
-                }
-                
-                if ((event & FileObserver.CLOSE_WRITE) != 0 && mObservedChildren.get(path)) {
-                    mObservedChildren.put(path, Boolean.FALSE);
-                    shouldSynchronize = true;
-                }
-            }
-        }
-        if (shouldSynchronize) {
-            startSyncOperation(path);
-        }
-        
-        if ((event & IN_IGNORE) != 0 &&
-                (path == null || path.length() == 0)) {
-            Log_OC.d(TAG, "Stopping the observance on " + mPath);
-        }
-    }
-    
-
-    /**
-     * Adds a child file to the list of files observed by the folder observer.
-     * 
-     * @param fileName         Name of a file inside the observed folder. 
-     */
-    public void startWatching(String fileName) {
-        synchronized (mObservedChildren) {
-            if (!mObservedChildren.containsKey(fileName)) {
-                mObservedChildren.put(fileName, Boolean.FALSE);
-            }
-        }
-        
-        if (new File(mPath).exists()) {
-            startWatching();
-            Log_OC.d(TAG, "Started watching parent folder " + mPath + "/");
-        }
-        // else - the observance can't be started on a file not existing;
-    }
-
-    
-    /**
-     * Removes a child file from the list of files observed by the folder observer.
-     * 
-     * @param fileName         Name of a file inside the observed folder. 
-     */
-    public void stopWatching(String fileName) {
-        synchronized (mObservedChildren) {
-            mObservedChildren.remove(fileName);
-            if (mObservedChildren.isEmpty()) {
-                stopWatching();
-                Log_OC.d(TAG, "Stopped watching parent folder " + mPath + "/");
-            }
-        }
-    }
-
-    /**
-     * @return      'True' when the folder is not watching any file inside.
-     */
-    public boolean isEmpty() {
-        synchronized (mObservedChildren) {
-            return mObservedChildren.isEmpty();
-        }
-    }
-    
-    
-    /**
-     * Triggers an operation to synchronize the contents of a file inside the observed folder with
-     * its remote counterpart in the associated ownCloud account.
-     *    
-     * @param fileName          Name of a file inside the watched folder.
-     */
-    private void startSyncOperation(String fileName) {
-        FileDataStorageManager storageManager = 
-                new FileDataStorageManager(mAccount, mContext.getContentResolver());
-        // a fresh object is needed; many things could have occurred to the file
-        // since it was registered to observe again, assuming that local files
-        // are linked to a remote file AT MOST, SOMETHING TO BE DONE;
-        OCFile file = storageManager.getFileByLocalPath(mPath + File.separator + fileName);
-        SynchronizeFileOperation sfo = 
-                new SynchronizeFileOperation(file, null, mAccount, true, mContext);
-        RemoteOperationResult result = sfo.execute(storageManager, mContext);
-        if (result.getCode() == ResultCode.SYNC_CONFLICT) {
-            // ISSUE 5: if the user is not running the app (this is a service!),
-            // this can be very intrusive; a notification should be preferred
-            Intent i = new Intent(mContext, ConflictsResolveActivity.class);
-            i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
-            i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
-            i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
-            mContext.startActivity(i);
-        }
-        // TODO save other errors in some point where the user can inspect them later;
-        // or maybe just toast them;
-        // or nothing, very strange fails
-    }
-}

+ 0 - 14
src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -85,7 +85,6 @@ import com.owncloud.android.operations.RemoveFileOperation;
 import com.owncloud.android.operations.RenameFileOperation;
 import com.owncloud.android.operations.SynchronizeFileOperation;
 import com.owncloud.android.operations.UploadFileOperation;
-import com.owncloud.android.services.observer.FileObserverService;
 import com.owncloud.android.syncadapter.FileSyncAdapter;
 import com.owncloud.android.ui.dialog.SendShareDialog;
 import com.owncloud.android.ui.dialog.SortingOrderDialogFragment;
@@ -187,19 +186,6 @@ public class FileDisplayActivity extends HookActivity
         super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account
         // is valid
 
-        /// grant that FileObserverService is watching favorite files
-        if (savedInstanceState == null) {
-            Intent initObserversIntent = FileObserverService.makeInitIntent(this);
-
-            if (FileObserverService.shouldStart()) {
-                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
-                    this.startForegroundService(initObserversIntent);
-                } else {
-                    this.startService(initObserversIntent);
-                }
-            }
-        }
-
         /// Load of saved instance state
         if (savedInstanceState != null) {
             mWaitingToPreview = savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);

+ 0 - 14
src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java

@@ -53,7 +53,6 @@ import com.owncloud.android.lib.resources.shares.ShareType;
 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
 import com.owncloud.android.operations.SynchronizeFileOperation;
 import com.owncloud.android.services.OperationsService;
-import com.owncloud.android.services.observer.FileObserverService;
 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
 import com.owncloud.android.ui.activity.FileActivity;
 import com.owncloud.android.ui.activity.ShareActivity;
@@ -725,19 +724,6 @@ public class FileOperationsHelper {
             file.setAvailableOffline(isAvailableOffline);
             mFileActivity.getStorageManager().saveFile(file);
 
-            /// register the OCFile instance in the observer service to monitor local updates
-            Intent observedFileIntent = FileObserverService.makeObservedFileIntent(
-                    mFileActivity,
-                    file,
-                    mFileActivity.getAccount(),
-                    isAvailableOffline);
-
-            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
-                mFileActivity.startForegroundService(observedFileIntent);
-            } else {
-                mFileActivity.startService(observedFileIntent);
-            }
-
             /// immediate content synchronization
             if (file.isAvailableOffline()) {
                 syncFile(file);

+ 16 - 0
src/main/java/com/owncloud/android/utils/FilesSyncHelper.java

@@ -34,6 +34,7 @@ import android.support.annotation.RequiresApi;
 import android.text.TextUtils;
 import android.util.Log;
 
+import com.evernote.android.job.JobManager;
 import com.evernote.android.job.JobRequest;
 import com.evernote.android.job.util.Device;
 import com.owncloud.android.MainApp;
@@ -48,6 +49,7 @@ import com.owncloud.android.db.OCUpload;
 import com.owncloud.android.files.services.FileUploader;
 import com.owncloud.android.jobs.FilesSyncJob;
 import com.owncloud.android.jobs.NContentObserverJob;
+import com.owncloud.android.jobs.OfflineSyncJob;
 
 import org.lukhnos.nnio.file.FileVisitResult;
 import org.lukhnos.nnio.file.Files;
@@ -59,6 +61,8 @@ import org.lukhnos.nnio.file.attribute.BasicFileAttributes;
 import java.io.File;
 import java.io.IOException;
 import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 /*
     Various utilities that make auto upload tick
@@ -296,6 +300,18 @@ public class FilesSyncHelper {
         }
     }
 
+    public static void scheduleOfflineSyncIfNeeded() {
+        Set<JobRequest> jobRequests = JobManager.instance().getAllJobRequestsForTag(OfflineSyncJob.TAG);
+        if (jobRequests.size() == 0) {
+            new JobRequest.Builder(OfflineSyncJob.TAG)
+                    .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
+                    .setUpdateCurrent(false)
+                    .build()
+                    .schedule();
+        }
+    }
+
+
     @RequiresApi(api = Build.VERSION_CODES.N)
     private static void cancelJobOnN() {
         JobScheduler jobScheduler = MainApp.getAppContext().getSystemService(JobScheduler.class);