FileDataStorageManager.java 111 KB

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