FileDataStorageManager.java 105 KB

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