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