NCManageDatabase.swift 87 KB

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