Untitled

mail@pastecode.io avatar
unknown
swift
5 months ago
5.4 kB
1
Indexable
//
//  WebsocketManager.swift
//  SteviaExample
//
//  Created by wakhid.hidayat on 08/08/24.
//

import Foundation
import SwiftCentrifuge

class NetworkWebSocketManager {
    public static let shared : NetworkWebSocketManager  = NetworkWebSocketManager()
    
    private init() {}
    
    private var client: CentrifugeClient?
    private var sub: CentrifugeSubscription?
    private var isConnected: Bool = false
    private var subscriptionCreated: Bool = false
    
    func setup() {
        let config = CentrifugeClientConfig()
        let url = "wss://ws3.indodax.com/ws/?format=protobuf"
        let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE5NDY2MTg0MTV9.UR1lBM6Eqh0yWz-PVirw1uPCxe60FdchR8eNVdsskeo"
        self.client = CentrifugeClient(url: url, config: config, delegate: self)
        self.client?.setToken(token)
        self.client?.connect()
        self.createSubscription()
    }
    
    func createSubscription() {
        do {
            sub = try self.client?.newSubscription(channel: "market:summary-24h", delegate: self)
        } catch {
            print("Can not create subscription: \(error)")
            return
        }
        sub?.subscribe()
        subscriptionCreated = true
    }
}

extension NetworkWebSocketManager: CentrifugeClientDelegate {
    func onConnect(_ c: CentrifugeClient, _ e: CentrifugeConnectEvent) {
        self.isConnected = true
        print("connected with id", e.client)
    }
    
    func onDisconnect(_ c: CentrifugeClient, _ e: CentrifugeDisconnectEvent) {
        self.isConnected = false
        print("disconnected", e.reason, "reconnect", e.reconnect)
    }

    func onSubscribe(_ client: CentrifugeClient, _ event: CentrifugeServerSubscribeEvent) {
        print("server-side subscribe to", event.channel, "recovered", event.recovered, "resubscribe", event.resubscribe)
    }

    func onPublish(_ client: CentrifugeClient, _ event: CentrifugeServerPublishEvent) {
        print("server-side publication from", event.channel, "offset", event.offset)
    }

    func onUnsubscribe(_ client: CentrifugeClient, _ event: CentrifugeServerUnsubscribeEvent) {
        print("server-side unsubscribe from", event.channel)
    }

    func onJoin(_ client: CentrifugeClient, _ event: CentrifugeServerJoinEvent) {
        print("server-side join in", event.channel, "client", event.client)
    }

    func onLeave(_ client: CentrifugeClient, _ event: CentrifugeServerLeaveEvent) {
        print("server-side leave in", event.channel, "client", event.client)
    }
}

extension NetworkWebSocketManager: CentrifugeSubscriptionDelegate {
    func onPublish(_ s: CentrifugeSubscription, _ e: CentrifugePublishEvent) {
        let data = String(data: e.data, encoding: .utf8) ?? ""
        print("message from channel", s.channel, data)
        // TODO: Decode e.data to [MarketItem] and set
        // TODO: Set market items with new data from channel
        
//        let json = JSON(e.data).arrayValue
////        debugPrint(json)
//        
//        for item in json {
//            let pair = item[0].stringValue
//            let lastPrice = item[2].intValue
//        }
//        for item in data {
//            let pair = [0] as? String ?? ""
//            let epochTimestamp = item[1] as? Int ?? 0
//            let lastPrice = item[2] as? Int ?? 0
//        }
//        let decoder = JSONDecoder()
//        guard let response = try? decoder.decode(WebSocketResponse.self, from: e.data) else { return }
//
//        for item in response.data {
//            guard item.count >= 3 else { continue }
//
//            let pair = item[0] as? String ?? ""
//            let epochTimestamp = item[1] as? Int ?? 0
//            let lastPrice = item[2] as? Int ?? 0
//
//            if let marketItem = marketItems.first(where: { $0.symbol == pair }) {
//                print(marketItem.symbol, marketItem.lastPrice)
//                print(pair, lastPrice)
////                marketItem.lastPrice = "\(lastPrice)"
//            }
//        }
    }
    
    func onSubscribeSuccess(_ s: CentrifugeSubscription, _ e: CentrifugeSubscribeSuccessEvent) {
        s.presence(completion: { result, error in
            if let err = error {
                print("Unexpected presence error: \(err)")
            } else if let presence = result {
                print(presence)
            }
        })
        s.history(limit: 10, completion: { result, error in
            if let err = error {
                print("Unexpected history error: \(err)")
            } else if let res = result {
                print("Num publications returned: \(res.publications.count)")
            }
        })
        print("successfully subscribed to channel \(s.channel)")
    }
    
    func onSubscribeError(_ s: CentrifugeSubscription, _ e: CentrifugeSubscribeErrorEvent) {
        print("failed to subscribe to channel", e.code, e.message)
    }
    
    func onUnsubscribe(_ s: CentrifugeSubscription, _ e: CentrifugeUnsubscribeEvent) {
        print("unsubscribed from channel", s.channel)
    }
    
    func onJoin(_ s: CentrifugeSubscription, _ e: CentrifugeJoinEvent) {
        print("client joined channel \(s.channel), user ID \(e.user)")
    }
    
    func onLeave(_ s: CentrifugeSubscription, _ e: CentrifugeLeaveEvent) {
        print("client left channel \(s.channel), user ID \(e.user)")
    }
}
Leave a Comment