NCManageDatabase.swift 82 KB

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