1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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.
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.
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/>.
18 package com
.owncloud
.android
.operations
;
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
;
29 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
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
;
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
;
52 import android
.accounts
.Account
;
53 import android
.content
.Context
;
57 * Remote operation performing the upload of a file to an ownCloud server
59 * @author David A. Velasco
61 public class UploadFileOperation
extends RemoteOperation
{
63 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
65 private Account mAccount
;
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
;
82 private UploadRemoteFileOperation mUploadOperation
;
84 protected RequestEntity mEntity
= null
;
87 public UploadFileOperation( Account account
,
91 boolean forceOverwrite
,
95 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
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());
107 mRemotePath
= file
.getRemotePath();
109 mIsInstant
= isInstant
;
110 mForceOverwrite
= forceOverwrite
;
111 mLocalBehaviour
= localBehaviour
;
112 mOriginalStoragePath
= mFile
.getStoragePath();
113 mOriginalFileName
= mFile
.getFileName();
117 public Account
getAccount() {
121 public String
getFileName() {
122 return mOriginalFileName
;
125 public OCFile
getFile() {
129 public OCFile
getOldFile() {
133 public String
getOriginalStoragePath() {
134 return mOriginalStoragePath
;
137 public String
getStoragePath() {
138 return mFile
.getStoragePath();
141 public String
getRemotePath() {
142 return mFile
.getRemotePath();
145 public String
getMimeType() {
146 return mFile
.getMimetype();
149 public boolean isInstant() {
153 public boolean isRemoteFolderToBeCreated() {
154 return mRemoteFolderToBeCreated
;
157 public void setRemoteFolderToBeCreated() {
158 mRemoteFolderToBeCreated
= true
;
161 public boolean getForceOverwrite() {
162 return mForceOverwrite
;
165 public boolean wasRenamed() {
169 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
170 return mDataTransferListeners
;
173 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
174 synchronized (mDataTransferListeners
) {
175 mDataTransferListeners
.add(listener
);
177 if (mEntity
!= null
) {
178 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
182 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
183 synchronized (mDataTransferListeners
) {
184 mDataTransferListeners
.remove(listener
);
186 if (mEntity
!= null
) {
187 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
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
;
197 // / rename the file to upload, if necessary
198 if (!mForceOverwrite
) {
199 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
200 mWasRenamed
= !remotePath
.equals(mRemotePath
);
202 createNewOCFile(remotePath
);
205 nameCheckPassed
= true
;
207 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
210 // getAvailableRemotePath()
212 expectedFile
= new File(expectedPath
);
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
) {
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
224 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
225 mFile
.setStoragePath(temporalPath
);
226 temporalFile
= new File(temporalPath
);
227 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
232 InputStream
in = null
;
233 OutputStream out
= null
;
235 File temporalParent
= temporalFile
.getParentFile();
236 temporalParent
.mkdirs();
237 if (!temporalParent
.isDirectory()) {
238 throw new IOException("Unexpected error: parent directory could not be created");
240 temporalFile
.createNewFile();
241 if (!temporalFile
.isFile()) {
242 throw new IOException("Unexpected error: target file could not be created");
244 in = new FileInputStream(originalFile
);
245 out
= new FileOutputStream(temporalFile
);
246 byte[] buf
= new byte[1024];
248 while ((len
= in.read(buf
)) > 0) {
249 out
.write(buf
, 0, len
);
252 } catch (Exception e
) {
253 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
260 } catch (Exception e
) {
261 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
266 } catch (Exception e
) {
267 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
273 localCopyPassed
= true
;
275 /// perform the upload
277 mUploadOperation
= new ChunkedUploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
278 mFile
.getMimetype());
280 mUploadOperation
= new UploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
281 mFile
.getMimetype());
283 Iterator
<OnDatatransferProgressListener
> listener
= mDataTransferListeners
.iterator();
284 while (listener
.hasNext()) {
285 mUploadOperation
.addDatatransferProgressListener(listener
.next());
287 result
= mUploadOperation
.execute(client
);
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
);
296 mFile
.setStoragePath(expectedPath
);
297 File fileToMove
= null
;
298 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
299 // ; see where temporalFile was
301 fileToMove
= temporalFile
;
302 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
303 fileToMove
= originalFile
;
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
314 // the best option could be show a warning message
317 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
324 } catch (Exception e
) {
325 // TODO something cleaner with cancellations
326 if (mCancellationRequested
.get()) {
327 result
= new RemoteOperationResult(new OperationCancelledException());
329 result
= new RemoteOperationResult(e
);
333 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
334 temporalFile
.delete();
336 if (result
.isSuccess()) {
337 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
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
)
347 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
349 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
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());
375 public boolean isSuccess(int status
) {
376 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
379 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
382 File f
= new File(mFile
.getStoragePath());
383 mEntity
= new FileRequestEntity(f
, getMimeType());
384 synchronized (mDataTransferListeners
) {
385 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListeners(mDataTransferListeners
);
387 mPutMethod
.setRequestEntity(mEntity
);
388 status
= client
.executeMethod(mPutMethod
);
389 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
392 mPutMethod
.releaseConnection(); // let the connection available for
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.
405 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
406 boolean check
= existsFile(wc
, remotePath
);
411 int pos
= remotePath
.lastIndexOf(".");
413 String extension
= "";
415 extension
= remotePath
.substring(pos
+ 1);
416 remotePath
= remotePath
.substring(0, pos
);
420 suffix
= " (" + count
+ ")";
422 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
425 check
= existsFile(wc
, remotePath
+ suffix
);
431 return remotePath
+ suffix
+ "." + extension
;
433 return remotePath
+ suffix
;
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();
443 public void cancel() {
444 mUploadOperation
.cancel();