FileSyncAdapter.java 17 KB

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