NCManageDatabase.swift 80 KB

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