com.pubnub.api.endpoints.MessageCounts.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pubnub-kotlin Show documentation
Show all versions of pubnub-kotlin Show documentation
PubNub is a cross-platform client-to-client (1:1 and 1:many) push service in the cloud, capable of
broadcasting real-time messages to millions of web and mobile clients simultaneously, in less than a quarter
second!
package com.pubnub.api.endpoints
import com.google.gson.JsonElement
import com.pubnub.api.Endpoint
import com.pubnub.api.PubNub
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.toCsv
import retrofit2.Call
import retrofit2.Response
import java.util.HashMap
/**
* @see [PubNub.messageCounts]
*/
class MessageCounts internal constructor(
pubnub: PubNub,
val channels: List,
val channelsTimetoken: List
) : Endpoint(pubnub) {
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 pubnub.retrofitManager.historyService.fetchCount(
subKey = pubnub.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
private fun addQueryParams(queryParams: MutableMap) {
if (channelsTimetoken.size == 1) queryParams["timetoken"] = channelsTimetoken.toCsv()
else queryParams["channelsTimetoken"] = channelsTimetoken.toCsv()
}
}