All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.pubnub.internal.endpoints.MessageCountsEndpoint.kt Maven / Gradle / Ivy

package com.pubnub.internal.endpoints

import com.google.gson.JsonElement
import com.pubnub.api.PubNubError
import com.pubnub.api.PubNubException
import com.pubnub.api.enums.PNOperationType
import com.pubnub.api.models.consumer.history.PNMessageCountResult
import com.pubnub.api.retry.RetryableEndpointGroup
import com.pubnub.internal.EndpointCore
import com.pubnub.internal.PubNubCore
import com.pubnub.internal.toCsv
import retrofit2.Call
import retrofit2.Response

/**
 * @see [PubNubCore.messageCounts]
 */
class MessageCountsEndpoint internal constructor(
    pubnub: PubNubCore,
    override val channels: List,
    override val channelsTimetoken: List,
) : EndpointCore(pubnub), MessageCountsInterface {
    override fun validateParams() {
        super.validateParams()
        if (channels.isEmpty()) {
            throw PubNubException(PubNubError.CHANNEL_MISSING)
        }
        if (channelsTimetoken.isEmpty()) {
            throw PubNubException(PubNubError.TIMETOKEN_MISSING)
        }
        if (channelsTimetoken.size != channels.size && channelsTimetoken.size > 1) {
            throw PubNubException(PubNubError.CHANNELS_TIMETOKEN_MISMATCH)
        }
    }

    override fun getAffectedChannels() = channels

    override fun doWork(queryParams: HashMap): Call {
        addQueryParams(queryParams)

        return retrofitManager.historyService.fetchCount(
            subKey = configuration.subscribeKey,
            channels = channels.toCsv(),
            options = queryParams,
        )
    }

    override fun createResponse(input: Response): PNMessageCountResult {
        val channelsMap = HashMap()

        val it = pubnub.mapper.getObjectIterator(input.body()!!, "channels")
        while (it.hasNext()) {
            val entry = it.next()
            channelsMap[entry.key] = entry.value.asLong
        }
        return PNMessageCountResult(channelsMap)
    }

    override fun operationType() = PNOperationType.PNMessageCountOperation

    override fun getEndpointGroupName(): RetryableEndpointGroup = RetryableEndpointGroup.MESSAGE_PERSISTENCE

    private fun addQueryParams(queryParams: MutableMap) {
        if (channelsTimetoken.size == 1) {
            queryParams["timetoken"] = channelsTimetoken.toCsv()
        } else {
            queryParams["channelsTimetoken"] = channelsTimetoken.toCsv()
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy