FileDataStorageManager.java 105 KB

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