FilesSyncHelper.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Mario Danic
  5. * @author Chris Narkiewicz
  6. * Copyright (C) 2017 Mario Danic
  7. * Copyright (C) 2017 Nextcloud
  8. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  12. * License as published by the Free Software Foundation; either
  13. * version 3 of the License, or any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public
  21. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package com.owncloud.android.utils;
  24. import android.accounts.Account;
  25. import android.app.job.JobInfo;
  26. import android.app.job.JobScheduler;
  27. import android.content.ComponentName;
  28. import android.content.ContentResolver;
  29. import android.content.Context;
  30. import android.database.Cursor;
  31. import android.net.Uri;
  32. import android.os.Build;
  33. import android.provider.MediaStore;
  34. import android.text.TextUtils;
  35. import android.util.Log;
  36. import com.evernote.android.job.JobManager;
  37. import com.evernote.android.job.JobRequest;
  38. import com.evernote.android.job.util.Device;
  39. import com.nextcloud.client.account.UserAccountManager;
  40. import com.nextcloud.client.preferences.AppPreferences;
  41. import com.owncloud.android.MainApp;
  42. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  43. import com.owncloud.android.datamodel.FilesystemDataProvider;
  44. import com.owncloud.android.datamodel.MediaFolderType;
  45. import com.owncloud.android.datamodel.SyncedFolder;
  46. import com.owncloud.android.datamodel.SyncedFolderProvider;
  47. import com.owncloud.android.datamodel.UploadsStorageManager;
  48. import com.owncloud.android.db.OCUpload;
  49. import com.owncloud.android.files.services.FileUploader;
  50. import com.owncloud.android.jobs.FilesSyncJob;
  51. import com.owncloud.android.jobs.NContentObserverJob;
  52. import com.owncloud.android.jobs.OfflineSyncJob;
  53. import org.lukhnos.nnio.file.FileVisitResult;
  54. import org.lukhnos.nnio.file.Files;
  55. import org.lukhnos.nnio.file.Path;
  56. import org.lukhnos.nnio.file.Paths;
  57. import org.lukhnos.nnio.file.SimpleFileVisitor;
  58. import org.lukhnos.nnio.file.attribute.BasicFileAttributes;
  59. import java.io.File;
  60. import java.io.IOException;
  61. import java.util.Set;
  62. import java.util.concurrent.TimeUnit;
  63. import androidx.annotation.RequiresApi;
  64. /**
  65. * Various utilities that make auto upload tick
  66. */
  67. public final class FilesSyncHelper {
  68. public static final String TAG = "FileSyncHelper";
  69. public static final String GLOBAL = "global";
  70. public static final String SYNCEDFOLDERINITIATED = "syncedFolderIntitiated_";
  71. public static final int ContentSyncJobId = 315;
  72. private FilesSyncHelper() {
  73. // utility class -> private constructor
  74. }
  75. public static void insertAllDBEntriesForSyncedFolder(SyncedFolder syncedFolder) {
  76. final Context context = MainApp.getAppContext();
  77. final ContentResolver contentResolver = context.getContentResolver();
  78. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
  79. Long currentTime = System.currentTimeMillis();
  80. double currentTimeInSeconds = currentTime / 1000.0;
  81. String currentTimeString = Long.toString((long) currentTimeInSeconds);
  82. String syncedFolderInitiatedKey = SYNCEDFOLDERINITIATED + syncedFolder.getId();
  83. boolean dryRun = TextUtils.isEmpty(arbitraryDataProvider.getValue
  84. (GLOBAL, syncedFolderInitiatedKey));
  85. if (MediaFolderType.IMAGE == syncedFolder.getType()) {
  86. if (dryRun) {
  87. arbitraryDataProvider.storeOrUpdateKeyValue(GLOBAL, syncedFolderInitiatedKey,
  88. currentTimeString);
  89. } else {
  90. FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
  91. , syncedFolder);
  92. FilesSyncHelper.insertContentIntoDB(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
  93. syncedFolder);
  94. }
  95. } else if (MediaFolderType.VIDEO == syncedFolder.getType()) {
  96. if (dryRun) {
  97. arbitraryDataProvider.storeOrUpdateKeyValue(GLOBAL, syncedFolderInitiatedKey,
  98. currentTimeString);
  99. } else {
  100. FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI,
  101. syncedFolder);
  102. FilesSyncHelper.insertContentIntoDB(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
  103. syncedFolder);
  104. }
  105. } else {
  106. try {
  107. if (dryRun) {
  108. arbitraryDataProvider.storeOrUpdateKeyValue(GLOBAL, syncedFolderInitiatedKey,
  109. currentTimeString);
  110. } else {
  111. FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
  112. Path path = Paths.get(syncedFolder.getLocalPath());
  113. String dateInitiated = arbitraryDataProvider.getValue(GLOBAL,
  114. syncedFolderInitiatedKey);
  115. Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  116. @Override
  117. public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
  118. File file = path.toFile();
  119. if (attrs.lastModifiedTime().toMillis() >= Long.parseLong(dateInitiated) * 1000) {
  120. filesystemDataProvider.storeOrUpdateFileValue(path.toAbsolutePath().toString(),
  121. attrs.lastModifiedTime().toMillis(), file.isDirectory(), syncedFolder);
  122. }
  123. return FileVisitResult.CONTINUE;
  124. }
  125. @Override
  126. public FileVisitResult visitFileFailed(Path file, IOException exc) {
  127. return FileVisitResult.CONTINUE;
  128. }
  129. });
  130. }
  131. } catch (IOException e) {
  132. Log.e(TAG, "Something went wrong while indexing files for auto upload " + e.getLocalizedMessage());
  133. }
  134. }
  135. }
  136. public static void insertAllDBEntries(AppPreferences preferences, boolean skipCustom) {
  137. final Context context = MainApp.getAppContext();
  138. final ContentResolver contentResolver = context.getContentResolver();
  139. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver,
  140. preferences);
  141. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  142. if (syncedFolder.isEnabled() && (MediaFolderType.CUSTOM != syncedFolder.getType() || !skipCustom)) {
  143. insertAllDBEntriesForSyncedFolder(syncedFolder);
  144. }
  145. }
  146. }
  147. private static void insertContentIntoDB(Uri uri, SyncedFolder syncedFolder) {
  148. final Context context = MainApp.getAppContext();
  149. final ContentResolver contentResolver = context.getContentResolver();
  150. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
  151. Cursor cursor;
  152. int column_index_data;
  153. int column_index_date_modified;
  154. final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
  155. String contentPath;
  156. boolean isFolder;
  157. String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_MODIFIED};
  158. String path = syncedFolder.getLocalPath();
  159. if (!path.endsWith("/")) {
  160. path = path + "/%";
  161. } else {
  162. path = path + "%";
  163. }
  164. String syncedFolderInitiatedKey = SYNCEDFOLDERINITIATED + syncedFolder.getId();
  165. String dateInitiated = arbitraryDataProvider.getValue(GLOBAL, syncedFolderInitiatedKey);
  166. cursor = context.getContentResolver().query(uri, projection, MediaStore.MediaColumns.DATA + " LIKE ?",
  167. new String[]{path}, null);
  168. if (cursor != null) {
  169. column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
  170. column_index_date_modified = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED);
  171. while (cursor.moveToNext()) {
  172. contentPath = cursor.getString(column_index_data);
  173. isFolder = new File(contentPath).isDirectory();
  174. if (cursor.getLong(column_index_date_modified) >= Long.parseLong(dateInitiated)) {
  175. filesystemDataProvider.storeOrUpdateFileValue(contentPath,
  176. cursor.getLong(column_index_date_modified), isFolder, syncedFolder);
  177. }
  178. }
  179. cursor.close();
  180. }
  181. }
  182. public static void restartJobsIfNeeded(UserAccountManager accountManager) {
  183. final Context context = MainApp.getAppContext();
  184. FileUploader.UploadRequester uploadRequester = new FileUploader.UploadRequester();
  185. boolean accountExists;
  186. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
  187. OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
  188. for (OCUpload failedUpload : failedUploads) {
  189. accountExists = false;
  190. // check if accounts still exists
  191. for (Account account : accountManager.getAccounts()) {
  192. if (account.name.equals(failedUpload.getAccountName())) {
  193. accountExists = true;
  194. break;
  195. }
  196. }
  197. if (!accountExists) {
  198. uploadsStorageManager.removeUpload(failedUpload);
  199. }
  200. }
  201. new Thread(() -> {
  202. if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY) &&
  203. !ConnectivityUtils.isInternetWalled(context)) {
  204. uploadRequester.retryFailedUploads(context, null, null);
  205. }
  206. }).start();
  207. }
  208. public static void scheduleFilesSyncIfNeeded(Context context) {
  209. // always run this because it also allows us to perform retries of manual uploads
  210. new JobRequest.Builder(FilesSyncJob.TAG)
  211. .setPeriodic(900000L, 300000L)
  212. .setUpdateCurrent(true)
  213. .build()
  214. .schedule();
  215. if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  216. scheduleJobOnN();
  217. }
  218. }
  219. public static void scheduleOfflineSyncIfNeeded() {
  220. Set<JobRequest> jobRequests = JobManager.instance().getAllJobRequestsForTag(OfflineSyncJob.TAG);
  221. if (jobRequests.isEmpty()) {
  222. new JobRequest.Builder(OfflineSyncJob.TAG)
  223. .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
  224. .setUpdateCurrent(false)
  225. .build()
  226. .schedule();
  227. }
  228. }
  229. @RequiresApi(api = Build.VERSION_CODES.N)
  230. public static void scheduleJobOnN() {
  231. JobScheduler jobScheduler = MainApp.getAppContext().getSystemService(JobScheduler.class);
  232. if (jobScheduler != null) {
  233. JobInfo.Builder builder = new JobInfo.Builder(ContentSyncJobId, new ComponentName(MainApp.getAppContext(),
  234. NContentObserverJob.class.getName()));
  235. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(android.provider.MediaStore.
  236. Images.Media.INTERNAL_CONTENT_URI,
  237. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  238. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MediaStore.
  239. Images.Media.EXTERNAL_CONTENT_URI,
  240. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  241. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(android.provider.MediaStore.
  242. Video.Media.INTERNAL_CONTENT_URI,
  243. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  244. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MediaStore.
  245. Video.Media.EXTERNAL_CONTENT_URI,
  246. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  247. builder.setTriggerContentMaxDelay(1500);
  248. jobScheduler.schedule(builder.build());
  249. }
  250. }
  251. }