c1bf61be62dbb16b116314f498cfbb3de1e38c33
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / FileDataStorageManager.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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.Collection;
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Vector;
28
29 import com.owncloud.android.MainApp;
30 import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
31 import com.owncloud.android.lib.common.utils.Log_OC;
32 import com.owncloud.android.lib.resources.shares.OCShare;
33 import com.owncloud.android.lib.resources.shares.ShareType;
34 import com.owncloud.android.lib.resources.files.FileUtils;
35 import com.owncloud.android.utils.FileStorageUtils;
36
37 import android.accounts.Account;
38 import android.content.ContentProviderClient;
39 import android.content.ContentProviderOperation;
40 import android.content.ContentProviderResult;
41 import android.content.ContentResolver;
42 import android.content.ContentUris;
43 import android.content.ContentValues;
44 import android.content.Intent;
45 import android.content.OperationApplicationException;
46 import android.database.Cursor;
47 import android.net.Uri;
48 import android.os.RemoteException;
49
50 public class FileDataStorageManager {
51
52 public static final int ROOT_PARENT_ID = 0;
53
54 private ContentResolver mContentResolver;
55 private ContentProviderClient mContentProviderClient;
56 private Account mAccount;
57
58 private static String TAG = FileDataStorageManager.class.getSimpleName();
59
60
61 public FileDataStorageManager(Account account, ContentResolver cr) {
62 mContentProviderClient = null;
63 mContentResolver = cr;
64 mAccount = account;
65 }
66
67 public FileDataStorageManager(Account account, ContentProviderClient cp) {
68 mContentProviderClient = cp;
69 mContentResolver = null;
70 mAccount = account;
71 }
72
73
74 public void setAccount(Account account) {
75 mAccount = account;
76 }
77
78 public Account getAccount() {
79 return mAccount;
80 }
81
82 public void setContentResolver(ContentResolver cr) {
83 mContentResolver = cr;
84 }
85
86 public ContentResolver getContentResolver() {
87 return mContentResolver;
88 }
89
90 public void setContentProviderClient(ContentProviderClient cp) {
91 mContentProviderClient = cp;
92 }
93
94 public ContentProviderClient getContentProviderClient() {
95 return mContentProviderClient;
96 }
97
98
99 public OCFile getFileByPath(String path) {
100 Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
101 OCFile file = null;
102 if (c.moveToFirst()) {
103 file = createFileInstance(c);
104 }
105 c.close();
106 if (file == null && OCFile.ROOT_PATH.equals(path)) {
107 return createRootDir(); // root should always exist
108 }
109 return file;
110 }
111
112
113 public OCFile getFileById(long id) {
114 Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
115 OCFile file = null;
116 if (c.moveToFirst()) {
117 file = createFileInstance(c);
118 }
119 c.close();
120 return file;
121 }
122
123 public OCFile getFileByLocalPath(String path) {
124 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
125 OCFile file = null;
126 if (c.moveToFirst()) {
127 file = createFileInstance(c);
128 }
129 c.close();
130 return file;
131 }
132
133 public boolean fileExists(long id) {
134 return fileExists(ProviderTableMeta._ID, String.valueOf(id));
135 }
136
137 public boolean fileExists(String path) {
138 return fileExists(ProviderTableMeta.FILE_PATH, path);
139 }
140
141
142 public Vector<OCFile> getFolderContent(OCFile f) {
143 if (f != null && f.isFolder() && f.getFileId() != -1) {
144 return getFolderContent(f.getFileId());
145
146 } else {
147 return new Vector<OCFile>();
148 }
149 }
150
151
152 public Vector<OCFile> getFolderImages(OCFile folder) {
153 Vector<OCFile> ret = new Vector<OCFile>();
154 if (folder != null) {
155 // TODO better implementation, filtering in the access to database instead of here
156 Vector<OCFile> tmp = getFolderContent(folder);
157 OCFile current = null;
158 for (int i=0; i<tmp.size(); i++) {
159 current = tmp.get(i);
160 if (current.isImage()) {
161 ret.add(current);
162 }
163 }
164 }
165 return ret;
166 }
167
168
169 public boolean saveFile(OCFile file) {
170 boolean overriden = false;
171 ContentValues cv = new ContentValues();
172 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
173 cv.put(
174 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
175 file.getModificationTimestampAtLastSyncForData()
176 );
177 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
178 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
179 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
180 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
181 //if (file.getParentId() != DataStorageManager.ROOT_PARENT_ID)
182 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
183 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
184 if (!file.isFolder())
185 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
186 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
187 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
188 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
189 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
190 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
191 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
192 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
193 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
194 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
195 cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
196 cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
197 cv.put(ProviderTableMeta.FILE_IS_UPLOADING, file.isUploading());
198
199 boolean sameRemotePath = fileExists(file.getRemotePath());
200 if (sameRemotePath ||
201 fileExists(file.getFileId()) ) { // for renamed files
202
203 OCFile oldFile = null;
204 if (sameRemotePath) {
205 oldFile = getFileByPath(file.getRemotePath());
206 file.setFileId(oldFile.getFileId());
207 } else {
208 oldFile = getFileById(file.getFileId());
209 }
210
211 overriden = true;
212 if (getContentResolver() != null) {
213 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
214 ProviderTableMeta._ID + "=?",
215 new String[] { String.valueOf(file.getFileId()) });
216 } else {
217 try {
218 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI,
219 cv, ProviderTableMeta._ID + "=?",
220 new String[] { String.valueOf(file.getFileId()) });
221 } catch (RemoteException e) {
222 Log_OC.e(TAG,
223 "Fail to insert insert file to database "
224 + e.getMessage());
225 }
226 }
227 } else {
228 Uri result_uri = null;
229 if (getContentResolver() != null) {
230 result_uri = getContentResolver().insert(
231 ProviderTableMeta.CONTENT_URI_FILE, cv);
232 } else {
233 try {
234 result_uri = getContentProviderClient().insert(
235 ProviderTableMeta.CONTENT_URI_FILE, cv);
236 } catch (RemoteException e) {
237 Log_OC.e(TAG,
238 "Fail to insert insert file to database "
239 + e.getMessage());
240 }
241 }
242 if (result_uri != null) {
243 long new_id = Long.parseLong(result_uri.getPathSegments()
244 .get(1));
245 file.setFileId(new_id);
246 }
247 }
248
249 // if (file.isFolder()) {
250 // updateFolderSize(file.getFileId());
251 // } else {
252 // updateFolderSize(file.getParentId());
253 // }
254
255 return overriden;
256 }
257
258
259 /**
260 * Inserts or updates the list of files contained in a given folder.
261 *
262 * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
263 * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
264 *
265 * @param folder
266 * @param files
267 * @param removeNotUpdated
268 */
269 public void saveFolder(
270 OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove
271 ) {
272
273 Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size()
274 + " children and " + filesToRemove.size() + " files to remove");
275
276 ArrayList<ContentProviderOperation> operations =
277 new ArrayList<ContentProviderOperation>(updatedFiles.size());
278
279 // prepare operations to insert or update files to save in the given folder
280 for (OCFile file : updatedFiles) {
281 ContentValues cv = new ContentValues();
282 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
283 cv.put(
284 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
285 file.getModificationTimestampAtLastSyncForData()
286 );
287 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
288 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
289 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
290 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
291 //cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
292 cv.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
293 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
294 if (!file.isFolder()) {
295 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
296 }
297 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
298 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
299 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
300 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
301 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
302 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
303 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
304 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
305 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
306 cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
307 cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
308 cv.put(ProviderTableMeta.FILE_IS_UPLOADING, file.isUploading());
309
310 boolean existsByPath = fileExists(file.getRemotePath());
311 if (existsByPath || fileExists(file.getFileId())) {
312 // updating an existing file
313 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
314 withValues(cv).
315 withSelection( ProviderTableMeta._ID + "=?",
316 new String[] { String.valueOf(file.getFileId()) })
317 .build());
318
319 } else {
320 // adding a new file
321 operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
322 withValues(cv).build());
323 }
324 }
325
326 // prepare operations to remove files in the given folder
327 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
328 ProviderTableMeta.FILE_PATH + "=?";
329 String [] whereArgs = null;
330 for (OCFile file : filesToRemove) {
331 if (file.getParentId() == folder.getFileId()) {
332 whereArgs = new String[]{mAccount.name, file.getRemotePath()};
333 //Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, "" + file.getFileId());
334 if (file.isFolder()) {
335 operations.add(ContentProviderOperation.newDelete(
336 ContentUris.withAppendedId(
337 ProviderTableMeta.CONTENT_URI_DIR, file.getFileId()
338 )
339 ).withSelection(where, whereArgs).build());
340
341 File localFolder =
342 new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
343 if (localFolder.exists()) {
344 removeLocalFolder(localFolder);
345 }
346 } else {
347 operations.add(ContentProviderOperation.newDelete(
348 ContentUris.withAppendedId(
349 ProviderTableMeta.CONTENT_URI_FILE, file.getFileId()
350 )
351 ).withSelection(where, whereArgs).build());
352
353 if (file.isDown()) {
354 String path = file.getStoragePath();
355 new File(path).delete();
356 triggerMediaScan(path); // notify MediaScanner about removed file
357 }
358 }
359 }
360 }
361
362 // update metadata of folder
363 ContentValues cv = new ContentValues();
364 cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
365 cv.put(
366 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
367 folder.getModificationTimestampAtLastSyncForData()
368 );
369 cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
370 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, 0);
371 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
372 cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
373 cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
374 cv.put(ProviderTableMeta.FILE_PATH, folder.getRemotePath());
375 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
376 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.getLastSyncDateForProperties());
377 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.getLastSyncDateForData());
378 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, folder.keepInSync() ? 1 : 0);
379 cv.put(ProviderTableMeta.FILE_ETAG, folder.getEtag());
380 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, folder.isShareByLink() ? 1 : 0);
381 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, folder.getPublicLink());
382 cv.put(ProviderTableMeta.FILE_PERMISSIONS, folder.getPermissions());
383 cv.put(ProviderTableMeta.FILE_REMOTE_ID, folder.getRemoteId());
384
385 operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
386 withValues(cv).
387 withSelection( ProviderTableMeta._ID + "=?",
388 new String[] { String.valueOf(folder.getFileId()) })
389 .build());
390
391 // apply operations in batch
392 ContentProviderResult[] results = null;
393 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
394 try {
395 if (getContentResolver() != null) {
396 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
397
398 } else {
399 results = getContentProviderClient().applyBatch(operations);
400 }
401
402 } catch (OperationApplicationException e) {
403 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
404
405 } catch (RemoteException e) {
406 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
407 }
408
409 // update new id in file objects for insertions
410 if (results != null) {
411 long newId;
412 Iterator<OCFile> filesIt = updatedFiles.iterator();
413 OCFile file = null;
414 for (int i=0; i<results.length; i++) {
415 if (filesIt.hasNext()) {
416 file = filesIt.next();
417 } else {
418 file = null;
419 }
420 if (results[i].uri != null) {
421 newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
422 //updatedFiles.get(i).setFileId(newId);
423 if (file != null) {
424 file.setFileId(newId);
425 }
426 }
427 }
428 }
429
430 //updateFolderSize(folder.getFileId());
431
432 }
433
434
435 // /**
436 // *
437 // * @param id
438 // */
439 // private void updateFolderSize(long id) {
440 // if (id > FileDataStorageManager.ROOT_PARENT_ID) {
441 // Log_OC.d(TAG, "Updating size of " + id);
442 // if (getContentResolver() != null) {
443 // getContentResolver().update(ProviderTableMeta.CONTENT_URI_DIR,
444 // new ContentValues(),
445 // won't be used, but cannot be null; crashes in KLP
446 // ProviderTableMeta._ID + "=?",
447 // new String[] { String.valueOf(id) });
448 // } else {
449 // try {
450 // getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_DIR,
451 // new ContentValues(),
452 // won't be used, but cannot be null; crashes in KLP
453 // ProviderTableMeta._ID + "=?",
454 // new String[] { String.valueOf(id) });
455 //
456 // } catch (RemoteException e) {
457 // Log_OC.e(
458 // TAG, "Exception in update of folder size through compatibility patch " + e.getMessage());
459 // }
460 // }
461 // } else {
462 // Log_OC.e(TAG, "not updating size for folder " + id);
463 // }
464 // }
465
466
467 public boolean removeFile(OCFile file, boolean removeDBData, boolean removeLocalCopy) {
468 boolean success = true;
469 if (file != null) {
470 if (file.isFolder()) {
471 success = removeFolder(file, removeDBData, removeLocalCopy);
472
473 } else {
474 if (removeDBData) {
475 Uri file_uri = ContentUris.withAppendedId(
476 ProviderTableMeta.CONTENT_URI_FILE,
477 file.getFileId()
478 );
479 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
480 ProviderTableMeta.FILE_PATH + "=?";
481 String [] whereArgs = new String[]{mAccount.name, file.getRemotePath()};
482 int deleted = 0;
483 if (getContentProviderClient() != null) {
484 try {
485 deleted = getContentProviderClient().delete(file_uri, where, whereArgs);
486 } catch (RemoteException e) {
487 e.printStackTrace();
488 }
489 } else {
490 deleted = getContentResolver().delete(file_uri, where, whereArgs);
491 }
492 success &= (deleted > 0);
493 }
494 String localPath = file.getStoragePath();
495 if (removeLocalCopy && file.isDown() && localPath != null && success) {
496 success = new File(localPath).delete();
497 if (success) {
498 triggerMediaScan(localPath);
499 }
500 if (!removeDBData && success) {
501 // maybe unnecessary, but should be checked TODO remove if unnecessary
502 file.setStoragePath(null);
503 saveFile(file);
504 }
505 }
506 }
507 }
508 return success;
509 }
510
511
512 public boolean removeFolder(OCFile folder, boolean removeDBData, boolean removeLocalContent) {
513 boolean success = true;
514 if (folder != null && folder.isFolder()) {
515 if (removeDBData && folder.getFileId() != -1) {
516 success = removeFolderInDb(folder);
517 }
518 if (removeLocalContent && success) {
519 success = removeLocalFolder(folder);
520 }
521 }
522 return success;
523 }
524
525 private boolean removeFolderInDb(OCFile folder) {
526 Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" +
527 folder.getFileId()); // URI for recursive deletion
528 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
529 ProviderTableMeta.FILE_PATH + "=?";
530 String [] whereArgs = new String[]{mAccount.name, folder.getRemotePath()};
531 int deleted = 0;
532 if (getContentProviderClient() != null) {
533 try {
534 deleted = getContentProviderClient().delete(folder_uri, where, whereArgs);
535 } catch (RemoteException e) {
536 e.printStackTrace();
537 }
538 } else {
539 deleted = getContentResolver().delete(folder_uri, where, whereArgs);
540 }
541 return deleted > 0;
542 }
543
544 private boolean removeLocalFolder(OCFile folder) {
545 boolean success = true;
546 File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, folder));
547 if (localFolder.exists()) {
548 // stage 1: remove the local files already registered in the files database
549 Vector<OCFile> files = getFolderContent(folder.getFileId());
550 if (files != null) {
551 for (OCFile file : files) {
552 if (file.isFolder()) {
553 success &= removeLocalFolder(file);
554 } else {
555 if (file.isDown()) {
556 String path = file.getStoragePath();
557 File localFile = new File(file.getStoragePath());
558 success &= localFile.delete();
559 if (success) {
560 file.setStoragePath(null);
561 saveFile(file);
562 triggerMediaScan(path); // notify MediaScanner about removed file
563 }
564 }
565 }
566 }
567 }
568
569 // stage 2: remove the folder itself and any local file inside out of sync;
570 // for instance, after clearing the app cache or reinstalling
571 success &= removeLocalFolder(localFolder);
572 }
573 return success;
574 }
575
576 private boolean removeLocalFolder(File localFolder) {
577 boolean success = true;
578 File[] localFiles = localFolder.listFiles();
579 if (localFiles != null) {
580 for (File localFile : localFiles) {
581 if (localFile.isDirectory()) {
582 success &= removeLocalFolder(localFile);
583 } else {
584 String path = localFile.getAbsolutePath();
585 success &= localFile.delete();
586 triggerMediaScan(path); // notify MediaScanner about removed file
587 }
588 }
589 }
590 success &= localFolder.delete();
591 return success;
592 }
593
594
595 /**
596 * Updates database and file system for a file or folder that was moved to a different location.
597 *
598 * TODO explore better (faster) implementations
599 * TODO throw exceptions up !
600 */
601 public void moveLocalFile(OCFile file, String targetPath, String targetParentPath) {
602
603 if (file != null && file.fileExists() && !OCFile.ROOT_PATH.equals(file.getFileName())) {
604
605 OCFile targetParent = getFileByPath(targetParentPath);
606 if (targetParent == null) {
607 throw new IllegalStateException("Parent folder of the target path does not exist!!");
608 }
609
610 /// 1. get all the descendants of the moved element in a single QUERY
611 Cursor c = null;
612 if (getContentProviderClient() != null) {
613 try {
614 c = getContentProviderClient().query(
615 ProviderTableMeta.CONTENT_URI,
616 null,
617 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
618 ProviderTableMeta.FILE_PATH + " LIKE ? ",
619 new String[] {
620 mAccount.name,
621 file.getRemotePath() + "%"
622 },
623 ProviderTableMeta.FILE_PATH + " ASC "
624 );
625 } catch (RemoteException e) {
626 Log_OC.e(TAG, e.getMessage());
627 }
628
629 } else {
630 c = getContentResolver().query(
631 ProviderTableMeta.CONTENT_URI,
632 null,
633 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
634 ProviderTableMeta.FILE_PATH + " LIKE ? ",
635 new String[] {
636 mAccount.name,
637 file.getRemotePath() + "%"
638 },
639 ProviderTableMeta.FILE_PATH + " ASC "
640 );
641 }
642
643 /// 2. prepare a batch of update operations to change all the descendants
644 ArrayList<ContentProviderOperation> operations =
645 new ArrayList<ContentProviderOperation>(c.getCount());
646 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
647 List<String> originalPathsToTriggerMediaScan = new ArrayList<String>();
648 List<String> newPathsToTriggerMediaScan = new ArrayList<String>();
649 if (c.moveToFirst()) {
650 int lengthOfOldPath = file.getRemotePath().length();
651 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
652 do {
653 ContentValues cv = new ContentValues(); // keep construction in the loop
654 OCFile child = createFileInstance(c);
655 cv.put(
656 ProviderTableMeta.FILE_PATH,
657 targetPath + child.getRemotePath().substring(lengthOfOldPath)
658 );
659 if (child.getStoragePath() != null &&
660 child.getStoragePath().startsWith(defaultSavePath)) {
661 // update link to downloaded content - but local move is not done here!
662 String targetLocalPath = defaultSavePath + targetPath +
663 child.getStoragePath().substring(lengthOfOldStoragePath);
664
665 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, targetLocalPath);
666
667 originalPathsToTriggerMediaScan.add(child.getStoragePath());
668 newPathsToTriggerMediaScan.add(targetLocalPath);
669
670 }
671 if (child.getRemotePath().equals(file.getRemotePath())) {
672 cv.put(
673 ProviderTableMeta.FILE_PARENT,
674 targetParent.getFileId()
675 );
676 }
677 operations.add(
678 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
679 withValues(cv).
680 withSelection(
681 ProviderTableMeta._ID + "=?",
682 new String[] { String.valueOf(child.getFileId()) }
683 )
684 .build());
685
686 } while (c.moveToNext());
687 }
688 c.close();
689
690 /// 3. apply updates in batch
691 try {
692 if (getContentResolver() != null) {
693 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
694
695 } else {
696 getContentProviderClient().applyBatch(operations);
697 }
698
699 } catch (Exception e) {
700 Log_OC.e(TAG, "Fail to update " + file.getFileId() + " and descendants in database", e);
701 }
702
703 /// 4. move in local file system
704 String originalLocalPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
705 String targetLocalPath = defaultSavePath + targetPath;
706 File localFile = new File(originalLocalPath);
707 boolean renamed = false;
708 if (localFile.exists()) {
709 File targetFile = new File(targetLocalPath);
710 File targetFolder = targetFile.getParentFile();
711 if (!targetFolder.exists()) {
712 targetFolder.mkdirs();
713 }
714 renamed = localFile.renameTo(targetFile);
715 }
716
717 if (renamed) {
718 Iterator<String> it = originalPathsToTriggerMediaScan.iterator();
719 while (it.hasNext()) {
720 // Notify MediaScanner about removed file
721 triggerMediaScan(it.next());
722 }
723 it = newPathsToTriggerMediaScan.iterator();
724 while (it.hasNext()) {
725 // Notify MediaScanner about new file/folder
726 triggerMediaScan(it.next());
727 }
728 }
729 }
730
731 }
732
733
734 private Vector<OCFile> getFolderContent(long parentId) {
735
736 Vector<OCFile> ret = new Vector<OCFile>();
737
738 Uri req_uri = Uri.withAppendedPath(
739 ProviderTableMeta.CONTENT_URI_DIR,
740 String.valueOf(parentId));
741 Cursor c = null;
742
743 if (getContentProviderClient() != null) {
744 try {
745 c = getContentProviderClient().query(req_uri, null,
746 ProviderTableMeta.FILE_PARENT + "=?" ,
747 new String[] { String.valueOf(parentId)}, null);
748 } catch (RemoteException e) {
749 Log_OC.e(TAG, e.getMessage());
750 return ret;
751 }
752 } else {
753 c = getContentResolver().query(req_uri, null,
754 ProviderTableMeta.FILE_PARENT + "=?" ,
755 new String[] { String.valueOf(parentId)}, null);
756 }
757
758 if (c.moveToFirst()) {
759 do {
760 OCFile child = createFileInstance(c);
761 ret.add(child);
762 } while (c.moveToNext());
763 }
764
765 c.close();
766
767 Collections.sort(ret);
768
769 return ret;
770 }
771
772
773 private OCFile createRootDir() {
774 OCFile file = new OCFile(OCFile.ROOT_PATH);
775 file.setMimetype("DIR");
776 file.setParentId(FileDataStorageManager.ROOT_PARENT_ID);
777 saveFile(file);
778 return file;
779 }
780
781 private boolean fileExists(String cmp_key, String value) {
782 Cursor c;
783 if (getContentResolver() != null) {
784 c = getContentResolver()
785 .query(ProviderTableMeta.CONTENT_URI,
786 null,
787 cmp_key + "=? AND "
788 + ProviderTableMeta.FILE_ACCOUNT_OWNER
789 + "=?",
790 new String[] { value, mAccount.name }, null);
791 } else {
792 try {
793 c = getContentProviderClient().query(
794 ProviderTableMeta.CONTENT_URI,
795 null,
796 cmp_key + "=? AND "
797 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
798 new String[] { value, mAccount.name }, null);
799 } catch (RemoteException e) {
800 Log_OC.e(TAG,
801 "Couldn't determine file existance, assuming non existance: "
802 + e.getMessage());
803 return false;
804 }
805 }
806 boolean retval = c.moveToFirst();
807 c.close();
808 return retval;
809 }
810
811 private Cursor getCursorForValue(String key, String value) {
812 Cursor c = null;
813 if (getContentResolver() != null) {
814 c = getContentResolver()
815 .query(ProviderTableMeta.CONTENT_URI,
816 null,
817 key + "=? AND "
818 + ProviderTableMeta.FILE_ACCOUNT_OWNER
819 + "=?",
820 new String[] { value, mAccount.name }, null);
821 } else {
822 try {
823 c = getContentProviderClient().query(
824 ProviderTableMeta.CONTENT_URI,
825 null,
826 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
827 + "=?", new String[] { value, mAccount.name },
828 null);
829 } catch (RemoteException e) {
830 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
831 c = null;
832 }
833 }
834 return c;
835 }
836
837
838 private OCFile createFileInstance(Cursor c) {
839 OCFile file = null;
840 if (c != null) {
841 file = new OCFile(c.getString(c
842 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
843 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
844 file.setParentId(c.getLong(c
845 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
846 file.setMimetype(c.getString(c
847 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
848 if (!file.isFolder()) {
849 file.setStoragePath(c.getString(c
850 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
851 if (file.getStoragePath() == null) {
852 // try to find existing file and bind it with current account;
853 // with the current update of SynchronizeFolderOperation, this won't be
854 // necessary anymore after a full synchronization of the account
855 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
856 if (f.exists()) {
857 file.setStoragePath(f.getAbsolutePath());
858 file.setLastSyncDateForData(f.lastModified());
859 }
860 }
861 }
862 file.setFileLength(c.getLong(c
863 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
864 file.setCreationTimestamp(c.getLong(c
865 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
866 file.setModificationTimestamp(c.getLong(c
867 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
868 file.setModificationTimestampAtLastSyncForData(c.getLong(c
869 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)));
870 file.setLastSyncDateForProperties(c.getLong(c
871 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
872 file.setLastSyncDateForData(c.getLong(c.
873 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
874 file.setKeepInSync(c.getInt(
875 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
876 file.setEtag(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)));
877 file.setShareByLink(c.getInt(
878 c.getColumnIndex(ProviderTableMeta.FILE_SHARE_BY_LINK)) == 1 ? true : false);
879 file.setPublicLink(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PUBLIC_LINK)));
880 file.setPermissions(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PERMISSIONS)));
881 file.setRemoteId(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID)));
882 file.setNeedsUpdateThumbnail(c.getInt(
883 c.getColumnIndex(ProviderTableMeta.FILE_UPDATE_THUMBNAIL)) == 1 ? true : false);
884 file.setDownloading(c.getInt(
885 c.getColumnIndex(ProviderTableMeta.FILE_IS_DOWNLOADING)) == 1 ? true : false);
886 file.setUploading(c.getInt(
887 c.getColumnIndex(ProviderTableMeta.FILE_IS_UPLOADING)) == 1 ? true : false);
888
889 }
890 return file;
891 }
892
893 /**
894 * Returns if the file/folder is shared by link or not
895 * @param path Path of the file/folder
896 * @return
897 */
898 public boolean isShareByLink(String path) {
899 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
900 OCFile file = null;
901 if (c.moveToFirst()) {
902 file = createFileInstance(c);
903 }
904 c.close();
905 return file.isShareByLink();
906 }
907
908 /**
909 * Returns the public link of the file/folder
910 * @param path Path of the file/folder
911 * @return
912 */
913 public String getPublicLink(String path) {
914 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
915 OCFile file = null;
916 if (c.moveToFirst()) {
917 file = createFileInstance(c);
918 }
919 c.close();
920 return file.getPublicLink();
921 }
922
923
924 // Methods for Shares
925 public boolean saveShare(OCShare share) {
926 boolean overriden = false;
927 ContentValues cv = new ContentValues();
928 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
929 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
930 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
931 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
932 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
933 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
934 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
935 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
936 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
937 cv.put(
938 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
939 share.getSharedWithDisplayName()
940 );
941 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
942 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
943 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
944 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
945
946 if (shareExists(share.getIdRemoteShared())) { // for renamed files
947
948 overriden = true;
949 if (getContentResolver() != null) {
950 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
951 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
952 new String[] { String.valueOf(share.getIdRemoteShared()) });
953 } else {
954 try {
955 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
956 cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
957 new String[] { String.valueOf(share.getIdRemoteShared()) });
958 } catch (RemoteException e) {
959 Log_OC.e(TAG,
960 "Fail to insert insert file to database "
961 + e.getMessage());
962 }
963 }
964 } else {
965 Uri result_uri = null;
966 if (getContentResolver() != null) {
967 result_uri = getContentResolver().insert(
968 ProviderTableMeta.CONTENT_URI_SHARE, cv);
969 } else {
970 try {
971 result_uri = getContentProviderClient().insert(
972 ProviderTableMeta.CONTENT_URI_SHARE, cv);
973 } catch (RemoteException e) {
974 Log_OC.e(TAG,
975 "Fail to insert insert file to database "
976 + e.getMessage());
977 }
978 }
979 if (result_uri != null) {
980 long new_id = Long.parseLong(result_uri.getPathSegments()
981 .get(1));
982 share.setId(new_id);
983 }
984 }
985
986 return overriden;
987 }
988
989
990 public OCShare getFirstShareByPathAndType(String path, ShareType type) {
991 Cursor c = null;
992 if (getContentResolver() != null) {
993 c = getContentResolver().query(
994 ProviderTableMeta.CONTENT_URI_SHARE,
995 null,
996 ProviderTableMeta.OCSHARES_PATH + "=? AND "
997 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
998 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
999 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
1000 null);
1001 } else {
1002 try {
1003 c = getContentProviderClient().query(
1004 ProviderTableMeta.CONTENT_URI_SHARE,
1005 null,
1006 ProviderTableMeta.OCSHARES_PATH + "=? AND "
1007 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
1008 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1009 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
1010 null);
1011
1012 } catch (RemoteException e) {
1013 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
1014 c = null;
1015 }
1016 }
1017 OCShare share = null;
1018 if (c.moveToFirst()) {
1019 share = createShareInstance(c);
1020 }
1021 c.close();
1022 return share;
1023 }
1024
1025 private OCShare createShareInstance(Cursor c) {
1026 OCShare share = null;
1027 if (c != null) {
1028 share = new OCShare(c.getString(c
1029 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
1030 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1031 share.setFileSource(c.getLong(c
1032 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
1033 share.setShareType(ShareType.fromValue(c.getInt(c
1034 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
1035 share.setPermissions(c.getInt(c
1036 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
1037 share.setSharedDate(c.getLong(c
1038 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
1039 share.setExpirationDate(c.getLong(c
1040 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
1041 share.setToken(c.getString(c
1042 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
1043 share.setSharedWithDisplayName(c.getString(c
1044 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
1045 share.setIsFolder(c.getInt(
1046 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1 ? true : false);
1047 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
1048 share.setIdRemoteShared(
1049 c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED))
1050 );
1051
1052 }
1053 return share;
1054 }
1055
1056 private boolean shareExists(String cmp_key, String value) {
1057 Cursor c;
1058 if (getContentResolver() != null) {
1059 c = getContentResolver()
1060 .query(ProviderTableMeta.CONTENT_URI_SHARE,
1061 null,
1062 cmp_key + "=? AND "
1063 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
1064 + "=?",
1065 new String[] { value, mAccount.name }, null);
1066 } else {
1067 try {
1068 c = getContentProviderClient().query(
1069 ProviderTableMeta.CONTENT_URI_SHARE,
1070 null,
1071 cmp_key + "=? AND "
1072 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1073 new String[] { value, mAccount.name }, null);
1074 } catch (RemoteException e) {
1075 Log_OC.e(TAG,
1076 "Couldn't determine file existance, assuming non existance: "
1077 + e.getMessage());
1078 return false;
1079 }
1080 }
1081 boolean retval = c.moveToFirst();
1082 c.close();
1083 return retval;
1084 }
1085
1086 private boolean shareExists(long remoteId) {
1087 return shareExists(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, String.valueOf(remoteId));
1088 }
1089
1090 private void cleanSharedFiles() {
1091 ContentValues cv = new ContentValues();
1092 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1093 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1094 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
1095 String [] whereArgs = new String[]{mAccount.name};
1096
1097 if (getContentResolver() != null) {
1098 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1099
1100 } else {
1101 try {
1102 getContentProviderClient().update(
1103 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1104 );
1105
1106 } catch (RemoteException e) {
1107 Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
1108 }
1109 }
1110 }
1111
1112 private void cleanSharedFilesInFolder(OCFile folder) {
1113 ContentValues cv = new ContentValues();
1114 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1115 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1116 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1117 ProviderTableMeta.FILE_PARENT + "=?";
1118 String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
1119
1120 if (getContentResolver() != null) {
1121 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1122
1123 } else {
1124 try {
1125 getContentProviderClient().update(
1126 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1127 );
1128
1129 } catch (RemoteException e) {
1130 Log_OC.e(TAG, "Exception in cleanSharedFilesInFolder " + e.getMessage());
1131 }
1132 }
1133 }
1134
1135 private void cleanShares() {
1136 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1137 String [] whereArgs = new String[]{mAccount.name};
1138
1139 if (getContentResolver() != null) {
1140 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1141
1142 } else {
1143 try {
1144 getContentProviderClient().delete(
1145 ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs
1146 );
1147
1148 } catch (RemoteException e) {
1149 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
1150 }
1151 }
1152 }
1153
1154 public void saveShares(Collection<OCShare> shares) {
1155 cleanShares();
1156 if (shares != null) {
1157 ArrayList<ContentProviderOperation> operations =
1158 new ArrayList<ContentProviderOperation>(shares.size());
1159
1160 // prepare operations to insert or update files to save in the given folder
1161 for (OCShare share : shares) {
1162 ContentValues cv = new ContentValues();
1163 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1164 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1165 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1166 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1167 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1168 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1169 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1170 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1171 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1172 cv.put(
1173 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1174 share.getSharedWithDisplayName()
1175 );
1176 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1177 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1178 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1179 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1180
1181 if (shareExists(share.getIdRemoteShared())) {
1182 // updating an existing file
1183 operations.add(
1184 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1185 withValues(cv).
1186 withSelection(
1187 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1188 new String[] { String.valueOf(share.getIdRemoteShared()) }
1189 ).
1190 build()
1191 );
1192
1193 } else {
1194 // adding a new file
1195 operations.add(
1196 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1197 withValues(cv).
1198 build()
1199 );
1200 }
1201 }
1202
1203 // apply operations in batch
1204 if (operations.size() > 0) {
1205 @SuppressWarnings("unused")
1206 ContentProviderResult[] results = null;
1207 Log_OC.d(TAG, "Sending " + operations.size() +
1208 " operations to FileContentProvider");
1209 try {
1210 if (getContentResolver() != null) {
1211 results = getContentResolver().applyBatch(
1212 MainApp.getAuthority(), operations
1213 );
1214
1215 } else {
1216 results = getContentProviderClient().applyBatch(operations);
1217 }
1218
1219 } catch (OperationApplicationException e) {
1220 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1221
1222 } catch (RemoteException e) {
1223 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1224 }
1225 }
1226 }
1227
1228 }
1229
1230 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1231 cleanSharedFiles();
1232
1233 if (sharedFiles != null) {
1234 ArrayList<ContentProviderOperation> operations =
1235 new ArrayList<ContentProviderOperation>(sharedFiles.size());
1236
1237 // prepare operations to insert or update files to save in the given folder
1238 for (OCFile file : sharedFiles) {
1239 ContentValues cv = new ContentValues();
1240 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1241 cv.put(
1242 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
1243 file.getModificationTimestampAtLastSyncForData()
1244 );
1245 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1246 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1247 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1248 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1249 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1250 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1251 if (!file.isFolder()) {
1252 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1253 }
1254 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1255 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1256 cv.put(
1257 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
1258 file.getLastSyncDateForData()
1259 );
1260 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
1261 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1262 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
1263 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1264 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
1265 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
1266 cv.put(
1267 ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
1268 file.needsUpdateThumbnail() ? 1 : 0
1269 );
1270 cv.put(
1271 ProviderTableMeta.FILE_IS_DOWNLOADING,
1272 file.isDownloading() ? 1 : 0
1273 );
1274 cv.put(
1275 ProviderTableMeta.FILE_IS_UPLOADING,
1276 file.isUploading() ? 1 : 0
1277 );
1278
1279 boolean existsByPath = fileExists(file.getRemotePath());
1280 if (existsByPath || fileExists(file.getFileId())) {
1281 // updating an existing file
1282 operations.add(
1283 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1284 withValues(cv).
1285 withSelection(
1286 ProviderTableMeta._ID + "=?",
1287 new String[] { String.valueOf(file.getFileId()) }
1288 ).build()
1289 );
1290
1291 } else {
1292 // adding a new file
1293 operations.add(
1294 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
1295 withValues(cv).
1296 build()
1297 );
1298 }
1299 }
1300
1301 // apply operations in batch
1302 if (operations.size() > 0) {
1303 @SuppressWarnings("unused")
1304 ContentProviderResult[] results = null;
1305 Log_OC.d(TAG, "Sending " + operations.size() +
1306 " operations to FileContentProvider");
1307 try {
1308 if (getContentResolver() != null) {
1309 results = getContentResolver().applyBatch(
1310 MainApp.getAuthority(), operations
1311 );
1312
1313 } else {
1314 results = getContentProviderClient().applyBatch(operations);
1315 }
1316
1317 } catch (OperationApplicationException e) {
1318 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1319
1320 } catch (RemoteException e) {
1321 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1322 }
1323 }
1324 }
1325
1326 }
1327
1328 public void removeShare(OCShare share){
1329 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1330 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
1331 ProviderTableMeta.FILE_PATH + "=?";
1332 String [] whereArgs = new String[]{mAccount.name, share.getPath()};
1333 if (getContentProviderClient() != null) {
1334 try {
1335 getContentProviderClient().delete(share_uri, where, whereArgs);
1336 } catch (RemoteException e) {
1337 e.printStackTrace();
1338 }
1339 } else {
1340 getContentResolver().delete(share_uri, where, whereArgs);
1341 }
1342 }
1343
1344 public void saveSharesDB(ArrayList<OCShare> shares) {
1345 saveShares(shares);
1346
1347 ArrayList<OCFile> sharedFiles = new ArrayList<OCFile>();
1348
1349 for (OCShare share : shares) {
1350 // Get the path
1351 String path = share.getPath();
1352 if (share.isFolder()) {
1353 path = path + FileUtils.PATH_SEPARATOR;
1354 }
1355
1356 // Update OCFile with data from share: ShareByLink and publicLink
1357 OCFile file = getFileByPath(path);
1358 if (file != null) {
1359 if (share.getShareType().equals(ShareType.PUBLIC_LINK)) {
1360 file.setShareByLink(true);
1361 sharedFiles.add(file);
1362 }
1363 }
1364 }
1365
1366 updateSharedFiles(sharedFiles);
1367 }
1368
1369
1370 public void saveSharesInFolder(ArrayList<OCShare> shares, OCFile folder) {
1371 cleanSharedFilesInFolder(folder);
1372 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1373 operations = prepareRemoveSharesInFolder(folder, operations);
1374
1375 if (shares != null) {
1376 // prepare operations to insert or update files to save in the given folder
1377 for (OCShare share : shares) {
1378 ContentValues cv = new ContentValues();
1379 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1380 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1381 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1382 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1383 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1384 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1385 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1386 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1387 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1388 cv.put(
1389 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1390 share.getSharedWithDisplayName()
1391 );
1392 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1393 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1394 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1395 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1396
1397 /*
1398 if (shareExists(share.getIdRemoteShared())) {
1399 // updating an existing share resource
1400 operations.add(
1401 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1402 withValues(cv).
1403 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1404 new String[] { String.valueOf(share.getIdRemoteShared()) })
1405 .build());
1406
1407 } else {
1408 */
1409 // adding a new share resource
1410 operations.add(
1411 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1412 withValues(cv).
1413 build()
1414 );
1415 //}
1416 }
1417 }
1418
1419 // apply operations in batch
1420 if (operations.size() > 0) {
1421 @SuppressWarnings("unused")
1422 ContentProviderResult[] results = null;
1423 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1424 try {
1425 if (getContentResolver() != null) {
1426 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1427
1428 } else {
1429 results = getContentProviderClient().applyBatch(operations);
1430 }
1431
1432 } catch (OperationApplicationException e) {
1433 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1434
1435 } catch (RemoteException e) {
1436 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1437 }
1438 }
1439 //}
1440
1441 }
1442
1443 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
1444 OCFile folder, ArrayList<ContentProviderOperation> preparedOperations
1445 ) {
1446 if (folder != null) {
1447 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1448 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1449 String [] whereArgs = new String[]{ "", mAccount.name };
1450
1451 Vector<OCFile> files = getFolderContent(folder);
1452
1453 for (OCFile file : files) {
1454 whereArgs[0] = file.getRemotePath();
1455 preparedOperations.add(
1456 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1457 withSelection(where, whereArgs).
1458 build()
1459 );
1460 }
1461 }
1462 return preparedOperations;
1463
1464 /*
1465 if (operations.size() > 0) {
1466 try {
1467 if (getContentResolver() != null) {
1468 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1469
1470 } else {
1471 getContentProviderClient().applyBatch(operations);
1472 }
1473
1474 } catch (OperationApplicationException e) {
1475 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1476
1477 } catch (RemoteException e) {
1478 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1479 }
1480 }
1481 */
1482
1483 /*
1484 if (getContentResolver() != null) {
1485
1486 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE,
1487 where,
1488 whereArgs);
1489 } else {
1490 try {
1491 getContentProviderClient().delete( ProviderTableMeta.CONTENT_URI_SHARE,
1492 where,
1493 whereArgs);
1494
1495 } catch (RemoteException e) {
1496 Log_OC.e(TAG, "Exception deleting shares in a folder " + e.getMessage());
1497 }
1498 }
1499 */
1500 //}
1501 }
1502
1503 public void triggerMediaScan(String path) {
1504 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1505 intent.setData(Uri.fromFile(new File(path)));
1506 MainApp.getAppContext().sendBroadcast(intent);
1507 }
1508
1509 }