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