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