Rename and remove operations connected to the contextual menu over items at the list...
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / RenameFileOperation.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
24 import org.apache.jackrabbit.webdav.client.methods.DavMethodBase;
25 //import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
26
27 import android.util.Log;
28
29 import com.owncloud.android.datamodel.DataStorageManager;
30 import com.owncloud.android.datamodel.OCFile;
31 import com.owncloud.android.files.services.FileDownloader;
32 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
33
34 import eu.alefzero.webdav.WebdavClient;
35 import eu.alefzero.webdav.WebdavUtils;
36
37 /**
38 * Remote operation performing the rename of a remote file (or folder?) in the ownCloud server.
39 *
40 * @author David A. Velasco
41 */
42 public class RenameFileOperation extends RemoteOperation {
43
44 private static final String TAG = RenameFileOperation.class.getSimpleName();
45
46 private static final int RENAME_READ_TIMEOUT = 10000;
47 private static final int RENAME_CONNECTION_TIMEOUT = 5000;
48
49
50 private OCFile mFile;
51 private String mNewName;
52 private DataStorageManager mStorageManager;
53
54
55 /**
56 * Constructor
57 *
58 * @param file OCFile instance describing the remote file or folder to rename
59 * @param newName New name to set as the name of file.
60 * @param storageManager Reference to the local database corresponding to the account where the file is contained.
61 */
62 public RenameFileOperation(OCFile file, String newName, DataStorageManager storageManager) {
63 mFile = file;
64 mNewName = newName;
65 mStorageManager = storageManager;
66 }
67
68 public OCFile getFile() {
69 return mFile;
70 }
71
72
73 /**
74 * Performs the rename operation.
75 *
76 * @param client Client object to communicate with the remote ownCloud server.
77 */
78 @Override
79 protected RemoteOperationResult run(WebdavClient client) {
80 RemoteOperationResult result = null;
81
82 LocalMoveMethod move = null;
83 //MoveMethod move = null; // TODO find out why not use this
84 String newRemotePath = null;
85 try {
86 if (mNewName.equals(mFile.getFileName())) {
87 return new RemoteOperationResult(ResultCode.OK);
88 }
89
90 newRemotePath = (new File(mFile.getRemotePath())).getParent() + mNewName;
91
92 // check if the new name is valid in the local file system
93 if (!isValidNewName()) {
94 return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
95 }
96
97 // check if a remote file with the new name already exists
98 if (client.existsFile(newRemotePath)) {
99 return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
100 }
101 /*move = new MoveMethod( client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()),
102 client.getBaseUri() + WebdavUtils.encodePath(newRemotePath),
103 false);*/
104 move = new LocalMoveMethod( client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()),
105 client.getBaseUri() + WebdavUtils.encodePath(newRemotePath));
106 int status = client.executeMethod(move, RENAME_READ_TIMEOUT, RENAME_CONNECTION_TIMEOUT);
107 if (move.succeeded()) {
108
109 // create new OCFile instance for the renamed file
110 OCFile newFile = obtainUpdatedFile();
111 OCFile oldFile = mFile;
112 mFile = newFile;
113
114 // try to rename the local copy of the file
115 if (oldFile.isDown()) {
116 File f = new File(oldFile.getStoragePath());
117 String newStoragePath = f.getParent() + mNewName;
118 if (f.renameTo(new File(newStoragePath))) {
119 mFile.setStoragePath(newStoragePath);
120 }
121 // else - NOTHING: the link to the local file is kept although the local name can't be updated
122 // TODO - study conditions when this could be a problem
123 }
124
125 mStorageManager.removeFile(oldFile, false);
126 mStorageManager.saveFile(mFile);
127
128 }
129
130 move.getResponseBodyAsString(); // exhaust response, although not interesting
131 result = new RemoteOperationResult(move.succeeded(), status);
132 Log.i(TAG, "Rename " + mFile.getRemotePath() + " to " + newRemotePath + ": " + result.getLogMessage());
133
134 } catch (Exception e) {
135 result = new RemoteOperationResult(e);
136 Log.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((newRemotePath==null) ? mNewName : newRemotePath) + ": " + result.getLogMessage(), e);
137
138 } finally {
139 if (move != null)
140 move.releaseConnection();
141 }
142 return result;
143 }
144
145
146 /**
147 * Checks if the new name to set is valid in the file system
148 *
149 * The only way to be sure is trying to create a file with that name. It's made in the temporal directory
150 * for downloads, out of any account, and then removed.
151 *
152 * IMPORTANT: The test must be made in the same file system where files are download. The internal storage
153 * could be formatted with a different file system.
154 *
155 * TODO move this method, and maybe FileDownload.get***Path(), to a class with utilities specific for the interactions with the file system
156 *
157 * @return 'True' if a temporal file named with the name to set could be created in the file system where
158 * local files are stored.
159 */
160 private boolean isValidNewName() {
161 // check tricky names
162 if (mNewName == null || mNewName.length() <= 0 || mNewName.contains(File.separator) || mNewName.contains("%")) {
163 return false;
164 }
165 // create a test file
166 String tmpFolder = FileDownloader.getTemporalPath("");
167 File testFile = new File(tmpFolder + mNewName);
168 try {
169 testFile.createNewFile(); // return value is ignored; it could be 'false' because the file already existed, that doesn't invalidate the name
170 } catch (IOException e) {
171 Log.i(TAG, "Test for validity of name " + mNewName + " in the file system failed");
172 return false;
173 }
174 boolean result = (testFile.exists() && testFile.isFile());
175
176 // cleaning ; result is ignored, since there is not much we could do in case of failure, but repeat and repeat...
177 testFile.delete();
178
179 return result;
180 }
181
182
183 /**
184 * Creates a new OCFile for the new remote name of the renamed file.
185 *
186 * @return OCFile object with the same information than mFile, but the renamed remoteFile and the storagePath (empty)
187 */
188 private OCFile obtainUpdatedFile() {
189 OCFile file = new OCFile(mStorageManager.getFileById(mFile.getParentId()).getRemotePath() + mNewName);
190 file.setCreationTimestamp(mFile.getCreationTimestamp());
191 file.setFileId(mFile.getFileId());
192 file.setFileLength(mFile.getFileLength());
193 file.setKeepInSync(mFile.keepInSync());
194 file.setLastSyncDate(mFile.getLastSyncDate());
195 file.setMimetype(mFile.getMimetype());
196 file.setModificationTimestamp(mFile.getModificationTimestamp());
197 file.setParentId(mFile.getParentId());
198 return file;
199 }
200
201
202 // move operation - TODO: find out why org.apache.jackrabbit.webdav.client.methods.MoveMethod is not used instead ¿?
203 private class LocalMoveMethod extends DavMethodBase {
204
205 public LocalMoveMethod(String uri, String dest) {
206 super(uri);
207 addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
208 }
209
210 @Override
211 public String getName() {
212 return "MOVE";
213 }
214
215 @Override
216 protected boolean isSuccess(int status) {
217 return status == 201 || status == 204;
218 }
219
220 }
221
222
223 }