1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
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 3 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 com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.files
.services
.FileUploader
;
37 import com
.owncloud
.android
.operations
.RemoteOperation
;
38 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
39 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
40 import com
.owncloud
.android
.utils
.FileStorageUtils
;
42 import eu
.alefzero
.webdav
.FileRequestEntity
;
43 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
44 import eu
.alefzero
.webdav
.WebdavClient
;
45 import eu
.alefzero
.webdav
.WebdavUtils
;
46 import android
.accounts
.Account
;
47 import android
.util
.Log
;
50 * Remote operation performing the upload of a file to an ownCloud server
52 * @author David A. Velasco
54 public class UploadFileOperation
extends RemoteOperation
{
56 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
58 private Account mAccount
;
60 private OCFile mOldFile
;
61 private String mRemotePath
= null
;
62 private boolean mIsInstant
= false
;
63 private boolean mRemoteFolderToBeCreated
= false
;
64 private boolean mForceOverwrite
= false
;
65 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
66 private boolean mWasRenamed
= false
;
67 PutMethod mPutMethod
= null
;
68 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
69 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
72 public UploadFileOperation( Account account
,
75 boolean forceOverwrite
,
78 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
80 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
81 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0 || !(new File(file
.getStoragePath()).exists())) {
82 throw new IllegalArgumentException("Illegal file in UploadFileOperation; storage path invalid or file not found: " + file
.getStoragePath());
87 mRemotePath
= file
.getRemotePath();
88 mIsInstant
= isInstant
;
89 mForceOverwrite
= forceOverwrite
;
90 mLocalBehaviour
= localBehaviour
;
94 public Account
getAccount() {
98 public OCFile
getFile() {
102 public OCFile
getOldFile() {
106 public String
getStoragePath() {
107 return mFile
.getStoragePath();
110 public String
getRemotePath() {
111 return mFile
.getRemotePath();
114 public String
getMimeType() {
115 return mFile
.getMimetype();
118 public boolean isInstant() {
122 public boolean isRemoteFolderToBeCreated() {
123 return mRemoteFolderToBeCreated
;
126 public void setRemoteFolderToBeCreated() {
127 mRemoteFolderToBeCreated
= true
;
130 public boolean getForceOverwrite() {
131 return mForceOverwrite
;
134 public boolean wasRenamed() {
138 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
139 return mDataTransferListeners
;
142 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
143 mDataTransferListeners
.add(listener
);
148 protected RemoteOperationResult
run(WebdavClient client
) {
149 RemoteOperationResult result
= null
;
150 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
151 String originalStoragePath
= mFile
.getStoragePath();
152 File temporalFile
= null
, originalFile
= new File(originalStoragePath
), expectedFile
= null
;
154 /// rename the file to upload, if necessary
155 if (!mForceOverwrite
) {
156 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
157 mWasRenamed
= !remotePath
.equals(mRemotePath
);
159 createNewOCFile(remotePath
);
162 nameCheckPassed
= true
;
164 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); /// not before getAvailableRemotePath() !!!
165 expectedFile
= new File(expectedPath
);
167 /// check location of local file; if not the expected, copy to a temporal file before upload (if COPY is the expected behaviour)
168 if (!originalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
170 File ocLocalFolder
= new File(FileStorageUtils
.getSavePath(mAccount
.name
));
171 if (ocLocalFolder
.getUsableSpace() < originalFile
.length()) {
172 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
173 return result
; // error condition when the file should be copied
176 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
177 mFile
.setStoragePath(temporalPath
);
178 temporalFile
= new File(temporalPath
);
179 if (!originalStoragePath
.equals(temporalPath
)) { // preventing weird but possible situation
180 InputStream
in = null
;
181 OutputStream out
= null
;
183 in = new FileInputStream(originalFile
);
184 out
= new FileOutputStream(temporalFile
);
185 byte[] buf
= new byte[1024];
187 while ((len
= in.read(buf
)) > 0){
188 out
.write(buf
, 0, len
);
192 if (in != null
) in.close();
193 } catch (Exception e
) {
194 Log
.d(TAG
, "Weird exception while closing input stream for " + originalStoragePath
+ " (ignoring)", e
);
197 if (out
!= null
) out
.close();
198 } catch (Exception e
) {
199 Log
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
205 localCopyPassed
= true
;
207 /// perform the upload
208 synchronized(mCancellationRequested
) {
209 if (mCancellationRequested
.get()) {
210 throw new OperationCancelledException();
212 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
215 int status
= uploadFile(client
);
218 /// move local temporal file or original file to its corresponding location in the ownCloud local folder
219 if (isSuccess(status
)) {
220 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
221 mFile
.setStoragePath(null
);
224 mFile
.setStoragePath(expectedPath
);
225 File fileToMove
= null
;
226 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY ; see where temporalFile was set
227 fileToMove
= temporalFile
;
228 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
229 fileToMove
= originalFile
;
231 expectedFile
= new File(mFile
.getStoragePath());
232 if (!expectedFile
.equals(fileToMove
) && !fileToMove
.renameTo(expectedFile
)) {
233 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_MOVED
);
239 result
= new RemoteOperationResult(isSuccess(status
), status
);
242 } catch (Exception e
) {
243 // TODO something cleaner with cancellations
244 if (mCancellationRequested
.get()) {
245 result
= new RemoteOperationResult(new OperationCancelledException());
247 result
= new RemoteOperationResult(e
);
252 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
253 temporalFile
.delete();
255 if (result
.isSuccess()) {
256 Log
.i(TAG
, "Upload of " + originalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
259 if (result
.getException() != null
) {
260 String complement
= "";
261 if (!nameCheckPassed
) {
262 complement
= " (while checking file existence in server)";
263 } else if (!localCopyPassed
) {
264 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
) + ")";
266 Log
.e(TAG
, "Upload of " + originalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
268 Log
.e(TAG
, "Upload of " + originalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
277 private void createNewOCFile(String newRemotePath
) {
278 // a new OCFile instance must be created for a new remote path
279 OCFile newFile
= new OCFile(newRemotePath
);
280 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
281 newFile
.setFileLength(mFile
.getFileLength());
282 newFile
.setMimetype(mFile
.getMimetype());
283 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
284 // newFile.setEtag(mFile.getEtag())
285 newFile
.setKeepInSync(mFile
.keepInSync());
286 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
287 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
288 newFile
.setStoragePath(mFile
.getStoragePath());
289 newFile
.setParentId(mFile
.getParentId());
295 public boolean isSuccess(int status
) {
296 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
300 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
303 File f
= new File(mFile
.getStoragePath());
304 FileRequestEntity entity
= new FileRequestEntity(f
, getMimeType());
305 entity
.addOnDatatransferProgressListeners(mDataTransferListeners
);
306 mPutMethod
.setRequestEntity(entity
);
307 status
= client
.executeMethod(mPutMethod
);
308 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
311 mPutMethod
.releaseConnection(); // let the connection available for other methods
317 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
318 * file is overwritten.
323 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
324 boolean check
= wc
.existsFile(remotePath
);
329 int pos
= remotePath
.lastIndexOf(".");
331 String extension
= "";
333 extension
= remotePath
.substring(pos
+1);
334 remotePath
= remotePath
.substring(0, pos
);
338 suffix
= " (" + count
+ ")";
340 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
342 check
= wc
.existsFile(remotePath
+ suffix
);
347 return remotePath
+ suffix
+ "." + extension
;
349 return remotePath
+ suffix
;
354 public void cancel() {
355 synchronized(mCancellationRequested
) {
356 mCancellationRequested
.set(true
);
357 if (mPutMethod
!= null
)