NCManageDatabase.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. //
  2. // NCManageDatabase.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/05/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. import RealmSwift
  9. class NCManageDatabase: NSObject {
  10. static let sharedInstance: NCManageDatabase = {
  11. let instance = NCManageDatabase()
  12. return instance
  13. }()
  14. override init() {
  15. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: k_capabilitiesGroups)
  16. var config = Realm.Configuration()
  17. config.fileURL = dirGroup?.appendingPathComponent("\(appDatabaseNextcloud)/\(k_databaseDefault)")
  18. Realm.Configuration.defaultConfiguration = config
  19. }
  20. //MARK: -
  21. //MARK: Utility Database
  22. func clearTable(_ table : Object.Type, account: String?) {
  23. let results : Results<Object>
  24. let realm = try! Realm()
  25. if (account != nil) {
  26. results = realm.objects(table).filter("account = '\(account!)'")
  27. } else {
  28. results = realm.objects(table)
  29. }
  30. try! realm.write {
  31. realm.delete(results)
  32. }
  33. }
  34. func removeDB() {
  35. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  36. let realmURLs = [
  37. realmURL,
  38. realmURL.appendingPathExtension("lock"),
  39. realmURL.appendingPathExtension("note"),
  40. realmURL.appendingPathExtension("management")
  41. ]
  42. for URL in realmURLs {
  43. do {
  44. try FileManager.default.removeItem(at: URL)
  45. } catch {
  46. // handle error
  47. }
  48. }
  49. }
  50. //MARK: -
  51. //MARK: Table Activity
  52. func addActivityServer(_ listOfActivity: [OCActivity], account: String) {
  53. let realm = try! Realm()
  54. try! realm.write {
  55. for activity in listOfActivity {
  56. // Verify
  57. let results = realm.objects(tableActivity.self).filter("idActivity = \(activity.idActivity)")
  58. if (results.count > 0) {
  59. continue
  60. }
  61. // Add new Activity
  62. let addActivity = tableActivity()
  63. addActivity.account = account
  64. addActivity.date = activity.date
  65. addActivity.idActivity = Double(activity.idActivity)
  66. addActivity.link = activity.link
  67. addActivity.note = activity.subject
  68. addActivity.type = k_activityTypeInfo
  69. realm.add(addActivity)
  70. }
  71. }
  72. }
  73. func addActivityClient(_ file: String, fileID: String, action: String, selector: String, note: String, type: String, verbose: Bool, account: String?, activeUrl: String?) {
  74. var noteReplacing : String = ""
  75. if (activeUrl != nil) {
  76. noteReplacing = note.replacingOccurrences(of: "\(activeUrl!)\(webDAV)", with: "")
  77. }
  78. noteReplacing = note.replacingOccurrences(of: "\(k_domain_session_queue).", with: "")
  79. let realm = try! Realm()
  80. try! realm.write {
  81. // Add new Activity
  82. let addActivity = tableActivity()
  83. if (account != nil) {
  84. addActivity.account = account!
  85. }
  86. addActivity.action = action
  87. addActivity.file = file
  88. addActivity.fileID = fileID
  89. addActivity.note = noteReplacing
  90. addActivity.selector = selector
  91. addActivity.type = type
  92. addActivity.verbose = verbose
  93. realm.add(addActivity)
  94. }
  95. }
  96. func getAllActivityWithPredicate(_ predicate: NSPredicate) -> [tableActivity] {
  97. let realm = try! Realm()
  98. let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  99. return Array(results)
  100. }
  101. //MARK: -
  102. //MARK: Table Automatic Upload
  103. func addAutomaticUpload(_ metadataNet: CCMetadataNet, account: String) -> Bool {
  104. let realm = try! Realm()
  105. // Verify if exists
  106. let results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)' AND assetLocalIdentifier = '\(metadataNet.assetLocalIdentifier)'")
  107. if (results.count > 0) {
  108. return false
  109. }
  110. try! realm.write {
  111. // Add new AutomaticUpload
  112. let addAutomaticUpload = tableAutomaticUpload()
  113. addAutomaticUpload.account = account
  114. addAutomaticUpload.assetLocalIdentifier = metadataNet.assetLocalIdentifier
  115. addAutomaticUpload.fileName = metadataNet.fileName
  116. addAutomaticUpload.selector = metadataNet.selector
  117. if (metadataNet.selectorPost != nil) {
  118. addAutomaticUpload.selectorPost = metadataNet.selectorPost
  119. }
  120. addAutomaticUpload.serverUrl = metadataNet.serverUrl
  121. addAutomaticUpload.session = metadataNet.session
  122. addAutomaticUpload.priority = metadataNet.priority
  123. realm.add(addAutomaticUpload)
  124. }
  125. return true
  126. }
  127. func getAutomaticUploadForAccount(_ account: String, selector: String) -> CCMetadataNet? {
  128. let realm = try! Realm()
  129. // Verify if exists
  130. let results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)' AND selector = '\(selector)' AND (lock == false)")
  131. if (results.count == 0) {
  132. return nil
  133. }
  134. let metadataNet = CCMetadataNet()
  135. metadataNet.action = actionUploadAsset
  136. metadataNet.assetLocalIdentifier = results[0].assetLocalIdentifier
  137. metadataNet.fileName = results[0].fileName
  138. metadataNet.priority = results[0].priority
  139. metadataNet.selector = results[0].selector
  140. metadataNet.selectorPost = results[0].selectorPost
  141. metadataNet.serverUrl = results[0].serverUrl
  142. metadataNet.session = results[0].session
  143. metadataNet.taskStatus = Int(k_taskStatusResume)
  144. // Lock True
  145. try! realm.write {
  146. results[0].lock = true
  147. }
  148. return metadataNet
  149. }
  150. func getAllLockAutomaticUploadForAccount(_ account: String) -> [tableAutomaticUpload] {
  151. let realm = try! Realm()
  152. let results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)' AND (lock = true)")
  153. return Array(results)
  154. }
  155. func unlockAutomaticUploadForAccount(_ account: String, assetLocalIdentifier: String) {
  156. let realm = try! Realm()
  157. let results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)' AND (assetLocalIdentifier = '\(assetLocalIdentifier)')")
  158. if (results.count > 0) {
  159. // Lock False
  160. try! realm.write {
  161. results[0].lock = false
  162. }
  163. }
  164. }
  165. func deleteAutomaticUploadForAccount(_ account: String, assetLocalIdentifier: String) {
  166. let realm = try! Realm()
  167. let results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)' AND (assetLocalIdentifier = '\(assetLocalIdentifier)')")
  168. if (results.count > 0) {
  169. try! realm.write {
  170. realm.delete(results)
  171. }
  172. }
  173. }
  174. func countAutomaticUploadForAccount(_ account: String, selector: String?) -> Int {
  175. let realm = try! Realm()
  176. let results : Results<tableAutomaticUpload>
  177. if (selector == nil) {
  178. results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)'")
  179. } else {
  180. results = realm.objects(tableAutomaticUpload.self).filter("account = '\(account)' AND (selector = '\(selector!)')")
  181. }
  182. return results.count
  183. }
  184. //MARK: -
  185. //MARK: Table Capabilities
  186. func addCapabilities(_ capabilities: OCCapabilities, account: String) {
  187. let realm = try! Realm()
  188. let results = realm.objects(tableCapabilities.self).filter("account = '\(account)'")
  189. try! realm.write {
  190. var resultCapabilities = tableCapabilities()
  191. if (results.count > 0) {
  192. resultCapabilities = results[0]
  193. }
  194. resultCapabilities.account = account
  195. resultCapabilities.themingBackground = capabilities.themingBackground
  196. resultCapabilities.themingColor = capabilities.themingColor
  197. resultCapabilities.themingLogo = capabilities.themingLogo
  198. resultCapabilities.themingName = capabilities.themingName
  199. resultCapabilities.themingSlogan = capabilities.themingSlogan
  200. resultCapabilities.themingUrl = capabilities.themingUrl
  201. resultCapabilities.versionMajor = capabilities.versionMajor
  202. resultCapabilities.versionMinor = capabilities.versionMinor
  203. resultCapabilities.versionMicro = capabilities.versionMicro
  204. resultCapabilities.versionString = capabilities.versionString
  205. if (results.count == 0) {
  206. realm.add(resultCapabilities)
  207. }
  208. }
  209. }
  210. func getCapabilitesForAccount(_ account: String) -> tableCapabilities? {
  211. let realm = try! Realm()
  212. let results = realm.objects(tableCapabilities.self).filter("account = '\(account)'")
  213. if (results.count > 0) {
  214. return results[0]
  215. } else {
  216. return nil
  217. }
  218. }
  219. func getServerVersionAccount(_ account: String) -> Int {
  220. let realm = try! Realm()
  221. let results = realm.objects(tableCapabilities.self).filter("account = '\(account)'")
  222. if (results.count > 0) {
  223. return results[0].versionMajor
  224. } else {
  225. return 0
  226. }
  227. }
  228. //MARK: -
  229. //MARK: Table Certificates
  230. func addCertificates(_ certificateLocation: String) {
  231. let realm = try! Realm()
  232. try! realm.write {
  233. let addCertificates = tableCertificates()
  234. addCertificates.certificateLocation = certificateLocation
  235. realm.add(addCertificates)
  236. }
  237. }
  238. func getAllCertificatesLocation(_ localCertificatesFolder: String) -> [String] {
  239. let realm = try! Realm()
  240. let results = realm.objects(tableCertificates.self)
  241. var arraycertificatePath = [String]()
  242. for result in results {
  243. arraycertificatePath.append("\(localCertificatesFolder)\(result.certificateLocation)")
  244. }
  245. return arraycertificatePath
  246. }
  247. //MARK: -
  248. //MARK: Table External Sites
  249. func addExternalSites(_ externalSites: OCExternalSites, account: String) {
  250. let realm = try! Realm()
  251. try! realm.write {
  252. let addExternalSite = tableExternalSites()
  253. addExternalSite.account = account
  254. addExternalSite.idExternalSite = externalSites.idExternalSite
  255. addExternalSite.icon = externalSites.icon
  256. addExternalSite.lang = externalSites.lang
  257. addExternalSite.name = externalSites.name
  258. addExternalSite.url = externalSites.url
  259. addExternalSite.type = externalSites.type
  260. realm.add(addExternalSite)
  261. }
  262. }
  263. func deleteAllExternalSitesForAccount(_ account: String) {
  264. let realm = try! Realm()
  265. let results = realm.objects(tableExternalSites.self).filter("account = '\(account)'")
  266. try! realm.write {
  267. realm.delete(results)
  268. }
  269. }
  270. func getAllExternalSitesWithPredicate(_ predicate: NSPredicate) -> [tableExternalSites] {
  271. let realm = try! Realm()
  272. let results = realm.objects(tableExternalSites.self).filter(predicate).sorted(byKeyPath: "idExternalSite", ascending: true)
  273. return Array(results)
  274. }
  275. //MARK: -
  276. //MARK: Table GPS
  277. func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  278. let realm = try! Realm()
  279. // Verify if exists
  280. let results = realm.objects(tableGPS.self).filter("latitude = '\(latitude)' AND longitude = '\(longitude)'")
  281. if (results.count > 0) {
  282. return
  283. }
  284. try! realm.write {
  285. // Add new GPS
  286. let addGPS = tableGPS()
  287. addGPS.location = location
  288. addGPS.placemarkAdministrativeArea = placemarkAdministrativeArea
  289. addGPS.placemarkCountry = placemarkCountry
  290. addGPS.placemarkLocality = placemarkLocality
  291. addGPS.placemarkPostalCode = placemarkPostalCode
  292. addGPS.placemarkThoroughfare = placemarkThoroughfare
  293. addGPS.latitude = latitude
  294. addGPS.longitude = longitude
  295. realm.add(addGPS)
  296. }
  297. }
  298. func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  299. let realm = try! Realm()
  300. let results = realm.objects(tableGPS.self).filter("latitude = '\(latitude)' AND longitude = '\(longitude)'")
  301. if (results.count == 0) {
  302. return nil
  303. } else {
  304. return results[0].location
  305. }
  306. }
  307. //MARK: -
  308. //MARK: Table Share
  309. func addShareLink(_ share: String, fileName: String, serverUrl: String, sharesLink: inout [String:String], account: String) {
  310. let realm = try! Realm()
  311. // Verify if exists
  312. let results = realm.objects(tableShare.self).filter("account = '\(account)' AND fileName = '\(fileName)' AND serverUrl = '\(serverUrl)'")
  313. if (results.count > 0) {
  314. try! realm.write {
  315. results[0].shareLink = share;
  316. }
  317. } else {
  318. // Add new record
  319. try! realm.write {
  320. let addShare = tableShare()
  321. addShare.account = account
  322. addShare.fileName = fileName
  323. addShare.serverUrl = serverUrl
  324. addShare.shareLink = share
  325. realm.add(addShare)
  326. }
  327. }
  328. sharesLink = [share: "\(serverUrl)\(fileName)"]
  329. }
  330. func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String, sharesUserAndGroup: inout [String:String], account: String) {
  331. let realm = try! Realm()
  332. // Verify if exists
  333. let results = realm.objects(tableShare.self).filter("account = '\(account)' AND fileName = '\(fileName)' AND serverUrl = '\(serverUrl)'")
  334. if (results.count > 0) {
  335. try! realm.write {
  336. results[0].shareUserAndGroup = share;
  337. }
  338. } else {
  339. // Add new record
  340. try! realm.write {
  341. let addShare = tableShare()
  342. addShare.account = account
  343. addShare.fileName = fileName
  344. addShare.serverUrl = serverUrl
  345. addShare.shareLink = share
  346. realm.add(addShare)
  347. }
  348. }
  349. sharesUserAndGroup = [share: "\(serverUrl)\(fileName)"]
  350. }
  351. func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: inout [String:String], sharesUserAndGroup: inout [String:String], account: String) {
  352. let realm = try! Realm()
  353. let results = realm.objects(tableShare.self).filter("account = '\(account)' AND (shareLink CONTAINS '\(share)' OR shareUserAndGroup CONTAINS '\(share))'")
  354. if (results.count > 0) {
  355. try! realm.write {
  356. if (results[0].shareLink.contains(share)) {
  357. results[0].shareLink = ""
  358. }
  359. if (results[0].shareUserAndGroup.contains(share)) {
  360. var shares : [String] = results[0].shareUserAndGroup.components(separatedBy: ",")
  361. if let index = shares.index(of:share) {
  362. shares.remove(at: index)
  363. }
  364. results[0].shareUserAndGroup = shares.joined(separator: ",")
  365. }
  366. if (results[0].shareLink.characters.count == 0 && results[0].shareUserAndGroup.characters.count == 0) {
  367. realm.delete(results[0])
  368. }
  369. }
  370. if (results[0].shareLink.characters.count > 0) {
  371. sharesLink = [results[0].shareLink: "\(serverUrl)\(fileName)"]
  372. } else {
  373. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  374. }
  375. if (results[0].shareUserAndGroup.characters.count > 0) {
  376. sharesUserAndGroup = [results[0].shareUserAndGroup: "\(serverUrl)\(fileName)"]
  377. } else {
  378. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  379. }
  380. }
  381. }
  382. func removeAllShareActiveAccount(_ account: String, sharesLink: inout [String:String], sharesUserAndGroup: inout [String:String]) {
  383. let realm = try! Realm()
  384. let results = realm.objects(tableShare.self).filter("account = '\(account)'")
  385. try! realm.write {
  386. realm.delete(results)
  387. }
  388. sharesLink.removeAll()
  389. sharesUserAndGroup.removeAll()
  390. }
  391. func updateShare(_ items: inout [String:OCSharedDto], sharesLink: inout [String:String], sharesUserAndGroup: inout [String:String] , account: String, activeUrl: String) {
  392. self.removeAllShareActiveAccount(account, sharesLink: &sharesLink, sharesUserAndGroup: &sharesUserAndGroup)
  393. var itemsLink = [OCSharedDto]()
  394. var itemsUsersAndGroups = [OCSharedDto]()
  395. for (idRemoteShared,_) in items {
  396. let item = items[idRemoteShared]!
  397. if (item.shareType == Int(shareTypeLink.rawValue)) {
  398. itemsLink.append(item)
  399. }
  400. if (item.shareWith.characters.count > 0 && (item.shareType == Int(shareTypeUser.rawValue) || item.shareType == Int(shareTypeGroup.rawValue) || item.shareType == Int(shareTypeRemote.rawValue) )) {
  401. itemsUsersAndGroups.append(item)
  402. }
  403. }
  404. // Link
  405. for item in itemsLink {
  406. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(item.path)"
  407. let fileName = NSString(string: fullPath).lastPathComponent
  408. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - (fullPath.characters.count-1)))
  409. if serverUrl.hasSuffix("/") {
  410. serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count-1))
  411. }
  412. if item.idRemoteShared > 0 {
  413. self.addShareLink("\(item.idRemoteShared)", fileName: fileName, serverUrl: serverUrl, sharesLink: &sharesLink, account: account)
  414. }
  415. }
  416. // Create dictionary
  417. var paths = [String:[String]]() //Key, value
  418. for item in itemsUsersAndGroups {
  419. if paths[item.path] != nil {
  420. var share : [String] = paths[item.path]!
  421. share.append("\(item.idRemoteShared)")
  422. paths[item.path] = share
  423. } else {
  424. paths[item.path] = ["\(item.idRemoteShared)"]
  425. }
  426. }
  427. // Write on DB
  428. }
  429. func populateSharesVariable(_ account: String, sharesLink: inout [String:String], sharesUserAndGroup: inout [String:String]) {
  430. sharesLink.removeAll()
  431. sharesUserAndGroup.removeAll()
  432. let realm = try! Realm()
  433. let results = realm.objects(tableShare.self).filter("account = '\(account)'")
  434. for resultShare in results {
  435. if (resultShare.shareLink.characters.count > 0) {
  436. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  437. }
  438. if (resultShare.shareUserAndGroup.characters.count > 0) {
  439. sharesLink = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  440. }
  441. }
  442. }
  443. //MARK: -
  444. }