Refactored to build ownCloud app with oc_framework as dependency
[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
28 import com.owncloud.android.Log_OC;
29 import com.owncloud.android.datamodel.FileDataStorageManager;
30 import com.owncloud.android.datamodel.OCFile;
31 import com.owncloud.android.oc_framework.network.webdav.WebdavClient;
32 import com.owncloud.android.oc_framework.network.webdav.WebdavUtils;
33 import com.owncloud.android.oc_framework.operations.RemoteOperation;
34 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
35 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
36 import com.owncloud.android.utils.FileStorageUtils;
37
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 = RenameFileOperation.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 FileDataStorageManager 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, FileDataStorageManager 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.isFolder()) {
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. 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.isFolder()) {
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, move.getResponseHeaders());
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.moveFolder(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 * @throws IOException When the temporal folder can not be created.
199 */
200 private boolean isValidNewName() throws IOException {
201 // check tricky names
202 if (mNewName == null || mNewName.length() <= 0 || mNewName.contains(File.separator) || mNewName.contains("%")) {
203 return false;
204 }
205 // create a test file
206 String tmpFolderName = FileStorageUtils.getTemporalPath("");
207 File testFile = new File(tmpFolderName + mNewName);
208 File tmpFolder = testFile.getParentFile();
209 tmpFolder.mkdirs();
210 if (!tmpFolder.isDirectory()) {
211 throw new IOException("Unexpected error: temporal directory could not be created");
212 }
213 try {
214 testFile.createNewFile(); // return value is ignored; it could be 'false' because the file already existed, that doesn't invalidate the name
215 } catch (IOException e) {
216 Log_OC.i(TAG, "Test for validity of name " + mNewName + " in the file system failed");
217 return false;
218 }
219 boolean result = (testFile.exists() && testFile.isFile());
220
221 // cleaning ; result is ignored, since there is not much we could do in case of failure, but repeat and repeat...
222 testFile.delete();
223
224 return result;
225 }
226
227
228 // move operation
229 private class LocalMoveMethod extends DavMethodBase {
230
231 public LocalMoveMethod(String uri, String dest) {
232 super(uri);
233 addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
234 }
235
236 @Override
237 public String getName() {
238 return "MOVE";
239 }
240
241 @Override
242 protected boolean isSuccess(int status) {
243 return status == 201 || status == 204;
244 }
245
246 }
247
248
249 }