FilesSyncHelper.java 14 KB

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