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