FileDataStorageManager.java 98 KB

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