FilesSyncHelper.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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.JobRequest;
  36. import com.evernote.android.job.util.Device;
  37. import com.owncloud.android.MainApp;
  38. import com.owncloud.android.authentication.AccountUtils;
  39. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  40. import com.owncloud.android.datamodel.FilesystemDataProvider;
  41. import com.owncloud.android.datamodel.MediaFolderType;
  42. import com.owncloud.android.datamodel.SyncedFolder;
  43. import com.owncloud.android.datamodel.SyncedFolderProvider;
  44. import com.owncloud.android.datamodel.UploadsStorageManager;
  45. import com.owncloud.android.db.OCUpload;
  46. import com.owncloud.android.files.services.FileUploader;
  47. import com.owncloud.android.jobs.FilesSyncJob;
  48. import com.owncloud.android.jobs.NContentObserverJob;
  49. import org.lukhnos.nnio.file.FileVisitResult;
  50. import org.lukhnos.nnio.file.Files;
  51. import org.lukhnos.nnio.file.Path;
  52. import org.lukhnos.nnio.file.Paths;
  53. import org.lukhnos.nnio.file.SimpleFileVisitor;
  54. import org.lukhnos.nnio.file.attribute.BasicFileAttributes;
  55. import java.io.File;
  56. import java.io.IOException;
  57. import java.util.List;
  58. /*
  59. Various utilities that make auto upload tick
  60. */
  61. public class FilesSyncHelper {
  62. public static final String TAG = "FileSyncHelper";
  63. public static final String GLOBAL = "global";
  64. public static final String SYNCEDFOLDERINITIATED = "syncedFolderIntitiated_";
  65. public static int ContentSyncJobId = 315;
  66. public static void insertAllDBEntriesForSyncedFolder(SyncedFolder syncedFolder) {
  67. final Context context = MainApp.getAppContext();
  68. final ContentResolver contentResolver = context.getContentResolver();
  69. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
  70. Long currentTime = System.currentTimeMillis();
  71. double currentTimeInSeconds = currentTime / 1000.0;
  72. String currentTimeString = Long.toString((long) currentTimeInSeconds);
  73. String syncedFolderInitiatedKey = SYNCEDFOLDERINITIATED + syncedFolder.getId();
  74. boolean dryRun = TextUtils.isEmpty(arbitraryDataProvider.getValue
  75. (GLOBAL, syncedFolderInitiatedKey));
  76. if (MediaFolderType.IMAGE == syncedFolder.getType()) {
  77. if (dryRun) {
  78. arbitraryDataProvider.storeOrUpdateKeyValue(GLOBAL, syncedFolderInitiatedKey,
  79. currentTimeString);
  80. } else {
  81. FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
  82. , syncedFolder);
  83. FilesSyncHelper.insertContentIntoDB(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
  84. syncedFolder);
  85. }
  86. } else if (MediaFolderType.VIDEO == syncedFolder.getType()) {
  87. if (dryRun) {
  88. arbitraryDataProvider.storeOrUpdateKeyValue(GLOBAL, syncedFolderInitiatedKey,
  89. currentTimeString);
  90. } else {
  91. FilesSyncHelper.insertContentIntoDB(android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI,
  92. syncedFolder);
  93. FilesSyncHelper.insertContentIntoDB(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
  94. syncedFolder);
  95. }
  96. } else {
  97. try {
  98. if (dryRun) {
  99. arbitraryDataProvider.storeOrUpdateKeyValue(GLOBAL, syncedFolderInitiatedKey,
  100. currentTimeString);
  101. } else {
  102. FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
  103. Path path = Paths.get(syncedFolder.getLocalPath());
  104. String dateInitiated = arbitraryDataProvider.getValue(GLOBAL,
  105. syncedFolderInitiatedKey);
  106. Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  107. @Override
  108. public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
  109. File file = path.toFile();
  110. if (attrs.lastModifiedTime().toMillis() >= Long.parseLong(dateInitiated) * 1000) {
  111. filesystemDataProvider.storeOrUpdateFileValue(path.toAbsolutePath().toString(),
  112. attrs.lastModifiedTime().toMillis(), file.isDirectory(), syncedFolder);
  113. }
  114. return FileVisitResult.CONTINUE;
  115. }
  116. @Override
  117. public FileVisitResult visitFileFailed(Path file, IOException exc) {
  118. return FileVisitResult.CONTINUE;
  119. }
  120. });
  121. }
  122. } catch (IOException e) {
  123. Log.e(TAG, "Something went wrong while indexing files for auto upload " + e.getLocalizedMessage());
  124. }
  125. }
  126. }
  127. public static void insertAllDBEntries(boolean skipCustom) {
  128. final Context context = MainApp.getAppContext();
  129. final ContentResolver contentResolver = context.getContentResolver();
  130. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
  131. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  132. if ((syncedFolder.isEnabled()) && ((MediaFolderType.CUSTOM != syncedFolder.getType()) || !skipCustom)) {
  133. insertAllDBEntriesForSyncedFolder(syncedFolder);
  134. }
  135. }
  136. }
  137. private static void insertContentIntoDB(Uri uri, SyncedFolder syncedFolder) {
  138. final Context context = MainApp.getAppContext();
  139. final ContentResolver contentResolver = context.getContentResolver();
  140. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
  141. Cursor cursor;
  142. int column_index_data;
  143. int column_index_date_modified;
  144. final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
  145. String contentPath;
  146. boolean isFolder;
  147. String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_MODIFIED};
  148. String path = syncedFolder.getLocalPath();
  149. if (!path.endsWith("/")) {
  150. path = path + "/%";
  151. } else {
  152. path = path + "%";
  153. }
  154. String syncedFolderInitiatedKey = SYNCEDFOLDERINITIATED + syncedFolder.getId();
  155. String dateInitiated = arbitraryDataProvider.getValue(GLOBAL, syncedFolderInitiatedKey);
  156. cursor = context.getContentResolver().query(uri, projection, MediaStore.MediaColumns.DATA + " LIKE ?",
  157. new String[]{path}, null);
  158. if (cursor != null) {
  159. column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
  160. column_index_date_modified = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED);
  161. while (cursor.moveToNext()) {
  162. contentPath = cursor.getString(column_index_data);
  163. isFolder = new File(contentPath).isDirectory();
  164. if (cursor.getLong(column_index_date_modified) >= Long.parseLong(dateInitiated)) {
  165. filesystemDataProvider.storeOrUpdateFileValue(contentPath,
  166. cursor.getLong(column_index_date_modified), isFolder, syncedFolder);
  167. }
  168. }
  169. cursor.close();
  170. }
  171. }
  172. public static void restartJobsIfNeeded() {
  173. final Context context = MainApp.getAppContext();
  174. FileUploader.UploadRequester uploadRequester = new FileUploader.UploadRequester();
  175. boolean accountExists;
  176. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
  177. OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
  178. for (OCUpload failedUpload : failedUploads) {
  179. accountExists = false;
  180. // check if accounts still exists
  181. for (Account account : AccountUtils.getAccounts(context)) {
  182. if (account.name.equals(failedUpload.getAccountName())) {
  183. accountExists = true;
  184. break;
  185. }
  186. }
  187. if (!accountExists) {
  188. uploadsStorageManager.removeUpload(failedUpload);
  189. }
  190. }
  191. new Thread(() -> {
  192. if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY) &&
  193. !ConnectivityUtils.isInternetWalled(context)) {
  194. uploadRequester.retryFailedUploads(context, null, null);
  195. }
  196. }).start();
  197. }
  198. @RequiresApi(api = Build.VERSION_CODES.N)
  199. public static boolean isContentObserverJobScheduled() {
  200. JobScheduler js = MainApp.getAppContext().getSystemService(JobScheduler.class);
  201. List<JobInfo> jobs = js.getAllPendingJobs();
  202. if (jobs == null || jobs.size() == 0) {
  203. return false;
  204. }
  205. for (int i = 0; i < jobs.size(); i++) {
  206. if (jobs.get(i).getId() == ContentSyncJobId) {
  207. return true;
  208. }
  209. }
  210. return false;
  211. }
  212. public static void scheduleNJobs(boolean force, Context context) {
  213. SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(context.getContentResolver());
  214. boolean hasVideoFolders = false;
  215. boolean hasImageFolders = false;
  216. if (syncedFolderProvider.getSyncedFolders() != null) {
  217. for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
  218. if (MediaFolderType.VIDEO == syncedFolder.getType()) {
  219. hasVideoFolders = true;
  220. } else if (MediaFolderType.IMAGE == syncedFolder.getType()) {
  221. hasImageFolders = true;
  222. }
  223. }
  224. }
  225. if (hasImageFolders || hasVideoFolders) {
  226. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  227. scheduleJobOnN(hasImageFolders, hasVideoFolders, force);
  228. }
  229. } else {
  230. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  231. cancelJobOnN();
  232. }
  233. }
  234. }
  235. public static void scheduleFilesSyncIfNeeded(Context context) {
  236. // always run this because it also allows us to perform retries of manual uploads
  237. new JobRequest.Builder(FilesSyncJob.TAG)
  238. .setPeriodic(900000L, 300000L)
  239. .setUpdateCurrent(true)
  240. .build()
  241. .schedule();
  242. if (context != null) {
  243. scheduleNJobs(false, context);
  244. }
  245. }
  246. @RequiresApi(api = Build.VERSION_CODES.N)
  247. private static void cancelJobOnN() {
  248. JobScheduler jobScheduler = MainApp.getAppContext().getSystemService(JobScheduler.class);
  249. if (isContentObserverJobScheduled()) {
  250. jobScheduler.cancel(ContentSyncJobId);
  251. }
  252. }
  253. @RequiresApi(api = Build.VERSION_CODES.N)
  254. private static void scheduleJobOnN(boolean hasImageFolders, boolean hasVideoFolders,
  255. boolean force) {
  256. JobScheduler jobScheduler = MainApp.getAppContext().getSystemService(JobScheduler.class);
  257. if ((hasImageFolders || hasVideoFolders) && (!isContentObserverJobScheduled() || force)) {
  258. JobInfo.Builder builder = new JobInfo.Builder(ContentSyncJobId, new ComponentName(MainApp.getAppContext(),
  259. NContentObserverJob.class.getName()));
  260. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(android.provider.MediaStore.
  261. Images.Media.INTERNAL_CONTENT_URI,
  262. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  263. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MediaStore.
  264. Images.Media.EXTERNAL_CONTENT_URI,
  265. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  266. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(android.provider.MediaStore.
  267. Video.Media.INTERNAL_CONTENT_URI,
  268. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  269. builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MediaStore.
  270. Video.Media.EXTERNAL_CONTENT_URI,
  271. JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  272. builder.setTriggerContentMaxDelay(1500);
  273. jobScheduler.schedule(builder.build());
  274. }
  275. }
  276. }