ca1894078bac10c4477ffb23a04cc4be8af3132b
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / FileDataStorageManager.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.datamodel;
20
21 import java.io.File;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Vector;
27
28 import com.owncloud.android.db.ProviderMeta;
29 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
30 import com.owncloud.android.utils.FileStorageUtils;
31
32 import android.accounts.Account;
33 import android.content.ContentProviderClient;
34 import android.content.ContentProviderOperation;
35 import android.content.ContentProviderResult;
36 import android.content.ContentResolver;
37 import android.content.ContentValues;
38 import android.content.OperationApplicationException;
39 import android.database.Cursor;
40 import android.net.Uri;
41 import android.os.RemoteException;
42 import android.util.Log;
43
44 public class FileDataStorageManager implements DataStorageManager {
45
46 private ContentResolver mContentResolver;
47 private ContentProviderClient mContentProvider;
48 private Account mAccount;
49
50 private static String TAG = "FileDataStorageManager";
51
52 public FileDataStorageManager(Account account, ContentResolver cr) {
53 mContentProvider = null;
54 mContentResolver = cr;
55 mAccount = account;
56 }
57
58 public FileDataStorageManager(Account account, ContentProviderClient cp) {
59 mContentProvider = cp;
60 mContentResolver = null;
61 mAccount = account;
62 }
63
64 @Override
65 public OCFile getFileByPath(String path) {
66 Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
67 OCFile file = null;
68 if (c.moveToFirst()) {
69 file = createFileInstance(c);
70 }
71 c.close();
72 return file;
73 }
74
75 @Override
76 public OCFile getFileById(long id) {
77 Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
78 OCFile file = null;
79 if (c.moveToFirst()) {
80 file = createFileInstance(c);
81 }
82 c.close();
83 return file;
84 }
85
86 public OCFile getFileByLocalPath(String path) {
87 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
88 OCFile file = null;
89 if (c.moveToFirst()) {
90 file = createFileInstance(c);
91 }
92 c.close();
93 return file;
94 }
95
96 @Override
97 public boolean fileExists(long id) {
98 return fileExists(ProviderTableMeta._ID, String.valueOf(id));
99 }
100
101 @Override
102 public boolean fileExists(String path) {
103 return fileExists(ProviderTableMeta.FILE_PATH, path);
104 }
105
106 @Override
107 public boolean saveFile(OCFile file) {
108 boolean overriden = false;
109 ContentValues cv = new ContentValues();
110 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
111 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
112 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
113 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
114 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
115 if (file.getParentId() != 0)
116 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
117 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
118 if (!file.isDirectory())
119 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
120 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
121 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDate());
122 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
123
124 if (fileExists(file.getRemotePath())) {
125 OCFile oldFile = getFileByPath(file.getRemotePath());
126 if (file.getStoragePath() == null && oldFile.getStoragePath() != null)
127 file.setStoragePath(oldFile.getStoragePath());
128 if (!file.isDirectory());
129 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
130 file.setFileId(oldFile.getFileId());
131
132 overriden = true;
133 if (getContentResolver() != null) {
134 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
135 ProviderTableMeta._ID + "=?",
136 new String[] { String.valueOf(file.getFileId()) });
137 } else {
138 try {
139 getContentProvider().update(ProviderTableMeta.CONTENT_URI,
140 cv, ProviderTableMeta._ID + "=?",
141 new String[] { String.valueOf(file.getFileId()) });
142 } catch (RemoteException e) {
143 Log.e(TAG,
144 "Fail to insert insert file to database "
145 + e.getMessage());
146 }
147 }
148 } else {
149 Uri result_uri = null;
150 if (getContentResolver() != null) {
151 result_uri = getContentResolver().insert(
152 ProviderTableMeta.CONTENT_URI_FILE, cv);
153 } else {
154 try {
155 result_uri = getContentProvider().insert(
156 ProviderTableMeta.CONTENT_URI_FILE, cv);
157 } catch (RemoteException e) {
158 Log.e(TAG,
159 "Fail to insert insert file to database "
160 + e.getMessage());
161 }
162 }
163 if (result_uri != null) {
164 long new_id = Long.parseLong(result_uri.getPathSegments()
165 .get(1));
166 file.setFileId(new_id);
167 }
168 }
169
170 if (file.isDirectory() && file.needsUpdatingWhileSaving())
171 for (OCFile f : getDirectoryContent(file))
172 saveFile(f);
173
174 return overriden;
175 }
176
177
178 @Override
179 public void saveFiles(List<OCFile> files) {
180
181 Iterator<OCFile> filesIt = files.iterator();
182 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(files.size());
183 OCFile file = null;
184
185 // prepare operations to perform
186 while (filesIt.hasNext()) {
187 file = filesIt.next();
188 ContentValues cv = new ContentValues();
189 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
190 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
191 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
192 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
193 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
194 if (file.getParentId() != 0)
195 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
196 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
197 if (!file.isDirectory())
198 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
199 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
200 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDate());
201 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
202
203 if (fileExists(file.getRemotePath())) {
204 OCFile tmpfile = getFileByPath(file.getRemotePath());
205 file.setStoragePath(tmpfile.getStoragePath());
206 if (!file.isDirectory());
207 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
208 file.setFileId(tmpfile.getFileId());
209
210 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
211 withValues(cv).
212 withSelection( ProviderTableMeta._ID + "=?",
213 new String[] { String.valueOf(file.getFileId()) })
214 .build());
215
216 } else {
217 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
218 }
219 }
220
221 // apply operations in batch
222 ContentProviderResult[] results = null;
223 try {
224 if (getContentResolver() != null) {
225 results = getContentResolver().applyBatch(ProviderMeta.AUTHORITY_FILES, operations);
226
227 } else {
228 results = getContentProvider().applyBatch(operations);
229 }
230
231 } catch (OperationApplicationException e) {
232 Log.e(TAG, "Fail to update/insert list of files to database " + e.getMessage());
233
234 } catch (RemoteException e) {
235 Log.e(TAG, "Fail to update/insert list of files to database " + e.getMessage());
236 }
237
238 // update new id in file objects for insertions
239 if (results != null) {
240 long newId;
241 for (int i=0; i<results.length; i++) {
242 if (results[i].uri != null) {
243 newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
244 files.get(i).setFileId(newId);
245 //Log.v(TAG, "Found and added id in insertion for " + files.get(i).getRemotePath());
246 }
247 }
248 }
249
250 for (OCFile aFile : files) {
251 if (aFile.isDirectory() && aFile.needsUpdatingWhileSaving())
252 saveFiles(getDirectoryContent(aFile));
253 }
254
255 }
256
257 public void setAccount(Account account) {
258 mAccount = account;
259 }
260
261 public Account getAccount() {
262 return mAccount;
263 }
264
265 public void setContentResolver(ContentResolver cr) {
266 mContentResolver = cr;
267 }
268
269 public ContentResolver getContentResolver() {
270 return mContentResolver;
271 }
272
273 public void setContentProvider(ContentProviderClient cp) {
274 mContentProvider = cp;
275 }
276
277 public ContentProviderClient getContentProvider() {
278 return mContentProvider;
279 }
280
281 @Override
282 public Vector<OCFile> getDirectoryContent(OCFile f) {
283 if (f != null && f.isDirectory() && f.getFileId() != -1) {
284 Vector<OCFile> ret = new Vector<OCFile>();
285
286 Uri req_uri = Uri.withAppendedPath(
287 ProviderTableMeta.CONTENT_URI_DIR,
288 String.valueOf(f.getFileId()));
289 Cursor c = null;
290
291 if (getContentProvider() != null) {
292 try {
293 c = getContentProvider().query(req_uri, null,
294 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
295 new String[] { mAccount.name }, null);
296 } catch (RemoteException e) {
297 Log.e(TAG, e.getMessage());
298 return ret;
299 }
300 } else {
301 c = getContentResolver().query(req_uri, null,
302 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
303 new String[] { mAccount.name }, null);
304 }
305
306 if (c.moveToFirst()) {
307 do {
308 OCFile child = createFileInstance(c);
309 ret.add(child);
310 } while (c.moveToNext());
311 }
312
313 c.close();
314
315 Collections.sort(ret);
316
317 return ret;
318 }
319 return null;
320 }
321
322 private boolean fileExists(String cmp_key, String value) {
323 Cursor c;
324 if (getContentResolver() != null) {
325 c = getContentResolver()
326 .query(ProviderTableMeta.CONTENT_URI,
327 null,
328 cmp_key + "=? AND "
329 + ProviderTableMeta.FILE_ACCOUNT_OWNER
330 + "=?",
331 new String[] { value, mAccount.name }, null);
332 } else {
333 try {
334 c = getContentProvider().query(
335 ProviderTableMeta.CONTENT_URI,
336 null,
337 cmp_key + "=? AND "
338 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
339 new String[] { value, mAccount.name }, null);
340 } catch (RemoteException e) {
341 Log.e(TAG,
342 "Couldn't determine file existance, assuming non existance: "
343 + e.getMessage());
344 return false;
345 }
346 }
347 boolean retval = c.moveToFirst();
348 c.close();
349 return retval;
350 }
351
352 private Cursor getCursorForValue(String key, String value) {
353 Cursor c = null;
354 if (getContentResolver() != null) {
355 c = getContentResolver()
356 .query(ProviderTableMeta.CONTENT_URI,
357 null,
358 key + "=? AND "
359 + ProviderTableMeta.FILE_ACCOUNT_OWNER
360 + "=?",
361 new String[] { value, mAccount.name }, null);
362 } else {
363 try {
364 c = getContentProvider().query(
365 ProviderTableMeta.CONTENT_URI,
366 null,
367 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
368 + "=?", new String[] { value, mAccount.name },
369 null);
370 } catch (RemoteException e) {
371 Log.e(TAG, "Could not get file details: " + e.getMessage());
372 c = null;
373 }
374 }
375 return c;
376 }
377
378 private OCFile createFileInstance(Cursor c) {
379 OCFile file = null;
380 if (c != null) {
381 file = new OCFile(c.getString(c
382 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
383 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
384 file.setParentId(c.getLong(c
385 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
386 file.setMimetype(c.getString(c
387 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
388 if (!file.isDirectory()) {
389 file.setStoragePath(c.getString(c
390 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
391 if (file.getStoragePath() == null) {
392 // try to find existing file and bind it with current account
393 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
394 if (f.exists())
395 file.setStoragePath(f.getAbsolutePath());
396 }
397 }
398 file.setFileLength(c.getLong(c
399 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
400 file.setCreationTimestamp(c.getLong(c
401 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
402 file.setModificationTimestamp(c.getLong(c
403 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
404 file.setLastSyncDate(c.getLong(c
405 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
406 file.setKeepInSync(c.getInt(
407 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
408 }
409 return file;
410 }
411
412 @Override
413 public void removeFile(OCFile file, boolean removeLocalCopy) {
414 Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
415 if (getContentProvider() != null) {
416 try {
417 getContentProvider().delete(file_uri,
418 ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
419 new String[]{mAccount.name});
420 } catch (RemoteException e) {
421 e.printStackTrace();
422 }
423 } else {
424 getContentResolver().delete(file_uri,
425 ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
426 new String[]{mAccount.name});
427 }
428 if (file.isDown() && removeLocalCopy) {
429 new File(file.getStoragePath()).delete();
430 }
431 }
432
433 }