161eb083ca31f7f728770c69f6ec150369a9ebff
[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.files.services.FileDownloader;
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 public Vector<OCFile> getDirectoryContent(OCFile f) {
282 if (f != null && f.isDirectory() && f.getFileId() != -1) {
283 Vector<OCFile> ret = new Vector<OCFile>();
284
285 Uri req_uri = Uri.withAppendedPath(
286 ProviderTableMeta.CONTENT_URI_DIR,
287 String.valueOf(f.getFileId()));
288 Cursor c = null;
289
290 if (getContentProvider() != null) {
291 try {
292 c = getContentProvider().query(req_uri, null,
293 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
294 new String[] { mAccount.name }, null);
295 } catch (RemoteException e) {
296 Log.e(TAG, e.getMessage());
297 return ret;
298 }
299 } else {
300 c = getContentResolver().query(req_uri, null,
301 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
302 new String[] { mAccount.name }, null);
303 }
304
305 if (c.moveToFirst()) {
306 do {
307 OCFile child = createFileInstance(c);
308 ret.add(child);
309 } while (c.moveToNext());
310 }
311
312 c.close();
313
314 Collections.sort(ret);
315
316 return ret;
317 }
318 return null;
319 }
320
321 private boolean fileExists(String cmp_key, String value) {
322 Cursor c;
323 if (getContentResolver() != null) {
324 c = getContentResolver()
325 .query(ProviderTableMeta.CONTENT_URI,
326 null,
327 cmp_key + "=? AND "
328 + ProviderTableMeta.FILE_ACCOUNT_OWNER
329 + "=?",
330 new String[] { value, mAccount.name }, null);
331 } else {
332 try {
333 c = getContentProvider().query(
334 ProviderTableMeta.CONTENT_URI,
335 null,
336 cmp_key + "=? AND "
337 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
338 new String[] { value, mAccount.name }, null);
339 } catch (RemoteException e) {
340 Log.e(TAG,
341 "Couldn't determine file existance, assuming non existance: "
342 + e.getMessage());
343 return false;
344 }
345 }
346 boolean retval = c.moveToFirst();
347 c.close();
348 return retval;
349 }
350
351 private Cursor getCursorForValue(String key, String value) {
352 Cursor c = null;
353 if (getContentResolver() != null) {
354 c = getContentResolver()
355 .query(ProviderTableMeta.CONTENT_URI,
356 null,
357 key + "=? AND "
358 + ProviderTableMeta.FILE_ACCOUNT_OWNER
359 + "=?",
360 new String[] { value, mAccount.name }, null);
361 } else {
362 try {
363 c = getContentProvider().query(
364 ProviderTableMeta.CONTENT_URI,
365 null,
366 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
367 + "=?", new String[] { value, mAccount.name },
368 null);
369 } catch (RemoteException e) {
370 Log.e(TAG, "Could not get file details: " + e.getMessage());
371 c = null;
372 }
373 }
374 return c;
375 }
376
377 private OCFile createFileInstance(Cursor c) {
378 OCFile file = null;
379 if (c != null) {
380 file = new OCFile(c.getString(c
381 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
382 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
383 file.setParentId(c.getLong(c
384 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
385 file.setMimetype(c.getString(c
386 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
387 if (!file.isDirectory()) {
388 file.setStoragePath(c.getString(c
389 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
390 if (file.getStoragePath() == null) {
391 // try to find existing file and bind it with current account
392 File f = new File(FileDownloader.getSavePath(mAccount.name) + file.getRemotePath());
393 if (f.exists())
394 file.setStoragePath(f.getAbsolutePath());
395 }
396 }
397 file.setFileLength(c.getLong(c
398 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
399 file.setCreationTimestamp(c.getLong(c
400 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
401 file.setModificationTimestamp(c.getLong(c
402 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
403 file.setLastSyncDate(c.getLong(c
404 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
405 file.setKeepInSync(c.getInt(
406 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
407 }
408 return file;
409 }
410
411 public void removeFile(OCFile file, boolean removeLocalCopy) {
412 Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
413 if (getContentProvider() != null) {
414 try {
415 getContentProvider().delete(file_uri,
416 ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
417 new String[]{mAccount.name});
418 } catch (RemoteException e) {
419 e.printStackTrace();
420 }
421 } else {
422 getContentResolver().delete(file_uri,
423 ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
424 new String[]{mAccount.name});
425 }
426 if (file.isDown() && removeLocalCopy) {
427 new File(file.getStoragePath()).delete();
428 }
429 }
430
431 }