FileDataStorageManager.java 88 KB

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