NCManageDatabase.swift 74 KB

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