FileSyncAdapter.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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.MainApp;
  26. import com.owncloud.android.R;
  27. import com.owncloud.android.authentication.AuthenticatorActivity;
  28. import com.owncloud.android.datamodel.FileDataStorageManager;
  29. import com.owncloud.android.datamodel.OCFile;
  30. import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
  31. import com.owncloud.android.operations.SynchronizeFolderOperation;
  32. import com.owncloud.android.operations.UpdateOCVersionOperation;
  33. import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
  34. import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
  35. import com.owncloud.android.utils.DisplayUtils;
  36. import com.owncloud.android.utils.Log_OC;
  37. import android.accounts.Account;
  38. import android.accounts.AccountsException;
  39. import android.app.Notification;
  40. import android.app.NotificationManager;
  41. import android.app.PendingIntent;
  42. import android.content.AbstractThreadedSyncAdapter;
  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. * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
  51. * ownCloud files.
  52. *
  53. * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
  54. *
  55. * @author Bartek Przybylski
  56. * @author David A. Velasco
  57. */
  58. public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
  59. private final static String TAG = FileSyncAdapter.class.getSimpleName();
  60. /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
  61. private static final int MAX_FAILED_RESULTS = 3;
  62. /** Time stamp for the current synchronization process, used to distinguish fresh data */
  63. private long mCurrentSyncTime;
  64. /** Flag made 'true' when a request to cancel the synchronization is received */
  65. private boolean mCancellation;
  66. /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
  67. private boolean mIsManualSync;
  68. /** Counter for failed operations in the synchronization process */
  69. private int mFailedResultsCounter;
  70. /** Result of the last failed operation */
  71. private RemoteOperationResult mLastFailedResult;
  72. /** Counter of conflicts found between local and remote files */
  73. private int mConflictsFound;
  74. /** Counter of failed operations in synchronization of kept-in-sync files */
  75. private int mFailsInFavouritesFound;
  76. /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
  77. private Map<String, String> mForgottenLocalFiles;
  78. /** {@link SyncResult} instance to return to the system when the synchronization finish */
  79. private SyncResult mSyncResult;
  80. /**
  81. * Creates a {@link FileSyncAdapter}
  82. *
  83. * {@inheritDoc}
  84. */
  85. public FileSyncAdapter(Context context, boolean autoInitialize) {
  86. super(context, autoInitialize);
  87. }
  88. /**
  89. * Creates a {@link FileSyncAdapter}
  90. *
  91. * {@inheritDoc}
  92. */
  93. public FileSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
  94. super(context, autoInitialize, allowParallelSyncs);
  95. }
  96. /**
  97. * {@inheritDoc}
  98. */
  99. @Override
  100. public synchronized void onPerformSync(Account account, Bundle extras,
  101. String authority, ContentProviderClient providerClient,
  102. SyncResult syncResult) {
  103. mCancellation = false;
  104. mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
  105. mFailedResultsCounter = 0;
  106. mLastFailedResult = null;
  107. mConflictsFound = 0;
  108. mFailsInFavouritesFound = 0;
  109. mForgottenLocalFiles = new HashMap<String, String>();
  110. mSyncResult = syncResult;
  111. mSyncResult.fullSyncRequested = false;
  112. mSyncResult.delayUntil = 60*60*24; // avoid too many automatic synchronizations
  113. this.setAccount(account);
  114. this.setContentProviderClient(providerClient);
  115. this.setStorageManager(new FileDataStorageManager(account, providerClient));
  116. try {
  117. this.initClientForCurrentAccount();
  118. } catch (IOException e) {
  119. /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
  120. mSyncResult.tooManyRetries = true;
  121. notifyFailedSynchronization();
  122. return;
  123. } catch (AccountsException e) {
  124. /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
  125. mSyncResult.tooManyRetries = true;
  126. notifyFailedSynchronization();
  127. return;
  128. }
  129. Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
  130. sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI
  131. try {
  132. updateOCVersion();
  133. mCurrentSyncTime = System.currentTimeMillis();
  134. if (!mCancellation) {
  135. synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
  136. } else {
  137. Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder because cancelation request");
  138. }
  139. } finally {
  140. // it's important making this although very unexpected errors occur; that's the reason for the finally
  141. if (mFailedResultsCounter > 0 && mIsManualSync) {
  142. /// don't let the system synchronization manager retries MANUAL synchronizations
  143. // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
  144. mSyncResult.tooManyRetries = true;
  145. /// notify the user about the failure of MANUAL synchronization
  146. notifyFailedSynchronization();
  147. }
  148. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  149. notifyFailsInFavourites();
  150. }
  151. if (mForgottenLocalFiles.size() > 0) {
  152. notifyForgottenLocalFiles();
  153. }
  154. sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI
  155. }
  156. }
  157. /**
  158. * Called by system SyncManager when a synchronization is required to be cancelled.
  159. *
  160. * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
  161. * before a new folder is fetched. Data of the last folder synchronized will be still
  162. * locally saved.
  163. *
  164. * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
  165. * and {@link #synchronizeFolder(String, long)}.
  166. */
  167. @Override
  168. public void onSyncCanceled() {
  169. Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
  170. mCancellation = true;
  171. super.onSyncCanceled();
  172. }
  173. /**
  174. * Updates the locally stored version value of the ownCloud server
  175. */
  176. private void updateOCVersion() {
  177. UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
  178. RemoteOperationResult result = update.execute(getClient());
  179. if (!result.isSuccess()) {
  180. mLastFailedResult = result;
  181. }
  182. }
  183. /**
  184. * Synchronizes the list of files contained in a folder identified with its remote path.
  185. *
  186. * Fetches the list and properties of the files contained in the given folder, including their
  187. * properties, and updates the local database with them.
  188. *
  189. * Enters in the child folders to synchronize their contents also, following a recursive
  190. * depth first strategy.
  191. *
  192. * @param folder Folder to synchronize.
  193. */
  194. private void synchronizeFolder(OCFile folder) {
  195. if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
  196. return;
  197. /*
  198. OCFile folder,
  199. long currentSyncTime,
  200. boolean updateFolderProperties,
  201. boolean syncFullAccount,
  202. DataStorageManager dataStorageManager,
  203. Account account,
  204. Context context ) {
  205. }
  206. */
  207. // folder synchronization
  208. SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( folder,
  209. mCurrentSyncTime,
  210. true,
  211. getStorageManager(),
  212. getAccount(),
  213. getContext()
  214. );
  215. RemoteOperationResult result = synchFolderOp.execute(getClient());
  216. // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
  217. sendStickyBroadcast(true, folder.getRemotePath(), null);
  218. // check the result of synchronizing the folder
  219. if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
  220. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  221. mConflictsFound += synchFolderOp.getConflictsFound();
  222. mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
  223. }
  224. if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
  225. mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
  226. }
  227. if (result.isSuccess()) {
  228. // synchronize children folders
  229. List<OCFile> children = synchFolderOp.getChildren();
  230. fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
  231. }
  232. } else {
  233. // in failures, the statistics for the global result are updated
  234. if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
  235. ( result.isIdPRedirection() &&
  236. getClient().getCredentials() == null )) {
  237. //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))) {
  238. mSyncResult.stats.numAuthExceptions++;
  239. } else if (result.getException() instanceof DavException) {
  240. mSyncResult.stats.numParseExceptions++;
  241. } else if (result.getException() instanceof IOException) {
  242. mSyncResult.stats.numIoExceptions++;
  243. }
  244. mFailedResultsCounter++;
  245. mLastFailedResult = result;
  246. }
  247. }
  248. /**
  249. * Checks if a failed result should terminate the synchronization process immediately, according to
  250. * OUR OWN POLICY
  251. *
  252. * @param failedResult Remote operation result to check.
  253. * @return 'True' if the result should immediately finish the synchronization
  254. */
  255. private boolean isFinisher(RemoteOperationResult failedResult) {
  256. if (failedResult != null) {
  257. RemoteOperationResult.ResultCode code = failedResult.getCode();
  258. return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
  259. code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
  260. code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
  261. code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
  262. }
  263. return false;
  264. }
  265. /**
  266. * Triggers the synchronization of any folder contained in the list of received files.
  267. *
  268. * @param files Files to recursively synchronize.
  269. */
  270. private void fetchChildren(OCFile parent, List<OCFile> files, boolean parentEtagChanged) {
  271. int i;
  272. OCFile newFile = null;
  273. String etag = null;
  274. boolean syncDown = false;
  275. for (i=0; i < files.size() && !mCancellation; i++) {
  276. newFile = files.get(i);
  277. if (newFile.isFolder()) {
  278. /*
  279. etag = newFile.getEtag();
  280. syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
  281. if(syncDown) { */
  282. synchronizeFolder(newFile);
  283. // update the size of the parent folder again after recursive synchronization
  284. //getStorageManager().updateFolderSize(parent.getFileId());
  285. sendStickyBroadcast(true, parent.getRemotePath(), null); // notify again to refresh size in UI
  286. //}
  287. }
  288. }
  289. if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " due to cancelation request");
  290. }
  291. /**
  292. * Sends a message to any application component interested in the progress of the synchronization.
  293. *
  294. * @param inProgress 'True' when the synchronization progress is not finished.
  295. * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
  296. */
  297. private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
  298. Intent i = new Intent(FileSyncService.getSyncMessage());
  299. i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
  300. i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
  301. if (dirRemotePath != null) {
  302. i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
  303. }
  304. if (result != null) {
  305. i.putExtra(FileSyncService.SYNC_RESULT, result);
  306. }
  307. getContext().sendStickyBroadcast(i);
  308. }
  309. /**
  310. * Notifies the user about a failed synchronization through the status notification bar
  311. */
  312. private void notifyFailedSynchronization() {
  313. Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
  314. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  315. boolean needsToUpdateCredentials = (mLastFailedResult != null &&
  316. ( mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
  317. ( mLastFailedResult.isIdPRedirection() &&
  318. getClient().getCredentials() == null )
  319. //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))
  320. )
  321. );
  322. // TODO put something smart in the contentIntent below for all the possible errors
  323. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  324. if (needsToUpdateCredentials) {
  325. // let the user update credentials with one click
  326. Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
  327. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
  328. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
  329. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
  330. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  331. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  332. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  333. notification.contentIntent = PendingIntent.getActivity(getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
  334. notification.setLatestEventInfo(getContext().getApplicationContext(),
  335. getContext().getString(R.string.sync_fail_ticker),
  336. String.format(getContext().getString(R.string.sync_fail_content_unauthorized), getAccount().name),
  337. notification.contentIntent);
  338. } else {
  339. notification.setLatestEventInfo(getContext().getApplicationContext(),
  340. getContext().getString(R.string.sync_fail_ticker),
  341. String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
  342. notification.contentIntent);
  343. }
  344. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
  345. }
  346. /**
  347. * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
  348. *
  349. * By now, we won't consider a failed synchronization.
  350. */
  351. private void notifyFailsInFavourites() {
  352. if (mFailedResultsCounter > 0) {
  353. Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
  354. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  355. // TODO put something smart in the contentIntent below
  356. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  357. notification.setLatestEventInfo(getContext().getApplicationContext(),
  358. getContext().getString(R.string.sync_fail_in_favourites_ticker),
  359. String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound),
  360. notification.contentIntent);
  361. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
  362. } else {
  363. Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
  364. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  365. // TODO put something smart in the contentIntent below
  366. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  367. notification.setLatestEventInfo(getContext().getApplicationContext(),
  368. getContext().getString(R.string.sync_conflicts_in_favourites_ticker),
  369. String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound),
  370. notification.contentIntent);
  371. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
  372. }
  373. }
  374. /**
  375. * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
  376. * copying them inside the ownCloud local directory was not possible.
  377. *
  378. * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
  379. * synchronization problems if a local file is linked to more than one remote file.
  380. *
  381. * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
  382. */
  383. private void notifyForgottenLocalFiles() {
  384. Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());
  385. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  386. /// includes a pending intent in the notification showing a more detailed explanation
  387. Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
  388. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
  389. ArrayList<String> remotePaths = new ArrayList<String>();
  390. ArrayList<String> localPaths = new ArrayList<String>();
  391. remotePaths.addAll(mForgottenLocalFiles.keySet());
  392. localPaths.addAll(mForgottenLocalFiles.values());
  393. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
  394. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
  395. explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  396. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);
  397. notification.setLatestEventInfo(getContext().getApplicationContext(),
  398. getContext().getString(R.string.sync_foreign_files_forgotten_ticker),
  399. String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size(), getContext().getString(R.string.app_name)),
  400. notification.contentIntent);
  401. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);
  402. }
  403. }