819d218fbce610becd444dd06d2d6ae6e24d79e5
[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 Account mAccount;
65 private OCFile mFile;
66 private OCFile mOldFile;
67 private String mRemotePath = null;
68 private boolean mChunked = false;
69 private boolean mIsInstant = false;
70 private boolean mRemoteFolderToBeCreated = false;
71 private boolean mForceOverwrite = false;
72 private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
73 private boolean mWasRenamed = false;
74 private String mOriginalFileName = null;
75 private String mOriginalStoragePath = null;
76 PutMethod mPutMethod = null;
77 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
78 private final 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 creation");
95 if (file == null)
96 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
97 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0) {
98 throw new IllegalArgumentException(
99 "Illegal file in UploadFileOperation; storage path invalid: "
100 + file.getStoragePath());
101 }
102
103 mAccount = account;
104 mFile = file;
105 mRemotePath = file.getRemotePath();
106 mChunked = chunked;
107 mIsInstant = isInstant;
108 mForceOverwrite = forceOverwrite;
109 mLocalBehaviour = localBehaviour;
110 mOriginalStoragePath = mFile.getStoragePath();
111 mOriginalFileName = mFile.getFileName();
112 mContext = context;
113 }
114
115 public Account getAccount() {
116 return mAccount;
117 }
118
119 public String getFileName() {
120 return mOriginalFileName;
121 }
122
123 public OCFile getFile() {
124 return mFile;
125 }
126
127 public OCFile getOldFile() {
128 return mOldFile;
129 }
130
131 public String getOriginalStoragePath() {
132 return mOriginalStoragePath;
133 }
134
135 public String getStoragePath() {
136 return mFile.getStoragePath();
137 }
138
139 public String getRemotePath() {
140 return mFile.getRemotePath();
141 }
142
143 public String getMimeType() {
144 return mFile.getMimetype();
145 }
146
147 public boolean isInstant() {
148 return mIsInstant;
149 }
150
151 public boolean isRemoteFolderToBeCreated() {
152 return mRemoteFolderToBeCreated;
153 }
154
155 public void setRemoteFolderToBeCreated() {
156 mRemoteFolderToBeCreated = true;
157 }
158
159 public boolean getForceOverwrite() {
160 return mForceOverwrite;
161 }
162
163 public boolean wasRenamed() {
164 return mWasRenamed;
165 }
166
167 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
168 return mDataTransferListeners;
169 }
170
171 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
172 synchronized (mDataTransferListeners) {
173 mDataTransferListeners.add(listener);
174 }
175 if (mEntity != null) {
176 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
177 }
178 }
179
180 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
181 synchronized (mDataTransferListeners) {
182 mDataTransferListeners.remove(listener);
183 }
184 if (mEntity != null) {
185 ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
186 }
187 }
188
189 @Override
190 protected RemoteOperationResult run(OwnCloudClient client) {
191 RemoteOperationResult result = null;
192 boolean localCopyPassed = false, nameCheckPassed = false;
193 File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
194 try {
195 // / rename the file to upload, if necessary
196 if (!mForceOverwrite) {
197 String remotePath = getAvailableRemotePath(client, mRemotePath);
198 mWasRenamed = !remotePath.equals(mRemotePath);
199 if (mWasRenamed) {
200 createNewOCFile(remotePath);
201 }
202 }
203 nameCheckPassed = true;
204
205 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
206 // not
207 // before
208 // getAvailableRemotePath()
209 // !!!
210 expectedFile = new File(expectedPath);
211
212 // check location of local file; if not the expected, copy to a
213 // temporal file before upload (if COPY is the expected behaviour)
214 if (!mOriginalStoragePath.equals(expectedPath) && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
215
216 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
217 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
218 return result; // error condition when the file should be
219 // copied
220
221 } else {
222
223 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
224 mFile.setStoragePath(temporalPath);
225 temporalFile = new File(temporalPath);
226
227 File temporalParent = temporalFile.getParentFile();
228 temporalParent.mkdirs();
229 if (!temporalParent.isDirectory()) {
230 throw new IOException("Unexpected error: parent directory could not be created");
231 }
232 temporalFile.createNewFile();
233 if (!temporalFile.isFile()) {
234 throw new IOException("Unexpected error: target file could not be created");
235 }
236
237 InputStream in = null;
238 OutputStream out = null;
239
240 try {
241
242 if (mOriginalStoragePath.startsWith("content://")) {
243
244 Uri uri = Uri.parse(mOriginalStoragePath);
245
246 in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
247 out = new FileOutputStream(temporalFile);
248
249 int nRead;
250 byte[] data = new byte[16384];
251
252 while ((nRead = in.read(data, 0, data.length)) != -1) {
253 out.write(data, 0, nRead);
254 }
255
256 out.flush();
257
258 } else {
259 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
260 // weird
261 // but
262 // possible
263 // situation
264
265 in = new FileInputStream(originalFile);
266 out = new FileOutputStream(temporalFile);
267 byte[] buf = new byte[1024];
268 int len;
269 while ((len = in.read(buf)) > 0) {
270 out.write(buf, 0, len);
271 }
272 }
273 }
274
275 } catch (Exception e) {
276 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
277 return result;
278
279 } finally {
280 try {
281 if (in != null)
282 in.close();
283 } catch (Exception e) {
284 Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e);
285 }
286 try {
287 if (out != null)
288 out.close();
289 } catch (Exception e) {
290 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
291 }
292 }
293 }
294 }
295 localCopyPassed = true;
296
297 /// perform the upload
298 if ( mChunked && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) {
299 mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
300 mFile.getMimetype());
301 } else {
302 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
303 mFile.getMimetype());
304 }
305 Iterator <OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
306 while (listener.hasNext()) {
307 mUploadOperation.addDatatransferProgressListener(listener.next());
308 }
309 result = mUploadOperation.execute(client);
310
311 /// move local temporal file or original file to its corresponding
312 // location in the ownCloud local folder
313 if (result.isSuccess()) {
314 if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
315 mFile.setStoragePath(null);
316
317 } else {
318 mFile.setStoragePath(expectedPath);
319 File fileToMove = null;
320 if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
321 // ; see where temporalFile was
322 // set
323 fileToMove = temporalFile;
324 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
325 fileToMove = originalFile;
326 }
327 if (!expectedFile.equals(fileToMove)) {
328 File expectedFolder = expectedFile.getParentFile();
329 expectedFolder.mkdirs();
330 if (!expectedFolder.isDirectory() || !fileToMove.renameTo(expectedFile)) {
331 mFile.setStoragePath(null); // forget the local file
332 // by now, treat this as a success; the file was
333 // uploaded; the user won't like that the local file
334 // is not linked, but this should be a very rare
335 // fail;
336 // the best option could be show a warning message
337 // (but not a fail)
338 // result = new
339 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
340 // return result;
341 }
342 }
343 }
344 }
345
346 } catch (Exception e) {
347 // TODO something cleaner with cancellations
348 if (mCancellationRequested.get()) {
349 result = new RemoteOperationResult(new OperationCancelledException());
350 } else {
351 result = new RemoteOperationResult(e);
352 }
353
354 } finally {
355 if (temporalFile != null && !originalFile.equals(temporalFile)) {
356 temporalFile.delete();
357 }
358 if (result.isSuccess()) {
359 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
360 } else {
361 if (result.getException() != null) {
362 String complement = "";
363 if (!nameCheckPassed) {
364 complement = " (while checking file existence in server)";
365 } else if (!localCopyPassed) {
366 complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
367 + ")";
368 }
369 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException());
370 } else {
371 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
372 }
373 }
374 }
375
376 return result;
377 }
378
379 private void createNewOCFile(String newRemotePath) {
380 // a new OCFile instance must be created for a new remote path
381 OCFile newFile = new OCFile(newRemotePath);
382 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
383 newFile.setFileLength(mFile.getFileLength());
384 newFile.setMimetype(mFile.getMimetype());
385 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
386 newFile.setModificationTimestampAtLastSyncForData(mFile.getModificationTimestampAtLastSyncForData());
387 // newFile.setEtag(mFile.getEtag())
388 newFile.setKeepInSync(mFile.keepInSync());
389 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
390 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
391 newFile.setStoragePath(mFile.getStoragePath());
392 newFile.setParentId(mFile.getParentId());
393 mOldFile = mFile;
394 mFile = newFile;
395 }
396
397 /**
398 * Checks if remotePath does not exist in the server and returns it, or adds
399 * a suffix to it in order to avoid the server file is overwritten.
400 *
401 * @param string
402 * @return
403 */
404 private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) throws Exception {
405 boolean check = existsFile(wc, remotePath);
406 if (!check) {
407 return remotePath;
408 }
409
410 int pos = remotePath.lastIndexOf(".");
411 String suffix = "";
412 String extension = "";
413 if (pos >= 0) {
414 extension = remotePath.substring(pos + 1);
415 remotePath = remotePath.substring(0, pos);
416 }
417 int count = 2;
418 do {
419 suffix = " (" + count + ")";
420 if (pos >= 0) {
421 check = existsFile(wc, remotePath + suffix + "." + extension);
422 }
423 else {
424 check = existsFile(wc, remotePath + suffix);
425 }
426 count++;
427 } while (check);
428
429 if (pos >= 0) {
430 return remotePath + suffix + "." + extension;
431 } else {
432 return remotePath + suffix;
433 }
434 }
435
436 private boolean existsFile(OwnCloudClient client, String remotePath){
437 ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false);
438 RemoteOperationResult result = existsOperation.execute(client);
439 return result.isSuccess();
440 }
441
442 public void cancel() {
443 mUploadOperation.cancel();
444 }
445 }