FileSyncAdapter.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.syncadapter;
  19. import java.io.IOException;
  20. import java.net.UnknownHostException;
  21. import java.util.ArrayList;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;
  25. import org.apache.jackrabbit.webdav.DavException;
  26. import com.owncloud.android.R;
  27. import com.owncloud.android.datamodel.DataStorageManager;
  28. import com.owncloud.android.datamodel.FileDataStorageManager;
  29. import com.owncloud.android.datamodel.OCFile;
  30. import com.owncloud.android.operations.RemoteOperationResult;
  31. import com.owncloud.android.operations.SynchronizeFolderOperation;
  32. import com.owncloud.android.operations.UpdateOCVersionOperation;
  33. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  34. import com.owncloud.android.ui.activity.ExplanationActivity;
  35. import android.accounts.Account;
  36. import android.app.Notification;
  37. import android.app.NotificationManager;
  38. import android.app.PendingIntent;
  39. import android.content.ContentProviderClient;
  40. import android.content.ContentResolver;
  41. import android.content.Context;
  42. import android.content.Intent;
  43. import android.content.SyncResult;
  44. import android.os.Bundle;
  45. import android.util.Log;
  46. /**
  47. * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
  48. * platform ContactOperations provider.
  49. *
  50. * @author Bartek Przybylski
  51. */
  52. public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
  53. private final static String TAG = "FileSyncAdapter";
  54. /**
  55. * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
  56. */
  57. private static final int MAX_FAILED_RESULTS = 3;
  58. private long mCurrentSyncTime;
  59. private boolean mCancellation;
  60. private boolean mIsManualSync;
  61. private int mFailedResultsCounter;
  62. private RemoteOperationResult mLastFailedResult;
  63. private SyncResult mSyncResult;
  64. private int mConflictsFound;
  65. private int mFailsInFavouritesFound;
  66. private Map<String, String> mForgottenLocalFiles;
  67. public FileSyncAdapter(Context context, boolean autoInitialize) {
  68. super(context, autoInitialize);
  69. }
  70. /**
  71. * {@inheritDoc}
  72. */
  73. @Override
  74. public synchronized void onPerformSync(Account account, Bundle extras,
  75. String authority, ContentProviderClient provider,
  76. SyncResult syncResult) {
  77. mCancellation = false;
  78. mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
  79. mFailedResultsCounter = 0;
  80. mLastFailedResult = null;
  81. mConflictsFound = 0;
  82. mFailsInFavouritesFound = 0;
  83. mForgottenLocalFiles = new HashMap<String, String>();
  84. mSyncResult = syncResult;
  85. mSyncResult.fullSyncRequested = false;
  86. mSyncResult.delayUntil = 60*60*24; // sync after 24h
  87. this.setAccount(account);
  88. this.setContentProvider(provider);
  89. this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
  90. try {
  91. this.initClientForCurrentAccount();
  92. } catch (UnknownHostException e) {
  93. /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
  94. mSyncResult.tooManyRetries = true;
  95. notifyFailedSynchronization();
  96. return;
  97. }
  98. Log.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
  99. sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI
  100. try {
  101. updateOCVersion();
  102. mCurrentSyncTime = System.currentTimeMillis();
  103. if (!mCancellation) {
  104. fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);
  105. } else {
  106. Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");
  107. }
  108. } finally {
  109. // it's important making this although very unexpected errors occur; that's the reason for the finally
  110. if (mFailedResultsCounter > 0 && mIsManualSync) {
  111. /// don't let the system synchronization manager retries MANUAL synchronizations
  112. // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
  113. mSyncResult.tooManyRetries = true;
  114. /// notify the user about the failure of MANUAL synchronization
  115. notifyFailedSynchronization();
  116. }
  117. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  118. notifyFailsInFavourites();
  119. }
  120. if (mForgottenLocalFiles.size() > 0) {
  121. notifyForgottenLocalFiles();
  122. }
  123. sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI
  124. }
  125. }
  126. /**
  127. * Called by system SyncManager when a synchronization is required to be cancelled.
  128. *
  129. * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
  130. * fetched will be still saved in the database. See onPerformSync implementation.
  131. */
  132. @Override
  133. public void onSyncCanceled() {
  134. Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
  135. mCancellation = true;
  136. super.onSyncCanceled();
  137. }
  138. /**
  139. * Updates the locally stored version value of the ownCloud server
  140. */
  141. private void updateOCVersion() {
  142. UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
  143. RemoteOperationResult result = update.execute(getClient());
  144. if (!result.isSuccess()) {
  145. mLastFailedResult = result;
  146. }
  147. }
  148. /**
  149. * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
  150. *
  151. * @param remotePath Remote path to the folder to synchronize.
  152. * @param parentId Database Id of the folder to synchronize.
  153. */
  154. private void fetchData(String remotePath, long parentId) {
  155. if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
  156. return;
  157. // perform folder synchronization
  158. SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath,
  159. mCurrentSyncTime,
  160. parentId,
  161. getStorageManager(),
  162. getAccount(),
  163. getContext()
  164. );
  165. RemoteOperationResult result = synchFolderOp.execute(getClient());
  166. // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
  167. sendStickyBroadcast(true, remotePath, null);
  168. if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
  169. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  170. mConflictsFound += synchFolderOp.getConflictsFound();
  171. mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
  172. }
  173. if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
  174. mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
  175. }
  176. // synchronize children folders
  177. List<OCFile> children = synchFolderOp.getChildren();
  178. fetchChildren(children); // beware of the 'hidden' recursion here!
  179. } else {
  180. if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
  181. mSyncResult.stats.numAuthExceptions++;
  182. } else if (result.getException() instanceof DavException) {
  183. mSyncResult.stats.numParseExceptions++;
  184. } else if (result.getException() instanceof IOException) {
  185. mSyncResult.stats.numIoExceptions++;
  186. }
  187. mFailedResultsCounter++;
  188. mLastFailedResult = result;
  189. }
  190. }
  191. /**
  192. * Checks if a failed result should terminate the synchronization process immediately, according to
  193. * OUR OWN POLICY
  194. *
  195. * @param failedResult Remote operation result to check.
  196. * @return 'True' if the result should immediately finish the synchronization
  197. */
  198. private boolean isFinisher(RemoteOperationResult failedResult) {
  199. if (failedResult != null) {
  200. RemoteOperationResult.ResultCode code = failedResult.getCode();
  201. return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
  202. code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
  203. code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
  204. code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
  205. }
  206. return false;
  207. }
  208. /**
  209. * Synchronize data of folders in the list of received files
  210. *
  211. * @param files Files to recursively fetch
  212. */
  213. private void fetchChildren(List<OCFile> files) {
  214. int i;
  215. for (i=0; i < files.size() && !mCancellation; i++) {
  216. OCFile newFile = files.get(i);
  217. if (newFile.isDirectory()) {
  218. fetchData(newFile.getRemotePath(), newFile.getFileId());
  219. }
  220. }
  221. if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");
  222. }
  223. /**
  224. * Sends a message to any application component interested in the progress of the synchronization.
  225. *
  226. * @param inProgress 'True' when the synchronization progress is not finished.
  227. * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
  228. */
  229. private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
  230. Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
  231. i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
  232. i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
  233. if (dirRemotePath != null) {
  234. i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
  235. }
  236. if (result != null) {
  237. i.putExtra(FileSyncService.SYNC_RESULT, result);
  238. }
  239. getContext().sendStickyBroadcast(i);
  240. }
  241. /**
  242. * Notifies the user about a failed synchronization through the status notification bar
  243. */
  244. private void notifyFailedSynchronization() {
  245. Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
  246. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  247. // TODO put something smart in the contentIntent below
  248. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  249. notification.setLatestEventInfo(getContext().getApplicationContext(),
  250. getContext().getString(R.string.sync_fail_ticker),
  251. String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
  252. notification.contentIntent);
  253. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
  254. }
  255. /**
  256. * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
  257. *
  258. * By now, we won't consider a failed synchronization.
  259. */
  260. private void notifyFailsInFavourites() {
  261. if (mFailedResultsCounter > 0) {
  262. Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
  263. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  264. // TODO put something smart in the contentIntent below
  265. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  266. notification.setLatestEventInfo(getContext().getApplicationContext(),
  267. getContext().getString(R.string.sync_fail_in_favourites_ticker),
  268. String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound),
  269. notification.contentIntent);
  270. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
  271. } else {
  272. Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
  273. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  274. // TODO put something smart in the contentIntent below
  275. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  276. notification.setLatestEventInfo(getContext().getApplicationContext(),
  277. getContext().getString(R.string.sync_conflicts_in_favourites_ticker),
  278. String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound),
  279. notification.contentIntent);
  280. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
  281. }
  282. }
  283. /**
  284. * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
  285. * copying them inside the ownCloud local directory was not possible.
  286. *
  287. * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
  288. * synchronization problems if a local file is linked to more than one remote file.
  289. *
  290. * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
  291. */
  292. private void notifyForgottenLocalFiles() {
  293. Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());
  294. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  295. /// includes a pending intent in the notification showing a more detailed explanation
  296. Intent explanationIntent = new Intent(getContext(), ExplanationActivity.class);
  297. String message = String.format(getContext().getString(R.string.sync_foreign_files_forgotten_explanation), getContext().getString(R.string.app_name), getAccount().name);
  298. explanationIntent.putExtra(ExplanationActivity.MESSAGE, message);
  299. ArrayList<String> remotePaths = new ArrayList<String>();
  300. ArrayList<String> localPaths = new ArrayList<String>();
  301. for (String remote : mForgottenLocalFiles.keySet()) {
  302. remotePaths.add(getContext().getString(R.string.sync_foreign_files_forgotten_remote_prefix) + remote);
  303. localPaths.add(getContext().getString(R.string.sync_foreign_files_forgotten_local_prefix) + mForgottenLocalFiles.get(remote));
  304. }
  305. explanationIntent.putExtra(ExplanationActivity.EXTRA_LIST, localPaths);
  306. explanationIntent.putExtra(ExplanationActivity.EXTRA_LIST_2, remotePaths);
  307. explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  308. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);
  309. notification.setLatestEventInfo(getContext().getApplicationContext(),
  310. getContext().getString(R.string.sync_foreign_files_forgotten_ticker),
  311. String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size()),
  312. notification.contentIntent);
  313. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);
  314. }
  315. }