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 com
.owncloud
.android
.Log_OC
;
36 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.files
.services
.FileUploader
;
38 import com
.owncloud
.android
.operations
.RemoteOperation
;
39 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
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
;
47 import android
.accounts
.Account
;
48 import android
.util
.Log
;
51 * Remote operation performing the upload of a file to an ownCloud server
53 * @author David A. Velasco
55 public class UploadFileOperation
extends RemoteOperation
{
57 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
59 private Account mAccount
;
61 private OCFile mOldFile
;
62 private String mRemotePath
= null
;
63 private boolean mIsInstant
= false
;
64 private boolean mRemoteFolderToBeCreated
= false
;
65 private boolean mForceOverwrite
= false
;
66 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
67 private boolean mWasRenamed
= false
;
68 private String mOriginalFileName
= null
;
69 private String mOriginalStoragePath
= null
;
70 PutMethod mPutMethod
= null
;
71 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
72 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
75 public UploadFileOperation( Account account
,
78 boolean forceOverwrite
,
81 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
83 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
84 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0 || !(new File(file
.getStoragePath()).exists())) {
85 throw new IllegalArgumentException("Illegal file in UploadFileOperation; storage path invalid or file not found: " + file
.getStoragePath());
90 mRemotePath
= file
.getRemotePath();
91 mIsInstant
= isInstant
;
92 mForceOverwrite
= forceOverwrite
;
93 mLocalBehaviour
= localBehaviour
;
94 mOriginalStoragePath
= mFile
.getStoragePath();
95 mOriginalFileName
= mFile
.getFileName();
99 public Account
getAccount() {
103 public String
getFileName() {
104 return mOriginalFileName
;
107 public OCFile
getFile() {
111 public OCFile
getOldFile() {
115 public String
getOriginalStoragePath() {
116 return mOriginalStoragePath
;
119 public String
getStoragePath() {
120 return mFile
.getStoragePath();
123 public String
getRemotePath() {
124 return mFile
.getRemotePath();
127 public String
getMimeType() {
128 return mFile
.getMimetype();
131 public boolean isInstant() {
135 public boolean isRemoteFolderToBeCreated() {
136 return mRemoteFolderToBeCreated
;
139 public void setRemoteFolderToBeCreated() {
140 mRemoteFolderToBeCreated
= true
;
143 public boolean getForceOverwrite() {
144 return mForceOverwrite
;
147 public boolean wasRenamed() {
151 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
152 return mDataTransferListeners
;
155 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
156 mDataTransferListeners
.add(listener
);
160 protected RemoteOperationResult
run(WebdavClient client
) {
161 RemoteOperationResult result
= null
;
162 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
163 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
165 /// rename the file to upload, if necessary
166 if (!mForceOverwrite
) {
167 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
168 mWasRenamed
= !remotePath
.equals(mRemotePath
);
170 createNewOCFile(remotePath
);
173 nameCheckPassed
= true
;
175 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); /// not before getAvailableRemotePath() !!!
176 expectedFile
= new File(expectedPath
);
178 /// check location of local file; if not the expected, copy to a temporal file before upload (if COPY is the expected behaviour)
179 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
181 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
182 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
183 return result
; // error condition when the file should be copied
186 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
187 mFile
.setStoragePath(temporalPath
);
188 temporalFile
= new File(temporalPath
);
189 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing weird but possible situation
190 InputStream
in = null
;
191 OutputStream out
= null
;
193 File temporalParent
= temporalFile
.getParentFile();
194 temporalParent
.mkdirs();
195 if (!temporalParent
.isDirectory()) {
196 throw new IOException("Unexpected error: parent directory could not be created");
198 temporalFile
.createNewFile();
199 if (!temporalFile
.isFile()) {
200 throw new IOException("Unexpected error: target file could not be created");
202 in = new FileInputStream(originalFile
);
203 out
= new FileOutputStream(temporalFile
);
204 byte[] buf
= new byte[1024];
206 while ((len
= in.read(buf
)) > 0){
207 out
.write(buf
, 0, len
);
210 } catch (Exception e
) {
211 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
216 if (in != null
) in.close();
217 } catch (Exception e
) {
218 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
221 if (out
!= null
) out
.close();
222 } catch (Exception e
) {
223 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
229 localCopyPassed
= true
;
231 /// perform the upload
232 synchronized(mCancellationRequested
) {
233 if (mCancellationRequested
.get()) {
234 throw new OperationCancelledException();
236 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
239 int status
= uploadFile(client
);
242 /// move local temporal file or original file to its corresponding location in the ownCloud local folder
243 if (isSuccess(status
)) {
244 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
245 mFile
.setStoragePath(null
);
248 mFile
.setStoragePath(expectedPath
);
249 File fileToMove
= null
;
250 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY ; see where temporalFile was set
251 fileToMove
= temporalFile
;
252 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
253 fileToMove
= originalFile
;
255 if (!expectedFile
.equals(fileToMove
)) {
256 File expectedFolder
= expectedFile
.getParentFile();
257 expectedFolder
.mkdirs();
258 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
259 mFile
.setStoragePath(null
); // forget the local file
260 // by now, treat this as a success; the file was uploaded; the user won't like that the local file is not linked, but this should be a veeery rare fail;
261 // the best option could be show a warning message (but not a fail)
262 //result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
269 result
= new RemoteOperationResult(isSuccess(status
), status
);
272 } catch (Exception e
) {
273 // TODO something cleaner with cancellations
274 if (mCancellationRequested
.get()) {
275 result
= new RemoteOperationResult(new OperationCancelledException());
277 result
= new RemoteOperationResult(e
);
282 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
283 temporalFile
.delete();
285 if (result
.isSuccess()) {
286 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
289 if (result
.getException() != null
) {
290 String complement
= "";
291 if (!nameCheckPassed
) {
292 complement
= " (while checking file existence in server)";
293 } else if (!localCopyPassed
) {
294 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
) + ")";
296 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
298 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
307 private void createNewOCFile(String newRemotePath
) {
308 // a new OCFile instance must be created for a new remote path
309 OCFile newFile
= new OCFile(newRemotePath
);
310 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
311 newFile
.setFileLength(mFile
.getFileLength());
312 newFile
.setMimetype(mFile
.getMimetype());
313 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
314 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
315 // newFile.setEtag(mFile.getEtag())
316 newFile
.setKeepInSync(mFile
.keepInSync());
317 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
318 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
319 newFile
.setStoragePath(mFile
.getStoragePath());
320 newFile
.setParentId(mFile
.getParentId());
326 public boolean isSuccess(int status
) {
327 return ((status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
));
331 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
334 File f
= new File(mFile
.getStoragePath());
335 FileRequestEntity entity
= new FileRequestEntity(f
, getMimeType());
336 entity
.addOnDatatransferProgressListeners(mDataTransferListeners
);
337 mPutMethod
.setRequestEntity(entity
);
338 status
= client
.executeMethod(mPutMethod
);
339 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
342 mPutMethod
.releaseConnection(); // let the connection available for other methods
348 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
349 * file is overwritten.
354 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
355 boolean check
= wc
.existsFile(remotePath
);
360 int pos
= remotePath
.lastIndexOf(".");
362 String extension
= "";
364 extension
= remotePath
.substring(pos
+1);
365 remotePath
= remotePath
.substring(0, pos
);
369 suffix
= " (" + count
+ ")";
371 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
373 check
= wc
.existsFile(remotePath
+ suffix
);
378 return remotePath
+ suffix
+ "." + extension
;
380 return remotePath
+ suffix
;
385 public void cancel() {
386 synchronized(mCancellationRequested
) {
387 mCancellationRequested
.set(true
);
388 if (mPutMethod
!= null
)