cae1f179868801bd553452b288de7e9a0db42a26
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / UploadFileOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.operations;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.util.HashSet;
27 import java.util.Set;
28 import java.util.concurrent.atomic.AtomicBoolean;
29
30 import org.apache.commons.httpclient.HttpException;
31 import org.apache.commons.httpclient.methods.PutMethod;
32 import org.apache.commons.httpclient.methods.RequestEntity;
33 import org.apache.http.HttpStatus;
34
35 import com.owncloud.android.Log_OC;
36 import android.accounts.Account;
37
38 import com.owncloud.android.datamodel.OCFile;
39 import com.owncloud.android.files.services.FileUploader;
40 import com.owncloud.android.network.ProgressiveDataTransferer;
41 import com.owncloud.android.operations.RemoteOperation;
42 import com.owncloud.android.operations.RemoteOperationResult;
43 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
44 import com.owncloud.android.utils.FileStorageUtils;
45
46 import eu.alefzero.webdav.FileRequestEntity;
47 import eu.alefzero.webdav.OnDatatransferProgressListener;
48 import eu.alefzero.webdav.WebdavClient;
49 import eu.alefzero.webdav.WebdavUtils;
50
51 /**
52 * Remote operation performing the upload of a file to an ownCloud server
53 *
54 * @author David A. Velasco
55 */
56 public class UploadFileOperation extends RemoteOperation {
57
58 private static final String TAG = UploadFileOperation.class.getSimpleName();
59
60 private Account mAccount;
61 private OCFile mFile;
62 private OCFile mOldFile;
63 private String mRemotePath = null;
64 private boolean mIsInstant = false;
65 private boolean mRemoteFolderToBeCreated = false;
66 private boolean mForceOverwrite = false;
67 private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
68 private boolean mWasRenamed = false;
69 private String mOriginalFileName = null;
70 private String mOriginalStoragePath = null;
71 PutMethod mPutMethod = null;
72 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
73 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
74
75 protected RequestEntity mEntity = null;
76
77
78 public UploadFileOperation( Account account,
79 OCFile file,
80 boolean isInstant,
81 boolean forceOverwrite,
82 int localBehaviour) {
83 if (account == null)
84 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
85 if (file == null)
86 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
87 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0
88 || !(new File(file.getStoragePath()).exists())) {
89 throw new IllegalArgumentException(
90 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
91 + file.getStoragePath());
92 }
93
94 mAccount = account;
95 mFile = file;
96 mRemotePath = file.getRemotePath();
97 mIsInstant = isInstant;
98 mForceOverwrite = forceOverwrite;
99 mLocalBehaviour = localBehaviour;
100 mOriginalStoragePath = mFile.getStoragePath();
101 mOriginalFileName = mFile.getFileName();
102 }
103
104 public Account getAccount() {
105 return mAccount;
106 }
107
108 public String getFileName() {
109 return mOriginalFileName;
110 }
111
112 public OCFile getFile() {
113 return mFile;
114 }
115
116 public OCFile getOldFile() {
117 return mOldFile;
118 }
119
120 public String getOriginalStoragePath() {
121 return mOriginalStoragePath;
122 }
123
124 public String getStoragePath() {
125 return mFile.getStoragePath();
126 }
127
128 public String getRemotePath() {
129 return mFile.getRemotePath();
130 }
131
132 public String getMimeType() {
133 return mFile.getMimetype();
134 }
135
136 public boolean isInstant() {
137 return mIsInstant;
138 }
139
140 public boolean isRemoteFolderToBeCreated() {
141 return mRemoteFolderToBeCreated;
142 }
143
144 public void setRemoteFolderToBeCreated() {
145 mRemoteFolderToBeCreated = true;
146 }
147
148 public boolean getForceOverwrite() {
149 return mForceOverwrite;
150 }
151
152 public boolean wasRenamed() {
153 return mWasRenamed;
154 }
155
156 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
157 return mDataTransferListeners;
158 }
159
160 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
161 synchronized (mDataTransferListeners) {
162 mDataTransferListeners.add(listener);
163 }
164 if (mEntity != null) {
165 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
166 }
167 }
168
169 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
170 synchronized (mDataTransferListeners) {
171 mDataTransferListeners.remove(listener);
172 }
173 if (mEntity != null) {
174 ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
175 }
176 }
177
178 @Override
179 protected RemoteOperationResult run(WebdavClient client) {
180 RemoteOperationResult result = null;
181 boolean localCopyPassed = false, nameCheckPassed = false;
182 File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
183 try {
184 // / rename the file to upload, if necessary
185 if (!mForceOverwrite) {
186 String remotePath = getAvailableRemotePath(client, mRemotePath);
187 mWasRenamed = !remotePath.equals(mRemotePath);
188 if (mWasRenamed) {
189 createNewOCFile(remotePath);
190 }
191 }
192 nameCheckPassed = true;
193
194 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
195 // not
196 // before
197 // getAvailableRemotePath()
198 // !!!
199 expectedFile = new File(expectedPath);
200
201 // / check location of local file; if not the expected, copy to a
202 // temporal file before upload (if COPY is the expected behaviour)
203 if (!mOriginalStoragePath.equals(expectedPath) && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
204
205 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
206 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
207 return result; // error condition when the file should be
208 // copied
209
210 } else {
211 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
212 mFile.setStoragePath(temporalPath);
213 temporalFile = new File(temporalPath);
214 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
215 // weird
216 // but
217 // possible
218 // situation
219 InputStream in = null;
220 OutputStream out = null;
221 try {
222 File temporalParent = temporalFile.getParentFile();
223 temporalParent.mkdirs();
224 if (!temporalParent.isDirectory()) {
225 throw new IOException("Unexpected error: parent directory could not be created");
226 }
227 temporalFile.createNewFile();
228 if (!temporalFile.isFile()) {
229 throw new IOException("Unexpected error: target file could not be created");
230 }
231 in = new FileInputStream(originalFile);
232 out = new FileOutputStream(temporalFile);
233 byte[] buf = new byte[1024];
234 int len;
235 while ((len = in.read(buf)) > 0) {
236 out.write(buf, 0, len);
237 }
238
239 } catch (Exception e) {
240 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
241 return result;
242
243 } finally {
244 try {
245 if (in != null)
246 in.close();
247 } catch (Exception e) {
248 Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e);
249 }
250 try {
251 if (out != null)
252 out.close();
253 } catch (Exception e) {
254 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
255 }
256 }
257 }
258 }
259 }
260 localCopyPassed = true;
261
262 // / perform the upload
263 synchronized (mCancellationRequested) {
264 if (mCancellationRequested.get()) {
265 throw new OperationCancelledException();
266 } else {
267 mPutMethod = new PutMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
268 }
269 }
270 int status = uploadFile(client);
271
272 // / move local temporal file or original file to its corresponding
273 // location in the ownCloud local folder
274 if (isSuccess(status)) {
275 if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
276 mFile.setStoragePath(null);
277
278 } else {
279 mFile.setStoragePath(expectedPath);
280 File fileToMove = null;
281 if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
282 // ; see where temporalFile was
283 // set
284 fileToMove = temporalFile;
285 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
286 fileToMove = originalFile;
287 }
288 if (!expectedFile.equals(fileToMove)) {
289 File expectedFolder = expectedFile.getParentFile();
290 expectedFolder.mkdirs();
291 if (!expectedFolder.isDirectory() || !fileToMove.renameTo(expectedFile)) {
292 mFile.setStoragePath(null); // forget the local file
293 // by now, treat this as a success; the file was
294 // uploaded; the user won't like that the local file
295 // is not linked, but this should be a very rare
296 // fail;
297 // the best option could be show a warning message
298 // (but not a fail)
299 // result = new
300 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
301 // return result;
302 }
303 }
304 }
305 }
306
307 result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
308
309 } catch (Exception e) {
310 // TODO something cleaner with cancellations
311 if (mCancellationRequested.get()) {
312 result = new RemoteOperationResult(new OperationCancelledException());
313 } else {
314 result = new RemoteOperationResult(e);
315 }
316
317 } finally {
318 if (temporalFile != null && !originalFile.equals(temporalFile)) {
319 temporalFile.delete();
320 }
321 if (result.isSuccess()) {
322 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
323 } else {
324 if (result.getException() != null) {
325 String complement = "";
326 if (!nameCheckPassed) {
327 complement = " (while checking file existence in server)";
328 } else if (!localCopyPassed) {
329 complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
330 + ")";
331 }
332 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException());
333 } else {
334 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
335 }
336 }
337 }
338
339 return result;
340 }
341
342 private void createNewOCFile(String newRemotePath) {
343 // a new OCFile instance must be created for a new remote path
344 OCFile newFile = new OCFile(newRemotePath);
345 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
346 newFile.setFileLength(mFile.getFileLength());
347 newFile.setMimetype(mFile.getMimetype());
348 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
349 newFile.setModificationTimestampAtLastSyncForData(mFile.getModificationTimestampAtLastSyncForData());
350 // newFile.setEtag(mFile.getEtag())
351 newFile.setKeepInSync(mFile.keepInSync());
352 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
353 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
354 newFile.setStoragePath(mFile.getStoragePath());
355 newFile.setParentId(mFile.getParentId());
356 mOldFile = mFile;
357 mFile = newFile;
358 }
359
360 public boolean isSuccess(int status) {
361 return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT));
362 }
363
364 protected int uploadFile(WebdavClient client) throws HttpException, IOException, OperationCancelledException {
365 int status = -1;
366 try {
367 File f = new File(mFile.getStoragePath());
368 mEntity = new FileRequestEntity(f, getMimeType());
369 synchronized (mDataTransferListeners) {
370 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners);
371 }
372 mPutMethod.setRequestEntity(mEntity);
373 status = client.executeMethod(mPutMethod);
374 client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
375
376 } finally {
377 mPutMethod.releaseConnection(); // let the connection available for
378 // other methods
379 }
380 return status;
381 }
382
383 /**
384 * Checks if remotePath does not exist in the server and returns it, or adds
385 * a suffix to it in order to avoid the server file is overwritten.
386 *
387 * @param string
388 * @return
389 */
390 private String getAvailableRemotePath(WebdavClient wc, String remotePath) throws Exception {
391 boolean check = wc.existsFile(remotePath);
392 if (!check) {
393 return remotePath;
394 }
395
396 int pos = remotePath.lastIndexOf(".");
397 String suffix = "";
398 String extension = "";
399 if (pos >= 0) {
400 extension = remotePath.substring(pos + 1);
401 remotePath = remotePath.substring(0, pos);
402 }
403 int count = 2;
404 do {
405 suffix = " (" + count + ")";
406 if (pos >= 0)
407 check = wc.existsFile(remotePath + suffix + "." + extension);
408 else
409 check = wc.existsFile(remotePath + suffix);
410 count++;
411 } while (check);
412
413 if (pos >= 0) {
414 return remotePath + suffix + "." + extension;
415 } else {
416 return remotePath + suffix;
417 }
418 }
419
420 public void cancel() {
421 synchronized (mCancellationRequested) {
422 mCancellationRequested.set(true);
423 if (mPutMethod != null)
424 mPutMethod.abort();
425 }
426 }
427
428 }