FileSyncAdapter.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * Copyright (C) 2011 Bartek Przybylski
  7. * Copyright (C) 2015 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  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 General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. package com.owncloud.android.syncadapter;
  23. import java.io.IOException;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. import org.apache.jackrabbit.webdav.DavException;
  29. import com.owncloud.android.MainApp;
  30. import com.owncloud.android.R;
  31. import com.owncloud.android.authentication.AuthenticatorActivity;
  32. import com.owncloud.android.datamodel.FileDataStorageManager;
  33. import com.owncloud.android.datamodel.OCFile;
  34. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  35. import com.owncloud.android.operations.RefreshFolderOperation;
  36. import com.owncloud.android.operations.UpdateOCVersionOperation;
  37. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  38. import com.owncloud.android.lib.common.utils.Log_OC;
  39. import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
  40. import android.accounts.Account;
  41. import android.accounts.AccountsException;
  42. import android.app.NotificationManager;
  43. import android.app.PendingIntent;
  44. import android.content.AbstractThreadedSyncAdapter;
  45. import android.content.ContentProviderClient;
  46. import android.content.ContentResolver;
  47. import android.content.Context;
  48. import android.content.Intent;
  49. import android.content.SyncResult;
  50. import android.os.Bundle;
  51. import android.support.v4.app.NotificationCompat;
  52. /**
  53. * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
  54. * ownCloud files.
  55. *
  56. * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle,
  57. * String, ContentProviderClient, SyncResult)}.
  58. */
  59. public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
  60. private final static String TAG = FileSyncAdapter.class.getSimpleName();
  61. /** Maximum number of failed folder synchronizations that are supported before finishing
  62. * the synchronization operation */
  63. private static final int MAX_FAILED_RESULTS = 3;
  64. public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() +
  65. ".EVENT_FULL_SYNC_START";
  66. public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() +
  67. ".EVENT_FULL_SYNC_END";
  68. public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED =
  69. FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
  70. //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED =
  71. // FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
  72. public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() +
  73. ".EXTRA_ACCOUNT_NAME";
  74. public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() +
  75. ".EXTRA_FOLDER_PATH";
  76. public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT";
  77. /** Time stamp for the current synchronization process, used to distinguish fresh data */
  78. private long mCurrentSyncTime;
  79. /** Flag made 'true' when a request to cancel the synchronization is received */
  80. private boolean mCancellation;
  81. /** When 'true' the process was requested by the user through the user interface;
  82. * when 'false', it was requested automatically by the system */
  83. private boolean mIsManualSync;
  84. /** Counter for failed operations in the synchronization process */
  85. private int mFailedResultsCounter;
  86. /** Result of the last failed operation */
  87. private RemoteOperationResult mLastFailedResult;
  88. /** Counter of conflicts found between local and remote files */
  89. private int mConflictsFound;
  90. /** Counter of failed operations in synchronization of kept-in-sync files */
  91. private int mFailsInFavouritesFound;
  92. /** Map of remote and local paths to files that where locally stored in a location out
  93. * of the ownCloud folder and couldn't be copied automatically into it */
  94. private Map<String, String> mForgottenLocalFiles;
  95. /** {@link SyncResult} instance to return to the system when the synchronization finish */
  96. private SyncResult mSyncResult;
  97. /** 'True' means that the server supports the share API */
  98. private boolean mIsShareSupported;
  99. /**
  100. * Creates a {@link FileSyncAdapter}
  101. *
  102. * {@inheritDoc}
  103. */
  104. public FileSyncAdapter(Context context, boolean autoInitialize) {
  105. super(context, autoInitialize);
  106. }
  107. /**
  108. * Creates a {@link FileSyncAdapter}
  109. *
  110. * {@inheritDoc}
  111. */
  112. public FileSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
  113. super(context, autoInitialize, allowParallelSyncs);
  114. }
  115. /**
  116. * {@inheritDoc}
  117. */
  118. @Override
  119. public synchronized void onPerformSync(Account account, Bundle extras,
  120. String authority, ContentProviderClient providerClient,
  121. SyncResult syncResult) {
  122. mCancellation = false;
  123. mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
  124. mFailedResultsCounter = 0;
  125. mLastFailedResult = null;
  126. mConflictsFound = 0;
  127. mFailsInFavouritesFound = 0;
  128. mForgottenLocalFiles = new HashMap<String, String>();
  129. mSyncResult = syncResult;
  130. mSyncResult.fullSyncRequested = false;
  131. mSyncResult.delayUntil = 60*60*24; // avoid too many automatic synchronizations
  132. this.setAccount(account);
  133. this.setContentProviderClient(providerClient);
  134. this.setStorageManager(new FileDataStorageManager(account, providerClient));
  135. try {
  136. this.initClientForCurrentAccount();
  137. } catch (IOException e) {
  138. /// the account is unknown for the Synchronization Manager, unreachable this context,
  139. // or can not be authenticated; don't try this again
  140. mSyncResult.tooManyRetries = true;
  141. notifyFailedSynchronization();
  142. return;
  143. } catch (AccountsException e) {
  144. /// the account is unknown for the Synchronization Manager, unreachable this context,
  145. // or can not be authenticated; don't try this again
  146. mSyncResult.tooManyRetries = true;
  147. notifyFailedSynchronization();
  148. return;
  149. }
  150. Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
  151. sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
  152. // of the synchronization to the UI
  153. try {
  154. updateOCVersion();
  155. mCurrentSyncTime = System.currentTimeMillis();
  156. if (!mCancellation) {
  157. synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
  158. } else {
  159. Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder " +
  160. "because cancelation request");
  161. }
  162. } finally {
  163. // it's important making this although very unexpected errors occur;
  164. // that's the reason for the finally
  165. if (mFailedResultsCounter > 0 && mIsManualSync) {
  166. /// don't let the system synchronization manager retries MANUAL synchronizations
  167. // (be careful: "MANUAL" currently includes the synchronization requested when
  168. // a new account is created and when the user changes the current account)
  169. mSyncResult.tooManyRetries = true;
  170. /// notify the user about the failure of MANUAL synchronization
  171. notifyFailedSynchronization();
  172. }
  173. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  174. notifyFailsInFavourites();
  175. }
  176. if (mForgottenLocalFiles.size() > 0) {
  177. notifyForgottenLocalFiles();
  178. }
  179. sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
  180. // the end to the UI
  181. }
  182. }
  183. /**
  184. * Called by system SyncManager when a synchronization is required to be cancelled.
  185. *
  186. * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
  187. * before a new folder is fetched. Data of the last folder synchronized will be still
  188. * locally saved.
  189. *
  190. * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
  191. * and {@link #synchronizeFolder(OCFile)}.
  192. */
  193. @Override
  194. public void onSyncCanceled() {
  195. Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
  196. mCancellation = true;
  197. super.onSyncCanceled();
  198. }
  199. /**
  200. * Updates the locally stored version value of the ownCloud server
  201. */
  202. private void updateOCVersion() {
  203. UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
  204. RemoteOperationResult result = update.execute(getClient());
  205. if (!result.isSuccess()) {
  206. mLastFailedResult = result;
  207. } else {
  208. mIsShareSupported = update.getOCVersion().isSharedSupported();
  209. }
  210. }
  211. /**
  212. * Synchronizes the list of files contained in a folder identified with its remote path.
  213. *
  214. * Fetches the list and properties of the files contained in the given folder, including their
  215. * properties, and updates the local database with them.
  216. *
  217. * Enters in the child folders to synchronize their contents also, following a recursive
  218. * depth first strategy.
  219. *
  220. * @param folder Folder to synchronize.
  221. */
  222. private void synchronizeFolder(OCFile folder) {
  223. if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
  224. return;
  225. /*
  226. OCFile folder,
  227. long currentSyncTime,
  228. boolean updateFolderProperties,
  229. boolean syncFullAccount,
  230. DataStorageManager dataStorageManager,
  231. Account account,
  232. Context context ) {
  233. }
  234. */
  235. // folder synchronization
  236. RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder,
  237. mCurrentSyncTime,
  238. true,
  239. mIsShareSupported,
  240. false,
  241. getStorageManager(),
  242. getAccount(),
  243. getContext()
  244. );
  245. RemoteOperationResult result = synchFolderOp.execute(getClient());
  246. // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
  247. sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED, folder.getRemotePath(), result);
  248. // check the result of synchronizing the folder
  249. if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
  250. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  251. mConflictsFound += synchFolderOp.getConflictsFound();
  252. mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
  253. }
  254. if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
  255. mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
  256. }
  257. if (result.isSuccess()) {
  258. // synchronize children folders
  259. List<OCFile> children = synchFolderOp.getChildren();
  260. // beware of the 'hidden' recursion here!
  261. fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged());
  262. }
  263. } else {
  264. // in failures, the statistics for the global result are updated
  265. if ( result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
  266. result.isIdPRedirection()
  267. ) {
  268. mSyncResult.stats.numAuthExceptions++;
  269. } else if (result.getException() instanceof DavException) {
  270. mSyncResult.stats.numParseExceptions++;
  271. } else if (result.getException() instanceof IOException) {
  272. mSyncResult.stats.numIoExceptions++;
  273. }
  274. mFailedResultsCounter++;
  275. mLastFailedResult = result;
  276. }
  277. }
  278. /**
  279. * Checks if a failed result should terminate the synchronization process immediately,
  280. * according to OUR OWN POLICY
  281. *
  282. * @param failedResult Remote operation result to check.
  283. * @return 'True' if the result should immediately finish the
  284. * synchronization
  285. */
  286. private boolean isFinisher(RemoteOperationResult failedResult) {
  287. if (failedResult != null) {
  288. RemoteOperationResult.ResultCode code = failedResult.getCode();
  289. return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
  290. code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
  291. code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
  292. code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
  293. }
  294. return false;
  295. }
  296. /**
  297. * Triggers the synchronization of any folder contained in the list of received files.
  298. *
  299. * @param files Files to recursively synchronize.
  300. */
  301. private void fetchChildren(OCFile parent, List<OCFile> files, boolean parentEtagChanged) {
  302. int i;
  303. OCFile newFile = null;
  304. //String etag = null;
  305. //boolean syncDown = false;
  306. for (i=0; i < files.size() && !mCancellation; i++) {
  307. newFile = files.get(i);
  308. if (newFile.isFolder()) {
  309. /*
  310. etag = newFile.getEtag();
  311. syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
  312. if(syncDown) { */
  313. synchronizeFolder(newFile);
  314. //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(),
  315. // null);
  316. //}
  317. }
  318. }
  319. if (mCancellation && i <files.size()) Log_OC.d(TAG,
  320. "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() +
  321. " due to cancelation request");
  322. }
  323. /**
  324. * Sends a message to any application component interested in the progress of the
  325. * synchronization.
  326. *
  327. * @param event Event in the process of synchronization to be notified.
  328. * @param dirRemotePath Remote path of the folder target of the event occurred.
  329. * @param result Result of an individual {@ SynchronizeFolderOperation},
  330. * if completed; may be null.
  331. */
  332. private void sendLocalBroadcast(String event, String dirRemotePath,
  333. RemoteOperationResult result) {
  334. Log_OC.d(TAG, "Send broadcast " + event);
  335. Intent intent = new Intent(event);
  336. intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
  337. if (dirRemotePath != null) {
  338. intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
  339. }
  340. if (result != null) {
  341. intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
  342. }
  343. getContext().sendStickyBroadcast(intent);
  344. //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
  345. }
  346. /**
  347. * Notifies the user about a failed synchronization through the status notification bar
  348. */
  349. private void notifyFailedSynchronization() {
  350. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  351. boolean needsToUpdateCredentials = (
  352. mLastFailedResult != null && (
  353. mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
  354. mLastFailedResult.isIdPRedirection()
  355. )
  356. );
  357. if (needsToUpdateCredentials) {
  358. // let the user update credentials with one click
  359. Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
  360. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
  361. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
  362. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  363. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  364. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  365. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  366. notificationBuilder
  367. .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
  368. .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
  369. .setContentIntent(PendingIntent.getActivity(
  370. getContext(), (int)System.currentTimeMillis(), updateAccountCredentials,
  371. PendingIntent.FLAG_ONE_SHOT
  372. ))
  373. .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
  374. } else {
  375. notificationBuilder
  376. .setTicker(i18n(R.string.sync_fail_ticker))
  377. .setContentTitle(i18n(R.string.sync_fail_ticker))
  378. .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
  379. }
  380. showNotification(R.string.sync_fail_ticker, notificationBuilder);
  381. }
  382. /**
  383. * Notifies the user about conflicts and strange fails when trying to synchronize the contents
  384. * of kept-in-sync files.
  385. *
  386. * By now, we won't consider a failed synchronization.
  387. */
  388. private void notifyFailsInFavourites() {
  389. if (mFailedResultsCounter > 0) {
  390. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  391. notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
  392. // TODO put something smart in the contentIntent below
  393. notificationBuilder
  394. .setContentIntent(PendingIntent.getActivity(
  395. getContext(), (int) System.currentTimeMillis(), new Intent(), 0
  396. ))
  397. .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
  398. .setContentText(i18n(R.string.sync_fail_in_favourites_content,
  399. mFailedResultsCounter + mConflictsFound, mConflictsFound));
  400. showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
  401. } else {
  402. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  403. notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
  404. // TODO put something smart in the contentIntent below
  405. notificationBuilder
  406. .setContentIntent(PendingIntent.getActivity(
  407. getContext(), (int) System.currentTimeMillis(), new Intent(), 0
  408. ))
  409. .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
  410. .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
  411. showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
  412. }
  413. }
  414. /**
  415. * Notifies the user about local copies of files out of the ownCloud local directory that
  416. * were 'forgotten' because copying them inside the ownCloud local directory was not possible.
  417. *
  418. * We don't want links to files out of the ownCloud local directory (foreign files) anymore.
  419. * It's easy to have synchronization problems if a local file is linked to more than one
  420. * remote file.
  421. *
  422. * We won't consider a synchronization as failed when foreign files can not be copied to
  423. * the ownCloud local directory.
  424. */
  425. private void notifyForgottenLocalFiles() {
  426. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  427. notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
  428. /// includes a pending intent in the notification showing a more detailed explanation
  429. Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
  430. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
  431. ArrayList<String> remotePaths = new ArrayList<String>();
  432. ArrayList<String> localPaths = new ArrayList<String>();
  433. remotePaths.addAll(mForgottenLocalFiles.keySet());
  434. localPaths.addAll(mForgottenLocalFiles.values());
  435. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
  436. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
  437. explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  438. notificationBuilder
  439. .setContentIntent(PendingIntent.getActivity(
  440. getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
  441. ))
  442. .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
  443. .setContentText(i18n(R.string.sync_foreign_files_forgotten_content,
  444. mForgottenLocalFiles.size(), i18n(R.string.app_name)));
  445. showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
  446. }
  447. /**
  448. * Creates a notification builder with some commonly used settings
  449. *
  450. * @return
  451. */
  452. private NotificationCompat.Builder createNotificationBuilder() {
  453. NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
  454. notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
  455. notificationBuilder.setColor(getContext().getResources().getColor(R.color.primary));
  456. return notificationBuilder;
  457. }
  458. /**
  459. * Builds and shows the notification
  460. *
  461. * @param id
  462. * @param builder
  463. */
  464. private void showNotification(int id, NotificationCompat.Builder builder) {
  465. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE))
  466. .notify(id, builder.build());
  467. }
  468. /**
  469. * Shorthand translation
  470. *
  471. * @param key
  472. * @param args
  473. * @return
  474. */
  475. private String i18n(int key, Object... args) {
  476. return getContext().getString(key, args);
  477. }
  478. }