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
.utils
.FileStorageUtils
;
47 import com
.owncloud
.android
.utils
.Log_OC
;
49 import android
.accounts
.Account
;
53 * Remote operation performing the upload of a file to an ownCloud server
55 * @author David A. Velasco
57 public class UploadFileOperation
extends RemoteOperation
{
59 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
61 private Account mAccount
;
63 private OCFile mOldFile
;
64 private String mRemotePath
= null
;
65 private boolean mIsInstant
= false
;
66 private boolean mRemoteFolderToBeCreated
= false
;
67 private boolean mForceOverwrite
= false
;
68 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
69 private boolean mWasRenamed
= false
;
70 private String mOriginalFileName
= null
;
71 private String mOriginalStoragePath
= null
;
72 PutMethod mPutMethod
= null
;
73 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
74 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
76 protected RequestEntity mEntity
= null
;
79 public UploadFileOperation( Account account
,
82 boolean forceOverwrite
,
85 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
87 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
88 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0
89 || !(new File(file
.getStoragePath()).exists())) {
90 throw new IllegalArgumentException(
91 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
92 + file
.getStoragePath());
97 mRemotePath
= file
.getRemotePath();
98 mIsInstant
= isInstant
;
99 mForceOverwrite
= forceOverwrite
;
100 mLocalBehaviour
= localBehaviour
;
101 mOriginalStoragePath
= mFile
.getStoragePath();
102 mOriginalFileName
= mFile
.getFileName();
105 public Account
getAccount() {
109 public String
getFileName() {
110 return mOriginalFileName
;
113 public OCFile
getFile() {
117 public OCFile
getOldFile() {
121 public String
getOriginalStoragePath() {
122 return mOriginalStoragePath
;
125 public String
getStoragePath() {
126 return mFile
.getStoragePath();
129 public String
getRemotePath() {
130 return mFile
.getRemotePath();
133 public String
getMimeType() {
134 return mFile
.getMimetype();
137 public boolean isInstant() {
141 public boolean isRemoteFolderToBeCreated() {
142 return mRemoteFolderToBeCreated
;
145 public void setRemoteFolderToBeCreated() {
146 mRemoteFolderToBeCreated
= true
;
149 public boolean getForceOverwrite() {
150 return mForceOverwrite
;
153 public boolean wasRenamed() {
157 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
158 return mDataTransferListeners
;
161 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
162 synchronized (mDataTransferListeners
) {
163 mDataTransferListeners
.add(listener
);
165 if (mEntity
!= null
) {
166 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
170 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
171 synchronized (mDataTransferListeners
) {
172 mDataTransferListeners
.remove(listener
);
174 if (mEntity
!= null
) {
175 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
180 protected RemoteOperationResult
run(WebdavClient client
) {
181 RemoteOperationResult result
= null
;
182 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
183 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
185 // / rename the file to upload, if necessary
186 if (!mForceOverwrite
) {
187 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
188 mWasRenamed
= !remotePath
.equals(mRemotePath
);
190 createNewOCFile(remotePath
);
193 nameCheckPassed
= true
;
195 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
198 // getAvailableRemotePath()
200 expectedFile
= new File(expectedPath
);
202 // / check location of local file; if not the expected, copy to a
203 // temporal file before upload (if COPY is the expected behaviour)
204 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
206 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
207 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
208 return result
; // error condition when the file should be
212 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
213 mFile
.setStoragePath(temporalPath
);
214 temporalFile
= new File(temporalPath
);
215 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
220 InputStream
in = null
;
221 OutputStream out
= null
;
223 File temporalParent
= temporalFile
.getParentFile();
224 temporalParent
.mkdirs();
225 if (!temporalParent
.isDirectory()) {
226 throw new IOException("Unexpected error: parent directory could not be created");
228 temporalFile
.createNewFile();
229 if (!temporalFile
.isFile()) {
230 throw new IOException("Unexpected error: target file could not be created");
232 in = new FileInputStream(originalFile
);
233 out
= new FileOutputStream(temporalFile
);
234 byte[] buf
= new byte[1024];
236 while ((len
= in.read(buf
)) > 0) {
237 out
.write(buf
, 0, len
);
240 } catch (Exception e
) {
241 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
248 } catch (Exception e
) {
249 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
254 } catch (Exception e
) {
255 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
261 localCopyPassed
= true
;
263 // / perform the upload
264 synchronized (mCancellationRequested
) {
265 if (mCancellationRequested
.get()) {
266 throw new OperationCancelledException();
268 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
271 int status
= uploadFile(client
);
273 // / move local temporal file or original file to its corresponding
274 // location in the ownCloud local folder
275 if (isSuccess(status
)) {
276 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
277 mFile
.setStoragePath(null
);
280 mFile
.setStoragePath(expectedPath
);
281 File fileToMove
= null
;
282 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
283 // ; see where temporalFile was
285 fileToMove
= temporalFile
;
286 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
287 fileToMove
= originalFile
;
289 if (!expectedFile
.equals(fileToMove
)) {
290 File expectedFolder
= expectedFile
.getParentFile();
291 expectedFolder
.mkdirs();
292 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
293 mFile
.setStoragePath(null
); // forget the local file
294 // by now, treat this as a success; the file was
295 // uploaded; the user won't like that the local file
296 // is not linked, but this should be a very rare
298 // the best option could be show a warning message
301 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
308 result
= new RemoteOperationResult(isSuccess(status
), status
, (mPutMethod
!= null ? mPutMethod
.getResponseHeaders() : null
));
310 } catch (Exception e
) {
311 // TODO something cleaner with cancellations
312 if (mCancellationRequested
.get()) {
313 result
= new RemoteOperationResult(new OperationCancelledException());
315 result
= new RemoteOperationResult(e
);
319 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
320 temporalFile
.delete();
322 if (result
.isSuccess()) {
323 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
325 if (result
.getException() != null
) {
326 String complement
= "";
327 if (!nameCheckPassed
) {
328 complement
= " (while checking file existence in server)";
329 } else if (!localCopyPassed
) {
330 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
)
333 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
335 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
343 private void createNewOCFile(String newRemotePath
) {
344 // a new OCFile instance must be created for a new remote path
345 OCFile newFile
= new OCFile(newRemotePath
);
346 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
347 newFile
.setFileLength(mFile
.getFileLength());
348 newFile
.setMimetype(mFile
.getMimetype());
349 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
350 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
351 // newFile.setEtag(mFile.getEtag())
352 newFile
.setKeepInSync(mFile
.keepInSync());
353 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
354 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
355 newFile
.setStoragePath(mFile
.getStoragePath());
356 newFile
.setParentId(mFile
.getParentId());
361 public boolean isSuccess(int status
) {
362 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
365 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
368 File f
= new File(mFile
.getStoragePath());
369 mEntity
= new FileRequestEntity(f
, getMimeType());
370 synchronized (mDataTransferListeners
) {
371 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListeners(mDataTransferListeners
);
373 mPutMethod
.setRequestEntity(mEntity
);
374 status
= client
.executeMethod(mPutMethod
);
375 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
378 mPutMethod
.releaseConnection(); // let the connection available for
385 * Checks if remotePath does not exist in the server and returns it, or adds
386 * a suffix to it in order to avoid the server file is overwritten.
391 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
392 boolean check
= wc
.existsFile(remotePath
);
397 int pos
= remotePath
.lastIndexOf(".");
399 String extension
= "";
401 extension
= remotePath
.substring(pos
+ 1);
402 remotePath
= remotePath
.substring(0, pos
);
406 suffix
= " (" + count
+ ")";
408 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
410 check
= wc
.existsFile(remotePath
+ suffix
);
415 return remotePath
+ suffix
+ "." + extension
;
417 return remotePath
+ suffix
;
421 public void cancel() {
422 synchronized (mCancellationRequested
) {
423 mCancellationRequested
.set(true
);
424 if (mPutMethod
!= null
)