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
.RequestEntity
;
36 import android
.accounts
.Account
;
37 import android
.content
.Context
;
38 import android
.net
.Uri
;
40 import com
.owncloud
.android
.MainApp
;
41 import com
.owncloud
.android
.datamodel
.OCFile
;
42 import com
.owncloud
.android
.files
.services
.FileUploader
;
43 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
44 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
45 import com
.owncloud
.android
.lib
.common
.network
.ProgressiveDataTransferer
;
46 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
;
47 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
48 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
49 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
50 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
51 import com
.owncloud
.android
.lib
.resources
.files
.ChunkedUploadRemoteFileOperation
;
52 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
53 import com
.owncloud
.android
.lib
.resources
.files
.UploadRemoteFileOperation
;
54 import com
.owncloud
.android
.utils
.FileStorageUtils
;
55 import com
.owncloud
.android
.utils
.UriUtils
;
59 * Remote operation performing the upload of a file to an ownCloud server
61 public class UploadFileOperation
extends RemoteOperation
{
63 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
65 private Account mAccount
;
67 private OCFile mOldFile
;
68 private String mRemotePath
= null
;
69 private boolean mChunked
= false
;
70 private boolean mIsInstant
= false
;
71 private boolean mRemoteFolderToBeCreated
= false
;
72 private boolean mForceOverwrite
= false
;
73 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
74 private boolean mWasRenamed
= false
;
75 private String mOriginalFileName
= null
;
76 private String mOriginalStoragePath
= null
;
77 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
78 private AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
79 private Context mContext
;
81 private UploadRemoteFileOperation mUploadOperation
;
83 protected RequestEntity mEntity
= null
;
86 public UploadFileOperation( Account account
,
90 boolean forceOverwrite
,
94 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " +
97 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
98 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0) {
99 throw new IllegalArgumentException(
100 "Illegal file in UploadFileOperation; storage path invalid: "
101 + file
.getStoragePath());
106 mRemotePath
= file
.getRemotePath();
108 mIsInstant
= isInstant
;
109 mForceOverwrite
= forceOverwrite
;
110 mLocalBehaviour
= localBehaviour
;
111 mOriginalStoragePath
= mFile
.getStoragePath();
112 mOriginalFileName
= mFile
.getFileName();
116 public Account
getAccount() {
120 public String
getFileName() {
121 return mOriginalFileName
;
124 public OCFile
getFile() {
128 public OCFile
getOldFile() {
132 public String
getOriginalStoragePath() {
133 return mOriginalStoragePath
;
136 public String
getStoragePath() {
137 return mFile
.getStoragePath();
140 public String
getRemotePath() {
141 return mFile
.getRemotePath();
144 public String
getMimeType() {
145 return mFile
.getMimetype();
148 public boolean isInstant() {
152 public boolean isRemoteFolderToBeCreated() {
153 return mRemoteFolderToBeCreated
;
156 public void setRemoteFolderToBeCreated() {
157 mRemoteFolderToBeCreated
= true
;
160 public boolean getForceOverwrite() {
161 return mForceOverwrite
;
164 public boolean wasRenamed() {
168 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
169 return mDataTransferListeners
;
172 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
173 synchronized (mDataTransferListeners
) {
174 mDataTransferListeners
.add(listener
);
176 if (mEntity
!= null
) {
177 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
181 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
182 synchronized (mDataTransferListeners
) {
183 mDataTransferListeners
.remove(listener
);
185 if (mEntity
!= null
) {
186 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
191 protected RemoteOperationResult
run(OwnCloudClient client
) {
192 RemoteOperationResult result
= null
;
193 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
194 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
196 // / rename the file to upload, if necessary
197 if (!mForceOverwrite
) {
198 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
199 mWasRenamed
= !remotePath
.equals(mRemotePath
);
201 createNewOCFile(remotePath
);
204 nameCheckPassed
= true
;
206 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
209 // getAvailableRemotePath()
211 expectedFile
= new File(expectedPath
);
213 // check location of local file; if not the expected, copy to a
214 // temporal file before upload (if COPY is the expected behaviour)
215 if (!mOriginalStoragePath
.equals(expectedPath
) &&
216 mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
218 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
219 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
220 return result
; // error condition when the file should be
225 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) +
226 mFile
.getRemotePath();
227 mFile
.setStoragePath(temporalPath
);
228 temporalFile
= new File(temporalPath
);
230 File temporalParent
= temporalFile
.getParentFile();
231 temporalParent
.mkdirs();
232 if (!temporalParent
.isDirectory()) {
233 throw new IOException("Unexpected error: parent directory could not be created");
235 temporalFile
.createNewFile();
236 if (!temporalFile
.isFile()) {
237 throw new IOException("Unexpected error: target file could not be created");
240 InputStream
in = null
;
241 OutputStream out
= null
;
245 // In case document provider schema as 'content://'
246 if (mOriginalStoragePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
248 Uri uri
= Uri
.parse(mOriginalStoragePath
);
250 in = MainApp
.getAppContext().getContentResolver().openInputStream(uri
);
251 out
= new FileOutputStream(temporalFile
);
254 byte[] data
= new byte[16384];
256 while (!mCancellationRequested
.get() &&
257 (nRead
= in.read(data
, 0, data
.length
)) != -1) {
258 out
.write(data
, 0, nRead
);
263 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
269 in = new FileInputStream(originalFile
);
270 out
= new FileOutputStream(temporalFile
);
271 byte[] buf
= new byte[1024];
273 while (!mCancellationRequested
.get() && (len
= in.read(buf
)) > 0) {
274 out
.write(buf
, 0, len
);
279 if (mCancellationRequested
.get()) {
280 result
= new RemoteOperationResult(new OperationCancelledException());
284 } catch (Exception e
) {
285 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
292 } catch (Exception e
) {
293 Log_OC
.d(TAG
, "Weird exception while closing input stream for " +
294 mOriginalStoragePath
+ " (ignoring)", e
);
299 } catch (Exception e
) {
300 Log_OC
.d(TAG
, "Weird exception while closing output stream for " +
301 expectedPath
+ " (ignoring)", e
);
306 localCopyPassed
= (result
== null
);
308 /// perform the upload
310 (new File(mFile
.getStoragePath())).length() >
311 ChunkedUploadRemoteFileOperation
.CHUNK_SIZE
) {
312 mUploadOperation
= new ChunkedUploadRemoteFileOperation(mFile
.getStoragePath(),
313 mFile
.getRemotePath(), mFile
.getMimetype());
315 mUploadOperation
= new UploadRemoteFileOperation(mFile
.getStoragePath(),
316 mFile
.getRemotePath(), mFile
.getMimetype());
318 Iterator
<OnDatatransferProgressListener
> listener
= mDataTransferListeners
.iterator();
319 while (listener
.hasNext()) {
320 mUploadOperation
.addDatatransferProgressListener(listener
.next());
322 if (mCancellationRequested
.get()) {
323 throw new OperationCancelledException();
326 result
= mUploadOperation
.execute(client
);
328 /// move local temporal file or original file to its corresponding
329 // location in the ownCloud local folder
330 if (result
.isSuccess()) {
331 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
332 mFile
.setStoragePath(null
);
335 mFile
.setStoragePath(expectedPath
);
336 File fileToMove
= null
;
337 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
338 // ; see where temporalFile was
340 fileToMove
= temporalFile
;
341 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
342 fileToMove
= originalFile
;
344 if (!expectedFile
.equals(fileToMove
)) {
345 File expectedFolder
= expectedFile
.getParentFile();
346 expectedFolder
.mkdirs();
347 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
348 mFile
.setStoragePath(null
); // forget the local file
349 // by now, treat this as a success; the file was
350 // uploaded; the user won't like that the local file
351 // is not linked, but this should be a very rare
353 // the best option could be show a warning message
356 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
363 } catch (Exception e
) {
364 result
= new RemoteOperationResult(e
);
367 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
368 temporalFile
.delete();
370 if (result
.isSuccess()) {
371 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " +
372 result
.getLogMessage());
374 if (result
.getException() != null
) {
375 String complement
= "";
376 if (!nameCheckPassed
) {
377 complement
= " (while checking file existence in server)";
378 } else if (!localCopyPassed
) {
379 complement
= " (while copying local file to " +
380 FileStorageUtils
.getSavePath(mAccount
.name
)
383 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+
384 ": " + result
.getLogMessage() + complement
, result
.getException());
386 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+
387 ": " + result
.getLogMessage());
395 private void createNewOCFile(String newRemotePath
) {
396 // a new OCFile instance must be created for a new remote path
397 OCFile newFile
= new OCFile(newRemotePath
);
398 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
399 newFile
.setFileLength(mFile
.getFileLength());
400 newFile
.setMimetype(mFile
.getMimetype());
401 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
402 newFile
.setModificationTimestampAtLastSyncForData(
403 mFile
.getModificationTimestampAtLastSyncForData());
404 newFile
.setEtag(mFile
.getEtag());
405 newFile
.setFavorite(mFile
.isFavorite());
406 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
407 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
408 newFile
.setStoragePath(mFile
.getStoragePath());
409 newFile
.setParentId(mFile
.getParentId());
415 * Checks if remotePath does not exist in the server and returns it, or adds
416 * a suffix to it in order to avoid the server file is overwritten.
422 private String
getAvailableRemotePath(OwnCloudClient wc
, String remotePath
) throws Exception
{
423 boolean check
= existsFile(wc
, remotePath
);
428 int pos
= remotePath
.lastIndexOf(".");
430 String extension
= "";
432 extension
= remotePath
.substring(pos
+ 1);
433 remotePath
= remotePath
.substring(0, pos
);
437 suffix
= " (" + count
+ ")";
439 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
442 check
= existsFile(wc
, remotePath
+ suffix
);
448 return remotePath
+ suffix
+ "." + extension
;
450 return remotePath
+ suffix
;
454 private boolean existsFile(OwnCloudClient client
, String remotePath
){
455 ExistenceCheckRemoteOperation existsOperation
=
456 new ExistenceCheckRemoteOperation(remotePath
, mContext
, false
);
457 RemoteOperationResult result
= existsOperation
.execute(client
);
458 return result
.isSuccess();
461 public void cancel() {
462 mCancellationRequested
= new AtomicBoolean(true
);
463 if (mUploadOperation
!= null
) {
464 mUploadOperation
.cancel();