NCManageDatabase.swift 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  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. let result = realm.objects(tableAccount.self).filter("account = %@", account).first
  110. if result != nil {
  111. try! realm.write {
  112. result?.password = password
  113. }
  114. }
  115. }
  116. func deleteAccount(_ account: String) {
  117. let realm = try! Realm()
  118. let result = realm.objects(tableAccount.self).filter("account = %@", account).first
  119. if result != nil {
  120. try! realm.write {
  121. realm.delete(result!)
  122. }
  123. }
  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. let results = realm.objects(tableAccount.self)
  178. try! realm.write {
  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. let result = realm.objects(tableAccount.self).filter("active = true").first
  193. if result != nil {
  194. try! realm.write {
  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. }
  217. }
  218. func setAccountAutoUploadDateAssetType(_ assetMediaType: PHAssetMediaType, assetDate: NSDate?) {
  219. let realm = try! Realm()
  220. let result = realm.objects(tableAccount.self).filter("active = true").first
  221. try! realm.write {
  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. let result = realm.objects(tableAccount.self).filter("active = true").first
  237. if result != nil {
  238. try! realm.write {
  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. let result = realm.objects(tableAccount.self).filter("active = true").first
  250. if result != nil {
  251. try! realm.write {
  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. let result = realm.objects(tableAccount.self).filter("account = %@", tblAccount!.account).first
  263. if result != nil {
  264. try! realm.write {
  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. let result = realm.objects(tableAutoUpload.self).filter("account = %@ AND assetLocalIdentifier = %@", tableAccount!.account, metadataNet.assetLocalIdentifier).first
  347. if result != nil {
  348. return false
  349. }
  350. try! realm.write {
  351. // Add new Auto Upload
  352. let addAutoUpload = tableAutoUpload()
  353. addAutoUpload.account = tableAccount!.account
  354. addAutoUpload.assetLocalIdentifier = metadataNet.assetLocalIdentifier
  355. addAutoUpload.fileName = metadataNet.fileName
  356. addAutoUpload.selector = metadataNet.selector
  357. if (metadataNet.selectorPost != nil) {
  358. addAutoUpload.selectorPost = metadataNet.selectorPost
  359. }
  360. addAutoUpload.serverUrl = metadataNet.serverUrl
  361. addAutoUpload.session = metadataNet.session
  362. addAutoUpload.priority = metadataNet.priority
  363. realm.add(addAutoUpload)
  364. }
  365. return true
  366. }
  367. func getAutoUpload(selector: String) -> CCMetadataNet? {
  368. let tableAccount = self.getAccountActive()
  369. if tableAccount == nil {
  370. return nil
  371. }
  372. let realm = try! Realm()
  373. let result = realm.objects(tableAutoUpload.self).filter("account = %@ AND selector = %@ AND lock == false", tableAccount!.account, selector).first
  374. if result == nil {
  375. return nil
  376. }
  377. let metadataNet = CCMetadataNet()
  378. metadataNet.action = actionUploadAsset
  379. metadataNet.assetLocalIdentifier = result?.assetLocalIdentifier
  380. metadataNet.fileName = result?.fileName
  381. metadataNet.priority = result!.priority
  382. metadataNet.selector = result?.selector
  383. metadataNet.selectorPost = result?.selectorPost
  384. metadataNet.serverUrl = result?.serverUrl
  385. metadataNet.session = result?.session
  386. metadataNet.taskStatus = Int(k_taskStatusResume)
  387. // Lock
  388. try! realm.write {
  389. result?.lock = true
  390. }
  391. return metadataNet
  392. }
  393. func getLockAutoUpload() -> [tableAutoUpload]? {
  394. let tableAccount = self.getAccountActive()
  395. if tableAccount == nil {
  396. return nil
  397. }
  398. let realm = try! Realm()
  399. let results = realm.objects(tableAutoUpload.self).filter("account = %@ AND lock = true", tableAccount!.account)
  400. return Array(results)
  401. }
  402. func unlockAutoUpload(assetLocalIdentifier: String) {
  403. let tableAccount = self.getAccountActive()
  404. if tableAccount == nil {
  405. return
  406. }
  407. let realm = try! Realm()
  408. let result = realm.objects(tableAutoUpload.self).filter("account = %@ AND assetLocalIdentifier = %@", tableAccount!.account, assetLocalIdentifier).first
  409. if result != nil {
  410. // UnLock
  411. try! realm.write {
  412. result?.lock = false
  413. }
  414. }
  415. }
  416. func deleteAutoUpload(assetLocalIdentifier: String) {
  417. let tableAccount = self.getAccountActive()
  418. if tableAccount == nil {
  419. return
  420. }
  421. let realm = try! Realm()
  422. let result = realm.objects(tableAutoUpload.self).filter("account = %@ AND assetLocalIdentifier = %@", tableAccount!.account, assetLocalIdentifier).first
  423. if result != nil {
  424. try! realm.write {
  425. realm.delete(result!)
  426. }
  427. }
  428. }
  429. func countAutoUpload(session: String?) -> Int {
  430. let tableAccount = self.getAccountActive()
  431. if tableAccount == nil {
  432. return 0
  433. }
  434. let realm = try! Realm()
  435. let results : Results<tableAutoUpload>
  436. if (session == nil) {
  437. results = realm.objects(tableAutoUpload.self).filter("account = %@", tableAccount!.account)
  438. } else {
  439. results = realm.objects(tableAutoUpload.self).filter("account = %@ AND session = %@", tableAccount!.account, session!)
  440. }
  441. return results.count
  442. }
  443. //MARK: -
  444. //MARK: Table Capabilities
  445. func addCapabilities(_ capabilities: OCCapabilities) {
  446. let tableAccount = self.getAccountActive()
  447. if tableAccount == nil {
  448. return
  449. }
  450. let realm = try! Realm()
  451. let result = realm.objects(tableCapabilities.self).filter("account = %@", tableAccount!.account).first
  452. try! realm.write {
  453. var resultCapabilities = tableCapabilities()
  454. if result != nil {
  455. resultCapabilities = result!
  456. }
  457. resultCapabilities.account = tableAccount!.account
  458. resultCapabilities.themingBackground = capabilities.themingBackground
  459. resultCapabilities.themingColor = capabilities.themingColor
  460. resultCapabilities.themingLogo = capabilities.themingLogo
  461. resultCapabilities.themingName = capabilities.themingName
  462. resultCapabilities.themingSlogan = capabilities.themingSlogan
  463. resultCapabilities.themingUrl = capabilities.themingUrl
  464. resultCapabilities.versionMajor = capabilities.versionMajor
  465. resultCapabilities.versionMinor = capabilities.versionMinor
  466. resultCapabilities.versionMicro = capabilities.versionMicro
  467. resultCapabilities.versionString = capabilities.versionString
  468. if result == nil {
  469. realm.add(resultCapabilities)
  470. }
  471. }
  472. }
  473. func getCapabilites() -> tableCapabilities? {
  474. let tableAccount = self.getAccountActive()
  475. if tableAccount == nil {
  476. return nil
  477. }
  478. let realm = try! Realm()
  479. let result = realm.objects(tableCapabilities.self).filter("account = %@", tableAccount!.account).first
  480. if result != nil {
  481. return result
  482. } else {
  483. return nil
  484. }
  485. }
  486. func getServerVersion() -> Int {
  487. let tableAccount = self.getAccountActive()
  488. if tableAccount == nil {
  489. return 0
  490. }
  491. let realm = try! Realm()
  492. let result = realm.objects(tableCapabilities.self).filter("account = %@", tableAccount!.account).first
  493. if result != nil {
  494. return result!.versionMajor
  495. } else {
  496. return 0
  497. }
  498. }
  499. //MARK: -
  500. //MARK: Table Certificates
  501. func addCertificates(_ certificateLocation: String) {
  502. let realm = try! Realm()
  503. try! realm.write {
  504. let addCertificates = tableCertificates()
  505. addCertificates.certificateLocation = certificateLocation
  506. realm.add(addCertificates)
  507. }
  508. }
  509. func getCertificatesLocation(_ localCertificatesFolder: String) -> [String] {
  510. let realm = try! Realm()
  511. let results = realm.objects(tableCertificates.self)
  512. var arraycertificatePath = [String]()
  513. for result in results {
  514. arraycertificatePath.append("\(localCertificatesFolder)\(result.certificateLocation)")
  515. }
  516. return arraycertificatePath
  517. }
  518. //MARK: -
  519. //MARK: Table Directory
  520. func addDirectory(serverUrl: String, permissions: String) -> String {
  521. let tableAccount = self.getAccountActive()
  522. if tableAccount == nil {
  523. return ""
  524. }
  525. let realm = try! Realm()
  526. let result = realm.objects(tableDirectory.self).filter("serverUrl = %@", serverUrl).first
  527. var directoryID: String = ""
  528. try! realm.write {
  529. if result == nil || (result?.isInvalidated)! {
  530. let addDirectory = tableDirectory()
  531. addDirectory.account = tableAccount!.account
  532. directoryID = NSUUID().uuidString
  533. addDirectory.directoryID = directoryID
  534. addDirectory.permissions = permissions
  535. addDirectory.serverUrl = serverUrl
  536. realm.add(addDirectory, update: true)
  537. } else {
  538. result?.permissions = permissions
  539. directoryID = result!.directoryID
  540. realm.add(result!, update: true)
  541. }
  542. }
  543. return directoryID
  544. }
  545. func deleteDirectoryAndSubDirectory(serverUrl: String) {
  546. let tableAccount = self.getAccountActive()
  547. if tableAccount == nil {
  548. return
  549. }
  550. let realm = try! Realm()
  551. let results = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl BEGINSWITH %@", tableAccount!.account, serverUrl)
  552. for result in results {
  553. // delete metadata
  554. self.deleteMetadata(predicate: NSPredicate(format: "directoryID = %@", result.directoryID), clearDateReadDirectoryID: result.directoryID)
  555. // delete local file
  556. self.deleteLocalFile(predicate: NSPredicate(format: "fileID = %@", result.fileID))
  557. /*
  558. // remove if in session
  559. if ([recordMetadata.session length] >0) {
  560. if (recordMetadata.sessionTaskIdentifier >= 0)
  561. [[CCNetworking sharedNetworking] settingSession:recordMetadata.session sessionTaskIdentifier:[recordMetadata.sessionTaskIdentifier integerValue] taskStatus: k_taskStatusCancel];
  562. if (recordMetadata.sessionTaskIdentifierPlist >= 0)
  563. [[CCNetworking sharedNetworking] settingSession:recordMetadata.session sessionTaskIdentifier:[recordMetadata.sessionTaskIdentifierPlist integerValue] taskStatus: k_taskStatusCancel];
  564. }
  565. */
  566. }
  567. // Delete table Dirrectory
  568. try! realm.write {
  569. realm.delete(results)
  570. }
  571. }
  572. func setDirectory(serverUrl: String, serverUrlTo: String?, etag: String?) {
  573. let tableAccount = self.getAccountActive()
  574. if tableAccount == nil {
  575. return
  576. }
  577. let realm = try! Realm()
  578. try! realm.write {
  579. let result = realm.objects(tableDirectory.self).filter("serverUrl = %@", serverUrl).first
  580. if result != nil {
  581. if serverUrlTo != nil {
  582. result?.serverUrl = serverUrlTo!
  583. }
  584. if etag != nil {
  585. result?.etag = etag!
  586. }
  587. }
  588. }
  589. }
  590. func clearDateRead(serverUrl: String?, directoryID: String?) {
  591. let tableAccount = self.getAccountActive()
  592. if tableAccount == nil {
  593. return
  594. }
  595. let realm = try! Realm()
  596. try! realm.write {
  597. var results : Results<tableDirectory>?
  598. if serverUrl != nil {
  599. results = realm.objects(tableDirectory.self).filter("serverUrl = %@", serverUrl!)
  600. }
  601. if directoryID != nil {
  602. results = realm.objects(tableDirectory.self).filter("directoryID = %@", directoryID!)
  603. }
  604. if results != nil {
  605. if results!.count > 0 {
  606. results![0].dateReadDirectory = nil
  607. results![0].etag = ""
  608. realm.add(results!, update: true)
  609. }
  610. }
  611. }
  612. }
  613. func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
  614. let tableAccount = self.getAccountActive()
  615. if tableAccount == nil {
  616. return nil
  617. }
  618. let realm = try! Realm()
  619. let result = realm.objects(tableDirectory.self).filter(predicate).first
  620. if result != nil {
  621. return result
  622. } else {
  623. return nil
  624. }
  625. }
  626. func getTablesDirectory(predicate: NSPredicate, sorted: String?, ascending: Bool) -> [tableDirectory]? {
  627. let tableAccount = self.getAccountActive()
  628. if tableAccount == nil {
  629. return nil
  630. }
  631. let realm = try! Realm()
  632. let results : Results<tableDirectory>
  633. if sorted == nil {
  634. results = realm.objects(tableDirectory.self).filter(predicate)
  635. } else {
  636. results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  637. }
  638. if (results.count > 0) {
  639. return Array(results)
  640. } else {
  641. return nil
  642. }
  643. }
  644. func getDirectoryID(_ serverUrl: String) -> String {
  645. let tableAccount = self.getAccountActive()
  646. if tableAccount == nil {
  647. return ""
  648. }
  649. let realm = try! Realm()
  650. let result = realm.objects(tableDirectory.self).filter("serverUrl = %@", serverUrl).first
  651. if result != nil {
  652. return (result?.directoryID)!
  653. } else {
  654. return self.addDirectory(serverUrl: serverUrl, permissions: "")
  655. }
  656. }
  657. func getServerUrl(_ directoryID: String) -> String {
  658. let tableAccount = self.getAccountActive()
  659. if tableAccount == nil {
  660. return ""
  661. }
  662. let realm = try! Realm()
  663. let result = realm.objects(tableDirectory.self).filter("directoryID = %@", directoryID).first
  664. if result != nil {
  665. return (result?.serverUrl)!
  666. } else {
  667. return ""
  668. }
  669. }
  670. func setDateReadDirectory(directoryID: String) {
  671. let tableAccount = self.getAccountActive()
  672. if tableAccount == nil {
  673. return
  674. }
  675. let realm = try! Realm()
  676. realm.beginWrite()
  677. let result = realm.objects(tableDirectory.self).filter("account = %@ AND directoryID = %@", tableAccount!.account, directoryID).first
  678. if result != nil {
  679. result?.dateReadDirectory = NSDate()
  680. }
  681. try! realm.commitWrite()
  682. }
  683. func setClearAllDateReadDirectory() {
  684. let tableAccount = self.getAccountActive()
  685. if tableAccount == nil {
  686. return
  687. }
  688. let realm = try! Realm()
  689. let results = realm.objects(tableDirectory.self)
  690. try! realm.write {
  691. for result in results {
  692. result.dateReadDirectory = nil;
  693. result.etag = ""
  694. }
  695. }
  696. }
  697. func setDirectoryLock(serverUrl: String, lock: Bool) -> Bool {
  698. var update = false
  699. let tableAccount = self.getAccountActive()
  700. if tableAccount == nil {
  701. return update
  702. }
  703. let realm = try! Realm()
  704. try! realm.write {
  705. let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", tableAccount!.account, serverUrl).first
  706. if result != nil {
  707. result?.lock = lock
  708. update = true
  709. }
  710. }
  711. return update
  712. }
  713. func setAllDirectoryUnLock() {
  714. let tableAccount = self.getAccountActive()
  715. if tableAccount == nil {
  716. return
  717. }
  718. let realm = try! Realm()
  719. let results = realm.objects(tableDirectory.self).filter("account = %@", tableAccount!.account)
  720. try! realm.write {
  721. for result in results {
  722. result.lock = false;
  723. }
  724. }
  725. }
  726. //MARK: -
  727. //MARK: Table External Sites
  728. func addExternalSites(_ externalSites: OCExternalSites) {
  729. let tableAccount = self.getAccountActive()
  730. if tableAccount == nil {
  731. return
  732. }
  733. let realm = try! Realm()
  734. try! realm.write {
  735. let addExternalSite = tableExternalSites()
  736. addExternalSite.account = tableAccount!.account
  737. addExternalSite.idExternalSite = externalSites.idExternalSite
  738. addExternalSite.icon = externalSites.icon
  739. addExternalSite.lang = externalSites.lang
  740. addExternalSite.name = externalSites.name
  741. addExternalSite.url = externalSites.url
  742. addExternalSite.type = externalSites.type
  743. realm.add(addExternalSite)
  744. }
  745. }
  746. func deleteExternalSites() {
  747. let tableAccount = self.getAccountActive()
  748. if tableAccount == nil {
  749. return
  750. }
  751. let realm = try! Realm()
  752. let results = realm.objects(tableExternalSites.self).filter("account = %@", tableAccount!.account)
  753. try! realm.write {
  754. realm.delete(results)
  755. }
  756. }
  757. func getAllExternalSites(predicate: NSPredicate) -> [tableExternalSites] {
  758. let realm = try! Realm()
  759. let results = realm.objects(tableExternalSites.self).filter(predicate).sorted(byKeyPath: "idExternalSite", ascending: true)
  760. return Array(results)
  761. }
  762. //MARK: -
  763. //MARK: Table GPS
  764. func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  765. let realm = try! Realm()
  766. // Verify if exists
  767. let result = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first
  768. if result != nil {
  769. return
  770. }
  771. try! realm.write {
  772. // Add new GPS
  773. let addGPS = tableGPS()
  774. addGPS.latitude = latitude
  775. addGPS.location = location
  776. addGPS.longitude = longitude
  777. addGPS.placemarkAdministrativeArea = placemarkAdministrativeArea
  778. addGPS.placemarkCountry = placemarkCountry
  779. addGPS.placemarkLocality = placemarkLocality
  780. addGPS.placemarkPostalCode = placemarkPostalCode
  781. addGPS.placemarkThoroughfare = placemarkThoroughfare
  782. realm.add(addGPS)
  783. }
  784. }
  785. func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  786. let realm = try! Realm()
  787. let result = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first
  788. if result == nil {
  789. return nil
  790. } else {
  791. return result!.location
  792. }
  793. }
  794. //MARK: -
  795. //MARK: Table LocalFile
  796. func addLocalFile(metadata: tableMetadata) {
  797. let tableAccount = self.getAccountActive()
  798. if tableAccount == nil {
  799. return
  800. }
  801. let realm = try! Realm()
  802. try! realm.write {
  803. let addLocaFile = tableLocalFile()
  804. addLocaFile.account = tableAccount!.account
  805. addLocaFile.date = metadata.date
  806. addLocaFile.etag = metadata.etag
  807. addLocaFile.exifDate = NSDate()
  808. addLocaFile.exifLatitude = "-1"
  809. addLocaFile.exifLongitude = "-1"
  810. addLocaFile.fileID = metadata.fileID
  811. addLocaFile.fileName = metadata.fileName
  812. addLocaFile.fileNamePrint = metadata.fileNamePrint
  813. addLocaFile.size = metadata.size
  814. realm.add(addLocaFile, update: true)
  815. }
  816. }
  817. func deleteLocalFile(predicate: NSPredicate) {
  818. let tableAccount = self.getAccountActive()
  819. if tableAccount == nil {
  820. return
  821. }
  822. let realm = try! Realm()
  823. let results = realm.objects(tableLocalFile.self).filter(predicate)
  824. try! realm.write {
  825. realm.delete(results)
  826. }
  827. }
  828. func setLocalFile(fileID: String, date: NSDate?, exifDate: NSDate?, exifLatitude: String?, exifLongitude: String?, fileName: String?, fileNamePrint: String?) {
  829. let tableAccount = self.getAccountActive()
  830. if tableAccount == nil {
  831. return
  832. }
  833. let realm = try! Realm()
  834. let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first
  835. if result != nil {
  836. try! realm.write {
  837. if date != nil {
  838. result?.date = date!
  839. }
  840. if exifDate != nil {
  841. result?.exifDate = exifDate!
  842. }
  843. if exifLatitude != nil {
  844. result?.exifLatitude = exifLatitude!
  845. }
  846. if exifLongitude != nil {
  847. result?.exifLongitude = exifLongitude!
  848. }
  849. if fileName != nil {
  850. result?.fileName = fileName!
  851. }
  852. if fileNamePrint != nil {
  853. result?.fileNamePrint = fileNamePrint!
  854. }
  855. }
  856. }
  857. }
  858. func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
  859. let tableAccount = self.getAccountActive()
  860. if tableAccount == nil {
  861. return nil
  862. }
  863. let realm = try! Realm()
  864. return realm.objects(tableLocalFile.self).filter(predicate).first
  865. }
  866. //MARK: -
  867. //MARK: Table Metadata
  868. func addMetadata(_ metadata: tableMetadata, activeUrl: String, serverUrl: String) -> tableMetadata? {
  869. let tableAccount = self.getAccountActive()
  870. if tableAccount == nil {
  871. return nil
  872. }
  873. let autoUploadFileName = self.getAccountAutoUploadFileName()
  874. let autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  875. let realm = try! Realm()
  876. realm.beginWrite()
  877. if (metadata.realm == nil) {
  878. let metadataWithIcon = CCUtility.insertTypeFileIconName(metadata, serverUrl: serverUrl, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory)
  879. realm.add(metadataWithIcon!, update: true)
  880. } else {
  881. realm.add(metadata, update: true)
  882. }
  883. try! realm.commitWrite()
  884. if metadata.isInvalidated {
  885. return nil
  886. }
  887. self.setDateReadDirectory(directoryID: metadata.directoryID)
  888. if metadata.isInvalidated {
  889. return nil
  890. } else {
  891. return tableMetadata.init(value: metadata)
  892. }
  893. }
  894. func addMetadatas(_ metadatas: [tableMetadata], activeUrl: String, serverUrl: String) -> [tableMetadata] {
  895. let autoUploadFileName = self.getAccountAutoUploadFileName()
  896. let autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  897. var arrayMetadatas = [tableMetadata]()
  898. let realm = try! Realm()
  899. try! realm.write {
  900. for metadata in metadatas {
  901. if metadata.realm == nil {
  902. let metadataWithIcon = CCUtility.insertTypeFileIconName(metadata, serverUrl: serverUrl, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory)
  903. realm.add(metadataWithIcon!, update: true)
  904. } else {
  905. realm.add(metadata, update: true)
  906. }
  907. arrayMetadatas.append(tableMetadata.init(value: metadata))
  908. }
  909. }
  910. let directoryID = self.getDirectoryID(serverUrl)
  911. self.setDateReadDirectory(directoryID: directoryID)
  912. return arrayMetadatas
  913. }
  914. func deleteMetadata(predicate: NSPredicate, clearDateReadDirectoryID: String?) {
  915. let tableAccount = self.getAccountActive()
  916. if tableAccount == nil {
  917. return
  918. }
  919. let realm = try! Realm()
  920. let results = realm.objects(tableMetadata.self).filter(predicate)
  921. if clearDateReadDirectoryID == nil {
  922. for result in results {
  923. self.setDateReadDirectory(directoryID: result.directoryID)
  924. }
  925. } else {
  926. self.setDateReadDirectory(directoryID: clearDateReadDirectoryID!)
  927. }
  928. try! realm.write {
  929. realm.delete(results)
  930. }
  931. }
  932. func moveMetadata(fileName: String, directoryID: String, directoryIDTo: String) {
  933. let tableAccount = self.getAccountActive()
  934. if tableAccount == nil {
  935. return
  936. }
  937. let realm = try! Realm()
  938. let results = realm.objects(tableMetadata.self).filter("account = %@ AND fileName = %@ AND directoryID = %@", tableAccount!.account, fileName, directoryID)
  939. try! realm.write {
  940. for result in results {
  941. result.directoryID = directoryIDTo
  942. }
  943. }
  944. self.setDateReadDirectory(directoryID: directoryID)
  945. self.setDateReadDirectory(directoryID: directoryIDTo)
  946. }
  947. func updateMetadata(_ metadata: tableMetadata, activeUrl: String) -> tableMetadata {
  948. let autoUploadFileName = self.getAccountAutoUploadFileName()
  949. let autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  950. let serverUrl = self.getServerUrl(metadata.directoryID)
  951. let metadataWithIcon = CCUtility.insertTypeFileIconName(metadata, serverUrl: serverUrl, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory)
  952. let realm = try! Realm()
  953. try! realm.write {
  954. realm.add(metadataWithIcon!, update: true)
  955. }
  956. self.setDateReadDirectory(directoryID: metadata.directoryID)
  957. return tableMetadata.init(value: metadata)
  958. }
  959. func setMetadataSession(_ session: String?, sessionError: String?, sessionSelector: String?, sessionSelectorPost: String?, sessionTaskIdentifier: Int, sessionTaskIdentifierPlist: Int, predicate: NSPredicate) {
  960. let tableAccount = self.getAccountActive()
  961. if tableAccount == nil {
  962. return
  963. }
  964. let realm = try! Realm()
  965. let result = realm.objects(tableMetadata.self).filter(predicate).first
  966. if result != nil {
  967. try! realm.write {
  968. if session != nil {
  969. result?.session = session!
  970. }
  971. if sessionError != nil {
  972. result?.sessionError = sessionError!
  973. }
  974. if sessionSelector != nil {
  975. result?.sessionSelector = sessionSelector!
  976. }
  977. if sessionSelectorPost != nil {
  978. result?.sessionSelectorPost = sessionSelectorPost!
  979. }
  980. if sessionTaskIdentifier != Int(k_taskIdentifierNULL) {
  981. result?.sessionTaskIdentifier = sessionTaskIdentifier
  982. }
  983. if sessionTaskIdentifierPlist != Int(k_taskIdentifierNULL) {
  984. result?.sessionTaskIdentifierPlist = sessionTaskIdentifierPlist
  985. }
  986. }
  987. }
  988. // Update Date Read Directory
  989. if result != nil {
  990. self.setDateReadDirectory(directoryID: (result?.directoryID)!)
  991. }
  992. }
  993. func setMetadataFavorite(fileID: String, favorite: Bool) {
  994. let tableAccount = self.getAccountActive()
  995. if tableAccount == nil {
  996. return
  997. }
  998. let realm = try! Realm()
  999. let result = realm.objects(tableMetadata.self).filter("account = %@ AND fileID = %@", tableAccount!.account, fileID).first
  1000. if result != nil {
  1001. try! realm.write {
  1002. result?.favorite = favorite
  1003. }
  1004. self.setDateReadDirectory(directoryID: result!.directoryID)
  1005. }
  1006. }
  1007. func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  1008. let tableAccount = self.getAccountActive()
  1009. if tableAccount == nil {
  1010. return nil
  1011. }
  1012. let realm = try! Realm()
  1013. let result = realm.objects(tableMetadata.self).filter(predicate).first
  1014. if result != nil {
  1015. return tableMetadata.init(value: result!)
  1016. } else {
  1017. return nil
  1018. }
  1019. }
  1020. func getMetadatas(predicate: NSPredicate, sorted: String?, ascending: Bool) -> [tableMetadata]? {
  1021. let tableAccount = self.getAccountActive()
  1022. if tableAccount == nil {
  1023. return nil
  1024. }
  1025. let realm = try! Realm()
  1026. let results : Results<tableMetadata>
  1027. if sorted == nil {
  1028. results = realm.objects(tableMetadata.self).filter(predicate)
  1029. } else {
  1030. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  1031. }
  1032. if (results.count > 0) {
  1033. return Array(convertMetadataToUnmanagedMetadata(results))
  1034. } else {
  1035. return nil
  1036. }
  1037. }
  1038. func getMetadataAtIndex(predicate: NSPredicate, sorted: String?, ascending: Bool, index: Int) -> tableMetadata? {
  1039. let tableAccount = self.getAccountActive()
  1040. if tableAccount == nil {
  1041. return nil
  1042. }
  1043. let realm = try! Realm()
  1044. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  1045. if (results.count > 0 && results.count > index) {
  1046. return tableMetadata.init(value: results[index])
  1047. } else {
  1048. return nil
  1049. }
  1050. }
  1051. func getMetadataFromFileName(_ fileName: String, directoryID: String) -> tableMetadata? {
  1052. let tableAccount = self.getAccountActive()
  1053. if tableAccount == nil {
  1054. return nil
  1055. }
  1056. let realm = try! Realm()
  1057. let result = realm.objects(tableMetadata.self).filter("account = %@ AND directoryID = %@ AND (fileName = %@ OR fileNameData = %@)", tableAccount!.account, directoryID, fileName, fileName).first
  1058. if result != nil {
  1059. return tableMetadata.init(value: result!)
  1060. } else {
  1061. return nil
  1062. }
  1063. }
  1064. func getTableMetadataDownload() -> [tableMetadata]? {
  1065. let tableAccount = self.getAccountActive()
  1066. if tableAccount == nil {
  1067. return nil
  1068. }
  1069. 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)
  1070. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1071. }
  1072. func getTableMetadataDownloadWWan() -> [tableMetadata]? {
  1073. let tableAccount = self.getAccountActive()
  1074. if tableAccount == nil {
  1075. return nil
  1076. }
  1077. let predicate = NSPredicate(format: "account = %@ AND session = %@ AND (sessionTaskIdentifier != %i OR sessionTaskIdentifierPlist != %i)", tableAccount!.account, k_download_session_wwan, k_taskIdentifierDone, k_taskIdentifierDone)
  1078. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1079. }
  1080. func getTableMetadataUpload() -> [tableMetadata]? {
  1081. let tableAccount = self.getAccountActive()
  1082. if tableAccount == nil {
  1083. return nil
  1084. }
  1085. 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)
  1086. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1087. }
  1088. func getTableMetadataUploadWWan() -> [tableMetadata]? {
  1089. let tableAccount = self.getAccountActive()
  1090. if tableAccount == nil {
  1091. return nil
  1092. }
  1093. let predicate = NSPredicate(format: "account = %@ AND session = %@ AND (sessionTaskIdentifier != %i OR sessionTaskIdentifierPlist != %i)", tableAccount!.account, k_upload_session_wwan, k_taskIdentifierDone, k_taskIdentifierDone)
  1094. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1095. }
  1096. func getTableMetadatasPhotos(serverUrl: String) -> [tableMetadata]? {
  1097. let tableAccount = self.getAccountActive()
  1098. if tableAccount == nil {
  1099. return nil
  1100. }
  1101. let realm = try! Realm()
  1102. let sorted = CCUtility.getOrderSettings()
  1103. let ascending = CCUtility.getAscendingSettings()
  1104. var recordsPhotosAutoUpload = [tableMetadata]()
  1105. let directories = self.getTablesDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl BEGINSWITH %@", tableAccount!.account, serverUrl), sorted: "serverUrl", ascending: true)
  1106. if directories != nil {
  1107. for directory in directories! {
  1108. 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)
  1109. let metadatas = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  1110. if metadatas.count > 0 {
  1111. for metadata in metadatas {
  1112. recordsPhotosAutoUpload.append(tableMetadata.init(value: metadata))
  1113. }
  1114. }
  1115. }
  1116. }
  1117. if recordsPhotosAutoUpload.count > 0 {
  1118. return Array(recordsPhotosAutoUpload)
  1119. } else {
  1120. return nil
  1121. }
  1122. }
  1123. func convertMetadataToUnmanagedMetadata(_ metadatas: Results<tableMetadata>) -> [tableMetadata] {
  1124. var unmanageMetadatas = [tableMetadata]()
  1125. for metadata in metadatas {
  1126. unmanageMetadatas.append(tableMetadata.init(value: metadata))
  1127. }
  1128. return unmanageMetadatas
  1129. }
  1130. //MARK: -
  1131. //MARK: Table Share
  1132. func addShareLink(_ share: String, fileName: String, serverUrl: String) -> [String:String]? {
  1133. let tableAccount = self.getAccountActive()
  1134. if tableAccount == nil {
  1135. return nil
  1136. }
  1137. let realm = try! Realm()
  1138. // Verify if exists
  1139. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", tableAccount!.account, fileName, serverUrl).first
  1140. if result != nil {
  1141. try! realm.write {
  1142. result?.shareLink = share
  1143. }
  1144. } else {
  1145. // Add new record
  1146. try! realm.write {
  1147. let addShare = tableShare()
  1148. addShare.account = tableAccount!.account
  1149. addShare.fileName = fileName
  1150. addShare.serverUrl = serverUrl
  1151. addShare.shareLink = share
  1152. realm.add(addShare)
  1153. }
  1154. }
  1155. return ["\(serverUrl)\(fileName)" : share]
  1156. }
  1157. func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String) -> [String:String]? {
  1158. let tableAccount = self.getAccountActive()
  1159. if tableAccount == nil {
  1160. return nil
  1161. }
  1162. let realm = try! Realm()
  1163. // Verify if exists
  1164. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", tableAccount!.account, fileName, serverUrl).first
  1165. if result != nil {
  1166. try! realm.write {
  1167. result?.shareUserAndGroup = share
  1168. }
  1169. } else {
  1170. // Add new record
  1171. try! realm.write {
  1172. let addShare = tableShare()
  1173. addShare.account = tableAccount!.account
  1174. addShare.fileName = fileName
  1175. addShare.serverUrl = serverUrl
  1176. addShare.shareUserAndGroup = share
  1177. realm.add(addShare)
  1178. }
  1179. }
  1180. return ["\(serverUrl)\(fileName)" : share]
  1181. }
  1182. func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: [String:String], sharesUserAndGroup: [String:String]) -> [Any]? {
  1183. let tableAccount = self.getAccountActive()
  1184. if tableAccount == nil {
  1185. return nil
  1186. }
  1187. var sharesLink = sharesLink
  1188. var sharesUserAndGroup = sharesUserAndGroup
  1189. let realm = try! Realm()
  1190. let results = realm.objects(tableShare.self).filter("account = %@ AND (shareLink CONTAINS %@ OR shareUserAndGroup CONTAINS %@)", tableAccount!.account, share, share)
  1191. if (results.count > 0) {
  1192. let result = results[0]
  1193. realm.beginWrite()
  1194. if (result.shareLink.contains(share)) {
  1195. result.shareLink = ""
  1196. }
  1197. if (result.shareUserAndGroup.contains(share)) {
  1198. var shares : [String] = result.shareUserAndGroup.components(separatedBy: ",")
  1199. if let index = shares.index(of:share) {
  1200. shares.remove(at: index)
  1201. }
  1202. result.shareUserAndGroup = shares.joined(separator: ",")
  1203. }
  1204. if (result.shareLink.characters.count > 0) {
  1205. sharesLink.updateValue(result.shareLink, forKey:"\(serverUrl)\(fileName)")
  1206. } else {
  1207. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  1208. }
  1209. if (result.shareUserAndGroup.characters.count > 0) {
  1210. sharesUserAndGroup.updateValue(result.shareUserAndGroup, forKey:"\(serverUrl)\(fileName)")
  1211. } else {
  1212. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  1213. }
  1214. if (result.shareLink.characters.count == 0 && result.shareUserAndGroup.characters.count == 0) {
  1215. realm.delete(result)
  1216. }
  1217. try! realm.commitWrite()
  1218. }
  1219. return [sharesLink, sharesUserAndGroup]
  1220. }
  1221. func removeShareActiveAccount() {
  1222. let tableAccount = self.getAccountActive()
  1223. if tableAccount == nil {
  1224. return
  1225. }
  1226. let realm = try! Realm()
  1227. let results = realm.objects(tableShare.self).filter("account = %@", tableAccount!.account)
  1228. try! realm.write {
  1229. realm.delete(results)
  1230. }
  1231. }
  1232. func updateShare(_ items: [String:OCSharedDto], activeUrl: String) -> [Any]? {
  1233. let tableAccount = self.getAccountActive()
  1234. if tableAccount == nil {
  1235. return nil
  1236. }
  1237. var sharesLink = [String:String]()
  1238. var sharesUserAndGroup = [String:String]()
  1239. self.removeShareActiveAccount()
  1240. var itemsLink = [OCSharedDto]()
  1241. var itemsUsersAndGroups = [OCSharedDto]()
  1242. for (_, itemOCSharedDto) in items {
  1243. if (itemOCSharedDto.shareType == Int(shareTypeLink.rawValue)) {
  1244. itemsLink.append(itemOCSharedDto)
  1245. }
  1246. if (itemOCSharedDto.shareWith.characters.count > 0 && (itemOCSharedDto.shareType == Int(shareTypeUser.rawValue) || itemOCSharedDto.shareType == Int(shareTypeGroup.rawValue) || itemOCSharedDto.shareType == Int(shareTypeRemote.rawValue) )) {
  1247. itemsUsersAndGroups.append(itemOCSharedDto)
  1248. }
  1249. }
  1250. // Manage sharesLink
  1251. for itemOCSharedDto in itemsLink {
  1252. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(itemOCSharedDto.path!)"
  1253. let fileName = NSString(string: fullPath).lastPathComponent
  1254. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - fileName.characters.count - 1))
  1255. if serverUrl.hasSuffix("/") {
  1256. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.characters.count - 1))
  1257. }
  1258. if itemOCSharedDto.idRemoteShared > 0 {
  1259. let sharesLinkReturn = self.addShareLink("\(itemOCSharedDto.idRemoteShared)", fileName: fileName, serverUrl: serverUrl)
  1260. if sharesLinkReturn != nil {
  1261. for (key,value) in sharesLinkReturn! {
  1262. sharesLink.updateValue(value, forKey:key)
  1263. }
  1264. }
  1265. }
  1266. }
  1267. // Manage sharesUserAndGroup
  1268. var paths = [String:[String]]()
  1269. for itemOCSharedDto in itemsUsersAndGroups {
  1270. if paths[itemOCSharedDto.path] != nil {
  1271. var share : [String] = paths[itemOCSharedDto.path]!
  1272. share.append("\(itemOCSharedDto.idRemoteShared)")
  1273. paths[itemOCSharedDto.path] = share
  1274. } else {
  1275. paths[itemOCSharedDto.path] = ["\(itemOCSharedDto.idRemoteShared)"]
  1276. }
  1277. }
  1278. for (path, idsRemoteSharedArray) in paths {
  1279. let idsRemoteShared = idsRemoteSharedArray.joined(separator: ",")
  1280. print("[LOG] share \(String(describing: idsRemoteShared))")
  1281. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(path)"
  1282. let fileName = NSString(string: fullPath).lastPathComponent
  1283. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - fileName.characters.count - 1))
  1284. if serverUrl.hasSuffix("/") {
  1285. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.characters.count - 1))
  1286. }
  1287. let sharesUserAndGroupReturn = self.addShareUserAndGroup(idsRemoteShared, fileName: fileName, serverUrl: serverUrl)
  1288. if sharesUserAndGroupReturn != nil {
  1289. for (key,value) in sharesUserAndGroupReturn! {
  1290. sharesUserAndGroup.updateValue(value, forKey:key)
  1291. }
  1292. }
  1293. }
  1294. return [sharesLink, sharesUserAndGroup]
  1295. }
  1296. func getShares() -> [Any]? {
  1297. let tableAccount = self.getAccountActive()
  1298. if tableAccount == nil {
  1299. return nil
  1300. }
  1301. var sharesLink = [String:String]()
  1302. var sharesUserAndGroup = [String:String]()
  1303. let realm = try! Realm()
  1304. let results = realm.objects(tableShare.self).filter("account = %@", tableAccount!.account)
  1305. for resultShare in results {
  1306. if (resultShare.shareLink.characters.count > 0) {
  1307. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1308. }
  1309. if (resultShare.shareUserAndGroup.characters.count > 0) {
  1310. sharesUserAndGroup = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1311. }
  1312. }
  1313. return [sharesLink, sharesUserAndGroup]
  1314. }
  1315. func getTableShares() -> [tableShare]? {
  1316. let tableAccount = self.getAccountActive()
  1317. if tableAccount == nil {
  1318. return nil
  1319. }
  1320. let realm = try! Realm()
  1321. let results = realm.objects(tableShare.self).filter("account = %@", tableAccount!.account).sorted(byKeyPath: "fileName", ascending: true)
  1322. return Array(results)
  1323. }
  1324. //MARK: -
  1325. //MARK: Migrate func
  1326. func addTableAccountFromCoredata(_ table: TableAccount) {
  1327. let realm = try! Realm()
  1328. let results = realm.objects(tableAccount.self).filter("account = %@", table.account!)
  1329. if (results.count == 0) {
  1330. try! realm.write {
  1331. let addAccount = tableAccount()
  1332. addAccount.account = table.account!
  1333. if table.active == 1 {
  1334. addAccount.active = true
  1335. }
  1336. if table.cameraUpload == 1 {
  1337. addAccount.autoUpload = true
  1338. }
  1339. if table.cameraUploadBackground == 1 {
  1340. addAccount.autoUploadBackground = true
  1341. }
  1342. if table.cameraUploadCreateSubfolder == 1 {
  1343. addAccount.autoUploadCreateSubfolder = true
  1344. }
  1345. if table.cameraUploadDatePhoto != nil {
  1346. addAccount.autoUploadDatePhoto = table.cameraUploadDatePhoto! as NSDate
  1347. }
  1348. if table.cameraUploadDateVideo != nil {
  1349. addAccount.autoUploadDateVideo = table.cameraUploadDateVideo! as NSDate
  1350. }
  1351. if table.cameraUploadFolderName != nil {
  1352. addAccount.autoUploadFileName = table.cameraUploadFolderName!
  1353. }
  1354. if table.cameraUploadFolderPath != nil {
  1355. addAccount.autoUploadDirectory = table.cameraUploadFolderPath!
  1356. }
  1357. if table.cameraUploadFull == 1 {
  1358. addAccount.autoUploadFull = true
  1359. }
  1360. if table.cameraUploadPhoto == 1 {
  1361. addAccount.autoUploadPhoto = true
  1362. }
  1363. if table.cameraUploadVideo == 1 {
  1364. addAccount.autoUploadVideo = true
  1365. }
  1366. if table.cameraUploadWWAnPhoto == 1 {
  1367. addAccount.autoUploadWWAnPhoto = true
  1368. }
  1369. if table.cameraUploadWWAnVideo == 1 {
  1370. addAccount.autoUploadWWAnVideo = true
  1371. }
  1372. addAccount.password = table.password!
  1373. addAccount.url = table.url!
  1374. addAccount.user = table.user!
  1375. realm.add(addAccount)
  1376. }
  1377. }
  1378. }
  1379. func addTableDirectoryFromCoredata(_ table: TableDirectory) {
  1380. let realm = try! Realm()
  1381. let results = realm.objects(tableDirectory.self).filter("directoryID = %@", table.directoryID!)
  1382. if (results.count == 0) {
  1383. try! realm.write {
  1384. let addDirectory = tableDirectory()
  1385. addDirectory.account = table.account!
  1386. addDirectory.directoryID = table.directoryID!
  1387. addDirectory.etag = table.rev!
  1388. if table.favorite == 1 {
  1389. addDirectory.favorite = true
  1390. }
  1391. addDirectory.fileID = table.fileID!
  1392. if table.lock == 1 {
  1393. addDirectory.lock = true
  1394. }
  1395. addDirectory.permissions = table.permissions!
  1396. addDirectory.serverUrl = table.serverUrl!
  1397. realm.add(addDirectory)
  1398. }
  1399. }
  1400. }
  1401. func addTableLocalFileFromCoredata(_ table: TableLocalFile) {
  1402. let realm = try! Realm()
  1403. let results = realm.objects(tableLocalFile.self).filter("fileID = %@", table.fileID!)
  1404. if (results.count == 0) {
  1405. try! realm.write {
  1406. let addLocalFile = tableLocalFile()
  1407. addLocalFile.account = table.account!
  1408. if table.date != nil {
  1409. addLocalFile.date = table.date! as NSDate
  1410. } else {
  1411. addLocalFile.date = NSDate()
  1412. }
  1413. addLocalFile.etag = table.rev!
  1414. if table.exifDate != nil {
  1415. addLocalFile.exifDate = table.exifDate! as NSDate
  1416. }
  1417. addLocalFile.exifLatitude = table.exifLatitude!
  1418. addLocalFile.exifLongitude = table.exifLongitude!
  1419. if table.favorite == 1 {
  1420. addLocalFile.favorite = true
  1421. }
  1422. addLocalFile.fileID = table.fileID!
  1423. addLocalFile.fileName = table.fileName!
  1424. addLocalFile.fileNamePrint = table.fileNamePrint!
  1425. addLocalFile.size = table.size as! Double
  1426. realm.add(addLocalFile)
  1427. }
  1428. }
  1429. }
  1430. //MARK: -
  1431. }