-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathNetworkDebuggingPlugin.swift
271 lines (241 loc) ยท 10.1 KB
/
NetworkDebuggingPlugin.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
//
// NetworkDebuggingPlugin.swift
// RxNetworks
//
// Created by Condy on 2021/12/12.
// https://github.com/yangKJ/RxNetworks
import Foundation
import Moya
/// ็ฝ็ปๆๅฐ๏ผDEBUGๆจกๅผๅ
็ฝฎๆไปถ
/// Network printing, DEBUG mode built in plugin.
public struct NetworkDebuggingPlugin: HasPluginsPropertyProtocol {
public var plugins: APIPlugins = []
public let options: NetworkDebuggingPlugin.Options
public init(options: NetworkDebuggingPlugin.Options = .concise) {
self.options = options
}
}
extension NetworkDebuggingPlugin {
public struct Options: Equatable {
/// This plugin has all the log records.
public static let all = Options.init(logOptions: LogOptions.all)
/// Concise printing log, has plugins and success body and error body.
public static let concise = Options.init(logOptions: LogOptions.concise)
/// Neither the request's nor the body of a response will be logged.
public static let nothing = Options.init(logOptions: LogOptions.haveNothing)
let logOptions: LogOptions
public init(logOptions: LogOptions) {
self.logOptions = logOptions
}
}
/// Enable print request information.
var openDebugRequest: Bool {
if options.logOptions.contains(.requestMethod) {
return true
}
if options.logOptions.contains(.requestBodyStream) {
return true
}
if options.logOptions.contains(.requestHeaders) {
return true
}
if options.logOptions.contains(.requestPlugins) {
return true
}
if options.logOptions.contains(.requestParameters) {
return true
}
return false
}
/// Turn on printing the response result.
var openDebugResponse: Bool {
if options.logOptions.contains(.successResponseBody) {
return true
}
if options.logOptions.contains(.errorResponseBody) {
return true
}
return false
}
}
extension NetworkDebuggingPlugin.Options {
public struct LogOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Neither the request's nor the body of a response will be logged.
public static let haveNothing: LogOptions = LogOptions(rawValue: 1 << 0)
/// The request's method will be logged.
public static let requestMethod: LogOptions = LogOptions(rawValue: 1 << 1)
/// The request's body stream will be logged.
public static let requestBodyStream: LogOptions = LogOptions(rawValue: 1 << 2)
/// The request's headers will be logged.
public static let requestHeaders: LogOptions = LogOptions(rawValue: 1 << 3)
/// The request's parameters will be logged.
public static let requestParameters: LogOptions = LogOptions(rawValue: 1 << 4)
/// The request's plugins will be logged.
public static let requestPlugins: LogOptions = LogOptions(rawValue: 1 << 5)
/// The body of a response that is a success will be logged.
public static let successResponseBody: LogOptions = LogOptions(rawValue: 1 << 87)
/// The body of a response that is an error will be logged.
public static let errorResponseBody: LogOptions = LogOptions(rawValue: 1 << 88)
/// Enable print request information.
public static let request: LogOptions = [requestMethod, requestBodyStream, requestHeaders, requestParameters, requestPlugins]
/// Turn on printing the response result.
public static let response: LogOptions = [successResponseBody, errorResponseBody]
/// Open the request log and response log at the same time.
public static let all: LogOptions = [request, response]
/// Concise printing log.
public static let concise: LogOptions = [requestPlugins, successResponseBody, errorResponseBody]
/// Diversity printing log.
public static let diversity: LogOptions = [requestPlugins, requestHeaders, requestParameters, successResponseBody, errorResponseBody]
}
}
extension NetworkDebuggingPlugin: PluginSubType {
public var pluginName: String {
return "Debugging"
}
public var usePriorityLevel: UsePriorityLevel {
UsePriorityLevel.low
}
public func configuration(_ request: HeadstreamRequest, target: TargetType) -> HeadstreamRequest {
#if DEBUG
if let result = request.result {
let lastResult = OutputResult(result: result, needMapJson: false)
ansysisResult(lastResult, target: target, local: true)
}
#endif
return request
}
public func willSend(_ request: RequestType, target: TargetType) {
#if DEBUG
printRequest(request, target: target)
#endif
}
public func outputResult(_ result: OutputResult, target: TargetType, onNext: @escaping OutputResultBlock) {
#if DEBUG
ansysisResult(result, target: target, local: false)
#endif
onNext(result)
}
}
extension NetworkDebuggingPlugin {
private var dateString: String {
get {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.locale = Locale.current
return formatter.string(from: Date())
}
}
private func realParameters(target: TargetType) -> APIParameters? {
guard options.logOptions.contains(.requestParameters) else {
return nil
}
if case .requestParameters(let parame, _) = target.task {
return parame
}
return nil
}
private func realHeaders(request: RequestType) -> [String: String]? {
guard options.logOptions.contains(.requestHeaders) else {
return nil
}
var allHeaders = request.sessionHeaders
if let httpRequestHeaders = request.request?.allHTTPHeaderFields {
allHeaders.merge(httpRequestHeaders) { $1 }
}
return allHeaders
}
private func realBodys(request: RequestType) -> String? {
guard options.logOptions.contains(.requestBodyStream) else {
return nil
}
return request.request?.httpBodyStream?.description
}
private func pluginsString() -> String? {
guard options.logOptions.contains(.requestPlugins) else {
return nil
}
return plugins.reduce("") { $0 + $1.className + " " }
}
private func printRequest(_ request: RequestType, target: TargetType) {
guard openDebugRequest else {
return
}
let requestLink = X.requestLink(with: target)
let prefix = """
โโโโโโโโโ ๐ท Prepare Request ๐ท โโโโโโโโ
โ Time: \(dateString)
โ URL: \(requestLink)\n
"""
let suffix = """
โ--------------------------------------
โ Advertis: ๆฅๅ็งAppๅฎๅถ,ๆๆ่ฏท้ฎ็ฎฑ่็ณปๆ,่ฐข่ฐข่ๆฟ!!!
โ Email: yangkj310@gmail.com
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
"""
var context: String = prefix
if options.logOptions.contains(.requestMethod) {
context += "โ Method: \(target.method.rawValue)\n"
}
if let value = realHeaders(request: request), !value.isEmpty {
context += "โ Headers: \(value)\n"
}
if let value = realParameters(target: target), !value.isEmpty {
context += "โ Parameters: \(value)\n"
}
if let value = realBodys(request: request), !value.isEmpty {
context += "โ BodyStream: \(value)\n"
}
if let value = pluginsString() {
context += """
โ--------------------------------------
โ Plugins: \(value)\n
"""
}
context += suffix
print(context)
}
private func ansysisResult(_ result: OutputResult, target: TargetType, local: Bool) {
if !openDebugResponse {
return
}
result.mapResult(success: { json in
if options.logOptions.contains(.successResponseBody) {
printResponse(target, json, local, true)
}
}, failure: { error in
if options.logOptions.contains(.errorResponseBody) {
printResponse(target, error.localizedDescription, local, false)
}
}, setToMappedResult: false, mapped2JSON: true)
}
private func printResponse(_ target: TargetType, _ result: Any?, _ local: Bool, _ success: Bool) {
guard openDebugResponse else {
return
}
let requestLink = X.requestLink(with: target)
let prefix = """
โโโโโโโโโโโโ ๐ Request ๐ โโโโโโโโโโโ
โ Time: \(dateString)
โ URL: \(requestLink)
โ--------------------------------------
โ Method: \(target.method.rawValue)
โ Host: \(target.baseURL.absoluteString)
โ Path: \(target.path)\n
"""
let suffix = """
โ---------- ๐ Response ๐ ----------
โ Result: \(success ? "Successed." : "Failed.")
โ DataType: \(local ? "Local data." : "Remote data.")
โ Response: \(result ?? "")
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
"""
var context: String = prefix
if let param = realParameters(target: target), param.isEmpty == false {
context += "โ Parameters: \(param)\n"
}
context += suffix
print(context)
}
}