FileDataStorageManager.java 101 KB

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