77724d09e9804cc746b98284712411fa8b9bb2ab
[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 OCFile mServerFile;
46 private DataStorageManager mStorageManager;
47 private Account mAccount;
48 private boolean mSyncFileContents;
49 private boolean mLocalChangeAlreadyKnown;
50 private Context mContext;
51
52 private boolean mTransferWasRequested = false;
53
54 public SynchronizeFileOperation(
55 OCFile localFile,
56 OCFile serverFile, // make this null to let the operation checks the server; added to reuse info from SynchronizeFolderOperation
57 DataStorageManager storageManager,
58 Account account,
59 boolean syncFileContents,
60 boolean localChangeAlreadyKnown,
61 Context context) {
62
63 mLocalFile = localFile;
64 mServerFile = serverFile;
65 mStorageManager = storageManager;
66 mAccount = account;
67 mSyncFileContents = syncFileContents;
68 mLocalChangeAlreadyKnown = localChangeAlreadyKnown;
69 mContext = context;
70 }
71
72
73 @Override
74 protected RemoteOperationResult run(WebdavClient client) {
75
76 PropFindMethod propfind = null;
77 RemoteOperationResult result = null;
78 mTransferWasRequested = false;
79 try {
80 if (!mLocalFile.isDown()) {
81 /// easy decision
82 requestForDownload(mLocalFile);
83 result = new RemoteOperationResult(ResultCode.OK);
84
85 } else {
86 /// local copy in the device -> need to think a bit more before do anything
87
88 if (mServerFile == null) {
89 /// take the duty of check the server for the current state of the file there
90 propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mLocalFile.getRemotePath()));
91 int status = client.executeMethod(propfind);
92 boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS;
93 if (isMultiStatus) {
94 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
95 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
96 client.getBaseUri().getPath());
97 mServerFile = fillOCFile(we);
98
99 } else {
100 client.exhaustResponse(propfind.getResponseBodyAsStream());
101 result = new RemoteOperationResult(false, status);
102 }
103 }
104
105 if (result == null) { // true if the server was not checked, or nothing was wrong with the remote request
106
107 /// check changes in server and local file
108 boolean serverChanged = false;
109 if (mServerFile.getEtag() != null) {
110 serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag())); // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
111 } else {
112 // server without etags
113 serverChanged = (mServerFile.getModificationTimestamp() > mLocalFile.getModificationTimestamp());
114 }
115 boolean localChanged = (mLocalChangeAlreadyKnown || mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
116 // TODO this will be always true after the app is upgraded to database version 3; will result in unnecessary uploads
117
118 /// decide action to perform depending upon changes
119 if (localChanged && serverChanged) {
120 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
121
122 } else if (localChanged) {
123 if (mSyncFileContents) {
124 requestForUpload(mLocalFile);
125 // the local update of file properties will be done by the FileUploader service when the upload finishes
126 } else {
127 // NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
128 // So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
129 // that an upload is necessary (for instance, in FileObserverService).
130 }
131 result = new RemoteOperationResult(ResultCode.OK);
132
133 } else if (serverChanged) {
134 if (mSyncFileContents) {
135 requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
136 // the update of local data will be done later by the FileUploader service when the upload finishes
137 } else {
138 // TODO CHECK: is this really useful in some point in the code?
139 mServerFile.setKeepInSync(mLocalFile.keepInSync());
140 mServerFile.setParentId(mLocalFile.getParentId());
141 mStorageManager.saveFile(mServerFile);
142
143 }
144 result = new RemoteOperationResult(ResultCode.OK);
145
146 } else {
147 // nothing changed, nothing to do
148 result = new RemoteOperationResult(ResultCode.OK);
149 }
150
151 }
152
153 }
154
155 Log.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
156
157 } catch (Exception e) {
158 result = new RemoteOperationResult(e);
159 Log.e(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage(), result.getException());
160
161 } finally {
162 if (propfind != null)
163 propfind.releaseConnection();
164 }
165 return result;
166 }
167
168
169 /**
170 * Requests for an upload to the FileUploader service
171 *
172 * @param file OCFile object representing the file to upload
173 */
174 private void requestForUpload(OCFile file) {
175 Intent i = new Intent(mContext, FileUploader.class);
176 i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
177 i.putExtra(FileUploader.KEY_FILE, file);
178 /*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!
179 i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
180 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
181 i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
182 mContext.startService(i);
183 mTransferWasRequested = true;
184 }
185
186
187 /**
188 * Requests for a download to the FileDownloader service
189 *
190 * @param file OCFile object representing the file to download
191 */
192 private void requestForDownload(OCFile file) {
193 Intent i = new Intent(mContext, FileDownloader.class);
194 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
195 i.putExtra(FileDownloader.EXTRA_FILE, file);
196 mContext.startService(i);
197 mTransferWasRequested = true;
198 }
199
200
201 /**
202 * Creates and populates a new {@link OCFile} object with the data read from the server.
203 *
204 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
205 * @return New OCFile instance representing the remote resource described by we.
206 */
207 private OCFile fillOCFile(WebdavEntry we) {
208 OCFile file = new OCFile(we.decodedPath());
209 file.setCreationTimestamp(we.createTimestamp());
210 file.setFileLength(we.contentLength());
211 file.setMimetype(we.contentType());
212 file.setModificationTimestamp(we.modifiedTimesamp());
213 file.setLastSyncDateForProperties(System.currentTimeMillis());
214 file.setLastSyncDateForData(0);
215 return file;
216 }
217
218
219 public boolean transferWasRequested() {
220 return mTransferWasRequested;
221 }
222
223 }