FileDataStorageManager.java 111 KB

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