Browse Source

Add support for retry & custom folders

Signed-off-by: Mario Danic <mario@lovelyhq.com>
Mario Danic 7 years ago
parent
commit
26c8e696fc

+ 2 - 0
src/main/java/com/owncloud/android/datamodel/UploadsStorageManager.java

@@ -128,6 +128,8 @@ public class UploadsStorageManager extends Observable {
         cv.put(ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER, ocUpload.isCreateRemoteFolder() ? 1 : 0);
         cv.put(ProviderTableMeta.UPLOADS_LAST_RESULT, ocUpload.getLastResult().getValue());
         cv.put(ProviderTableMeta.UPLOADS_CREATED_BY, ocUpload.getCreadtedBy());
+        cv.put(ProviderTableMeta.UPLOADS_IS_WHILE_CHARGING_ONLY, ocUpload.isWhileChargingOnly() ? 1 : 0);
+        cv.put(ProviderTableMeta.UPLOADS_IS_WIFI_ONLY, ocUpload.isUseWifiOnly() ? 1 : 0);
 
         Uri result = getDB().insert(ProviderTableMeta.CONTENT_URI_UPLOADS, cv);
 

+ 39 - 1
src/main/java/com/owncloud/android/db/OCUpload.java

@@ -100,8 +100,18 @@ public class OCUpload implements Parcelable {
      */
     private long mUploadEndTimeStamp;
 
-
     /**
+     * Upload only via wifi?
+     */
+    private boolean mIsUseWifiOnly;
+    /**
+     * Upload only if phone being charged?
+     */
+    private boolean mIsWhileChargingOnly;
+    /**
+
+
+     /**
      * Main constructor
      *
      * @param localPath         Absolute path in the local file system to the file to be uploaded.
@@ -151,6 +161,8 @@ public class OCUpload implements Parcelable {
         mUploadStatus = UploadStatus.UPLOAD_IN_PROGRESS;
         mLastResult = UploadResult.UNKNOWN;
         mCreatedBy = UploadFileOperation.CREATED_BY_USER;
+        mIsUseWifiOnly = true;
+        mIsWhileChargingOnly = false;
     }
 
     // Getters & Setters
@@ -340,6 +352,28 @@ public class OCUpload implements Parcelable {
         }
     };
 
+    /**
+     * @return the isUseWifiOnly
+     */
+    public boolean isUseWifiOnly() {
+        return mIsUseWifiOnly;
+    }
+
+    /**
+     * @param isUseWifiOnly the isUseWifiOnly to set
+     */
+    public void setUseWifiOnly(boolean isUseWifiOnly) {
+        this.mIsUseWifiOnly = isUseWifiOnly;
+    }
+
+    public void setWhileChargingOnly(boolean isWhileChargingOnly) {
+        this.mIsWhileChargingOnly = isWhileChargingOnly;
+    }
+
+    public boolean isWhileChargingOnly() {
+        return mIsWhileChargingOnly;
+    }
+
     /**
      * Reconstruct from parcel
      *
@@ -369,6 +403,8 @@ public class OCUpload implements Parcelable {
             mLastResult = UploadResult.UNKNOWN;
         }
         mCreatedBy = source.readInt();
+        mIsUseWifiOnly = (source.readInt() == 1);
+        mIsWhileChargingOnly = (source.readInt() == 1);
     }
 
 
@@ -390,6 +426,8 @@ public class OCUpload implements Parcelable {
         dest.writeLong(mUploadEndTimeStamp);
         dest.writeString(((mLastResult == null) ? "" : mLastResult.name()));
         dest.writeInt(mCreatedBy);
+        dest.writeInt(mIsUseWifiOnly ? 1 : 0);
+        dest.writeInt(mIsWhileChargingOnly ? 1 : 0);
     }
 
     enum CanUploadFileNowStatus {NOW, LATER, FILE_GONE, ERROR}

+ 2 - 0
src/main/java/com/owncloud/android/db/ProviderMeta.java

@@ -173,6 +173,8 @@ public class ProviderMeta {
         public static final String UPLOADS_LAST_RESULT = "last_result";
         public static final String UPLOADS_CREATED_BY = "created_by";
         public static final String UPLOADS_DEFAULT_SORT_ORDER = ProviderTableMeta._ID + " collate nocase desc";
+        public static final String UPLOADS_IS_WHILE_CHARGING_ONLY = "is_while_charging_only";
+        public static final String UPLOADS_IS_WIFI_ONLY = "is_wifi_only";
 
         // Columns of synced folder table
         public static final String SYNCED_FOLDER_LOCAL_PATH = "local_path";

+ 22 - 5
src/main/java/com/owncloud/android/files/services/FileUploader.java

@@ -143,6 +143,9 @@ public class FileUploader extends Service
      * Key to signal what is the origin of the upload request
      */
     public static final String KEY_CREATED_BY = "CREATED_BY";
+
+    public static final String KEY_WHILE_ON_WIFI_ONLY = "KEY_ON_WIFI_ONLY";
+
     /**
      * Set to true if upload is to performed only when phone is being charged.
      */
@@ -150,6 +153,7 @@ public class FileUploader extends Service
 
     public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
 
+
     public static final int LOCAL_BEHAVIOUR_COPY = 0;
     public static final int LOCAL_BEHAVIOUR_MOVE = 1;
     public static final int LOCAL_BEHAVIOUR_FORGET = 2;
@@ -213,7 +217,9 @@ public class FileUploader extends Service
                 String[] mimeTypes,
                 Integer behaviour,
                 Boolean createRemoteFolder,
-                int createdBy
+                int createdBy,
+                boolean requiresWifi,
+                boolean requiresCharging
         ) {
             Intent intent = new Intent(context, FileUploader.class);
 
@@ -224,6 +230,9 @@ public class FileUploader extends Service
             intent.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, behaviour);
             intent.putExtra(FileUploader.KEY_CREATE_REMOTE_FOLDER, createRemoteFolder);
             intent.putExtra(FileUploader.KEY_CREATED_BY, createdBy);
+            intent.putExtra(FileUploader.KEY_WHILE_ON_WIFI_ONLY, requiresWifi);
+            intent.putExtra(FileUploader.KEY_WHILE_CHARGING_ONLY, requiresCharging);
+
 
             context.startService(intent);
         }
@@ -232,7 +241,8 @@ public class FileUploader extends Service
          * Call to upload a new single file
          */
         public void uploadNewFile(Context context, Account account, String localPath, String remotePath, int
-                behaviour, String mimeType, boolean createRemoteFile, int createdBy) {
+                behaviour, String mimeType, boolean createRemoteFile, int createdBy, boolean requiresWifi,
+                                  boolean requiresCharging) {
 
             uploadNewFile(
                 context,
@@ -242,7 +252,9 @@ public class FileUploader extends Service
                 new String[]{mimeType},
                 behaviour,
                 createRemoteFile,
-                createdBy
+                createdBy,
+                requiresWifi,
+                requiresCharging
             );
         }
 
@@ -457,6 +469,9 @@ public class FileUploader extends Service
             boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
             int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
 
+            boolean onWifiOnly = intent.getBooleanExtra(KEY_WHILE_ON_WIFI_ONLY, false);
+            boolean whileChargingOnly = intent.getBooleanExtra(KEY_WHILE_CHARGING_ONLY, false);
+
             if (intent.hasExtra(KEY_FILE) && files == null) {
                 Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
                 return Service.START_NOT_STICKY;
@@ -502,10 +517,12 @@ public class FileUploader extends Service
                     ocUpload.setCreateRemoteFolder(isCreateRemoteFolder);
                     ocUpload.setCreatedBy(createdBy);
                     ocUpload.setLocalAction(localAction);
-                    /*ocUpload.setUseWifiOnly(isUseWifiOnly);
-                    ocUpload.setWhileChargingOnly(isWhileChargingOnly);*/
+                    ocUpload.setUseWifiOnly(onWifiOnly);
+                    ocUpload.setWhileChargingOnly(whileChargingOnly);
+
                     ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
 
+
                     newUpload = new UploadFileOperation(
                             account,
                             files[i],

+ 16 - 16
src/main/java/com/owncloud/android/jobs/AutoUploadJob.java

@@ -47,10 +47,13 @@ import java.nio.channels.OverlappingFileLockException;
 public class AutoUploadJob extends Job {
     public static final String TAG = "AutoUploadJob";
 
-    static final String LOCAL_PATH = "filePath";
-    static final String REMOTE_PATH = "remotePath";
+    public static final String LOCAL_PATH = "filePath";
+    public static final String REMOTE_PATH = "remotePath";
     public static final String ACCOUNT = "account";
-    static final String UPLOAD_BEHAVIOUR = "uploadBehaviour";
+    public static final String UPLOAD_BEHAVIOUR = "uploadBehaviour";
+    public static final String REQUIRES_WIFI = "requiresWifi";
+    public static final String REQUIRES_CHARGING = "requiresCharging";
+
 
     @NonNull
     @Override
@@ -69,10 +72,11 @@ public class AutoUploadJob extends Job {
         final Account account = AccountUtils.getOwnCloudAccountByName(context, bundle.getString(ACCOUNT, ""));
         final Integer uploadBehaviour = bundle.getInt(UPLOAD_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_FORGET);
 
+        final boolean requiresWifi = bundle.getBoolean(REQUIRES_WIFI, false);
+        final boolean requiresCharging = bundle.getBoolean(REQUIRES_CHARGING, false);
 
         File file = new File(filePath);
 
-
         // File can be deleted between job generation and job execution. If file does not exist, just ignore it
         if (file.exists()) {
             final String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(file.getAbsolutePath());
@@ -93,29 +97,25 @@ public class AutoUploadJob extends Job {
                         uploadBehaviour,
                         mimeType,
                         true,           // create parent folder if not existent
-                        UploadFileOperation.CREATED_BY_USER
+                        UploadFileOperation.CREATED_BY_USER,
+                        requiresWifi,
+                        requiresCharging
                 );
 
+                lock.release();
+                wakeLock.release();
+                return Result.SUCCESS;
+
             } catch (FileNotFoundException e) {
                 Log_OC.d(TAG, "Something went wrong while trying to access file");
             } catch (OverlappingFileLockException e) {
                 Log_OC.d(TAG, "Overlapping file lock exception");
             } catch (IOException e) {
                 Log_OC.d(TAG, "IO exception");
-            }  finally {
-                if (lock != null) {
-                    try {
-                        lock.release();
-                    } catch (IOException e) {
-                        Log_OC.d(TAG, "Failed to release lock");
-                    }
-                }
             }
         }
 
-
         wakeLock.release();
-        return Result.SUCCESS;
+        return Result.RESCHEDULE;
     }
-
 }

+ 3 - 1
src/main/java/com/owncloud/android/jobs/ContactsBackupJob.java

@@ -157,7 +157,9 @@ public class ContactsBackupJob extends Job {
                     FileUploader.LOCAL_BEHAVIOUR_MOVE,
                     null,
                     true,
-                    UploadFileOperation.CREATED_BY_USER
+                    UploadFileOperation.CREATED_BY_USER,
+                    false,
+                    false
             );
 
         } catch (Exception e) {

+ 55 - 53
src/main/java/com/owncloud/android/jobs/FilesSyncJob.java

@@ -59,7 +59,6 @@ public class FilesSyncJob extends Job {
         - there are cases where we could upload the file twice, like: upload starts and fails. file gets changed,
         and gets uploaded. we manually restart the failed upload.
         - we need to handle upload directly in a job rather than via service to properly handle failures etc
-        - no automatic retry
      */
 
     @NonNull
@@ -84,62 +83,65 @@ public class FilesSyncJob extends Job {
 
             for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
                 if (syncedFolder.isEnabled()) {
-                    // ignore custom folders for now
-                    if (MediaFolder.CUSTOM != syncedFolder.getType()) {
-                        for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
-                                Long.toString(syncedFolder.getId()))) {
-                            if (JobManager.instance().getAllJobRequests().size() < 80) {
-                                File file = new File(path);
-
-                                Long lastModificationTime = file.lastModified();
-                                final Locale currentLocale = context.getResources().getConfiguration().locale;
-
-                                if (MediaFolder.IMAGE == syncedFolder.getType()) {
-                                    String mimetypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
-                                    if ("image/jpeg".equalsIgnoreCase(mimetypeString) || "image/tiff".
-                                            equalsIgnoreCase(mimetypeString)) {
-                                        try {
-                                            ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
-                                            String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
-                                            if (!TextUtils.isEmpty(exifDate)) {
-                                                ParsePosition pos = new ParsePosition(0);
-                                                SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss",
-                                                        currentLocale);
-                                                sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
-                                                Date dateTime = sFormatter.parse(exifDate, pos);
-                                                lastModificationTime = dateTime.getTime();
-                                            }
-
-                                        } catch (IOException e) {
-                                            Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
+                    for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
+                            Long.toString(syncedFolder.getId()))) {
+                        if (JobManager.instance().getAllJobRequests().size() < 80) {
+                            File file = new File(path);
+
+                            Long lastModificationTime = file.lastModified();
+                            final Locale currentLocale = context.getResources().getConfiguration().locale;
+
+                            if (MediaFolder.IMAGE == syncedFolder.getType()) {
+                                String mimetypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
+                                if ("image/jpeg".equalsIgnoreCase(mimetypeString) || "image/tiff".
+                                        equalsIgnoreCase(mimetypeString)) {
+                                    try {
+                                        ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
+                                        String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
+                                        if (!TextUtils.isEmpty(exifDate)) {
+                                            ParsePosition pos = new ParsePosition(0);
+                                            SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss",
+                                                    currentLocale);
+                                            sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
+                                            Date dateTime = sFormatter.parse(exifDate, pos);
+                                            lastModificationTime = dateTime.getTime();
                                         }
+
+                                    } catch (IOException e) {
+                                        Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
                                     }
                                 }
-
-                                PersistableBundleCompat bundle = new PersistableBundleCompat();
-                                bundle.putString(AutoUploadJob.LOCAL_PATH, file.getAbsolutePath());
-                                bundle.putString(AutoUploadJob.REMOTE_PATH, FileStorageUtils.getInstantUploadFilePath(
-                                        currentLocale,
-                                        syncedFolder.getRemotePath(), file.getName(),
-                                        lastModificationTime,
-                                        syncedFolder.getSubfolderByDate()));
-                                bundle.putString(AutoUploadJob.ACCOUNT, syncedFolder.getAccount());
-                                bundle.putInt(AutoUploadJob.UPLOAD_BEHAVIOUR, syncedFolder.getUploadAction());
-
-                                new JobRequest.Builder(AutoUploadJob.TAG)
-                                        .setExecutionWindow(30_000L, 80_000L)
-                                        .setRequiresCharging(syncedFolder.getChargingOnly())
-                                        .setRequiredNetworkType(syncedFolder.getWifiOnly() ? JobRequest.NetworkType.UNMETERED :
-                                                JobRequest.NetworkType.CONNECTED)
-                                        .setExtras(bundle)
-                                        .setRequirementsEnforced(true)
-                                        .setUpdateCurrent(false)
-                                        .build()
-                                        .schedule();
-
-                                filesystemDataProvider.updateFilesystemFileAsSentForUpload(path,
-                                        Long.toString(syncedFolder.getId()));
                             }
+
+                            PersistableBundleCompat bundle = new PersistableBundleCompat();
+
+                            boolean needsCharging = syncedFolder.getChargingOnly();
+                            boolean needsWifi = syncedFolder.getWifiOnly();
+
+                            bundle.putString(AutoUploadJob.LOCAL_PATH, file.getAbsolutePath());
+                            bundle.putString(AutoUploadJob.REMOTE_PATH, FileStorageUtils.getInstantUploadFilePath(
+                                    currentLocale,
+                                    syncedFolder.getRemotePath(), file.getName(),
+                                    lastModificationTime,
+                                    syncedFolder.getSubfolderByDate()));
+                            bundle.putString(AutoUploadJob.ACCOUNT, syncedFolder.getAccount());
+                            bundle.putInt(AutoUploadJob.UPLOAD_BEHAVIOUR, syncedFolder.getUploadAction());
+                            bundle.putBoolean(AutoUploadJob.REQUIRES_WIFI, needsWifi);
+                            bundle.putBoolean(AutoUploadJob.REQUIRES_CHARGING, needsCharging);
+
+                            new JobRequest.Builder(AutoUploadJob.TAG)
+                                    .setExecutionWindow(30_000L, 80_000L)
+                                    .setRequiresCharging(needsCharging)
+                                    .setRequiredNetworkType(syncedFolder.getWifiOnly() ? JobRequest.NetworkType.UNMETERED :
+                                            JobRequest.NetworkType.CONNECTED)
+                                    .setExtras(bundle)
+                                    .setRequirementsEnforced(true)
+                                    .setUpdateCurrent(false)
+                                    .build()
+                                    .schedule();
+
+                            filesystemDataProvider.updateFilesystemFileAsSentForUpload(path,
+                                    Long.toString(syncedFolder.getId()));
                         }
                     }
                 }

+ 10 - 0
src/main/java/com/owncloud/android/providers/FileContentProvider.java

@@ -1051,6 +1051,14 @@ public class FileContentProvider extends ContentProvider {
                             ADD_COLUMN + ProviderTableMeta.SYNCED_FOLDER_TYPE +
                             " INTEGER " + " DEFAULT 0");
 
+                    Log_OC.i(SQL, "Add charging and wifi columns to uploads");
+                    db.execSQL(ALTER_TABLE + ProviderTableMeta.UPLOADS_TABLE_NAME +
+                            ADD_COLUMN + ProviderTableMeta.UPLOADS_IS_WIFI_ONLY +
+                            " INTEGER " + " DEFAULT 0");
+
+                    db.execSQL(ALTER_TABLE + ProviderTableMeta.UPLOADS_TABLE_NAME +
+                            ADD_COLUMN + ProviderTableMeta.UPLOADS_IS_WHILE_CHARGING_ONLY +
+                            " INTEGER " + " DEFAULT 0");
 
                     // create Filesystem table
                     Log_OC.i(SQL, "Create filesystem table");
@@ -1194,6 +1202,8 @@ public class FileContentProvider extends ContentProvider {
                 + ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER + INTEGER  // boolean
                 + ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP + INTEGER
                 + ProviderTableMeta.UPLOADS_LAST_RESULT + INTEGER     // Upload LastResult
+                + ProviderTableMeta.UPLOADS_IS_WHILE_CHARGING_ONLY + INTEGER  // boolean
+                + ProviderTableMeta.UPLOADS_IS_WIFI_ONLY + INTEGER // boolean
                 + ProviderTableMeta.UPLOADS_CREATED_BY + " INTEGER );"    // Upload createdBy
         );
 

+ 3 - 1
src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -914,7 +914,9 @@ public class FileDisplayActivity extends HookActivity
                     null,           // MIME type will be detected from file name
                     behaviour,
                     false,          // do not create parent folder if not existent
-                    UploadFileOperation.CREATED_BY_USER
+                    UploadFileOperation.CREATED_BY_USER,
+                    false,
+                    false
             );
 
         } else {

+ 3 - 1
src/main/java/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java

@@ -913,7 +913,9 @@ public class ReceiveExternalFilesActivity extends FileActivity
             FileUploader.LOCAL_BEHAVIOUR_COPY,
             null,
             true,
-            UploadFileOperation.CREATED_BY_USER
+            UploadFileOperation.CREATED_BY_USER,
+            false,
+            false
             );
         finish();
     }

+ 3 - 1
src/main/java/com/owncloud/android/ui/asynctasks/CopyAndUploadContentUrisTask.java

@@ -228,7 +228,9 @@ public class CopyAndUploadContentUrisTask extends AsyncTask<Object, Void, Result
             behaviour,
             mimeType,
             false,      // do not create parent folder if not existent
-            UploadFileOperation.CREATED_BY_USER
+            UploadFileOperation.CREATED_BY_USER,
+            false,
+             false
         );
     }
 

+ 3 - 1
src/main/java/com/owncloud/android/ui/helpers/UriUploader.java

@@ -166,7 +166,9 @@ public class UriUploader {
                 mBehaviour,
                 null,       // MIME type will be detected from file name
                 false,      // do not create parent folder if not existent
-                UploadFileOperation.CREATED_BY_USER
+                UploadFileOperation.CREATED_BY_USER,
+                false,
+                false
         );
     }
 

+ 95 - 3
src/main/java/com/owncloud/android/utils/FilesSyncHelper.java

@@ -20,27 +20,46 @@
  */
 package com.owncloud.android.utils;
 
+import android.accounts.Account;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.database.Cursor;
 import android.net.Uri;
 import android.provider.MediaStore;
 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.evernote.android.job.util.support.PersistableBundleCompat;
 import com.owncloud.android.MainApp;
+import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.datamodel.ArbitraryDataProvider;
 import com.owncloud.android.datamodel.FilesystemDataProvider;
 import com.owncloud.android.datamodel.MediaFolder;
 import com.owncloud.android.datamodel.SyncedFolder;
 import com.owncloud.android.datamodel.SyncedFolderProvider;
+import com.owncloud.android.datamodel.UploadsStorageManager;
+import com.owncloud.android.db.OCUpload;
 import com.owncloud.android.jobs.AutoUploadJob;
 
+import org.lukhnos.nnio.file.FileVisitResult;
+import org.lukhnos.nnio.file.Files;
+import org.lukhnos.nnio.file.Path;
+import org.lukhnos.nnio.file.Paths;
+import org.lukhnos.nnio.file.SimpleFileVisitor;
+import org.lukhnos.nnio.file.attribute.BasicFileAttributes;
+
 import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.channels.OverlappingFileLockException;
 
 public class FilesSyncHelper {
+    public static final String TAG = "FileSyncHelper";
 
     public static void insertAllDBEntriesForSyncedFolder(SyncedFolder syncedFolder) {
         final Context context = MainApp.getAppContext();
@@ -73,13 +92,50 @@ public class FilesSyncHelper {
             }
 
         } else {
-            // custom folder, do nothing
+            try {
+
+                FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
+                Path path = Paths.get(syncedFolder.getLocalPath());
+
+                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
+                    @Override
+                    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
+
+                        File file = path.toFile();
+                        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
+                        FileLock lock = channel.lock();
+                        try {
+                            lock = channel.tryLock();
+                            filesystemDataProvider.storeOrUpdateFileValue(path.toAbsolutePath().toString(),
+                                    attrs.lastModifiedTime().toMillis(), file.isDirectory(), syncedFolder, dryRun);
+                        } catch (OverlappingFileLockException e) {
+                            filesystemDataProvider.storeOrUpdateFileValue(path.toAbsolutePath().toString(),
+                                    attrs.lastModifiedTime().toMillis(), file.isDirectory(), syncedFolder, dryRun);
+                        } finally {
+                            lock.release();
+                        }
+
+                        return FileVisitResult.CONTINUE;
+                    }
+
+                    @Override
+                    public FileVisitResult visitFileFailed(Path file, IOException exc) {
+                        return FileVisitResult.CONTINUE;
+                    }
+                });
+
+                if (dryRun) {
+                    arbitraryDataProvider.storeOrUpdateKeyValue("global", syncedFolderInitiatedKey,
+                            "1");
+                }
+
+            } catch (IOException e) {
+                Log.d(TAG, "Something went wrong while indexing files for auto upload");
+            }
         }
     }
 
     public static void insertAllDBEntries() {
-        boolean dryRun;
-
         final Context context = MainApp.getAppContext();
         final ContentResolver contentResolver = context.getContentResolver();
         SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
@@ -159,5 +215,41 @@ public class FilesSyncHelper {
                 }
             }
         }
+
+        UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
+        OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
+
+        boolean accountExists = false;
+        for (OCUpload failedUpload: failedUploads) {
+            accountExists = false;
+            uploadsStorageManager.removeUpload(failedUpload);
+
+            // check if accounts still exists
+            for (Account account : AccountUtils.getAccounts(context)) {
+                if (account.name.equals(failedUpload.getAccountName())) {
+                    accountExists = true;
+                    break;
+                }
+            }
+
+            if (accountExists) {
+                PersistableBundleCompat bundle = new PersistableBundleCompat();
+                bundle.putString(AutoUploadJob.LOCAL_PATH, failedUpload.getLocalPath());
+                bundle.putString(AutoUploadJob.REMOTE_PATH, failedUpload.getRemotePath());
+                bundle.putString(AutoUploadJob.ACCOUNT, failedUpload.getAccountName());
+                bundle.putInt(AutoUploadJob.UPLOAD_BEHAVIOUR, failedUpload.getLocalAction());
+
+                new JobRequest.Builder(AutoUploadJob.TAG)
+                        .setExecutionWindow(30_000L, 80_000L)
+                        .setRequiresCharging(failedUpload.isWhileChargingOnly())
+                        .setRequiredNetworkType(failedUpload.isUseWifiOnly() ? JobRequest.NetworkType.UNMETERED :
+                                JobRequest.NetworkType.CONNECTED)
+                        .setExtras(bundle)
+                        .setRequirementsEnforced(true)
+                        .setUpdateCurrent(false)
+                        .build()
+                        .schedule();
+            }
+        }
     }
 }