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