FileSyncAdapter.java 23 KB

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