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