Merge branch 'develop' into refactor_remote_operation_to_create_folder
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / RenameFileOperation.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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.operations;
19
20 import java.io.File;
21 import java.io.IOException;
22
23 import org.apache.jackrabbit.webdav.client.methods.DavMethodBase;
24
25 import com.owncloud.android.Log_OC;
26 import com.owncloud.android.datamodel.FileDataStorageManager;
27 import com.owncloud.android.datamodel.OCFile;
28 import com.owncloud.android.oc_framework.network.webdav.WebdavClient;
29 import com.owncloud.android.oc_framework.network.webdav.WebdavUtils;
30 import com.owncloud.android.oc_framework.operations.RemoteOperation;
31 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
32 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
33 import com.owncloud.android.utils.FileStorageUtils;
34 //import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
35
36 import android.accounts.Account;
37
38
39
40 /**
41 * Remote operation performing the rename of a remote file (or folder?) in the ownCloud server.
42 *
43 * @author David A. Velasco
44 */
45 public class RenameFileOperation extends RemoteOperation {
46
47 private static final String TAG = RenameFileOperation.class.getSimpleName();
48
49 private static final int RENAME_READ_TIMEOUT = 10000;
50 private static final int RENAME_CONNECTION_TIMEOUT = 5000;
51
52
53 private OCFile mFile;
54 private Account mAccount;
55 private String mNewName;
56 private String mNewRemotePath;
57 private FileDataStorageManager mStorageManager;
58
59
60 /**
61 * Constructor
62 *
63 * @param file OCFile instance describing the remote file or folder to rename
64 * @param account OwnCloud account containing the remote file
65 * @param newName New name to set as the name of file.
66 * @param storageManager Reference to the local database corresponding to the account where the file is contained.
67 */
68 public RenameFileOperation(OCFile file, Account account, String newName, FileDataStorageManager storageManager) {
69 mFile = file;
70 mAccount = account;
71 mNewName = newName;
72 mNewRemotePath = null;
73 mStorageManager = storageManager;
74 }
75
76 public OCFile getFile() {
77 return mFile;
78 }
79
80
81 /**
82 * Performs the rename operation.
83 *
84 * @param client Client object to communicate with the remote ownCloud server.
85 */
86 @Override
87 protected RemoteOperationResult run(WebdavClient client) {
88 RemoteOperationResult result = null;
89
90 LocalMoveMethod move = null;
91 mNewRemotePath = null;
92 try {
93 if (mNewName.equals(mFile.getFileName())) {
94 return new RemoteOperationResult(ResultCode.OK);
95 }
96
97 String parent = (new File(mFile.getRemotePath())).getParent();
98 parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent + OCFile.PATH_SEPARATOR;
99 mNewRemotePath = parent + mNewName;
100 if (mFile.isFolder()) {
101 mNewRemotePath += OCFile.PATH_SEPARATOR;
102 }
103
104 // check if the new name is valid in the local file system
105 if (!isValidNewName()) {
106 return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
107 }
108
109 // check if a file with the new name already exists
110 if (client.existsFile(mNewRemotePath) || // remote check could fail by network failure. by indeterminate behavior of HEAD for folders ...
111 mStorageManager.getFileByPath(mNewRemotePath) != null) { // ... so local check is convenient
112 return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
113 }
114 move = new LocalMoveMethod( client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()),
115 client.getBaseUri() + WebdavUtils.encodePath(mNewRemotePath));
116 int status = client.executeMethod(move, RENAME_READ_TIMEOUT, RENAME_CONNECTION_TIMEOUT);
117 if (move.succeeded()) {
118
119 if (mFile.isFolder()) {
120 saveLocalDirectory();
121
122 } else {
123 saveLocalFile();
124
125 }
126
127 /*
128 *} else if (mFile.isDirectory() && (status == 207 || status >= 500)) {
129 * // TODO
130 * // if server fails in the rename of a folder, some children files could have been moved to a folder with the new name while some others
131 * // stayed in the old folder;
132 * //
133 * // easiest and heaviest solution is synchronizing the parent folder (or the full account);
134 * //
135 * // a better solution is synchronizing the folders with the old and new names;
136 *}
137 */
138
139 }
140
141 move.getResponseBodyAsString(); // exhaust response, although not interesting
142 result = new RemoteOperationResult(move.succeeded(), status, move.getResponseHeaders());
143 Log_OC.i(TAG, "Rename " + mFile.getRemotePath() + " to " + mNewRemotePath + ": " + result.getLogMessage());
144
145 } catch (Exception e) {
146 result = new RemoteOperationResult(e);
147 Log_OC.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " + result.getLogMessage(), e);
148
149 } finally {
150 if (move != null)
151 move.releaseConnection();
152 }
153 return result;
154 }
155
156
157 private void saveLocalDirectory() {
158 mStorageManager.moveFolder(mFile, mNewRemotePath);
159 String localPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
160 File localDir = new File(localPath);
161 if (localDir.exists()) {
162 localDir.renameTo(new File(FileStorageUtils.getSavePath(mAccount.name) + mNewRemotePath));
163 // TODO - if renameTo fails, children files that are already down will result unlinked
164 }
165 }
166
167 private void saveLocalFile() {
168 mFile.setFileName(mNewName);
169
170 // try to rename the local copy of the file
171 if (mFile.isDown()) {
172 File f = new File(mFile.getStoragePath());
173 String parentStoragePath = f.getParent();
174 if (!parentStoragePath.endsWith(File.separator))
175 parentStoragePath += File.separator;
176 if (f.renameTo(new File(parentStoragePath + mNewName))) {
177 mFile.setStoragePath(parentStoragePath + mNewName);
178 }
179 // else - NOTHING: the link to the local file is kept although the local name can't be updated
180 // TODO - study conditions when this could be a problem
181 }
182
183 mStorageManager.saveFile(mFile);
184 }
185
186 /**
187 * Checks if the new name to set is valid in the file system
188 *
189 * The only way to be sure is trying to create a file with that name. It's made in the temporal directory
190 * for downloads, out of any account, and then removed.
191 *
192 * IMPORTANT: The test must be made in the same file system where files are download. The internal storage
193 * could be formatted with a different file system.
194 *
195 * TODO move this method, and maybe FileDownload.get***Path(), to a class with utilities specific for the interactions with the file system
196 *
197 * @return 'True' if a temporal file named with the name to set could be created in the file system where
198 * local files are stored.
199 * @throws IOException When the temporal folder can not be created.
200 */
201 private boolean isValidNewName() throws IOException {
202 // check tricky names
203 if (mNewName == null || mNewName.length() <= 0 || mNewName.contains(File.separator) || mNewName.contains("%")) {
204 return false;
205 }
206 // create a test file
207 String tmpFolderName = FileStorageUtils.getTemporalPath("");
208 File testFile = new File(tmpFolderName + mNewName);
209 File tmpFolder = testFile.getParentFile();
210 tmpFolder.mkdirs();
211 if (!tmpFolder.isDirectory()) {
212 throw new IOException("Unexpected error: temporal directory could not be created");
213 }
214 try {
215 testFile.createNewFile(); // return value is ignored; it could be 'false' because the file already existed, that doesn't invalidate the name
216 } catch (IOException e) {
217 Log_OC.i(TAG, "Test for validity of name " + mNewName + " in the file system failed");
218 return false;
219 }
220 boolean result = (testFile.exists() && testFile.isFile());
221
222 // cleaning ; result is ignored, since there is not much we could do in case of failure, but repeat and repeat...
223 testFile.delete();
224
225 return result;
226 }
227
228
229 // move operation
230 private class LocalMoveMethod extends DavMethodBase {
231
232 public LocalMoveMethod(String uri, String dest) {
233 super(uri);
234 addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
235 }
236
237 @Override
238 public String getName() {
239 return "MOVE";
240 }
241
242 @Override
243 protected boolean isSuccess(int status) {
244 return status == 201 || status == 204;
245 }
246
247 }
248
249
250 }