NCManageDatabase.swift 80 KB

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