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
.network
.webdav
.WebdavUtils
;
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
.ExistenceCheckRemoteOperation
;
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 Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
76 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
77 private Context mContext
;
79 protected RequestEntity mEntity
= null
;
82 public UploadFileOperation( Account account
,
85 boolean forceOverwrite
,
89 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
91 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
92 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0
93 || !(new File(file
.getStoragePath()).exists())) {
94 throw new IllegalArgumentException(
95 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
96 + file
.getStoragePath());
101 mRemotePath
= file
.getRemotePath();
102 mIsInstant
= isInstant
;
103 mForceOverwrite
= forceOverwrite
;
104 mLocalBehaviour
= localBehaviour
;
105 mOriginalStoragePath
= mFile
.getStoragePath();
106 mOriginalFileName
= mFile
.getFileName();
110 public Account
getAccount() {
114 public String
getFileName() {
115 return mOriginalFileName
;
118 public OCFile
getFile() {
122 public OCFile
getOldFile() {
126 public String
getOriginalStoragePath() {
127 return mOriginalStoragePath
;
130 public String
getStoragePath() {
131 return mFile
.getStoragePath();
134 public String
getRemotePath() {
135 return mFile
.getRemotePath();
138 public String
getMimeType() {
139 return mFile
.getMimetype();
142 public boolean isInstant() {
146 public boolean isRemoteFolderToBeCreated() {
147 return mRemoteFolderToBeCreated
;
150 public void setRemoteFolderToBeCreated() {
151 mRemoteFolderToBeCreated
= true
;
154 public boolean getForceOverwrite() {
155 return mForceOverwrite
;
158 public boolean wasRenamed() {
162 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
163 return mDataTransferListeners
;
166 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
167 synchronized (mDataTransferListeners
) {
168 mDataTransferListeners
.add(listener
);
170 if (mEntity
!= null
) {
171 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
175 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
176 synchronized (mDataTransferListeners
) {
177 mDataTransferListeners
.remove(listener
);
179 if (mEntity
!= null
) {
180 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
185 protected RemoteOperationResult
run(WebdavClient client
) {
186 RemoteOperationResult result
= null
;
187 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
188 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
190 // / rename the file to upload, if necessary
191 if (!mForceOverwrite
) {
192 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
193 mWasRenamed
= !remotePath
.equals(mRemotePath
);
195 createNewOCFile(remotePath
);
198 nameCheckPassed
= true
;
200 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
203 // getAvailableRemotePath()
205 expectedFile
= new File(expectedPath
);
207 // check location of local file; if not the expected, copy to a
208 // temporal file before upload (if COPY is the expected behaviour)
209 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
211 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
212 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
213 return result
; // error condition when the file should be
217 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
218 mFile
.setStoragePath(temporalPath
);
219 temporalFile
= new File(temporalPath
);
220 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
225 InputStream
in = null
;
226 OutputStream out
= null
;
228 File temporalParent
= temporalFile
.getParentFile();
229 temporalParent
.mkdirs();
230 if (!temporalParent
.isDirectory()) {
231 throw new IOException("Unexpected error: parent directory could not be created");
233 temporalFile
.createNewFile();
234 if (!temporalFile
.isFile()) {
235 throw new IOException("Unexpected error: target file could not be created");
237 in = new FileInputStream(originalFile
);
238 out
= new FileOutputStream(temporalFile
);
239 byte[] buf
= new byte[1024];
241 while ((len
= in.read(buf
)) > 0) {
242 out
.write(buf
, 0, len
);
245 } catch (Exception e
) {
246 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
253 } catch (Exception e
) {
254 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
259 } catch (Exception e
) {
260 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
266 localCopyPassed
= true
;
268 // / perform the upload
269 synchronized (mCancellationRequested
) {
270 if (mCancellationRequested
.get()) {
271 throw new OperationCancelledException();
273 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
276 int status
= uploadFile(client
);
278 // / move local temporal file or original file to its corresponding
279 // location in the ownCloud local folder
280 if (isSuccess(status
)) {
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 result
= new RemoteOperationResult(isSuccess(status
), status
, (mPutMethod
!= null ? mPutMethod
.getResponseHeaders() : null
));
315 } catch (Exception e
) {
316 // TODO something cleaner with cancellations
317 if (mCancellationRequested
.get()) {
318 result
= new RemoteOperationResult(new OperationCancelledException());
320 result
= new RemoteOperationResult(e
);
324 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
325 temporalFile
.delete();
327 if (result
.isSuccess()) {
328 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
330 if (result
.getException() != null
) {
331 String complement
= "";
332 if (!nameCheckPassed
) {
333 complement
= " (while checking file existence in server)";
334 } else if (!localCopyPassed
) {
335 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
)
338 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
340 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
348 private void createNewOCFile(String newRemotePath
) {
349 // a new OCFile instance must be created for a new remote path
350 OCFile newFile
= new OCFile(newRemotePath
);
351 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
352 newFile
.setFileLength(mFile
.getFileLength());
353 newFile
.setMimetype(mFile
.getMimetype());
354 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
355 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
356 // newFile.setEtag(mFile.getEtag())
357 newFile
.setKeepInSync(mFile
.keepInSync());
358 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
359 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
360 newFile
.setStoragePath(mFile
.getStoragePath());
361 newFile
.setParentId(mFile
.getParentId());
366 public boolean isSuccess(int status
) {
367 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
370 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
373 File f
= new File(mFile
.getStoragePath());
374 mEntity
= new FileRequestEntity(f
, getMimeType());
375 synchronized (mDataTransferListeners
) {
376 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListeners(mDataTransferListeners
);
378 mPutMethod
.setRequestEntity(mEntity
);
379 status
= client
.executeMethod(mPutMethod
);
380 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
383 mPutMethod
.releaseConnection(); // let the connection available for
390 * Checks if remotePath does not exist in the server and returns it, or adds
391 * a suffix to it in order to avoid the server file is overwritten.
396 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
397 boolean check
= existsFile(wc
, remotePath
);
402 int pos
= remotePath
.lastIndexOf(".");
404 String extension
= "";
406 extension
= remotePath
.substring(pos
+ 1);
407 remotePath
= remotePath
.substring(0, pos
);
411 suffix
= " (" + count
+ ")";
413 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
416 check
= existsFile(wc
, remotePath
+ suffix
);
422 return remotePath
+ suffix
+ "." + extension
;
424 return remotePath
+ suffix
;
428 private boolean existsFile(WebdavClient client
, String remotePath
){
429 ExistenceCheckRemoteOperation existsOperation
= new ExistenceCheckRemoteOperation(remotePath
, mContext
, false
);
430 RemoteOperationResult result
= existsOperation
.execute(client
);
431 return result
.isSuccess();
434 public void cancel() {
435 synchronized (mCancellationRequested
) {
436 mCancellationRequested
.set(true
);
437 if (mPutMethod
!= null
)