FileDataStorageManager.java 100 KB

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