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
;
28 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
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
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.files
.services
.FileUploader
;
37 import com
.owncloud
.android
.oc_framework
.network
.ProgressiveDataTransferer
;
38 import com
.owncloud
.android
.oc_framework
.network
.webdav
.FileRequestEntity
;
39 import com
.owncloud
.android
.oc_framework
.network
.webdav
.OnDatatransferProgressListener
;
40 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavClient
;
41 import com
.owncloud
.android
.oc_framework
.operations
.OperationCancelledException
;
42 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperation
;
43 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
;
44 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
.ResultCode
;
45 import com
.owncloud
.android
.oc_framework
.operations
.remote
.ExistenceCheckRemoteOperation
;
46 import com
.owncloud
.android
.oc_framework
.operations
.remote
.UploadRemoteFileOperation
;
47 import com
.owncloud
.android
.utils
.FileStorageUtils
;
48 import com
.owncloud
.android
.utils
.Log_OC
;
50 import android
.accounts
.Account
;
51 import android
.content
.Context
;
55 * Remote operation performing the upload of a file to an ownCloud server
57 * @author David A. Velasco
59 public class UploadFileOperation
extends RemoteOperation
{
61 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
63 private Account mAccount
;
65 private OCFile mOldFile
;
66 private String mRemotePath
= null
;
67 private boolean mIsInstant
= false
;
68 private boolean mRemoteFolderToBeCreated
= false
;
69 private boolean mForceOverwrite
= false
;
70 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
71 private boolean mWasRenamed
= false
;
72 private String mOriginalFileName
= null
;
73 private String mOriginalStoragePath
= null
;
74 PutMethod mPutMethod
= null
;
75 private OnDatatransferProgressListener mDataTransferListener
;
76 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
77 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
78 private Context mContext
;
80 private UploadRemoteFileOperation mUploadOperation
;
82 protected RequestEntity mEntity
= null
;
85 public UploadFileOperation( Account account
,
88 boolean forceOverwrite
,
91 OnDatatransferProgressListener listener
) {
93 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
95 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
96 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0
97 || !(new File(file
.getStoragePath()).exists())) {
98 throw new IllegalArgumentException(
99 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
100 + file
.getStoragePath());
105 mRemotePath
= file
.getRemotePath();
106 mIsInstant
= isInstant
;
107 mForceOverwrite
= forceOverwrite
;
108 mLocalBehaviour
= localBehaviour
;
109 mOriginalStoragePath
= mFile
.getStoragePath();
110 mOriginalFileName
= mFile
.getFileName();
112 mDataTransferListener
= listener
;
115 public Account
getAccount() {
119 public String
getFileName() {
120 return mOriginalFileName
;
123 public OCFile
getFile() {
127 public OCFile
getOldFile() {
131 public String
getOriginalStoragePath() {
132 return mOriginalStoragePath
;
135 public String
getStoragePath() {
136 return mFile
.getStoragePath();
139 public String
getRemotePath() {
140 return mFile
.getRemotePath();
143 public String
getMimeType() {
144 return mFile
.getMimetype();
147 public boolean isInstant() {
151 public boolean isRemoteFolderToBeCreated() {
152 return mRemoteFolderToBeCreated
;
155 public void setRemoteFolderToBeCreated() {
156 mRemoteFolderToBeCreated
= true
;
159 public boolean getForceOverwrite() {
160 return mForceOverwrite
;
163 public boolean wasRenamed() {
167 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
168 return mDataTransferListeners
;
171 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
172 synchronized (mDataTransferListeners
) {
173 mDataTransferListeners
.add(listener
);
175 if (mEntity
!= null
) {
176 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
180 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
181 synchronized (mDataTransferListeners
) {
182 mDataTransferListeners
.remove(listener
);
184 if (mEntity
!= null
) {
185 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
190 protected RemoteOperationResult
run(WebdavClient client
) {
191 RemoteOperationResult result
= null
;
192 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
193 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
195 // / rename the file to upload, if necessary
196 if (!mForceOverwrite
) {
197 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
198 mWasRenamed
= !remotePath
.equals(mRemotePath
);
200 createNewOCFile(remotePath
);
203 nameCheckPassed
= true
;
205 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
208 // getAvailableRemotePath()
210 expectedFile
= new File(expectedPath
);
212 // check location of local file; if not the expected, copy to a
213 // temporal file before upload (if COPY is the expected behaviour)
214 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
216 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
217 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
218 return result
; // error condition when the file should be
222 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
223 mFile
.setStoragePath(temporalPath
);
224 temporalFile
= new File(temporalPath
);
225 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
230 InputStream
in = null
;
231 OutputStream out
= null
;
233 File temporalParent
= temporalFile
.getParentFile();
234 temporalParent
.mkdirs();
235 if (!temporalParent
.isDirectory()) {
236 throw new IOException("Unexpected error: parent directory could not be created");
238 temporalFile
.createNewFile();
239 if (!temporalFile
.isFile()) {
240 throw new IOException("Unexpected error: target file could not be created");
242 in = new FileInputStream(originalFile
);
243 out
= new FileOutputStream(temporalFile
);
244 byte[] buf
= new byte[1024];
246 while ((len
= in.read(buf
)) > 0) {
247 out
.write(buf
, 0, len
);
250 } catch (Exception e
) {
251 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
258 } catch (Exception e
) {
259 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
264 } catch (Exception e
) {
265 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
271 localCopyPassed
= true
;
273 /// perform the upload
274 mUploadOperation
= new UploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
275 mFile
.getMimetype());
276 result
= mUploadOperation
.execute(client
);
278 /// move local temporal file or original file to its corresponding
279 // location in the ownCloud local folder
280 if (result
.isSuccess()) {
281 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
282 mFile
.setStoragePath(null
);
285 mFile
.setStoragePath(expectedPath
);
286 File fileToMove
= null
;
287 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
288 // ; see where temporalFile was
290 fileToMove
= temporalFile
;
291 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
292 fileToMove
= originalFile
;
294 if (!expectedFile
.equals(fileToMove
)) {
295 File expectedFolder
= expectedFile
.getParentFile();
296 expectedFolder
.mkdirs();
297 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
298 mFile
.setStoragePath(null
); // forget the local file
299 // by now, treat this as a success; the file was
300 // uploaded; the user won't like that the local file
301 // is not linked, but this should be a very rare
303 // the best option could be show a warning message
306 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
313 } catch (Exception e
) {
314 // TODO something cleaner with cancellations
315 if (mCancellationRequested
.get()) {
316 result
= new RemoteOperationResult(new OperationCancelledException());
318 result
= new RemoteOperationResult(e
);
322 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
323 temporalFile
.delete();
325 if (result
.isSuccess()) {
326 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
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
)
336 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
338 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
346 private void createNewOCFile(String newRemotePath
) {
347 // a new OCFile instance must be created for a new remote path
348 OCFile newFile
= new OCFile(newRemotePath
);
349 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
350 newFile
.setFileLength(mFile
.getFileLength());
351 newFile
.setMimetype(mFile
.getMimetype());
352 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
353 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
354 // newFile.setEtag(mFile.getEtag())
355 newFile
.setKeepInSync(mFile
.keepInSync());
356 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
357 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
358 newFile
.setStoragePath(mFile
.getStoragePath());
359 newFile
.setParentId(mFile
.getParentId());
364 public boolean isSuccess(int status
) {
365 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
368 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
371 File f
= new File(mFile
.getStoragePath());
372 mEntity
= new FileRequestEntity(f
, getMimeType());
373 synchronized (mDataTransferListeners
) {
374 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListeners(mDataTransferListeners
);
376 mPutMethod
.setRequestEntity(mEntity
);
377 status
= client
.executeMethod(mPutMethod
);
378 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
381 mPutMethod
.releaseConnection(); // let the connection available for
388 * Checks if remotePath does not exist in the server and returns it, or adds
389 * a suffix to it in order to avoid the server file is overwritten.
394 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
395 boolean check
= existsFile(wc
, remotePath
);
400 int pos
= remotePath
.lastIndexOf(".");
402 String extension
= "";
404 extension
= remotePath
.substring(pos
+ 1);
405 remotePath
= remotePath
.substring(0, pos
);
409 suffix
= " (" + count
+ ")";
411 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
414 check
= existsFile(wc
, remotePath
+ suffix
);
420 return remotePath
+ suffix
+ "." + extension
;
422 return remotePath
+ suffix
;
426 private boolean existsFile(WebdavClient client
, String remotePath
){
427 ExistenceCheckRemoteOperation existsOperation
= new ExistenceCheckRemoteOperation(remotePath
, mContext
, false
);
428 RemoteOperationResult result
= existsOperation
.execute(client
);
429 return result
.isSuccess();
432 public void cancel() {
433 mUploadOperation
.cancel();