26b05159d918b00169037e8fb1359d413ac7d111
[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.operations.OperationCancelledException;
42 import com.owncloud.android.oc_framework.operations.RemoteOperation;
43 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
44 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
45 import com.owncloud.android.oc_framework.operations.remote.ExistenceCheckRemoteOperation;
46 import com.owncloud.android.oc_framework.operations.remote.UploadRemoteFileOperation;
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 OnDatatransferProgressListener mDataTransferListener;
76 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
77 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
78 private Context mContext;
79
80 private UploadRemoteFileOperation mUploadOperation;
81
82 protected RequestEntity mEntity = null;
83
84
85 public UploadFileOperation( Account account,
86 OCFile file,
87 boolean isInstant,
88 boolean forceOverwrite,
89 int localBehaviour,
90 Context context,
91 OnDatatransferProgressListener listener) {
92 if (account == null)
93 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
94 if (file == null)
95 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
96 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0
97 || !(new File(file.getStoragePath()).exists())) {
98 throw new IllegalArgumentException(
99 "Illegal file in UploadFileOperation; storage path invalid or file not found: "
100 + file.getStoragePath());
101 }
102
103 mAccount = account;
104 mFile = file;
105 mRemotePath = file.getRemotePath();
106 mIsInstant = isInstant;
107 mForceOverwrite = forceOverwrite;
108 mLocalBehaviour = localBehaviour;
109 mOriginalStoragePath = mFile.getStoragePath();
110 mOriginalFileName = mFile.getFileName();
111 mContext = context;
112 mDataTransferListener = listener;
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(WebdavClient 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 String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
223 mFile.setStoragePath(temporalPath);
224 temporalFile = new File(temporalPath);
225 if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
226 // weird
227 // but
228 // possible
229 // situation
230 InputStream in = null;
231 OutputStream out = null;
232 try {
233 File temporalParent = temporalFile.getParentFile();
234 temporalParent.mkdirs();
235 if (!temporalParent.isDirectory()) {
236 throw new IOException("Unexpected error: parent directory could not be created");
237 }
238 temporalFile.createNewFile();
239 if (!temporalFile.isFile()) {
240 throw new IOException("Unexpected error: target file could not be created");
241 }
242 in = new FileInputStream(originalFile);
243 out = new FileOutputStream(temporalFile);
244 byte[] buf = new byte[1024];
245 int len;
246 while ((len = in.read(buf)) > 0) {
247 out.write(buf, 0, len);
248 }
249
250 } catch (Exception e) {
251 result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
252 return result;
253
254 } finally {
255 try {
256 if (in != null)
257 in.close();
258 } catch (Exception e) {
259 Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath + " (ignoring)", e);
260 }
261 try {
262 if (out != null)
263 out.close();
264 } catch (Exception e) {
265 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
266 }
267 }
268 }
269 }
270 }
271 localCopyPassed = true;
272
273 /// perform the upload
274 mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
275 mFile.getMimetype());
276 result = mUploadOperation.execute(client);
277
278 /// move local temporal file or original file to its corresponding
279 // location in the ownCloud local folder
280 if (result.isSuccess()) {
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 } catch (Exception e) {
314 // TODO something cleaner with cancellations
315 if (mCancellationRequested.get()) {
316 result = new RemoteOperationResult(new OperationCancelledException());
317 } else {
318 result = new RemoteOperationResult(e);
319 }
320
321 } finally {
322 if (temporalFile != null && !originalFile.equals(temporalFile)) {
323 temporalFile.delete();
324 }
325 if (result.isSuccess()) {
326 Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
327 } else {
328 if (result.getException() != null) {
329 String complement = "";
330 if (!nameCheckPassed) {
331 complement = " (while checking file existence in server)";
332 } else if (!localCopyPassed) {
333 complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
334 + ")";
335 }
336 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage() + complement, result.getException());
337 } else {
338 Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
339 }
340 }
341 }
342
343 return result;
344 }
345
346 private void createNewOCFile(String newRemotePath) {
347 // a new OCFile instance must be created for a new remote path
348 OCFile newFile = new OCFile(newRemotePath);
349 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
350 newFile.setFileLength(mFile.getFileLength());
351 newFile.setMimetype(mFile.getMimetype());
352 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
353 newFile.setModificationTimestampAtLastSyncForData(mFile.getModificationTimestampAtLastSyncForData());
354 // newFile.setEtag(mFile.getEtag())
355 newFile.setKeepInSync(mFile.keepInSync());
356 newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
357 newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
358 newFile.setStoragePath(mFile.getStoragePath());
359 newFile.setParentId(mFile.getParentId());
360 mOldFile = mFile;
361 mFile = newFile;
362 }
363
364 public boolean isSuccess(int status) {
365 return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT));
366 }
367
368 protected int uploadFile(WebdavClient client) throws HttpException, IOException, OperationCancelledException {
369 int status = -1;
370 try {
371 File f = new File(mFile.getStoragePath());
372 mEntity = new FileRequestEntity(f, getMimeType());
373 synchronized (mDataTransferListeners) {
374 ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners);
375 }
376 mPutMethod.setRequestEntity(mEntity);
377 status = client.executeMethod(mPutMethod);
378 client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
379
380 } finally {
381 mPutMethod.releaseConnection(); // let the connection available for
382 // other methods
383 }
384 return status;
385 }
386
387 /**
388 * Checks if remotePath does not exist in the server and returns it, or adds
389 * a suffix to it in order to avoid the server file is overwritten.
390 *
391 * @param string
392 * @return
393 */
394 private String getAvailableRemotePath(WebdavClient wc, String remotePath) throws Exception {
395 boolean check = existsFile(wc, remotePath);
396 if (!check) {
397 return remotePath;
398 }
399
400 int pos = remotePath.lastIndexOf(".");
401 String suffix = "";
402 String extension = "";
403 if (pos >= 0) {
404 extension = remotePath.substring(pos + 1);
405 remotePath = remotePath.substring(0, pos);
406 }
407 int count = 2;
408 do {
409 suffix = " (" + count + ")";
410 if (pos >= 0) {
411 check = existsFile(wc, remotePath + suffix + "." + extension);
412 }
413 else {
414 check = existsFile(wc, remotePath + suffix);
415 }
416 count++;
417 } while (check);
418
419 if (pos >= 0) {
420 return remotePath + suffix + "." + extension;
421 } else {
422 return remotePath + suffix;
423 }
424 }
425
426 private boolean existsFile(WebdavClient client, String remotePath){
427 ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false);
428 RemoteOperationResult result = existsOperation.execute(client);
429 return result.isSuccess();
430 }
431
432 public void cancel() {
433 mUploadOperation.cancel();
434 }
435
436 }