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