FileDataStorageManager.java 88 KB

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