Fixed NullPointerExceptionS in upload cancelations
[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.OCFile;
43 import com.owncloud.android.files.services.FileUploader;
44 import com.owncloud.android.lib.common.OwnCloudClient;
45 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
46 import com.owncloud.android.lib.common.network.ProgressiveDataTransferer;
47 import com.owncloud.android.lib.common.operations.OperationCancelledException;
48 import com.owncloud.android.lib.common.operations.RemoteOperation;
49 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
50 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
51 import com.owncloud.android.lib.common.utils.Log_OC;
52 import com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation;
53 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
54 import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
55 import com.owncloud.android.utils.FileStorageUtils;
56 import com.owncloud.android.utils.UriUtils;
57
58
59 /**
60 * Remote operation performing the upload of a file to an ownCloud server
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 " +
97 "creation");
98 if (file == null)
99 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
100 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0) {
101 throw new IllegalArgumentException(
102 "Illegal file in UploadFileOperation; storage path invalid: "
103 + file.getStoragePath());
104 }
105
106 mAccount = account;
107 mFile = file;
108 mRemotePath = file.getRemotePath();
109 mChunked = chunked;
110 mIsInstant = isInstant;
111 mForceOverwrite = forceOverwrite;
112 mLocalBehaviour = localBehaviour;
113 mOriginalStoragePath = mFile.getStoragePath();
114 mOriginalFileName = mFile.getFileName();
115 mContext = context;
116 }
117
118 public Account getAccount() {
119 return mAccount;
120 }
121
122 public String getFileName() {
123 return mOriginalFileName;
124 }
125
126 public OCFile getFile() {
127 return mFile;
128 }
129
130 public OCFile getOldFile() {
131 return mOldFile;
132 }
133
134 public String getOriginalStoragePath() {
135 return mOriginalStoragePath;
136 }
137
138 public String getStoragePath() {
139 return mFile.getStoragePath();
140 }
141
142 public String getRemotePath() {
143 return mFile.getRemotePath();
144 }
145
146 public String getMimeType() {
147 return mFile.getMimetype();
148 }
149
150 public boolean isInstant() {
151 return mIsInstant;
152 }
153
154 public boolean isRemoteFolderToBeCreated() {
155 return mRemoteFolderToBeCreated;
156 }
157
158 public void setRemoteFolderToBeCreated() {
159 mRemoteFolderToBeCreated = true;
160 }
161
162 public boolean getForceOverwrite() {
163 return mForceOverwrite;
164 }
165
166 public boolean wasRenamed() {
167 return mWasRenamed;
168 }
169
170 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
171 return mDataTransferListeners;
172 }
173
174 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
175 synchronized (mDataTransferListeners) {
176 mDataTransferListeners.add(listener);
177 }
178 if (mEntity != null) {
179 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
180 }
181 }
182
183 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
184 synchronized (mDataTransferListeners) {
185 mDataTransferListeners.remove(listener);
186 }
187 if (mEntity != null) {
188 ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
189 }
190 }
191
192 @Override
193 protected RemoteOperationResult run(OwnCloudClient client) {
194 RemoteOperationResult result = null;
195 boolean localCopyPassed = false, nameCheckPassed = false;
196 File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
197 try {
198 // / rename the file to upload, if necessary
199 if (!mForceOverwrite) {
200 String remotePath = getAvailableRemotePath(client, mRemotePath);
201 mWasRenamed = !remotePath.equals(mRemotePath);
202 if (mWasRenamed) {
203 createNewOCFile(remotePath);
204 }
205 }
206 nameCheckPassed = true;
207
208 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
209 // not
210 // before
211 // getAvailableRemotePath()
212 // !!!
213 expectedFile = new File(expectedPath);
214
215 // check location of local file; if not the expected, copy to a
216 // temporal file before upload (if COPY is the expected behaviour)
217 if (!mOriginalStoragePath.equals(expectedPath) &&
218 mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
219
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
223 // copied
224
225 } else {
226
227 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) +
228 mFile.getRemotePath();
229 mFile.setStoragePath(temporalPath);
230 temporalFile = new File(temporalPath);
231
232 File temporalParent = temporalFile.getParentFile();
233 temporalParent.mkdirs();
234 if (!temporalParent.isDirectory()) {
235 throw new IOException("Unexpected error: parent directory could not be created");
236 }
237 temporalFile.createNewFile();
238 if (!temporalFile.isFile()) {
239 throw new IOException("Unexpected error: target file could not be created");
240 }
241
242 InputStream in = null;
243 OutputStream out = null;
244
245 try {
246
247 // In case document provider schema as 'content://'
248 if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
249
250 Uri uri = Uri.parse(mOriginalStoragePath);
251
252 in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
253 out = new FileOutputStream(temporalFile);
254
255 int nRead;
256 byte[] data = new byte[16384];
257
258 while (!mCancellationRequested.get() &&
259 (nRead = in.read(data, 0, data.length)) != -1) {
260 out.write(data, 0, nRead);
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 if (mCancellationRequested.get()) {
282 result = new RemoteOperationResult(new OperationCancelledException());
283 }
284
285
286 } catch (Exception e) {
287 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
288 return result;
289
290 } finally {
291 try {
292 if (in != null)
293 in.close();
294 } catch (Exception e) {
295 Log_OC.d(TAG, "Weird exception while closing input stream for " +
296 mOriginalStoragePath + " (ignoring)", e);
297 }
298 try {
299 if (out != null)
300 out.close();
301 } catch (Exception e) {
302 Log_OC.d(TAG, "Weird exception while closing output stream for " +
303 expectedPath + " (ignoring)", e);
304 }
305 }
306 }
307 }
308 localCopyPassed = (result == null);
309
310 /// perform the upload
311 if ( mChunked &&
312 (new File(mFile.getStoragePath())).length() >
313 ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) {
314 mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(),
315 mFile.getRemotePath(), mFile.getMimetype());
316 } else {
317 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(),
318 mFile.getRemotePath(), mFile.getMimetype());
319 }
320 Iterator <OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
321 while (listener.hasNext()) {
322 mUploadOperation.addDatatransferProgressListener(listener.next());
323 }
324 if (mCancellationRequested.get()) {
325 throw new OperationCancelledException();
326 }
327
328 result = mUploadOperation.execute(client);
329
330 /// move local temporal file or original file to its corresponding
331 // location in the ownCloud local folder
332 if (result.isSuccess()) {
333 if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
334 mFile.setStoragePath(null);
335
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 }
364
365 } catch (Exception e) {
366 result = new RemoteOperationResult(e);
367
368 } finally {
369 if (temporalFile != null && !originalFile.equals(temporalFile)) {
370 temporalFile.delete();
371 }
372 if (result.isSuccess()) {
373 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " +
374 result.getLogMessage());
375 } else {
376 if (result.getException() != null) {
377 String complement = "";
378 if (!nameCheckPassed) {
379 complement = " (while checking file existence in server)";
380 } else if (!localCopyPassed) {
381 complement = " (while copying local file to " +
382 FileStorageUtils.getSavePath(mAccount.name)
383 + ")";
384 }
385 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
386 ": " + result.getLogMessage() + complement, result.getException());
387 } else {
388 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
389 ": " + result.getLogMessage());
390 }
391 }
392 }
393
394 return result;
395 }
396
397 private void createNewOCFile(String newRemotePath) {
398 // a new OCFile instance must be created for a new remote path
399 OCFile newFile = new OCFile(newRemotePath);
400 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
401 newFile.setFileLength(mFile.getFileLength());
402 newFile.setMimetype(mFile.getMimetype());
403 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
404 newFile.setModificationTimestampAtLastSyncForData(
405 mFile.getModificationTimestampAtLastSyncForData());
406 // newFile.setEtag(mFile.getEtag())
407 newFile.setFavorite(mFile.isFavorite());
408 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
409 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
410 newFile.setStoragePath(mFile.getStoragePath());
411 newFile.setParentId(mFile.getParentId());
412 mOldFile = mFile;
413 mFile = newFile;
414 }
415
416 /**
417 * Checks if remotePath does not exist in the server and returns it, or adds
418 * a suffix to it in order to avoid the server file is overwritten.
419 *
420 * @param wc
421 * @param remotePath
422 * @return
423 */
424 private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) throws Exception {
425 boolean check = existsFile(wc, remotePath);
426 if (!check) {
427 return remotePath;
428 }
429
430 int pos = remotePath.lastIndexOf(".");
431 String suffix = "";
432 String extension = "";
433 if (pos >= 0) {
434 extension = remotePath.substring(pos + 1);
435 remotePath = remotePath.substring(0, pos);
436 }
437 int count = 2;
438 do {
439 suffix = " (" + count + ")";
440 if (pos >= 0) {
441 check = existsFile(wc, remotePath + suffix + "." + extension);
442 }
443 else {
444 check = existsFile(wc, remotePath + suffix);
445 }
446 count++;
447 } while (check);
448
449 if (pos >= 0) {
450 return remotePath + suffix + "." + extension;
451 } else {
452 return remotePath + suffix;
453 }
454 }
455
456 private boolean existsFile(OwnCloudClient client, String remotePath){
457 ExistenceCheckRemoteOperation existsOperation =
458 new ExistenceCheckRemoteOperation(remotePath, mContext, false);
459 RemoteOperationResult result = existsOperation.execute(client);
460 return result.isSuccess();
461 }
462
463 public void cancel() {
464 mCancellationRequested = new AtomicBoolean(true);
465 if (mUploadOperation != null) {
466 mUploadOperation.cancel();
467 }
468 }
469 }