NCManageDatabase.swift 71 KB

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