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