FileDataStorageManager.java 103 KB

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