7fad177b579bbb39d6e8ac85dd5ee24cc6b72ac1
[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.RequestEntity;
35
36 import android.accounts.Account;
37 import android.content.Context;
38 import android.net.Uri;
39
40 import com.owncloud.android.MainApp;
41 import com.owncloud.android.datamodel.OCFile;
42 import com.owncloud.android.files.services.FileUploader;
43 import com.owncloud.android.lib.common.OwnCloudClient;
44 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
45 import com.owncloud.android.lib.common.network.ProgressiveDataTransferer;
46 import com.owncloud.android.lib.common.operations.OperationCancelledException;
47 import com.owncloud.android.lib.common.operations.RemoteOperation;
48 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
49 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
50 import com.owncloud.android.lib.common.utils.Log_OC;
51 import com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation;
52 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
53 import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
54 import com.owncloud.android.utils.FileStorageUtils;
55 import com.owncloud.android.utils.UriUtils;
56
57
58 /**
59 * Remote operation performing the upload of a file to an ownCloud server
60 */
61 public class UploadFileOperation extends RemoteOperation {
62
63 private static final String TAG = UploadFileOperation.class.getSimpleName();
64
65 private Account mAccount;
66 private OCFile mFile;
67 private OCFile mOldFile;
68 private String mRemotePath = null;
69 private boolean mChunked = false;
70 private boolean mIsInstant = false;
71 private boolean mRemoteFolderToBeCreated = false;
72 private boolean mForceOverwrite = false;
73 private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
74 private boolean mWasRenamed = false;
75 private String mOriginalFileName = null;
76 private String mOriginalStoragePath = null;
77 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
78 private AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
79 private Context mContext;
80
81 private UploadRemoteFileOperation mUploadOperation;
82
83 protected RequestEntity mEntity = null;
84
85
86 public UploadFileOperation( Account account,
87 OCFile file,
88 boolean chunked,
89 boolean isInstant,
90 boolean forceOverwrite,
91 int localBehaviour,
92 Context context) {
93 if (account == null)
94 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " +
95 "creation");
96 if (file == null)
97 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
98 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0) {
99 throw new IllegalArgumentException(
100 "Illegal file in UploadFileOperation; storage path invalid: "
101 + file.getStoragePath());
102 }
103
104 mAccount = account;
105 mFile = file;
106 mRemotePath = file.getRemotePath();
107 mChunked = chunked;
108 mIsInstant = isInstant;
109 mForceOverwrite = forceOverwrite;
110 mLocalBehaviour = localBehaviour;
111 mOriginalStoragePath = mFile.getStoragePath();
112 mOriginalFileName = mFile.getFileName();
113 mContext = context;
114 }
115
116 public Account getAccount() {
117 return mAccount;
118 }
119
120 public String getFileName() {
121 return mOriginalFileName;
122 }
123
124 public OCFile getFile() {
125 return mFile;
126 }
127
128 public OCFile getOldFile() {
129 return mOldFile;
130 }
131
132 public String getOriginalStoragePath() {
133 return mOriginalStoragePath;
134 }
135
136 public String getStoragePath() {
137 return mFile.getStoragePath();
138 }
139
140 public String getRemotePath() {
141 return mFile.getRemotePath();
142 }
143
144 public String getMimeType() {
145 return mFile.getMimetype();
146 }
147
148 public boolean isInstant() {
149 return mIsInstant;
150 }
151
152 public boolean isRemoteFolderToBeCreated() {
153 return mRemoteFolderToBeCreated;
154 }
155
156 public void setRemoteFolderToBeCreated() {
157 mRemoteFolderToBeCreated = true;
158 }
159
160 public boolean getForceOverwrite() {
161 return mForceOverwrite;
162 }
163
164 public boolean wasRenamed() {
165 return mWasRenamed;
166 }
167
168 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
169 return mDataTransferListeners;
170 }
171
172 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
173 synchronized (mDataTransferListeners) {
174 mDataTransferListeners.add(listener);
175 }
176 if (mEntity != null) {
177 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
178 }
179 }
180
181 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
182 synchronized (mDataTransferListeners) {
183 mDataTransferListeners.remove(listener);
184 }
185 if (mEntity != null) {
186 ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
187 }
188 }
189
190 @Override
191 protected RemoteOperationResult run(OwnCloudClient client) {
192 RemoteOperationResult result = null;
193 boolean localCopyPassed = false, nameCheckPassed = false;
194 File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
195 try {
196 // / rename the file to upload, if necessary
197 if (!mForceOverwrite) {
198 String remotePath = getAvailableRemotePath(client, mRemotePath);
199 mWasRenamed = !remotePath.equals(mRemotePath);
200 if (mWasRenamed) {
201 createNewOCFile(remotePath);
202 }
203 }
204 nameCheckPassed = true;
205
206 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
207 // not
208 // before
209 // getAvailableRemotePath()
210 // !!!
211 expectedFile = new File(expectedPath);
212
213 // check location of local file; if not the expected, copy to a
214 // temporal file before upload (if COPY is the expected behaviour)
215 if (!mOriginalStoragePath.equals(expectedPath) &&
216 mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
217
218 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
219 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
220 return result; // error condition when the file should be
221 // copied
222
223 } else {
224
225 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) +
226 mFile.getRemotePath();
227 mFile.setStoragePath(temporalPath);
228 temporalFile = new File(temporalPath);
229
230 File temporalParent = temporalFile.getParentFile();
231 temporalParent.mkdirs();
232 if (!temporalParent.isDirectory()) {
233 throw new IOException("Unexpected error: parent directory could not be created");
234 }
235 temporalFile.createNewFile();
236 if (!temporalFile.isFile()) {
237 throw new IOException("Unexpected error: target file could not be created");
238 }
239
240 InputStream in = null;
241 OutputStream out = null;
242
243 try {
244
245 // In case document provider schema as 'content://'
246 if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
247
248 Uri uri = Uri.parse(mOriginalStoragePath);
249
250 in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
251 out = new FileOutputStream(temporalFile);
252
253 int nRead;
254 byte[] data = new byte[16384];
255
256 while (!mCancellationRequested.get() &&
257 (nRead = in.read(data, 0, data.length)) != -1) {
258 out.write(data, 0, nRead);
259 }
260 out.flush();
261
262 } else {
263 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
264 // weird
265 // but
266 // possible
267 // situation
268
269 in = new FileInputStream(originalFile);
270 out = new FileOutputStream(temporalFile);
271 byte[] buf = new byte[1024];
272 int len;
273 while (!mCancellationRequested.get() && (len = in.read(buf)) > 0) {
274 out.write(buf, 0, len);
275 }
276 }
277 }
278
279 if (mCancellationRequested.get()) {
280 result = new RemoteOperationResult(new OperationCancelledException());
281 }
282
283
284 } catch (Exception e) {
285 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
286 return result;
287
288 } finally {
289 try {
290 if (in != null)
291 in.close();
292 } catch (Exception e) {
293 Log_OC.d(TAG, "Weird exception while closing input stream for " +
294 mOriginalStoragePath + " (ignoring)", e);
295 }
296 try {
297 if (out != null)
298 out.close();
299 } catch (Exception e) {
300 Log_OC.d(TAG, "Weird exception while closing output stream for " +
301 expectedPath + " (ignoring)", e);
302 }
303 }
304 }
305 }
306 localCopyPassed = (result == null);
307
308 /// perform the upload
309 if ( mChunked &&
310 (new File(mFile.getStoragePath())).length() >
311 ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) {
312 mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(),
313 mFile.getRemotePath(), mFile.getMimetype());
314 } else {
315 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(),
316 mFile.getRemotePath(), mFile.getMimetype());
317 }
318 Iterator <OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
319 while (listener.hasNext()) {
320 mUploadOperation.addDatatransferProgressListener(listener.next());
321 }
322 if (mCancellationRequested.get()) {
323 throw new OperationCancelledException();
324 }
325
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
334 } else {
335 mFile.setStoragePath(expectedPath);
336 File fileToMove = null;
337 if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
338 // ; see where temporalFile was
339 // set
340 fileToMove = temporalFile;
341 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
342 fileToMove = originalFile;
343 }
344 if (!expectedFile.equals(fileToMove)) {
345 File expectedFolder = expectedFile.getParentFile();
346 expectedFolder.mkdirs();
347 if (!expectedFolder.isDirectory() || !fileToMove.renameTo(expectedFile)) {
348 mFile.setStoragePath(null); // forget the local file
349 // by now, treat this as a success; the file was
350 // uploaded; the user won't like that the local file
351 // is not linked, but this should be a very rare
352 // fail;
353 // the best option could be show a warning message
354 // (but not a fail)
355 // result = new
356 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
357 // return result;
358 }
359 }
360 }
361 }
362
363 } catch (Exception e) {
364 result = new RemoteOperationResult(e);
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.setFavorite(mFile.isFavorite());
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 }