NCManageDatabase.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. //
  2. // NCManageDatabase.swift
  3. // Crypto Cloud Technology Nextcloud
  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. static let sharedInstance: NCManageDatabase = {
  26. let instance = NCManageDatabase()
  27. return instance
  28. }()
  29. override init() {
  30. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  31. var config = Realm.Configuration()
  32. config.fileURL = dirGroup?.appendingPathComponent("\(appDatabaseNextcloud)/\(k_databaseDefault)")
  33. Realm.Configuration.defaultConfiguration = config
  34. }
  35. //MARK: -
  36. //MARK: Utility Database
  37. func clearTable(_ table : Object.Type, account: String?) {
  38. let results : Results<Object>
  39. let realm = try! Realm()
  40. if (account != nil) {
  41. results = realm.objects(table).filter("account = %@", account!)
  42. } else {
  43. results = realm.objects(table)
  44. }
  45. try! realm.write {
  46. realm.delete(results)
  47. }
  48. }
  49. func removeDB() {
  50. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  51. let realmURLs = [
  52. realmURL,
  53. realmURL.appendingPathExtension("lock"),
  54. realmURL.appendingPathExtension("note"),
  55. realmURL.appendingPathExtension("management")
  56. ]
  57. for URL in realmURLs {
  58. do {
  59. try FileManager.default.removeItem(at: URL)
  60. } catch {
  61. // handle error
  62. }
  63. }
  64. }
  65. //MARK: -
  66. //MARK: Table Account
  67. func addAccount(_ account: String, url: String, user: String, password: String) {
  68. let realm = try! Realm()
  69. try! realm.write {
  70. let addAccount = tableAccount()
  71. addAccount.account = account
  72. // Brand
  73. if NCBrandOptions.sharedInstance.use_default_automatic_upload {
  74. addAccount.cameraUpload = true
  75. addAccount.cameraUploadPhoto = true
  76. addAccount.cameraUploadVideo = true
  77. addAccount.cameraUploadWWAnVideo = true
  78. }
  79. addAccount.password = password
  80. addAccount.url = url
  81. addAccount.user = user
  82. }
  83. }
  84. func setAccountPassword(_ account: String, password: String) {
  85. let realm = try! Realm()
  86. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  87. if (results.count > 0) {
  88. try! realm.write {
  89. results[0].password = password
  90. }
  91. }
  92. }
  93. func deleteAccount(_ account: String) {
  94. let realm = try! Realm()
  95. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  96. if (results.count > 0) {
  97. try! realm.write {
  98. realm.delete(results)
  99. }
  100. }
  101. }
  102. func getAccountActive() -> tableAccount? {
  103. let realm = try! Realm()
  104. let results = realm.objects(tableAccount.self).filter("active = true")
  105. if (results.count > 0) {
  106. return results[0]
  107. } else {
  108. return nil
  109. }
  110. }
  111. func getAccounts(_ account: String?) -> [tableAccount] {
  112. let realm = try! Realm()
  113. let results : Results<tableAccount>
  114. if account == nil {
  115. results = realm.objects(tableAccount.self).sorted(byKeyPath: "account", ascending: true)
  116. } else {
  117. results = realm.objects(tableAccount.self).filter("account = %@", account!).sorted(byKeyPath: "account", ascending: true)
  118. }
  119. return Array(results)
  120. }
  121. // getCameraUploadFolderNameActiveAccount + getCameraUploadFolderPathActiveAccount
  122. func getAccountsCameraUploadFolderName(_ account: String, activeUrl : String?) -> String {
  123. let realm = try! Realm()
  124. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  125. if (results.count > 0) {
  126. if results[0].cameraUploadFolderName.characters.count > 0 {
  127. if activeUrl == nil {
  128. return results[0].cameraUploadFolderName
  129. } else {
  130. return results[0].cameraUploadFolderPath
  131. }
  132. } else {
  133. if activeUrl == nil {
  134. return k_folderDefaultCameraUpload
  135. } else {
  136. return CCUtility.getHomeServerUrlActiveUrl(activeUrl!)
  137. }
  138. }
  139. }
  140. return ""
  141. }
  142. // getCameraUploadFolderNamePathActiveAccount
  143. func getAccountsCameraUploadFolderPath(_ account: String, activeUrl : String) -> String {
  144. let cameraFolderName = self.getAccountsCameraUploadFolderName(account, activeUrl: nil)
  145. let cameraFolderPath = self.getAccountsCameraUploadFolderName(account, activeUrl: activeUrl)
  146. let folderPhotos = CCUtility.stringAppendServerUrl(cameraFolderPath, addFileName: cameraFolderName)!
  147. return folderPhotos
  148. }
  149. func setAccountActive(_ account: String) -> tableAccount {
  150. let realm = try! Realm()
  151. var activeAccount = tableAccount()
  152. let results = realm.objects(tableAccount.self)
  153. try! realm.write {
  154. for result in results {
  155. if result.account == account {
  156. result.active = true
  157. activeAccount = result
  158. } else {
  159. result.active = false
  160. }
  161. }
  162. }
  163. return activeAccount
  164. }
  165. func setAccountCameraStateFiled(_ account: String, state: Bool, field: String) {
  166. let realm = try! Realm()
  167. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  168. if (results.count > 0) {
  169. try! realm.write {
  170. switch field {
  171. case "cameraUpload":
  172. results[0].cameraUpload = state
  173. case "cameraUploadBackground":
  174. results[0].cameraUploadBackground = state
  175. case "cameraUploadCreateSubfolder":
  176. results[0].cameraUploadCreateSubfolder = state
  177. case "cameraUploadFull":
  178. results[0].cameraUploadFull = state
  179. case "cameraUploadPhoto":
  180. results[0].cameraUploadPhoto = state
  181. case "cameraUploadVideo":
  182. results[0].cameraUploadVideo = state
  183. case "cameraUploadWWAnPhoto":
  184. results[0].cameraUploadWWAnPhoto = state
  185. case "cameraUploadWWAnVideo":
  186. results[0].cameraUploadWWAnVideo = state
  187. default:
  188. print("No founfd field")
  189. }
  190. }
  191. }
  192. }
  193. func setAccountsCameraUploadDateAssetType(_ account: String, assetMediaType: PHAssetMediaType, assetDate: NSDate) {
  194. let realm = try! Realm()
  195. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  196. try! realm.write {
  197. if (assetMediaType == PHAssetMediaType.image && results.count > 0) {
  198. results[0].cameraUploadDatePhoto = assetDate
  199. }
  200. if (assetMediaType == PHAssetMediaType.video && results.count > 0) {
  201. results[0].cameraUploadDateVideo = assetDate
  202. }
  203. }
  204. }
  205. func setAccountsCameraUploadFolderName(_ account: String, folderName: String?) {
  206. let realm = try! Realm()
  207. var folderName : String? = folderName
  208. if folderName == nil {
  209. folderName = self.getAccountsCameraUploadFolderName(account, activeUrl: nil)
  210. }
  211. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  212. if (results.count > 0) {
  213. try! realm.write {
  214. results[0].cameraUploadFolderName = folderName!
  215. }
  216. }
  217. }
  218. func setAccountsCameraUploadFolderPath(_ account: String, pathName: String?, activeUrl: String) {
  219. let realm = try! Realm()
  220. var pathName : String? = pathName
  221. if pathName == nil {
  222. pathName = self.getAccountsCameraUploadFolderPath(account, activeUrl: activeUrl)
  223. }
  224. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  225. if (results.count > 0) {
  226. try! realm.write {
  227. results[0].cameraUploadFolderPath = pathName!
  228. }
  229. }
  230. }
  231. func setAccountsUserProfile(_ account: String, userProfile: OCUserProfile) {
  232. let realm = try! Realm()
  233. let results = realm.objects(tableAccount.self).filter("account = %@", account)
  234. if (results.count > 0) {
  235. try! realm.write {
  236. results[0].enabled = userProfile.enabled
  237. results[0].address = userProfile.address
  238. results[0].displayName = userProfile.displayName
  239. results[0].email = userProfile.email
  240. results[0].phone = userProfile.phone
  241. results[0].twitter = userProfile.twitter
  242. results[0].webpage = results[0].webpage
  243. results[0].quota = userProfile.quota
  244. results[0].quotaFree = userProfile.quotaFree
  245. results[0].quotaRelative = userProfile.quotaRelative
  246. results[0].quotaTotal = userProfile.quotaTotal
  247. results[0].quotaUsed = userProfile.quotaUsed
  248. }
  249. }
  250. }
  251. //MARK: -
  252. //MARK: Table Activity
  253. func getActivityWithPredicate(_ predicate: NSPredicate) -> [tableActivity] {
  254. let realm = try! Realm()
  255. let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  256. return Array(results)
  257. }
  258. func addActivityServer(_ listOfActivity: [OCActivity], account: String) {
  259. let realm = try! Realm()
  260. try! realm.write {
  261. for activity in listOfActivity {
  262. let results = realm.objects(tableActivity.self).filter("idActivity = %d", activity.idActivity)
  263. if (results.count > 0) {
  264. continue
  265. }
  266. // Add new Activity
  267. let addActivity = tableActivity()
  268. addActivity.account = account
  269. if activity.date != nil {
  270. addActivity.date = activity.date! as NSDate
  271. }
  272. addActivity.idActivity = Double(activity.idActivity)
  273. addActivity.link = activity.link
  274. addActivity.note = activity.subject
  275. addActivity.type = k_activityTypeInfo
  276. realm.add(addActivity)
  277. }
  278. }
  279. }
  280. func addActivityClient(_ file: String, fileID: String, action: String, selector: String, note: String, type: String, verbose: Bool, account: String?, activeUrl: String?) {
  281. var noteReplacing : String = ""
  282. if (activeUrl != nil) {
  283. noteReplacing = note.replacingOccurrences(of: "\(activeUrl!)\(webDAV)", with: "")
  284. }
  285. noteReplacing = note.replacingOccurrences(of: "\(k_domain_session_queue).", with: "")
  286. let realm = try! Realm()
  287. try! realm.write {
  288. // Add new Activity
  289. let addActivity = tableActivity()
  290. if (account != nil) {
  291. addActivity.account = account!
  292. }
  293. addActivity.action = action
  294. addActivity.file = file
  295. addActivity.fileID = fileID
  296. addActivity.note = noteReplacing
  297. addActivity.selector = selector
  298. addActivity.type = type
  299. addActivity.verbose = verbose
  300. realm.add(addActivity)
  301. }
  302. }
  303. //MARK: -
  304. //MARK: Table Automatic Upload
  305. func addAutomaticUpload(_ metadataNet: CCMetadataNet, account: String) -> Bool {
  306. let realm = try! Realm()
  307. let results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND assetLocalIdentifier = %@", account, metadataNet.assetLocalIdentifier)
  308. if (results.count > 0) {
  309. return false
  310. }
  311. try! realm.write {
  312. // Add new AutomaticUpload
  313. let addAutomaticUpload = tableAutomaticUpload()
  314. addAutomaticUpload.account = account
  315. addAutomaticUpload.assetLocalIdentifier = metadataNet.assetLocalIdentifier
  316. addAutomaticUpload.fileName = metadataNet.fileName
  317. addAutomaticUpload.selector = metadataNet.selector
  318. if (metadataNet.selectorPost != nil) {
  319. addAutomaticUpload.selectorPost = metadataNet.selectorPost
  320. }
  321. addAutomaticUpload.serverUrl = metadataNet.serverUrl
  322. addAutomaticUpload.session = metadataNet.session
  323. addAutomaticUpload.priority = metadataNet.priority
  324. realm.add(addAutomaticUpload)
  325. }
  326. return true
  327. }
  328. func getAutomaticUploadForAccount(_ account: String, selector: String) -> CCMetadataNet? {
  329. let realm = try! Realm()
  330. let results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND selector = %@ AND lock == false", account, selector)
  331. if (results.count == 0) {
  332. return nil
  333. }
  334. let metadataNet = CCMetadataNet()
  335. metadataNet.action = actionUploadAsset
  336. metadataNet.assetLocalIdentifier = results[0].assetLocalIdentifier
  337. metadataNet.fileName = results[0].fileName
  338. metadataNet.priority = results[0].priority
  339. metadataNet.selector = results[0].selector
  340. metadataNet.selectorPost = results[0].selectorPost
  341. metadataNet.serverUrl = results[0].serverUrl
  342. metadataNet.session = results[0].session
  343. metadataNet.taskStatus = Int(k_taskStatusResume)
  344. // Lock
  345. try! realm.write {
  346. results[0].lock = true
  347. }
  348. return metadataNet
  349. }
  350. func getLockAutomaticUploadForAccount(_ account: String) -> [tableAutomaticUpload] {
  351. let realm = try! Realm()
  352. let results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND lock = true", account)
  353. return Array(results)
  354. }
  355. func unlockAutomaticUploadForAccount(_ account: String, assetLocalIdentifier: String) {
  356. let realm = try! Realm()
  357. let results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND assetLocalIdentifier = %@", account, assetLocalIdentifier)
  358. if (results.count > 0) {
  359. // UnLock
  360. try! realm.write {
  361. results[0].lock = false
  362. }
  363. }
  364. }
  365. func deleteAutomaticUploadForAccount(_ account: String, assetLocalIdentifier: String) {
  366. let realm = try! Realm()
  367. let results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND assetLocalIdentifier = %@", account, assetLocalIdentifier)
  368. if (results.count > 0) {
  369. try! realm.write {
  370. realm.delete(results)
  371. }
  372. }
  373. }
  374. func countAutomaticUploadForAccount(_ account: String, session: String?) -> Int {
  375. let realm = try! Realm()
  376. let results : Results<tableAutomaticUpload>
  377. if (session == nil) {
  378. results = realm.objects(tableAutomaticUpload.self).filter("account = %@", account)
  379. } else {
  380. results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND session = %@", account, session!)
  381. }
  382. return results.count
  383. }
  384. //MARK: -
  385. //MARK: Table Capabilities
  386. func addCapabilities(_ capabilities: OCCapabilities, account: String) {
  387. let realm = try! Realm()
  388. let results = realm.objects(tableCapabilities.self).filter("account = %@", account)
  389. try! realm.write {
  390. var resultCapabilities = tableCapabilities()
  391. if (results.count > 0) {
  392. resultCapabilities = results[0]
  393. }
  394. resultCapabilities.account = account
  395. resultCapabilities.themingBackground = capabilities.themingBackground
  396. resultCapabilities.themingColor = capabilities.themingColor
  397. resultCapabilities.themingLogo = capabilities.themingLogo
  398. resultCapabilities.themingName = capabilities.themingName
  399. resultCapabilities.themingSlogan = capabilities.themingSlogan
  400. resultCapabilities.themingUrl = capabilities.themingUrl
  401. resultCapabilities.versionMajor = capabilities.versionMajor
  402. resultCapabilities.versionMinor = capabilities.versionMinor
  403. resultCapabilities.versionMicro = capabilities.versionMicro
  404. resultCapabilities.versionString = capabilities.versionString
  405. if (results.count == 0) {
  406. realm.add(resultCapabilities)
  407. }
  408. }
  409. }
  410. func getCapabilitesForAccount(_ account: String) -> tableCapabilities? {
  411. let realm = try! Realm()
  412. let results = realm.objects(tableCapabilities.self).filter("account = %@", account)
  413. if (results.count > 0) {
  414. return results[0]
  415. } else {
  416. return nil
  417. }
  418. }
  419. func getServerVersionAccount(_ account: String) -> Int {
  420. let realm = try! Realm()
  421. let results = realm.objects(tableCapabilities.self).filter("account = %@", account)
  422. if (results.count > 0) {
  423. return results[0].versionMajor
  424. } else {
  425. return 0
  426. }
  427. }
  428. //MARK: -
  429. //MARK: Table Certificates
  430. func addCertificates(_ certificateLocation: String) {
  431. let realm = try! Realm()
  432. try! realm.write {
  433. let addCertificates = tableCertificates()
  434. addCertificates.certificateLocation = certificateLocation
  435. realm.add(addCertificates)
  436. }
  437. }
  438. func getCertificatesLocation(_ localCertificatesFolder: String) -> [String] {
  439. let realm = try! Realm()
  440. let results = realm.objects(tableCertificates.self)
  441. var arraycertificatePath = [String]()
  442. for result in results {
  443. arraycertificatePath.append("\(localCertificatesFolder)\(result.certificateLocation)")
  444. }
  445. return arraycertificatePath
  446. }
  447. //MARK: -
  448. //MARK: Table External Sites
  449. func addExternalSites(_ externalSites: OCExternalSites, account: String) {
  450. let realm = try! Realm()
  451. try! realm.write {
  452. let addExternalSite = tableExternalSites()
  453. addExternalSite.account = account
  454. addExternalSite.idExternalSite = externalSites.idExternalSite
  455. addExternalSite.icon = externalSites.icon
  456. addExternalSite.lang = externalSites.lang
  457. addExternalSite.name = externalSites.name
  458. addExternalSite.url = externalSites.url
  459. addExternalSite.type = externalSites.type
  460. realm.add(addExternalSite)
  461. }
  462. }
  463. func deleteExternalSitesForAccount(_ account: String) {
  464. let realm = try! Realm()
  465. let results = realm.objects(tableExternalSites.self).filter("account = %@", account)
  466. try! realm.write {
  467. realm.delete(results)
  468. }
  469. }
  470. func getAllExternalSitesWithPredicate(_ predicate: NSPredicate) -> [tableExternalSites] {
  471. let realm = try! Realm()
  472. let results = realm.objects(tableExternalSites.self).filter(predicate).sorted(byKeyPath: "idExternalSite", ascending: true)
  473. return Array(results)
  474. }
  475. //MARK: -
  476. //MARK: Table GPS
  477. func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  478. let realm = try! Realm()
  479. // Verify if exists
  480. let results = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude)
  481. if (results.count > 0) {
  482. return
  483. }
  484. try! realm.write {
  485. // Add new GPS
  486. let addGPS = tableGPS()
  487. addGPS.location = location
  488. addGPS.placemarkAdministrativeArea = placemarkAdministrativeArea
  489. addGPS.placemarkCountry = placemarkCountry
  490. addGPS.placemarkLocality = placemarkLocality
  491. addGPS.placemarkPostalCode = placemarkPostalCode
  492. addGPS.placemarkThoroughfare = placemarkThoroughfare
  493. addGPS.latitude = latitude
  494. addGPS.longitude = longitude
  495. realm.add(addGPS)
  496. }
  497. }
  498. func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  499. let realm = try! Realm()
  500. let results = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude)
  501. if (results.count == 0) {
  502. return nil
  503. } else {
  504. return results[0].location
  505. }
  506. }
  507. //MARK: -
  508. //MARK: Table Share
  509. func addShareLink(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String] {
  510. let realm = try! Realm()
  511. // Verify if exists
  512. let results = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl)
  513. if (results.count > 0) {
  514. try! realm.write {
  515. results[0].shareLink = share;
  516. }
  517. } else {
  518. // Add new record
  519. try! realm.write {
  520. let addShare = tableShare()
  521. addShare.account = account
  522. addShare.fileName = fileName
  523. addShare.serverUrl = serverUrl
  524. addShare.shareLink = share
  525. realm.add(addShare)
  526. }
  527. }
  528. return ["\(serverUrl)\(fileName)" : share]
  529. }
  530. func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String] {
  531. let realm = try! Realm()
  532. // Verify if exists
  533. let results = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl)
  534. if (results.count > 0) {
  535. try! realm.write {
  536. results[0].shareUserAndGroup = share;
  537. }
  538. } else {
  539. // Add new record
  540. try! realm.write {
  541. let addShare = tableShare()
  542. addShare.account = account
  543. addShare.fileName = fileName
  544. addShare.serverUrl = serverUrl
  545. addShare.shareUserAndGroup = share
  546. realm.add(addShare)
  547. }
  548. }
  549. return ["\(serverUrl)\(fileName)" : share]
  550. }
  551. func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: [String:String], sharesUserAndGroup: [String:String], account: String) -> [Any] {
  552. var sharesLink = sharesLink
  553. var sharesUserAndGroup = sharesUserAndGroup
  554. let realm = try! Realm()
  555. let results = realm.objects(tableShare.self).filter("account = %@ AND (shareLink CONTAINS %@ OR shareUserAndGroup CONTAINS %@)", account, share, share)
  556. if (results.count > 0) {
  557. let result = results[0]
  558. realm.beginWrite()
  559. if (result.shareLink.contains(share)) {
  560. result.shareLink = ""
  561. }
  562. if (result.shareUserAndGroup.contains(share)) {
  563. var shares : [String] = result.shareUserAndGroup.components(separatedBy: ",")
  564. if let index = shares.index(of:share) {
  565. shares.remove(at: index)
  566. }
  567. result.shareUserAndGroup = shares.joined(separator: ",")
  568. }
  569. if (result.shareLink.characters.count > 0) {
  570. sharesLink.updateValue(result.shareLink, forKey:"\(serverUrl)\(fileName)")
  571. } else {
  572. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  573. }
  574. if (result.shareUserAndGroup.characters.count > 0) {
  575. sharesUserAndGroup.updateValue(result.shareUserAndGroup, forKey:"\(serverUrl)\(fileName)")
  576. } else {
  577. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  578. }
  579. if (result.shareLink.characters.count == 0 && result.shareUserAndGroup.characters.count == 0) {
  580. realm.delete(result)
  581. }
  582. try! realm.commitWrite()
  583. }
  584. return [sharesLink, sharesUserAndGroup]
  585. }
  586. func removeShareActiveAccount(_ account: String) {
  587. let realm = try! Realm()
  588. let results = realm.objects(tableShare.self).filter("account = %@", account)
  589. try! realm.write {
  590. realm.delete(results)
  591. }
  592. }
  593. func updateShare(_ items: [String:OCSharedDto], account: String, activeUrl: String) -> [Any] {
  594. var sharesLink = [String:String]()
  595. var sharesUserAndGroup = [String:String]()
  596. self.removeShareActiveAccount(account)
  597. var itemsLink = [OCSharedDto]()
  598. var itemsUsersAndGroups = [OCSharedDto]()
  599. for (_, itemOCSharedDto) in items {
  600. if (itemOCSharedDto.shareType == Int(shareTypeLink.rawValue)) {
  601. itemsLink.append(itemOCSharedDto)
  602. }
  603. if (itemOCSharedDto.shareWith.characters.count > 0 && (itemOCSharedDto.shareType == Int(shareTypeUser.rawValue) || itemOCSharedDto.shareType == Int(shareTypeGroup.rawValue) || itemOCSharedDto.shareType == Int(shareTypeRemote.rawValue) )) {
  604. itemsUsersAndGroups.append(itemOCSharedDto)
  605. }
  606. }
  607. // Manage sharesLink
  608. for itemOCSharedDto in itemsLink {
  609. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(itemOCSharedDto.path!)"
  610. let fileName = NSString(string: fullPath).lastPathComponent
  611. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - fileName.characters.count - 1))
  612. if serverUrl.hasSuffix("/") {
  613. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.characters.count - 1))
  614. }
  615. if itemOCSharedDto.idRemoteShared > 0 {
  616. let sharesLinkReturn = self.addShareLink("\(itemOCSharedDto.idRemoteShared)", fileName: fileName, serverUrl: serverUrl, account: account)
  617. for (key,value) in sharesLinkReturn {
  618. sharesLink.updateValue(value, forKey:key)
  619. }
  620. }
  621. }
  622. // Manage sharesUserAndGroup
  623. var paths = [String:[String]]()
  624. for itemOCSharedDto in itemsUsersAndGroups {
  625. if paths[itemOCSharedDto.path] != nil {
  626. var share : [String] = paths[itemOCSharedDto.path]!
  627. share.append("\(itemOCSharedDto.idRemoteShared)")
  628. paths[itemOCSharedDto.path] = share
  629. } else {
  630. paths[itemOCSharedDto.path] = ["\(itemOCSharedDto.idRemoteShared)"]
  631. }
  632. }
  633. for (path, idsRemoteSharedArray) in paths {
  634. let idsRemoteShared = idsRemoteSharedArray.joined(separator: ",")
  635. print("[LOG] share \(String(describing: idsRemoteShared))")
  636. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(path)"
  637. let fileName = NSString(string: fullPath).lastPathComponent
  638. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - fileName.characters.count - 1))
  639. if serverUrl.hasSuffix("/") {
  640. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.characters.count - 1))
  641. }
  642. let sharesUserAndGroupReturn = self.addShareUserAndGroup(idsRemoteShared, fileName: fileName, serverUrl: serverUrl, account: account)
  643. for (key,value) in sharesUserAndGroupReturn {
  644. sharesUserAndGroup.updateValue(value, forKey:key)
  645. }
  646. }
  647. return [sharesLink, sharesUserAndGroup]
  648. }
  649. func getSharesAccount(_ account: String) -> [Any] {
  650. var sharesLink = [String:String]()
  651. var sharesUserAndGroup = [String:String]()
  652. let realm = try! Realm()
  653. let results = realm.objects(tableShare.self).filter("account = %@", account)
  654. for resultShare in results {
  655. if (resultShare.shareLink.characters.count > 0) {
  656. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  657. }
  658. if (resultShare.shareUserAndGroup.characters.count > 0) {
  659. sharesUserAndGroup = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  660. }
  661. }
  662. return [sharesLink, sharesUserAndGroup]
  663. }
  664. //MARK: -
  665. }