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