Merge branch 'develop' into pinEnhancement
[pub/Android/ownCloud.git] / src / com / owncloud / android / providers / FileContentProvider.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 */
22
23 package com.owncloud.android.providers;
24
25 import java.io.File;
26 import java.security.Provider;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29
30 import com.owncloud.android.MainApp;
31 import com.owncloud.android.R;
32 import com.owncloud.android.datamodel.OCFile;
33 import com.owncloud.android.db.ProviderMeta;
34 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
35 import com.owncloud.android.lib.common.accounts.AccountUtils;
36 import com.owncloud.android.lib.common.utils.Log_OC;
37 import com.owncloud.android.lib.resources.shares.ShareType;
38 import com.owncloud.android.utils.FileStorageUtils;
39
40 import android.accounts.Account;
41 import android.accounts.AccountManager;
42 import android.content.ContentProvider;
43 import android.content.ContentProviderOperation;
44 import android.content.ContentProviderResult;
45 import android.content.ContentUris;
46 import android.content.ContentValues;
47 import android.content.Context;
48 import android.content.OperationApplicationException;
49 import android.content.UriMatcher;
50 import android.database.Cursor;
51 import android.database.SQLException;
52 import android.database.sqlite.SQLiteDatabase;
53 import android.database.sqlite.SQLiteOpenHelper;
54 import android.database.sqlite.SQLiteQueryBuilder;
55 import android.net.Uri;
56 import android.text.TextUtils;
57
58 /**
59 * The ContentProvider for the ownCloud App.
60 */
61 public class FileContentProvider extends ContentProvider {
62
63 private DataBaseHelper mDbHelper;
64
65 // Projection for filelist table
66 private static HashMap<String, String> mFileProjectionMap;
67 static {
68 mFileProjectionMap = new HashMap<String, String>();
69 mFileProjectionMap.put(ProviderTableMeta._ID, ProviderTableMeta._ID);
70 mFileProjectionMap.put(ProviderTableMeta.FILE_PARENT,
71 ProviderTableMeta.FILE_PARENT);
72 mFileProjectionMap.put(ProviderTableMeta.FILE_PATH,
73 ProviderTableMeta.FILE_PATH);
74 mFileProjectionMap.put(ProviderTableMeta.FILE_NAME,
75 ProviderTableMeta.FILE_NAME);
76 mFileProjectionMap.put(ProviderTableMeta.FILE_CREATION,
77 ProviderTableMeta.FILE_CREATION);
78 mFileProjectionMap.put(ProviderTableMeta.FILE_MODIFIED,
79 ProviderTableMeta.FILE_MODIFIED);
80 mFileProjectionMap.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
81 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA);
82 mFileProjectionMap.put(ProviderTableMeta.FILE_CONTENT_LENGTH,
83 ProviderTableMeta.FILE_CONTENT_LENGTH);
84 mFileProjectionMap.put(ProviderTableMeta.FILE_CONTENT_TYPE,
85 ProviderTableMeta.FILE_CONTENT_TYPE);
86 mFileProjectionMap.put(ProviderTableMeta.FILE_STORAGE_PATH,
87 ProviderTableMeta.FILE_STORAGE_PATH);
88 mFileProjectionMap.put(ProviderTableMeta.FILE_LAST_SYNC_DATE,
89 ProviderTableMeta.FILE_LAST_SYNC_DATE);
90 mFileProjectionMap.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
91 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA);
92 mFileProjectionMap.put(ProviderTableMeta.FILE_KEEP_IN_SYNC,
93 ProviderTableMeta.FILE_KEEP_IN_SYNC);
94 mFileProjectionMap.put(ProviderTableMeta.FILE_ACCOUNT_OWNER,
95 ProviderTableMeta.FILE_ACCOUNT_OWNER);
96 mFileProjectionMap.put(ProviderTableMeta.FILE_ETAG,
97 ProviderTableMeta.FILE_ETAG);
98 mFileProjectionMap.put(ProviderTableMeta.FILE_SHARE_BY_LINK,
99 ProviderTableMeta.FILE_SHARE_BY_LINK);
100 mFileProjectionMap.put(ProviderTableMeta.FILE_PUBLIC_LINK,
101 ProviderTableMeta.FILE_PUBLIC_LINK);
102 mFileProjectionMap.put(ProviderTableMeta.FILE_PERMISSIONS,
103 ProviderTableMeta.FILE_PERMISSIONS);
104 mFileProjectionMap.put(ProviderTableMeta.FILE_REMOTE_ID,
105 ProviderTableMeta.FILE_REMOTE_ID);
106 mFileProjectionMap.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
107 ProviderTableMeta.FILE_UPDATE_THUMBNAIL);
108 mFileProjectionMap.put(ProviderTableMeta.FILE_IS_DOWNLOADING,
109 ProviderTableMeta.FILE_IS_DOWNLOADING);
110 }
111
112 private static final int SINGLE_FILE = 1;
113 private static final int DIRECTORY = 2;
114 private static final int ROOT_DIRECTORY = 3;
115 private static final int SHARES = 4;
116
117 private static final String TAG = FileContentProvider.class.getSimpleName();
118
119 // Projection for ocshares table
120 private static HashMap<String, String> mOCSharesProjectionMap;
121 static {
122 mOCSharesProjectionMap = new HashMap<String, String>();
123 mOCSharesProjectionMap.put(ProviderTableMeta._ID, ProviderTableMeta._ID);
124 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_FILE_SOURCE,
125 ProviderTableMeta.OCSHARES_FILE_SOURCE);
126 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE,
127 ProviderTableMeta.OCSHARES_ITEM_SOURCE);
128 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_SHARE_TYPE,
129 ProviderTableMeta.OCSHARES_SHARE_TYPE);
130 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_SHARE_WITH,
131 ProviderTableMeta.OCSHARES_SHARE_WITH);
132 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_PATH,
133 ProviderTableMeta.OCSHARES_PATH);
134 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_PERMISSIONS,
135 ProviderTableMeta.OCSHARES_PERMISSIONS);
136 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_SHARED_DATE,
137 ProviderTableMeta.OCSHARES_SHARED_DATE);
138 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE,
139 ProviderTableMeta.OCSHARES_EXPIRATION_DATE);
140 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_TOKEN,
141 ProviderTableMeta.OCSHARES_TOKEN);
142 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
143 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME);
144 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY,
145 ProviderTableMeta.OCSHARES_IS_DIRECTORY);
146 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_USER_ID,
147 ProviderTableMeta.OCSHARES_USER_ID);
148 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED,
149 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED);
150 mOCSharesProjectionMap.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER,
151 ProviderTableMeta.OCSHARES_ACCOUNT_OWNER);
152 }
153
154 private UriMatcher mUriMatcher;
155
156 @Override
157 public int delete(Uri uri, String where, String[] whereArgs) {
158 //Log_OC.d(TAG, "Deleting " + uri + " at provider " + this);
159 int count = 0;
160 SQLiteDatabase db = mDbHelper.getWritableDatabase();
161 db.beginTransaction();
162 try {
163 count = delete(db, uri, where, whereArgs);
164 db.setTransactionSuccessful();
165 } finally {
166 db.endTransaction();
167 }
168 getContext().getContentResolver().notifyChange(uri, null);
169 return count;
170 }
171
172 private int delete(SQLiteDatabase db, Uri uri, String where, String[] whereArgs) {
173 int count = 0;
174 switch (mUriMatcher.match(uri)) {
175 case SINGLE_FILE:
176 Cursor c = query(db, uri, null, where, whereArgs, null);
177 String remoteId = "";
178 if (c != null && c.moveToFirst()) {
179 remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID));
180 //ThumbnailsCacheManager.removeFileFromCache(remoteId);
181 }
182 Log_OC.d(TAG, "Removing FILE " + remoteId);
183
184 count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,
185 ProviderTableMeta._ID
186 + "="
187 + uri.getPathSegments().get(1)
188 + (!TextUtils.isEmpty(where) ? " AND (" + where
189 + ")" : ""), whereArgs);
190 /* just for log
191 if (c!=null) {
192 c.close();
193 }
194 */
195 break;
196 case DIRECTORY:
197 // deletion of folder is recursive
198 /*
199 Uri folderUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, Long.parseLong(uri.getPathSegments().get(1)));
200 Cursor folder = query(db, folderUri, null, null, null, null);
201 String folderName = "(unknown)";
202 if (folder != null && folder.moveToFirst()) {
203 folderName = folder.getString(folder.getColumnIndex(ProviderTableMeta.FILE_PATH));
204 }
205 */
206 Cursor children = query(uri, null, null, null, null);
207 if (children != null && children.moveToFirst()) {
208 long childId;
209 boolean isDir;
210 while (!children.isAfterLast()) {
211 childId = children.getLong(children.getColumnIndex(ProviderTableMeta._ID));
212 isDir = "DIR".equals(children.getString(
213 children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)
214 ));
215 //remotePath = children.getString(children.getColumnIndex(ProviderTableMeta.FILE_PATH));
216 if (isDir) {
217 count += delete(
218 db,
219 ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
220 null,
221 null
222 );
223 } else {
224 count += delete(
225 db,
226 ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
227 null,
228 null
229 );
230 }
231 children.moveToNext();
232 }
233 children.close();
234 } /*else {
235 Log_OC.d(TAG, "No child to remove in DIRECTORY " + folderName);
236 }
237 Log_OC.d(TAG, "Removing DIRECTORY " + folderName + " (or maybe not) ");
238 */
239 count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,
240 ProviderTableMeta._ID
241 + "="
242 + uri.getPathSegments().get(1)
243 + (!TextUtils.isEmpty(where) ? " AND (" + where
244 + ")" : ""), whereArgs);
245 /* Just for log
246 if (folder != null) {
247 folder.close();
248 }*/
249 break;
250 case ROOT_DIRECTORY:
251 //Log_OC.d(TAG, "Removing ROOT!");
252 count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs);
253 break;
254 case SHARES:
255 count = db.delete(ProviderTableMeta.OCSHARES_TABLE_NAME, where, whereArgs);
256 break;
257 default:
258 //Log_OC.e(TAG, "Unknown uri " + uri);
259 throw new IllegalArgumentException("Unknown uri: " + uri.toString());
260 }
261 return count;
262 }
263
264 @Override
265 public String getType(Uri uri) {
266 switch (mUriMatcher.match(uri)) {
267 case ROOT_DIRECTORY:
268 return ProviderTableMeta.CONTENT_TYPE;
269 case SINGLE_FILE:
270 return ProviderTableMeta.CONTENT_TYPE_ITEM;
271 default:
272 throw new IllegalArgumentException("Unknown Uri id."
273 + uri.toString());
274 }
275 }
276
277 @Override
278 public Uri insert(Uri uri, ContentValues values) {
279 Uri newUri = null;
280 SQLiteDatabase db = mDbHelper.getWritableDatabase();
281 db.beginTransaction();
282 try {
283 newUri = insert(db, uri, values);
284 db.setTransactionSuccessful();
285 } finally {
286 db.endTransaction();
287 }
288 getContext().getContentResolver().notifyChange(newUri, null);
289 return newUri;
290 }
291
292 private Uri insert(SQLiteDatabase db, Uri uri, ContentValues values) {
293 switch (mUriMatcher.match(uri)){
294 case ROOT_DIRECTORY:
295 case SINGLE_FILE:
296 String remotePath = values.getAsString(ProviderTableMeta.FILE_PATH);
297 String accountName = values.getAsString(ProviderTableMeta.FILE_ACCOUNT_OWNER);
298 String[] projection = new String[] {
299 ProviderTableMeta._ID, ProviderTableMeta.FILE_PATH,
300 ProviderTableMeta.FILE_ACCOUNT_OWNER
301 };
302 String where = ProviderTableMeta.FILE_PATH + "=? AND " +
303 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
304 String[] whereArgs = new String[] {remotePath, accountName};
305 Cursor doubleCheck = query(db, uri, projection, where, whereArgs, null);
306 // ugly patch; serious refactorization is needed to reduce work in
307 // FileDataStorageManager and bring it to FileContentProvider
308 if (doubleCheck == null || !doubleCheck.moveToFirst()) {
309 long rowId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values);
310 if (rowId > 0) {
311 Uri insertedFileUri =
312 ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId);
313 return insertedFileUri;
314 } else {
315 throw new SQLException("ERROR " + uri);
316 }
317 } else {
318 // file is already inserted; race condition, let's avoid a duplicated entry
319 Uri insertedFileUri = ContentUris.withAppendedId(
320 ProviderTableMeta.CONTENT_URI_FILE,
321 doubleCheck.getLong(doubleCheck.getColumnIndex(ProviderTableMeta._ID))
322 );
323 doubleCheck.close();
324
325 return insertedFileUri;
326 }
327
328 case SHARES:
329 String path = values.getAsString(ProviderTableMeta.OCSHARES_PATH);
330 String accountNameShare= values.getAsString(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER);
331 String[] projectionShare = new String[] {
332 ProviderTableMeta._ID, ProviderTableMeta.OCSHARES_PATH,
333 ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
334 };
335 String whereShare = ProviderTableMeta.OCSHARES_PATH + "=? AND " +
336 ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
337 String[] whereArgsShare = new String[] {path, accountNameShare};
338 Uri insertedShareUri = null;
339 Cursor doubleCheckShare =
340 query(db, uri, projectionShare, whereShare, whereArgsShare, null);
341 // ugly patch; serious refactorization is needed to reduce work in
342 // FileDataStorageManager and bring it to FileContentProvider
343 if (doubleCheckShare == null || !doubleCheckShare.moveToFirst()) {
344 long rowId = db.insert(ProviderTableMeta.OCSHARES_TABLE_NAME, null, values);
345 if (rowId >0) {
346 insertedShareUri =
347 ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, rowId);
348 } else {
349 throw new SQLException("ERROR " + uri);
350
351 }
352 } else {
353 // file is already inserted; race condition, let's avoid a duplicated entry
354 insertedShareUri = ContentUris.withAppendedId(
355 ProviderTableMeta.CONTENT_URI_SHARE,
356 doubleCheckShare.getLong(
357 doubleCheckShare.getColumnIndex(ProviderTableMeta._ID)
358 )
359 );
360 doubleCheckShare.close();
361 }
362 updateFilesTableAccordingToShareInsertion(db, uri, values);
363 return insertedShareUri;
364
365
366 default:
367 throw new IllegalArgumentException("Unknown uri id: " + uri);
368 }
369
370 }
371
372 private void updateFilesTableAccordingToShareInsertion(
373 SQLiteDatabase db, Uri uri, ContentValues shareValues
374 ) {
375 ContentValues fileValues = new ContentValues();
376 fileValues.put(
377 ProviderTableMeta.FILE_SHARE_BY_LINK,
378 ShareType.PUBLIC_LINK.getValue() ==
379 shareValues.getAsInteger(ProviderTableMeta.OCSHARES_SHARE_TYPE) ? 1 : 0
380 );
381 String whereShare = ProviderTableMeta.FILE_PATH + "=? AND " +
382 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
383 String[] whereArgsShare = new String[] {
384 shareValues.getAsString(ProviderTableMeta.OCSHARES_PATH),
385 shareValues.getAsString(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER)
386 };
387 db.update(ProviderTableMeta.FILE_TABLE_NAME, fileValues, whereShare, whereArgsShare);
388 }
389
390
391 @Override
392 public boolean onCreate() {
393 mDbHelper = new DataBaseHelper(getContext());
394
395 String authority = getContext().getResources().getString(R.string.authority);
396 mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
397 mUriMatcher.addURI(authority, null, ROOT_DIRECTORY);
398 mUriMatcher.addURI(authority, "file/", SINGLE_FILE);
399 mUriMatcher.addURI(authority, "file/#", SINGLE_FILE);
400 mUriMatcher.addURI(authority, "dir/", DIRECTORY);
401 mUriMatcher.addURI(authority, "dir/#", DIRECTORY);
402 mUriMatcher.addURI(authority, "shares/", SHARES);
403 mUriMatcher.addURI(authority, "shares/#", SHARES);
404
405 return true;
406 }
407
408
409 @Override
410 public Cursor query(
411 Uri uri,
412 String[] projection,
413 String selection,
414 String[] selectionArgs,
415 String sortOrder
416 ) {
417
418 Cursor result = null;
419 SQLiteDatabase db = mDbHelper.getReadableDatabase();
420 db.beginTransaction();
421 try {
422 result = query(db, uri, projection, selection, selectionArgs, sortOrder);
423 db.setTransactionSuccessful();
424 } finally {
425 db.endTransaction();
426 }
427 return result;
428 }
429
430 private Cursor query(
431 SQLiteDatabase db,
432 Uri uri,
433 String[] projection,
434 String selection,
435 String[] selectionArgs,
436 String sortOrder
437 ) {
438
439 SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();
440
441 sqlQuery.setTables(ProviderTableMeta.FILE_TABLE_NAME);
442 sqlQuery.setProjectionMap(mFileProjectionMap);
443
444 switch (mUriMatcher.match(uri)) {
445 case ROOT_DIRECTORY:
446 break;
447 case DIRECTORY:
448 String folderId = uri.getPathSegments().get(1);
449 sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + "="
450 + folderId);
451 break;
452 case SINGLE_FILE:
453 if (uri.getPathSegments().size() > 1) {
454 sqlQuery.appendWhere(ProviderTableMeta._ID + "="
455 + uri.getPathSegments().get(1));
456 }
457 break;
458 case SHARES:
459 sqlQuery.setTables(ProviderTableMeta.OCSHARES_TABLE_NAME);
460 sqlQuery.setProjectionMap(mOCSharesProjectionMap);
461 if (uri.getPathSegments().size() > 1) {
462 sqlQuery.appendWhere(ProviderTableMeta._ID + "="
463 + uri.getPathSegments().get(1));
464 }
465 break;
466 default:
467 throw new IllegalArgumentException("Unknown uri id: " + uri);
468 }
469
470 String order;
471 if (TextUtils.isEmpty(sortOrder)) {
472 if (mUriMatcher.match(uri) == SHARES) {
473 order = ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER;
474 } else {
475
476 order = ProviderTableMeta.FILE_DEFAULT_SORT_ORDER;
477 }
478 } else {
479 order = sortOrder;
480 }
481
482 // DB case_sensitive
483 db.execSQL("PRAGMA case_sensitive_like = true");
484 Cursor c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order);
485 c.setNotificationUri(getContext().getContentResolver(), uri);
486 return c;
487 }
488
489 @Override
490 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
491
492 int count = 0;
493 SQLiteDatabase db = mDbHelper.getWritableDatabase();
494 db.beginTransaction();
495 try {
496 count = update(db, uri, values, selection, selectionArgs);
497 db.setTransactionSuccessful();
498 } finally {
499 db.endTransaction();
500 }
501 getContext().getContentResolver().notifyChange(uri, null);
502 return count;
503 }
504
505
506
507 private int update(
508 SQLiteDatabase db,
509 Uri uri,
510 ContentValues values,
511 String selection,
512 String[] selectionArgs
513 ) {
514 switch (mUriMatcher.match(uri)) {
515 case DIRECTORY:
516 return 0; //updateFolderSize(db, selectionArgs[0]);
517 case SHARES:
518 return db.update(
519 ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs
520 );
521 default:
522 return db.update(
523 ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs
524 );
525 }
526 }
527
528 /*
529 private int updateFolderSize(SQLiteDatabase db, String folderId) {
530 int count = 0;
531 String [] whereArgs = new String[] { folderId };
532
533 // read current size saved for the folder
534 long folderSize = 0;
535 long folderParentId = -1;
536 Uri selectFolderUri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, folderId);
537 String[] folderProjection = new String[] { ProviderTableMeta.FILE_CONTENT_LENGTH, ProviderTableMeta.FILE_PARENT};
538 String folderWhere = ProviderTableMeta._ID + "=?";
539 Cursor folderCursor = query(db, selectFolderUri, folderProjection, folderWhere, whereArgs, null);
540 if (folderCursor != null && folderCursor.moveToFirst()) {
541 folderSize = folderCursor.getLong(folderCursor.getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH));;
542 folderParentId = folderCursor.getLong(folderCursor.getColumnIndex(ProviderTableMeta.FILE_PARENT));;
543 }
544 folderCursor.close();
545
546 // read and sum sizes of children
547 long childrenSize = 0;
548 Uri selectChildrenUri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, folderId);
549 String[] childrenProjection = new String[] { ProviderTableMeta.FILE_CONTENT_LENGTH, ProviderTableMeta.FILE_PARENT};
550 String childrenWhere = ProviderTableMeta.FILE_PARENT + "=?";
551 Cursor childrenCursor = query(db, selectChildrenUri, childrenProjection, childrenWhere, whereArgs, null);
552 if (childrenCursor != null && childrenCursor.moveToFirst()) {
553 while (!childrenCursor.isAfterLast()) {
554 childrenSize += childrenCursor.getLong(childrenCursor.getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH));
555 childrenCursor.moveToNext();
556 }
557 }
558 childrenCursor.close();
559
560 // update if needed
561 if (folderSize != childrenSize) {
562 Log_OC.d("FileContentProvider", "Updating " + folderSize + " to " + childrenSize);
563 ContentValues cv = new ContentValues();
564 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, childrenSize);
565 count = db.update(ProviderTableMeta.FILE_TABLE_NAME, cv, folderWhere, whereArgs);
566
567 // propagate update until root
568 if (folderParentId > FileDataStorageManager.ROOT_PARENT_ID) {
569 Log_OC.d("FileContentProvider", "Propagating update to " + folderParentId);
570 updateFolderSize(db, String.valueOf(folderParentId));
571 } else {
572 Log_OC.d("FileContentProvider", "NOT propagating to " + folderParentId);
573 }
574 } else {
575 Log_OC.d("FileContentProvider", "NOT updating, sizes are " + folderSize + " and " + childrenSize);
576 }
577 return count;
578 }
579 */
580
581 @Override
582 public ContentProviderResult[] applyBatch (ArrayList<ContentProviderOperation> operations)
583 throws OperationApplicationException {
584 Log_OC.d("FileContentProvider", "applying batch in provider " + this +
585 " (temporary: " + isTemporary() + ")" );
586 ContentProviderResult[] results = new ContentProviderResult[operations.size()];
587 int i=0;
588
589 SQLiteDatabase db = mDbHelper.getWritableDatabase();
590 db.beginTransaction(); // it's supposed that transactions can be nested
591 try {
592 for (ContentProviderOperation operation : operations) {
593 results[i] = operation.apply(this, results, i);
594 i++;
595 }
596 db.setTransactionSuccessful();
597 } finally {
598 db.endTransaction();
599 }
600 Log_OC.d("FileContentProvider", "applied batch in provider " + this);
601 return results;
602 }
603
604
605 class DataBaseHelper extends SQLiteOpenHelper {
606
607 public DataBaseHelper(Context context) {
608 super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);
609
610 }
611
612 @Override
613 public void onCreate(SQLiteDatabase db) {
614 // files table
615 Log_OC.i("SQL", "Entering in onCreate");
616 db.execSQL("CREATE TABLE " + ProviderTableMeta.FILE_TABLE_NAME + "("
617 + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, "
618 + ProviderTableMeta.FILE_NAME + " TEXT, "
619 + ProviderTableMeta.FILE_PATH + " TEXT, "
620 + ProviderTableMeta.FILE_PARENT + " INTEGER, "
621 + ProviderTableMeta.FILE_CREATION + " INTEGER, "
622 + ProviderTableMeta.FILE_MODIFIED + " INTEGER, "
623 + ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, "
624 + ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, "
625 + ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, "
626 + ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT, "
627 + ProviderTableMeta.FILE_LAST_SYNC_DATE + " INTEGER, "
628 + ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER, "
629 + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " INTEGER, "
630 + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " INTEGER, "
631 + ProviderTableMeta.FILE_ETAG + " TEXT, "
632 + ProviderTableMeta.FILE_SHARE_BY_LINK + " INTEGER, "
633 + ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT, "
634 + ProviderTableMeta.FILE_PERMISSIONS + " TEXT null,"
635 + ProviderTableMeta.FILE_REMOTE_ID + " TEXT null,"
636 + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER," //boolean
637 + ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER);" //boolean
638 );
639
640 // Create table ocshares
641 db.execSQL("CREATE TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME + "("
642 + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, "
643 + ProviderTableMeta.OCSHARES_FILE_SOURCE + " INTEGER, "
644 + ProviderTableMeta.OCSHARES_ITEM_SOURCE + " INTEGER, "
645 + ProviderTableMeta.OCSHARES_SHARE_TYPE + " INTEGER, "
646 + ProviderTableMeta.OCSHARES_SHARE_WITH + " TEXT, "
647 + ProviderTableMeta.OCSHARES_PATH + " TEXT, "
648 + ProviderTableMeta.OCSHARES_PERMISSIONS+ " INTEGER, "
649 + ProviderTableMeta.OCSHARES_SHARED_DATE + " INTEGER, "
650 + ProviderTableMeta.OCSHARES_EXPIRATION_DATE + " INTEGER, "
651 + ProviderTableMeta.OCSHARES_TOKEN + " TEXT, "
652 + ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME + " TEXT, "
653 + ProviderTableMeta.OCSHARES_IS_DIRECTORY + " INTEGER, " // boolean
654 + ProviderTableMeta.OCSHARES_USER_ID + " INTEGER, "
655 + ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + " INTEGER,"
656 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + " TEXT );" );
657 }
658
659 @Override
660 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
661 Log_OC.i("SQL", "Entering in onUpgrade");
662 boolean upgraded = false;
663 if (oldVersion == 1 && newVersion >= 2) {
664 Log_OC.i("SQL", "Entering in the #1 ADD in onUpgrade");
665 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
666 " ADD COLUMN " + ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER " +
667 " DEFAULT 0");
668 upgraded = true;
669 }
670 if (oldVersion < 3 && newVersion >= 3) {
671 Log_OC.i("SQL", "Entering in the #2 ADD in onUpgrade");
672 db.beginTransaction();
673 try {
674 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
675 " ADD COLUMN " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA +
676 " INTEGER " + " DEFAULT 0");
677
678 // assume there are not local changes pending to upload
679 db.execSQL("UPDATE " + ProviderTableMeta.FILE_TABLE_NAME +
680 " SET " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " = "
681 + System.currentTimeMillis() +
682 " WHERE " + ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL");
683
684 upgraded = true;
685 db.setTransactionSuccessful();
686 } finally {
687 db.endTransaction();
688 }
689 }
690 if (oldVersion < 4 && newVersion >= 4) {
691 Log_OC.i("SQL", "Entering in the #3 ADD in onUpgrade");
692 db.beginTransaction();
693 try {
694 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
695 " ADD COLUMN " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA +
696 " INTEGER " + " DEFAULT 0");
697
698 db.execSQL("UPDATE " + ProviderTableMeta.FILE_TABLE_NAME +
699 " SET " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " = " +
700 ProviderTableMeta.FILE_MODIFIED +
701 " WHERE " + ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL");
702
703 upgraded = true;
704 db.setTransactionSuccessful();
705 } finally {
706 db.endTransaction();
707 }
708 }
709 if (!upgraded)
710 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
711 ", newVersion == " + newVersion);
712
713 if (oldVersion < 5 && newVersion >= 5) {
714 Log_OC.i("SQL", "Entering in the #4 ADD in onUpgrade");
715 db.beginTransaction();
716 try {
717 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
718 " ADD COLUMN " + ProviderTableMeta.FILE_ETAG + " TEXT " +
719 " DEFAULT NULL");
720
721 upgraded = true;
722 db.setTransactionSuccessful();
723 } finally {
724 db.endTransaction();
725 }
726 }
727 if (!upgraded)
728 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
729 ", newVersion == " + newVersion);
730
731 if (oldVersion < 6 && newVersion >= 6) {
732 Log_OC.i("SQL", "Entering in the #5 ADD in onUpgrade");
733 db.beginTransaction();
734 try {
735 db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
736 " ADD COLUMN " + ProviderTableMeta.FILE_SHARE_BY_LINK + " INTEGER " +
737 " DEFAULT 0");
738
739 db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
740 " ADD COLUMN " + ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT " +
741 " DEFAULT NULL");
742
743 // Create table ocshares
744 db.execSQL("CREATE TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME + "("
745 + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, "
746 + ProviderTableMeta.OCSHARES_FILE_SOURCE + " INTEGER, "
747 + ProviderTableMeta.OCSHARES_ITEM_SOURCE + " INTEGER, "
748 + ProviderTableMeta.OCSHARES_SHARE_TYPE + " INTEGER, "
749 + ProviderTableMeta.OCSHARES_SHARE_WITH + " TEXT, "
750 + ProviderTableMeta.OCSHARES_PATH + " TEXT, "
751 + ProviderTableMeta.OCSHARES_PERMISSIONS + " INTEGER, "
752 + ProviderTableMeta.OCSHARES_SHARED_DATE + " INTEGER, "
753 + ProviderTableMeta.OCSHARES_EXPIRATION_DATE + " INTEGER, "
754 + ProviderTableMeta.OCSHARES_TOKEN + " TEXT, "
755 + ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME + " TEXT, "
756 + ProviderTableMeta.OCSHARES_IS_DIRECTORY + " INTEGER, " // boolean
757 + ProviderTableMeta.OCSHARES_USER_ID + " INTEGER, "
758 + ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + " INTEGER,"
759 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + " TEXT );");
760
761 upgraded = true;
762 db.setTransactionSuccessful();
763 } finally {
764 db.endTransaction();
765 }
766 }
767 if (!upgraded)
768 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
769 ", newVersion == " + newVersion);
770
771 if (oldVersion < 7 && newVersion >= 7) {
772 Log_OC.i("SQL", "Entering in the #7 ADD in onUpgrade");
773 db.beginTransaction();
774 try {
775 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
776 " ADD COLUMN " + ProviderTableMeta.FILE_PERMISSIONS + " TEXT " +
777 " DEFAULT NULL");
778
779 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
780 " ADD COLUMN " + ProviderTableMeta.FILE_REMOTE_ID + " TEXT " +
781 " DEFAULT NULL");
782
783 upgraded = true;
784 db.setTransactionSuccessful();
785 } finally {
786 db.endTransaction();
787 }
788 }
789 if (!upgraded)
790 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
791 ", newVersion == " + newVersion);
792
793 if (oldVersion < 8 && newVersion >= 8) {
794 Log_OC.i("SQL", "Entering in the #8 ADD in onUpgrade");
795 db.beginTransaction();
796 try {
797 db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
798 " ADD COLUMN " + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER " +
799 " DEFAULT 0");
800
801 upgraded = true;
802 db.setTransactionSuccessful();
803 } finally {
804 db.endTransaction();
805 }
806 }
807 if (!upgraded)
808 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
809 ", newVersion == " + newVersion);
810
811 if (oldVersion < 9 && newVersion >= 9) {
812 Log_OC.i("SQL", "Entering in the #9 ADD in onUpgrade");
813 db.beginTransaction();
814 try {
815 db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
816 " ADD COLUMN " + ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER " +
817 " DEFAULT 0");
818
819 upgraded = true;
820 db.setTransactionSuccessful();
821 } finally {
822 db.endTransaction();
823 }
824 }
825 if (!upgraded)
826 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
827 ", newVersion == " + newVersion);
828
829 if (oldVersion < 10 && newVersion >= 10) {
830 Log_OC.i("SQL", "Entering in the #10 ADD in onUpgrade");
831 updateAccountName(db);
832 upgraded = true;
833 }
834 if (!upgraded)
835 Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
836 ", newVersion == " + newVersion);
837 }
838 }
839
840
841 /**
842 * Version 10 of database does not modify its scheme. It coincides with the upgrade of the ownCloud account names
843 * structure to include in it the path to the server instance. Updating the account names and path to local files
844 * in the files table is a must to keep the existing account working and the database clean.
845 *
846 * See {@link com.owncloud.android.authentication.AccountUtils#updateAccountVersion(android.content.Context)}
847 *
848 * @param db Database where table of files is included.
849 */
850 private void updateAccountName(SQLiteDatabase db){
851 Log_OC.d("SQL", "THREAD: "+ Thread.currentThread().getName());
852 AccountManager ama = AccountManager.get(getContext());
853 try {
854 // get accounts from AccountManager ; we can't be sure if accounts in it are updated or not although
855 // we know the update was previously done in {link @FileActivity#onCreate} because the changes through
856 // AccountManager are not synchronous
857 Account[] accounts = AccountManager.get(getContext()).getAccountsByType(
858 MainApp.getAccountType());
859 String serverUrl, username, oldAccountName, newAccountName;
860 for (Account account : accounts) {
861 // build both old and new account name
862 serverUrl = ama.getUserData(account, AccountUtils.Constants.KEY_OC_BASE_URL);
863 username = account.name.substring(0, account.name.lastIndexOf('@'));
864 oldAccountName = AccountUtils.buildAccountNameOld(Uri.parse(serverUrl), username);
865 newAccountName = AccountUtils.buildAccountName(Uri.parse(serverUrl), username);
866
867 // update values in database
868 db.beginTransaction();
869 try {
870 ContentValues cv = new ContentValues();
871 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, newAccountName);
872 int num = db.update(ProviderTableMeta.FILE_TABLE_NAME,
873 cv,
874 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
875 new String[]{oldAccountName});
876
877 Log_OC.d("SQL", "Updated account in database: old name == " + oldAccountName +
878 ", new name == " + newAccountName + " (" + num + " rows updated )");
879
880 // update path for downloaded files
881 updateDownloadedFiles(db, newAccountName, oldAccountName);
882
883 db.setTransactionSuccessful();
884
885 } catch (SQLException e) {
886 Log_OC.e(TAG, "SQL Exception upgrading account names or paths in database", e);
887 } finally {
888 db.endTransaction();
889 }
890 }
891 } catch (Exception e) {
892 Log_OC.e(TAG, "Exception upgrading account names or paths in database", e);
893 }
894 }
895
896
897 /**
898 * Rename the local ownCloud folder of one account to match the a rename of the account itself. Updates the
899 * table of files in database so that the paths to the local files keep being the same.
900 *
901 * @param db Database where table of files is included.
902 * @param newAccountName New name for the target OC account.
903 * @param oldAccountName Old name of the target OC account.
904 */
905 private void updateDownloadedFiles(SQLiteDatabase db, String newAccountName,
906 String oldAccountName) {
907
908 String whereClause = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
909 ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL";
910
911 Cursor c = db.query(ProviderTableMeta.FILE_TABLE_NAME,
912 null,
913 whereClause,
914 new String[] { newAccountName },
915 null, null, null);
916
917 try {
918 if (c.moveToFirst()) {
919 // create storage path
920 String oldAccountPath = FileStorageUtils.getSavePath(oldAccountName);
921 String newAccountPath = FileStorageUtils.getSavePath(newAccountName);
922
923 // move files
924 File oldAccountFolder = new File(oldAccountPath);
925 File newAccountFolder = new File(newAccountPath);
926 oldAccountFolder.renameTo(newAccountFolder);
927
928 // update database
929 do {
930 // Update database
931 String oldPath = c.getString(
932 c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
933 OCFile file = new OCFile(
934 c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH)));
935 String newPath = FileStorageUtils.getDefaultSavePathFor(newAccountName, file);
936
937 ContentValues cv = new ContentValues();
938 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newPath);
939 db.update(ProviderTableMeta.FILE_TABLE_NAME,
940 cv,
941 ProviderTableMeta.FILE_STORAGE_PATH + "=?",
942 new String[]{oldPath});
943
944 Log_OC.v("SQL", "Updated path of downloaded file: old file name == " + oldPath +
945 ", new file name == " + newPath);
946
947 } while (c.moveToNext());
948 }
949 } finally {
950 c.close();
951 }
952
953 }
954
955 }