FileDataStorageManager.java 97 KB

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