Welcome to mirror list, hosted at ThFree Co, Russian Federation.

NCDataSource.swift « Data « iOSClient - github.com/nextcloud/ios.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: df9660aa29c3e99ee6f4c84c85a63ec0a345c4b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//
//  NCDataSource.swift
//  Nextcloud
//
//  Created by Marino Faggiana on 06/09/2020.
//  Copyright © 2020 Marino Faggiana. All rights reserved.
//
//  Author Marino Faggiana <marino.faggiana@nextcloud.com>
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import UIKit
import NCCommunication

class NCDataSource: NSObject {

    var metadatas: [tableMetadata] = []
    var metadatasForSection: [NCMetadataForSection] = []

    var directory: tableDirectory?
    var groupByField: String = ""

    private var sectionsValue: [String] = []
    private var providers: [NCCSearchProvider]?
    private var searchResults: [NCCSearchResult]?
    private var shares: [tableShare] = []
    private var localFiles: [tableLocalFile] = []

    private var ascending: Bool = true
    private var sort: String = ""
    private var directoryOnTop: Bool = true
    private var favoriteOnTop: Bool = true
    private var filterLivePhoto: Bool = true

    override init() {
        super.init()
    }

    init(metadatas: [tableMetadata], account: String, directory: tableDirectory? = nil, sort: String? = "none", ascending: Bool? = false, directoryOnTop: Bool? = true, favoriteOnTop: Bool? = true, filterLivePhoto: Bool? = true, groupByField: String = "name", providers: [NCCSearchProvider]? = nil, searchResults: [NCCSearchResult]? = nil) {
        super.init()

        self.metadatas = metadatas
        self.directory = directory
        self.shares = NCManageDatabase.shared.getTableShares(account: account)
        self.localFiles = NCManageDatabase.shared.getTableLocalFile(account: account)
        self.sort = sort ?? "none"
        self.ascending = ascending ?? false
        self.directoryOnTop = directoryOnTop ?? true
        self.favoriteOnTop = favoriteOnTop ?? true
        self.filterLivePhoto = filterLivePhoto ?? true
        self.groupByField = groupByField
        // unified search
        self.providers = providers
        self.searchResults = searchResults

        createSections()
    }

    // MARK: -

    func clearDataSource() {

        self.metadatas.removeAll()
        self.metadatasForSection.removeAll()
        self.directory = nil
        self.sectionsValue.removeAll()
        self.providers = nil
        self.searchResults = nil
        self.shares.removeAll()
        self.localFiles.removeAll()
    }

    func clearDirectory() {

        self.directory = nil
    }

    func changeGroupByField(_ groupByField: String) {

        self.groupByField = groupByField
        print("DATASOURCE: set group by filed " + groupByField)
        self.metadatasForSection.removeAll()
        self.sectionsValue.removeAll()
        print("DATASOURCE: remove  all sections")

        createSections()
    }

    func addSection(metadatas: [tableMetadata], searchResult: NCCSearchResult?) {

        self.metadatas.append(contentsOf: metadatas)

        if let searchResult = searchResult {
            self.searchResults?.append(searchResult)
        }

        createSections()
    }

    internal func createSections() {

        // get all Section
        for metadata in self.metadatas {
            // skipped livePhoto
            if filterLivePhoto && metadata.livePhoto && metadata.ext == "mov" {
                continue
            }
            let section = NSLocalizedString(self.getSectionValue(metadata: metadata), comment: "")
            if !self.sectionsValue.contains(section) {
                self.sectionsValue.append(section)
            }
        }

        // Unified search
        if let providers = self.providers, !providers.isEmpty {
            let sectionsDictionary = ThreadSafeDictionary<String,Int>()
            for section in self.sectionsValue {
                if let provider = providers.filter({ $0.id == section}).first {
                    sectionsDictionary[section] = provider.order
                }
            }
            self.sectionsValue.removeAll()
            let sectionsDictionarySorted = sectionsDictionary.sorted(by: { $0.value < $1.value } )
            for section in sectionsDictionarySorted {
                if section.key == NCGlobal.shared.appName {
                    self.sectionsValue.insert(section.key, at: 0)
                } else {
                    self.sectionsValue.append(section.key)
                }
            }

        } else {

        // normal
            let directory = NSLocalizedString("directory", comment: "").lowercased().firstUppercased
            self.sectionsValue = self.sectionsValue.sorted {
                if directoryOnTop && $0 == directory {
                    return true
                } else if directoryOnTop && $1 == directory {
                    return false
                }
                if self.ascending {
                    return $0 < $1
                } else {
                    return $0 > $1
                }
            }
        }

        for sectionValue in self.sectionsValue {
            if !existsMetadataForSection(sectionValue: sectionValue) {
                print("DATASOURCE: create metadata for section: " + sectionValue)
                createMetadataForSection(sectionValue: sectionValue)
            }
        }
    }

    internal func createMetadataForSection(sectionValue: String) {

        var searchResult: NCCSearchResult?
        if let providers = self.providers, !providers.isEmpty, let searchResults = self.searchResults {
            searchResult = searchResults.filter({ $0.id == sectionValue}).first
        }
        let metadatas = self.metadatas.filter({ getSectionValue(metadata: $0) == sectionValue})
        let metadataForSection = NCMetadataForSection.init(sectionValue: sectionValue,
                                                            metadatas: metadatas,
                                                            shares: self.shares,
                                                            localFiles: self.localFiles,
                                                            lastSearchResult: searchResult,
                                                            sort: self.sort,
                                                            ascending: self.ascending,
                                                            directoryOnTop: self.directoryOnTop,
                                                            favoriteOnTop: self.favoriteOnTop,
                                                            filterLivePhoto: self.filterLivePhoto)
        metadatasForSection.append(metadataForSection)
    }

    func getMetadataSourceForAllSections() -> [tableMetadata] {

        var metadatas: [tableMetadata] = []

        for section in metadatasForSection {
            metadatas.append(contentsOf: section.metadatas)
        }

        return metadatas
    }

    // MARK: -

    @discardableResult
    func appendMetadatasToSection(_ metadatas: [tableMetadata], metadataForSection: NCMetadataForSection, lastSearchResult: NCCSearchResult) -> [IndexPath] {
        
        guard let sectionIndex =  getSectionIndex(metadataForSection.sectionValue) else { return [] }
        var indexPaths: [IndexPath] = []

        self.metadatas.append(contentsOf: metadatas)
        metadataForSection.metadatas.append(contentsOf: metadatas)
        metadataForSection.lastSearchResult = lastSearchResult
        metadataForSection.createMetadatas()

        for metadata in metadatas {
            if let rowIndex = metadataForSection.metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) {
                indexPaths.append(IndexPath(row: rowIndex, section: sectionIndex))
            }
        }

        return indexPaths
    }

    @discardableResult
    func addMetadata(_ metadata: tableMetadata) -> (indexPath: IndexPath?, sameSections: Bool) {

        let numberOfSections = self.numberOfSections()
        let sectionValue = getSectionValue(metadata: metadata)

        // ADD metadatasSource
        if let rowIndex = self.metadatas.firstIndex(where: {$0.fileNameView == metadata.fileNameView || $0.ocId == metadata.ocId}) {
            self.metadatas[rowIndex] = metadata
        } else {
            self.metadatas.append(metadata)
        }

        // ADD metadataForSection
        if let sectionIndex = getSectionIndex(sectionValue), let metadataForSection = getMetadataForSection(sectionIndex) {
            if let rowIndex = metadataForSection.metadatas.firstIndex(where: {$0.fileNameView == metadata.fileNameView || $0.ocId == metadata.ocId}) {
                metadataForSection.metadatas[rowIndex] = metadata
                return (IndexPath(row: rowIndex, section: sectionIndex), self.isSameNumbersOfSections(numberOfSections: numberOfSections))
            } else {
                metadataForSection.metadatas.append(metadata)
                metadataForSection.createMetadatas()
                if let rowIndex = metadataForSection.metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) {
                    return (IndexPath(row: rowIndex, section: sectionIndex), self.isSameNumbersOfSections(numberOfSections: numberOfSections))
                }
                return (nil, self.isSameNumbersOfSections(numberOfSections: numberOfSections))
            }
        } else {
            // NEW section
            createSections()
            // get IndexPath of new section
            if let sectionIndex = getSectionIndex(sectionValue), let metadataForSection = getMetadataForSection(sectionIndex) {
                if let rowIndex = metadataForSection.metadatas.firstIndex(where: {$0.fileNameView == metadata.fileNameView || $0.ocId == metadata.ocId}) {
                    return (IndexPath(row: rowIndex, section: sectionIndex), self.isSameNumbersOfSections(numberOfSections: numberOfSections))
                }
            }
        }

        return (nil, self.isSameNumbersOfSections(numberOfSections: numberOfSections))
    }

    func deleteMetadata(ocId: String) -> (indexPath: IndexPath?, sameSections: Bool) {

        let numberOfSections = self.numberOfSections()
        var indexPathReturn: IndexPath?
        var sectionValue = ""

        // DELETE metadataForSection (IMPORTANT FIRST)
        let (indexPath, metadataForSection) = self.getIndexPathMetadata(ocId: ocId)
        if let indexPath = indexPath, let metadataForSection = metadataForSection, indexPath.row < metadataForSection.metadatas.count {
            metadataForSection.metadatas.remove(at: indexPath.row)
            if metadataForSection.metadatas.count == 0 {
                // REMOVE sectionsValue / metadatasForSection
                sectionValue = metadataForSection.sectionValue
                if let sectionIndex = getSectionIndex(sectionValue) {
                    self.sectionsValue.remove(at: sectionIndex)
                }
                if let index = getIndexMetadatasForSection(sectionValue) {
                    self.metadatasForSection.remove(at: index)
                }
            } else {
                metadataForSection.createMetadatas()
            }
            indexPathReturn = indexPath
        } else { return (nil, false) }

        // DELETE metadatasSource (IMPORTANT LAST)
        if let rowIndex = self.metadatas.firstIndex(where: {$0.ocId == ocId}) {
            self.metadatas.remove(at: rowIndex)
        }

        return (indexPathReturn, self.isSameNumbersOfSections(numberOfSections: numberOfSections))
    }

    @discardableResult
    func reloadMetadata(ocId: String, ocIdTemp: String? = nil) -> (indexPath: IndexPath?, sameSections: Bool) {

        let numberOfSections = self.numberOfSections()
        var ocIdSearch = ocId

        guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return (nil, self.isSameNumbersOfSections(numberOfSections: numberOfSections)) }

        if let ocIdTemp = ocIdTemp {
            ocIdSearch = ocIdTemp
        }

        // UPDATE metadataForSection (IMPORTANT FIRST)
        let (indexPath, metadataForSection) = self.getIndexPathMetadata(ocId: ocIdSearch)
        if let indexPath = indexPath, let metadataForSection = metadataForSection {
            metadataForSection.metadatas[indexPath.row] = metadata
            metadataForSection.createMetadatas()
        }

        // UPDATE metadatasSource (IMPORTANT LAST)
        if let rowIndex = self.metadatas.firstIndex(where: {$0.ocId == ocIdSearch}) {
            self.metadatas[rowIndex] = metadata
        }

        let result = self.getIndexPathMetadata(ocId: ocId)
        return (result.indexPath, self.isSameNumbersOfSections(numberOfSections: numberOfSections))
    }

    // MARK: -

    func getIndexPathMetadata(ocId: String) -> (indexPath: IndexPath?, metadataForSection: NCMetadataForSection?) {
        guard let metadata = self.metadatas.filter({ $0.ocId == ocId}).first else { return (nil, nil) }
        let sectionValue = getSectionValue(metadata: metadata)
        guard let sectionIndex = getSectionIndex(sectionValue), let metadataForSection = getMetadataForSection(sectionValue), let rowIndex = metadataForSection.metadatas.firstIndex(where: {$0.ocId == ocId}) else { return (nil, nil) }
        return (IndexPath(row: rowIndex, section: sectionIndex), metadataForSection)
    }

    func isSameNumbersOfSections(numberOfSections: Int) -> Bool {
        guard self.metadatasForSection.count > 0 else { return false }
        return numberOfSections == self.numberOfSections()
    }

    func numberOfSections() -> Int {
        guard self.sectionsValue.count > 0 else { return 1 }
        return self.sectionsValue.count
    }
    
    func numberOfItemsInSection(_ section: Int) -> Int {
        guard self.sectionsValue.count > 0 && self.metadatas.count > 0, let metadataForSection = getMetadataForSection(section) else { return 0}
        return metadataForSection.metadatas.count
    }

    func cellForItemAt(indexPath: IndexPath) -> tableMetadata? {
        guard metadatasForSection.count > 0 && indexPath.section < metadatasForSection.count, let metadataForSection = getMetadataForSection(indexPath.section), indexPath.row < metadataForSection.metadatas.count else { return nil }
        return metadataForSection.metadatas[indexPath.row]
    }

    func getSectionValue(indexPath: IndexPath) -> String {
        guard metadatasForSection.count > 0 , let metadataForSection = self.getMetadataForSection(indexPath.section) else { return ""}
        return metadataForSection.sectionValue
    }

    func getSectionValueLocalization(indexPath: IndexPath) -> String {
        guard metadatasForSection.count > 0 , let metadataForSection = self.getMetadataForSection(indexPath.section) else { return ""}
        if let searchResults = self.searchResults, let searchResult = searchResults.filter({ $0.id == metadataForSection.sectionValue}).first {
            return searchResult.name
        }
        return metadataForSection.sectionValue
    }

    func getFooterInformationAllMetadatas() -> (directories: Int, files: Int, size: Int64) {

        var directories: Int = 0
        var files: Int = 0
        var size: Int64 = 0

        for metadataForSection in metadatasForSection {
            directories += metadataForSection.numDirectory
            files += metadataForSection.numFile
            size += metadataForSection.totalSize
        }

        return (directories, files, size)
    }

    // MARK: -

    internal func getSectionValue(metadata: tableMetadata) -> String {

        switch self.groupByField {
        case "name":
            return NSLocalizedString(metadata.name, comment: "")
        case "classFile":
            return NSLocalizedString(metadata.classFile, comment: "").lowercased().firstUppercased
        default:
            return NSLocalizedString(metadata.classFile, comment: "")
        }
    }

    internal func getIndexMetadatasForSection(_ sectionValue: String) -> Int? {
        return self.metadatasForSection.firstIndex(where: {$0.sectionValue == sectionValue })
    }

    internal func getSectionIndex(_ sectionValue: String) -> Int? {
         return self.sectionsValue.firstIndex(where: {$0 == sectionValue })
    }

    internal func existsMetadataForSection(sectionValue: String) -> Bool {
        return !self.metadatasForSection.filter({ $0.sectionValue == sectionValue }).isEmpty
    }

    internal func getMetadataForSection(_ section: Int) -> NCMetadataForSection? {
        guard section < sectionsValue.count, let metadataForSection = self.metadatasForSection.filter({ $0.sectionValue == sectionsValue[section]}).first else { return nil }
        return metadataForSection
    }

    internal func getMetadataForSection(_ sectionValue: String) -> NCMetadataForSection? {
        guard let metadataForSection = self.metadatasForSection.filter({ $0.sectionValue == sectionValue }).first else { return nil }
        return metadataForSection
    }
}

// MARK: -

class NCMetadataForSection: NSObject {

    var sectionValue: String
    var metadatas: [tableMetadata]
    var shares: [tableShare]
    var localFiles: [tableLocalFile]
    var lastSearchResult: NCCSearchResult?
    var unifiedSearchInProgress: Bool = false

    private var sort : String
    private var ascending: Bool
    private var directoryOnTop: Bool
    private var favoriteOnTop: Bool
    private var filterLivePhoto: Bool

    private var metadatasSorted: [tableMetadata] = []
    private var metadatasFavoriteDirectory: [tableMetadata] = []
    private var metadatasFavoriteFile: [tableMetadata] = []
    private var metadatasDirectory: [tableMetadata] = []
    private var metadatasFile: [tableMetadata] = []

    public var numDirectory: Int = 0
    public var numFile: Int = 0
    public var totalSize: Int64 = 0
    public let metadataShare  = ThreadSafeDictionary<String,tableShare>()
    public var metadataOffLine: [String] = []
    public var directories: [tableDirectory]?

    init(sectionValue: String, metadatas: [tableMetadata], shares: [tableShare], localFiles: [tableLocalFile], lastSearchResult: NCCSearchResult?, sort: String, ascending: Bool, directoryOnTop: Bool, favoriteOnTop: Bool, filterLivePhoto: Bool) {

        self.sectionValue = sectionValue
        self.metadatas = metadatas
        self.shares = shares
        self.localFiles = localFiles
        self.lastSearchResult = lastSearchResult
        self.sort = sort
        self.ascending = ascending
        self.directoryOnTop = directoryOnTop
        self.favoriteOnTop = favoriteOnTop
        self.filterLivePhoto = filterLivePhoto

        super.init()

        createMetadatas()
    }

    func createMetadatas() {

        // Clear
        //
        metadatasSorted.removeAll()
        metadatasFavoriteDirectory.removeAll()
        metadatasFavoriteFile.removeAll()
        metadatasDirectory.removeAll()
        metadatasFile.removeAll()
        metadataShare.removeAll()
        metadataOffLine.removeAll()

        numDirectory = 0
        numFile = 0
        totalSize = 0

        var ocIds: [String] = []

        // Metadata order
        //
        if sort != "none" && sort != "" {
            metadatasSorted = metadatas.sorted {

                switch sort {
                case "date":
                    if ascending {
                        return ($0.date as Date) < ($1.date as Date)
                    } else {
                        return ($0.date as Date) > ($1.date as Date)
                    }
                case "size":
                    if ascending {
                        return $0.size < $1.size
                    } else {
                        return $0.size > $1.size
                    }
                default:
                    if ascending {
                        return $0.fileNameView.lowercased() < $1.fileNameView.lowercased()
                    } else {
                        return $0.fileNameView.lowercased() > $1.fileNameView.lowercased()
                    }
                }
            }
        } else {
            metadatasSorted = metadatas
        }

        // Initialize datasource
        //
        for metadata in metadatasSorted {

            // skipped the root file
            if metadata.fileName == "." || metadata.serverUrl == ".." {
                continue
            }

            // skipped livePhoto
            if filterLivePhoto && metadata.livePhoto && metadata.ext == "mov" {
                continue
            }

            // share
            if let share = self.shares.filter({ $0.serverUrl == metadata.serverUrl && $0.fileName == metadata.fileName }).first {
                metadataShare[metadata.ocId] = share
            }

            // Organized the metadata
            if metadata.favorite && favoriteOnTop {
                if metadata.directory {
                    metadatasFavoriteDirectory.append(metadata)
                } else {
                    metadatasFavoriteFile.append(metadata)
                }
            } else if  metadata.directory && directoryOnTop {
                metadatasDirectory.append(metadata)
            } else {
                metadatasFile.append(metadata)
            }

            //Info
            if metadata.directory {
                ocIds.append(metadata.ocId)
                numDirectory += 1
            } else {
                numFile += 1
                totalSize += metadata.size
            }
        }

        directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "ocId IN %@", ocIds), sorted: "serverUrl", ascending: true)

        metadatas.removeAll()

        // Struct view : favorite dir -> favorite file -> directory -> files
        metadatas += metadatasFavoriteDirectory
        metadatas += metadatasFavoriteFile
        metadatas += metadatasDirectory
        metadatas += metadatasFile
    }
}