NCManageDatabase.swift 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546
  1. //
  2. // NCManageDatabase.swift
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 06/05/17.
  6. // Copyright © 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import RealmSwift
  24. class NCManageDatabase: NSObject {
  25. @objc static let sharedInstance: NCManageDatabase = {
  26. let instance = NCManageDatabase()
  27. return instance
  28. }()
  29. override init() {
  30. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  31. var configCompact = Realm.Configuration(
  32. fileURL: dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)"),
  33. shouldCompactOnLaunch: { totalBytes, usedBytes in
  34. // totalBytes refers to the size of the file on disk in bytes (data + free space)
  35. // usedBytes refers to the number of bytes used by data in the file
  36. // Compact if the file is over 100MB in size and less than 50% 'used'
  37. let oneHundredMB = 100 * 1024 * 1024
  38. return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
  39. })
  40. // Encrypting the database file on disk with AES-256+SHA2 by supplying a 64-byte encryption key
  41. if NCBrandOptions.sharedInstance.use_database_encryption {
  42. if let keyData = NCBrandOptions.sharedInstance.databaseEncryptionKey.data(using: String.Encoding.utf8, allowLossyConversion: false) {
  43. configCompact.encryptionKey = keyData
  44. }
  45. }
  46. do {
  47. // Realm is compacted on the first open if the configuration block conditions were met.
  48. _ = try Realm(configuration: configCompact)
  49. } catch {
  50. // handle error compacting or opening Realm
  51. }
  52. var config = Realm.Configuration(
  53. fileURL: dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)"),
  54. schemaVersion: 43,
  55. // 10 : Version 2.18.0
  56. // 11 : Version 2.18.2
  57. // 12 : Version 2.19.0.5
  58. // 13 : Version 2.19.0.14
  59. // 14 : Version 2.19.0.xx
  60. // 15 : Version 2.19.2
  61. // 16 : Version 2.20.2
  62. // 17 : Version 2.20.4
  63. // 18 : Version 2.20.6
  64. // 19 : Version 2.20.7
  65. // 20 : Version 2.21.0
  66. // 21 : Version 2.21.0.3
  67. // 22 : Version 2.21.0.9
  68. // 23 : Version 2.21.0.15
  69. // 24 : Version 2.21.2.5
  70. // 25 : Version 2.21.3.1
  71. // 26 : Version 2.22.0.4
  72. // 27 : Version 2.22.0.7
  73. // 28 : Version 2.22.3.5
  74. // 29 : Version 2.22.5.2
  75. // 30 : Version 2.22.6.0
  76. // 31 : Version 2.22.6.3
  77. // 32 : Version 2.22.6.10
  78. // 33 : Version 2.22.7.1
  79. // 34 : Version 2.22.8.14
  80. // 35 : Version 2.22.8.14
  81. // 36 : Version 2.22.8.14
  82. // 37 : Version 2.22.8.14
  83. // 38 : Version 2.22.8.20
  84. // 39 : Version 2.22.9.1
  85. // 40 : Version 2.22.9.3
  86. // 41 : Version 2.22.9.5
  87. // 42 : Version 2.23.1.0
  88. // 43 : Version 2.23.2.0
  89. migrationBlock: { migration, oldSchemaVersion in
  90. // We haven’t migrated anything yet, so oldSchemaVersion == 0
  91. /*
  92. if (oldSchemaVersion < 37) {
  93. migration.enumerateObjects(ofType: tableMetadata.className()) { oldObject, newObject in
  94. let account = oldObject!["account"] as! String
  95. let serverUrl = oldObject!["serverUrl"] as! String
  96. let fileName = oldObject!["fileName"] as! String
  97. newObject!["metadataID"] = CCUtility.createMetadataID(fromAccount: account, serverUrl: serverUrl, fileName: fileName)
  98. }
  99. migration.enumerateObjects(ofType: tablePhotos.className()) { oldObject, newObject in
  100. let account = oldObject!["account"] as! String
  101. let serverUrl = oldObject!["serverUrl"] as! String
  102. let fileName = oldObject!["fileName"] as! String
  103. newObject!["metadataID"] = CCUtility.createMetadataID(fromAccount: account, serverUrl: serverUrl, fileName: fileName)
  104. }
  105. }
  106. */
  107. if oldSchemaVersion < 41 {
  108. migration.deleteData(forType: tableActivity.className())
  109. migration.deleteData(forType: tableMetadata.className())
  110. migration.deleteData(forType: tableDirectory.className())
  111. }
  112. })
  113. // Encrypting the database file on disk with AES-256+SHA2 by supplying a 64-byte encryption key
  114. if NCBrandOptions.sharedInstance.use_database_encryption {
  115. if let keyData = NCBrandOptions.sharedInstance.databaseEncryptionKey.data(using: String.Encoding.utf8, allowLossyConversion: false) {
  116. config.encryptionKey = keyData
  117. }
  118. }
  119. Realm.Configuration.defaultConfiguration = config
  120. _ = try! Realm()
  121. }
  122. //MARK: -
  123. //MARK: Utility Database
  124. @objc func clearTable(_ table : Object.Type, account: String?) {
  125. let results : Results<Object>
  126. let realm = try! Realm()
  127. realm.beginWrite()
  128. if let account = account {
  129. results = realm.objects(table).filter("account = %@", account)
  130. } else {
  131. results = realm.objects(table)
  132. }
  133. realm.delete(results)
  134. do {
  135. try realm.commitWrite()
  136. } catch let error {
  137. print("[LOG] Could not write to database: ", error)
  138. }
  139. }
  140. @objc func removeDB() {
  141. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  142. let realmURLs = [
  143. realmURL,
  144. realmURL.appendingPathExtension("lock"),
  145. realmURL.appendingPathExtension("note"),
  146. realmURL.appendingPathExtension("management")
  147. ]
  148. for URL in realmURLs {
  149. do {
  150. try FileManager.default.removeItem(at: URL)
  151. } catch let error {
  152. print("[LOG] Could not write to database: ", error)
  153. }
  154. }
  155. }
  156. @objc func getThreadConfined(_ object: Object) -> Any {
  157. // id tradeReference = [[NCManageDatabase sharedInstance] getThreadConfined:metadata];
  158. return ThreadSafeReference(to: object)
  159. }
  160. @objc func putThreadConfined(_ tableRef: Any) -> Object? {
  161. //tableMetadata *metadataThread = (tableMetadata *)[[NCManageDatabase sharedInstance] putThreadConfined:tradeReference];
  162. let realm = try! Realm()
  163. return realm.resolve(tableRef as! ThreadSafeReference<Object>)
  164. }
  165. @objc func isTableInvalidated(_ object: Object) -> Bool {
  166. return object.isInvalidated
  167. }
  168. //MARK: -
  169. //MARK: Table Account
  170. @objc func addAccount(_ account: String, url: String, user: String, password: String, loginFlow: Bool) {
  171. let realm = try! Realm()
  172. realm.beginWrite()
  173. let addObject = tableAccount()
  174. addObject.account = account
  175. addObject.loginFlow = loginFlow
  176. // Brand
  177. if NCBrandOptions.sharedInstance.use_default_auto_upload {
  178. addObject.autoUpload = true
  179. addObject.autoUploadImage = true
  180. addObject.autoUploadVideo = true
  181. addObject.autoUploadWWAnVideo = true
  182. }
  183. addObject.password = password
  184. addObject.url = url
  185. addObject.user = user
  186. addObject.userID = user
  187. realm.add(addObject)
  188. do {
  189. try realm.commitWrite()
  190. } catch let error {
  191. print("[LOG] Could not write to database: ", error)
  192. }
  193. }
  194. @objc func setAccountPassword(_ account: String, password: String) -> tableAccount? {
  195. let realm = try! Realm()
  196. realm.beginWrite()
  197. guard let result = realm.objects(tableAccount.self).filter("account = %@", account).first else {
  198. realm.cancelWrite()
  199. return nil
  200. }
  201. result.password = password
  202. do {
  203. try realm.commitWrite()
  204. } catch let error {
  205. print("[LOG] Could not write to database: ", error)
  206. return nil
  207. }
  208. return result
  209. }
  210. @objc func deleteAccount(_ account: String) {
  211. let realm = try! Realm()
  212. realm.beginWrite()
  213. guard let result = realm.objects(tableAccount.self).filter("account = %@", account).first else {
  214. realm.cancelWrite()
  215. return
  216. }
  217. realm.delete(result)
  218. do {
  219. try realm.commitWrite()
  220. } catch let error {
  221. print("[LOG] Could not write to database: ", error)
  222. }
  223. }
  224. @objc func getAccountActive() -> tableAccount? {
  225. let realm = try! Realm()
  226. realm.refresh()
  227. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  228. return nil
  229. }
  230. return result
  231. }
  232. @objc func getAccounts() -> [String]? {
  233. let realm = try! Realm()
  234. realm.refresh()
  235. let results = realm.objects(tableAccount.self).sorted(byKeyPath: "account", ascending: true)
  236. if results.count > 0 {
  237. return Array(results.map { $0.account })
  238. }
  239. return nil
  240. }
  241. @objc func getAccount(predicate: NSPredicate) -> tableAccount? {
  242. let realm = try! Realm()
  243. realm.refresh()
  244. if let result = realm.objects(tableAccount.self).filter(predicate).first {
  245. return tableAccount.init(value: result)
  246. }
  247. return nil
  248. }
  249. @objc func getAccountAutoUploadFileName() -> String {
  250. let realm = try! Realm()
  251. realm.refresh()
  252. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  253. return ""
  254. }
  255. if result.autoUploadFileName.count > 0 {
  256. return result.autoUploadFileName
  257. } else {
  258. return NCBrandOptions.sharedInstance.folderDefaultAutoUpload
  259. }
  260. }
  261. @objc func getAccountAutoUploadDirectory(_ activeUrl : String) -> String {
  262. let realm = try! Realm()
  263. realm.refresh()
  264. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  265. return ""
  266. }
  267. if result.autoUploadDirectory.count > 0 {
  268. return result.autoUploadDirectory
  269. } else {
  270. return CCUtility.getHomeServerUrlActiveUrl(activeUrl)
  271. }
  272. }
  273. @objc func getAccountAutoUploadPath(_ activeUrl : String) -> String {
  274. let cameraFileName = self.getAccountAutoUploadFileName()
  275. let cameraDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  276. let folderPhotos = CCUtility.stringAppendServerUrl(cameraDirectory, addFileName: cameraFileName)!
  277. return folderPhotos
  278. }
  279. @objc func setAccountActive(_ account: String) -> tableAccount? {
  280. let realm = try! Realm()
  281. var activeAccount = tableAccount()
  282. do {
  283. try realm.write {
  284. let results = realm.objects(tableAccount.self)
  285. for result in results {
  286. if result.account == account {
  287. result.active = true
  288. activeAccount = result
  289. } else {
  290. result.active = false
  291. }
  292. }
  293. }
  294. } catch let error {
  295. print("[LOG] Could not write to database: ", error)
  296. return nil
  297. }
  298. return activeAccount
  299. }
  300. @objc func setAccountAutoUploadProperty(_ property: String, state: Bool) {
  301. let realm = try! Realm()
  302. realm.beginWrite()
  303. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  304. realm.cancelWrite()
  305. return
  306. }
  307. if (tableAccount().objectSchema.properties.contains { $0.name == property }) {
  308. result[property] = state
  309. do {
  310. try realm.commitWrite()
  311. } catch let error {
  312. print("[LOG] Could not write to database: ", error)
  313. }
  314. } else {
  315. print("[LOG] property not found")
  316. }
  317. }
  318. @objc func setAccountAutoUploadFileName(_ fileName: String?) {
  319. let realm = try! Realm()
  320. do {
  321. try realm.write {
  322. if let result = realm.objects(tableAccount.self).filter("active = true").first {
  323. if let fileName = fileName {
  324. result.autoUploadFileName = fileName
  325. } else {
  326. result.autoUploadFileName = self.getAccountAutoUploadFileName()
  327. }
  328. }
  329. }
  330. } catch let error {
  331. print("[LOG] Could not write to database: ", error)
  332. }
  333. }
  334. @objc func setAccountAutoUploadDirectory(_ serverUrl: String?, activeUrl: String) {
  335. let realm = try! Realm()
  336. do {
  337. try realm.write {
  338. if let result = realm.objects(tableAccount.self).filter("active = true").first {
  339. if let serverUrl = serverUrl {
  340. result.autoUploadDirectory = serverUrl
  341. } else {
  342. result.autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  343. }
  344. }
  345. }
  346. } catch let error {
  347. print("[LOG] Could not write to database: ", error)
  348. }
  349. }
  350. @objc func setAccountUserProfile(_ userProfile: OCUserProfile) -> tableAccount? {
  351. guard let activeAccount = self.getAccountActive() else {
  352. return nil
  353. }
  354. let realm = try! Realm()
  355. do {
  356. try realm.write {
  357. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  358. return
  359. }
  360. // Update userID
  361. if userProfile.id.count == 0 { // for old config.
  362. result.userID = result.user
  363. } else {
  364. result.userID = userProfile.id
  365. }
  366. result.enabled = userProfile.enabled
  367. result.address = userProfile.address
  368. result.displayName = userProfile.displayName
  369. result.email = userProfile.email
  370. result.phone = userProfile.phone
  371. result.twitter = userProfile.twitter
  372. result.webpage = userProfile.webpage
  373. result.quota = userProfile.quota
  374. result.quotaFree = userProfile.quotaFree
  375. result.quotaRelative = userProfile.quotaRelative
  376. result.quotaTotal = userProfile.quotaTotal
  377. result.quotaUsed = userProfile.quotaUsed
  378. }
  379. } catch let error {
  380. print("[LOG] Could not write to database: ", error)
  381. }
  382. return activeAccount
  383. }
  384. @objc func setAccountDateSearchContentTypeImageVideo(_ date: Date) {
  385. guard let activeAccount = self.getAccountActive() else {
  386. return
  387. }
  388. let realm = try! Realm()
  389. do {
  390. try realm.write {
  391. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  392. return
  393. }
  394. result.dateSearchContentTypeImageVideo = date
  395. }
  396. } catch let error {
  397. print("[LOG] Could not write to database: ", error)
  398. }
  399. }
  400. @objc func getAccountStartDirectoryMediaTabView(_ homeServerUrl: String) -> String {
  401. guard let activeAccount = self.getAccountActive() else {
  402. return ""
  403. }
  404. let realm = try! Realm()
  405. realm.refresh()
  406. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  407. return ""
  408. }
  409. if result.startDirectoryPhotosTab == "" {
  410. self.setAccountStartDirectoryMediaTabView(homeServerUrl)
  411. return homeServerUrl
  412. } else {
  413. return result.startDirectoryPhotosTab
  414. }
  415. }
  416. @objc func setAccountStartDirectoryMediaTabView(_ directory: String) {
  417. guard let activeAccount = self.getAccountActive() else {
  418. return
  419. }
  420. let realm = try! Realm()
  421. do {
  422. try realm.write {
  423. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  424. return
  425. }
  426. result.startDirectoryPhotosTab = directory
  427. }
  428. } catch let error {
  429. print("[LOG] Could not write to database: ", error)
  430. }
  431. }
  432. //MARK: -
  433. //MARK: Table Activity
  434. @objc func addActivity(_ listOfActivity: [OCActivity], account: String) {
  435. let realm = try! Realm()
  436. do {
  437. try realm.write {
  438. for activity in listOfActivity {
  439. let addObjectActivity = tableActivity()
  440. addObjectActivity.account = account
  441. addObjectActivity.idActivity = activity.idActivity
  442. addObjectActivity.idPrimaryKey = account + String(activity.idActivity)
  443. if let date = activity.date {
  444. addObjectActivity.date = date as NSDate
  445. }
  446. addObjectActivity.app = activity.app
  447. addObjectActivity.type = activity.type
  448. addObjectActivity.user = activity.user
  449. addObjectActivity.subject = activity.subject
  450. if activity.subject_rich.count > 0 {
  451. addObjectActivity.subjectRich = activity.subject_rich[0] as? String ?? ""
  452. if activity.subject_rich.count > 1 {
  453. if let dict = activity.subject_rich[1] as? [String:AnyObject] {
  454. for (key, value) in dict {
  455. let addObjectActivitySubjectRich = tableActivitySubjectRich()
  456. if let dict = value as? [String:AnyObject] {
  457. addObjectActivitySubjectRich.account = account
  458. switch dict["id"] {
  459. case is String:
  460. addObjectActivitySubjectRich.id = dict["id"] as? String ?? ""
  461. case is Int:
  462. addObjectActivitySubjectRich.id = String(dict["id"] as? Int ?? 0)
  463. default: addObjectActivitySubjectRich.id = ""
  464. }
  465. addObjectActivitySubjectRich.name = dict["name"] as? String ?? ""
  466. addObjectActivitySubjectRich.idPrimaryKey = account + String(activity.idActivity) + addObjectActivitySubjectRich.id + addObjectActivitySubjectRich.name
  467. addObjectActivitySubjectRich.key = key
  468. addObjectActivitySubjectRich.idActivity = activity.idActivity
  469. addObjectActivitySubjectRich.link = dict["link"] as? String ?? ""
  470. addObjectActivitySubjectRich.path = dict["path"] as? String ?? ""
  471. addObjectActivitySubjectRich.type = dict["type"] as? String ?? ""
  472. realm.add(addObjectActivitySubjectRich, update: true)
  473. }
  474. }
  475. }
  476. }
  477. }
  478. if activity.previews.count > 0 {
  479. for case let activityPreview as [String:AnyObject] in activity.previews {
  480. let addObjectActivityPreview = tableActivityPreview()
  481. addObjectActivityPreview.account = account
  482. addObjectActivityPreview.idActivity = activity.idActivity
  483. addObjectActivityPreview.fileId = activityPreview["fileId"] as? Int ?? 0
  484. addObjectActivityPreview.idPrimaryKey = account + String(activity.idActivity) + String(addObjectActivityPreview.fileId)
  485. addObjectActivityPreview.source = activityPreview["source"] as? String ?? ""
  486. addObjectActivityPreview.link = activityPreview["link"] as? String ?? ""
  487. addObjectActivityPreview.mimeType = activityPreview["mimeType"] as? String ?? ""
  488. addObjectActivityPreview.view = activityPreview["view"] as? String ?? ""
  489. addObjectActivityPreview.isMimeTypeIcon = activityPreview["isMimeTypeIcon"] as? Bool ?? false
  490. realm.add(addObjectActivityPreview, update: true)
  491. }
  492. }
  493. addObjectActivity.icon = activity.icon
  494. addObjectActivity.link = activity.link
  495. addObjectActivity.message = activity.message
  496. addObjectActivity.objectType = activity.object_type
  497. addObjectActivity.objectId = activity.object_id
  498. addObjectActivity.objectName = activity.object_name
  499. realm.add(addObjectActivity, update: true)
  500. }
  501. }
  502. } catch let error {
  503. print("[LOG] Could not write to database: ", error)
  504. }
  505. }
  506. @objc func getActivity(predicate: NSPredicate) -> [tableActivity] {
  507. let realm = try! Realm()
  508. realm.refresh()
  509. let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  510. return Array(results.map { tableActivity.init(value:$0) })
  511. }
  512. @objc func getActivitySubjectRich(account: String, idActivity: Int, key: String) -> tableActivitySubjectRich? {
  513. let realm = try! Realm()
  514. realm.refresh()
  515. let results = realm.objects(tableActivitySubjectRich.self).filter("account = %@ && idActivity == %d && key = %@", account, idActivity, key).first
  516. return results.map { tableActivitySubjectRich.init(value:$0) }
  517. }
  518. @objc func getActivitySubjectRich(account: String, idActivity: Int, id: String) -> tableActivitySubjectRich? {
  519. let realm = try! Realm()
  520. realm.refresh()
  521. let results = realm.objects(tableActivitySubjectRich.self).filter("account = %@ && idActivity == %d && id == %@", account, idActivity, id).first
  522. return results.map { tableActivitySubjectRich.init(value:$0) }
  523. }
  524. @objc func getActivityPreview(account: String, idActivity: Int, orderKeysId: [String]) -> [tableActivityPreview] {
  525. let realm = try! Realm()
  526. realm.refresh()
  527. var results = [tableActivityPreview]()
  528. for id in orderKeysId {
  529. if let result = realm.objects(tableActivityPreview.self).filter("account = %@ && idActivity == %d && fileId == %d", account, idActivity, Int(id) ?? 0).first {
  530. results.append(result)
  531. }
  532. }
  533. return results
  534. }
  535. @objc func getActivityLastIdActivity(account: String) -> Int {
  536. let realm = try! Realm()
  537. realm.refresh()
  538. if let entities = realm.objects(tableActivity.self).filter("account = %@", account).max(by: { $0.idActivity < $1.idActivity }) {
  539. return entities.idActivity
  540. }
  541. return 0
  542. }
  543. //MARK: -
  544. //MARK: Table Capabilities
  545. @objc func addCapabilities(_ capabilities: OCCapabilities, account: String) {
  546. let realm = try! Realm()
  547. do {
  548. try realm.write {
  549. let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first
  550. var resultCapabilities = tableCapabilities()
  551. if let result = result {
  552. resultCapabilities = result
  553. }
  554. resultCapabilities.account = account
  555. resultCapabilities.themingBackground = capabilities.themingBackground
  556. resultCapabilities.themingBackgroundDefault = capabilities.themingBackgroundDefault
  557. resultCapabilities.themingBackgroundPlain = capabilities.themingBackgroundPlain
  558. resultCapabilities.themingColor = capabilities.themingColor
  559. resultCapabilities.themingColorElement = capabilities.themingColorElement
  560. resultCapabilities.themingColorText = capabilities.themingColorText
  561. resultCapabilities.themingLogo = capabilities.themingLogo
  562. resultCapabilities.themingName = capabilities.themingName
  563. resultCapabilities.themingSlogan = capabilities.themingSlogan
  564. resultCapabilities.themingUrl = capabilities.themingUrl
  565. resultCapabilities.versionMajor = capabilities.versionMajor
  566. resultCapabilities.versionMinor = capabilities.versionMinor
  567. resultCapabilities.versionMicro = capabilities.versionMicro
  568. resultCapabilities.versionString = capabilities.versionString
  569. resultCapabilities.endToEndEncryption = capabilities.isEndToEndEncryptionEnabled
  570. resultCapabilities.endToEndEncryptionVersion = capabilities.endToEndEncryptionVersion
  571. resultCapabilities.richdocumentsMimetypes.removeAll()
  572. for mimeType in capabilities.richdocumentsMimetypes {
  573. resultCapabilities.richdocumentsMimetypes.append(mimeType as! String)
  574. }
  575. resultCapabilities.richdocumentsDirectEditing = capabilities.richdocumentsDirectEditing
  576. // FILES SHARING
  577. resultCapabilities.isFilesSharingAPIEnabled = capabilities.isFilesSharingAPIEnabled
  578. resultCapabilities.filesSharingDefaulPermissions = capabilities.filesSharingDefaulPermissions
  579. resultCapabilities.isFilesSharingGroupSharing = capabilities.isFilesSharingGroupSharing
  580. resultCapabilities.isFilesSharingReSharing = capabilities.isFilesSharingReSharing
  581. resultCapabilities.isFilesSharingPublicShareLinkEnabled = capabilities.isFilesSharingPublicShareLinkEnabled
  582. resultCapabilities.isFilesSharingAllowPublicUploadsEnabled = capabilities.isFilesSharingAllowPublicUploadsEnabled
  583. resultCapabilities.isFilesSharingAllowPublicUserSendMail = capabilities.isFilesSharingAllowPublicUserSendMail
  584. resultCapabilities.isFilesSharingAllowPublicUploadFilesDrop = capabilities.isFilesSharingAllowPublicUploadFilesDrop
  585. resultCapabilities.isFilesSharingAllowPublicMultipleLinks = capabilities.isFilesSharingAllowPublicMultipleLinks
  586. resultCapabilities.isFilesSharingPublicExpireDateByDefaultEnabled = capabilities.isFilesSharingPublicExpireDateByDefaultEnabled
  587. resultCapabilities.isFilesSharingPublicExpireDateEnforceEnabled = capabilities.isFilesSharingPublicExpireDateEnforceEnabled
  588. resultCapabilities.filesSharingPublicExpireDateDays = capabilities.filesSharingPublicExpireDateDays
  589. resultCapabilities.isFilesSharingPublicPasswordEnforced = capabilities.isFilesSharingPublicPasswordEnforced
  590. resultCapabilities.isFilesSharingAllowUserSendMail = capabilities.isFilesSharingAllowUserSendMail
  591. resultCapabilities.isFilesSharingUserExpireDate = capabilities.isFilesSharingUserExpireDate
  592. resultCapabilities.isFilesSharingGroupEnabled = capabilities.isFilesSharingGroupEnabled
  593. resultCapabilities.isFilesSharingGroupExpireDate = capabilities.isFilesSharingGroupExpireDate
  594. resultCapabilities.isFilesSharingFederationAllowUserSendShares = capabilities.isFilesSharingFederationAllowUserSendShares
  595. resultCapabilities.isFilesSharingFederationAllowUserReceiveShares = capabilities.isFilesSharingFederationAllowUserReceiveShares
  596. resultCapabilities.isFilesSharingFederationExpireDate = capabilities.isFilesSharingFederationExpireDate
  597. resultCapabilities.isFileSharingShareByMailEnabled = capabilities.isFileSharingShareByMailEnabled
  598. resultCapabilities.isFileSharingShareByMailPassword = capabilities.isFileSharingShareByMailPassword
  599. resultCapabilities.isFileSharingShareByMailUploadFilesDrop = capabilities.isFileSharingShareByMailUploadFilesDrop
  600. if result == nil {
  601. realm.add(resultCapabilities)
  602. }
  603. }
  604. } catch let error {
  605. print("[LOG] Could not write to database: ", error)
  606. }
  607. }
  608. @objc func getCapabilites(account: String) -> tableCapabilities? {
  609. let realm = try! Realm()
  610. realm.refresh()
  611. return realm.objects(tableCapabilities.self).filter("account = %@", account).first
  612. }
  613. @objc func getServerVersion(account: String) -> Int {
  614. let realm = try! Realm()
  615. realm.refresh()
  616. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  617. return 0
  618. }
  619. return result.versionMajor
  620. }
  621. @objc func getEndToEndEncryptionVersion(account: String) -> Float {
  622. let realm = try! Realm()
  623. realm.refresh()
  624. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  625. return 0
  626. }
  627. return Float(result.endToEndEncryptionVersion)!
  628. }
  629. @objc func compareServerVersion(_ versionCompare: String, account: String) -> Int {
  630. let realm = try! Realm()
  631. guard let capabilities = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  632. return -1
  633. }
  634. let versionServer = capabilities.versionString
  635. var v1 = versionServer.split(separator:".").map { Int(String($0)) }
  636. var v2 = versionCompare.split(separator:".").map { Int(String($0)) }
  637. var result = 0
  638. for i in 0..<max(v1.count,v2.count) {
  639. let left = i >= v1.count ? 0 : v1[i]
  640. let right = i >= v2.count ? 0 : v2[i]
  641. if (left == right) {
  642. result = 0
  643. } else if left! > right! {
  644. return 1
  645. } else if right! > left! {
  646. return -1
  647. }
  648. }
  649. return result
  650. }
  651. @objc func getRichdocumentsMimetypes(account: String) -> [String]? {
  652. let realm = try! Realm()
  653. realm.refresh()
  654. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  655. return nil
  656. }
  657. return Array(result.richdocumentsMimetypes)
  658. }
  659. //MARK: -
  660. //MARK: Table Certificates
  661. @objc func addCertificates(_ certificateLocation: String) {
  662. let realm = try! Realm()
  663. do {
  664. try realm.write {
  665. let addObject = tableCertificates()
  666. addObject.certificateLocation = certificateLocation
  667. realm.add(addObject)
  668. }
  669. } catch let error {
  670. print("[LOG] Could not write to database: ", error)
  671. }
  672. }
  673. @objc func getCertificatesLocation(_ localCertificatesFolder: String) -> [String] {
  674. let realm = try! Realm()
  675. realm.refresh()
  676. let results = realm.objects(tableCertificates.self)
  677. return Array(results.map { "\(localCertificatesFolder)/\($0.certificateLocation)" })
  678. }
  679. //MARK: -
  680. //MARK: Table Directory
  681. @objc func addDirectory(encrypted: Bool, favorite: Bool, fileID: String?, permissions: String?, serverUrl: String, account: String) -> tableDirectory? {
  682. let realm = try! Realm()
  683. realm.beginWrite()
  684. var addObject = tableDirectory()
  685. let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first
  686. if result != nil {
  687. addObject = result!
  688. } else {
  689. addObject.directoryID = CCUtility.createDirectoyID(fromAccount: account, serverUrl: serverUrl)
  690. }
  691. addObject.account = account
  692. addObject.e2eEncrypted = encrypted
  693. addObject.favorite = favorite
  694. if let fileID = fileID {
  695. addObject.fileID = fileID
  696. }
  697. if let permissions = permissions {
  698. addObject.permissions = permissions
  699. }
  700. addObject.serverUrl = serverUrl
  701. realm.add(addObject, update: true)
  702. do {
  703. try realm.commitWrite()
  704. } catch let error {
  705. print("[LOG] Could not write to database: ", error)
  706. return nil
  707. }
  708. return tableDirectory.init(value: addObject)
  709. }
  710. @objc func deleteDirectoryAndSubDirectory(serverUrl: String, account: String) {
  711. let realm = try! Realm()
  712. realm.refresh()
  713. let results = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl BEGINSWITH %@", account, serverUrl)
  714. // Delete table Metadata & LocalFile
  715. for result in results {
  716. self.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", result.account, result.serverUrl))
  717. self.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", result.fileID))
  718. }
  719. // Delete table Dirrectory
  720. do {
  721. try realm.write {
  722. realm.delete(results)
  723. }
  724. } catch let error {
  725. print("[LOG] Could not write to database: ", error)
  726. }
  727. }
  728. @objc func setDirectory(serverUrl: String, serverUrlTo: String?, etag: String?, fileID: String?, encrypted: Bool, account: String) {
  729. let realm = try! Realm()
  730. do {
  731. try realm.write {
  732. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  733. return
  734. }
  735. let directory = tableDirectory.init(value: result)
  736. realm.delete(result)
  737. directory.e2eEncrypted = encrypted
  738. if let etag = etag {
  739. directory.etag = etag
  740. }
  741. if let fileID = fileID {
  742. directory.fileID = fileID
  743. }
  744. if let serverUrlTo = serverUrlTo {
  745. directory.serverUrl = serverUrlTo
  746. }
  747. directory.directoryID = CCUtility.createDirectoyID(fromAccount: account, serverUrl: directory.serverUrl)
  748. realm.add(directory, update: true)
  749. }
  750. } catch let error {
  751. print("[LOG] Could not write to database: ", error)
  752. }
  753. }
  754. @objc func clearDateRead(serverUrl: String, account: String) {
  755. let realm = try! Realm()
  756. do {
  757. try realm.write {
  758. var predicate = NSPredicate()
  759. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)
  760. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  761. return
  762. }
  763. result.dateReadDirectory = nil
  764. result.etag = ""
  765. realm.add(result, update: true)
  766. }
  767. } catch let error {
  768. print("[LOG] Could not write to database: ", error)
  769. }
  770. }
  771. @objc func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
  772. let realm = try! Realm()
  773. realm.refresh()
  774. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  775. return nil
  776. }
  777. return tableDirectory.init(value: result)
  778. }
  779. @objc func getTablesDirectory(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableDirectory]? {
  780. let realm = try! Realm()
  781. realm.refresh()
  782. let results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  783. if (results.count > 0) {
  784. return Array(results.map { tableDirectory.init(value:$0) })
  785. } else {
  786. return nil
  787. }
  788. }
  789. @objc func setDateReadDirectory(serverUrl: String, account: String) {
  790. let realm = try! Realm()
  791. realm.beginWrite()
  792. guard let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  793. realm.cancelWrite()
  794. return
  795. }
  796. result.dateReadDirectory = NSDate()
  797. do {
  798. try realm.commitWrite()
  799. } catch let error {
  800. print("[LOG] Could not write to database: ", error)
  801. }
  802. }
  803. @objc func setClearAllDateReadDirectory() {
  804. let realm = try! Realm()
  805. do {
  806. try realm.write {
  807. let results = realm.objects(tableDirectory.self)
  808. for result in results {
  809. result.dateReadDirectory = nil;
  810. result.etag = ""
  811. }
  812. }
  813. } catch let error {
  814. print("[LOG] Could not write to database: ", error)
  815. }
  816. }
  817. @objc func setDirectoryLock(serverUrl: String, lock: Bool, account: String) -> Bool {
  818. let realm = try! Realm()
  819. var update = false
  820. do {
  821. try realm.write {
  822. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  823. realm.cancelWrite()
  824. return
  825. }
  826. result.lock = lock
  827. update = true
  828. }
  829. } catch let error {
  830. print("[LOG] Could not write to database: ", error)
  831. return false
  832. }
  833. return update
  834. }
  835. @objc func setAllDirectoryUnLock(account: String) {
  836. let realm = try! Realm()
  837. do {
  838. try realm.write {
  839. let results = realm.objects(tableDirectory.self).filter("account = %@", account)
  840. for result in results {
  841. result.lock = false;
  842. }
  843. }
  844. } catch let error {
  845. print("[LOG] Could not write to database: ", error)
  846. }
  847. }
  848. @objc func setDirectory(serverUrl: String, offline: Bool, account: String) {
  849. let realm = try! Realm()
  850. do {
  851. try realm.write {
  852. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  853. realm.cancelWrite()
  854. return
  855. }
  856. result.offline = offline
  857. }
  858. } catch let error {
  859. print("[LOG] Could not write to database: ", error)
  860. }
  861. }
  862. //MARK: -
  863. //MARK: Table e2e Encryption
  864. @objc func addE2eEncryption(_ e2e: tableE2eEncryption) -> Bool {
  865. guard self.getAccountActive() != nil else {
  866. return false
  867. }
  868. let realm = try! Realm()
  869. do {
  870. try realm.write {
  871. realm.add(e2e, update: true)
  872. }
  873. } catch let error {
  874. print("[LOG] Could not write to database: ", error)
  875. return false
  876. }
  877. return true
  878. }
  879. @objc func deleteE2eEncryption(predicate: NSPredicate) {
  880. guard self.getAccountActive() != nil else {
  881. return
  882. }
  883. let realm = try! Realm()
  884. do {
  885. try realm.write {
  886. let results = realm.objects(tableE2eEncryption.self).filter(predicate)
  887. realm.delete(results)
  888. }
  889. } catch let error {
  890. print("[LOG] Could not write to database: ", error)
  891. }
  892. }
  893. @objc func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
  894. guard self.getAccountActive() != nil else {
  895. return nil
  896. }
  897. let realm = try! Realm()
  898. realm.refresh()
  899. guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else {
  900. return nil
  901. }
  902. return tableE2eEncryption.init(value: result)
  903. }
  904. @objc func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption]? {
  905. guard self.getAccountActive() != nil else {
  906. return nil
  907. }
  908. let realm = try! Realm()
  909. realm.refresh()
  910. let results : Results<tableE2eEncryption>
  911. results = realm.objects(tableE2eEncryption.self).filter(predicate)
  912. if (results.count > 0) {
  913. return Array(results.map { tableE2eEncryption.init(value:$0) })
  914. } else {
  915. return nil
  916. }
  917. }
  918. @objc func renameFileE2eEncryption(serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
  919. guard let tableAccount = self.getAccountActive() else {
  920. return
  921. }
  922. let realm = try! Realm()
  923. realm.beginWrite()
  924. guard let result = realm.objects(tableE2eEncryption.self).filter("account = %@ AND serverUrl = %@ AND fileNameIdentifier = %@", tableAccount.account, serverUrl, fileNameIdentifier).first else {
  925. realm.cancelWrite()
  926. return
  927. }
  928. let object = tableE2eEncryption.init(value: result)
  929. realm.delete(result)
  930. object.fileName = newFileName
  931. object.fileNamePath = newFileNamePath
  932. realm.add(object)
  933. do {
  934. try realm.commitWrite()
  935. } catch let error {
  936. print("[LOG] Could not write to database: ", error)
  937. return
  938. }
  939. return
  940. }
  941. //MARK: -
  942. //MARK: Table e2e Encryption Lock
  943. @objc func getE2ETokenLock(serverUrl: String) -> tableE2eEncryptionLock? {
  944. guard let tableAccount = self.getAccountActive() else {
  945. return nil
  946. }
  947. let realm = try! Realm()
  948. realm.refresh()
  949. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account = %@ AND serverUrl = %@", tableAccount.account, serverUrl).first else {
  950. return nil
  951. }
  952. return tableE2eEncryptionLock.init(value: result)
  953. }
  954. @objc func setE2ETokenLock(serverUrl: String, fileID: String, token: String) {
  955. guard let tableAccount = self.getAccountActive() else {
  956. return
  957. }
  958. let realm = try! Realm()
  959. realm.beginWrite()
  960. let addObject = tableE2eEncryptionLock()
  961. addObject.account = tableAccount.account
  962. addObject.fileID = fileID
  963. addObject.serverUrl = serverUrl
  964. addObject.token = token
  965. realm.add(addObject, update: true)
  966. do {
  967. try realm.commitWrite()
  968. } catch let error {
  969. print("[LOG] Could not write to database: ", error)
  970. }
  971. }
  972. @objc func deteleE2ETokenLock(serverUrl: String) {
  973. guard let tableAccount = self.getAccountActive() else {
  974. return
  975. }
  976. let realm = try! Realm()
  977. realm.beginWrite()
  978. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account = %@ AND serverUrl = %@", tableAccount.account, serverUrl).first else {
  979. return
  980. }
  981. realm.delete(result)
  982. do {
  983. try realm.commitWrite()
  984. } catch let error {
  985. print("[LOG] Could not write to database: ", error)
  986. }
  987. }
  988. //MARK: -
  989. //MARK: Table External Sites
  990. @objc func addExternalSites(_ externalSites: OCExternalSites, account: String) {
  991. let realm = try! Realm()
  992. do {
  993. try realm.write {
  994. let addObject = tableExternalSites()
  995. addObject.account = account
  996. addObject.idExternalSite = externalSites.idExternalSite
  997. addObject.icon = externalSites.icon
  998. addObject.lang = externalSites.lang
  999. addObject.name = externalSites.name
  1000. addObject.url = externalSites.url
  1001. addObject.type = externalSites.type
  1002. realm.add(addObject)
  1003. }
  1004. } catch let error {
  1005. print("[LOG] Could not write to database: ", error)
  1006. }
  1007. }
  1008. @objc func deleteExternalSites(account: String) {
  1009. let realm = try! Realm()
  1010. do {
  1011. try realm.write {
  1012. let results = realm.objects(tableExternalSites.self).filter("account = %@", account)
  1013. realm.delete(results)
  1014. }
  1015. } catch let error {
  1016. print("[LOG] Could not write to database: ", error)
  1017. }
  1018. }
  1019. @objc func getAllExternalSites(account: String) -> [tableExternalSites]? {
  1020. let realm = try! Realm()
  1021. realm.refresh()
  1022. let results = realm.objects(tableExternalSites.self).filter("account = %@", account).sorted(byKeyPath: "idExternalSite", ascending: true)
  1023. return Array(results)
  1024. }
  1025. //MARK: -
  1026. //MARK: Table GPS
  1027. @objc func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  1028. let realm = try! Realm()
  1029. realm.beginWrite()
  1030. // Verify if exists
  1031. guard realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first == nil else {
  1032. realm.cancelWrite()
  1033. return
  1034. }
  1035. // Add new GPS
  1036. let addObject = tableGPS()
  1037. addObject.latitude = latitude
  1038. addObject.location = location
  1039. addObject.longitude = longitude
  1040. addObject.placemarkAdministrativeArea = placemarkAdministrativeArea
  1041. addObject.placemarkCountry = placemarkCountry
  1042. addObject.placemarkLocality = placemarkLocality
  1043. addObject.placemarkPostalCode = placemarkPostalCode
  1044. addObject.placemarkThoroughfare = placemarkThoroughfare
  1045. realm.add(addObject)
  1046. do {
  1047. try realm.commitWrite()
  1048. } catch let error {
  1049. print("[LOG] Could not write to database: ", error)
  1050. }
  1051. }
  1052. @objc func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  1053. let realm = try! Realm()
  1054. realm.refresh()
  1055. guard let result = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first else {
  1056. return nil
  1057. }
  1058. return result.location
  1059. }
  1060. //MARK: -
  1061. //MARK: Table LocalFile
  1062. @objc func addLocalFile(metadata: tableMetadata) {
  1063. let realm = try! Realm()
  1064. do {
  1065. try realm.write {
  1066. let addObject = tableLocalFile()
  1067. addObject.account = metadata.account
  1068. addObject.date = metadata.date
  1069. addObject.etag = metadata.etag
  1070. addObject.exifDate = NSDate()
  1071. addObject.exifLatitude = "-1"
  1072. addObject.exifLongitude = "-1"
  1073. addObject.fileID = metadata.fileID
  1074. addObject.fileName = metadata.fileName
  1075. addObject.size = metadata.size
  1076. realm.add(addObject, update: true)
  1077. }
  1078. } catch let error {
  1079. print("[LOG] Could not write to database: ", error)
  1080. }
  1081. }
  1082. @objc func deleteLocalFile(predicate: NSPredicate) {
  1083. let realm = try! Realm()
  1084. do {
  1085. try realm.write {
  1086. let results = realm.objects(tableLocalFile.self).filter(predicate)
  1087. realm.delete(results)
  1088. }
  1089. } catch let error {
  1090. print("[LOG] Could not write to database: ", error)
  1091. }
  1092. }
  1093. @objc func setLocalFile(fileID: String, date: NSDate?, exifDate: NSDate?, exifLatitude: String?, exifLongitude: String?, fileName: String?, etag: String?) {
  1094. let realm = try! Realm()
  1095. do {
  1096. try realm.write {
  1097. guard let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first else {
  1098. realm.cancelWrite()
  1099. return
  1100. }
  1101. if let date = date {
  1102. result.date = date
  1103. }
  1104. if let exifDate = exifDate {
  1105. result.exifDate = exifDate
  1106. }
  1107. if let exifLatitude = exifLatitude {
  1108. result.exifLatitude = exifLatitude
  1109. }
  1110. if let exifLongitude = exifLongitude {
  1111. result.exifLongitude = exifLongitude
  1112. }
  1113. if let fileName = fileName {
  1114. result.fileName = fileName
  1115. }
  1116. if let etag = etag {
  1117. result.etag = etag
  1118. }
  1119. }
  1120. } catch let error {
  1121. print("[LOG] Could not write to database: ", error)
  1122. }
  1123. }
  1124. @objc func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
  1125. let realm = try! Realm()
  1126. realm.refresh()
  1127. guard let result = realm.objects(tableLocalFile.self).filter(predicate).first else {
  1128. return nil
  1129. }
  1130. return tableLocalFile.init(value: result)
  1131. }
  1132. @objc func getTableLocalFiles(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableLocalFile]? {
  1133. let realm = try! Realm()
  1134. realm.refresh()
  1135. let results = realm.objects(tableLocalFile.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1136. if (results.count > 0) {
  1137. return Array(results.map { tableLocalFile.init(value:$0) })
  1138. } else {
  1139. return nil
  1140. }
  1141. }
  1142. @objc func setLocalFile(fileID: String, offline: Bool) {
  1143. let realm = try! Realm()
  1144. do {
  1145. try realm.write {
  1146. guard let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first else {
  1147. realm.cancelWrite()
  1148. return
  1149. }
  1150. result.offline = offline
  1151. }
  1152. } catch let error {
  1153. print("[LOG] Could not write to database: ", error)
  1154. }
  1155. }
  1156. //MARK: -
  1157. //MARK: Table Metadata
  1158. @objc func addMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  1159. if metadata.isInvalidated {
  1160. return nil
  1161. }
  1162. let serverUrl = metadata.serverUrl
  1163. let account = metadata.account
  1164. let realm = try! Realm()
  1165. do {
  1166. try realm.write {
  1167. realm.add(metadata, update: true)
  1168. }
  1169. } catch let error {
  1170. print("[LOG] Could not write to database: ", error)
  1171. return nil
  1172. }
  1173. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1174. if metadata.isInvalidated {
  1175. return nil
  1176. }
  1177. return tableMetadata.init(value: metadata)
  1178. }
  1179. @objc func addMetadatas(_ metadatas: [tableMetadata]) -> [tableMetadata]? {
  1180. var directoryToClearDate = [String:String]()
  1181. let realm = try! Realm()
  1182. do {
  1183. try realm.write {
  1184. for metadata in metadatas {
  1185. directoryToClearDate[metadata.serverUrl] = metadata.account
  1186. realm.add(metadata, update: true)
  1187. }
  1188. }
  1189. } catch let error {
  1190. print("[LOG] Could not write to database: ", error)
  1191. return nil
  1192. }
  1193. for (serverUrl, account) in directoryToClearDate {
  1194. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1195. }
  1196. return Array(metadatas.map { tableMetadata.init(value:$0) })
  1197. }
  1198. @objc func deleteMetadata(predicate: NSPredicate) {
  1199. var directoryToClearDate = [String:String]()
  1200. let realm = try! Realm()
  1201. realm.beginWrite()
  1202. let results = realm.objects(tableMetadata.self).filter(predicate)
  1203. for result in results {
  1204. directoryToClearDate[result.serverUrl] = result.account
  1205. }
  1206. realm.delete(results)
  1207. do {
  1208. try realm.commitWrite()
  1209. } catch let error {
  1210. print("[LOG] Could not write to database: ", error)
  1211. return
  1212. }
  1213. for (serverUrl, account) in directoryToClearDate {
  1214. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1215. }
  1216. }
  1217. @objc func moveMetadata(fileID: String, serverUrlTo: String) {
  1218. let realm = try! Realm()
  1219. do {
  1220. try realm.write {
  1221. let results = realm.objects(tableMetadata.self).filter("fileID == %@", fileID)
  1222. for result in results {
  1223. result.serverUrl = serverUrlTo
  1224. }
  1225. }
  1226. } catch let error {
  1227. print("[LOG] Could not write to database: ", error)
  1228. return
  1229. }
  1230. }
  1231. @objc func addMetadataServerUrl(fileID: String, serverUrl: String) {
  1232. let realm = try! Realm()
  1233. do {
  1234. try realm.write {
  1235. let results = realm.objects(tableMetadata.self).filter("fileID == %@", fileID)
  1236. for result in results {
  1237. result.serverUrl = serverUrl
  1238. }
  1239. }
  1240. } catch let error {
  1241. print("[LOG] Could not write to database: ", error)
  1242. return
  1243. }
  1244. }
  1245. @objc func renameMetadata(fileNameTo: String, fileID: String) -> tableMetadata? {
  1246. var result :tableMetadata?
  1247. let realm = try! Realm()
  1248. do {
  1249. try realm.write {
  1250. result = realm.objects(tableMetadata.self).filter("fileID == %@", fileID).first
  1251. if result != nil {
  1252. result!.fileName = fileNameTo
  1253. result!.fileNameView = fileNameTo
  1254. }
  1255. }
  1256. } catch let error {
  1257. print("[LOG] Could not write to database: ", error)
  1258. return nil
  1259. }
  1260. if result == nil {
  1261. return nil
  1262. }
  1263. self.setDateReadDirectory(serverUrl: result!.serverUrl, account: result!.account)
  1264. return tableMetadata.init(value: result!)
  1265. }
  1266. @objc func updateMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  1267. let account = metadata.account
  1268. let serverUrl = metadata.serverUrl
  1269. let realm = try! Realm()
  1270. do {
  1271. try realm.write {
  1272. realm.add(metadata, update: true)
  1273. }
  1274. } catch let error {
  1275. print("[LOG] Could not write to database: ", error)
  1276. return nil
  1277. }
  1278. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1279. return tableMetadata.init(value: metadata)
  1280. }
  1281. @objc func copyMetadata(_ object: tableMetadata) -> tableMetadata? {
  1282. return tableMetadata.init(value: object)
  1283. }
  1284. @objc func setMetadataSession(_ session: String?, sessionError: String?, sessionSelector: String?, sessionTaskIdentifier: Int, status: Int, predicate: NSPredicate) {
  1285. let realm = try! Realm()
  1286. realm.beginWrite()
  1287. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1288. realm.cancelWrite()
  1289. return
  1290. }
  1291. if let session = session {
  1292. result.session = session
  1293. }
  1294. if let sessionError = sessionError {
  1295. result.sessionError = sessionError
  1296. }
  1297. if let sessionSelector = sessionSelector {
  1298. result.sessionSelector = sessionSelector
  1299. }
  1300. result.sessionTaskIdentifier = sessionTaskIdentifier
  1301. result.status = status
  1302. let account = result.account
  1303. let serverUrl = result.serverUrl
  1304. do {
  1305. try realm.commitWrite()
  1306. } catch let error {
  1307. print("[LOG] Could not write to database: ", error)
  1308. return
  1309. }
  1310. // Update Date Read Directory
  1311. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1312. }
  1313. @objc func setMetadataFavorite(fileID: String, favorite: Bool) {
  1314. let realm = try! Realm()
  1315. realm.beginWrite()
  1316. guard let result = realm.objects(tableMetadata.self).filter("fileID == %@", fileID).first else {
  1317. realm.cancelWrite()
  1318. return
  1319. }
  1320. result.favorite = favorite
  1321. let account = result.account
  1322. let serverUrl = result.serverUrl
  1323. do {
  1324. try realm.commitWrite()
  1325. } catch let error {
  1326. print("[LOG] Could not write to database: ", error)
  1327. return
  1328. }
  1329. // Update Date Read Directory
  1330. setDateReadDirectory(serverUrl: serverUrl, account: account)
  1331. }
  1332. @objc func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  1333. let realm = try! Realm()
  1334. realm.beginWrite()
  1335. guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first else {
  1336. realm.cancelWrite()
  1337. return
  1338. }
  1339. result.fileNameView = newFileNameView
  1340. let account = result.account
  1341. let serverUrl = result.serverUrl
  1342. do {
  1343. try realm.commitWrite()
  1344. } catch let error {
  1345. print("[LOG] Could not write to database: ", error)
  1346. return
  1347. }
  1348. // Update Date Read Directory
  1349. setDateReadDirectory(serverUrl: serverUrl, account: account)
  1350. }
  1351. @objc func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  1352. let realm = try! Realm()
  1353. realm.refresh()
  1354. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1355. return nil
  1356. }
  1357. return tableMetadata.init(value: result)
  1358. }
  1359. @objc func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
  1360. let realm = try! Realm()
  1361. realm.refresh()
  1362. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1363. if (results.count > 0) {
  1364. return tableMetadata.init(value: results[0])
  1365. } else {
  1366. return nil
  1367. }
  1368. }
  1369. @objc func getMetadatas(predicate: NSPredicate, sorted: String?, ascending: Bool) -> [tableMetadata]? {
  1370. let realm = try! Realm()
  1371. realm.refresh()
  1372. let results : Results<tableMetadata>
  1373. if let sorted = sorted {
  1374. if (tableMetadata().objectSchema.properties.contains { $0.name == sorted }) {
  1375. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1376. } else {
  1377. results = realm.objects(tableMetadata.self).filter(predicate)
  1378. }
  1379. } else {
  1380. results = realm.objects(tableMetadata.self).filter(predicate)
  1381. }
  1382. if (results.count > 0) {
  1383. return Array(results.map { tableMetadata.init(value:$0) })
  1384. } else {
  1385. return nil
  1386. }
  1387. }
  1388. @objc func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
  1389. let realm = try! Realm()
  1390. realm.refresh()
  1391. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1392. if (results.count > 0 && results.count > index) {
  1393. return tableMetadata.init(value: results[index])
  1394. } else {
  1395. return nil
  1396. }
  1397. }
  1398. @objc func getMetadataInSessionFromFileName(_ fileName: String, serverUrl: String, taskIdentifier: Int) -> tableMetadata? {
  1399. let realm = try! Realm()
  1400. realm.refresh()
  1401. guard let result = realm.objects(tableMetadata.self).filter("serverUrl == %@ AND fileName == %@ AND session != '' AND sessionTaskIdentifier == %d", serverUrl, fileName, taskIdentifier).first else {
  1402. return nil
  1403. }
  1404. return tableMetadata.init(value: result)
  1405. }
  1406. @objc func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String:NSNumber] {
  1407. var listIdentifierRank = [String:NSNumber]()
  1408. let realm = try! Realm()
  1409. realm.refresh()
  1410. var counter = 10 as Int64
  1411. let results = realm.objects(tableMetadata.self).filter("account = %@ AND directory = true AND favorite = true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  1412. for result in results {
  1413. counter += 1
  1414. listIdentifierRank[result.fileID] = NSNumber(value: Int64(counter))
  1415. }
  1416. return listIdentifierRank
  1417. }
  1418. @objc func clearMetadatasUpload(account: String) {
  1419. let realm = try! Realm()
  1420. do {
  1421. try realm.write {
  1422. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, k_metadataStatusWaitUpload, k_metadataStatusUploadError)
  1423. realm.delete(results)
  1424. }
  1425. } catch let error {
  1426. print("[LOG] Could not write to database: ", error)
  1427. }
  1428. }
  1429. @objc func initNewMetadata(_ metadata: tableMetadata) -> tableMetadata {
  1430. return tableMetadata.init(value: metadata)
  1431. }
  1432. //MARK: -
  1433. //MARK: Table Media
  1434. @objc func getTableMedia(predicate: NSPredicate) -> tableMetadata? {
  1435. let realm = try! Realm()
  1436. realm.refresh()
  1437. guard let result = realm.objects(tableMedia.self).filter(predicate).first else {
  1438. return nil
  1439. }
  1440. return tableMetadata.init(value: result)
  1441. }
  1442. @objc func getTableMedias(predicate: NSPredicate) -> [tableMetadata]? {
  1443. let realm = try! Realm()
  1444. realm.refresh()
  1445. let results = realm.objects(tableMedia.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  1446. if (results.count > 0) {
  1447. return Array(results.map { tableMetadata.init(value:$0) })
  1448. } else {
  1449. return nil
  1450. }
  1451. }
  1452. func createTableMedia(_ metadatas: [tableMetadata], lteDate: Date, gteDate: Date,account: String) -> (isDifferent: Bool, newInsert: Int) {
  1453. let realm = try! Realm()
  1454. realm.refresh()
  1455. var numDelete: Int = 0
  1456. var numInsert: Int = 0
  1457. var etagsDelete = [String]()
  1458. var etagsInsert = [String]()
  1459. var isDifferent: Bool = false
  1460. var newInsert: Int = 0
  1461. do {
  1462. try realm.write {
  1463. // DELETE
  1464. let results = realm.objects(tableMedia.self).filter("account = %@ AND date >= %@ AND date <= %@", account, gteDate, lteDate)
  1465. etagsDelete = Array(results.map { $0.etag })
  1466. numDelete = results.count
  1467. // INSERT
  1468. let photos = Array(metadatas.map { tableMedia.init(value:$0) })
  1469. etagsInsert = Array(photos.map { $0.etag })
  1470. numInsert = photos.count
  1471. // CALCULATE DIFFERENT RETURN
  1472. if etagsDelete.count == etagsInsert.count && etagsDelete.sorted() == etagsInsert.sorted() {
  1473. isDifferent = false
  1474. } else {
  1475. isDifferent = true
  1476. newInsert = numInsert - numDelete
  1477. realm.delete(results)
  1478. realm.add(photos, update: true)
  1479. }
  1480. }
  1481. } catch let error {
  1482. print("[LOG] Could not write to database: ", error)
  1483. realm.cancelWrite()
  1484. }
  1485. return(isDifferent, newInsert)
  1486. }
  1487. @objc func getTableMediaDate(account: String, order: ComparisonResult) -> Date {
  1488. let realm = try! Realm()
  1489. realm.refresh()
  1490. if let entities = realm.objects(tableMedia.self).filter("account = %@", account).max(by: { $0.date.compare($1.date as Date) == order }) {
  1491. return Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: entities.date as Date)!
  1492. }
  1493. return Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!
  1494. }
  1495. //MARK: -
  1496. //MARK: Table Photo Library
  1497. @objc func addPhotoLibrary(_ assets: [PHAsset], account: String) -> Bool {
  1498. let realm = try! Realm()
  1499. if realm.isInWriteTransaction {
  1500. print("[LOG] Could not write to database, addPhotoLibrary is already in write transaction")
  1501. return false
  1502. } else {
  1503. do {
  1504. try realm.write {
  1505. var creationDateString = ""
  1506. for asset in assets {
  1507. let addObject = tablePhotoLibrary()
  1508. addObject.account = account
  1509. addObject.assetLocalIdentifier = asset.localIdentifier
  1510. addObject.mediaType = asset.mediaType.rawValue
  1511. if let creationDate = asset.creationDate {
  1512. addObject.creationDate = creationDate as NSDate
  1513. creationDateString = String(describing: creationDate)
  1514. } else {
  1515. creationDateString = ""
  1516. }
  1517. if let modificationDate = asset.modificationDate {
  1518. addObject.modificationDate = modificationDate as NSDate
  1519. }
  1520. addObject.idAsset = "\(account)\(asset.localIdentifier)\(creationDateString)"
  1521. realm.add(addObject, update: true)
  1522. }
  1523. }
  1524. } catch let error {
  1525. print("[LOG] Could not write to database: ", error)
  1526. return false
  1527. }
  1528. }
  1529. return true
  1530. }
  1531. @objc func getPhotoLibraryIdAsset(image: Bool, video: Bool, account: String) -> [String]? {
  1532. let realm = try! Realm()
  1533. realm.refresh()
  1534. var predicate = NSPredicate()
  1535. if (image && video) {
  1536. predicate = NSPredicate(format: "account == %@ AND (mediaType == %i OR mediaType == %i)", account, PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
  1537. } else if (image) {
  1538. predicate = NSPredicate(format: "account == %@ AND mediaType == %i", account, PHAssetMediaType.image.rawValue)
  1539. } else if (video) {
  1540. predicate = NSPredicate(format: "account == %@ AND mediaType == %i", account, PHAssetMediaType.video.rawValue)
  1541. }
  1542. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1543. let idsAsset = results.map { $0.idAsset }
  1544. return Array(idsAsset)
  1545. }
  1546. @objc func getPhotoLibrary(predicate: NSPredicate) -> [tablePhotoLibrary] {
  1547. let realm = try! Realm()
  1548. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1549. return Array(results.map { tablePhotoLibrary.init(value:$0) })
  1550. }
  1551. //MARK: -
  1552. //MARK: Table Share
  1553. @objc func addShareLink(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String]? {
  1554. let realm = try! Realm()
  1555. realm.beginWrite()
  1556. // Verify if exists
  1557. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl).first
  1558. if result != nil {
  1559. result?.shareLink = share
  1560. } else {
  1561. // Add new
  1562. let addObject = tableShare()
  1563. addObject.account = account
  1564. addObject.fileName = fileName
  1565. addObject.serverUrl = serverUrl
  1566. addObject.shareLink = share
  1567. realm.add(addObject)
  1568. }
  1569. do {
  1570. try realm.commitWrite()
  1571. } catch let error {
  1572. print("[LOG] Could not write to database: ", error)
  1573. return nil
  1574. }
  1575. return ["\(serverUrl)\(fileName)" : share]
  1576. }
  1577. @objc func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String]? {
  1578. let realm = try! Realm()
  1579. realm.beginWrite()
  1580. // Verify if exists
  1581. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl).first
  1582. if result != nil {
  1583. result?.shareUserAndGroup = share
  1584. } else {
  1585. // Add new
  1586. let addObject = tableShare()
  1587. addObject.account = account
  1588. addObject.fileName = fileName
  1589. addObject.serverUrl = serverUrl
  1590. addObject.shareUserAndGroup = share
  1591. realm.add(addObject)
  1592. }
  1593. do {
  1594. try realm.commitWrite()
  1595. } catch let error {
  1596. print("[LOG] Could not write to database: ", error)
  1597. return nil
  1598. }
  1599. return ["\(serverUrl)\(fileName)" : share]
  1600. }
  1601. @objc func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: [String:String], sharesUserAndGroup: [String:String], account: String) -> [Any]? {
  1602. var sharesLink = sharesLink
  1603. var sharesUserAndGroup = sharesUserAndGroup
  1604. let realm = try! Realm()
  1605. realm.beginWrite()
  1606. let results = realm.objects(tableShare.self).filter("account = %@ AND (shareLink CONTAINS %@ OR shareUserAndGroup CONTAINS %@)", account, share, share)
  1607. if (results.count > 0) {
  1608. let result = results[0]
  1609. if (result.shareLink.contains(share)) {
  1610. result.shareLink = ""
  1611. }
  1612. if (result.shareUserAndGroup.contains(share)) {
  1613. var shares : [String] = result.shareUserAndGroup.components(separatedBy: ",")
  1614. if let index = shares.index(of:share) {
  1615. shares.remove(at: index)
  1616. }
  1617. result.shareUserAndGroup = shares.joined(separator: ",")
  1618. }
  1619. if (result.shareLink.count > 0) {
  1620. sharesLink.updateValue(result.shareLink, forKey:"\(serverUrl)\(fileName)")
  1621. } else {
  1622. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  1623. }
  1624. if (result.shareUserAndGroup.count > 0) {
  1625. sharesUserAndGroup.updateValue(result.shareUserAndGroup, forKey:"\(serverUrl)\(fileName)")
  1626. } else {
  1627. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  1628. }
  1629. if (result.shareLink.count == 0 && result.shareUserAndGroup.count == 0) {
  1630. realm.delete(result)
  1631. }
  1632. }
  1633. do {
  1634. try realm.commitWrite()
  1635. } catch let error {
  1636. print("[LOG] Could not write to database: ", error)
  1637. return nil
  1638. }
  1639. return [sharesLink, sharesUserAndGroup]
  1640. }
  1641. @objc func removeShareActiveAccount(account: String) {
  1642. let realm = try! Realm()
  1643. do {
  1644. try realm.write {
  1645. let results = realm.objects(tableShare.self).filter("account = %@", account)
  1646. realm.delete(results)
  1647. }
  1648. } catch let error {
  1649. print("[LOG] Could not write to database: ", error)
  1650. }
  1651. }
  1652. @objc func updateShare(_ items: [String:OCSharedDto], activeUrl: String, account: String) -> [Any]? {
  1653. var sharesLink = [String:String]()
  1654. var sharesUserAndGroup = [String:String]()
  1655. self.removeShareActiveAccount(account: account)
  1656. var itemsLink = [OCSharedDto]()
  1657. var itemsUsersAndGroups = [OCSharedDto]()
  1658. for (_, itemOCSharedDto) in items {
  1659. if (itemOCSharedDto.shareType == Int(shareTypeLink.rawValue)) {
  1660. itemsLink.append(itemOCSharedDto)
  1661. }
  1662. if (itemOCSharedDto.shareWith.count > 0 && (itemOCSharedDto.shareType == Int(shareTypeUser.rawValue) || itemOCSharedDto.shareType == Int(shareTypeGroup.rawValue) || itemOCSharedDto.shareType == Int(shareTypeRemote.rawValue) )) {
  1663. itemsUsersAndGroups.append(itemOCSharedDto)
  1664. }
  1665. }
  1666. // Manage sharesLink
  1667. for itemOCSharedDto in itemsLink {
  1668. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(itemOCSharedDto.path!)"
  1669. let fileName = NSString(string: fullPath).lastPathComponent
  1670. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.count - fileName.count - 1))
  1671. if serverUrl.hasSuffix("/") {
  1672. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.count - 1))
  1673. }
  1674. if itemOCSharedDto.idRemoteShared > 0 {
  1675. let sharesLinkReturn = self.addShareLink("\(itemOCSharedDto.idRemoteShared)", fileName: fileName, serverUrl: serverUrl, account: account)
  1676. if sharesLinkReturn != nil {
  1677. for (key,value) in sharesLinkReturn! {
  1678. sharesLink.updateValue(value, forKey:key)
  1679. }
  1680. }
  1681. }
  1682. }
  1683. // Manage sharesUserAndGroup
  1684. var paths = [String:[String]]()
  1685. for itemOCSharedDto in itemsUsersAndGroups {
  1686. if paths[itemOCSharedDto.path] != nil {
  1687. var share : [String] = paths[itemOCSharedDto.path]!
  1688. share.append("\(itemOCSharedDto.idRemoteShared)")
  1689. paths[itemOCSharedDto.path] = share
  1690. } else {
  1691. paths[itemOCSharedDto.path] = ["\(itemOCSharedDto.idRemoteShared)"]
  1692. }
  1693. }
  1694. for (path, idsRemoteSharedArray) in paths {
  1695. let idsRemoteShared = idsRemoteSharedArray.joined(separator: ",")
  1696. print("[LOG] share \(String(describing: idsRemoteShared))")
  1697. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(path)"
  1698. let fileName = NSString(string: fullPath).lastPathComponent
  1699. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.count - fileName.count - 1))
  1700. if serverUrl.hasSuffix("/") {
  1701. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.count - 1))
  1702. }
  1703. let sharesUserAndGroupReturn = self.addShareUserAndGroup(idsRemoteShared, fileName: fileName, serverUrl: serverUrl, account: account)
  1704. if sharesUserAndGroupReturn != nil {
  1705. for (key,value) in sharesUserAndGroupReturn! {
  1706. sharesUserAndGroup.updateValue(value, forKey:key)
  1707. }
  1708. }
  1709. }
  1710. return [sharesLink, sharesUserAndGroup]
  1711. }
  1712. @objc func getShares(account: String) -> [Any]? {
  1713. var sharesLink = [String:String]()
  1714. var sharesUserAndGroup = [String:String]()
  1715. let realm = try! Realm()
  1716. let results = realm.objects(tableShare.self).filter("account = %@", account)
  1717. for resultShare in results {
  1718. if (resultShare.shareLink.count > 0) {
  1719. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1720. }
  1721. if (resultShare.shareUserAndGroup.count > 0) {
  1722. sharesUserAndGroup = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1723. }
  1724. }
  1725. return [sharesLink, sharesUserAndGroup]
  1726. }
  1727. @objc func getTableShares(account: String) -> [tableShare]? {
  1728. let realm = try! Realm()
  1729. realm.refresh()
  1730. let results = realm.objects(tableShare.self).filter("account = %@", account).sorted(byKeyPath: "fileName", ascending: true)
  1731. return Array(results)
  1732. }
  1733. //MARK: -
  1734. //MARK: Table Tag
  1735. @objc func addTag(_ fileID: String ,tagIOS: Data?, account: String) {
  1736. let realm = try! Realm()
  1737. do {
  1738. try realm.write {
  1739. // Add new
  1740. let addObject = tableTag()
  1741. addObject.account = account
  1742. addObject.fileID = fileID
  1743. addObject.tagIOS = tagIOS
  1744. realm.add(addObject, update: true)
  1745. }
  1746. } catch let error {
  1747. print("[LOG] Could not write to database: ", error)
  1748. }
  1749. }
  1750. @objc func deleteTag(_ fileID: String) {
  1751. let realm = try! Realm()
  1752. realm.beginWrite()
  1753. guard let result = realm.objects(tableTag.self).filter("fileID == %@", fileID).first else {
  1754. realm.cancelWrite()
  1755. return
  1756. }
  1757. realm.delete(result)
  1758. do {
  1759. try realm.commitWrite()
  1760. } catch let error {
  1761. print("[LOG] Could not write to database: ", error)
  1762. }
  1763. }
  1764. @objc func getTags(predicate: NSPredicate) -> [tableTag] {
  1765. let realm = try! Realm()
  1766. realm.refresh()
  1767. let results = realm.objects(tableTag.self).filter(predicate)
  1768. return Array(results.map { tableTag.init(value:$0) })
  1769. }
  1770. @objc func getTag(predicate: NSPredicate) -> tableTag? {
  1771. let realm = try! Realm()
  1772. realm.refresh()
  1773. guard let result = realm.objects(tableTag.self).filter(predicate).first else {
  1774. return nil
  1775. }
  1776. return tableTag.init(value: result)
  1777. }
  1778. //MARK: -
  1779. //MARK: Table Trash
  1780. @objc func addTrashs(_ trashs: [tableTrash]) {
  1781. let realm = try! Realm()
  1782. do {
  1783. try realm.write {
  1784. for trash in trashs {
  1785. realm.add(trash, update: true)
  1786. }
  1787. }
  1788. } catch let error {
  1789. print("[LOG] Could not write to database: ", error)
  1790. return
  1791. }
  1792. }
  1793. @objc func deleteTrash(filePath: String?, account: String) {
  1794. let realm = try! Realm()
  1795. var predicate = NSPredicate()
  1796. realm.beginWrite()
  1797. if filePath == nil {
  1798. predicate = NSPredicate(format: "account == %@", account)
  1799. } else {
  1800. predicate = NSPredicate(format: "account = %@ AND filePath = %@", account, filePath!)
  1801. }
  1802. let results = realm.objects(tableTrash.self).filter(predicate)
  1803. realm.delete(results)
  1804. do {
  1805. try realm.commitWrite()
  1806. } catch let error {
  1807. print("[LOG] Could not write to database: ", error)
  1808. }
  1809. }
  1810. @objc func deleteTrash(fileID: String?, account: String) {
  1811. let realm = try! Realm()
  1812. var predicate = NSPredicate()
  1813. realm.beginWrite()
  1814. if fileID == nil {
  1815. predicate = NSPredicate(format: "account == %@", account)
  1816. } else {
  1817. predicate = NSPredicate(format: "account = %@ AND fileID = %@", account, fileID!)
  1818. }
  1819. let result = realm.objects(tableTrash.self).filter(predicate)
  1820. realm.delete(result)
  1821. do {
  1822. try realm.commitWrite()
  1823. } catch let error {
  1824. print("[LOG] Could not write to database: ", error)
  1825. }
  1826. }
  1827. @objc func getTrash(filePath: String, sorted: String, ascending: Bool, account: String) -> [tableTrash]? {
  1828. let realm = try! Realm()
  1829. realm.refresh()
  1830. let results = realm.objects(tableTrash.self).filter("account = %@ AND filePath = %@", account, filePath).sorted(byKeyPath: sorted, ascending: ascending)
  1831. return Array(results.map { tableTrash.init(value:$0) })
  1832. }
  1833. @objc func getTrashItem(fileID: String, account: String) -> tableTrash? {
  1834. let realm = try! Realm()
  1835. realm.refresh()
  1836. guard let result = realm.objects(tableTrash.self).filter("account = %@ AND fileID = %@", account, fileID).first else {
  1837. return nil
  1838. }
  1839. return tableTrash.init(value: result)
  1840. }
  1841. //MARK: -
  1842. }