Removed some logs
[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_IN_CONFLICT, file.isInConflict());
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_IN_CONFLICT, file.isInConflict());
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, false);
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.setInConflict(c.getInt(
901 c.getColumnIndex(ProviderTableMeta.FILE_IN_CONFLICT)) == 1 ? true : false);
902
903 }
904 return file;
905 }
906
907 // Methods for Shares
908 public boolean saveShare(OCShare share) {
909 boolean overriden = false;
910 ContentValues cv = new ContentValues();
911 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
912 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
913 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
914 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
915 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
916 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
917 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
918 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
919 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
920 cv.put(
921 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
922 share.getSharedWithDisplayName()
923 );
924 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
925 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
926 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
927 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
928
929 if (shareExists(share.getIdRemoteShared())) { // for renamed files; no more delete and create
930 overriden = true;
931 if (getContentResolver() != null) {
932 getContentResolver().update(ProviderTableMeta.CONTENT_URI_SHARE, cv,
933 ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
934 new String[]{String.valueOf(share.getIdRemoteShared())});
935 } else {
936 try {
937 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_SHARE,
938 cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
939 new String[]{String.valueOf(share.getIdRemoteShared())});
940 } catch (RemoteException e) {
941 Log_OC.e(TAG,
942 "Fail to insert insert file to database "
943 + e.getMessage());
944 }
945 }
946 } else {
947 Uri result_uri = null;
948 if (getContentResolver() != null) {
949 result_uri = getContentResolver().insert(
950 ProviderTableMeta.CONTENT_URI_SHARE, cv);
951 } else {
952 try {
953 result_uri = getContentProviderClient().insert(
954 ProviderTableMeta.CONTENT_URI_SHARE, cv);
955 } catch (RemoteException e) {
956 Log_OC.e(TAG,
957 "Fail to insert insert file to database "
958 + e.getMessage());
959 }
960 }
961 if (result_uri != null) {
962 long new_id = Long.parseLong(result_uri.getPathSegments()
963 .get(1));
964 share.setId(new_id);
965 }
966 }
967
968 return overriden;
969 }
970
971
972 public OCShare getFirstShareByPathAndType(String path, ShareType type) {
973 Cursor c = null;
974 if (getContentResolver() != null) {
975 c = getContentResolver().query(
976 ProviderTableMeta.CONTENT_URI_SHARE,
977 null,
978 ProviderTableMeta.OCSHARES_PATH + "=? AND "
979 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
980 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
981 new String[]{path, Integer.toString(type.getValue()), mAccount.name},
982 null);
983 } else {
984 try {
985 c = getContentProviderClient().query(
986 ProviderTableMeta.CONTENT_URI_SHARE,
987 null,
988 ProviderTableMeta.OCSHARES_PATH + "=? AND "
989 + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? AND "
990 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
991 new String[]{path, Integer.toString(type.getValue()), mAccount.name},
992 null);
993
994 } catch (RemoteException e) {
995 Log_OC.e(TAG, "Could not get file details: " + e.getMessage());
996 c = null;
997 }
998 }
999 OCShare share = null;
1000 if (c.moveToFirst()) {
1001 share = createShareInstance(c);
1002 }
1003 c.close();
1004 return share;
1005 }
1006
1007 private OCShare createShareInstance(Cursor c) {
1008 OCShare share = null;
1009 if (c != null) {
1010 share = new OCShare(c.getString(c
1011 .getColumnIndex(ProviderTableMeta.OCSHARES_PATH)));
1012 share.setId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
1013 share.setFileSource(c.getLong(c
1014 .getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)));
1015 share.setShareType(ShareType.fromValue(c.getInt(c
1016 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE))));
1017 share.setPermissions(c.getInt(c
1018 .getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)));
1019 share.setSharedDate(c.getLong(c
1020 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)));
1021 share.setExpirationDate(c.getLong(c
1022 .getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)));
1023 share.setToken(c.getString(c
1024 .getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)));
1025 share.setSharedWithDisplayName(c.getString(c
1026 .getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)));
1027 share.setIsFolder(c.getInt(
1028 c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1);
1029 share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
1030 share.setIdRemoteShared(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED)));
1031 }
1032 return share;
1033 }
1034
1035 private boolean shareExists(String cmp_key, String value) {
1036 Cursor c;
1037 if (getContentResolver() != null) {
1038 c = getContentResolver()
1039 .query(ProviderTableMeta.CONTENT_URI_SHARE,
1040 null,
1041 cmp_key + "=? AND "
1042 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
1043 + "=?",
1044 new String[]{value, mAccount.name}, null);
1045 } else {
1046 try {
1047 c = getContentProviderClient().query(
1048 ProviderTableMeta.CONTENT_URI_SHARE,
1049 null,
1050 cmp_key + "=? AND "
1051 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?",
1052 new String[]{value, mAccount.name}, null);
1053 } catch (RemoteException e) {
1054 Log_OC.e(TAG,
1055 "Couldn't determine file existance, assuming non existance: "
1056 + e.getMessage());
1057 return false;
1058 }
1059 }
1060 boolean retval = c.moveToFirst();
1061 c.close();
1062 return retval;
1063 }
1064
1065 private boolean shareExists(long remoteId) {
1066 return shareExists(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, String.valueOf(remoteId));
1067 }
1068
1069 private void cleanSharedFiles() {
1070 ContentValues cv = new ContentValues();
1071 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1072 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1073 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
1074 String[] whereArgs = new String[]{mAccount.name};
1075
1076 if (getContentResolver() != null) {
1077 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1078
1079 } else {
1080 try {
1081 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1082 } catch (RemoteException e) {
1083 Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
1084 }
1085 }
1086 }
1087
1088 private void cleanSharedFilesInFolder(OCFile folder) {
1089 ContentValues cv = new ContentValues();
1090 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
1091 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
1092 String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
1093 ProviderTableMeta.FILE_PARENT + "=?";
1094 String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
1095
1096 if (getContentResolver() != null) {
1097 getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1098
1099 } else {
1100 try {
1101 getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
1102 } catch (RemoteException e) {
1103 Log_OC.e(TAG, "Exception in cleanSharedFilesInFolder " + e.getMessage());
1104 }
1105 }
1106 }
1107
1108 private void cleanShares() {
1109 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1110 String[] whereArgs = new String[]{mAccount.name};
1111
1112 if (getContentResolver() != null) {
1113 getContentResolver().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1114
1115 } else {
1116 try {
1117 getContentProviderClient().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
1118 } catch (RemoteException e) {
1119 Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
1120 }
1121 }
1122 }
1123
1124 public void saveShares(Collection<OCShare> shares) {
1125 cleanShares();
1126 if (shares != null) {
1127 ArrayList<ContentProviderOperation> operations =
1128 new ArrayList<ContentProviderOperation>(shares.size());
1129
1130 // prepare operations to insert or update files to save in the given folder
1131 for (OCShare share : shares) {
1132 ContentValues cv = new ContentValues();
1133 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1134 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1135 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1136 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1137 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1138 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1139 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1140 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1141 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1142 cv.put(
1143 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1144 share.getSharedWithDisplayName()
1145 );
1146 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1147 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1148 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1149 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1150
1151 if (shareExists(share.getIdRemoteShared())) {
1152 // updating an existing file
1153 operations.add(
1154 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1155 withValues(cv).
1156 withSelection(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1157 new String[]{String.valueOf(share.getIdRemoteShared())})
1158 .build());
1159 } else {
1160 // adding a new file
1161 operations.add(
1162 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1163 withValues(cv).
1164 build()
1165 );
1166 }
1167 }
1168
1169 // apply operations in batch
1170 if (operations.size() > 0) {
1171 @SuppressWarnings("unused")
1172 ContentProviderResult[] results = null;
1173 Log_OC.d(TAG, "Sending " + operations.size() +
1174 " operations to FileContentProvider");
1175 try {
1176 if (getContentResolver() != null) {
1177 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1178 } else {
1179 results = getContentProviderClient().applyBatch(operations);
1180 }
1181
1182 } catch (OperationApplicationException e) {
1183 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1184
1185 } catch (RemoteException e) {
1186 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1187 }
1188 }
1189 }
1190
1191 }
1192
1193 public void updateSharedFiles(Collection<OCFile> sharedFiles) {
1194 cleanSharedFiles();
1195
1196 if (sharedFiles != null) {
1197 ArrayList<ContentProviderOperation> operations =
1198 new ArrayList<ContentProviderOperation>(sharedFiles.size());
1199
1200 // prepare operations to insert or update files to save in the given folder
1201 for (OCFile file : sharedFiles) {
1202 ContentValues cv = new ContentValues();
1203 cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
1204 cv.put(
1205 ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
1206 file.getModificationTimestampAtLastSyncForData()
1207 );
1208 cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
1209 cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
1210 cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
1211 cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
1212 cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
1213 cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
1214 if (!file.isFolder()) {
1215 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
1216 }
1217 cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
1218 cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
1219 cv.put(
1220 ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
1221 file.getLastSyncDateForData()
1222 );
1223 cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.isFavorite() ? 1 : 0);
1224 cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
1225 cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
1226 cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
1227 cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
1228 cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
1229 cv.put(
1230 ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
1231 file.needsUpdateThumbnail() ? 1 : 0
1232 );
1233 cv.put(
1234 ProviderTableMeta.FILE_IS_DOWNLOADING,
1235 file.isDownloading() ? 1 : 0
1236 );
1237 cv.put(
1238 ProviderTableMeta.FILE_IN_CONFLICT,
1239 file.isInConflict() ? 1 : 0
1240 );
1241
1242 boolean existsByPath = fileExists(file.getRemotePath());
1243 if (existsByPath || fileExists(file.getFileId())) {
1244 // updating an existing file
1245 operations.add(
1246 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
1247 withValues(cv).
1248 withSelection(ProviderTableMeta._ID + "=?",
1249 new String[]{String.valueOf(file.getFileId())})
1250 .build());
1251
1252 } else {
1253 // adding a new file
1254 operations.add(
1255 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
1256 withValues(cv).
1257 build()
1258 );
1259 }
1260 }
1261
1262 // apply operations in batch
1263 if (operations.size() > 0) {
1264 @SuppressWarnings("unused")
1265 ContentProviderResult[] results = null;
1266 Log_OC.d(TAG, "Sending " + operations.size() +
1267 " operations to FileContentProvider");
1268 try {
1269 if (getContentResolver() != null) {
1270 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1271 } else {
1272 results = getContentProviderClient().applyBatch(operations);
1273 }
1274
1275 } catch (OperationApplicationException e) {
1276 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1277
1278 } catch (RemoteException e) {
1279 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1280 }
1281 }
1282 }
1283
1284 }
1285
1286 public void removeShare(OCShare share) {
1287 Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
1288 String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
1289 ProviderTableMeta.FILE_PATH + "=?";
1290 String [] whereArgs = new String[]{mAccount.name, share.getPath()};
1291 if (getContentProviderClient() != null) {
1292 try {
1293 getContentProviderClient().delete(share_uri, where, whereArgs);
1294 } catch (RemoteException e) {
1295 e.printStackTrace();
1296 }
1297 } else {
1298 getContentResolver().delete(share_uri, where, whereArgs);
1299 }
1300 }
1301
1302 public void saveSharesDB(ArrayList<OCShare> shares) {
1303 saveShares(shares);
1304
1305 ArrayList<OCFile> sharedFiles = new ArrayList<OCFile>();
1306
1307 for (OCShare share : shares) {
1308 // Get the path
1309 String path = share.getPath();
1310 if (share.isFolder()) {
1311 path = path + FileUtils.PATH_SEPARATOR;
1312 }
1313
1314 // Update OCFile with data from share: ShareByLink and publicLink
1315 OCFile file = getFileByPath(path);
1316 if (file != null) {
1317 if (share.getShareType().equals(ShareType.PUBLIC_LINK)) {
1318 file.setShareByLink(true);
1319 sharedFiles.add(file);
1320 }
1321 }
1322 }
1323
1324 updateSharedFiles(sharedFiles);
1325 }
1326
1327
1328 public void saveSharesInFolder(ArrayList<OCShare> shares, OCFile folder) {
1329 cleanSharedFilesInFolder(folder);
1330 ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
1331 operations = prepareRemoveSharesInFolder(folder, operations);
1332
1333 if (shares != null) {
1334 // prepare operations to insert or update files to save in the given folder
1335 for (OCShare share : shares) {
1336 ContentValues cv = new ContentValues();
1337 cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, share.getFileSource());
1338 cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, share.getItemSource());
1339 cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, share.getShareType().getValue());
1340 cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, share.getShareWith());
1341 cv.put(ProviderTableMeta.OCSHARES_PATH, share.getPath());
1342 cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, share.getPermissions());
1343 cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
1344 cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
1345 cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
1346 cv.put(
1347 ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
1348 share.getSharedWithDisplayName()
1349 );
1350 cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
1351 cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
1352 cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
1353 cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
1354
1355 /*
1356 if (shareExists(share.getIdRemoteShared())) {
1357 // updating an existing share resource
1358 operations.add(
1359 ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
1360 withValues(cv).
1361 withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
1362 new String[] { String.valueOf(share.getIdRemoteShared()) })
1363 .build());
1364
1365 } else {
1366 */
1367 // adding a new share resource
1368 operations.add(
1369 ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
1370 withValues(cv).
1371 build()
1372 );
1373 //}
1374 }
1375 }
1376
1377 // apply operations in batch
1378 if (operations.size() > 0) {
1379 @SuppressWarnings("unused")
1380 ContentProviderResult[] results = null;
1381 Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
1382 try {
1383 if (getContentResolver() != null) {
1384 results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
1385
1386 } else {
1387 results = getContentProviderClient().applyBatch(operations);
1388 }
1389
1390 } catch (OperationApplicationException e) {
1391 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1392
1393 } catch (RemoteException e) {
1394 Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
1395 }
1396 }
1397 //}
1398
1399 }
1400
1401 private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
1402 OCFile folder, ArrayList<ContentProviderOperation> preparedOperations) {
1403 if (folder != null) {
1404 String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
1405 + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
1406 String [] whereArgs = new String[]{ "", mAccount.name };
1407
1408 // TODO Enable when "On Device" is recovered ?
1409 Vector<OCFile> files = getFolderContent(folder /*, false*/);
1410
1411 for (OCFile file : files) {
1412 whereArgs[0] = file.getRemotePath();
1413 preparedOperations.add(
1414 ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
1415 withSelection(where, whereArgs).
1416 build()
1417 );
1418 }
1419 }
1420 return preparedOperations;
1421 }
1422
1423 public void triggerMediaScan(String path) {
1424 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1425 intent.setData(Uri.fromFile(new File(path)));
1426 MainApp.getAppContext().sendBroadcast(intent);
1427 }
1428
1429 public void deleteFileInMediaScan(String path) {
1430
1431 String mimetypeString = FileStorageUtils.getMimeTypeFromName(path);
1432 ContentResolver contentResolver = getContentResolver();
1433
1434 if (contentResolver != null) {
1435 if (mimetypeString.startsWith("image/")) {
1436 // Images
1437 contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1438 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1439 } else if (mimetypeString.startsWith("audio/")) {
1440 // Audio
1441 contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1442 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1443 } else if (mimetypeString.startsWith("video/")) {
1444 // Video
1445 contentResolver.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1446 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1447 }
1448 } else {
1449 ContentProviderClient contentProviderClient = getContentProviderClient();
1450 try {
1451 if (mimetypeString.startsWith("image/")) {
1452 // Images
1453 contentProviderClient.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1454 MediaStore.Images.Media.DATA + "=?", new String[]{path});
1455 } else if (mimetypeString.startsWith("audio/")) {
1456 // Audio
1457 contentProviderClient.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1458 MediaStore.Audio.Media.DATA + "=?", new String[]{path});
1459 } else if (mimetypeString.startsWith("video/")) {
1460 // Video
1461 contentProviderClient.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
1462 MediaStore.Video.Media.DATA + "=?", new String[]{path});
1463 }
1464 } catch (RemoteException e) {
1465 Log_OC.e(TAG, "Exception deleting media file in MediaStore " + e.getMessage());
1466 }
1467 }
1468
1469 }
1470
1471 public void saveConflict(OCFile file, boolean inConflict) {
1472 if (!file.isDown()) {
1473 inConflict = false;
1474 }
1475 ContentValues cv = new ContentValues();
1476 cv.put(ProviderTableMeta.FILE_IN_CONFLICT, inConflict ? 1 : 0);
1477 int updated = 0;
1478 if (getContentResolver() != null) {
1479 updated = getContentResolver().update(
1480 ProviderTableMeta.CONTENT_URI_FILE,
1481 cv,
1482 ProviderTableMeta._ID + "=?",
1483 new String[] { String.valueOf(file.getFileId())}
1484 );
1485 } else {
1486 try {
1487 updated = getContentProviderClient().update(
1488 ProviderTableMeta.CONTENT_URI_FILE,
1489 cv,
1490 ProviderTableMeta._ID + "=?",
1491 new String[]{String.valueOf(file.getFileId())}
1492 );
1493 } catch (RemoteException e) {
1494 Log_OC.e(TAG, "Failed saving conflict in database " + e.getMessage());
1495 }
1496 }
1497
1498 Log_OC.d(TAG, "Number of files updated with CONFLICT: " + updated);
1499
1500 if (updated > 0) {
1501 if (inConflict) {
1502 /// set conflict in all ancestor folders
1503
1504 long parentId = file.getParentId();
1505 Set<String> ancestorIds = new HashSet<String>();
1506 while (parentId != FileDataStorageManager.ROOT_PARENT_ID) {
1507 ancestorIds.add(Long.toString(parentId));
1508 parentId = getFileById(parentId).getParentId();
1509 }
1510
1511 if (ancestorIds.size() > 0) {
1512 StringBuffer whereBuffer = new StringBuffer();
1513 whereBuffer.append(ProviderTableMeta._ID).append(" IN (");
1514 for (int i = 0; i < ancestorIds.size() - 1; i++) {
1515 whereBuffer.append("?,");
1516 }
1517 whereBuffer.append("?");
1518 whereBuffer.append(")");
1519
1520 if (getContentResolver() != null) {
1521 updated = getContentResolver().update(
1522 ProviderTableMeta.CONTENT_URI_FILE,
1523 cv,
1524 whereBuffer.toString(),
1525 ancestorIds.toArray(new String[]{})
1526 );
1527 } else {
1528 try {
1529 updated = getContentProviderClient().update(
1530 ProviderTableMeta.CONTENT_URI_FILE,
1531 cv,
1532 whereBuffer.toString(),
1533 ancestorIds.toArray(new String[]{})
1534 );
1535 } catch (RemoteException e) {
1536 Log_OC.e(TAG, "Failed saving conflict in database " + e.getMessage());
1537 }
1538 }
1539 } // else file is ROOT folder, no parent to set in conflict
1540
1541 } else {
1542 /// update conflict in ancestor folders
1543 // (not directly unset; maybe there are more conflicts below them)
1544 String parentPath = file.getRemotePath();
1545 if (parentPath.endsWith(OCFile.PATH_SEPARATOR)) {
1546 parentPath = parentPath.substring(0, parentPath.length() - 1);
1547 }
1548 parentPath = parentPath.substring(0, parentPath.lastIndexOf(OCFile.PATH_SEPARATOR) + 1);
1549
1550 Log_OC.d(TAG, "checking parents to remove conflict; STARTING with " + parentPath);
1551 while (parentPath.length() > 0) {
1552
1553 String where =
1554 ProviderTableMeta.FILE_IN_CONFLICT + " = 1 AND " +
1555 ProviderTableMeta.FILE_CONTENT_TYPE + " != 'DIR' AND " +
1556 ProviderTableMeta.FILE_ACCOUNT_OWNER + " = ? AND " +
1557 ProviderTableMeta.FILE_PATH + " LIKE ?";
1558 Cursor descendentsInConflict = getContentResolver().query(
1559 ProviderTableMeta.CONTENT_URI_FILE,
1560 new String[]{ProviderTableMeta._ID},
1561 where,
1562 new String[]{mAccount.name, parentPath + "%"},
1563 null
1564 );
1565 if (descendentsInConflict == null || descendentsInConflict.getCount() == 0) {
1566 Log_OC.d(TAG, "NO MORE conflicts in " + parentPath);
1567 if (getContentResolver() != null) {
1568 updated = getContentResolver().update(
1569 ProviderTableMeta.CONTENT_URI_FILE,
1570 cv,
1571 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + "=?",
1572 new String[]{mAccount.name, parentPath}
1573 );
1574 } else {
1575 try {
1576 updated = getContentProviderClient().update(
1577 ProviderTableMeta.CONTENT_URI_FILE,
1578 cv,
1579 ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + "=?"
1580 , new String[]{mAccount.name, parentPath}
1581 );
1582 } catch (RemoteException e) {
1583 Log_OC.e(TAG, "Failed saving conflict in database " + e.getMessage());
1584 }
1585 }
1586
1587 } else {
1588 Log_OC.d(TAG, "STILL " + descendentsInConflict.getCount() + " in " + parentPath);
1589 }
1590
1591 if (descendentsInConflict != null) {
1592 descendentsInConflict.close();
1593 }
1594
1595 parentPath = parentPath.substring(0, parentPath.length() - 1); // trim last /
1596 parentPath = parentPath.substring(0, parentPath.lastIndexOf(OCFile.PATH_SEPARATOR) + 1);
1597 Log_OC.d(TAG, "checking parents to remove conflict; NEXT " + parentPath);
1598 }
1599 }
1600 }
1601
1602 }
1603 }