c24c94b7f06a3692697c4e80ca50ae80f9a3626c
[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(localPath);
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 // notify MediaScanner about removed file
560 deleteFileInMediaScan(file.getStoragePath());
561 file.setStoragePath(null);
562 saveFile(file);
563 }
564 }
565 }
566 }
567 }
568
569 // stage 2: remove the folder itself and any local file inside out of sync;
570 // for instance, after clearing the app cache or reinstalling
571 success &= removeLocalFolder(localFolder);
572 }
573 return success;
574 }
575
576 private boolean removeLocalFolder(File localFolder) {
577 boolean success = true;
578 File[] localFiles = localFolder.listFiles();
579 if (localFiles != null) {
580 for (File localFile : localFiles) {
581 if (localFile.isDirectory()) {
582 success &= removeLocalFolder(localFile);
583 } else {
584 String path = localFile.getAbsolutePath();
585 success &= localFile.delete();
586 }
587 }
588 }
589 success &= localFolder.delete();
590 return success;
591 }
592
593
594 /**
595 * Updates database and file system for a file or folder that was moved to a different location.
596 *
597 * TODO explore better (faster) implementations
598 * TODO throw exceptions up !
599 */
600 public void moveLocalFile(OCFile file, String targetPath, String targetParentPath) {
601
602 if (file != null && file.fileExists() && !OCFile.ROOT_PATH.equals(file.getFileName())) {
603
604 OCFile targetParent = getFileByPath(targetParentPath);
605 if (targetParent == null) {
606 throw new IllegalStateException("Parent folder of the target path does not exist!!");
607 }
608
609 /// 1. get all the descendants of the moved element in a single QUERY
610 Cursor c = null;
611 if (getContentProviderClient() != null) {
612 try {
613 c = getContentProviderClient().query(
614 ProviderTableMeta.CONTENT_URI,
615 null,
616 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
617 ProviderTableMeta.FILE_PATH + " LIKE ? ",
618 new String[] {
619 mAccount.name,
620 file.getRemotePath() + "%"
621 },
622 ProviderTableMeta.FILE_PATH + " ASC "
623 );
624 } catch (RemoteException e) {
625 Log_OC.e(TAG, e.getMessage());
626 }
627
628 } else {
629 c = getContentResolver().query(
630 ProviderTableMeta.CONTENT_URI,
631 null,
632 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
633 ProviderTableMeta.FILE_PATH + " LIKE ? ",
634 new String[] {
635 mAccount.name,
636 file.getRemotePath() + "%"
637 },
638 ProviderTableMeta.FILE_PATH + " ASC "
639 );
640 }
641
642 /// 2. prepare a batch of update operations to change all the descendants
643 ArrayList<ContentProviderOperation> operations =
644 new ArrayList<ContentProviderOperation>(c.getCount());
645 String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
646 List<String> originalPathsToTriggerMediaScan = new ArrayList<String>();
647 List<String> newPathsToTriggerMediaScan = new ArrayList<String>();
648 if (c.moveToFirst()) {
649 int lengthOfOldPath = file.getRemotePath().length();
650 int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
651 do {
652 ContentValues cv = new ContentValues(); // keep construction in the loop
653 OCFile child = createFileInstance(c);
654 cv.put(
655 ProviderTableMeta.FILE_PATH,
656 targetPath + child.getRemotePath().substring(lengthOfOldPath)
657 );
658 if (child.getStoragePath() != null &&
659 child.getStoragePath().startsWith(defaultSavePath)) {
660 // update link to downloaded content - but local move is not done here!
661 String targetLocalPath = defaultSavePath + targetPath +
662 child.getStoragePath().substring(lengthOfOldStoragePath);
663
664 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, targetLocalPath);
665
666 originalPathsToTriggerMediaScan.add(child.getStoragePath());
667 newPathsToTriggerMediaScan.add(targetLocalPath);
668
669 }
670 if (child.getRemotePath().equals(file.getRemotePath())) {
671 cv.put(
672 ProviderTableMeta.FILE_PARENT,
673 targetParent.getFileId()
674 );
675 }
676 operations.add(
677 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
678 withValues(cv).
679 withSelection(
680 ProviderTableMeta._ID + "=?",
681 new String[] { String.valueOf(child.getFileId()) }
682 )
683 .build());
684
685 } while (c.moveToNext());
686 }
687 c.close();
688
689 /// 3. apply updates in batch
690 try {
691 if (getContentResolver() != null) {
692 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
693
694 } else {
695 getContentProviderClient().applyBatch(operations);
696 }
697
698 } catch (Exception e) {
699 Log_OC.e(TAG, "Fail to update " + file.getFileId() + " and descendants in database", e);
700 }
701
702 /// 4. move in local file system
703 String originalLocalPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
704 String targetLocalPath = defaultSavePath + targetPath;
705 File localFile = new File(originalLocalPath);
706 boolean renamed = false;
707 if (localFile.exists()) {
708 File targetFile = new File(targetLocalPath);
709 File targetFolder = targetFile.getParentFile();
710 if (!targetFolder.exists()) {
711 targetFolder.mkdirs();
712 }
713 renamed = localFile.renameTo(targetFile);
714 }
715
716 if (renamed) {
717 Iterator<String> it = originalPathsToTriggerMediaScan.iterator();
718 while (it.hasNext()) {
719 // Notify MediaScanner about removed file
720 deleteFileInMediaScan(it.next());
721 }
722 it = newPathsToTriggerMediaScan.iterator();
723 while (it.hasNext()) {
724 // Notify MediaScanner about new file/folder
725 triggerMediaScan(it.next());
726 }
727 }
728 }
729
730 }
731
732
733 private Vector<OCFile> getFolderContent(long parentId) {
734
735 Vector<OCFile> ret = new Vector<OCFile>();
736
737 Uri req_uri = Uri.withAppendedPath(
738 ProviderTableMeta.CONTENT_URI_DIR,
739 String.valueOf(parentId));
740 Cursor c = null;
741
742 if (getContentProviderClient() != null) {
743 try {
744 c = getContentProviderClient().query(req_uri, null,
745 ProviderTableMeta.FILE_PARENT + "=?" ,
746 new String[] { String.valueOf(parentId)}, null);
747 } catch (RemoteException e) {
748 Log_OC.e(TAG, e.getMessage());
749 return ret;
750 }
751 } else {
752 c = getContentResolver().query(req_uri, null,
753 ProviderTableMeta.FILE_PARENT + "=?" ,
754 new String[] { String.valueOf(parentId)}, null);
755 }
756
757 if (c.moveToFirst()) {
758 do {
759 OCFile child = createFileInstance(c);
760 ret.add(child);
761 } while (c.moveToNext());
762 }
763
764 c.close();
765
766 Collections.sort(ret);
767
768 return ret;
769 }
770
771
772 private OCFile createRootDir() {
773 OCFile file = new OCFile(OCFile.ROOT_PATH);
774 file.setMimetype("DIR");
775 file.setParentId(FileDataStorageManager.ROOT_PARENT_ID);
776 saveFile(file);
777 return file;
778 }
779
780 private boolean fileExists(String cmp_key, String value) {
781 Cursor c;
782 if (getContentResolver() != null) {
783 c = getContentResolver()
784 .query(ProviderTableMeta.CONTENT_URI,
785 null,
786 cmp_key + "=? AND "
787 + ProviderTableMeta.FILE_ACCOUNT_OWNER
788 + "=?",
789 new String[] { value, mAccount.name }, null);
790 } else {
791 try {
792 c = getContentProviderClient().query(
793 ProviderTableMeta.CONTENT_URI,
794 null,
795 cmp_key + "=? AND "
796 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
797 new String[] { value, mAccount.name }, null);
798 } catch (RemoteException e) {
799 Log_OC.e(TAG,
800 "Couldn't determine file existance, assuming non existance: "
801 + e.getMessage());
802 return false;
803 }
804 }
805 boolean retval = c.moveToFirst();
806 c.close();
807 return retval;
808 }
809
810 private Cursor getCursorForValue(String key, String value) {
811 Cursor c = null;
812 if (getContentResolver() != null) {
813 c = getContentResolver()
814 .query(ProviderTableMeta.CONTENT_URI,
815 null,
816 key + "=? AND "
817 + ProviderTableMeta.FILE_ACCOUNT_OWNER
818 + "=?",
819 new String[] { value, mAccount.name }, null);
820 } else {
821 try {
822 c = getContentProviderClient().query(
823 ProviderTableMeta.CONTENT_URI,
824 null,
825 key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
826 + "=?", new String[] { value, mAccount.name },
827 null);
828 } catch (RemoteException e) {
829 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
830 c = null;
831 }
832 }
833 return c;
834 }
835
836
837 private OCFile createFileInstance(Cursor c) {
838 OCFile file = null;
839 if (c != null) {
840 file = new OCFile(c.getString(c
841 .getColumnIndex(ProviderTableMeta.FILE_PATH)));
842 file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
843 file.setParentId(c.getLong(c
844 .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
845 file.setMimetype(c.getString(c
846 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
847 if (!file.isFolder()) {
848 file.setStoragePath(c.getString(c
849 .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
850 if (file.getStoragePath() == null) {
851 // try to find existing file and bind it with current account;
852 // with the current update of SynchronizeFolderOperation, this won't be
853 // necessary anymore after a full synchronization of the account
854 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
855 if (f.exists()) {
856 file.setStoragePath(f.getAbsolutePath());
857 file.setLastSyncDateForData(f.lastModified());
858 }
859 }
860 }
861 file.setFileLength(c.getLong(c
862 .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
863 file.setCreationTimestamp(c.getLong(c
864 .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
865 file.setModificationTimestamp(c.getLong(c
866 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
867 file.setModificationTimestampAtLastSyncForData(c.getLong(c
868 .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)));
869 file.setLastSyncDateForProperties(c.getLong(c
870 .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE)));
871 file.setLastSyncDateForData(c.getLong(c.
872 getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)));
873 file.setKeepInSync(c.getInt(
874 c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) == 1 ? true : false);
875 file.setEtag(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)));
876 file.setShareByLink(c.getInt(
877 c.getColumnIndex(ProviderTableMeta.FILE_SHARE_BY_LINK)) == 1 ? true : false);
878 file.setPublicLink(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PUBLIC_LINK)));
879 file.setPermissions(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PERMISSIONS)));
880 file.setRemoteId(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID)));
881 file.setNeedsUpdateThumbnail(c.getInt(
882 c.getColumnIndex(ProviderTableMeta.FILE_UPDATE_THUMBNAIL)) == 1 ? true : false);
883 file.setDownloading(c.getInt(
884 c.getColumnIndex(ProviderTableMeta.FILE_IS_DOWNLOADING)) == 1 ? true : false);
885
886 }
887 return file;
888 }
889
890 /**
891 * Returns if the file/folder is shared by link or not
892 * @param path Path of the file/folder
893 * @return
894 */
895 public boolean isShareByLink(String path) {
896 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
897 OCFile file = null;
898 if (c.moveToFirst()) {
899 file = createFileInstance(c);
900 }
901 c.close();
902 return file.isShareByLink();
903 }
904
905 /**
906 * Returns the public link of the file/folder
907 * @param path Path of the file/folder
908 * @return
909 */
910 public String getPublicLink(String path) {
911 Cursor c = getCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path);
912 OCFile file = null;
913 if (c.moveToFirst()) {
914 file = createFileInstance(c);
915 }
916 c.close();
917 return file.getPublicLink();
918 }
919
920
921 // Methods for Shares
922 public boolean saveShare(OCShare share) {
923 boolean overriden = false;
924 ContentValues cv = new ContentValues();
925 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
926 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
927 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
928 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
929 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
930 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
931 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
932 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
933 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
934 cv.put(
935 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
936 share.getSharedWithDisplayName()
937 );
938 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
939 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
940 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
941 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
942
943 if (shareExists(share.getIdRemoteShared())) { // for renamed files
944
945 overriden = true;
946 if (getContentResolver() != null) {
947 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
948 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
949 new String[] { String.valueOf(share.getIdRemoteShared()) });
950 } else {
951 try {
952 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
953 cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
954 new String[] { String.valueOf(share.getIdRemoteShared()) });
955 } catch (RemoteException e) {
956 Log_OC.e(TAG,
957 "Fail to insert insert file to database "
958 + e.getMessage());
959 }
960 }
961 } else {
962 Uri result_uri = null;
963 if (getContentResolver() != null) {
964 result_uri = getContentResolver().insert(
965 ProviderTableMeta.CONTENT_URI_SHARE, cv);
966 } else {
967 try {
968 result_uri = getContentProviderClient().insert(
969 ProviderTableMeta.CONTENT_URI_SHARE, cv);
970 } catch (RemoteException e) {
971 Log_OC.e(TAG,
972 "Fail to insert insert file to database "
973 + e.getMessage());
974 }
975 }
976 if (result_uri != null) {
977 long new_id = Long.parseLong(result_uri.getPathSegments()
978 .get(1));
979 share.setId(new_id);
980 }
981 }
982
983 return overriden;
984 }
985
986
987 public OCShare getFirstShareByPathAndType(String path, ShareType type) {
988 Cursor c = null;
989 if (getContentResolver() != null) {
990 c = getContentResolver().query(
991 ProviderTableMeta.CONTENT_URI_SHARE,
992 null,
993 ProviderTableMeta.OCSHARES_PATH + "=? AND "
994 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
995 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
996 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
997 null);
998 } else {
999 try {
1000 c = getContentProviderClient().query(
1001 ProviderTableMeta.CONTENT_URI_SHARE,
1002 null,
1003 ProviderTableMeta.OCSHARES_PATH + "=? AND "
1004 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
1005 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1006 new String[] { path, Integer.toString(type.getValue()), mAccount.name },
1007 null);
1008
1009 } catch (RemoteException e) {
1010 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
1011 c = null;
1012 }
1013 }
1014 OCShare share = null;
1015 if (c.moveToFirst()) {
1016 share = createShareInstance(c);
1017 }
1018 c.close();
1019 return share;
1020 }
1021
1022 private OCShare createShareInstance(Cursor c) {
1023 OCShare share = null;
1024 if (c != null) {
1025 share = new OCShare(c.getString(c
1026 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
1027 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1028 share.setFileSource(c.getLong(c
1029 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
1030 share.setShareType(ShareType.fromValue(c.getInt(c
1031 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
1032 share.setPermissions(c.getInt(c
1033 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
1034 share.setSharedDate(c.getLong(c
1035 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
1036 share.setExpirationDate(c.getLong(c
1037 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
1038 share.setToken(c.getString(c
1039 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
1040 share.setSharedWithDisplayName(c.getString(c
1041 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
1042 share.setIsFolder(c.getInt(
1043 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1 ? true : false);
1044 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
1045 share.setIdRemoteShared(
1046 c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED))
1047 );
1048
1049 }
1050 return share;
1051 }
1052
1053 private boolean shareExists(String cmp_key, String value) {
1054 Cursor c;
1055 if (getContentResolver() != null) {
1056 c = getContentResolver()
1057 .query(ProviderTableMeta.CONTENT_URI_SHARE,
1058 null,
1059 cmp_key + "=? AND "
1060 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
1061 + "=?",
1062 new String[] { value, mAccount.name }, null);
1063 } else {
1064 try {
1065 c = getContentProviderClient().query(
1066 ProviderTableMeta.CONTENT_URI_SHARE,
1067 null,
1068 cmp_key + "=? AND "
1069 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1070 new String[] { value, mAccount.name }, null);
1071 } catch (RemoteException e) {
1072 Log_OC.e(TAG,
1073 "Couldn't determine file existance, assuming non existance: "
1074 + e.getMessage());
1075 return false;
1076 }
1077 }
1078 boolean retval = c.moveToFirst();
1079 c.close();
1080 return retval;
1081 }
1082
1083 private boolean shareExists(long remoteId) {
1084 return shareExists(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, String.valueOf(remoteId));
1085 }
1086
1087 private void cleanSharedFiles() {
1088 ContentValues cv = new ContentValues();
1089 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1090 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1091 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
1092 String [] whereArgs = new String[]{mAccount.name};
1093
1094 if (getContentResolver() != null) {
1095 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1096
1097 } else {
1098 try {
1099 getContentProviderClient().update(
1100 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1101 );
1102
1103 } catch (RemoteException e) {
1104 Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
1105 }
1106 }
1107 }
1108
1109 private void cleanSharedFilesInFolder(OCFile folder) {
1110 ContentValues cv = new ContentValues();
1111 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1112 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1113 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1114 ProviderTableMeta.FILE_PARENT + "=?";
1115 String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
1116
1117 if (getContentResolver() != null) {
1118 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1119
1120 } else {
1121 try {
1122 getContentProviderClient().update(
1123 ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
1124 );
1125
1126 } catch (RemoteException e) {
1127 Log_OC.e(TAG, "Exception in cleanSharedFilesInFolder " + e.getMessage());
1128 }
1129 }
1130 }
1131
1132 private void cleanShares() {
1133 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1134 String [] whereArgs = new String[]{mAccount.name};
1135
1136 if (getContentResolver() != null) {
1137 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1138
1139 } else {
1140 try {
1141 getContentProviderClient().delete(
1142 ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs
1143 );
1144
1145 } catch (RemoteException e) {
1146 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
1147 }
1148 }
1149 }
1150
1151 public void saveShares(Collection<OCShare> shares) {
1152 cleanShares();
1153 if (shares != null) {
1154 ArrayList<ContentProviderOperation> operations =
1155 new ArrayList<ContentProviderOperation>(shares.size());
1156
1157 // prepare operations to insert or update files to save in the given folder
1158 for (OCShare share : shares) {
1159 ContentValues cv = new ContentValues();
1160 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1161 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1162 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1163 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1164 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1165 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1166 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1167 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1168 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1169 cv.put(
1170 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1171 share.getSharedWithDisplayName()
1172 );
1173 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1174 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1175 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1176 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1177
1178 if (shareExists(share.getIdRemoteShared())) {
1179 // updating an existing file
1180 operations.add(
1181 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1182 withValues(cv).
1183 withSelection(
1184 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1185 new String[] { String.valueOf(share.getIdRemoteShared()) }
1186 ).
1187 build()
1188 );
1189
1190 } else {
1191 // adding a new file
1192 operations.add(
1193 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1194 withValues(cv).
1195 build()
1196 );
1197 }
1198 }
1199
1200 // apply operations in batch
1201 if (operations.size() > 0) {
1202 @SuppressWarnings("unused")
1203 ContentProviderResult[] results = null;
1204 Log_OC.d(TAG, "Sending " + operations.size() +
1205 " operations to FileContentProvider");
1206 try {
1207 if (getContentResolver() != null) {
1208 results = getContentResolver().applyBatch(
1209 MainApp.getAuthority(), operations
1210 );
1211
1212 } else {
1213 results = getContentProviderClient().applyBatch(operations);
1214 }
1215
1216 } catch (OperationApplicationException e) {
1217 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1218
1219 } catch (RemoteException e) {
1220 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1221 }
1222 }
1223 }
1224
1225 }
1226
1227 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1228 cleanSharedFiles();
1229
1230 if (sharedFiles != null) {
1231 ArrayList<ContentProviderOperation> operations =
1232 new ArrayList<ContentProviderOperation>(sharedFiles.size());
1233
1234 // prepare operations to insert or update files to save in the given folder
1235 for (OCFile file : sharedFiles) {
1236 ContentValues cv = new ContentValues();
1237 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1238 cv.put(
1239 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
1240 file.getModificationTimestampAtLastSyncForData()
1241 );
1242 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1243 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1244 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1245 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1246 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1247 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1248 if (!file.isFolder()) {
1249 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1250 }
1251 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1252 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1253 cv.put(
1254 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
1255 file.getLastSyncDateForData()
1256 );
1257 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
1258 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1259 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
1260 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1261 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
1262 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
1263 cv.put(
1264 ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
1265 file.needsUpdateThumbnail() ? 1 : 0
1266 );
1267 cv.put(
1268 ProviderTableMeta.FILE_IS_DOWNLOADING,
1269 file.isDownloading() ? 1 : 0
1270 );
1271
1272 boolean existsByPath = fileExists(file.getRemotePath());
1273 if (existsByPath || fileExists(file.getFileId())) {
1274 // updating an existing file
1275 operations.add(
1276 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1277 withValues(cv).
1278 withSelection(
1279 ProviderTableMeta._ID + "=?",
1280 new String[] { String.valueOf(file.getFileId()) }
1281 ).build()
1282 );
1283
1284 } else {
1285 // adding a new file
1286 operations.add(
1287 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
1288 withValues(cv).
1289 build()
1290 );
1291 }
1292 }
1293
1294 // apply operations in batch
1295 if (operations.size() > 0) {
1296 @SuppressWarnings("unused")
1297 ContentProviderResult[] results = null;
1298 Log_OC.d(TAG, "Sending " + operations.size() +
1299 " operations to FileContentProvider");
1300 try {
1301 if (getContentResolver() != null) {
1302 results = getContentResolver().applyBatch(
1303 MainApp.getAuthority(), operations
1304 );
1305
1306 } else {
1307 results = getContentProviderClient().applyBatch(operations);
1308 }
1309
1310 } catch (OperationApplicationException e) {
1311 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1312
1313 } catch (RemoteException e) {
1314 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1315 }
1316 }
1317 }
1318
1319 }
1320
1321 public void removeShare(OCShare share){
1322 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1323 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
1324 ProviderTableMeta.FILE_PATH + "=?";
1325 String [] whereArgs = new String[]{mAccount.name, share.getPath()};
1326 if (getContentProviderClient() != null) {
1327 try {
1328 getContentProviderClient().delete(share_uri, where, whereArgs);
1329 } catch (RemoteException e) {
1330 e.printStackTrace();
1331 }
1332 } else {
1333 getContentResolver().delete(share_uri, where, whereArgs);
1334 }
1335 }
1336
1337 public void saveSharesDB(ArrayList<OCShare> shares) {
1338 saveShares(shares);
1339
1340 ArrayList<OCFile> sharedFiles = new ArrayList<OCFile>();
1341
1342 for (OCShare share : shares) {
1343 // Get the path
1344 String path = share.getPath();
1345 if (share.isFolder()) {
1346 path = path + FileUtils.PATH_SEPARATOR;
1347 }
1348
1349 // Update OCFile with data from share: ShareByLink and publicLink
1350 OCFile file = getFileByPath(path);
1351 if (file != null) {
1352 if (share.getShareType().equals(ShareType.PUBLIC_LINK)) {
1353 file.setShareByLink(true);
1354 sharedFiles.add(file);
1355 }
1356 }
1357 }
1358
1359 updateSharedFiles(sharedFiles);
1360 }
1361
1362
1363 public void saveSharesInFolder(ArrayList<OCShare> shares, OCFile folder) {
1364 cleanSharedFilesInFolder(folder);
1365 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1366 operations = prepareRemoveSharesInFolder(folder, operations);
1367
1368 if (shares != null) {
1369 // prepare operations to insert or update files to save in the given folder
1370 for (OCShare share : shares) {
1371 ContentValues cv = new ContentValues();
1372 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1373 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1374 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1375 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1376 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1377 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1378 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1379 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1380 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1381 cv.put(
1382 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1383 share.getSharedWithDisplayName()
1384 );
1385 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1386 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1387 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1388 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1389
1390 /*
1391 if (shareExists(share.getIdRemoteShared())) {
1392 // updating an existing share resource
1393 operations.add(
1394 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1395 withValues(cv).
1396 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1397 new String[] { String.valueOf(share.getIdRemoteShared()) })
1398 .build());
1399
1400 } else {
1401 */
1402 // adding a new share resource
1403 operations.add(
1404 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1405 withValues(cv).
1406 build()
1407 );
1408 //}
1409 }
1410 }
1411
1412 // apply operations in batch
1413 if (operations.size() > 0) {
1414 @SuppressWarnings("unused")
1415 ContentProviderResult[] results = null;
1416 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1417 try {
1418 if (getContentResolver() != null) {
1419 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1420
1421 } else {
1422 results = getContentProviderClient().applyBatch(operations);
1423 }
1424
1425 } catch (OperationApplicationException e) {
1426 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1427
1428 } catch (RemoteException e) {
1429 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1430 }
1431 }
1432 //}
1433
1434 }
1435
1436 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
1437 OCFile folder, ArrayList<ContentProviderOperation> preparedOperations
1438 ) {
1439 if (folder != null) {
1440 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1441 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1442 String [] whereArgs = new String[]{ "", mAccount.name };
1443
1444 Vector<OCFile> files = getFolderContent(folder);
1445
1446 for (OCFile file : files) {
1447 whereArgs[0] = file.getRemotePath();
1448 preparedOperations.add(
1449 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1450 withSelection(where, whereArgs).
1451 build()
1452 );
1453 }
1454 }
1455 return preparedOperations;
1456
1457 /*
1458 if (operations.size() > 0) {
1459 try {
1460 if (getContentResolver() != null) {
1461 getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1462
1463 } else {
1464 getContentProviderClient().applyBatch(operations);
1465 }
1466
1467 } catch (OperationApplicationException e) {
1468 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1469
1470 } catch (RemoteException e) {
1471 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1472 }
1473 }
1474 */
1475
1476 /*
1477 if (getContentResolver() != null) {
1478
1479 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE,
1480 where,
1481 whereArgs);
1482 } else {
1483 try {
1484 getContentProviderClient().delete( ProviderTableMeta.CONTENT_URI_SHARE,
1485 where,
1486 whereArgs);
1487
1488 } catch (RemoteException e) {
1489 Log_OC.e(TAG, "Exception deleting shares in a folder " + e.getMessage());
1490 }
1491 }
1492 */
1493 //}
1494 }
1495
1496 public void triggerMediaScan(String path) {
1497 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1498 intent.setData(Uri.fromFile(new File(path)));
1499 MainApp.getAppContext().sendBroadcast(intent);
1500 }
1501
1502 public void deleteFileInMediaScan(String path) {
1503
1504 String mimetypeString = FileStorageUtils.getMimeTypeFromName(path);
1505 if (mimetypeString.startsWith("image/")) {
1506 // Images
1507 getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1508 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1509 } else if (mimetypeString.startsWith("audio/")) {
1510 // Audio
1511 getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1512 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1513 } else if (mimetypeString.startsWith("video/")) {
1514 // Video
1515 getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1516 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1517 }
1518
1519 }
1520
1521 }