FileDataStorageManager.java 104 KB

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