NCManageDatabase.swift 92 KB

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