Skip to content

Commit

Permalink
1.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
hhhello0507 committed Jul 8, 2024
1 parent 3eee0d6 commit bda2cd9
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 31 deletions.
Binary file not shown.
Binary file modified Sources/.DS_Store
Binary file not shown.
64 changes: 52 additions & 12 deletions Sources/ApeunStompKit/ApeunStomp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import SocketRocket
import Combine

public enum ApeunStompEvent {
case stompClient(jsonBody: AnyObject?, stringBody: String?, header: ApeunStomp.StompHeaders?, destination: String)
case stompClient(jsonBody: String, stringBody: String?, header: ApeunStomp.StompHeaders?, destination: String)
case stompClientDidDisconnect
case stompClientDidConnect
case serverDidSendReceipt(receiptId: String)
Expand All @@ -13,8 +13,6 @@ public enum ApeunStompEvent {
public class ApeunStomp: NSObject {

public typealias StompHeaders = [String: String]
private var subscriptions = Set<AnyCancellable>()

// MARK: - Parameters
private var request: URLRequest
private var connectionHeaders: StompHeaders?
Expand All @@ -25,7 +23,8 @@ public class ApeunStomp: NSObject {
private(set) var connection: Bool = false
private var reconnectTimer : Timer?

private let subject = PassthroughSubject<ApeunStompEvent, Never>()
public let subject = PassthroughSubject<ApeunStompEvent, Never>()
private let jsonDecoder = JSONDecoder()

public init(
request: URLRequest,
Expand Down Expand Up @@ -184,7 +183,7 @@ public class ApeunStomp: NSObject {
subject.send(.stompClientDidConnect)
} else if command == .responseFrameMessage { // Message comes to this part
// Response
subject.send(.stompClient(jsonBody: self.dictForJSONString(jsonStr: body), stringBody: body, header: headers, destination: self.destinationFromHeader(header: headers)))
subject.send(.stompClient(jsonBody:/* self.dictForJSONString(jsonStr: body)*/body ?? "", stringBody: body, header: headers, destination: self.destinationFromHeader(header: headers)))
} else if command == .responseFrameReceipt { //
// Receipt
if let receiptId = headers[StompCommands.responseHeaderReceiptId.rawValue] {
Expand All @@ -203,9 +202,56 @@ public class ApeunStomp: NSObject {
}

// MARK: - Subscribe
public func subscribe(destination: String) {
public func subBody<D: Decodable>(destination: String, res: D.Type) -> AnyPublisher<D, StompError> {
connection = true
subscribeToDestination(destination: destination, ackMode: .AutoMode)
return subject
.tryMap { e in
guard case .stompClient(let jsonBody, _, _, let d) = e,
d == destination,
let json = jsonBody.data(using: .utf8) else {
if case .serverDidSendError(let description, let message) = e {
print("\(description), \(message)")
}
throw StompError.unknownError
}
do {
let res = try self.jsonDecoder.decode(D.self, from: json)
print(res)
return res
} catch {
print(error)
throw StompError.decodingFailure
}
}
.compactMap { $0 }
.mapError {
if let error = $0 as? StompError {
return error
}
return StompError.unknownError
}
.eraseToAnyPublisher()
}

public func subConnect() -> AnyPublisher<Void, Never> {
subject
.compactMap { e in
guard case .stompClientDidConnect = e else {
return nil
}
}
.eraseToAnyPublisher()
}

public func subPing() -> AnyPublisher<Void, Never> {
subject
.compactMap { e in
guard case .serverDidSendPing = e else {
return nil
}
}
.eraseToAnyPublisher()
}

public func subscribeToDestination(destination: String, ackMode: StompAckMode) {
Expand Down Expand Up @@ -321,12 +367,6 @@ public class ApeunStomp: NSObject {
self.disconnect()
}
}

public func subscribe(_ subscriber: @escaping (ApeunStompEvent) -> Void) {
subject
.sink(receiveValue: subscriber)
.store(in: &subscriptions)
}
}


Expand Down
5 changes: 5 additions & 0 deletions Sources/ApeunStompKit/StompError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public enum StompError: Error {
case decodingFailure
case connectFailure
case unknownError
}
97 changes: 78 additions & 19 deletions Sources/Test/main.swift
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
import ApeunStompKit
import Foundation
import SwiftUI
import Combine

private var subscriptions = Set<AnyCancellable>()

struct Res: Decodable {
let id: String
let chatRoomId: String
let type: String
let userId: Int
let message: String?
let emoticon: String?
let eventList: [Int]?
}

struct Req: Encodable {
let roomId: String = "6683baa5c10b712fbd2ed9d8" //보내는 방 주소
let type: String = "MESSAGE" // 형식 MESSAGE, IMG, FILE
let message: String = "asdasd 성공" // 채팅
let message: String = "wow 성공" // 채팅
}

private let url = URL(string: "wss://hoolc.me/stomp/chat")!

private var header: [String: String] {
[
"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MywiZW1haWwiOiJ0ZXN0QHRlc3QiLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWF0IjoxNzIwMzU2NTUxLCJleHAiOjE3MjAzNjI1NTF9.jgLIplC6AGWvcAnwUb0mpl57fQjYXbWT5HRfNNrvLKg",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MTksImVtYWlsIjoiaGhoZWxsbzA1MDdAZ21haWwuY29tIiwicm9sZSI6IlJPTEVfVVNFUiIsImlhdCI6MTcyMDQwMTYyNiwiZXhwIjoxNzIwNDA3NjI2fQ.HuX6yDMOATeNnzgIgS1T0xNeytmufqT5R50SPq5qm_c",
StompCommands.commandHeaderHeartBeat.rawValue: "0,10000"
]
}
Expand All @@ -24,31 +37,77 @@ let payloadObject: [String: Any] = [
]
let s = ApeunStomp(request: .init(url: url), connectionHeaders: header)

let subUrl = "/exchange/chat.exchange/room.6683baa5c10b712fbd2ed9d8"

s.openSocket()

s.subscribe { event in
switch event {
case .stompClient(let jsonBody, let stringBody, let header, let destination):
print("💎 didReceived")
print("\(jsonBody), \(stringBody), \(header), \(destination)")
case .stompClientDidDisconnect:
print("💎 didDisconnect")
case .stompClientDidConnect:
print("💎 didConnect")
s.subscribe(destination: "/exchange/chat.exchange/room.6683baa5c10b712fbd2ed9d8")
s.subConnect()
.sink { _ in
print("connected")
s.sendJSONForDict(
dict: Req(),
to: "/pub/chat.message"
)
case .serverDidSendReceipt(let receiptId):
print("💎 didSendReceipt - receiptId: \(receiptId)")
case .serverDidSendError(let description, let message):
print("💎 didSendError - description: \(description), message: \(message)")
case .serverDidSendPing:
print("💎 didSendPing")

s.subBody(destination: subUrl, res: Res.self)
.sink {
switch $0 {
case .finished:
break
case .failure(let error):
print(error)
}
} receiveValue: {
dump($0)
}
.store(in: &subscriptions)
s.subPing()
.sink { _ in
print("💎 ping")
}
.store(in: &subscriptions)
}
}
.store(in: &subscriptions)
//
//s.subscribe { event in
// switch event {
// case .stompClient(let jsonBody, let stringBody, let header, let destination):
// print("💎 didReceived")
// print("\(jsonBody), \(stringBody), \(header), \(destination)")
// case .stompClientDidDisconnect:
// print("💎 didDisconnect")
// case .stompClientDidConnect:
// print("💎 didConnect")
// s.subscribe(destination: subUrl) // MARK: - Sub
// s.sendJSONForDict(
// dict: Req(),
// to: "/pub/chat.message"
// )
// case .serverDidSendReceipt(let receiptId):
// print("💎 didSendReceipt - receiptId: \(receiptId)")
// case .serverDidSendError(let description, let message):
// print("💎 didSendError - description: \(description), message: \(message)")
// case .serverDidSendPing:
// print("💎 didSendPing")
// }
//}

print("running...")

RunLoop.main.run()
/*
"{
"id":"668b20e8235cf34a020fc6d8",
"chatRoomId":"6683baa5c10b712fbd2ed9d8",
"type":"MESSAGE",
"userId":19,
"message":"asdasd 성공",
"eventList":null,"emoticon":null,
"emojiList":[],"mention":[],
"mentionAll":false,
"timestamp":"2024-07-07T23:12:40.411326096",
"read":[19],
"messageStatus":"ALIVE"
}"
), Optional(["redelivered": "false", "content-encoding": "UTF-8", "content-type": "application/json", "content-length": "288", "__TypeId__": "com.seugi.api.domain.chat.domain.chat.model.Message", "message-id": "T_/exchange/chat.exchange/room.6683baa5c10b712fbd2ed9d8@@session-OB1xQ2Izce5uXFgLJmqYHw@@1", "priority": "0", "persistent": "true", "destination": "/exchange/chat.exchange/room.6683baa5c10b712fbd2ed9d8", "subscription": "/exchange/chat.exchange/room.6683baa5c10b712fbd2ed9d8"]), /exchange/chat.exchange/room.6683baa5c10b712fbd2ed9d8
*/

0 comments on commit bda2cd9

Please sign in to comment.