-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
RemoteStorage.swift
909 lines (797 loc) · 32.3 KB
/
RemoteStorage.swift
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//
// RemoteStorage.swift
// ccViewer
//
// Created by rei6 on 2019/03/09.
// Copyright © 2019 lithium03. All rights reserved.
//
import Foundation
import os.log
import CoreData
public enum CloudStorages: CaseIterable {
case Local
case Files
case DropBox
case GoogleDrive
case OneDrive
case pCloud
case WebDAV
case CryptCarotDAV
case CryptRclone
case Cryptomator
}
public protocol RemoteStorage {
func auth(onFinish: ((Bool) -> Void)?) -> Void
func logout()
func list(fileId: String, onFinish: (() -> Void)?)
func list(path: String, onFinish: (() -> Void)?)
func read(fileId: String, start: Int64?, length: Int64?, onFinish: ((Data?) -> Void)?)
func mkdir(parentId: String, newname: String, onFinish: ((String?)->Void)?)
func delete(fileId: String, onFinish: ((Bool)->Void)?)
func rename(fileId: String, newname: String, onFinish: ((String?)->Void)?)
func chagetime(fileId: String, newdate: Date, onFinish: ((String?)->Void)?)
func move(fileId: String, fromParent: String, toParent: String, onFinish: ((String?)->Void)?)
func upload(parentId: String, sessionId: String, uploadname: String, target: URL, onFinish: ((String?)->Void)?)
func get(fileId: String) -> RemoteItem?
func get(path: String) -> RemoteItem?
func config() -> String
func getStorageType() -> CloudStorages
func cancel()
var rootName: String { get }
}
public class RemoteItem {
public let storage: String
public let id: String
public let name: String
public let ext: String
public let size: Int64
public let path: String
public let parent: String
public let isFolder: Bool
public let mDate: Date?
public let cDate: Date?
public let substart: Int64
public let subend: Int64
public let subid: String?
let service: RemoteStorage
init?(storage: String, id: String) {
self.storage = storage
self.id = id
guard let service = CloudFactory.shared[storage] else {
return nil
}
self.service = service
if id == "" {
self.name = ""
self.ext = ""
self.size = 0
self.path = "\(storage):/"
self.parent = ""
self.isFolder = true
self.mDate = nil
self.cDate = nil
self.substart = -1
self.subend = -1
self.subid = nil
}
else {
let item1 = CloudFactory.shared.data.getData(storage: storage, fileId: id)
guard let origin = item1 else {
return nil
}
guard let name = origin.name else {
return nil
}
self.name = name
self.ext = origin.ext?.lowercased() ?? ""
self.size = origin.size
guard let path = origin.path else {
return nil
}
self.path = path
guard let parent = origin.parent else {
return nil
}
self.isFolder = origin.folder
self.parent = parent
self.mDate = origin.mdate
self.cDate = origin.cdate
self.substart = origin.substart
self.subend = origin.subend
self.subid = origin.subid
}
}
convenience init?(path: String) {
guard let origin = CloudFactory.shared.data.getData(path: path) else {
return nil
}
guard let storage = origin.storage else {
return nil
}
guard let id = origin.id else {
return nil
}
self.init(storage: storage, id: id)
}
public func open() -> RemoteStream {
return RemoteStream(size: 0)
}
public func cancel() {
service.cancel()
}
public func mkdir(newname: String, onFinish: ((String?)->Void)?){
if isFolder {
service.mkdir(parentId: id, newname: newname, onFinish: onFinish)
}
else {
onFinish?(nil)
}
}
public func delete(onFinish: ((Bool)->Void)?){
service.delete(fileId: id, onFinish: onFinish)
}
public func rename(newname: String, onFinish: ((String?)->Void)?) {
service.rename(fileId: id, newname: newname, onFinish: onFinish)
}
public func changetime(newdate: Date, onFinish: ((String?)->Void)?) {
service.chagetime(fileId: id, newdate: newdate, onFinish: onFinish)
}
public func move(toParentId: String, onFinish: ((String?)->Void)?) {
service.move(fileId: id, fromParent: parent, toParent: toParentId, onFinish: onFinish)
}
public func read(start: Int64? = nil, length: Int64? = nil, onFinish: ((Data?)->Void)?){
service.read(fileId: id, start: start, length: length, onFinish: onFinish)
}
}
public class RemoteStream {
public internal(set) var size:Int64
public var isLive = true
private let read_queue = DispatchQueue(label: "read")
init(size: Int64) {
self.size = size
}
public func read(position: Int64, length: Int, onProgress: ((Int)->Bool)? = nil) -> Data? {
return nil
}
public func read(position: Int64, length: Int, onProgress: ((Int)->Bool)? = nil, onFinish: @escaping (Data?) -> Void) {
read_queue.async {
let fixlen = (Int64(length) + position >= self.size) ? Int(self.size - position) : length
let data = self.read(position: position, length: fixlen, onProgress: onProgress)
DispatchQueue.global().async {
onFinish(data)
}
}
}
public func preload(position: Int64, length: Int) {
}
}
public class CloudFactory {
private static let _shared = CloudFactory()
public static var shared: CloudFactory { return _shared }
let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "application")
public var urlSessionDidFinishCallback: ((URLSession)->Void)?
private init() {
storageList = [:]
initializeDatabase()
}
public func initializeDatabase() {
os_log("%{public}@", log: log, type: .info, "CloudFactory(init)")
storageList = [:]
if let sList = getKeyChain(key: "remoteStorageList") {
let classmap = Dictionary(uniqueKeysWithValues: CloudStorages.allCases.map() { (CloudFactory.getServiceName(service: $0), $0) })
do {
if let d = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(sList) as? [String: String] {
print(d)
let tList = d.map() { key, value -> (String, RemoteStorage?) in
guard let jsondata = value.data(using: .utf8) else {
return (key, nil)
}
guard let json = try? JSONSerialization.jsonObject(with: jsondata, options: []) else {
return (key, nil)
}
guard let conf = json as? [String: String?], conf["name"] == key else {
return (key, nil)
}
guard let valueService = conf["service"], let newService = valueService else {
return (key, nil)
}
if let newClass = classmap[newService] {
os_log("%{public}@", log: log, type: .info, "Restore \(key) \(newService)")
let newItem = newStorage(service: newClass, tagname: key)
return (key, newItem)
}
return (key, nil)
}
storageList = Dictionary(uniqueKeysWithValues: tList.filter() { $1 != nil }.map() { ($0, $1!)} )
saveConfig()
}
}
catch {
let _ = delKeyChain(key: "remoteStorageList")
}
}
storageList["Local"] = newStorage(service: .Local, tagname: "Local")
}
public let data = dataItems()
public let cache = FileCache()
public func getIcon(service: CloudStorages) -> UIImage? {
switch service {
case .GoogleDrive:
return UIImage(named: "google", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .DropBox:
return UIImage(named: "dropbox", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .OneDrive:
return UIImage(named: "onedrive", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .pCloud:
return UIImage(named: "pcloud", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .WebDAV:
return UIImage(named: "webdav", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .CryptCarotDAV:
return UIImage(named: "carot", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .CryptRclone:
return UIImage(named: "rclone", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .Cryptomator:
return UIImage(named: "cryptomator", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .Local:
return UIImage(named: "local", in: Bundle(for: type(of: self)), compatibleWith: nil)
case .Files:
return UIImage(named: "files", in: Bundle(for: type(of: self)), compatibleWith: nil)
}
}
public class func getServiceName(service: CloudStorages) -> String {
switch service {
case .GoogleDrive:
return "GoogleDrive"
case .DropBox:
return "DropBox"
case .OneDrive:
return "OneDrive"
case .pCloud:
return "pCloud"
case .WebDAV:
return "WebDAV"
case .CryptCarotDAV:
return "CryptCarotDAV"
case .CryptRclone:
return "CryptRclone"
case .Cryptomator:
return "Cryptomator"
case .Local:
return "Local"
case .Files:
return "Files"
}
}
var storageList: [String: RemoteStorage]
class func createInstance(service: CloudStorages, tagname: String) -> RemoteStorage {
switch service {
case .GoogleDrive:
return GoogleDriveStorageCustom(name: tagname)
case .DropBox:
return DropBoxStorage(name: tagname)
case .OneDrive:
return OneDriveStorage(name: tagname)
case .pCloud:
return pCloudStorage(name: tagname)
case .WebDAV:
return WebDAVStorage(name: tagname)
case .CryptCarotDAV:
return CryptCarotDAV(name: tagname)
case .CryptRclone:
return CryptRclone(name: tagname)
case .Cryptomator:
return Cryptomator(name: tagname)
case .Local:
return LocalStorage(name: tagname)
case .Files:
return FilesStorage(name: tagname)
}
}
func saveConfig() {
do {
let seq = storageList.filter({ $0.key != "Local" }).map(){ key, value in (key, value.config()) }
let d = Dictionary(uniqueKeysWithValues: seq)
let rData = try NSKeyedArchiver.archivedData(withRootObject: d, requiringSecureCoding: true)
let _ = setKeyChain(key: "remoteStorageList", data: rData)
os_log("%{public}@", log: log, type: .info, "saveConfig success")
}
catch {
let _ = delKeyChain(key: "remoteStorageList")
}
}
public func newStorage(service: CloudStorages, tagname: String) -> RemoteStorage {
if let p = self[tagname] {
return p
}
let newInstance = CloudFactory.createInstance(service: service, tagname: tagname)
storageList[tagname] = newInstance
saveConfig()
return newInstance
}
func loadChild(item: RemoteData, onFinish: @escaping ([RemoteData])->Void) {
self[item.storage ?? ""]?.list(fileId: item.id ?? "") {
var loadData = [RemoteData]()
let children = self.data.listData(storage: item.storage ?? "", parentID: item.id ?? "")
loadData += children.filter({ $0.folder })
DispatchQueue.global().async {
onFinish(loadData)
}
}
}
func findChild(storage: String, id: String, onFinish: @escaping ([RemoteData])->Void) {
let children = self.data.listData(storage: storage, parentID: id)
DispatchQueue.global().async {
var loadData = [RemoteData]()
if children.count > 0 {
for item in children.filter({ $0.folder }) {
let group = DispatchGroup()
group.enter()
self.findChild(storage: item.storage ?? "", id: item.id ?? "") { newload in
loadData += newload
group.leave()
}
group.wait()
}
onFinish(loadData)
}
else {
if let item = self.data.getData(storage: storage, fileId: id) {
loadData += [item]
}
DispatchQueue.global().async {
onFinish(loadData)
}
}
}
}
public func deepLoad(storage: String) {
DispatchQueue.global().async {
self.findChild(storage: storage, id: "") { newload in
let group = DispatchGroup()
var remain = newload
while remain.count > 0 {
if let target = remain.first {
remain = Array(remain.dropFirst())
group.enter()
self.loadChild(item: target) { addItems in
remain += addItems
group.leave()
}
group.wait()
}
else {
break
}
}
}
}
}
public subscript(name: String) -> RemoteStorage? {
return storageList[name]
}
public var storages: [String] {
return [String](storageList.keys).sorted()
}
public func delStorage(tagname: String) {
if let p = self[tagname] {
p.logout()
let depended = getKeyChain(cond: "^\(tagname)_depended")
for (key, dep) in depended {
if let s = String(data: dep, encoding: .utf8) {
delStorage(tagname: s)
let _ = delKeyChain(key: key)
}
}
storageList.removeValue(forKey: tagname)
saveConfig()
}
}
public func delAllStorage() {
let _ = storageList.map() { delStorage(tagname: $0.key) }
}
public func removeAllAuth() {
if delAllKeyChain() {
storageList = [:]
storageList["Local"] = CloudFactory.createInstance(service: .Local, tagname: "Local")
}
}
func getKeyChain(key: String) -> Data? {
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue as Any]
var data: AnyObject?
let matchingStatus = withUnsafeMutablePointer(to: &data){
SecItemCopyMatching(dic as CFDictionary, UnsafeMutablePointer($0))
}
if matchingStatus == errSecSuccess {
if let getData = data as? Data {
return getData
}
return nil
} else {
return nil
}
}
func getKeyChain(cond: String) -> [String: Data] {
guard let regex = try? NSRegularExpression(pattern: cond, options: []) else {
return [:]
}
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecReturnAttributes as String: kCFBooleanTrue as Any,
kSecReturnData as String: kCFBooleanTrue as Any,
kSecMatchLimit as String: kSecMatchLimitAll]
var data: AnyObject?
let matchingStatus = withUnsafeMutablePointer(to: &data){
SecItemCopyMatching(dic as CFDictionary, UnsafeMutablePointer($0))
}
if matchingStatus == errSecSuccess {
var ret: [String: Data] = [:]
if let result = data as? [[String: Any]] {
for item in result {
if let account = item[kSecAttrAccount as String] as? String {
if regex.numberOfMatches(in: account, options: [], range: NSRange(location: 0, length: account.count)) != 0 {
if let d = item[kSecValueData as String] as? Data {
ret[account] = d
}
else {
print("取得失敗: Dataが不正")
}
}
}
}
}
return ret
} else {
print("取得失敗")
return [:]
}
}
func delAllKeyChain() -> Bool {
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrSynchronizable as String: kCFBooleanTrue as Any]
let dic2: [String: Any] = [kSecClass as String: kSecClassGenericPassword]
let dic3: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrSynchronizable as String: kCFBooleanTrue as Any,
kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly]
if SecItemDelete(dic as CFDictionary) == errSecSuccess {
print("削除成功")
} else {
print("削除失敗")
}
if SecItemDelete(dic2 as CFDictionary) == errSecSuccess {
print("削除成功")
} else {
print("削除失敗")
}
if SecItemDelete(dic3 as CFDictionary) == errSecSuccess {
print("削除成功")
} else {
print("削除失敗")
}
return true
}
func delKeyChain(key: String) -> Bool {
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key]
if SecItemDelete(dic as CFDictionary) == errSecSuccess {
print("削除成功")
return true
} else {
print("削除失敗")
return false
}
}
func setKeyChain(key: String, data: Data) -> Bool{
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data]
var itemAddStatus: OSStatus?
let matchingStatus = SecItemCopyMatching(dic as CFDictionary, nil)
if matchingStatus == errSecItemNotFound {
// 保存
itemAddStatus = SecItemAdd(dic as CFDictionary, nil)
} else if matchingStatus == errSecSuccess {
// 更新
itemAddStatus = SecItemUpdate(dic as CFDictionary, [kSecValueData as String: data] as CFDictionary)
} else {
print("保存失敗")
}
if itemAddStatus == errSecSuccess {
return true
} else {
print("保存失敗")
return false
}
}
}
public class RemoteStorageBase: NSObject, RemoteStorage {
static let semaphore_key = DispatchSemaphore(value: 1)
public var rootName: String = ""
public func read(fileId: String, start: Int64?, length: Int64?, onFinish: ((Data?) -> Void)?) {
readFile(fileId: fileId, start: start, length: length, onFinish: onFinish)
}
public func upload(parentId: String, sessionId: String, uploadname: String, target: URL, onFinish: ((String?)->Void)?) {
uploadFile(parentId: parentId, sessionId: sessionId, uploadname: uploadname, target: target, onFinish: onFinish)
}
public func move(fileId: String, fromParent: String, toParent: String, onFinish: ((String?) -> Void)?) {
moveItem(fileId: fileId, fromParentId: fromParent, toParentId: toParent, onFinish: onFinish)
}
public func chagetime(fileId: String, newdate: Date, onFinish: ((String?) -> Void)?) {
changeTime(fileId: fileId, newdate: newdate, onFinish: onFinish)
}
public func rename(fileId: String, newname: String, onFinish: ((String?) -> Void)?) {
renameItem(fileId: fileId, newname: newname, onFinish: onFinish)
}
public func delete(fileId: String, onFinish: ((Bool) -> Void)?) {
deleteItem(fileId: fileId, onFinish: onFinish)
}
func makeFolder(parentId: String, parentPath: String, newname: String, callCount: Int = 0, onFinish: ((String?) -> Void)?) {
onFinish?(nil)
}
public func get(fileId: String) -> RemoteItem? {
return fileId.contains("\t") ? getsubitem(fileId: fileId) : getRaw(fileId: fileId)
}
public func get(path: String) -> RemoteItem? {
return getRaw(path: path)
}
public func getRaw(fileId: String) -> RemoteItem? {
return RemoteItem(storage: storageName ?? "", id: fileId)
}
public func getRaw(path: String) -> RemoteItem? {
return RemoteItem(path: path)
}
public func getStorageType() -> CloudStorages {
return .GoogleDrive
}
let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "application")
var storageName: String?
var service: String?
var cancelTime = Date(timeIntervalSince1970: 0)
public func cancel() {
cancelTime = Date(timeIntervalSinceNow: 0.5)
}
public func config() -> String {
let conf = ["name": storageName,
"service": service
]
do {
let json = try JSONSerialization.data(withJSONObject: conf, options: [])
return String(bytes: json, encoding: .utf8) ?? ""
}
catch {
return ""
}
}
public func auth(onFinish: ((Bool) -> Void)?) -> Void {
onFinish?(true)
}
func deleteItems(name: String) {
CloudFactory.shared.data.persistentContainer.performBackgroundTask { context in
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "storage == %@", name)
if let result = try? context.fetch(fetchRequest) {
for object in result {
context.delete(object as! NSManagedObject)
}
}
try? context.save()
}
}
public func logout() {
if let name = storageName {
os_log("%{public}@", log: log, type: .info, "logout(\(name))")
deleteItems(name: name)
}
}
func ListChildren(fileId: String = "", path: String = "", onFinish: (() -> Void)?) {
onFinish?()
}
func deleteChild(parent: String, context: NSManagedObjectContext) {
context.perform {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "parent == %@ && storage == %@", parent, self.storageName ?? "")
if let result = try? context.fetch(fetchRequest), let items = result as? [RemoteData] {
for item in items {
context.delete(item)
}
}
}
}
func deleteChildRecursive(parent: String, context: NSManagedObjectContext) {
context.perform {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "parent == %@ && storage == %@", parent, self.storageName ?? "")
if let result = try? context.fetch(fetchRequest), let items = result as? [RemoteData] {
for item in items {
if let p = item.id {
self.deleteChildRecursive(parent: p, context: context)
}
context.delete(item)
}
}
}
}
public func list(fileId: String, onFinish: (() -> Void)?) {
if fileId == "" {
let backgroundContext = CloudFactory.shared.data.persistentContainer.newBackgroundContext()
self.deleteChild(parent: fileId, context: backgroundContext)
backgroundContext.perform {
try? backgroundContext.save()
self.ListChildren(onFinish: onFinish)
}
}
else {
var path = ""
let backgroundContext = CloudFactory.shared.data.persistentContainer.newBackgroundContext()
backgroundContext.perform {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "id == %@ && storage == %@", fileId, self.storageName ?? "")
if let result = try? backgroundContext.fetch(fetchRequest) {
if let items = result as? [RemoteData] {
path = items.first?.path ?? ""
}
}
if path != "" {
self.deleteChild(parent: fileId, context: backgroundContext)
}
}
backgroundContext.perform {
if path != "" {
try? backgroundContext.save()
self.ListChildren(fileId: fileId, path: path, onFinish: onFinish)
}
else {
onFinish?()
}
}
}
}
public func list(path: String, onFinish: (() -> Void)?) {
if path == "" || path == "\(storageName ?? ""):/" {
ListChildren(onFinish: onFinish)
}
else {
var ids: [String] = []
let backgroundContext = CloudFactory.shared.data.persistentContainer.newBackgroundContext()
backgroundContext.perform {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "path == %@", path)
if let result = try? backgroundContext.fetch(fetchRequest), let items = result as? [RemoteData] {
ids = items.filter { $0.id != nil }.map { $0.id! }
}
for id in ids {
self.deleteChild(parent: id, context: backgroundContext)
}
}
backgroundContext.perform {
try? backgroundContext.save()
if ids.isEmpty {
onFinish?()
return
}
for id in ids {
self.ListChildren(fileId: id, path: path, onFinish: onFinish)
}
}
}
}
public func mkdir(parentId: String, newname: String, onFinish: ((String?) -> Void)?) {
if parentId == "" {
makeFolder(parentId: parentId, parentPath: "", newname: newname, onFinish: onFinish)
}
else{
var path = ""
if Thread.isMainThread {
let viewContext = CloudFactory.shared.data.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "id == %@ && storage == %@", parentId, self.storageName ?? "")
if let result = try? viewContext.fetch(fetchRequest) {
if let items = result as? [RemoteData] {
path = items.first?.path ?? ""
}
}
}
else {
DispatchQueue.main.sync {
let viewContext = CloudFactory.shared.data.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RemoteData")
fetchRequest.predicate = NSPredicate(format: "id == %@ && storage == %@", parentId, self.storageName ?? "")
if let result = try? viewContext.fetch(fetchRequest) {
if let items = result as? [RemoteData] {
path = items.first?.path ?? ""
}
}
}
}
if path != "" {
self.makeFolder(parentId: parentId, parentPath: path, newname: newname, onFinish: onFinish)
}
else {
onFinish?(nil)
}
}
}
func deleteItem(fileId: String, callCount: Int = 0, onFinish: ((Bool) -> Void)?) {
onFinish?(false)
}
func renameItem(fileId: String, newname: String, callCount: Int = 0, onFinish: ((String?) -> Void)?) {
onFinish?(nil)
}
func changeTime(fileId: String, newdate: Date, callCount: Int = 0, onFinish: ((String?) -> Void)?) {
onFinish?(nil)
}
func moveItem(fileId: String, fromParentId: String, toParentId: String, callCount: Int = 0, onFinish: ((String?) -> Void)?) {
onFinish?(nil)
}
func readFile(fileId: String, start: Int64?, length: Int64?, callCount: Int = 0, onFinish: ((Data?) -> Void)?) {
onFinish?(nil)
}
func uploadFile(parentId: String, sessionId: String, uploadname: String, target: URL, onFinish: ((String?)->Void)?) {
onFinish?(nil)
}
func getKeyChain(key: String) -> String? {
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue as Any]
RemoteStorageBase.semaphore_key.wait()
defer {
RemoteStorageBase.semaphore_key.signal()
}
var data: AnyObject?
let matchingStatus = withUnsafeMutablePointer(to: &data){
SecItemCopyMatching(dic as CFDictionary, UnsafeMutablePointer($0))
}
if matchingStatus == errSecSuccess {
if let getData = data as? Data,
let getStr = String(data: getData, encoding: .utf8) {
return getStr
}
return nil
} else {
return nil
}
}
func delKeyChain(key: String) -> Bool {
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key]
RemoteStorageBase.semaphore_key.wait()
defer {
RemoteStorageBase.semaphore_key.signal()
}
if SecItemDelete(dic as CFDictionary) == errSecSuccess {
return true
} else {
return false
}
}
func setKeyChain(key: String, value: String) -> Bool{
let data = value.data(using: .utf8)
guard let _data = data else {
return false
}
let dic: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: _data]
RemoteStorageBase.semaphore_key.wait()
defer {
RemoteStorageBase.semaphore_key.signal()
}
var itemAddStatus: OSStatus?
let matchingStatus = SecItemCopyMatching(dic as CFDictionary, nil)
if matchingStatus == errSecItemNotFound {
// 保存
itemAddStatus = SecItemAdd(dic as CFDictionary, nil)
} else if matchingStatus == errSecSuccess {
// 更新
itemAddStatus = SecItemUpdate(dic as CFDictionary, [kSecValueData as String: _data] as CFDictionary)
} else {
print("保存失敗")
}
if itemAddStatus == errSecSuccess {
return true
} else {
print("保存失敗")
return false
}
}
}