Merge remote-tracking branch 'remotes/upstream/resizedImages' into beta
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / UploadFileOperation.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
6 *
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.
10 *
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.
15 *
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/>.
18 *
19 */
20
21 package com.owncloud.android.operations;
22
23 import java.io.File;
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;
31 import java.util.Set;
32 import java.util.concurrent.atomic.AtomicBoolean;
33
34 import org.apache.commons.httpclient.methods.PutMethod;
35 import org.apache.commons.httpclient.methods.RequestEntity;
36
37 import android.accounts.Account;
38 import android.content.Context;
39 import android.net.Uri;
40
41 import com.owncloud.android.MainApp;
42 import com.owncloud.android.datamodel.FileDataStorageManager;
43 import com.owncloud.android.datamodel.OCFile;
44 import com.owncloud.android.files.services.FileUploader;
45 import com.owncloud.android.lib.common.OwnCloudClient;
46 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
47 import com.owncloud.android.lib.common.network.ProgressiveDataTransferer;
48 import com.owncloud.android.lib.common.operations.OperationCancelledException;
49 import com.owncloud.android.lib.common.operations.RemoteOperation;
50 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
51 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
52 import com.owncloud.android.lib.common.utils.Log_OC;
53 import com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation;
54 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
55 import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
56 import com.owncloud.android.utils.FileStorageUtils;
57 import com.owncloud.android.utils.UriUtils;
58
59
60 /**
61 * Remote operation performing the upload of a file to an ownCloud server
62 */
63 public class UploadFileOperation extends RemoteOperation {
64
65 private static final String TAG = UploadFileOperation.class.getSimpleName();
66
67 private Account mAccount;
68 private OCFile mFile;
69 private OCFile mOldFile;
70 private String mRemotePath = null;
71 private boolean mChunked = false;
72 private boolean mIsInstant = false;
73 private boolean mRemoteFolderToBeCreated = false;
74 private boolean mForceOverwrite = false;
75 private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
76 private boolean mWasRenamed = false;
77 private String mOriginalFileName = null;
78 private String mOriginalStoragePath = null;
79 PutMethod mPutMethod = null;
80 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
81 private AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
82 private Context mContext;
83
84 private UploadRemoteFileOperation mUploadOperation;
85
86 protected RequestEntity mEntity = null;
87
88
89 public UploadFileOperation( Account account,
90 OCFile file,
91 boolean chunked,
92 boolean isInstant,
93 boolean forceOverwrite,
94 int localBehaviour,
95 Context context) {
96 if (account == null)
97 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " +
98 "creation");
99 if (file == null)
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());
105 }
106
107 mAccount = account;
108 mFile = file;
109 mRemotePath = file.getRemotePath();
110 mChunked = chunked;
111 mIsInstant = isInstant;
112 mForceOverwrite = forceOverwrite;
113 mLocalBehaviour = localBehaviour;
114 mOriginalStoragePath = mFile.getStoragePath();
115 mOriginalFileName = mFile.getFileName();
116 mContext = context;
117 }
118
119 public Account getAccount() {
120 return mAccount;
121 }
122
123 public String getFileName() {
124 return mOriginalFileName;
125 }
126
127 public OCFile getFile() {
128 return mFile;
129 }
130
131 public OCFile getOldFile() {
132 return mOldFile;
133 }
134
135 public String getOriginalStoragePath() {
136 return mOriginalStoragePath;
137 }
138
139 public String getStoragePath() {
140 return mFile.getStoragePath();
141 }
142
143 public String getRemotePath() {
144 return mFile.getRemotePath();
145 }
146
147 public String getMimeType() {
148 return mFile.getMimetype();
149 }
150
151 public boolean isInstant() {
152 return mIsInstant;
153 }
154
155 public boolean isRemoteFolderToBeCreated() {
156 return mRemoteFolderToBeCreated;
157 }
158
159 public void setRemoteFolderToBeCreated() {
160 mRemoteFolderToBeCreated = true;
161 }
162
163 public boolean getForceOverwrite() {
164 return mForceOverwrite;
165 }
166
167 public boolean wasRenamed() {
168 return mWasRenamed;
169 }
170
171 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
172 return mDataTransferListeners;
173 }
174
175 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
176 synchronized (mDataTransferListeners) {
177 mDataTransferListeners.add(listener);
178 }
179 if (mEntity != null) {
180 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
181 }
182 }
183
184 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
185 synchronized (mDataTransferListeners) {
186 mDataTransferListeners.remove(listener);
187 }
188 if (mEntity != null) {
189 ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
190 }
191 }
192
193 @Override
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;
198 try {
199 // / rename the file to upload, if necessary
200 if (!mForceOverwrite) {
201 String remotePath = getAvailableRemotePath(client, mRemotePath);
202 mWasRenamed = !remotePath.equals(mRemotePath);
203 if (mWasRenamed) {
204 createNewOCFile(remotePath);
205 }
206 }
207 nameCheckPassed = true;
208
209 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
210 // not
211 // before
212 // getAvailableRemotePath()
213 // !!!
214 expectedFile = new File(expectedPath);
215
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) &&
219 mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
220
221 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
222 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
223 return result; // error condition when the file should be
224 // copied
225
226 } else {
227
228 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) +
229 mFile.getRemotePath();
230 mFile.setStoragePath(temporalPath);
231 temporalFile = new File(temporalPath);
232
233 File temporalParent = temporalFile.getParentFile();
234 temporalParent.mkdirs();
235 if (!temporalParent.isDirectory()) {
236 throw new IOException("Unexpected error: parent directory could not be created");
237 }
238 temporalFile.createNewFile();
239 if (!temporalFile.isFile()) {
240 throw new IOException("Unexpected error: target file could not be created");
241 }
242
243 InputStream in = null;
244 OutputStream out = null;
245
246 try {
247
248 // In case document provider schema as 'content://'
249 if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
250
251 Uri uri = Uri.parse(mOriginalStoragePath);
252
253 in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
254 out = new FileOutputStream(temporalFile);
255
256 int nRead;
257 byte[] data = new byte[16384];
258
259 while (!mCancellationRequested.get() &&
260 (nRead = in.read(data, 0, data.length)) != -1) {
261 out.write(data, 0, nRead);
262 }
263 out.flush();
264
265 } else {
266 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
267 // weird
268 // but
269 // possible
270 // situation
271
272 in = new FileInputStream(originalFile);
273 out = new FileOutputStream(temporalFile);
274 byte[] buf = new byte[1024];
275 int len;
276 while (!mCancellationRequested.get() && (len = in.read(buf)) > 0) {
277 out.write(buf, 0, len);
278 }
279 }
280 }
281
282 if (mCancellationRequested.get()) {
283 result = new RemoteOperationResult(new OperationCancelledException());
284 }
285
286
287 } catch (Exception e) {
288 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
289 return result;
290
291 } finally {
292 try {
293 if (in != null)
294 in.close();
295 } catch (Exception e) {
296 Log_OC.d(TAG, "Weird exception while closing input stream for " +
297 mOriginalStoragePath + " (ignoring)", e);
298 }
299 try {
300 if (out != null)
301 out.close();
302 } catch (Exception e) {
303 Log_OC.d(TAG, "Weird exception while closing output stream for " +
304 expectedPath + " (ignoring)", e);
305 }
306 }
307 }
308 }
309 localCopyPassed = (result == null);
310
311 /// perform the upload
312 if ( mChunked &&
313 (new File(mFile.getStoragePath())).length() >
314 ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) {
315 mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(),
316 mFile.getRemotePath(), mFile.getMimetype());
317 } else {
318 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(),
319 mFile.getRemotePath(), mFile.getMimetype());
320 }
321 Iterator <OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
322 while (listener.hasNext()) {
323 mUploadOperation.addDatatransferProgressListener(listener.next());
324 }
325 if (!mCancellationRequested.get()) {
326 result = mUploadOperation.execute(client);
327
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);
333 } else if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_REMOVE){
334 mFile.setStoragePath(null);
335 originalFile.delete();
336 } else {
337 mFile.setStoragePath(expectedPath);
338 File fileToMove = null;
339 if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
340 // ; see where temporalFile was
341 // set
342 fileToMove = temporalFile;
343 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
344 fileToMove = originalFile;
345 }
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
354 // fail;
355 // the best option could be show a warning message
356 // (but not a fail)
357 // result = new
358 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
359 // return result;
360 }
361 }
362 }
363 FileDataStorageManager.triggerMediaScan(originalFile.getAbsolutePath());
364 FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
365 }
366 }
367
368 } catch (Exception e) {
369 // TODO something cleaner with cancellations
370 if (mCancellationRequested.get()) {
371 result = new RemoteOperationResult(new OperationCancelledException());
372 } else {
373 result = new RemoteOperationResult(e);
374 }
375
376 } finally {
377 if (temporalFile != null && !originalFile.equals(temporalFile)) {
378 temporalFile.delete();
379 }
380 if (result.isSuccess()) {
381 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " +
382 result.getLogMessage());
383 } else {
384 if (result.getException() != null) {
385 String complement = "";
386 if (!nameCheckPassed) {
387 complement = " (while checking file existence in server)";
388 } else if (!localCopyPassed) {
389 complement = " (while copying local file to " +
390 FileStorageUtils.getSavePath(mAccount.name)
391 + ")";
392 }
393 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
394 ": " + result.getLogMessage() + complement, result.getException());
395 } else {
396 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
397 ": " + result.getLogMessage());
398 }
399 }
400 }
401
402 return result;
403 }
404
405 private void createNewOCFile(String newRemotePath) {
406 // a new OCFile instance must be created for a new remote path
407 OCFile newFile = new OCFile(newRemotePath);
408 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
409 newFile.setFileLength(mFile.getFileLength());
410 newFile.setMimetype(mFile.getMimetype());
411 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
412 newFile.setModificationTimestampAtLastSyncForData(
413 mFile.getModificationTimestampAtLastSyncForData());
414 // newFile.setEtag(mFile.getEtag())
415 newFile.setFavorite(mFile.isFavorite());
416 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
417 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
418 newFile.setStoragePath(mFile.getStoragePath());
419 newFile.setParentId(mFile.getParentId());
420 mOldFile = mFile;
421 mFile = newFile;
422 }
423
424 /**
425 * Checks if remotePath does not exist in the server and returns it, or adds
426 * a suffix to it in order to avoid the server file is overwritten.
427 *
428 * @param wc
429 * @param remotePath
430 * @return
431 */
432 private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) throws Exception {
433 boolean check = existsFile(wc, remotePath);
434 if (!check) {
435 return remotePath;
436 }
437
438 int pos = remotePath.lastIndexOf(".");
439 String suffix = "";
440 String extension = "";
441 if (pos >= 0) {
442 extension = remotePath.substring(pos + 1);
443 remotePath = remotePath.substring(0, pos);
444 }
445 int count = 2;
446 do {
447 suffix = " (" + count + ")";
448 if (pos >= 0) {
449 check = existsFile(wc, remotePath + suffix + "." + extension);
450 }
451 else {
452 check = existsFile(wc, remotePath + suffix);
453 }
454 count++;
455 } while (check);
456
457 if (pos >= 0) {
458 return remotePath + suffix + "." + extension;
459 } else {
460 return remotePath + suffix;
461 }
462 }
463
464 private boolean existsFile(OwnCloudClient client, String remotePath){
465 ExistenceCheckRemoteOperation existsOperation =
466 new ExistenceCheckRemoteOperation(remotePath, mContext, false);
467 RemoteOperationResult result = existsOperation.execute(client);
468 return result.isSuccess();
469 }
470
471 public void cancel() {
472 mCancellationRequested = new AtomicBoolean(true);
473 if (mUploadOperation != null) {
474 mUploadOperation.cancel();
475 }
476 }
477 }