XMPPController.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // XMPPController.swift
  3. // Chat (iOS)
  4. //
  5. // Created by Sergey Tarasov on 12.10.2022.
  6. //
  7. import XMPPFramework
  8. import XMPPFrameworkSwift
  9. final class XMPPController: NSObject {
  10. static let shared: XMPPController = XMPPController()
  11. let xmppStream: XMPPStream
  12. let xmppReconnect: XMPPReconnect
  13. let xmppRoster: XMPPRoster
  14. let xmppRosterStorage: XMPPRosterMemoryStorage
  15. let xmppMUCLight: XMPPMUCLight
  16. var xmppAuth: XMPPPlainAuthentication
  17. private override init() {
  18. self.xmppStream = XMPPStream()
  19. self.xmppReconnect = XMPPReconnect()
  20. self.xmppRosterStorage = XMPPRosterMemoryStorage()
  21. self.xmppRoster = XMPPRoster(rosterStorage: xmppRosterStorage)
  22. self.xmppMUCLight = XMPPMUCLight()
  23. self.xmppAuth = XMPPPlainAuthentication()
  24. self.xmppReconnect.activate(xmppStream)
  25. self.xmppRoster.activate(xmppStream)
  26. self.xmppMUCLight.activate(xmppStream)
  27. super.init()
  28. self.xmppStream.addDelegate(self, delegateQueue: .main)
  29. self.xmppReconnect.addDelegate(self, delegateQueue: .main)
  30. setupStream()
  31. }
  32. func setupStream() {
  33. self.xmppStream.hostName = "msg.sharix-app.org"
  34. self.xmppStream.hostPort = 5222
  35. self.xmppStream.startTLSPolicy = XMPPStreamStartTLSPolicy.allowed
  36. }
  37. func login(with login: String, and password: String) {
  38. self.xmppStream.myJID = XMPPJID(string: login)
  39. self.xmppAuth = XMPPPlainAuthentication(stream: xmppStream, password: password)
  40. }
  41. func connect() {
  42. if self.xmppStream.isDisconnected {
  43. do {
  44. try xmppStream.connect(withTimeout: XMPPStreamTimeoutNone)
  45. } catch {
  46. }
  47. }
  48. }
  49. }
  50. extension XMPPController: XMPPReconnectDelegate {
  51. func xmppReconnect(_ sender: XMPPReconnect, shouldAttemptAutoReconnect connectionFlags: SCNetworkConnectionFlags) -> Bool {
  52. print("---------- xmppReconnect:shouldAttemptAutoReconnect: ----------")
  53. return true
  54. }
  55. }
  56. extension XMPPController: XMPPStreamDelegate {
  57. func xmppStreamDidConnect(_ sender: XMPPStream) {
  58. do {
  59. try self.xmppStream.authenticate(xmppAuth)
  60. } catch {
  61. }
  62. }
  63. func xmppStreamDidAuthenticate(_ sender: XMPPStream) {
  64. sender.send(XMPPPresence())
  65. print("Stream: Authenticated")
  66. }
  67. }