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