FileSyncAdapter.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  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.List;
  21. import java.util.Vector;
  22. import org.apache.http.HttpStatus;
  23. import org.apache.jackrabbit.webdav.DavException;
  24. import org.apache.jackrabbit.webdav.MultiStatus;
  25. import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
  26. import com.owncloud.android.R;
  27. import com.owncloud.android.datamodel.FileDataStorageManager;
  28. import com.owncloud.android.datamodel.OCFile;
  29. import com.owncloud.android.files.services.FileDownloader;
  30. import android.accounts.Account;
  31. import android.app.Notification;
  32. import android.app.NotificationManager;
  33. import android.app.PendingIntent;
  34. import android.content.ContentProviderClient;
  35. import android.content.ContentResolver;
  36. import android.content.Context;
  37. import android.content.Intent;
  38. import android.content.SyncResult;
  39. import android.os.Bundle;
  40. import android.util.Log;
  41. import eu.alefzero.webdav.WebdavEntry;
  42. import eu.alefzero.webdav.WebdavUtils;
  43. /**
  44. * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
  45. * platform ContactOperations provider.
  46. *
  47. * @author Bartek Przybylski
  48. */
  49. public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
  50. private final static String TAG = "FileSyncAdapter";
  51. /* Commented code for ugly performance tests
  52. private final static int MAX_DELAYS = 100;
  53. private static long[] mResponseDelays = new long[MAX_DELAYS];
  54. private static long[] mSaveDelays = new long[MAX_DELAYS];
  55. private int mDelaysIndex = 0;
  56. private int mDelaysCount = 0;
  57. */
  58. private long mCurrentSyncTime;
  59. private boolean mCancellation;
  60. private boolean mIsManualSync;
  61. private boolean mRightSync;
  62. public FileSyncAdapter(Context context, boolean autoInitialize) {
  63. super(context, autoInitialize);
  64. }
  65. @Override
  66. public synchronized void onPerformSync(Account account, Bundle extras,
  67. String authority, ContentProviderClient provider,
  68. SyncResult syncResult) {
  69. mCancellation = false;
  70. mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
  71. mRightSync = true;
  72. this.setAccount(account);
  73. this.setContentProvider(provider);
  74. this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
  75. /* Commented code for ugly performance tests
  76. mDelaysIndex = 0;
  77. mDelaysCount = 0;
  78. */
  79. Log.d(TAG, "syncing owncloud account " + account.name);
  80. sendStickyBroadcast(true, null); // message to signal the start to the UI
  81. String uri = getUri().toString();
  82. PropFindMethod query = null;
  83. try {
  84. mCurrentSyncTime = System.currentTimeMillis();
  85. query = new PropFindMethod(uri + "/");
  86. int status = getClient().executeMethod(query);
  87. if (status != HttpStatus.SC_UNAUTHORIZED) {
  88. MultiStatus resp = query.getResponseBodyAsMultiStatus();
  89. if (resp.getResponses().length > 0) {
  90. WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath());
  91. OCFile file = fillOCFile(we);
  92. file.setParentId(0);
  93. getStorageManager().saveFile(file);
  94. if (!mCancellation) {
  95. fetchData(uri, syncResult, file.getFileId());
  96. }
  97. }
  98. } else {
  99. syncResult.stats.numAuthExceptions++;
  100. }
  101. } catch (IOException e) {
  102. syncResult.stats.numIoExceptions++;
  103. logException(e, uri + "/");
  104. } catch (DavException e) {
  105. syncResult.stats.numParseExceptions++;
  106. logException(e, uri + "/");
  107. } catch (Exception e) {
  108. // TODO something smart with syncresult
  109. logException(e, uri + "/");
  110. mRightSync = false;
  111. } finally {
  112. if (query != null)
  113. query.releaseConnection(); // let the connection available for other methods
  114. mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0);
  115. if (!mRightSync && mIsManualSync) {
  116. /// don't let the system synchronization manager retries MANUAL synchronizations
  117. // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
  118. syncResult.tooManyRetries = true;
  119. /// notify the user about the failure of MANUAL synchronization
  120. Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
  121. notification.flags |= Notification.FLAG_AUTO_CANCEL;
  122. // TODO put something smart in the contentIntent below
  123. notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
  124. notification.setLatestEventInfo(getContext().getApplicationContext(),
  125. getContext().getString(R.string.sync_fail_ticker),
  126. String.format(getContext().getString(R.string.sync_fail_content), account.name),
  127. notification.contentIntent);
  128. ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
  129. }
  130. sendStickyBroadcast(false, null); // message to signal the end to the UI
  131. }
  132. /* Commented code for ugly performance tests
  133. long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;
  134. for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
  135. sum += mResponseDelays[i];
  136. max = Math.max(max, mResponseDelays[i]);
  137. min = Math.min(min, mResponseDelays[i]);
  138. }
  139. mean = sum / mDelaysCount;
  140. Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
  141. sum = 0; max = 0; min = Long.MAX_VALUE;
  142. for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
  143. sum += mSaveDelays[i];
  144. max = Math.max(max, mSaveDelays[i]);
  145. min = Math.min(min, mSaveDelays[i]);
  146. }
  147. mean = sum / mDelaysCount;
  148. Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
  149. Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);
  150. */
  151. }
  152. private void fetchData(String uri, SyncResult syncResult, long parentId) {
  153. PropFindMethod query = null;
  154. try {
  155. Log.d(TAG, "fetching " + uri);
  156. // remote request
  157. query = new PropFindMethod(uri);
  158. /* Commented code for ugly performance tests
  159. long responseDelay = System.currentTimeMillis();
  160. */
  161. int status = getClient().executeMethod(query);
  162. /* Commented code for ugly performance tests
  163. responseDelay = System.currentTimeMillis() - responseDelay;
  164. Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");
  165. */
  166. if (status != HttpStatus.SC_UNAUTHORIZED) {
  167. MultiStatus resp = query.getResponseBodyAsMultiStatus();
  168. // insertion or update of files
  169. List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
  170. for (int i = 1; i < resp.getResponses().length; ++i) {
  171. WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());
  172. OCFile file = fillOCFile(we);
  173. file.setParentId(parentId);
  174. if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&
  175. getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&
  176. file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())
  177. .getModificationTimestamp()) {
  178. Intent intent = new Intent(this.getContext(), FileDownloader.class);
  179. intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
  180. intent.putExtra(FileDownloader.EXTRA_FILE, file);
  181. /*intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath());
  182. intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath());
  183. intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength());*/
  184. file.setKeepInSync(true);
  185. getContext().startService(intent);
  186. }
  187. if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
  188. file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
  189. // Log.v(TAG, "adding file: " + file);
  190. updatedFiles.add(file);
  191. if (parentId == 0)
  192. parentId = file.getFileId();
  193. }
  194. /* Commented code for ugly performance tests
  195. long saveDelay = System.currentTimeMillis();
  196. */
  197. getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update
  198. /* Commented code for ugly performance tests
  199. saveDelay = System.currentTimeMillis() - saveDelay;
  200. Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");
  201. */
  202. // removal of obsolete files
  203. Vector<OCFile> files = getStorageManager().getDirectoryContent(
  204. getStorageManager().getFileById(parentId));
  205. OCFile file;
  206. String currentSavePath = FileDownloader.getSavePath(getAccount().name);
  207. for (int i=0; i < files.size(); ) {
  208. file = files.get(i);
  209. if (file.getLastSyncDate() != mCurrentSyncTime) {
  210. Log.v(TAG, "removing file: " + file);
  211. getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
  212. files.remove(i);
  213. } else {
  214. i++;
  215. }
  216. }
  217. // recursive fetch
  218. for (int i=0; i < files.size() && !mCancellation; i++) {
  219. OCFile newFile = files.get(i);
  220. if (newFile.getMimetype().equals("DIR")) {
  221. fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId());
  222. }
  223. }
  224. if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");
  225. /* Commented code for ugly performance tests
  226. mResponseDelays[mDelaysIndex] = responseDelay;
  227. mSaveDelays[mDelaysIndex] = saveDelay;
  228. mDelaysCount++;
  229. mDelaysIndex++;
  230. if (mDelaysIndex >= MAX_DELAYS)
  231. mDelaysIndex = 0;
  232. */
  233. } else {
  234. syncResult.stats.numAuthExceptions++;
  235. }
  236. } catch (IOException e) {
  237. syncResult.stats.numIoExceptions++;
  238. logException(e, uri);
  239. } catch (DavException e) {
  240. syncResult.stats.numParseExceptions++;
  241. logException(e, uri);
  242. } catch (Exception e) {
  243. // TODO something smart with syncresult
  244. mRightSync = false;
  245. logException(e, uri);
  246. } finally {
  247. if (query != null)
  248. query.releaseConnection(); // let the connection available for other methods
  249. // synchronized folder -> notice to UI
  250. sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());
  251. }
  252. }
  253. private OCFile fillOCFile(WebdavEntry we) {
  254. OCFile file = new OCFile(we.decodedPath());
  255. file.setCreationTimestamp(we.createTimestamp());
  256. file.setFileLength(we.contentLength());
  257. file.setMimetype(we.contentType());
  258. file.setModificationTimestamp(we.modifiedTimesamp());
  259. file.setLastSyncDate(mCurrentSyncTime);
  260. return file;
  261. }
  262. private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) {
  263. Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
  264. i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
  265. i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
  266. if (dirRemotePath != null) {
  267. i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
  268. }
  269. getContext().sendStickyBroadcast(i);
  270. }
  271. /**
  272. * Called by system SyncManager when a synchronization is required to be cancelled.
  273. *
  274. * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
  275. * fetched will be still saved in the database. See onPerformSync implementation.
  276. */
  277. @Override
  278. public void onSyncCanceled() {
  279. Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
  280. mCancellation = true;
  281. super.onSyncCanceled();
  282. }
  283. /**
  284. * Logs an exception triggered in a synchronization request.
  285. *
  286. * @param e Caught exception.
  287. * @param uri Uri to the remote directory that was fetched when the synchronization failed
  288. */
  289. private void logException(Exception e, String uri) {
  290. if (e instanceof IOException) {
  291. Log.e(TAG, "Unrecovered transport exception while synchronizing " + uri + " at " + getAccount().name, e);
  292. } else if (e instanceof DavException) {
  293. Log.e(TAG, "Unexpected WebDAV exception while synchronizing " + uri + " at " + getAccount().name, e);
  294. } else {
  295. Log.e(TAG, "Unexpected exception while synchronizing " + uri + " at " + getAccount().name, e);
  296. }
  297. }
  298. }