FileDataStorageManager.java 100 KB

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