lila/modules/insight/src/main/InsightApi.scala

86 lines
2.4 KiB
Scala
Raw Normal View History

2015-11-26 21:05:59 -07:00
package lila.insight
2015-11-24 23:49:13 -07:00
import lila.game.{ Game, GameRepo, Pov }
2015-11-25 03:27:01 -07:00
import lila.user.User
import org.joda.time.DateTime
2015-11-25 03:27:01 -07:00
2015-11-26 21:05:59 -07:00
final class InsightApi(
2015-11-26 12:12:34 -07:00
storage: Storage,
pipeline: AggregationPipeline,
insightUserApi: InsightUserApi,
2019-12-03 12:15:15 -07:00
gameRepo: GameRepo,
indexer: InsightIndexer
)(implicit ec: scala.concurrent.ExecutionContext) {
2015-11-25 03:27:01 -07:00
2015-11-26 21:05:59 -07:00
import InsightApi._
2015-11-25 03:27:01 -07:00
def insightUser(user: User): Fu[InsightUser] =
insightUserApi find user.id flatMap {
case Some(u) =>
u.lastSeen.isBefore(DateTime.now minusDays 1) ?? {
insightUserApi setSeenNow user
} inject u
case None =>
for {
count <- storage count user.id
ecos <- storage ecos user.id
c = InsightUser.make(user.id, count, ecos)
_ <- insightUserApi save c
} yield c
2020-05-05 22:11:15 -06:00
}
2015-11-28 07:23:47 -07:00
2015-11-26 12:12:34 -07:00
def ask[X](question: Question[X], user: User): Fu[Answer[X]] =
2019-12-13 07:30:20 -07:00
pipeline
.aggregate(question, user)
.flatMap { aggDocs =>
val clusters = AggregationClusters(question, aggDocs)
val gameIds = lila.common.ThreadLocalRandom.shuffle(clusters.flatMap(_.gameIds)) take 4
2019-12-13 07:30:20 -07:00
gameRepo.userPovsByGameIds(gameIds, user) map { povs =>
Answer(question, clusters, povs)
}
2015-11-29 05:59:11 -07:00
}
2019-12-13 07:30:20 -07:00
.monSuccess(_.insight.request)
2015-11-26 12:12:34 -07:00
def userStatus(user: User): Fu[UserStatus] =
2019-12-03 12:15:15 -07:00
gameRepo lastFinishedRatedNotFromPosition user flatMap {
2015-11-26 12:12:34 -07:00
case None => fuccess(UserStatus.NoGame)
2019-12-13 07:30:20 -07:00
case Some(game) =>
storage fetchLast user.id map {
case None => UserStatus.Empty
case Some(entry) if entry.date isBefore game.createdAt => UserStatus.Stale
case _ => UserStatus.Fresh
}
}
2020-05-27 21:08:37 -06:00
def indexAll(userId: User.ID) =
2019-12-13 07:30:20 -07:00
indexer
2020-05-27 21:08:37 -06:00
.all(userId)
2019-12-10 14:01:18 -07:00
.monSuccess(_.insight.index) >>
insightUserApi.remove(userId)
2019-12-13 07:30:20 -07:00
def updateGame(g: Game) =
Pov(g)
.map { pov =>
pov.player.userId ?? { userId =>
2021-01-22 01:18:06 -07:00
storage find InsightEntry.povToId(pov) flatMap {
2019-12-13 07:30:20 -07:00
_ ?? { old =>
indexer.update(g, userId, old)
}
}
}
}
2019-12-13 07:30:20 -07:00
.sequenceFu
.void
2015-11-24 23:49:13 -07:00
}
2015-11-26 12:12:34 -07:00
2015-11-26 21:05:59 -07:00
object InsightApi {
2015-11-26 12:12:34 -07:00
sealed trait UserStatus
object UserStatus {
case object NoGame extends UserStatus
2019-12-13 07:30:20 -07:00
case object Empty extends UserStatus
case object Stale extends UserStatus
case object Fresh extends UserStatus
2015-11-26 12:12:34 -07:00
}
}