sss.openstar.controller.ProviderHelper.scala Maven / Gradle / Ivy
package sss.openstar.controller
import sss.ancillary.{FailWithException, Logging}
import sss.openstar.UniqueNodeIdentifier
import sss.openstar.account.NodeIdentity
import sss.openstar.identityledger.{AddMessageStore, IdentityAttribute, IdentityService, IdentityServiceQuery, ProviderChargeAttribute, RemoveMessageStore, SystemAttributeCategory}
import sss.openstar.tools.SendTxSupport.SendTx
import sss.openstar.ui.rpc._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
object ProviderHelper extends Logging {
case class RegisteredProvider(name: UniqueNodeIdentifier, amount: Long)
def listRegisteredProviders(startIndex: Long, pageSize: Int)(implicit identityService: IdentityService): Try[Seq[RegisteredProvider]] = Try {
identityService
.listByAttribute(SystemAttributeCategory.ProviderCharge, startIndex, pageSize)
.map {
case IdentityAttribute(identity, ProviderChargeAttribute(amount)) =>
RegisteredProvider(identity, amount)
case x =>
FailWithException.fail(s"Programming fail $x should never be here")
}
}
def getProviders(identity: UniqueNodeIdentifier)(
implicit identityService: IdentityService
): Set[RegisteredProvider] = {
identityService.messageStores(identity)
.map { storeProvider =>
(storeProvider,
identityService
.listAttributes(storeProvider)
.find(_.category == SystemAttributeCategory.ProviderCharge)
)
}.collect {
case (storeProvider, Some(ProviderChargeAttribute(amount))) =>
RegisteredProvider(storeProvider, amount)
}
}
def removeProvider(provider: UniqueNodeIdentifier, user: NodeIdentity)(
implicit identityServiceQuery: IdentityServiceQuery,
sendTx: SendTx,
ec: ExecutionContext
): Future[ResultOk] = {
Utils.simplySignedIdentityLedgerItem(
user,
RemoveMessageStore(user.id, provider)
)
} flatMap { le =>
sendTx(le).whenCommitted.map(_.internalCommit).toOkResult
} recover {
case e =>
log.error("Failed to create RemoveMessageStore tx", e)
problem("Internal error - failed to create tx, see logs")
}
def addProvider(provider: UniqueNodeIdentifier, userId: NodeIdentity)
(implicit sendTx: SendTx,
ec: ExecutionContext): Future[ResultOk] = {
Utils.simplySignedIdentityLedgerItem(
userId,
AddMessageStore(userId.id, provider)
) flatMap (
sendTx(_)
.whenAvailableLocally
.map(_.commitTxResult.internalCommit)
.toOkResult
) andThen {
case x =>
log.info(s"Added provider $x !!!")
}
} recover {
case e =>
log.error("Failed to create AddMessageStore tx", e)
problem("Internal error - failed to create tx, see logs")
}
}