NCManageDatabase.swift 79 KB

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