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