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