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