FileSyncAdapter.java 20 KB

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