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
.Log_OC
;
36 import android
.accounts
.Account
;
38 import com
.owncloud
.android
.datamodel
.OCFile
;
39 import com
.owncloud
.android
.files
.services
.FileUploader
;
40 import com
.owncloud
.android
.network
.ProgressiveDataTransferer
;
41 import com
.owncloud
.android
.operations
.RemoteOperation
;
42 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
43 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
44 import com
.owncloud
.android
.utils
.FileStorageUtils
;
46 import eu
.alefzero
.webdav
.FileRequestEntity
;
47 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
48 import eu
.alefzero
.webdav
.WebdavClient
;
49 import eu
.alefzero
.webdav
.WebdavUtils
;
52 * Remote operation performing the upload of a file to an ownCloud server
54 * @author David A. Velasco
56 public class UploadFileOperation
extends RemoteOperation
{
58 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
60 private Account mAccount
;
62 private OCFile mOldFile
;
63 private String mRemotePath
= null
;
64 private boolean mIsInstant
= false
;
65 private boolean mRemoteFolderToBeCreated
= false
;
66 private boolean mForceOverwrite
= false
;
67 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
68 private boolean mWasRenamed
= false
;
69 private String mOriginalFileName
= null
;
70 private String mOriginalStoragePath
= null
;
71 PutMethod mPutMethod
= null
;
72 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
73 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
75 protected RequestEntity mEntity
= null
;
78 public UploadFileOperation( Account account
,
81 boolean forceOverwrite
,
84 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
86 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
87 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0
88 || !(new File(file
.getStoragePath()).exists())) {
89 throw new IllegalArgumentException(
90 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
91 + file
.getStoragePath());
96 mRemotePath
= file
.getRemotePath();
97 mIsInstant
= isInstant
;
98 mForceOverwrite
= forceOverwrite
;
99 mLocalBehaviour
= localBehaviour
;
100 mOriginalStoragePath
= mFile
.getStoragePath();
101 mOriginalFileName
= mFile
.getFileName();
104 public Account
getAccount() {
108 public String
getFileName() {
109 return mOriginalFileName
;
112 public OCFile
getFile() {
116 public OCFile
getOldFile() {
120 public String
getOriginalStoragePath() {
121 return mOriginalStoragePath
;
124 public String
getStoragePath() {
125 return mFile
.getStoragePath();
128 public String
getRemotePath() {
129 return mFile
.getRemotePath();
132 public String
getMimeType() {
133 return mFile
.getMimetype();
136 public boolean isInstant() {
140 public boolean isRemoteFolderToBeCreated() {
141 return mRemoteFolderToBeCreated
;
144 public void setRemoteFolderToBeCreated() {
145 mRemoteFolderToBeCreated
= true
;
148 public boolean getForceOverwrite() {
149 return mForceOverwrite
;
152 public boolean wasRenamed() {
156 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
157 return mDataTransferListeners
;
160 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
161 synchronized (mDataTransferListeners
) {
162 mDataTransferListeners
.add(listener
);
164 if (mEntity
!= null
) {
165 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
169 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
170 synchronized (mDataTransferListeners
) {
171 mDataTransferListeners
.remove(listener
);
173 if (mEntity
!= null
) {
174 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
179 protected RemoteOperationResult
run(WebdavClient client
) {
180 RemoteOperationResult result
= null
;
181 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
182 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
184 // / rename the file to upload, if necessary
185 if (!mForceOverwrite
) {
186 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
187 mWasRenamed
= !remotePath
.equals(mRemotePath
);
189 createNewOCFile(remotePath
);
192 nameCheckPassed
= true
;
194 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
197 // getAvailableRemotePath()
199 expectedFile
= new File(expectedPath
);
201 // / check location of local file; if not the expected, copy to a
202 // temporal file before upload (if COPY is the expected behaviour)
203 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
205 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
206 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
207 return result
; // error condition when the file should be
211 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
212 mFile
.setStoragePath(temporalPath
);
213 temporalFile
= new File(temporalPath
);
214 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
219 InputStream
in = null
;
220 OutputStream out
= null
;
222 File temporalParent
= temporalFile
.getParentFile();
223 temporalParent
.mkdirs();
224 if (!temporalParent
.isDirectory()) {
225 throw new IOException("Unexpected error: parent directory could not be created");
227 temporalFile
.createNewFile();
228 if (!temporalFile
.isFile()) {
229 throw new IOException("Unexpected error: target file could not be created");
231 in = new FileInputStream(originalFile
);
232 out
= new FileOutputStream(temporalFile
);
233 byte[] buf
= new byte[1024];
235 while ((len
= in.read(buf
)) > 0) {
236 out
.write(buf
, 0, len
);
239 } catch (Exception e
) {
240 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
247 } catch (Exception e
) {
248 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
253 } catch (Exception e
) {
254 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
260 localCopyPassed
= true
;
262 // / perform the upload
263 synchronized (mCancellationRequested
) {
264 if (mCancellationRequested
.get()) {
265 throw new OperationCancelledException();
267 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
270 int status
= uploadFile(client
);
272 // / move local temporal file or original file to its corresponding
273 // location in the ownCloud local folder
274 if (isSuccess(status
)) {
275 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
276 mFile
.setStoragePath(null
);
279 mFile
.setStoragePath(expectedPath
);
280 File fileToMove
= null
;
281 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
282 // ; see where temporalFile was
284 fileToMove
= temporalFile
;
285 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
286 fileToMove
= originalFile
;
288 if (!expectedFile
.equals(fileToMove
)) {
289 File expectedFolder
= expectedFile
.getParentFile();
290 expectedFolder
.mkdirs();
291 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
292 mFile
.setStoragePath(null
); // forget the local file
293 // by now, treat this as a success; the file was
294 // uploaded; the user won't like that the local file
295 // is not linked, but this should be a very rare
297 // the best option could be show a warning message
300 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
307 result
= new RemoteOperationResult(isSuccess(status
), status
, (mPutMethod
!= null ? mPutMethod
.getResponseHeaders() : null
));
309 } catch (Exception e
) {
310 // TODO something cleaner with cancellations
311 if (mCancellationRequested
.get()) {
312 result
= new RemoteOperationResult(new OperationCancelledException());
314 result
= new RemoteOperationResult(e
);
318 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
319 temporalFile
.delete();
321 if (result
.isSuccess()) {
322 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
324 if (result
.getException() != null
) {
325 String complement
= "";
326 if (!nameCheckPassed
) {
327 complement
= " (while checking file existence in server)";
328 } else if (!localCopyPassed
) {
329 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
)
332 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
334 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
342 private void createNewOCFile(String newRemotePath
) {
343 // a new OCFile instance must be created for a new remote path
344 OCFile newFile
= new OCFile(newRemotePath
);
345 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
346 newFile
.setFileLength(mFile
.getFileLength());
347 newFile
.setMimetype(mFile
.getMimetype());
348 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
349 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
350 // newFile.setEtag(mFile.getEtag())
351 newFile
.setKeepInSync(mFile
.keepInSync());
352 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
353 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
354 newFile
.setStoragePath(mFile
.getStoragePath());
355 newFile
.setParentId(mFile
.getParentId());
360 public boolean isSuccess(int status
) {
361 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
364 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
367 File f
= new File(mFile
.getStoragePath());
368 mEntity
= new FileRequestEntity(f
, getMimeType());
369 synchronized (mDataTransferListeners
) {
370 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListeners(mDataTransferListeners
);
372 mPutMethod
.setRequestEntity(mEntity
);
373 status
= client
.executeMethod(mPutMethod
);
374 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
377 mPutMethod
.releaseConnection(); // let the connection available for
384 * Checks if remotePath does not exist in the server and returns it, or adds
385 * a suffix to it in order to avoid the server file is overwritten.
390 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
391 boolean check
= wc
.existsFile(remotePath
);
396 int pos
= remotePath
.lastIndexOf(".");
398 String extension
= "";
400 extension
= remotePath
.substring(pos
+ 1);
401 remotePath
= remotePath
.substring(0, pos
);
405 suffix
= " (" + count
+ ")";
407 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
409 check
= wc
.existsFile(remotePath
+ suffix
);
414 return remotePath
+ suffix
+ "." + extension
;
416 return remotePath
+ suffix
;
420 public void cancel() {
421 synchronized (mCancellationRequested
) {
422 mCancellationRequested
.set(true
);
423 if (mPutMethod
!= null
)