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