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