forked from zhiphe/Potatso-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfig.swift
115 lines (98 loc) · 3.08 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
115
//
// Config.swift
// Potatso
//
// Created by LEI on 4/6/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import RealmSwift
import PotatsoModel
import YAML
public enum ConfigError: ErrorType {
case DownloadFail
case SyntaxError
}
extension ConfigError: CustomStringConvertible {
public var description: String {
switch self {
case .DownloadFail:
return "Download fail"
case .SyntaxError:
return "Syntax error"
}
}
}
public class Config {
public var groups: [ConfigurationGroup] = []
public var proxies: [Proxy] = []
public var ruleSets: [RuleSet] = []
let realm: Realm
var configDict: [String: AnyObject] = [:]
public init() {
realm = try! Realm()
}
public func setup(string configString: String) throws {
guard let object = try? YAMLSerialization.objectWithYAMLString(configString, options: kYAMLReadOptionStringScalars), yaml = object as? [String: AnyObject] else {
throw ConfigError.SyntaxError
}
self.configDict = yaml
try setupModels()
}
public func setup(url url: NSURL) throws {
guard let string = try? String(contentsOfURL: url) else {
throw ConfigError.DownloadFail
}
try setup(string: string)
}
public func save() throws {
do {
try realm.commitWrite()
}catch {
throw error
}
}
func setupModels() throws {
realm.beginWrite()
do {
try setupProxies()
try setupRuleSets()
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 setupRuleSets() throws{
if let proxiesConfig = configDict["ruleSets"] as? [[String: AnyObject]] {
ruleSets = try proxiesConfig.map({ (config) -> RuleSet? in
return try RuleSet(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)
}
}
}
}