55 lines
1.5 KiB
Swift
55 lines
1.5 KiB
Swift
// RFC - 6120
|
|
import Foundation
|
|
|
|
final class ParserModule: XmppModule {
|
|
let id = "Parser module"
|
|
|
|
private var callback: ((Event) async -> Void)?
|
|
private let parser = XMLParser()
|
|
private var task: Task<Void, Never>?
|
|
|
|
init(_ fire: @escaping (Event) async -> Void) {
|
|
callback = fire
|
|
task = Task {
|
|
for await element in parser.element {
|
|
switch element {
|
|
case .streamStarted(let attributes):
|
|
await callback?(.streamStarted(args: attributes))
|
|
|
|
case .streamEnded:
|
|
await callback?(.streamEnded)
|
|
|
|
case .element(let xml):
|
|
await callback?(.xmlInbound(xml))
|
|
|
|
case .parserError(let error):
|
|
await callback?(.parserError(error))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func reduce(oldState: ClientState, with event: Event) -> ClientState {
|
|
// small hack here, need be sure that parser resetted before
|
|
// start stream xml will send, so using reduce instead process method
|
|
// for that (no perfomance issue here)
|
|
if case .startStream = event {
|
|
parser.restart()
|
|
}
|
|
return oldState
|
|
}
|
|
|
|
func process(state _: ClientState, with event: Event) async -> Event? {
|
|
switch event {
|
|
case .socketReceived(let data):
|
|
Task {
|
|
parser.parse(data: data)
|
|
}
|
|
return nil
|
|
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
}
|