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