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