FileSyncAdapter.java 23 KB

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