Merge branch 'develop' into obeySortOrder_fixmerge
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / UploadFileOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 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.atomic.AtomicBoolean;
30
31 import org.apache.commons.httpclient.methods.PutMethod;
32 import org.apache.commons.httpclient.methods.RequestEntity;
33
34 import android.accounts.Account;
35 import android.content.Context;
36 import android.net.Uri;
37
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;
53 import com.owncloud.android.utils.UriUtils;
54
55
56 /**
57 * Remote operation performing the upload of a file to an ownCloud server
58 *
59 * @author David A. Velasco
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 PutMethod mPutMethod = null;
78 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
79 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
80 private Context mContext;
81
82 private UploadRemoteFileOperation mUploadOperation;
83
84 protected RequestEntity mEntity = null;
85
86
87 public UploadFileOperation( Account account,
88 OCFile file,
89 boolean chunked,
90 boolean isInstant,
91 boolean forceOverwrite,
92 int localBehaviour,
93 Context context) {
94 if (account == null)
95 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation 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) && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
216
217 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
218 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
219 return result; // error condition when the file should be
220 // copied
221
222 } else {
223
224 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
225 mFile.setStoragePath(temporalPath);
226 temporalFile = new File(temporalPath);
227
228 File temporalParent = temporalFile.getParentFile();
229 temporalParent.mkdirs();
230 if (!temporalParent.isDirectory()) {
231 throw new IOException("Unexpected error: parent directory could not be created");
232 }
233 temporalFile.createNewFile();
234 if (!temporalFile.isFile()) {
235 throw new IOException("Unexpected error: target file could not be created");
236 }
237
238 InputStream in = null;
239 OutputStream out = null;
240
241 try {
242
243 // In case document provider schema as 'content://'
244 if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
245
246 Uri uri = Uri.parse(mOriginalStoragePath);
247
248 in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
249 out = new FileOutputStream(temporalFile);
250
251 int nRead;
252 byte[] data = new byte[16384];
253
254 while ((nRead = in.read(data, 0, data.length)) != -1) {
255 out.write(data, 0, nRead);
256 }
257
258 out.flush();
259
260 } else {
261 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
262 // weird
263 // but
264 // possible
265 // situation
266
267 in = new FileInputStream(originalFile);
268 out = new FileOutputStream(temporalFile);
269 byte[] buf = new byte[1024];
270 int len;
271 while ((len = in.read(buf)) > 0) {
272 out.write(buf, 0, len);
273 }
274 }
275 }
276
277 } catch (Exception e) {
278 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
279 return result;
280
281 } finally {
282 try {
283 if (in != null)
284 in.close();
285 } catch (Exception e) {
286 Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e);
287 }
288 try {
289 if (out != null)
290 out.close();
291 } catch (Exception e) {
292 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
293 }
294 }
295 }
296 }
297 localCopyPassed = true;
298
299 /// perform the upload
300 if ( mChunked && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) {
301 mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
302 mFile.getMimetype());
303 } else {
304 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
305 mFile.getMimetype());
306 }
307 Iterator <OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
308 while (listener.hasNext()) {
309 mUploadOperation.addDatatransferProgressListener(listener.next());
310 }
311 result = mUploadOperation.execute(client);
312
313 /// move local temporal file or original file to its corresponding
314 // location in the ownCloud local folder
315 if (result.isSuccess()) {
316 if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
317 mFile.setStoragePath(null);
318
319 } else {
320 mFile.setStoragePath(expectedPath);
321 File fileToMove = null;
322 if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
323 // ; see where temporalFile was
324 // set
325 fileToMove = temporalFile;
326 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
327 fileToMove = originalFile;
328 }
329 if (!expectedFile.equals(fileToMove)) {
330 File expectedFolder = expectedFile.getParentFile();
331 expectedFolder.mkdirs();
332 if (!expectedFolder.isDirectory() || !fileToMove.renameTo(expectedFile)) {
333 mFile.setStoragePath(null); // forget the local file
334 // by now, treat this as a success; the file was
335 // uploaded; the user won't like that the local file
336 // is not linked, but this should be a very rare
337 // fail;
338 // the best option could be show a warning message
339 // (but not a fail)
340 // result = new
341 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
342 // return result;
343 }
344 }
345 }
346 }
347
348 } catch (Exception e) {
349 // TODO something cleaner with cancellations
350 if (mCancellationRequested.get()) {
351 result = new RemoteOperationResult(new OperationCancelledException());
352 } else {
353 result = new RemoteOperationResult(e);
354 }
355
356 } finally {
357 if (temporalFile != null && !originalFile.equals(temporalFile)) {
358 temporalFile.delete();
359 }
360 if (result.isSuccess()) {
361 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
362 } else {
363 if (result.getException() != null) {
364 String complement = "";
365 if (!nameCheckPassed) {
366 complement = " (while checking file existence in server)";
367 } else if (!localCopyPassed) {
368 complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
369 + ")";
370 }
371 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException());
372 } else {
373 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
374 }
375 }
376 }
377
378 return result;
379 }
380
381 private void createNewOCFile(String newRemotePath) {
382 // a new OCFile instance must be created for a new remote path
383 OCFile newFile = new OCFile(newRemotePath);
384 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
385 newFile.setFileLength(mFile.getFileLength());
386 newFile.setMimetype(mFile.getMimetype());
387 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
388 newFile.setModificationTimestampAtLastSyncForData(mFile.getModificationTimestampAtLastSyncForData());
389 // newFile.setEtag(mFile.getEtag())
390 newFile.setKeepInSync(mFile.keepInSync());
391 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
392 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
393 newFile.setStoragePath(mFile.getStoragePath());
394 newFile.setParentId(mFile.getParentId());
395 mOldFile = mFile;
396 mFile = newFile;
397 }
398
399 /**
400 * Checks if remotePath does not exist in the server and returns it, or adds
401 * a suffix to it in order to avoid the server file is overwritten.
402 *
403 * @param string
404 * @return
405 */
406 private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) throws Exception {
407 boolean check = existsFile(wc, remotePath);
408 if (!check) {
409 return remotePath;
410 }
411
412 int pos = remotePath.lastIndexOf(".");
413 String suffix = "";
414 String extension = "";
415 if (pos >= 0) {
416 extension = remotePath.substring(pos + 1);
417 remotePath = remotePath.substring(0, pos);
418 }
419 int count = 2;
420 do {
421 suffix = " (" + count + ")";
422 if (pos >= 0) {
423 check = existsFile(wc, remotePath + suffix + "." + extension);
424 }
425 else {
426 check = existsFile(wc, remotePath + suffix);
427 }
428 count++;
429 } while (check);
430
431 if (pos >= 0) {
432 return remotePath + suffix + "." + extension;
433 } else {
434 return remotePath + suffix;
435 }
436 }
437
438 private boolean existsFile(OwnCloudClient client, String remotePath){
439 ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false);
440 RemoteOperationResult result = existsOperation.execute(client);
441 return result.isSuccess();
442 }
443
444 public void cancel() {
445 mUploadOperation.cancel();
446 }
447 }