Fixed bug: when a file is checked as 'keep in sync' and the immediate synchronization...
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFileOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 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
19 package com.owncloud.android.operations;
20
21 import org.apache.http.HttpStatus;
22 import org.apache.jackrabbit.webdav.MultiStatus;
23 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
24
25 import android.accounts.Account;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.util.Log;
29
30 import com.owncloud.android.datamodel.DataStorageManager;
31 import com.owncloud.android.datamodel.OCFile;
32 import com.owncloud.android.files.services.FileDownloader;
33 import com.owncloud.android.files.services.FileUploader;
34 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
35
36 import eu.alefzero.webdav.WebdavClient;
37 import eu.alefzero.webdav.WebdavEntry;
38 import eu.alefzero.webdav.WebdavUtils;
39
40 public class SynchronizeFileOperation extends RemoteOperation {
41
42 private String TAG = SynchronizeFileOperation.class.getSimpleName();
43 //private String mRemotePath;
44 private OCFile mLocalFile;
45 private DataStorageManager mStorageManager;
46 private Account mAccount;
47 private boolean mSyncFileContents;
48 private boolean mLocalChangeAlreadyKnown;
49 private Context mContext;
50
51 private boolean mTransferWasRequested = false;
52
53 public SynchronizeFileOperation(
54 OCFile localFile,
55 DataStorageManager dataStorageManager,
56 Account account,
57 boolean syncFileContents,
58 boolean localChangeAlreadyKnown,
59 Context context) {
60
61 //mRemotePath = remotePath;
62 mLocalFile = localFile;
63 mStorageManager = dataStorageManager;
64 mAccount = account;
65 mSyncFileContents = syncFileContents;
66 mLocalChangeAlreadyKnown = localChangeAlreadyKnown;
67 mContext = context;
68 }
69
70
71 @Override
72 protected RemoteOperationResult run(WebdavClient client) {
73
74 PropFindMethod propfind = null;
75 RemoteOperationResult result = null;
76 mTransferWasRequested = false;
77 try {
78 if (!mLocalFile.isDown()) {
79 /// easy decision
80 requestForDownload(mLocalFile);
81 result = new RemoteOperationResult(ResultCode.OK);
82
83 } else {
84 /// local copy in the device -> need to think a bit more before do anything
85
86 propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mLocalFile.getRemotePath()));
87 int status = client.executeMethod(propfind);
88 boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS;
89 if (isMultiStatus) {
90 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
91 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
92 client.getBaseUri().getPath());
93 OCFile serverFile = fillOCFile(we);
94
95 /// check changes in server and local file
96 boolean serverChanged = false;
97 if (serverFile.getEtag() != null) {
98 serverChanged = (!serverFile.getEtag().equals(mLocalFile.getEtag())); // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
99 } else {
100 // server without etags
101 serverChanged = (serverFile.getModificationTimestamp() > mLocalFile.getModificationTimestamp());
102 }
103 boolean localChanged = (mLocalChangeAlreadyKnown || mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
104 // TODO this will be always true after the app is upgraded to database version 3; will result in unnecessary uploads
105
106 /// decide action to perform depending upon changes
107 if (localChanged && serverChanged) {
108 // conflict
109 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
110
111 } else if (localChanged) {
112 if (mSyncFileContents) {
113 requestForUpload(mLocalFile);
114 // the local update of file properties will be done by the FileUploader service when the upload finishes
115 } else {
116 // NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
117 // So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
118 // that an upload is necessary (for instance, in FileObserverService).
119 }
120 result = new RemoteOperationResult(ResultCode.OK);
121
122 } else if (serverChanged) {
123 if (mSyncFileContents) {
124 requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
125 // the update of local data will be done later by the FileUploader service when the upload finishes
126 } else {
127 // TODO CHECK: is this really useful in some point in the code?
128 serverFile.setKeepInSync(mLocalFile.keepInSync());
129 serverFile.setParentId(mLocalFile.getParentId());
130 mStorageManager.saveFile(serverFile);
131
132 }
133 result = new RemoteOperationResult(ResultCode.OK);
134
135 } else {
136 // nothing changed, nothing to do
137 result = new RemoteOperationResult(ResultCode.OK);
138 }
139
140 } else {
141 client.exhaustResponse(propfind.getResponseBodyAsStream());
142 result = new RemoteOperationResult(false, status);
143 }
144
145 }
146
147 Log.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
148
149 } catch (Exception e) {
150 result = new RemoteOperationResult(e);
151 Log.e(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage(), result.getException());
152
153 } finally {
154 if (propfind != null)
155 propfind.releaseConnection();
156 }
157 return result;
158 }
159
160
161 /**
162 * Requests for an upload to the FileUploader service
163 *
164 * @param file OCFile object representing the file to upload
165 */
166 private void requestForUpload(OCFile file) {
167 Intent i = new Intent(mContext, FileUploader.class);
168 i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
169 i.putExtra(FileUploader.KEY_FILE, file);
170 /*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it!
171 i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
172 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
173 i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
174 mContext.startService(i);
175 mTransferWasRequested = true;
176 }
177
178
179 /**
180 * Requests for a download to the FileDownloader service
181 *
182 * @param file OCFile object representing the file to download
183 */
184 private void requestForDownload(OCFile file) {
185 Intent i = new Intent(mContext, FileDownloader.class);
186 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
187 i.putExtra(FileDownloader.EXTRA_FILE, file);
188 mContext.startService(i);
189 mTransferWasRequested = true;
190 }
191
192
193 /**
194 * Creates and populates a new {@link OCFile} object with the data read from the server.
195 *
196 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
197 * @return New OCFile instance representing the remote resource described by we.
198 */
199 private OCFile fillOCFile(WebdavEntry we) {
200 OCFile file = new OCFile(we.decodedPath());
201 file.setCreationTimestamp(we.createTimestamp());
202 file.setFileLength(we.contentLength());
203 file.setMimetype(we.contentType());
204 file.setModificationTimestamp(we.modifiedTimesamp());
205 file.setLastSyncDateForProperties(System.currentTimeMillis());
206 file.setLastSyncDateForData(0);
207 return file;
208 }
209
210
211 public boolean transferWasRequested() {
212 return mTransferWasRequested;
213 }
214
215 }