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
.commons
.httpclient
.methods
.RequestEntity
;
34 import org
.apache
.http
.HttpStatus
;
36 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.files
.services
.FileUploader
;
38 import com
.owncloud
.android
.network
.ProgressiveDataTransferer
;
39 import com
.owncloud
.android
.operations
.RemoteOperation
;
40 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
41 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
42 import com
.owncloud
.android
.utils
.FileStorageUtils
;
44 import eu
.alefzero
.webdav
.FileRequestEntity
;
45 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
46 import eu
.alefzero
.webdav
.WebdavClient
;
47 import eu
.alefzero
.webdav
.WebdavUtils
;
48 import android
.accounts
.Account
;
49 import android
.util
.Log
;
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 || !(new File(file
.getStoragePath()).exists())) {
88 throw new IllegalArgumentException("Illegal file in UploadFileOperation; storage path invalid or file not found: " + file
.getStoragePath());
93 mRemotePath
= file
.getRemotePath();
94 mIsInstant
= isInstant
;
95 mForceOverwrite
= forceOverwrite
;
96 mLocalBehaviour
= localBehaviour
;
97 mOriginalStoragePath
= mFile
.getStoragePath();
98 mOriginalFileName
= mFile
.getFileName();
102 public Account
getAccount() {
106 public String
getFileName() {
107 return mOriginalFileName
;
110 public OCFile
getFile() {
114 public OCFile
getOldFile() {
118 public String
getOriginalStoragePath() {
119 return mOriginalStoragePath
;
122 public String
getStoragePath() {
123 return mFile
.getStoragePath();
126 public String
getRemotePath() {
127 return mFile
.getRemotePath();
130 public String
getMimeType() {
131 return mFile
.getMimetype();
134 public boolean isInstant() {
138 public boolean isRemoteFolderToBeCreated() {
139 return mRemoteFolderToBeCreated
;
142 public void setRemoteFolderToBeCreated() {
143 mRemoteFolderToBeCreated
= true
;
146 public boolean getForceOverwrite() {
147 return mForceOverwrite
;
150 public boolean wasRenamed() {
154 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
155 return mDataTransferListeners
;
158 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
159 synchronized (mDataTransferListeners
) {
160 mDataTransferListeners
.add(listener
);
162 if (mEntity
!= null
) {
163 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
167 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
168 synchronized (mDataTransferListeners
) {
169 mDataTransferListeners
.remove(listener
);
171 if (mEntity
!= null
) {
172 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
177 protected RemoteOperationResult
run(WebdavClient client
) {
178 RemoteOperationResult result
= null
;
179 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
180 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
182 /// rename the file to upload, if necessary
183 if (!mForceOverwrite
) {
184 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
185 mWasRenamed
= !remotePath
.equals(mRemotePath
);
187 createNewOCFile(remotePath
);
190 nameCheckPassed
= true
;
192 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); /// not before getAvailableRemotePath() !!!
193 expectedFile
= new File(expectedPath
);
195 /// check location of local file; if not the expected, copy to a temporal file before upload (if COPY is the expected behaviour)
196 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
198 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
199 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
200 return result
; // error condition when the file should be copied
203 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
204 mFile
.setStoragePath(temporalPath
);
205 temporalFile
= new File(temporalPath
);
206 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing weird but possible situation
207 InputStream
in = null
;
208 OutputStream out
= null
;
210 File temporalParent
= temporalFile
.getParentFile();
211 temporalParent
.mkdirs();
212 if (!temporalParent
.isDirectory()) {
213 throw new IOException("Unexpected error: parent directory could not be created");
215 temporalFile
.createNewFile();
216 if (!temporalFile
.isFile()) {
217 throw new IOException("Unexpected error: target file could not be created");
219 in = new FileInputStream(originalFile
);
220 out
= new FileOutputStream(temporalFile
);
221 byte[] buf
= new byte[1024];
223 while ((len
= in.read(buf
)) > 0){
224 out
.write(buf
, 0, len
);
227 } catch (Exception e
) {
228 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
233 if (in != null
) in.close();
234 } catch (Exception e
) {
235 Log
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
238 if (out
!= null
) out
.close();
239 } catch (Exception e
) {
240 Log
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
246 localCopyPassed
= true
;
248 /// perform the upload
249 synchronized(mCancellationRequested
) {
250 if (mCancellationRequested
.get()) {
251 throw new OperationCancelledException();
253 mPutMethod
= new PutMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mFile
.getRemotePath()));
256 int status
= uploadFile(client
);
259 /// move local temporal file or original file to its corresponding location in the ownCloud local folder
260 if (isSuccess(status
)) {
261 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
262 mFile
.setStoragePath(null
);
265 mFile
.setStoragePath(expectedPath
);
266 File fileToMove
= null
;
267 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY ; see where temporalFile was set
268 fileToMove
= temporalFile
;
269 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
270 fileToMove
= originalFile
;
272 if (!expectedFile
.equals(fileToMove
)) {
273 File expectedFolder
= expectedFile
.getParentFile();
274 expectedFolder
.mkdirs();
275 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
276 mFile
.setStoragePath(null
); // forget the local file
277 // 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;
278 // the best option could be show a warning message (but not a fail)
279 //result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
286 result
= new RemoteOperationResult(isSuccess(status
), status
);
289 } catch (Exception e
) {
290 // TODO something cleaner with cancellations
291 if (mCancellationRequested
.get()) {
292 result
= new RemoteOperationResult(new OperationCancelledException());
294 result
= new RemoteOperationResult(e
);
299 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
300 temporalFile
.delete();
302 if (result
.isSuccess()) {
303 Log
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
306 if (result
.getException() != null
) {
307 String complement
= "";
308 if (!nameCheckPassed
) {
309 complement
= " (while checking file existence in server)";
310 } else if (!localCopyPassed
) {
311 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
) + ")";
313 Log
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
315 Log
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
324 private void createNewOCFile(String newRemotePath
) {
325 // a new OCFile instance must be created for a new remote path
326 OCFile newFile
= new OCFile(newRemotePath
);
327 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
328 newFile
.setFileLength(mFile
.getFileLength());
329 newFile
.setMimetype(mFile
.getMimetype());
330 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
331 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
332 // newFile.setEtag(mFile.getEtag())
333 newFile
.setKeepInSync(mFile
.keepInSync());
334 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
335 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
336 newFile
.setStoragePath(mFile
.getStoragePath());
337 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
));
348 protected int uploadFile(WebdavClient client
) throws HttpException
, IOException
, OperationCancelledException
{
351 File f
= new File(mFile
.getStoragePath());
352 mEntity
= new FileRequestEntity(f
, getMimeType());
353 synchronized (mDataTransferListeners
) {
354 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListeners(mDataTransferListeners
);
356 mPutMethod
.setRequestEntity(mEntity
);
357 status
= client
.executeMethod(mPutMethod
);
358 client
.exhaustResponse(mPutMethod
.getResponseBodyAsStream());
361 mPutMethod
.releaseConnection(); // let the connection available for other methods
367 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
368 * file is overwritten.
373 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) throws Exception
{
374 boolean check
= wc
.existsFile(remotePath
);
379 int pos
= remotePath
.lastIndexOf(".");
381 String extension
= "";
383 extension
= remotePath
.substring(pos
+1);
384 remotePath
= remotePath
.substring(0, pos
);
388 suffix
= " (" + count
+ ")";
390 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
392 check
= wc
.existsFile(remotePath
+ suffix
);
397 return remotePath
+ suffix
+ "." + extension
;
399 return remotePath
+ suffix
;
404 public void cancel() {
405 synchronized(mCancellationRequested
) {
406 mCancellationRequested
.set(true
);
407 if (mPutMethod
!= null
)