forked from ShadowsocksR-Live/iShadowsocksR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Config.swift
114 lines (97 loc) · 3.1 KB
/
Config.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
//
// Config.swift
//
// Created by LEI on 4/6/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import RealmSwift
import PotatsoModel
import yaml
public enum ConfigError: Error {
case downloadFail
case syntaxError
}
extension ConfigError: CustomStringConvertible {
public var description: String {
switch self {
case .downloadFail:
return "Download fail"
case .syntaxError:
return "Syntax error"
}
}
}
open class Config {
open var groups: [ConfigurationGroup] = []
open var proxies: [Proxy] = []
open var ruleSets: [ProxyRuleSet] = []
let realm: Realm
var configDict: [String: AnyObject] = [:]
public init() {
realm = try! Realm()
}
open func setup(string configString: String) throws {
guard configString.count > 0, let object = try? YAMLSerialization.object(withYAMLString: configString, options: kYAMLReadOptionStringScalars), let yaml = object as? [String: AnyObject] else {
throw ConfigError.syntaxError
}
self.configDict = yaml
try setupModels()
}
open func setup(url: URL) throws {
guard let string = try? String(contentsOf: url) else {
throw ConfigError.downloadFail
}
try setup(string: string)
}
open func save() throws {
do {
try realm.commitWrite()
}catch {
throw error
}
}
func setupModels() throws {
realm.beginWrite()
do {
try setupProxies()
try setupProxyRuleSets()
try setupConfigGroups()
}catch {
realm.cancelWrite()
throw error
}
}
func setupProxies() throws {
if let proxiesConfig = configDict["proxies"] as? [[String: AnyObject]] {
proxies = try proxiesConfig.map({ (config) -> Proxy? in
return try Proxy(dictionary: config, inRealm: realm)
}).filter { $0 != nil }.map { $0! }
try proxies.forEach {
try $0.validate(inRealm: realm)
realm.add($0)
}
}
}
func setupProxyRuleSets() throws{
if let proxiesConfig = configDict["ruleSets"] as? [[String: AnyObject]] {
ruleSets = try proxiesConfig.map({ (config) -> ProxyRuleSet? in
return try ProxyRuleSet(dictionary: config, inRealm: realm)
}).filter { $0 != nil }.map { $0! }
try ruleSets.forEach {
try $0.validate(inRealm: realm)
realm.add($0)
}
}
}
func setupConfigGroups() throws{
if let proxiesConfig = configDict["configGroups"] as? [[String: AnyObject]] {
groups = try proxiesConfig.map({ (config) -> ConfigurationGroup? in
return try ConfigurationGroup(dictionary: config, inRealm: realm)
}).filter { $0 != nil }.map { $0! }
try groups.forEach {
try $0.validate(inRealm: realm)
realm.add($0)
}
}
}
}