FileSyncAdapter.java 23 KB

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