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