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 as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.operations
;
22 import java
.io
.FileInputStream
;
23 import java
.io
.FileOutputStream
;
24 import java
.io
.IOException
;
25 import java
.io
.InputStream
;
26 import java
.io
.OutputStream
;
27 import java
.util
.HashSet
;
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
.http
.HttpStatus
;
35 import android
.accounts
.Account
;
36 import android
.util
.Log
;
38 import com
.owncloud
.android
.datamodel
.OCFile
;
39 import com
.owncloud
.android
.files
.services
.FileUploader
;
40 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
41 import com
.owncloud
.android
.utils
.FileStorageUtils
;
43 import eu
.alefzero
.webdav
.FileRequestEntity
;
44 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
45 import eu
.alefzero
.webdav
.WebdavClient
;
46 import eu
.alefzero
.webdav
.WebdavUtils
;
49 * Remote operation performing the upload of a file to an ownCloud server
51 * @author David A. Velasco
53 public class UploadFileOperation
extends RemoteOperation
{
55 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
57 private Account mAccount
;
59 private OCFile mOldFile
;
60 private String mRemotePath
= null
;
61 private boolean mIsInstant
= false
;
62 private boolean mRemoteFolderToBeCreated
= false
;
63 private boolean mForceOverwrite
= false
;
64 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
65 private boolean mWasRenamed
= false
;
66 private String mOriginalFileName
= null
;
67 private String mOriginalStoragePath
= null
;
68 PutMethod mPutMethod
= null
;
69 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
70 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
72 public UploadFileOperation(Account account
, OCFile file
, boolean isInstant
, boolean forceOverwrite
,
75 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
77 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
78 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0
79 || !(new File(file
.getStoragePath()).exists())) {
80 throw new IllegalArgumentException(
81 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
82 + file
.getStoragePath());
87 mRemotePath
= file
.getRemotePath();
88 mIsInstant
= isInstant
;
89 mForceOverwrite
= forceOverwrite
;
90 mLocalBehaviour
= localBehaviour
;
91 mOriginalStoragePath
= mFile
.getStoragePath();
92 mOriginalFileName
= mFile
.getFileName();
95 public Account
getAccount() {
99 public String
getFileName() {
100 return mOriginalFileName
;
103 public OCFile
getFile() {
107 public OCFile
getOldFile() {
111 public String
getOriginalStoragePath() {
112 return mOriginalStoragePath
;
115 public String
getStoragePath() {
116 return mFile
.getStoragePath();
119 public String
getRemotePath() {
120 return mFile
.getRemotePath();
123 public String
getMimeType() {
124 return mFile
.getMimetype();
127 public boolean isInstant() {
131 public boolean isRemoteFolderToBeCreated() {
132 return mRemoteFolderToBeCreated
;
135 public void setRemoteFolderToBeCreated() {
136 mRemoteFolderToBeCreated
= true
;
139 public boolean getForceOverwrite() {
140 return mForceOverwrite
;
143 public boolean wasRenamed() {
147 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
148 return mDataTransferListeners
;
151 public void addDatatransferProgressListener(OnDatatransferProgressListener listener
) {
152 mDataTransferListeners
.add(listener
);
156 protected RemoteOperationResult
run(WebdavClient client
) {
157 RemoteOperationResult result
= null
;
158 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
159 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
161 // / rename the file to upload, if necessary
162 if (!mForceOverwrite
) {
163 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
164 mWasRenamed
= !remotePath
.equals(mRemotePath
);
166 createNewOCFile(remotePath
);
169 nameCheckPassed
= true
;
171 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
174 // getAvailableRemotePath()
176 expectedFile
= new File(expectedPath
);
178 // / check location of local file; if not the expected, copy to a
179 // temporal file before upload (if COPY is the expected behaviour)
180 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
182 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
183 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
184 return result
; // error condition when the file should be
188 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
189 mFile
.setStoragePath(temporalPath
);
190 temporalFile
= new File(temporalPath
);
191 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
196 InputStream
in = null
;
197 OutputStream out
= null
;
199 File temporalParent
= temporalFile
.getParentFile();
200 temporalParent
.mkdirs();
201 if (!temporalParent
.isDirectory()) {
202 throw new IOException("Unexpected error: parent directory could not be created");
204 temporalFile
.createNewFile();
205 if (!temporalFile
.isFile()) {
206 throw new IOException("Unexpected error: target file could not be created");
208 in = new FileInputStream(originalFile
);
209 out
= new FileOutputStream(temporalFile
);
210 byte[] buf
= new byte[1024];
212 while ((len
= in.read(buf
)) > 0) {
213 out
.write(buf
, 0, len
);
216 } catch (Exception e
) {
217 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
224 } catch (Exception e
) {
225 Log
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
231 } catch (Exception e
) {
232 Log
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
239 localCopyPassed
= true
;
241 // / perform the upload
242 synchronized (mCancellationRequested
) {
243 if (mCancellationRequested
.get()) {
244 throw new OperationCancelledException();
246 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
249 int status
= uploadFile(client
);
251 // / move local temporal file or original file to its corresponding
252 // location in the ownCloud local folder
253 if (isSuccess(status
)) {
254 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
255 mFile
.setStoragePath(null
);
258 mFile
.setStoragePath(expectedPath
);
259 File fileToMove
= null
;
260 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
261 // ; see where temporalFile was
263 fileToMove
= temporalFile
;
264 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
265 fileToMove
= originalFile
;
267 if (!expectedFile
.equals(fileToMove
)) {
268 File expectedFolder
= expectedFile
.getParentFile();
269 expectedFolder
.mkdirs();
270 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
271 mFile
.setStoragePath(null
); // forget the local file
272 // by now, treat this as a success; the file was
273 // uploaded; the user won't like that the local file
274 // is not linked, but this should be a very rare
276 // the best option could be show a warning message
279 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
286 result
= new RemoteOperationResult(isSuccess(status
), status
);
288 } catch (Exception e
) {
289 // TODO something cleaner with cancellations
290 if (mCancellationRequested
.get()) {
291 result
= new RemoteOperationResult(new OperationCancelledException());
293 result
= new RemoteOperationResult(e
);
297 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
298 temporalFile
.delete();
300 if (result
.isSuccess()) {
301 Log
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
304 if (result
.getException() != null
) {
305 String complement
= "";
306 if (!nameCheckPassed
) {
307 complement
= " (while checking file existence in server)";
308 } else if (!localCopyPassed
) {
309 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
)
313 "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage()
314 + complement
, result
.getException());
317 "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
325 private void createNewOCFile(String newRemotePath
) {
326 // a new OCFile instance must be created for a new remote path
327 OCFile newFile
= new OCFile(newRemotePath
);
328 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
329 newFile
.setFileLength(mFile
.getFileLength());
330 newFile
.setMimetype(mFile
.getMimetype());
331 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
332 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
333 // newFile.setEtag(mFile.getEtag())
334 newFile
.setKeepInSync(mFile
.keepInSync());
335 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
336 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
337 newFile
.setStoragePath(mFile
.getStoragePath());
338 newFile
.setParentId(mFile
.getParentId());
343 public boolean isSuccess(int status
) {
344 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
347 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
350 File f
= new File(mFile
.getStoragePath());
351 FileRequestEntity entity
= new FileRequestEntity(f
, getMimeType());
352 entity
.addOnDatatransferProgressListeners(mDataTransferListeners
);
353 mPutMethod
.setRequestEntity(entity
);
354 status
= client
.executeMethod(mPutMethod
);
355 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
358 mPutMethod
.releaseConnection(); // let the connection available for
365 * Checks if remotePath does not exist in the server and returns it, or adds
366 * a suffix to it in order to avoid the server file is overwritten.
371 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
372 boolean check
= wc
.existsFile(remotePath
);
377 int pos
= remotePath
.lastIndexOf(".");
379 String extension
= "";
381 extension
= remotePath
.substring(pos
+ 1);
382 remotePath
= remotePath
.substring(0, pos
);
386 suffix
= " (" + count
+ ")";
388 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
390 check
= wc
.existsFile(remotePath
+ suffix
);
395 return remotePath
+ suffix
+ "." + extension
;
397 return remotePath
+ suffix
;
401 public void cancel() {
402 synchronized (mCancellationRequested
) {
403 mCancellationRequested
.set(true
);
404 if (mPutMethod
!= null
)