OC-2332: rewrite getAvailableRemotePath from UpdateFileOperation, using ExistenceCehe...
[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.Set;
28 import java.util.concurrent.atomic.AtomicBoolean;
29
30 import org.apache.commons.httpclient.HttpException;
31 import org.apache.commons.httpclient.methods.PutMethod;
32 import org.apache.commons.httpclient.methods.RequestEntity;
33 import org.apache.http.HttpStatus;
34
35 import com.owncloud.android.datamodel.OCFile;
36 import com.owncloud.android.files.services.FileUploader;
37 import com.owncloud.android.oc_framework.network.ProgressiveDataTransferer;
38 import com.owncloud.android.oc_framework.network.webdav.FileRequestEntity;
39 import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener;
40 import com.owncloud.android.oc_framework.network.webdav.WebdavClient;
41 import com.owncloud.android.oc_framework.network.webdav.WebdavUtils;
42 import com.owncloud.android.oc_framework.operations.OperationCancelledException;
43 import com.owncloud.android.oc_framework.operations.RemoteOperation;
44 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
45 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
46 import com.owncloud.android.oc_framework.operations.remote.ExistenceCheckRemoteOperation;
47 import com.owncloud.android.utils.FileStorageUtils;
48 import com.owncloud.android.utils.Log_OC;
49
50 import android.accounts.Account;
51 import android.content.Context;
52
53
54 /**
55 * Remote operation performing the upload of a file to an ownCloud server
56 *
57 * @author David A. Velasco
58 */
59 public class UploadFileOperation extends RemoteOperation {
60
61 private static final String TAG = UploadFileOperation.class.getSimpleName();
62
63 private Account mAccount;
64 private OCFile mFile;
65 private OCFile mOldFile;
66 private String mRemotePath = null;
67 private boolean mIsInstant = false;
68 private boolean mRemoteFolderToBeCreated = false;
69 private boolean mForceOverwrite = false;
70 private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
71 private boolean mWasRenamed = false;
72 private String mOriginalFileName = null;
73 private String mOriginalStoragePath = null;
74 PutMethod mPutMethod = null;
75 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
76 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
77 private Context mContext;
78
79 protected RequestEntity mEntity = null;
80
81
82 public UploadFileOperation( Account account,
83 OCFile file,
84 boolean isInstant,
85 boolean forceOverwrite,
86 int localBehaviour,
87 Context context) {
88 if (account == null)
89 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
90 if (file == null)
91 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
92 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0
93 || !(new File(file.getStoragePath()).exists())) {
94 throw new IllegalArgumentException(
95 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
96 + file.getStoragePath());
97 }
98
99 mAccount = account;
100 mFile = file;
101 mRemotePath = file.getRemotePath();
102 mIsInstant = isInstant;
103 mForceOverwrite = forceOverwrite;
104 mLocalBehaviour = localBehaviour;
105 mOriginalStoragePath = mFile.getStoragePath();
106 mOriginalFileName = mFile.getFileName();
107 mContext = context;
108 }
109
110 public Account getAccount() {
111 return mAccount;
112 }
113
114 public String getFileName() {
115 return mOriginalFileName;
116 }
117
118 public OCFile getFile() {
119 return mFile;
120 }
121
122 public OCFile getOldFile() {
123 return mOldFile;
124 }
125
126 public String getOriginalStoragePath() {
127 return mOriginalStoragePath;
128 }
129
130 public String getStoragePath() {
131 return mFile.getStoragePath();
132 }
133
134 public String getRemotePath() {
135 return mFile.getRemotePath();
136 }
137
138 public String getMimeType() {
139 return mFile.getMimetype();
140 }
141
142 public boolean isInstant() {
143 return mIsInstant;
144 }
145
146 public boolean isRemoteFolderToBeCreated() {
147 return mRemoteFolderToBeCreated;
148 }
149
150 public void setRemoteFolderToBeCreated() {
151 mRemoteFolderToBeCreated = true;
152 }
153
154 public boolean getForceOverwrite() {
155 return mForceOverwrite;
156 }
157
158 public boolean wasRenamed() {
159 return mWasRenamed;
160 }
161
162 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
163 return mDataTransferListeners;
164 }
165
166 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
167 synchronized (mDataTransferListeners) {
168 mDataTransferListeners.add(listener);
169 }
170 if (mEntity != null) {
171 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener);
172 }
173 }
174
175 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
176 synchronized (mDataTransferListeners) {
177 mDataTransferListeners.remove(listener);
178 }
179 if (mEntity != null) {
180 ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener);
181 }
182 }
183
184 @Override
185 protected RemoteOperationResult run(WebdavClient client) {
186 RemoteOperationResult result = null;
187 boolean localCopyPassed = false, nameCheckPassed = false;
188 File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
189 try {
190 // / rename the file to upload, if necessary
191 if (!mForceOverwrite) {
192 String remotePath = getAvailableRemotePath(client, mRemotePath);
193 mWasRenamed = !remotePath.equals(mRemotePath);
194 if (mWasRenamed) {
195 createNewOCFile(remotePath);
196 }
197 }
198 nameCheckPassed = true;
199
200 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
201 // not
202 // before
203 // getAvailableRemotePath()
204 // !!!
205 expectedFile = new File(expectedPath);
206
207 // check location of local file; if not the expected, copy to a
208 // temporal file before upload (if COPY is the expected behaviour)
209 if (!mOriginalStoragePath.equals(expectedPath) && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {
210
211 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
212 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
213 return result; // error condition when the file should be
214 // copied
215
216 } else {
217 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
218 mFile.setStoragePath(temporalPath);
219 temporalFile = new File(temporalPath);
220 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
221 // weird
222 // but
223 // possible
224 // situation
225 InputStream in = null;
226 OutputStream out = null;
227 try {
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 in = new FileInputStream(originalFile);
238 out = new FileOutputStream(temporalFile);
239 byte[] buf = new byte[1024];
240 int len;
241 while ((len = in.read(buf)) > 0) {
242 out.write(buf, 0, len);
243 }
244
245 } catch (Exception e) {
246 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
247 return result;
248
249 } finally {
250 try {
251 if (in != null)
252 in.close();
253 } catch (Exception e) {
254 Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e);
255 }
256 try {
257 if (out != null)
258 out.close();
259 } catch (Exception e) {
260 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
261 }
262 }
263 }
264 }
265 }
266 localCopyPassed = true;
267
268 // / perform the upload
269 synchronized (mCancellationRequested) {
270 if (mCancellationRequested.get()) {
271 throw new OperationCancelledException();
272 } else {
273 mPutMethod = new PutMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
274 }
275 }
276 int status = uploadFile(client);
277
278 // / move local temporal file or original file to its corresponding
279 // location in the ownCloud local folder
280 if (isSuccess(status)) {
281 if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
282 mFile.setStoragePath(null);
283
284 } else {
285 mFile.setStoragePath(expectedPath);
286 File fileToMove = null;
287 if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
288 // ; see where temporalFile was
289 // set
290 fileToMove = temporalFile;
291 } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
292 fileToMove = originalFile;
293 }
294 if (!expectedFile.equals(fileToMove)) {
295 File expectedFolder = expectedFile.getParentFile();
296 expectedFolder.mkdirs();
297 if (!expectedFolder.isDirectory() || !fileToMove.renameTo(expectedFile)) {
298 mFile.setStoragePath(null); // forget the local file
299 // by now, treat this as a success; the file was
300 // uploaded; the user won't like that the local file
301 // is not linked, but this should be a very rare
302 // fail;
303 // the best option could be show a warning message
304 // (but not a fail)
305 // result = new
306 // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
307 // return result;
308 }
309 }
310 }
311 }
312
313 result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
314
315 } catch (Exception e) {
316 // TODO something cleaner with cancellations
317 if (mCancellationRequested.get()) {
318 result = new RemoteOperationResult(new OperationCancelledException());
319 } else {
320 result = new RemoteOperationResult(e);
321 }
322
323 } finally {
324 if (temporalFile != null && !originalFile.equals(temporalFile)) {
325 temporalFile.delete();
326 }
327 if (result.isSuccess()) {
328 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
329 } else {
330 if (result.getException() != null) {
331 String complement = "";
332 if (!nameCheckPassed) {
333 complement = " (while checking file existence in server)";
334 } else if (!localCopyPassed) {
335 complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
336 + ")";
337 }
338 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException());
339 } else {
340 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
341 }
342 }
343 }
344
345 return result;
346 }
347
348 private void createNewOCFile(String newRemotePath) {
349 // a new OCFile instance must be created for a new remote path
350 OCFile newFile = new OCFile(newRemotePath);
351 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
352 newFile.setFileLength(mFile.getFileLength());
353 newFile.setMimetype(mFile.getMimetype());
354 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
355 newFile.setModificationTimestampAtLastSyncForData(mFile.getModificationTimestampAtLastSyncForData());
356 // newFile.setEtag(mFile.getEtag())
357 newFile.setKeepInSync(mFile.keepInSync());
358 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
359 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
360 newFile.setStoragePath(mFile.getStoragePath());
361 newFile.setParentId(mFile.getParentId());
362 mOldFile = mFile;
363 mFile = newFile;
364 }
365
366 public boolean isSuccess(int status) {
367 return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT));
368 }
369
370 protected int uploadFile(WebdavClient client) throws HttpException, IOException, OperationCancelledException {
371 int status = -1;
372 try {
373 File f = new File(mFile.getStoragePath());
374 mEntity = new FileRequestEntity(f, getMimeType());
375 synchronized (mDataTransferListeners) {
376 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners);
377 }
378 mPutMethod.setRequestEntity(mEntity);
379 status = client.executeMethod(mPutMethod);
380 client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
381
382 } finally {
383 mPutMethod.releaseConnection(); // let the connection available for
384 // other methods
385 }
386 return status;
387 }
388
389 /**
390 * Checks if remotePath does not exist in the server and returns it, or adds
391 * a suffix to it in order to avoid the server file is overwritten.
392 *
393 * @param string
394 * @return
395 */
396 private String getAvailableRemotePath(WebdavClient wc, String remotePath) throws Exception {
397 boolean check = existsFile(wc, remotePath);
398 if (!check) {
399 return remotePath;
400 }
401
402 int pos = remotePath.lastIndexOf(".");
403 String suffix = "";
404 String extension = "";
405 if (pos >= 0) {
406 extension = remotePath.substring(pos + 1);
407 remotePath = remotePath.substring(0, pos);
408 }
409 int count = 2;
410 do {
411 suffix = " (" + count + ")";
412 if (pos >= 0) {
413 check = existsFile(wc, remotePath + suffix + "." + extension);
414 }
415 else {
416 check = existsFile(wc, remotePath + suffix);
417 }
418 count++;
419 } while (check);
420
421 if (pos >= 0) {
422 return remotePath + suffix + "." + extension;
423 } else {
424 return remotePath + suffix;
425 }
426 }
427
428 private boolean existsFile(WebdavClient client, String remotePath){
429 ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false);
430 RemoteOperationResult result = existsOperation.execute(client);
431 return result.isSuccess();
432 }
433
434 public void cancel() {
435 synchronized (mCancellationRequested) {
436 mCancellationRequested.set(true);
437 if (mPutMethod != null)
438 mPutMethod.abort();
439 }
440 }
441
442 }