Get file mimeType and pass it for being checked on UploadFileOperation class. Take...
[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
54
55 /**
56 * Remote operation performing the upload of a file to an ownCloud server
57 *
58 * @author David A. Velasco
59 */
60 public class UploadFileOperation extends RemoteOperation {
61
62 private static final String TAG = UploadFileOperation.class.getSimpleName();
63
64 private static final String URI_CONTENT_SCHEME = "content://";
65 private static final String MIME_TYPE_PDF = "application/pdf";
66 private static final String FILE_EXTENSION_PDF = ".pdf";
67
68 private Account mAccount;
69 private OCFile mFile;
70 private OCFile mOldFile;
71 private String mRemotePath = null;
72 private boolean mChunked = false;
73 private boolean mIsInstant = false;
74 private boolean mRemoteFolderToBeCreated = false;
75 private boolean mForceOverwrite = false;
76 private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
77 private boolean mWasRenamed = false;
78 private String mOriginalFileName = null;
79 private String mOriginalStoragePath = null;
80 PutMethod mPutMethod = null;
81 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
82 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
83 private Context mContext;
84
85 private UploadRemoteFileOperation mUploadOperation;
86
87 protected RequestEntity mEntity = null;
88
89
90 public UploadFileOperation( Account account,
91 OCFile file,
92 boolean chunked,
93 boolean isInstant,
94 boolean forceOverwrite,
95 int localBehaviour,
96 Context context) {
97 if (account == null)
98 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation 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) && 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) + mFile.getRemotePath();
228
229 if (isPdfFileFromContentProviderWithoutExtension()){
230 temporalPath += FILE_EXTENSION_PDF;
231 mFile.setRemotePath(mFile.getRemotePath() + FILE_EXTENSION_PDF);
232 }
233
234 mFile.setStoragePath(temporalPath);
235 temporalFile = new File(temporalPath);
236
237 File temporalParent = temporalFile.getParentFile();
238 temporalParent.mkdirs();
239 if (!temporalParent.isDirectory()) {
240 throw new IOException("Unexpected error: parent directory could not be created");
241 }
242 temporalFile.createNewFile();
243 if (!temporalFile.isFile()) {
244 throw new IOException("Unexpected error: target file could not be created");
245 }
246
247 InputStream in = null;
248 OutputStream out = null;
249
250 try {
251
252 // In case document provider schema as 'content://'
253 if (mOriginalStoragePath.startsWith(URI_CONTENT_SCHEME)) {
254
255 Uri uri = Uri.parse(mOriginalStoragePath);
256
257 in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
258 out = new FileOutputStream(temporalFile);
259
260 int nRead;
261 byte[] data = new byte[16384];
262
263 while ((nRead = in.read(data, 0, data.length)) != -1) {
264 out.write(data, 0, nRead);
265 }
266
267 out.flush();
268
269 } else {
270 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
271 // weird
272 // but
273 // possible
274 // situation
275
276 in = new FileInputStream(originalFile);
277 out = new FileOutputStream(temporalFile);
278 byte[] buf = new byte[1024];
279 int len;
280 while ((len = in.read(buf)) > 0) {
281 out.write(buf, 0, len);
282 }
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 " + mOriginalStoragePath + " (ignoring)", e);
296 }
297 try {
298 if (out != null)
299 out.close();
300 } catch (Exception e) {
301 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
302 }
303 }
304 }
305 }
306 localCopyPassed = true;
307
308 /// perform the upload
309 if ( mChunked && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) {
310 mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
311 mFile.getMimetype());
312 } else {
313 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
314 mFile.getMimetype());
315 }
316 Iterator <OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
317 while (listener.hasNext()) {
318 mUploadOperation.addDatatransferProgressListener(listener.next());
319 }
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 } catch (Exception e) {
358 // TODO something cleaner with cancellations
359 if (mCancellationRequested.get()) {
360 result = new RemoteOperationResult(new OperationCancelledException());
361 } else {
362 result = new RemoteOperationResult(e);
363 }
364
365 } finally {
366 if (temporalFile != null && !originalFile.equals(temporalFile)) {
367 temporalFile.delete();
368 }
369 if (result.isSuccess()) {
370 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
371 } else {
372 if (result.getException() != null) {
373 String complement = "";
374 if (!nameCheckPassed) {
375 complement = " (while checking file existence in server)";
376 } else if (!localCopyPassed) {
377 complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
378 + ")";
379 }
380 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException());
381 } else {
382 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
383 }
384 }
385 }
386
387 return result;
388 }
389
390 private void createNewOCFile(String newRemotePath) {
391 // a new OCFile instance must be created for a new remote path
392 OCFile newFile = new OCFile(newRemotePath);
393 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
394 newFile.setFileLength(mFile.getFileLength());
395 newFile.setMimetype(mFile.getMimetype());
396 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
397 newFile.setModificationTimestampAtLastSyncForData(mFile.getModificationTimestampAtLastSyncForData());
398 // newFile.setEtag(mFile.getEtag())
399 newFile.setKeepInSync(mFile.keepInSync());
400 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
401 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
402 newFile.setStoragePath(mFile.getStoragePath());
403 newFile.setParentId(mFile.getParentId());
404 mOldFile = mFile;
405 mFile = newFile;
406 }
407
408 /**
409 * Checks if remotePath does not exist in the server and returns it, or adds
410 * a suffix to it in order to avoid the server file is overwritten.
411 *
412 * @param string
413 * @return
414 */
415 private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) throws Exception {
416 boolean check = existsFile(wc, remotePath);
417 if (!check) {
418 return remotePath;
419 }
420
421 int pos = remotePath.lastIndexOf(".");
422 String suffix = "";
423 String extension = "";
424 if (pos >= 0) {
425 extension = remotePath.substring(pos + 1);
426 remotePath = remotePath.substring(0, pos);
427 }
428 int count = 2;
429 do {
430 suffix = " (" + count + ")";
431 if (pos >= 0) {
432 check = existsFile(wc, remotePath + suffix + "." + extension);
433 }
434 else {
435 check = existsFile(wc, remotePath + suffix);
436 }
437 count++;
438 } while (check);
439
440 if (pos >= 0) {
441 return remotePath + suffix + "." + extension;
442 } else {
443 return remotePath + suffix;
444 }
445 }
446
447 private boolean existsFile(OwnCloudClient client, String remotePath){
448 ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false);
449 RemoteOperationResult result = existsOperation.execute(client);
450 return result.isSuccess();
451 }
452
453 public void cancel() {
454 mUploadOperation.cancel();
455 }
456
457 /**
458 * Checks if content provider, using the content:// scheme, returns a file with mime-type
459 * 'application/pdf' but file has not extension
460 * @return true if is needed to add the pdf file extension to the file
461 */
462 private boolean isPdfFileFromContentProviderWithoutExtension() {
463 return mOriginalStoragePath.startsWith(URI_CONTENT_SCHEME) &&
464 mFile.getMimetype().equals(MIME_TYPE_PDF) &&
465 !mFile.getFileName().endsWith(FILE_EXTENSION_PDF);
466 }
467 }