RoomManager.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // RoomManager.swift
  3. // Chat (iOS)
  4. //
  5. // Created by Sergey Tarasov on 17.08.2022.
  6. //
  7. import Foundation
  8. import XMPPFramework
  9. import XMPPFrameworkSwift
  10. class RoomManager: NSObject {
  11. var room: XMPPRoom
  12. var storage: XMPPRoomMemoryStorage
  13. var mam: XMPPMessageArchiveManagement
  14. var messages: [XMPPMessage] = []
  15. init(with jidString: String) {
  16. self.storage = XMPPRoomMemoryStorage()
  17. self.room = XMPPRoom(roomStorage: self.storage, jid: XMPPJID(string: jidString)!)
  18. self.mam = XMPPMessageArchiveManagement()
  19. super.init()
  20. self.room.activate(StreamManager.shared.stream)
  21. self.mam.activate(StreamManager.shared.stream)
  22. self.room.join(usingNickname: StreamManager.shared.stream.myJID?.user ?? "Test", history: nil)
  23. self.room.addDelegate(self, delegateQueue: DispatchQueue.main)
  24. self.mam.addDelegate(self, delegateQueue: DispatchQueue.main)
  25. }
  26. func fetchMessages() {
  27. self.messages.removeAll()
  28. let field = DDXMLElement(name: "field")
  29. field.addAttribute(withName: "var", stringValue: "with")
  30. field.addChild(DDXMLElement(name: "value", stringValue: self.room.roomJID.bare))
  31. self.mam.retrieveMessageArchive(at: nil, withFields: [field], with: nil)
  32. }
  33. }
  34. extension RoomManager: XMPPRoomMemoryStorageDelegate {
  35. func xmppRoomMemoryStorage(
  36. _ sender: XMPPRoomMemoryStorage!,
  37. didReceiveMessage message: XMPPRoomMessageMemoryStorageObject!,
  38. fromOccupant occupant: XMPPRoomOccupantMemoryStorageObject!,
  39. at index: UInt,
  40. in allMessages: [Any]!
  41. ) {
  42. debugPrint(message.debugDescription)
  43. }
  44. }
  45. extension RoomManager: XMPPRoomDelegate {
  46. func xmppRoomDidJoin(_ sender: XMPPRoom) {
  47. }
  48. }
  49. extension RoomManager: XMPPMessageArchiveManagementDelegate {
  50. func xmppMessageArchiveManagement(
  51. _ xmppMessageArchiveManagement: XMPPMessageArchiveManagement,
  52. didReceiveMAMMessage message: XMPPMessage
  53. ) {
  54. if let result = message.children?.first,
  55. let forwarded = result.children?.first,
  56. let msg = forwarded.children?.first as? DDXMLElement {
  57. let xmppmsg = XMPPMessage(from: msg)
  58. if xmppmsg.isMessageWithBody {
  59. self.messages.append(xmppmsg)
  60. }
  61. }
  62. }
  63. func xmppMessageArchiveManagement(_ xmppMessageArchiveManagement: XMPPMessageArchiveManagement, didFinishReceivingMessagesWith resultSet: XMPPResultSet) {
  64. }
  65. }