FileSyncAdapter.java 23 KB

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