NCManageDatabase.swift 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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_automatic_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 Automatic Upload
  340. func addAutomaticUpload(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(tableAutomaticUpload.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 AutomaticUpload
  352. let addAutomaticUpload = tableAutomaticUpload()
  353. addAutomaticUpload.account = tableAccount!.account
  354. addAutomaticUpload.assetLocalIdentifier = metadataNet.assetLocalIdentifier
  355. addAutomaticUpload.fileName = metadataNet.fileName
  356. addAutomaticUpload.selector = metadataNet.selector
  357. if (metadataNet.selectorPost != nil) {
  358. addAutomaticUpload.selectorPost = metadataNet.selectorPost
  359. }
  360. addAutomaticUpload.serverUrl = metadataNet.serverUrl
  361. addAutomaticUpload.session = metadataNet.session
  362. addAutomaticUpload.priority = metadataNet.priority
  363. realm.add(addAutomaticUpload)
  364. }
  365. return true
  366. }
  367. func getAutomaticUpload(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(tableAutomaticUpload.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 getLockAutomaticUpload() -> [tableAutomaticUpload]? {
  394. let tableAccount = self.getAccountActive()
  395. if tableAccount == nil {
  396. return nil
  397. }
  398. let realm = try! Realm()
  399. let results = realm.objects(tableAutomaticUpload.self).filter("account = %@ AND lock = true", tableAccount!.account)
  400. return Array(results)
  401. }
  402. func unlockAutomaticUpload(assetLocalIdentifier: String) {
  403. let tableAccount = self.getAccountActive()
  404. if tableAccount == nil {
  405. return
  406. }
  407. let realm = try! Realm()
  408. let result = realm.objects(tableAutomaticUpload.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 deleteAutomaticUpload(assetLocalIdentifier: String) {
  417. let tableAccount = self.getAccountActive()
  418. if tableAccount == nil {
  419. return
  420. }
  421. let realm = try! Realm()
  422. let result = realm.objects(tableAutomaticUpload.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 countAutomaticUpload(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<tableAutomaticUpload>
  436. if (session == nil) {
  437. results = realm.objects(tableAutomaticUpload.self).filter("account = %@", tableAccount!.account)
  438. } else {
  439. results = realm.objects(tableAutomaticUpload.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 {
  530. result?.permissions = permissions
  531. directoryID = result!.directoryID
  532. realm.add(result!, update: true)
  533. } else {
  534. let addDirectory = tableDirectory()
  535. addDirectory.account = tableAccount!.account
  536. directoryID = NSUUID().uuidString
  537. addDirectory.directoryID = directoryID
  538. addDirectory.permissions = permissions
  539. addDirectory.serverUrl = serverUrl
  540. realm.add(addDirectory, 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. let result = realm.objects(tableDirectory.self).filter("account = %@ AND directoryID = %@", tableAccount!.account, directoryID).first
  677. try! realm.write {
  678. if result != nil {
  679. result?.dateReadDirectory = NSDate()
  680. }
  681. }
  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 metadata
  872. }
  873. let autoUploadFileName = self.getAccountAutoUploadFileName()
  874. let autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  875. let realm = try! Realm()
  876. try! realm.write {
  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. }
  884. self.setDateReadDirectory(directoryID: metadata.directoryID)
  885. return tableMetadata.init(value: metadata)
  886. }
  887. func addMetadatas(_ metadatas: [tableMetadata], activeUrl: String, serverUrl: String) -> [tableMetadata] {
  888. let autoUploadFileName = self.getAccountAutoUploadFileName()
  889. let autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  890. var arrayMetadatas = [tableMetadata]()
  891. let realm = try! Realm()
  892. try! realm.write {
  893. for metadata in metadatas {
  894. if (metadata.realm == nil) {
  895. let metadataWithIcon = CCUtility.insertTypeFileIconName(metadata, serverUrl: serverUrl, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory)
  896. realm.add(metadataWithIcon!, update: true)
  897. } else {
  898. realm.add(metadata, update: true)
  899. }
  900. arrayMetadatas.append(tableMetadata.init(value: metadata))
  901. }
  902. }
  903. let directoryID = self.getDirectoryID(serverUrl)
  904. self.setDateReadDirectory(directoryID: directoryID)
  905. return arrayMetadatas
  906. }
  907. func deleteMetadata(predicate: NSPredicate, clearDateReadDirectoryID: String?) {
  908. let tableAccount = self.getAccountActive()
  909. if tableAccount == nil {
  910. return
  911. }
  912. let realm = try! Realm()
  913. let results = realm.objects(tableMetadata.self).filter(predicate)
  914. if clearDateReadDirectoryID == nil {
  915. for result in results {
  916. self.setDateReadDirectory(directoryID: result.directoryID)
  917. }
  918. } else {
  919. self.setDateReadDirectory(directoryID: clearDateReadDirectoryID!)
  920. }
  921. try! realm.write {
  922. realm.delete(results)
  923. }
  924. }
  925. func moveMetadata(fileName: String, directoryID: String, directoryIDTo: String) {
  926. let tableAccount = self.getAccountActive()
  927. if tableAccount == nil {
  928. return
  929. }
  930. let realm = try! Realm()
  931. let results = realm.objects(tableMetadata.self).filter("account = %@ AND fileName = %@ AND directoryID = %@", tableAccount!.account, fileName, directoryID)
  932. try! realm.write {
  933. for result in results {
  934. result.directoryID = directoryIDTo
  935. }
  936. }
  937. self.setDateReadDirectory(directoryID: directoryID)
  938. self.setDateReadDirectory(directoryID: directoryIDTo)
  939. }
  940. func updateMetadata(_ metadata: tableMetadata, activeUrl: String) -> tableMetadata {
  941. let autoUploadFileName = self.getAccountAutoUploadFileName()
  942. let autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  943. let serverUrl = self.getServerUrl(metadata.directoryID)
  944. let metadataWithIcon = CCUtility.insertTypeFileIconName(metadata, serverUrl: serverUrl, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory)
  945. let realm = try! Realm()
  946. try! realm.write {
  947. realm.add(metadataWithIcon!, update: true)
  948. }
  949. self.setDateReadDirectory(directoryID: metadata.directoryID)
  950. return tableMetadata.init(value: metadata)
  951. }
  952. func setMetadataSession(_ session: String?, sessionError: String?, sessionSelector: String?, sessionSelectorPost: String?, sessionTaskIdentifier: Int, sessionTaskIdentifierPlist: Int, predicate: NSPredicate) {
  953. let tableAccount = self.getAccountActive()
  954. if tableAccount == nil {
  955. return
  956. }
  957. let realm = try! Realm()
  958. let result = realm.objects(tableMetadata.self).filter(predicate).first
  959. if result != nil {
  960. try! realm.write {
  961. if session != nil {
  962. result?.session = session!
  963. }
  964. if sessionError != nil {
  965. result?.sessionError = sessionError!
  966. }
  967. if sessionSelector != nil {
  968. result?.sessionSelector = sessionSelector!
  969. }
  970. if sessionSelectorPost != nil {
  971. result?.sessionSelectorPost = sessionSelectorPost!
  972. }
  973. if sessionTaskIdentifier != Int(k_taskIdentifierNULL) {
  974. result?.sessionTaskIdentifier = sessionTaskIdentifier
  975. }
  976. if sessionTaskIdentifierPlist != Int(k_taskIdentifierNULL) {
  977. result?.sessionTaskIdentifierPlist = sessionTaskIdentifierPlist
  978. }
  979. }
  980. }
  981. // Update Date Read Directory
  982. if result != nil {
  983. self.setDateReadDirectory(directoryID: (result?.directoryID)!)
  984. }
  985. }
  986. func setMetadataFavorite(fileID: String, favorite: Bool) {
  987. let tableAccount = self.getAccountActive()
  988. if tableAccount == nil {
  989. return
  990. }
  991. let realm = try! Realm()
  992. let result = realm.objects(tableMetadata.self).filter("account = %@ AND fileID = %@", tableAccount!.account, fileID).first
  993. if result != nil {
  994. try! realm.write {
  995. result?.favorite = favorite
  996. }
  997. self.setDateReadDirectory(directoryID: result!.directoryID)
  998. }
  999. }
  1000. func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  1001. let tableAccount = self.getAccountActive()
  1002. if tableAccount == nil {
  1003. return nil
  1004. }
  1005. let realm = try! Realm()
  1006. let result = realm.objects(tableMetadata.self).filter(predicate).first
  1007. if result != nil {
  1008. return tableMetadata.init(value: result!)
  1009. } else {
  1010. return nil
  1011. }
  1012. }
  1013. func getMetadatas(predicate: NSPredicate, sorted: String?, ascending: Bool) -> [tableMetadata]? {
  1014. let tableAccount = self.getAccountActive()
  1015. if tableAccount == nil {
  1016. return nil
  1017. }
  1018. let realm = try! Realm()
  1019. let results : Results<tableMetadata>
  1020. if sorted == nil {
  1021. results = realm.objects(tableMetadata.self).filter(predicate)
  1022. } else {
  1023. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  1024. }
  1025. if (results.count > 0) {
  1026. return Array(convertMetadataToUnmanagedMetadata(results))
  1027. } else {
  1028. return nil
  1029. }
  1030. }
  1031. func getMetadataAtIndex(predicate: NSPredicate, sorted: String?, ascending: Bool, index: Int) -> tableMetadata? {
  1032. let tableAccount = self.getAccountActive()
  1033. if tableAccount == nil {
  1034. return nil
  1035. }
  1036. let realm = try! Realm()
  1037. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  1038. if (results.count > 0 && results.count > index) {
  1039. return tableMetadata.init(value: results[index])
  1040. } else {
  1041. return nil
  1042. }
  1043. }
  1044. func getMetadataFromFileName(_ fileName: String, directoryID: String) -> 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("account = %@ AND directoryID = %@ AND (fileName = %@ OR fileNameData = %@)", tableAccount!.account, directoryID, fileName, fileName).first
  1051. if result != nil {
  1052. return tableMetadata.init(value: result!)
  1053. } else {
  1054. return nil
  1055. }
  1056. }
  1057. func getTableMetadataDownload() -> [tableMetadata]? {
  1058. let tableAccount = self.getAccountActive()
  1059. if tableAccount == nil {
  1060. return nil
  1061. }
  1062. 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)
  1063. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1064. }
  1065. func getTableMetadataDownloadWWan() -> [tableMetadata]? {
  1066. let tableAccount = self.getAccountActive()
  1067. if tableAccount == nil {
  1068. return nil
  1069. }
  1070. let predicate = NSPredicate(format: "account = %@ AND session = %@ AND (sessionTaskIdentifier != %i OR sessionTaskIdentifierPlist != %i)", tableAccount!.account, k_download_session_wwan, k_taskIdentifierDone, k_taskIdentifierDone)
  1071. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1072. }
  1073. func getTableMetadataUpload() -> [tableMetadata]? {
  1074. let tableAccount = self.getAccountActive()
  1075. if tableAccount == nil {
  1076. return nil
  1077. }
  1078. 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)
  1079. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1080. }
  1081. func getTableMetadataUploadWWan() -> [tableMetadata]? {
  1082. let tableAccount = self.getAccountActive()
  1083. if tableAccount == nil {
  1084. return nil
  1085. }
  1086. let predicate = NSPredicate(format: "account = %@ AND session = %@ AND (sessionTaskIdentifier != %i OR sessionTaskIdentifierPlist != %i)", tableAccount!.account, k_upload_session_wwan, k_taskIdentifierDone, k_taskIdentifierDone)
  1087. return self.getMetadatas(predicate: predicate, sorted: nil, ascending: false)
  1088. }
  1089. func getTableMetadatasPhotos(serverUrl: String) -> [tableMetadata]? {
  1090. let tableAccount = self.getAccountActive()
  1091. if tableAccount == nil {
  1092. return nil
  1093. }
  1094. let realm = try! Realm()
  1095. let sorted = CCUtility.getOrderSettings()
  1096. let ascending = CCUtility.getAscendingSettings()
  1097. var recordsPhotosAutoUpload = [tableMetadata]()
  1098. let directories = self.getTablesDirectory(predicate: NSPredicate(format: "account = %@ AND serverUrl BEGINSWITH %@", tableAccount!.account, serverUrl), sorted: "serverUrl", ascending: true)
  1099. if directories != nil {
  1100. for directory in directories! {
  1101. 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)
  1102. let metadatas = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted!, ascending: ascending)
  1103. if metadatas.count > 0 {
  1104. for metadata in metadatas {
  1105. recordsPhotosAutoUpload.append(tableMetadata.init(value: metadata))
  1106. }
  1107. }
  1108. }
  1109. }
  1110. if recordsPhotosAutoUpload.count > 0 {
  1111. return Array(recordsPhotosAutoUpload)
  1112. } else {
  1113. return nil
  1114. }
  1115. }
  1116. func convertMetadataToUnmanagedMetadata(_ metadatas: Results<tableMetadata>) -> [tableMetadata] {
  1117. var unmanageMetadatas = [tableMetadata]()
  1118. for metadata in metadatas {
  1119. unmanageMetadatas.append(tableMetadata.init(value: metadata))
  1120. }
  1121. return unmanageMetadatas
  1122. }
  1123. //MARK: -
  1124. //MARK: Table Share
  1125. func addShareLink(_ share: String, fileName: String, serverUrl: String) -> [String:String]? {
  1126. let tableAccount = self.getAccountActive()
  1127. if tableAccount == nil {
  1128. return nil
  1129. }
  1130. let realm = try! Realm()
  1131. // Verify if exists
  1132. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", tableAccount!.account, fileName, serverUrl).first
  1133. if result != nil {
  1134. try! realm.write {
  1135. result?.shareLink = share
  1136. }
  1137. } else {
  1138. // Add new record
  1139. try! realm.write {
  1140. let addShare = tableShare()
  1141. addShare.account = tableAccount!.account
  1142. addShare.fileName = fileName
  1143. addShare.serverUrl = serverUrl
  1144. addShare.shareLink = share
  1145. realm.add(addShare)
  1146. }
  1147. }
  1148. return ["\(serverUrl)\(fileName)" : share]
  1149. }
  1150. func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String) -> [String:String]? {
  1151. let tableAccount = self.getAccountActive()
  1152. if tableAccount == nil {
  1153. return nil
  1154. }
  1155. let realm = try! Realm()
  1156. // Verify if exists
  1157. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", tableAccount!.account, fileName, serverUrl).first
  1158. if result != nil {
  1159. try! realm.write {
  1160. result?.shareUserAndGroup = share
  1161. }
  1162. } else {
  1163. // Add new record
  1164. try! realm.write {
  1165. let addShare = tableShare()
  1166. addShare.account = tableAccount!.account
  1167. addShare.fileName = fileName
  1168. addShare.serverUrl = serverUrl
  1169. addShare.shareUserAndGroup = share
  1170. realm.add(addShare)
  1171. }
  1172. }
  1173. return ["\(serverUrl)\(fileName)" : share]
  1174. }
  1175. func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: [String:String], sharesUserAndGroup: [String:String]) -> [Any]? {
  1176. let tableAccount = self.getAccountActive()
  1177. if tableAccount == nil {
  1178. return nil
  1179. }
  1180. var sharesLink = sharesLink
  1181. var sharesUserAndGroup = sharesUserAndGroup
  1182. let realm = try! Realm()
  1183. let results = realm.objects(tableShare.self).filter("account = %@ AND (shareLink CONTAINS %@ OR shareUserAndGroup CONTAINS %@)", tableAccount!.account, share, share)
  1184. if (results.count > 0) {
  1185. let result = results[0]
  1186. realm.beginWrite()
  1187. if (result.shareLink.contains(share)) {
  1188. result.shareLink = ""
  1189. }
  1190. if (result.shareUserAndGroup.contains(share)) {
  1191. var shares : [String] = result.shareUserAndGroup.components(separatedBy: ",")
  1192. if let index = shares.index(of:share) {
  1193. shares.remove(at: index)
  1194. }
  1195. result.shareUserAndGroup = shares.joined(separator: ",")
  1196. }
  1197. if (result.shareLink.characters.count > 0) {
  1198. sharesLink.updateValue(result.shareLink, forKey:"\(serverUrl)\(fileName)")
  1199. } else {
  1200. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  1201. }
  1202. if (result.shareUserAndGroup.characters.count > 0) {
  1203. sharesUserAndGroup.updateValue(result.shareUserAndGroup, forKey:"\(serverUrl)\(fileName)")
  1204. } else {
  1205. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  1206. }
  1207. if (result.shareLink.characters.count == 0 && result.shareUserAndGroup.characters.count == 0) {
  1208. realm.delete(result)
  1209. }
  1210. try! realm.commitWrite()
  1211. }
  1212. return [sharesLink, sharesUserAndGroup]
  1213. }
  1214. func removeShareActiveAccount() {
  1215. let tableAccount = self.getAccountActive()
  1216. if tableAccount == nil {
  1217. return
  1218. }
  1219. let realm = try! Realm()
  1220. let results = realm.objects(tableShare.self).filter("account = %@", tableAccount!.account)
  1221. try! realm.write {
  1222. realm.delete(results)
  1223. }
  1224. }
  1225. func updateShare(_ items: [String:OCSharedDto], activeUrl: String) -> [Any]? {
  1226. let tableAccount = self.getAccountActive()
  1227. if tableAccount == nil {
  1228. return nil
  1229. }
  1230. var sharesLink = [String:String]()
  1231. var sharesUserAndGroup = [String:String]()
  1232. self.removeShareActiveAccount()
  1233. var itemsLink = [OCSharedDto]()
  1234. var itemsUsersAndGroups = [OCSharedDto]()
  1235. for (_, itemOCSharedDto) in items {
  1236. if (itemOCSharedDto.shareType == Int(shareTypeLink.rawValue)) {
  1237. itemsLink.append(itemOCSharedDto)
  1238. }
  1239. if (itemOCSharedDto.shareWith.characters.count > 0 && (itemOCSharedDto.shareType == Int(shareTypeUser.rawValue) || itemOCSharedDto.shareType == Int(shareTypeGroup.rawValue) || itemOCSharedDto.shareType == Int(shareTypeRemote.rawValue) )) {
  1240. itemsUsersAndGroups.append(itemOCSharedDto)
  1241. }
  1242. }
  1243. // Manage sharesLink
  1244. for itemOCSharedDto in itemsLink {
  1245. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(itemOCSharedDto.path!)"
  1246. let fileName = NSString(string: fullPath).lastPathComponent
  1247. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - fileName.characters.count - 1))
  1248. if serverUrl.hasSuffix("/") {
  1249. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.characters.count - 1))
  1250. }
  1251. if itemOCSharedDto.idRemoteShared > 0 {
  1252. let sharesLinkReturn = self.addShareLink("\(itemOCSharedDto.idRemoteShared)", fileName: fileName, serverUrl: serverUrl)
  1253. if sharesLinkReturn != nil {
  1254. for (key,value) in sharesLinkReturn! {
  1255. sharesLink.updateValue(value, forKey:key)
  1256. }
  1257. }
  1258. }
  1259. }
  1260. // Manage sharesUserAndGroup
  1261. var paths = [String:[String]]()
  1262. for itemOCSharedDto in itemsUsersAndGroups {
  1263. if paths[itemOCSharedDto.path] != nil {
  1264. var share : [String] = paths[itemOCSharedDto.path]!
  1265. share.append("\(itemOCSharedDto.idRemoteShared)")
  1266. paths[itemOCSharedDto.path] = share
  1267. } else {
  1268. paths[itemOCSharedDto.path] = ["\(itemOCSharedDto.idRemoteShared)"]
  1269. }
  1270. }
  1271. for (path, idsRemoteSharedArray) in paths {
  1272. let idsRemoteShared = idsRemoteSharedArray.joined(separator: ",")
  1273. print("[LOG] share \(String(describing: idsRemoteShared))")
  1274. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(path)"
  1275. let fileName = NSString(string: fullPath).lastPathComponent
  1276. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.characters.count - fileName.characters.count - 1))
  1277. if serverUrl.hasSuffix("/") {
  1278. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.characters.count - 1))
  1279. }
  1280. let sharesUserAndGroupReturn = self.addShareUserAndGroup(idsRemoteShared, fileName: fileName, serverUrl: serverUrl)
  1281. if sharesUserAndGroupReturn != nil {
  1282. for (key,value) in sharesUserAndGroupReturn! {
  1283. sharesUserAndGroup.updateValue(value, forKey:key)
  1284. }
  1285. }
  1286. }
  1287. return [sharesLink, sharesUserAndGroup]
  1288. }
  1289. func getShares() -> [Any]? {
  1290. let tableAccount = self.getAccountActive()
  1291. if tableAccount == nil {
  1292. return nil
  1293. }
  1294. var sharesLink = [String:String]()
  1295. var sharesUserAndGroup = [String:String]()
  1296. let realm = try! Realm()
  1297. let results = realm.objects(tableShare.self).filter("account = %@", tableAccount!.account)
  1298. for resultShare in results {
  1299. if (resultShare.shareLink.characters.count > 0) {
  1300. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1301. }
  1302. if (resultShare.shareUserAndGroup.characters.count > 0) {
  1303. sharesUserAndGroup = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1304. }
  1305. }
  1306. return [sharesLink, sharesUserAndGroup]
  1307. }
  1308. //MARK: -
  1309. //MARK: Migrate func
  1310. func addTableAccountFromCoredata(_ table: TableAccount) {
  1311. let realm = try! Realm()
  1312. let results = realm.objects(tableAccount.self).filter("account = %@", table.account!)
  1313. if (results.count == 0) {
  1314. try! realm.write {
  1315. let addAccount = tableAccount()
  1316. addAccount.account = table.account!
  1317. if table.active == 1 {
  1318. addAccount.active = true
  1319. }
  1320. if table.cameraUpload == 1 {
  1321. addAccount.autoUpload = true
  1322. }
  1323. if table.cameraUploadBackground == 1 {
  1324. addAccount.autoUploadBackground = true
  1325. }
  1326. if table.cameraUploadCreateSubfolder == 1 {
  1327. addAccount.autoUploadCreateSubfolder = true
  1328. }
  1329. if table.cameraUploadDatePhoto != nil {
  1330. addAccount.autoUploadDatePhoto = table.cameraUploadDatePhoto! as NSDate
  1331. }
  1332. if table.cameraUploadDateVideo != nil {
  1333. addAccount.autoUploadDateVideo = table.cameraUploadDateVideo! as NSDate
  1334. }
  1335. if table.cameraUploadFolderName != nil {
  1336. addAccount.autoUploadFileName = table.cameraUploadFolderName!
  1337. }
  1338. if table.cameraUploadFolderPath != nil {
  1339. addAccount.autoUploadDirectory = table.cameraUploadFolderPath!
  1340. }
  1341. if table.cameraUploadFull == 1 {
  1342. addAccount.autoUploadFull = true
  1343. }
  1344. if table.cameraUploadPhoto == 1 {
  1345. addAccount.autoUploadPhoto = true
  1346. }
  1347. if table.cameraUploadVideo == 1 {
  1348. addAccount.autoUploadVideo = true
  1349. }
  1350. if table.cameraUploadWWAnPhoto == 1 {
  1351. addAccount.autoUploadWWAnPhoto = true
  1352. }
  1353. if table.cameraUploadWWAnVideo == 1 {
  1354. addAccount.autoUploadWWAnVideo = true
  1355. }
  1356. addAccount.password = table.password!
  1357. addAccount.url = table.url!
  1358. addAccount.user = table.user!
  1359. realm.add(addAccount)
  1360. }
  1361. }
  1362. }
  1363. func addTableDirectoryFromCoredata(_ table: TableDirectory) {
  1364. let realm = try! Realm()
  1365. let results = realm.objects(tableDirectory.self).filter("directoryID = %@", table.directoryID!)
  1366. if (results.count == 0) {
  1367. try! realm.write {
  1368. let addDirectory = tableDirectory()
  1369. addDirectory.account = table.account!
  1370. addDirectory.directoryID = table.directoryID!
  1371. addDirectory.etag = table.rev!
  1372. if table.favorite == 1 {
  1373. addDirectory.favorite = true
  1374. }
  1375. addDirectory.fileID = table.fileID!
  1376. if table.lock == 1 {
  1377. addDirectory.lock = true
  1378. }
  1379. addDirectory.permissions = table.permissions!
  1380. addDirectory.serverUrl = table.serverUrl!
  1381. realm.add(addDirectory)
  1382. }
  1383. }
  1384. }
  1385. func addTableLocalFileFromCoredata(_ table: TableLocalFile) {
  1386. let realm = try! Realm()
  1387. let results = realm.objects(tableLocalFile.self).filter("fileID = %@", table.fileID!)
  1388. if (results.count == 0) {
  1389. try! realm.write {
  1390. let addLocalFile = tableLocalFile()
  1391. addLocalFile.account = table.account!
  1392. addLocalFile.date = table.date! as NSDate
  1393. addLocalFile.etag = table.rev!
  1394. if table.exifDate != nil {
  1395. addLocalFile.exifDate = table.exifDate! as NSDate
  1396. }
  1397. addLocalFile.exifLatitude = table.exifLatitude!
  1398. addLocalFile.exifLongitude = table.exifLongitude!
  1399. if table.favorite == 1 {
  1400. addLocalFile.favorite = true
  1401. }
  1402. addLocalFile.fileID = table.fileID!
  1403. addLocalFile.fileName = table.fileName!
  1404. addLocalFile.fileNamePrint = table.fileNamePrint!
  1405. addLocalFile.size = table.size as! Double
  1406. realm.add(addLocalFile)
  1407. }
  1408. }
  1409. }
  1410. //MARK: -
  1411. }