Cancellation in uploads and access to details view pressing the status notification
[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.IOException;
23 import java.util.HashSet;
24 import java.util.Set;
25 import java.util.concurrent.atomic.AtomicBoolean;
26
27 import org.apache.commons.httpclient.HttpException;
28 import org.apache.commons.httpclient.methods.PutMethod;
29 import org.apache.http.HttpStatus;
30
31 import com.owncloud.android.datamodel.OCFile;
32 import com.owncloud.android.operations.RemoteOperation;
33 import com.owncloud.android.operations.RemoteOperationResult;
34
35 import eu.alefzero.webdav.FileRequestEntity;
36 import eu.alefzero.webdav.OnDatatransferProgressListener;
37 import eu.alefzero.webdav.WebdavClient;
38 import eu.alefzero.webdav.WebdavUtils;
39 import android.accounts.Account;
40 import android.util.Log;
41
42 /**
43 * Remote operation performing the upload of a file to an ownCloud server
44 *
45 * @author David A. Velasco
46 */
47 public class UploadFileOperation extends RemoteOperation {
48
49 private static final String TAG = UploadFileOperation.class.getCanonicalName();
50
51 private Account mAccount;
52 private OCFile mFile;
53 private String mRemotePath = null;
54 private boolean mIsInstant = false;
55 private boolean mForceOverwrite = false;
56 PutMethod mPutMethod = null;
57 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
58 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
59
60
61 public UploadFileOperation( Account account,
62 OCFile file,
63 boolean isInstant,
64 boolean forceOverwrite) {
65 if (account == null)
66 throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation creation");
67 if (file == null)
68 throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
69 if (file.getStoragePath() == null || file.getStoragePath().length() <= 0 || !(new File(file.getStoragePath()).exists())) {
70 throw new IllegalArgumentException("Illegal file in UploadFileOperation; storage path invalid or file not found: " + file.getStoragePath());
71 }
72
73 mAccount = account;
74 mFile = file;
75 mRemotePath = file.getRemotePath();
76 mIsInstant = isInstant;
77 mForceOverwrite = forceOverwrite;
78 }
79
80
81 public Account getAccount() {
82 return mAccount;
83 }
84
85 public OCFile getFile() {
86 return mFile;
87 }
88
89 public String getStoragePath() {
90 return mFile.getStoragePath();
91 }
92
93 public String getRemotePath() {
94 //return mFile.getRemotePath(); // DON'T MAKE THIS ; the remotePath used can be different to mFile.getRemotePath() if mForceOverwrite is 'false'; see run(...)
95 return mRemotePath;
96 }
97
98 public String getMimeType() {
99 return mFile.getMimetype();
100 }
101
102 public boolean isInstant() {
103 return mIsInstant;
104 }
105
106 public boolean getForceOverwrite() {
107 return mForceOverwrite;
108 }
109
110
111 public Set<OnDatatransferProgressListener> getDataTransferListeners() {
112 return mDataTransferListeners;
113 }
114
115 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
116 mDataTransferListeners.add(listener);
117 }
118
119
120 @Override
121 protected RemoteOperationResult run(WebdavClient client) {
122 RemoteOperationResult result = null;
123 boolean nameCheckPassed = false;
124 try {
125 /// rename the file to upload, if necessary
126 if (!mForceOverwrite) {
127 mRemotePath = getAvailableRemotePath(client, mRemotePath);
128 }
129
130 /// perform the upload
131 nameCheckPassed = true;
132 synchronized(mCancellationRequested) {
133 if (mCancellationRequested.get()) {
134 throw new OperationCancelledException();
135 } else {
136 mPutMethod = new PutMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
137 }
138 }
139 int status = uploadFile(client);
140 result = new RemoteOperationResult(isSuccess(status), status);
141 Log.i(TAG, "Upload of " + mFile.getStoragePath() + " to " + mRemotePath + ": " + result.getLogMessage());
142
143 } catch (Exception e) {
144 // TODO something cleaner
145 if (mCancellationRequested.get()) {
146 result = new RemoteOperationResult(new OperationCancelledException());
147 } else {
148 result = new RemoteOperationResult(e);
149 }
150 Log.e(TAG, "Upload of " + mFile.getStoragePath() + " to " + mRemotePath + ": " + result.getLogMessage() + (nameCheckPassed?"":" (while checking file existence in server)"), result.getException());
151 }
152
153 return result;
154 }
155
156
157 public boolean isSuccess(int status) {
158 return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT));
159 }
160
161
162 protected int uploadFile(WebdavClient client) throws HttpException, IOException, OperationCancelledException {
163 int status = -1;
164 try {
165 File f = new File(mFile.getStoragePath());
166 FileRequestEntity entity = new FileRequestEntity(f, getMimeType());
167 entity.addOnDatatransferProgressListeners(mDataTransferListeners);
168 mPutMethod.setRequestEntity(entity);
169 status = client.executeMethod(mPutMethod);
170 client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
171
172 } finally {
173 mPutMethod.releaseConnection(); // let the connection available for other methods
174 }
175 return status;
176 }
177
178 /**
179 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
180 * file is overwritten.
181 *
182 * @param string
183 * @return
184 */
185 private String getAvailableRemotePath(WebdavClient wc, String remotePath) throws Exception {
186 boolean check = wc.existsFile(remotePath);
187 if (!check) {
188 return remotePath;
189 }
190
191 int pos = remotePath.lastIndexOf(".");
192 String suffix = "";
193 String extension = "";
194 if (pos >= 0) {
195 extension = remotePath.substring(pos+1);
196 remotePath = remotePath.substring(0, pos);
197 }
198 int count = 2;
199 do {
200 suffix = " (" + count + ")";
201 if (pos >= 0)
202 check = wc.existsFile(remotePath + suffix + "." + extension);
203 else
204 check = wc.existsFile(remotePath + suffix);
205 count++;
206 } while (check);
207
208 if (pos >=0) {
209 return remotePath + suffix + "." + extension;
210 } else {
211 return remotePath + suffix;
212 }
213 }
214
215
216 public void cancel() {
217 synchronized(mCancellationRequested) {
218 mCancellationRequested.set(true);
219 if (mPutMethod != null)
220 mPutMethod.abort();
221 }
222 }
223
224 }