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