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