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 version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.operations
;
21 import java
.io
.FileInputStream
;
22 import java
.io
.FileOutputStream
;
23 import java
.io
.IOException
;
24 import java
.io
.InputStream
;
25 import java
.io
.OutputStream
;
26 import java
.util
.HashSet
;
27 import java
.util
.Iterator
;
29 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
31 import org
.apache
.commons
.httpclient
.methods
.PutMethod
;
32 import org
.apache
.commons
.httpclient
.methods
.RequestEntity
;
34 import android
.accounts
.Account
;
35 import android
.content
.Context
;
36 import android
.net
.Uri
;
38 import com
.owncloud
.android
.MainApp
;
39 import com
.owncloud
.android
.datamodel
.OCFile
;
40 import com
.owncloud
.android
.files
.services
.FileUploader
;
41 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
42 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
43 import com
.owncloud
.android
.lib
.common
.network
.ProgressiveDataTransferer
;
44 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
;
45 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
46 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
47 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
48 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
49 import com
.owncloud
.android
.lib
.resources
.files
.ChunkedUploadRemoteFileOperation
;
50 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
51 import com
.owncloud
.android
.lib
.resources
.files
.UploadRemoteFileOperation
;
52 import com
.owncloud
.android
.utils
.FileStorageUtils
;
56 * Remote operation performing the upload of a file to an ownCloud server
58 * @author David A. Velasco
60 public class UploadFileOperation
extends RemoteOperation
{
62 private static final String TAG
= UploadFileOperation
.class.getSimpleName();
64 private static final String URI_CONTENT_SCHEME
= "content://";
65 private static final String MIME_TYPE_PDF
= "application/pdf";
66 private static final String FILE_EXTENSION_PDF
= ".pdf";
68 private Account mAccount
;
70 private OCFile mOldFile
;
71 private String mRemotePath
= null
;
72 private boolean mChunked
= false
;
73 private boolean mIsInstant
= false
;
74 private boolean mRemoteFolderToBeCreated
= false
;
75 private boolean mForceOverwrite
= false
;
76 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
77 private boolean mWasRenamed
= false
;
78 private String mOriginalFileName
= null
;
79 private String mOriginalStoragePath
= null
;
80 PutMethod mPutMethod
= null
;
81 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
82 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
83 private Context mContext
;
85 private UploadRemoteFileOperation mUploadOperation
;
87 protected RequestEntity mEntity
= null
;
90 public UploadFileOperation( Account account
,
94 boolean forceOverwrite
,
98 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
100 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
101 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0) {
102 throw new IllegalArgumentException(
103 "Illegal file in UploadFileOperation; storage path invalid: "
104 + file
.getStoragePath());
109 mRemotePath
= file
.getRemotePath();
111 mIsInstant
= isInstant
;
112 mForceOverwrite
= forceOverwrite
;
113 mLocalBehaviour
= localBehaviour
;
114 mOriginalStoragePath
= mFile
.getStoragePath();
115 mOriginalFileName
= mFile
.getFileName();
119 public Account
getAccount() {
123 public String
getFileName() {
124 return mOriginalFileName
;
127 public OCFile
getFile() {
131 public OCFile
getOldFile() {
135 public String
getOriginalStoragePath() {
136 return mOriginalStoragePath
;
139 public String
getStoragePath() {
140 return mFile
.getStoragePath();
143 public String
getRemotePath() {
144 return mFile
.getRemotePath();
147 public String
getMimeType() {
148 return mFile
.getMimetype();
151 public boolean isInstant() {
155 public boolean isRemoteFolderToBeCreated() {
156 return mRemoteFolderToBeCreated
;
159 public void setRemoteFolderToBeCreated() {
160 mRemoteFolderToBeCreated
= true
;
163 public boolean getForceOverwrite() {
164 return mForceOverwrite
;
167 public boolean wasRenamed() {
171 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
172 return mDataTransferListeners
;
175 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
176 synchronized (mDataTransferListeners
) {
177 mDataTransferListeners
.add(listener
);
179 if (mEntity
!= null
) {
180 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
184 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
185 synchronized (mDataTransferListeners
) {
186 mDataTransferListeners
.remove(listener
);
188 if (mEntity
!= null
) {
189 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
194 protected RemoteOperationResult
run(OwnCloudClient client
) {
195 RemoteOperationResult result
= null
;
196 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
197 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
199 // / rename the file to upload, if necessary
200 if (!mForceOverwrite
) {
201 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
202 mWasRenamed
= !remotePath
.equals(mRemotePath
);
204 createNewOCFile(remotePath
);
207 nameCheckPassed
= true
;
209 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
212 // getAvailableRemotePath()
214 expectedFile
= new File(expectedPath
);
216 // check location of local file; if not the expected, copy to a
217 // temporal file before upload (if COPY is the expected behaviour)
218 if (!mOriginalStoragePath
.equals(expectedPath
) && 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
) + mFile
.getRemotePath();
229 if (isPdfFileFromContentProviderWithoutExtension()){
230 temporalPath
+= FILE_EXTENSION_PDF
;
231 mFile
.setRemotePath(mFile
.getRemotePath() + FILE_EXTENSION_PDF
);
234 mFile
.setStoragePath(temporalPath
);
235 temporalFile
= new File(temporalPath
);
237 File temporalParent
= temporalFile
.getParentFile();
238 temporalParent
.mkdirs();
239 if (!temporalParent
.isDirectory()) {
240 throw new IOException("Unexpected error: parent directory could not be created");
242 temporalFile
.createNewFile();
243 if (!temporalFile
.isFile()) {
244 throw new IOException("Unexpected error: target file could not be created");
247 InputStream
in = null
;
248 OutputStream out
= null
;
252 // In case document provider schema as 'content://'
253 if (mOriginalStoragePath
.startsWith(URI_CONTENT_SCHEME
)) {
255 Uri uri
= Uri
.parse(mOriginalStoragePath
);
257 in = MainApp
.getAppContext().getContentResolver().openInputStream(uri
);
258 out
= new FileOutputStream(temporalFile
);
261 byte[] data
= new byte[16384];
263 while ((nRead
= in.read(data
, 0, data
.length
)) != -1) {
264 out
.write(data
, 0, nRead
);
270 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
276 in = new FileInputStream(originalFile
);
277 out
= new FileOutputStream(temporalFile
);
278 byte[] buf
= new byte[1024];
280 while ((len
= in.read(buf
)) > 0) {
281 out
.write(buf
, 0, len
);
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 " + mOriginalStoragePath
+ " (ignoring)", e
);
300 } catch (Exception e
) {
301 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
306 localCopyPassed
= true
;
308 /// perform the upload
309 if ( mChunked
&& (new File(mFile
.getStoragePath())).length() > ChunkedUploadRemoteFileOperation
.CHUNK_SIZE
) {
310 mUploadOperation
= new ChunkedUploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
311 mFile
.getMimetype());
313 mUploadOperation
= new UploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
314 mFile
.getMimetype());
316 Iterator
<OnDatatransferProgressListener
> listener
= mDataTransferListeners
.iterator();
317 while (listener
.hasNext()) {
318 mUploadOperation
.addDatatransferProgressListener(listener
.next());
320 result
= mUploadOperation
.execute(client
);
322 /// move local temporal file or original file to its corresponding
323 // location in the ownCloud local folder
324 if (result
.isSuccess()) {
325 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
326 mFile
.setStoragePath(null
);
329 mFile
.setStoragePath(expectedPath
);
330 File fileToMove
= null
;
331 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
332 // ; see where temporalFile was
334 fileToMove
= temporalFile
;
335 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
336 fileToMove
= originalFile
;
338 if (!expectedFile
.equals(fileToMove
)) {
339 File expectedFolder
= expectedFile
.getParentFile();
340 expectedFolder
.mkdirs();
341 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
342 mFile
.setStoragePath(null
); // forget the local file
343 // by now, treat this as a success; the file was
344 // uploaded; the user won't like that the local file
345 // is not linked, but this should be a very rare
347 // the best option could be show a warning message
350 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
357 } catch (Exception e
) {
358 // TODO something cleaner with cancellations
359 if (mCancellationRequested
.get()) {
360 result
= new RemoteOperationResult(new OperationCancelledException());
362 result
= new RemoteOperationResult(e
);
366 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
367 temporalFile
.delete();
369 if (result
.isSuccess()) {
370 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
372 if (result
.getException() != null
) {
373 String complement
= "";
374 if (!nameCheckPassed
) {
375 complement
= " (while checking file existence in server)";
376 } else if (!localCopyPassed
) {
377 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
)
380 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
382 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
390 private void createNewOCFile(String newRemotePath
) {
391 // a new OCFile instance must be created for a new remote path
392 OCFile newFile
= new OCFile(newRemotePath
);
393 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
394 newFile
.setFileLength(mFile
.getFileLength());
395 newFile
.setMimetype(mFile
.getMimetype());
396 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
397 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
398 // newFile.setEtag(mFile.getEtag())
399 newFile
.setKeepInSync(mFile
.keepInSync());
400 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
401 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
402 newFile
.setStoragePath(mFile
.getStoragePath());
403 newFile
.setParentId(mFile
.getParentId());
409 * Checks if remotePath does not exist in the server and returns it, or adds
410 * a suffix to it in order to avoid the server file is overwritten.
415 private String
getAvailableRemotePath(OwnCloudClient wc
, String remotePath
) throws Exception
{
416 boolean check
= existsFile(wc
, remotePath
);
421 int pos
= remotePath
.lastIndexOf(".");
423 String extension
= "";
425 extension
= remotePath
.substring(pos
+ 1);
426 remotePath
= remotePath
.substring(0, pos
);
430 suffix
= " (" + count
+ ")";
432 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
435 check
= existsFile(wc
, remotePath
+ suffix
);
441 return remotePath
+ suffix
+ "." + extension
;
443 return remotePath
+ suffix
;
447 private boolean existsFile(OwnCloudClient client
, String remotePath
){
448 ExistenceCheckRemoteOperation existsOperation
= new ExistenceCheckRemoteOperation(remotePath
, mContext
, false
);
449 RemoteOperationResult result
= existsOperation
.execute(client
);
450 return result
.isSuccess();
453 public void cancel() {
454 mUploadOperation
.cancel();
458 * Checks if content provider, using the content:// scheme, returns a file with mime-type
459 * 'application/pdf' but file has not extension
460 * @return true if is needed to add the pdf file extension to the file
462 private boolean isPdfFileFromContentProviderWithoutExtension() {
463 return mOriginalStoragePath
.startsWith(URI_CONTENT_SCHEME
) &&
464 mFile
.getMimetype().equals(MIME_TYPE_PDF
) &&
465 !mFile
.getFileName().endsWith(FILE_EXTENSION_PDF
);