NCManageDatabase.swift 65 KB

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