2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 package com
.owncloud
.android
.operations
;
24 import java
.io
.FileInputStream
;
25 import java
.io
.FileOutputStream
;
26 import java
.io
.IOException
;
27 import java
.io
.InputStream
;
28 import java
.io
.OutputStream
;
29 import java
.util
.HashSet
;
30 import java
.util
.Iterator
;
32 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
34 import org
.apache
.commons
.httpclient
.methods
.PutMethod
;
35 import org
.apache
.commons
.httpclient
.methods
.RequestEntity
;
37 import android
.accounts
.Account
;
38 import android
.content
.Context
;
39 import android
.net
.Uri
;
41 import com
.owncloud
.android
.MainApp
;
42 import com
.owncloud
.android
.datamodel
.OCFile
;
43 import com
.owncloud
.android
.files
.services
.FileUploader
;
44 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
45 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
46 import com
.owncloud
.android
.lib
.common
.network
.ProgressiveDataTransferer
;
47 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
;
48 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
49 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
50 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
51 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
52 import com
.owncloud
.android
.lib
.resources
.files
.ChunkedUploadRemoteFileOperation
;
53 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
54 import com
.owncloud
.android
.lib
.resources
.files
.UploadRemoteFileOperation
;
55 import com
.owncloud
.android
.utils
.FileStorageUtils
;
56 import com
.owncloud
.android
.utils
.UriUtils
;
60 * Remote operation performing the upload of a file to an ownCloud server
62 public class UploadFileOperation
extends RemoteOperation
{
64 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
66 private Account mAccount
;
68 private OCFile mOldFile
;
69 private String mRemotePath
= null
;
70 private boolean mChunked
= false
;
71 private boolean mIsInstant
= false
;
72 private boolean mRemoteFolderToBeCreated
= false
;
73 private boolean mForceOverwrite
= false
;
74 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
75 private boolean mWasRenamed
= false
;
76 private String mOriginalFileName
= null
;
77 private String mOriginalStoragePath
= null
;
78 PutMethod mPutMethod
= null
;
79 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
80 private AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
81 private Context mContext
;
83 private UploadRemoteFileOperation mUploadOperation
;
85 protected RequestEntity mEntity
= null
;
88 public UploadFileOperation( Account account
,
92 boolean forceOverwrite
,
96 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " +
99 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
100 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0) {
101 throw new IllegalArgumentException(
102 "Illegal file in UploadFileOperation; storage path invalid: "
103 + file
.getStoragePath());
108 mRemotePath
= file
.getRemotePath();
110 mIsInstant
= isInstant
;
111 mForceOverwrite
= forceOverwrite
;
112 mLocalBehaviour
= localBehaviour
;
113 mOriginalStoragePath
= mFile
.getStoragePath();
114 mOriginalFileName
= mFile
.getFileName();
118 public Account
getAccount() {
122 public String
getFileName() {
123 return mOriginalFileName
;
126 public OCFile
getFile() {
130 public OCFile
getOldFile() {
134 public String
getOriginalStoragePath() {
135 return mOriginalStoragePath
;
138 public String
getStoragePath() {
139 return mFile
.getStoragePath();
142 public String
getRemotePath() {
143 return mFile
.getRemotePath();
146 public String
getMimeType() {
147 return mFile
.getMimetype();
150 public boolean isInstant() {
154 public boolean isRemoteFolderToBeCreated() {
155 return mRemoteFolderToBeCreated
;
158 public void setRemoteFolderToBeCreated() {
159 mRemoteFolderToBeCreated
= true
;
162 public boolean getForceOverwrite() {
163 return mForceOverwrite
;
166 public boolean wasRenamed() {
170 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
171 return mDataTransferListeners
;
174 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
175 synchronized (mDataTransferListeners
) {
176 mDataTransferListeners
.add(listener
);
178 if (mEntity
!= null
) {
179 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
183 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
184 synchronized (mDataTransferListeners
) {
185 mDataTransferListeners
.remove(listener
);
187 if (mEntity
!= null
) {
188 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
193 protected RemoteOperationResult
run(OwnCloudClient client
) {
194 RemoteOperationResult result
= null
;
195 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
196 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
198 // / rename the file to upload, if necessary
199 if (!mForceOverwrite
) {
200 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
201 mWasRenamed
= !remotePath
.equals(mRemotePath
);
203 createNewOCFile(remotePath
);
206 nameCheckPassed
= true
;
208 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
211 // getAvailableRemotePath()
213 expectedFile
= new File(expectedPath
);
215 // check location of local file; if not the expected, copy to a
216 // temporal file before upload (if COPY is the expected behaviour)
217 if (!mOriginalStoragePath
.equals(expectedPath
) &&
218 mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
220 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
221 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
222 return result
; // error condition when the file should be
227 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) +
228 mFile
.getRemotePath();
229 mFile
.setStoragePath(temporalPath
);
230 temporalFile
= new File(temporalPath
);
232 File temporalParent
= temporalFile
.getParentFile();
233 temporalParent
.mkdirs();
234 if (!temporalParent
.isDirectory()) {
235 throw new IOException("Unexpected error: parent directory could not be created");
237 temporalFile
.createNewFile();
238 if (!temporalFile
.isFile()) {
239 throw new IOException("Unexpected error: target file could not be created");
242 InputStream
in = null
;
243 OutputStream out
= null
;
247 // In case document provider schema as 'content://'
248 if (mOriginalStoragePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
250 Uri uri
= Uri
.parse(mOriginalStoragePath
);
252 in = MainApp
.getAppContext().getContentResolver().openInputStream(uri
);
253 out
= new FileOutputStream(temporalFile
);
256 byte[] data
= new byte[16384];
258 while (!mCancellationRequested
.get() &&
259 (nRead
= in.read(data
, 0, data
.length
)) != -1) {
260 out
.write(data
, 0, nRead
);
265 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
271 in = new FileInputStream(originalFile
);
272 out
= new FileOutputStream(temporalFile
);
273 byte[] buf
= new byte[1024];
275 while (!mCancellationRequested
.get() && (len
= in.read(buf
)) > 0) {
276 out
.write(buf
, 0, len
);
281 if (mCancellationRequested
.get()) {
282 result
= new RemoteOperationResult(new OperationCancelledException());
286 } catch (Exception e
) {
287 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
294 } catch (Exception e
) {
295 Log_OC
.d(TAG
, "Weird exception while closing input stream for " +
296 mOriginalStoragePath
+ " (ignoring)", e
);
301 } catch (Exception e
) {
302 Log_OC
.d(TAG
, "Weird exception while closing output stream for " +
303 expectedPath
+ " (ignoring)", e
);
308 localCopyPassed
= (result
== null
);
310 /// perform the upload
312 (new File(mFile
.getStoragePath())).length() >
313 ChunkedUploadRemoteFileOperation
.CHUNK_SIZE
) {
314 mUploadOperation
= new ChunkedUploadRemoteFileOperation(mFile
.getStoragePath(),
315 mFile
.getRemotePath(), mFile
.getMimetype());
317 mUploadOperation
= new UploadRemoteFileOperation(mFile
.getStoragePath(),
318 mFile
.getRemotePath(), mFile
.getMimetype());
320 Iterator
<OnDatatransferProgressListener
> listener
= mDataTransferListeners
.iterator();
321 while (listener
.hasNext()) {
322 mUploadOperation
.addDatatransferProgressListener(listener
.next());
324 if (mCancellationRequested
.get()) {
325 throw new OperationCancelledException();
328 result
= mUploadOperation
.execute(client
);
330 /// move local temporal file or original file to its corresponding
331 // location in the ownCloud local folder
332 if (result
.isSuccess()) {
333 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
334 mFile
.setStoragePath(null
);
337 mFile
.setStoragePath(expectedPath
);
338 File fileToMove
= null
;
339 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
340 // ; see where temporalFile was
342 fileToMove
= temporalFile
;
343 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
344 fileToMove
= originalFile
;
346 if (!expectedFile
.equals(fileToMove
)) {
347 File expectedFolder
= expectedFile
.getParentFile();
348 expectedFolder
.mkdirs();
349 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
350 mFile
.setStoragePath(null
); // forget the local file
351 // by now, treat this as a success; the file was
352 // uploaded; the user won't like that the local file
353 // is not linked, but this should be a very rare
355 // the best option could be show a warning message
358 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
365 } catch (Exception e
) {
366 result
= new RemoteOperationResult(e
);
369 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
370 temporalFile
.delete();
372 if (result
.isSuccess()) {
373 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " +
374 result
.getLogMessage());
376 if (result
.getException() != null
) {
377 String complement
= "";
378 if (!nameCheckPassed
) {
379 complement
= " (while checking file existence in server)";
380 } else if (!localCopyPassed
) {
381 complement
= " (while copying local file to " +
382 FileStorageUtils
.getSavePath(mAccount
.name
)
385 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+
386 ": " + result
.getLogMessage() + complement
, result
.getException());
388 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+
389 ": " + result
.getLogMessage());
397 private void createNewOCFile(String newRemotePath
) {
398 // a new OCFile instance must be created for a new remote path
399 OCFile newFile
= new OCFile(newRemotePath
);
400 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
401 newFile
.setFileLength(mFile
.getFileLength());
402 newFile
.setMimetype(mFile
.getMimetype());
403 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
404 newFile
.setModificationTimestampAtLastSyncForData(
405 mFile
.getModificationTimestampAtLastSyncForData());
406 // newFile.setEtag(mFile.getEtag())
407 newFile
.setFavorite(mFile
.isFavorite());
408 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
409 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
410 newFile
.setStoragePath(mFile
.getStoragePath());
411 newFile
.setParentId(mFile
.getParentId());
417 * Checks if remotePath does not exist in the server and returns it, or adds
418 * a suffix to it in order to avoid the server file is overwritten.
424 private String
getAvailableRemotePath(OwnCloudClient wc
, String remotePath
) throws Exception
{
425 boolean check
= existsFile(wc
, remotePath
);
430 int pos
= remotePath
.lastIndexOf(".");
432 String extension
= "";
434 extension
= remotePath
.substring(pos
+ 1);
435 remotePath
= remotePath
.substring(0, pos
);
439 suffix
= " (" + count
+ ")";
441 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
444 check
= existsFile(wc
, remotePath
+ suffix
);
450 return remotePath
+ suffix
+ "." + extension
;
452 return remotePath
+ suffix
;
456 private boolean existsFile(OwnCloudClient client
, String remotePath
){
457 ExistenceCheckRemoteOperation existsOperation
=
458 new ExistenceCheckRemoteOperation(remotePath
, mContext
, false
);
459 RemoteOperationResult result
= existsOperation
.execute(client
);
460 return result
.isSuccess();
463 public void cancel() {
464 mCancellationRequested
= new AtomicBoolean(true
);
465 if (mUploadOperation
!= null
) {
466 mUploadOperation
.cancel();