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