Browse Source

Change of hearts

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

+ 4 - 1
src/main/java/com/owncloud/android/MainApp.java

@@ -48,6 +48,7 @@ import com.owncloud.android.lib.common.utils.Log_OC;
 import com.owncloud.android.ui.activity.Preferences;
 import com.owncloud.android.ui.activity.WhatsNewActivity;
 import com.owncloud.android.utils.AnalyticsUtils;
+import com.owncloud.android.utils.FilesSyncHelper;
 import com.owncloud.android.utils.PermissionUtil;
 
 import java.util.ArrayList;
@@ -127,7 +128,7 @@ public class MainApp extends MultiDexApplication {
             PreferenceManager.setAutoUploadSplitEntries(this, true);
         }
 
-        if (!JobManager.instance().getAllJobRequestsForTag(FilesSyncJob.TAG).isEmpty()) {
+        if (JobManager.instance().getAllJobRequestsForTag(FilesSyncJob.TAG).isEmpty()) {
             new JobRequest.Builder(FilesSyncJob.TAG)
                     .setPeriodic(900000L, 300000L)
                     .setUpdateCurrent(true)
@@ -135,6 +136,8 @@ public class MainApp extends MultiDexApplication {
                     .schedule();
         }
 
+        FilesSyncHelper.restartJobsIfNeeded();
+
         // register global protection with pass code
         registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
 

+ 7 - 7
src/main/java/com/owncloud/android/datamodel/FileSystemDataSet.java

@@ -29,20 +29,20 @@ public class FileSystemDataSet {
     private boolean isFolder;
     private boolean isSentForUpload;
     private long foundAt;
-    private String account;
+    private long syncedFolderId;
 
     public FileSystemDataSet() {
     }
 
     public FileSystemDataSet(int id, String localPath, long modifiedAt, boolean isFolder,
-                             boolean isSentForUpload, long foundAt, String account) {
+                             boolean isSentForUpload, long foundAt, long syncedFolderId) {
         this.id = id;
         this.localPath = localPath;
         this.modifiedAt = modifiedAt;
         this.isFolder = isFolder;
         this.isSentForUpload = isSentForUpload;
         this.foundAt = foundAt;
-        this.account = account;
+        this.syncedFolderId = syncedFolderId;
     }
 
     public int getId() {
@@ -93,11 +93,11 @@ public class FileSystemDataSet {
         isSentForUpload = sentForUpload;
     }
 
-    public String getAccount() {
-        return account;
+    public long getSyncedFolderId() {
+        return syncedFolderId;
     }
 
-    public void setAccount(String account) {
-        this.account = account;
+    public void setSyncedFolderId(long syncedFolderId) {
+        this.syncedFolderId = syncedFolderId;
     }
 }

+ 16 - 32
src/main/java/com/owncloud/android/datamodel/FilesystemDataProvider.java

@@ -27,11 +27,10 @@ import android.net.Uri;
 import com.owncloud.android.db.ProviderMeta;
 import com.owncloud.android.lib.common.utils.Log_OC;
 
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Set;
 
-import javax.annotation.Nullable;
-
 public class FilesystemDataProvider {
 
     static private final String TAG = FilesystemDataProvider.class.getSimpleName();
@@ -45,7 +44,7 @@ public class FilesystemDataProvider {
         this.contentResolver = contentResolver;
     }
 
-    public void updateFilesInList(Object[] paths, String account) {
+    public void updateFilesInList(Object[] paths, String syncedFolderId) {
         ContentValues cv = new ContentValues();
         cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD, 1);
 
@@ -58,33 +57,26 @@ public class FilesystemDataProvider {
                 ProviderMeta.ProviderTableMeta.CONTENT_URI_FILESYSTEM,
                 cv,
                 ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH + " IN (?) and " +
-                        ProviderMeta.ProviderTableMeta.FILESYSTEM_ACCOUNT + " = ?",
-                stringPaths
+                        ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID + " = ?",
+                new String[]{Arrays.toString(stringPaths), syncedFolderId}
         );
 
     }
 
-    public Set<String> getFilesForUpload(String localPath, String account, @Nullable String filetype) {
+    public Set<String> getFilesForUpload(String localPath, String syncedFolderId) {
         Set<String> localPathsToUpload = new HashSet<>();
 
         String likeParam = localPath + "%";
-        String likeFiletypeParam = "";
-        if (filetype != null) {
-            likeFiletypeParam = filetype + "%";
-        } else {
-            likeFiletypeParam = "%";
-        }
 
 
         Cursor cursor = contentResolver.query(
                 ProviderMeta.ProviderTableMeta.CONTENT_URI_FILESYSTEM,
                 null,
                 ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH + " LIKE ? and " +
-                        ProviderMeta.ProviderTableMeta.FILESYSTEM_ACCOUNT + " = ? and " +
-                        ProviderMeta.ProviderTableMeta.FILESYSTEM_MIMETYPE + " LIKE ? and " +
+                        ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID + " = ? and " +
                         ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD + " = ? and " +
                         ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_IS_FOLDER + " = ?",
-                new String[]{likeParam, account, likeFiletypeParam, "0", "0"},
+                new String[]{likeParam, syncedFolderId, "0", "0"},
                 null);
 
         if (cursor != null && cursor.moveToFirst()) {
@@ -132,9 +124,10 @@ public class FilesystemDataProvider {
         }
     }
 
-    public void storeOrUpdateFileValue(String localPath, long modifiedAt, boolean isFolder, String account,
-                                       boolean dryRun, @Nullable String mimetype) {
-        FileSystemDataSet data = getFilesystemDataSet(localPath, account);
+    public void storeOrUpdateFileValue(String localPath, long modifiedAt, boolean isFolder, SyncedFolder syncedFolder,
+                                       boolean dryRun) {
+
+        FileSystemDataSet data = getFilesystemDataSet(localPath, syncedFolder);
 
         int isFolderValue = 0;
         if (isFolder) {
@@ -151,12 +144,7 @@ public class FilesystemDataProvider {
             cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_MODIFIED, modifiedAt);
             cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_IS_FOLDER, isFolderValue);
             cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD, dryRun);
-            cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_ACCOUNT, account);
-
-            if (mimetype != null) {
-                cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_MIMETYPE, mimetype);
-            }
-
+            cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID, syncedFolder.getId());
 
             Uri result = contentResolver.insert(ProviderMeta.ProviderTableMeta.CONTENT_URI_FILESYSTEM, cv);
 
@@ -169,10 +157,6 @@ public class FilesystemDataProvider {
                 cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD, 0);
             }
 
-            if (mimetype != null) {
-                cv.put(ProviderMeta.ProviderTableMeta.FILESYSTEM_MIMETYPE, mimetype);
-            }
-
 
             int result = contentResolver.update(
                     ProviderMeta.ProviderTableMeta.CONTENT_URI_FILESYSTEM,
@@ -187,14 +171,14 @@ public class FilesystemDataProvider {
         }
     }
 
-    private FileSystemDataSet getFilesystemDataSet(String localPathParam, String account) {
+    private FileSystemDataSet getFilesystemDataSet(String localPathParam, SyncedFolder syncedFolder) {
 
         Cursor cursor = contentResolver.query(
                 ProviderMeta.ProviderTableMeta.CONTENT_URI_FILESYSTEM,
                 null,
                 ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH + " = ? and " +
-                        ProviderMeta.ProviderTableMeta.FILESYSTEM_ACCOUNT + " = ?",
-                new String[]{localPathParam, account},
+                        ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID + " = ?",
+                new String[]{localPathParam, Long.toString(syncedFolder.getId())},
                 null
         );
 
@@ -224,7 +208,7 @@ public class FilesystemDataProvider {
                     Log_OC.e(TAG, "Arbitrary value could not be created from cursor");
                 } else {
                     dataSet = new FileSystemDataSet(id, localPath, modifiedAt, isFolder, isSentForUpload, foundAt,
-                            account);
+                            syncedFolder.getId());
                 }
             }
             cursor.close();

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

@@ -208,7 +208,6 @@ public class ProviderMeta {
         public static final String FILESYSTEM_FILE_IS_FOLDER = "is_folder";
         public static final String FILESYSTEM_FILE_FOUND_RECENTLY = "found_at";
         public static final String FILESYSTEM_FILE_SENT_FOR_UPLOAD = "upload_triggered";
-        public static final String FILESYSTEM_ACCOUNT = "account";
-        public static final String FILESYSTEM_MIMETYPE = "mimetype";
+        public static final String FILESYSTEM_SYNCED_FOLDER_ID = "syncedfolder_id";
     }
 }

+ 52 - 109
src/main/java/com/owncloud/android/jobs/FilesSyncJob.java

@@ -27,12 +27,10 @@ import android.media.ExifInterface;
 import android.os.PowerManager;
 import android.support.annotation.NonNull;
 import android.text.TextUtils;
-import android.util.Log;
 
 import com.evernote.android.job.Job;
 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.datamodel.FilesystemDataProvider;
@@ -47,19 +45,13 @@ import java.io.File;
 import java.io.IOException;
 import java.text.ParsePosition;
 import java.text.SimpleDateFormat;
-import java.util.ArrayList;
 import java.util.Date;
-import java.util.List;
 import java.util.Locale;
 import java.util.TimeZone;
 
 public class FilesSyncJob extends Job {
     public static final String TAG = "FilesSyncJob";
 
-    private static final String LAST_AUTOUPLOAD_JOB_RUN = "last_autoupload_job_run";
-
-    // TODO: check for wifi status & charging status, stop and restart jobs as required
-
     @NonNull
     @Override
     protected Result onRunJob(Params params) {
@@ -71,9 +63,8 @@ public class FilesSyncJob extends Job {
                 TAG);
         wakeLock.acquire();
 
-        restartJobsIfNeeded();
-
-        FilesSyncHelper.prepareSyncStatusForAccounts();
+        FilesSyncHelper.restartJobsIfNeeded();
+        FilesSyncHelper.insertAllDBEntries();
 
         // Create all the providers we'll need
         final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
@@ -81,74 +72,62 @@ public class FilesSyncJob extends Job {
 
         for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
             if (syncedFolder.isEnabled()) {
-                String syncedFolderType;
-                if (MediaFolder.IMAGE == syncedFolder.getType()) {
-                    syncedFolderType = "image/";
-                    Log.d("IN A JOB", "SYNCED FOLDER VIDEO");
-                } else if (MediaFolder.VIDEO == syncedFolder.getType()) {
-                    syncedFolderType = "video/";
-                    Log.d("IN A JOB", "SYNCED FOLDER IMAGE");
-                } else {
-                    syncedFolderType = null;
-                    Log.d("IN A JOB", "SYNCED FOLDER ENABLED");
-                }
-
-                Log.d("IN A JOB", "SYNCED FOLDER ENABLED");
-
                 // ignore custom folders for now
-                if (syncedFolderType != null) {
+                if (MediaFolder.CUSTOM != syncedFolder.getType()) {
                     for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
-                            syncedFolder.getAccount(), syncedFolderType)) {
-                        File file = new File(path);
-
-                        Log.d("IN A JOB", "PERO");
-                        Long lastModificationTime = file.lastModified();
-                        final Locale currentLocale = context.getResources().getConfiguration().locale;
-
-                        if (syncedFolder.equals("image/")) {
-                            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();
+                            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());
                                     }
-
-                                } 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.updateFilesInList(new Object[]{path}, syncedFolder.getAccount());
+                            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.updateFilesInList(new Object[]{path},
+                                    Long.toString(syncedFolder.getId()));
+                        }
                     }
                 }
             }
@@ -157,40 +136,4 @@ public class FilesSyncJob extends Job {
         wakeLock.release();
         return Result.SUCCESS;
     }
-
-
-    private void restartJobsIfNeeded() {
-        final Context context = MainApp.getAppContext();
-        List<Integer> restartedJobIds = new ArrayList<Integer>();
-        int jobId;
-        boolean restartedInCurrentIteration = false;
-
-        for (JobRequest jobRequest : JobManager.instance().getAllJobRequestsForTag(AutoUploadJob.TAG)) {
-            restartedInCurrentIteration = false;
-            // Handle case of charging
-            if (jobRequest.requiresCharging() && Device.isCharging(context)) {
-                if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.CONNECTED) &&
-                        !Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
-                    jobId = jobRequest.cancelAndEdit().build().schedule();
-                    restartedInCurrentIteration = true;
-                } else if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.UNMETERED) &&
-                        Device.getNetworkType(context).equals(JobRequest.NetworkType.UNMETERED)) {
-                    jobId = jobRequest.cancelAndEdit().build().schedule();
-                    restartedInCurrentIteration = true;
-                }
-            }
-
-            // Handle case of wifi
-
-            if (!restartedInCurrentIteration) {
-                if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.CONNECTED) &&
-                        !Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
-                    jobRequest.cancelAndEdit().build().schedule();
-                } else if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.UNMETERED) &&
-                        Device.getNetworkType(context).equals(JobRequest.NetworkType.UNMETERED)) {
-                    jobRequest.cancelAndEdit().build().schedule();
-                }
-            }
-        }
-    }
 }

+ 1 - 2
src/main/java/com/owncloud/android/providers/FileContentProvider.java

@@ -1258,8 +1258,7 @@ public class FileContentProvider extends ContentProvider {
                 + ProviderTableMeta.FILESYSTEM_FILE_IS_FOLDER + " INTEGER, "
                 + ProviderTableMeta.FILESYSTEM_FILE_FOUND_RECENTLY + " LONG, "
                 + ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD + " INTEGER, "
-                + ProviderTableMeta.FILESYSTEM_ACCOUNT + " STRING, "
-                + ProviderTableMeta.FILESYSTEM_MIMETYPE + " STRING, "
+                + ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID + " STRING, "
                 + ProviderTableMeta.FILESYSTEM_FILE_MODIFIED + " LONG );"
         );
     }

+ 0 - 6
src/main/java/com/owncloud/android/ui/activity/FolderSyncActivity.java

@@ -480,9 +480,6 @@ public class FolderSyncActivity extends FileActivity implements FolderSyncAdapte
                 syncedFolderDisplayItem.setId(storedId);
             }
         }
-
-        FilesSyncHelper.prepareSyncStatusForAccounts();
-
     }
 
     @Override
@@ -525,7 +522,6 @@ public class FolderSyncActivity extends FileActivity implements FolderSyncAdapte
             long storedId = mSyncedFolderProvider.storeFolderSync(newCustomFolder);
             if (storedId != -1) {
                 newCustomFolder.setId(storedId);
-                FilesSyncHelper.prepareSyncStatusForAccounts();
             }
             mAdapter.addSyncFolderItem(newCustomFolder);
         } else {
@@ -540,12 +536,10 @@ public class FolderSyncActivity extends FileActivity implements FolderSyncAdapte
                 long storedId = mSyncedFolderProvider.storeFolderSync(item);
                 if (storedId != -1) {
                     item.setId(storedId);
-                    FilesSyncHelper.prepareSyncStatusForAccounts();
                 }
             } else {
                 // existing synced folder setup to be updated
                 mSyncedFolderProvider.updateSyncFolder(item);
-                FilesSyncHelper.prepareSyncStatusForAccounts();
             }
 
             if(dirty) {

+ 68 - 55
src/main/java/com/owncloud/android/utils/FilesSyncHelper.java

@@ -20,107 +20,120 @@
  */
 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 com.evernote.android.job.JobManager;
+import com.evernote.android.job.JobRequest;
+import com.evernote.android.job.util.Device;
 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.jobs.AutoUploadJob;
 
 import java.io.File;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Set;
 
 public class FilesSyncHelper {
 
-    private static final String LAST_AUTOUPLOAD_JOB_RUN = "last_autoupload_job_run";
-
-
-    private static void insertAllDBEntries() {
+    public static void insertAllDBEntries() {
         boolean dryRun = false;
 
-        final Context context = MainApp.getAppContext();
-        final ContentResolver contentResolver = context.getContentResolver();
-        ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
-
-        for (Account account : AccountUtils.getAccounts(context)) {
-            if (TextUtils.isEmpty(arbitraryDataProvider.getValue(account.name, LAST_AUTOUPLOAD_JOB_RUN))) {
-                dryRun = true;
-            } else {
-                dryRun = false;
-            }
-
-            FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, dryRun,
-                    account.name);
-            FilesSyncHelper.insertContentIntoDB(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, dryRun, account.name);
-            FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI, dryRun,
-                    account.name);
-            FilesSyncHelper.insertContentIntoDB(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, dryRun, account.name);
-        }
-    }
-
-    public static void prepareSyncStatusForAccounts() {
         final Context context = MainApp.getAppContext();
         final ContentResolver contentResolver = context.getContentResolver();
         SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
-        ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
 
-        Set<String> enabledAccounts = new HashSet<>();
         for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
-            enabledAccounts.add(syncedFolder.getAccount());
-        }
-
-        for (String enabledAccount : enabledAccounts) {
-            arbitraryDataProvider.storeOrUpdateKeyValue(enabledAccount, LAST_AUTOUPLOAD_JOB_RUN,
-                    Long.toString(System.currentTimeMillis()));
+            if (syncedFolder.isEnabled()) {
+
+                if (MediaFolder.IMAGE == syncedFolder.getType()) {
+                    FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
+                            , dryRun, syncedFolder);
+                    FilesSyncHelper.insertContentIntoDB(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, dryRun,
+                            syncedFolder);
+                } else if (MediaFolder.VIDEO == syncedFolder.getType()) {
+                    FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI,
+                            dryRun, syncedFolder);
+                    FilesSyncHelper.insertContentIntoDB(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, dryRun,
+                            syncedFolder);
+                } else {
+                    // custom folder, do nothing
+                }
+            }
         }
-
-        ArrayList<String> accountsArrayList = new ArrayList<>();
-        accountsArrayList.addAll(enabledAccounts);
-        arbitraryDataProvider.deleteForKeyWhereAccountNotIn(accountsArrayList, LAST_AUTOUPLOAD_JOB_RUN);
-
-        insertAllDBEntries();
-
     }
 
-    public static void insertContentIntoDB(Uri uri, boolean dryRun, String account) {
+    private static void insertContentIntoDB(Uri uri, boolean dryRun, SyncedFolder syncedFolder) {
         final Context context = MainApp.getAppContext();
         final ContentResolver contentResolver = context.getContentResolver();
 
         Cursor cursor;
-        int column_index_data, column_index_date_modified, column_index_mimetype;
+        int column_index_data, column_index_date_modified;
 
         final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
 
         String contentPath;
         boolean isFolder;
 
-        String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_MODIFIED,
-                MediaStore.MediaColumns.MIME_TYPE};
+        String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_MODIFIED};
+
+        String path = syncedFolder.getLocalPath();
+        if (!path.endsWith("/")) {
+            path = path + "/%";
+        } else {
+            path = path + "%";
+        }
+
+        cursor = context.getContentResolver().query(uri, projection, MediaStore.MediaColumns.DATA + " LIKE ?",
+                new String[]{path}, null);
 
-        cursor = context.getContentResolver().query(uri, projection, null, null, null);
         if (cursor != null) {
             column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
             column_index_date_modified = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED);
-            column_index_mimetype = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE);
             while (cursor.moveToNext()) {
                 contentPath = cursor.getString(column_index_data);
                 isFolder = new File(contentPath).isDirectory();
                 filesystemDataProvider.storeOrUpdateFileValue(cursor.getString(column_index_data),
-                        cursor.getLong(column_index_date_modified), isFolder, account, dryRun,
-                        cursor.getString(column_index_mimetype));
+                        cursor.getLong(column_index_date_modified), isFolder, syncedFolder, dryRun);
             }
             cursor.close();
         }
     }
 
+    public static void restartJobsIfNeeded() {
+        final Context context = MainApp.getAppContext();
+        boolean restartedInCurrentIteration = false;
+
+        for (JobRequest jobRequest : JobManager.instance().getAllJobRequestsForTag(AutoUploadJob.TAG)) {
+            restartedInCurrentIteration = false;
+            // Handle case of charging
+            if (jobRequest.requiresCharging() && Device.isCharging(context)) {
+                if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.CONNECTED) &&
+                        !Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
+                    jobRequest.cancelAndEdit().build().schedule();
+                    restartedInCurrentIteration = true;
+                } else if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.UNMETERED) &&
+                        Device.getNetworkType(context).equals(JobRequest.NetworkType.UNMETERED)) {
+                    jobRequest.cancelAndEdit().build().schedule();
+                    restartedInCurrentIteration = true;
+                }
+            }
+
+            // Handle case of wifi
+
+            if (!restartedInCurrentIteration) {
+                if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.CONNECTED) &&
+                        !Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
+                    jobRequest.cancelAndEdit().build().schedule();
+                } else if (jobRequest.requiredNetworkType().equals(JobRequest.NetworkType.UNMETERED) &&
+                        Device.getNetworkType(context).equals(JobRequest.NetworkType.UNMETERED)) {
+                    jobRequest.cancelAndEdit().build().schedule();
+                }
+            }
+        }
+    }
 }