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 Account mAccount
;
66 private OCFile mOldFile
;
67 private String mRemotePath
= null
;
68 private boolean mChunked
= false
;
69 private boolean mIsInstant
= false
;
70 private boolean mRemoteFolderToBeCreated
= false
;
71 private boolean mForceOverwrite
= false
;
72 private int mLocalBehaviour
= FileUploader
.LOCAL_BEHAVIOUR_COPY
;
73 private boolean mWasRenamed
= false
;
74 private String mOriginalFileName
= null
;
75 private String mOriginalStoragePath
= null
;
76 PutMethod mPutMethod
= null
;
77 private Set
<OnDatatransferProgressListener
> mDataTransferListeners
= new HashSet
<OnDatatransferProgressListener
>();
78 private final 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 creation");
96 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
97 if (file
.getStoragePath() == null
|| file
.getStoragePath().length() <= 0) {
98 throw new IllegalArgumentException(
99 "Illegal file in UploadFileOperation; storage path invalid: "
100 + file
.getStoragePath());
105 mRemotePath
= file
.getRemotePath();
107 mIsInstant
= isInstant
;
108 mForceOverwrite
= forceOverwrite
;
109 mLocalBehaviour
= localBehaviour
;
110 mOriginalStoragePath
= mFile
.getStoragePath();
111 mOriginalFileName
= mFile
.getFileName();
115 public Account
getAccount() {
119 public String
getFileName() {
120 return mOriginalFileName
;
123 public OCFile
getFile() {
127 public OCFile
getOldFile() {
131 public String
getOriginalStoragePath() {
132 return mOriginalStoragePath
;
135 public String
getStoragePath() {
136 return mFile
.getStoragePath();
139 public String
getRemotePath() {
140 return mFile
.getRemotePath();
143 public String
getMimeType() {
144 return mFile
.getMimetype();
147 public boolean isInstant() {
151 public boolean isRemoteFolderToBeCreated() {
152 return mRemoteFolderToBeCreated
;
155 public void setRemoteFolderToBeCreated() {
156 mRemoteFolderToBeCreated
= true
;
159 public boolean getForceOverwrite() {
160 return mForceOverwrite
;
163 public boolean wasRenamed() {
167 public Set
<OnDatatransferProgressListener
> getDataTransferListeners() {
168 return mDataTransferListeners
;
171 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
) {
172 synchronized (mDataTransferListeners
) {
173 mDataTransferListeners
.add(listener
);
175 if (mEntity
!= null
) {
176 ((ProgressiveDataTransferer
)mEntity
).addDatatransferProgressListener(listener
);
180 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener
) {
181 synchronized (mDataTransferListeners
) {
182 mDataTransferListeners
.remove(listener
);
184 if (mEntity
!= null
) {
185 ((ProgressiveDataTransferer
)mEntity
).removeDatatransferProgressListener(listener
);
190 protected RemoteOperationResult
run(OwnCloudClient client
) {
191 RemoteOperationResult result
= null
;
192 boolean localCopyPassed
= false
, nameCheckPassed
= false
;
193 File temporalFile
= null
, originalFile
= new File(mOriginalStoragePath
), expectedFile
= null
;
195 // / rename the file to upload, if necessary
196 if (!mForceOverwrite
) {
197 String remotePath
= getAvailableRemotePath(client
, mRemotePath
);
198 mWasRenamed
= !remotePath
.equals(mRemotePath
);
200 createNewOCFile(remotePath
);
203 nameCheckPassed
= true
;
205 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
); // /
208 // getAvailableRemotePath()
210 expectedFile
= new File(expectedPath
);
212 // check location of local file; if not the expected, copy to a
213 // temporal file before upload (if COPY is the expected behaviour)
214 if (!mOriginalStoragePath
.equals(expectedPath
) && mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_COPY
) {
216 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
217 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_FULL
);
218 return result
; // error condition when the file should be
223 String temporalPath
= FileStorageUtils
.getTemporalPath(mAccount
.name
) + mFile
.getRemotePath();
224 mFile
.setStoragePath(temporalPath
);
225 temporalFile
= new File(temporalPath
);
227 File temporalParent
= temporalFile
.getParentFile();
228 temporalParent
.mkdirs();
229 if (!temporalParent
.isDirectory()) {
230 throw new IOException("Unexpected error: parent directory could not be created");
232 temporalFile
.createNewFile();
233 if (!temporalFile
.isFile()) {
234 throw new IOException("Unexpected error: target file could not be created");
237 InputStream
in = null
;
238 OutputStream out
= null
;
242 if (mOriginalStoragePath
.startsWith("content://")) {
244 Uri uri
= Uri
.parse(mOriginalStoragePath
);
246 in = MainApp
.getAppContext().getContentResolver().openInputStream(uri
);
247 out
= new FileOutputStream(temporalFile
);
250 byte[] data
= new byte[16384];
252 while ((nRead
= in.read(data
, 0, data
.length
)) != -1) {
253 out
.write(data
, 0, nRead
);
259 if (!mOriginalStoragePath
.equals(temporalPath
)) { // preventing
265 in = new FileInputStream(originalFile
);
266 out
= new FileOutputStream(temporalFile
);
267 byte[] buf
= new byte[1024];
269 while ((len
= in.read(buf
)) > 0) {
270 out
.write(buf
, 0, len
);
275 } catch (Exception e
) {
276 result
= new RemoteOperationResult(ResultCode
.LOCAL_STORAGE_NOT_COPIED
);
283 } catch (Exception e
) {
284 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + mOriginalStoragePath
+ " (ignoring)", e
);
289 } catch (Exception e
) {
290 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
295 localCopyPassed
= true
;
297 /// perform the upload
298 if ( mChunked
&& (new File(mFile
.getStoragePath())).length() > ChunkedUploadRemoteFileOperation
.CHUNK_SIZE
) {
299 mUploadOperation
= new ChunkedUploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
300 mFile
.getMimetype());
302 mUploadOperation
= new UploadRemoteFileOperation(mFile
.getStoragePath(), mFile
.getRemotePath(),
303 mFile
.getMimetype());
305 Iterator
<OnDatatransferProgressListener
> listener
= mDataTransferListeners
.iterator();
306 while (listener
.hasNext()) {
307 mUploadOperation
.addDatatransferProgressListener(listener
.next());
309 result
= mUploadOperation
.execute(client
);
311 /// move local temporal file or original file to its corresponding
312 // location in the ownCloud local folder
313 if (result
.isSuccess()) {
314 if (mLocalBehaviour
== FileUploader
.LOCAL_BEHAVIOUR_FORGET
) {
315 mFile
.setStoragePath(null
);
318 mFile
.setStoragePath(expectedPath
);
319 File fileToMove
= null
;
320 if (temporalFile
!= null
) { // FileUploader.LOCAL_BEHAVIOUR_COPY
321 // ; see where temporalFile was
323 fileToMove
= temporalFile
;
324 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
325 fileToMove
= originalFile
;
327 if (!expectedFile
.equals(fileToMove
)) {
328 File expectedFolder
= expectedFile
.getParentFile();
329 expectedFolder
.mkdirs();
330 if (!expectedFolder
.isDirectory() || !fileToMove
.renameTo(expectedFile
)) {
331 mFile
.setStoragePath(null
); // forget the local file
332 // by now, treat this as a success; the file was
333 // uploaded; the user won't like that the local file
334 // is not linked, but this should be a very rare
336 // the best option could be show a warning message
339 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
346 } catch (Exception e
) {
347 // TODO something cleaner with cancellations
348 if (mCancellationRequested
.get()) {
349 result
= new RemoteOperationResult(new OperationCancelledException());
351 result
= new RemoteOperationResult(e
);
355 if (temporalFile
!= null
&& !originalFile
.equals(temporalFile
)) {
356 temporalFile
.delete();
358 if (result
.isSuccess()) {
359 Log_OC
.i(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
361 if (result
.getException() != null
) {
362 String complement
= "";
363 if (!nameCheckPassed
) {
364 complement
= " (while checking file existence in server)";
365 } else if (!localCopyPassed
) {
366 complement
= " (while copying local file to " + FileStorageUtils
.getSavePath(mAccount
.name
)
369 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage() + complement
, result
.getException());
371 Log_OC
.e(TAG
, "Upload of " + mOriginalStoragePath
+ " to " + mRemotePath
+ ": " + result
.getLogMessage());
379 private void createNewOCFile(String newRemotePath
) {
380 // a new OCFile instance must be created for a new remote path
381 OCFile newFile
= new OCFile(newRemotePath
);
382 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
383 newFile
.setFileLength(mFile
.getFileLength());
384 newFile
.setMimetype(mFile
.getMimetype());
385 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
386 newFile
.setModificationTimestampAtLastSyncForData(mFile
.getModificationTimestampAtLastSyncForData());
387 // newFile.setEtag(mFile.getEtag())
388 newFile
.setKeepInSync(mFile
.keepInSync());
389 newFile
.setLastSyncDateForProperties(mFile
.getLastSyncDateForProperties());
390 newFile
.setLastSyncDateForData(mFile
.getLastSyncDateForData());
391 newFile
.setStoragePath(mFile
.getStoragePath());
392 newFile
.setParentId(mFile
.getParentId());
398 * Checks if remotePath does not exist in the server and returns it, or adds
399 * a suffix to it in order to avoid the server file is overwritten.
404 private String
getAvailableRemotePath(OwnCloudClient wc
, String remotePath
) throws Exception
{
405 boolean check
= existsFile(wc
, remotePath
);
410 int pos
= remotePath
.lastIndexOf(".");
412 String extension
= "";
414 extension
= remotePath
.substring(pos
+ 1);
415 remotePath
= remotePath
.substring(0, pos
);
419 suffix
= " (" + count
+ ")";
421 check
= existsFile(wc
, remotePath
+ suffix
+ "." + extension
);
424 check
= existsFile(wc
, remotePath
+ suffix
);
430 return remotePath
+ suffix
+ "." + extension
;
432 return remotePath
+ suffix
;
436 private boolean existsFile(OwnCloudClient client
, String remotePath
){
437 ExistenceCheckRemoteOperation existsOperation
= new ExistenceCheckRemoteOperation(remotePath
, mContext
, false
);
438 RemoteOperationResult result
= existsOperation
.execute(client
);
439 return result
.isSuccess();
442 public void cancel() {
443 mUploadOperation
.cancel();