[db] Change username by id of user
continuous-integration/drone/push Build is failing Details

master
Lucas EVARD 11 months ago
parent 1fcda17412
commit 047b631392

@ -72,11 +72,6 @@
<version>${ktor_version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-network-tls-certificates-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>

@ -5,6 +5,5 @@ import allin.model.Participation
interface ParticipationDataSource {
fun addParticipation(participation: Participation)
fun getParticipationFromBetId(betid: String): List<Participation>
fun getParticipationFromUserId(username: String, betid: String): List<Participation>
fun deleteParticipation(id: String): Boolean
}

@ -15,4 +15,5 @@ interface UserDataSource {
fun addImage(userid: String, image: ByteArray)
fun removeImage(userid: String)
fun getImage(userid: String): String?
fun getUserById(id: String): UserDTO?
}

@ -47,9 +47,9 @@ class MockParticipationDataSource(private val mockData: MockDataSource.MockData)
override fun getParticipationFromBetId(betid: String): List<Participation> =
participations.filter { it.betId == betid }
override fun getParticipationFromUserId(username: String, betid: String): List<Participation> =
/*override fun getParticipationFromUserId(username: String, betid: String): List<Participation> =
participations.filter { it.betId == betid && it.username == username }
*/
override fun deleteParticipation(id: String): Boolean {
val participation = participations.find { it.id == id }
val result = participations.remove(participation)

@ -19,7 +19,7 @@ class MockUserDataSource(private val mockData: MockDataSource.MockData) : UserDa
nbCoins = usr.nbCoins,
token = usr.token,
image = null,
nbBets = mockData.participations.count { it.username == usr.username },
nbBets = mockData.participations.count { it.userId == usr.id },
nbFriends = mockData.friends.count { f ->
f.receiver == usr.username &&
mockData.friends.any { it.sender == usr.username && it.receiver == f.sender }
@ -84,8 +84,32 @@ class MockUserDataSource(private val mockData: MockDataSource.MockData) : UserDa
}
}
override fun getImage(userid: String): String? {
return users.find { it.id == userid }?.image
}
override fun getImage(userid: String) =
users.find { it.id == userid }?.image
override fun getUserById(id: String) =
mockData.users.find { it.id == id }?.let { usr ->
UserDTO(
id = usr.id,
username = usr.username,
email = usr.email,
nbCoins = usr.nbCoins,
token = usr.token,
image = null,
nbBets = mockData.participations.count { it.userId == usr.id },
nbFriends = mockData.friends.count { f ->
f.receiver == usr.username &&
mockData.friends.any { it.sender == usr.username && it.receiver == f.sender }
},
bestWin = mockData.participations
.filter {
(it.id == usr.id) &&
(mockData.results.find { r -> r.betId == it.betId })?.result == it.answer
}
.maxBy { it.stake }
.stake,
friendStatus = null,
)
}
}

@ -55,8 +55,8 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
override fun getBetById(id: String): Bet? =
database.bets.find { it.id eq id }?.toBet(database)
override fun getBetDetailById(id: String, username: String): BetDetail? =
database.bets.find { it.id eq id }?.toBetDetail(database, username)
override fun getBetDetailById(id: String, userid: String): BetDetail? =
database.bets.find { it.id eq id }?.toBetDetail(database, userid)
override fun getBetsNotFinished(): List<Bet> {
val currentTime = ZonedDateTime.now(ZoneId.of("+02:00"))
@ -70,7 +70,7 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
.filter {
(it.createdBy eq user.id) and (BetsEntity.status eq BetStatus.CLOSING)
}
.map { it.toBetDetail(database, user.username) }
.map { it.toBetDetail(database, user.id) }
}
override fun confirmBet(betId: String, result: String) {
@ -97,27 +97,27 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
database.betResultNotifications.add(
BetResultNotificationEntity {
this.betId = betId
this.username = participation.username
this.userid = participation.userid
}
)
val amount = (participation.stake * (resultAnswerInfo?.odds ?: 1f)).roundToInt()
database.update(UsersEntity) { usr ->
set(usr.nbCoins, usr.nbCoins + amount)
where { usr.username eq participation.username }
where { usr.id eq participation.userid }
}
}
}
override fun getWonNotifications(username: String): List<BetResultDetail> {
override fun getWonNotifications(userid: String): List<BetResultDetail> {
return database.betResultNotifications
.filter { it.username eq username }
.filter { it.userid eq userid }
.flatMap { notif ->
notif.delete()
database.participations
.filter {
(it.username eq username) and
(it.id eq userid) and
(it.betId eq notif.betId)
}
.mapNotNull { participation ->
@ -132,9 +132,9 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
}
}
override fun getHistory(username: String): List<BetResultDetail> {
override fun getHistory(userid: String): List<BetResultDetail> {
return database.participations
.filter { it.username eq username }
.filter { it.userid eq userid }
.mapNotNull { participation ->
database.betResults
.find { it.betId eq participation.bet.id }
@ -145,14 +145,14 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
}
}
override fun getCurrent(username: String): List<BetDetail> {
override fun getCurrent(userid: String): List<BetDetail> {
return database.participations
.filter { it.username eq username }
.filter { it.userid eq userid }
.mapNotNull {
if (it.bet.status !in listOf(BetStatus.FINISHED, BetStatus.CANCELLED)) {
it.bet.toBetDetail(
database = database,
username = username
userid = userid
)
} else null
}
@ -257,7 +257,7 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
database.participations
.filter { it.betId eq bet.id }
.forEach { participation ->
database.users.find { it.username eq participation.username }?.let { user ->
database.users.find { it.id eq participation.userid }?.let { user ->
user.nbCoins += participation.stake
user.flushChanges()
}

@ -75,8 +75,8 @@ class PostgresDataSource : AllInDataSource() {
"""
CREATE TABLE IF NOT EXISTS betresultnotification (
betid VARCHAR(255),
username varchar(250),
CONSTRAINT pk_id_username PRIMARY KEY (betid, username)
userid varchar(250),
CONSTRAINT pk_id_username PRIMARY KEY (betid, userid)
)
""".trimIndent()
)
@ -86,7 +86,7 @@ class PostgresDataSource : AllInDataSource() {
CREATE TABLE IF NOT EXISTS participation (
id VARCHAR(255) PRIMARY KEY,
bet VARCHAR(255),
username varchar(250),
userid varchar(250),
answer varchar(250),
stake int
)

@ -4,7 +4,6 @@ import allin.data.ParticipationDataSource
import allin.data.postgres.entities.*
import allin.model.Participation
import org.ktorm.database.Database
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.ktorm.dsl.insert
import org.ktorm.entity.*
@ -15,7 +14,7 @@ class PostgresParticipationDataSource(private val database: Database) : Particip
database.insert(ParticipationsEntity) {
set(it.id, participation.id)
set(it.betId, participation.betId)
set(it.username, participation.username)
set(it.userid, participation.userId)
set(it.answer, participation.answer)
set(it.stake, participation.stake)
}
@ -42,12 +41,7 @@ class PostgresParticipationDataSource(private val database: Database) : Particip
}
override fun getParticipationFromBetId(betid: String): List<Participation> =
database.participations.filter { it.betId eq betid }.map { it.toParticipation() }
override fun getParticipationFromUserId(username: String, betid: String): List<Participation> =
database.participations.filter {
(ParticipationsEntity.betId eq betid) and (ParticipationsEntity.username eq username)
}.map { it.toParticipation() }
database.participations.filter { it.betId eq betid }.map { it.toParticipation(database) }
override fun deleteParticipation(id: String): Boolean {
val participation = database.participations.find { it.id eq id } ?: return false

@ -21,6 +21,9 @@ class PostgresUserDataSource(private val database: Database) : UserDataSource {
?.let { it.toUserDTO(database) to it.password }
?: (null to null)
override fun getUserById(id: String): UserDTO? =
database.users.find { it.id eq id }?.toUserDTO(database)
override fun addUser(user: User) {
database.users.add(
UserEntity {

@ -48,11 +48,11 @@ interface BetEntity : Entity<BetEntity> {
)
}
fun toBetDetail(database: Database, username: String): BetDetail {
fun toBetDetail(database: Database, userid: String): BetDetail {
val bet = this.toBet(database)
val participations = database.participations.filter { it.betId eq bet.id }
val userParticipation = participations.find { it.username eq username }
val participationEntities = participations.map { it.toParticipation() }
val userParticipation = participations.find { it.userid eq userid }
val participationEntities = participations.map { it.toParticipation(database) }
val answerInfos = database.betAnswerInfos
.filter { it.betId eq bet.id }
@ -62,7 +62,7 @@ interface BetEntity : Entity<BetEntity> {
bet = bet,
answers = getBetAnswerDetail(bet, participationEntities, answerInfos),
participations = participationEntities,
userParticipation = userParticipation?.toParticipation(),
userParticipation = userParticipation?.toParticipation(database),
wonParticipation = if (bet.status == BetStatus.FINISHED) {
val result = database.betResults.find { it.betId eq this.id }
result?.let { r ->

@ -36,7 +36,7 @@ interface BetResultEntity : Entity<BetResultEntity> {
return BetResultDetail(
betResult = this.toBetResult(),
bet = bet.toBet(database),
participation = participationEntity.toParticipation(),
participation = participationEntity.toParticipation(database),
amount = (participationEntity.stake * (answerInfo?.odds ?: 1f)).roundToInt(),
won = participationEntity.answer == result
)

@ -10,12 +10,12 @@ interface BetResultNotificationEntity : Entity<BetResultNotificationEntity> {
companion object : Entity.Factory<BetResultNotificationEntity>()
var betId: String
var username: String
var userid: String
}
object BetResultNotificationsEntity : Table<BetResultNotificationEntity>("betresultnotification") {
val betId = varchar("betid").primaryKey().bindTo { it.betId }
val username = varchar("username").primaryKey().bindTo { it.username }
val userid = varchar("userid").primaryKey().bindTo { it.userid }
}
val Database.betResultNotifications get() = this.sequenceOf(BetResultNotificationsEntity)

@ -1,8 +1,12 @@
package allin.data.postgres.entities
import allin.model.Participation
import allin.utils.AppConfig
import org.ktorm.database.Database
import org.ktorm.dsl.eq
import org.ktorm.entity.Entity
import org.ktorm.entity.filter
import org.ktorm.entity.map
import org.ktorm.entity.sequenceOf
import org.ktorm.schema.Table
import org.ktorm.schema.int
@ -13,24 +17,26 @@ interface ParticipationEntity : Entity<ParticipationEntity> {
var id: String
var bet: BetEntity
var username: String
var userid: String
var answer: String
var stake: Int
fun toParticipation() =
fun toParticipation(database: Database) =
Participation(
id = id,
betId = bet.id,
username = username,
userId = userid,
answer = answer,
stake = stake
stake = stake,
username = database.users.filter { it.id eq userid }.map { it.username }.first,
imageUser = AppConfig.imageManager.getImage(id, database)
)
}
object ParticipationsEntity : Table<ParticipationEntity>("participation") {
val id = varchar("id").primaryKey().bindTo { it.id }
val betId = varchar("bet").references(BetsEntity) { it.bet }
val username = varchar("username").bindTo { it.username }
val userid = varchar("userid").bindTo { it.userid }
val answer = varchar("answer").bindTo { it.answer }
val stake = int("stake").bindTo { it.stake }
}

@ -2,7 +2,6 @@ package allin.data.postgres.entities
import allin.dto.UserDTO
import allin.model.FriendStatus
import allin.routing.imageManagerUser
import allin.utils.AppConfig
import org.ktorm.database.Database
import org.ktorm.dsl.and
@ -31,8 +30,8 @@ interface UserEntity : Entity<UserEntity> {
email = email,
nbCoins = nbCoins,
token = null,
image = getImage(id, database),
nbBets = database.participations.count { it.username eq this.username },
image = AppConfig.imageManager.getImage(id, database),
nbBets = database.participations.count { it.userid eq this.id },
nbFriends = database.friends
.filter { it.receiver eq this.id }
.mapNotNull { p -> database.friends.any { (it.sender eq this.id) and (it.receiver eq p.sender) } }
@ -48,14 +47,6 @@ interface UserEntity : Entity<UserEntity> {
friendStatus = friendStatus
)
fun getImage(userId: String, database: Database): String? {
val imageByte = database.usersimage.find { it.id eq id }?.image ?: return null
val urlfile = "images/$userId"
if (!imageManagerUser.imageAvailable(urlfile)) {
imageManagerUser.saveImage(urlfile, imageByte)
}
return "${AppConfig.urlManager.getURL()}users/${urlfile}"
}
}
object UsersEntity : Table<UserEntity>("users") {

@ -6,9 +6,11 @@ import kotlinx.serialization.Serializable
data class Participation(
val id: String,
val betId: String,
val username: String,
val userId: String,
val answer: String,
val stake: Int
val stake: Int,
val username: String,
val imageUser: String? = null
)
@Serializable

@ -40,19 +40,19 @@ fun Application.betDetailRouter() {
}
}
}) {
logManager.log("Routing","GET /betdetail/get/{id}")
logManager.log("Routing", "GET /betdetail/get/{id}")
hasToken { principal ->
verifyUserFromToken(userDataSource, principal) { user, _ ->
val id = call.parameters["id"].toString()
val result = betDataSource.getBetDetailById(id, user.username)
val result = betDataSource.getBetDetailById(id, user.id)
if (result != null) {
logManager.log("Routing","ACCEPTED GET /betdetail/get/{id}\t${result}")
logManager.log("Routing", "ACCEPTED GET /betdetail/get/{id}\t${result}")
call.respond(
HttpStatusCode.Accepted,
result
)
} else {
logManager.log("Routing","${ApiMessage.BET_NOT_FOUND} GET /betdetail/get/{id}")
logManager.log("Routing", "${ApiMessage.BET_NOT_FOUND} GET /betdetail/get/{id}")
call.respond(HttpStatusCode.NotFound, ApiMessage.BET_NOT_FOUND)
}
}

@ -259,7 +259,7 @@ fun Application.betRouter() {
hasToken { principal ->
verifyUserFromToken(userDataSource, principal) { user, _ ->
logManager.log("Routing", "ACCEPTED /bets/getWon")
call.respond(HttpStatusCode.Accepted, betDataSource.getWonNotifications(user.username))
call.respond(HttpStatusCode.Accepted, betDataSource.getWonNotifications(user.id))
}
}
}
@ -285,9 +285,9 @@ fun Application.betRouter() {
verifyUserFromToken(userDataSource, principal) { user, _ ->
logManager.log(
"Routing",
"ACCEPTED /bets/toConfirm\t${betDataSource.getHistory(user.username)}"
"ACCEPTED /bets/toConfirm\t${betDataSource.getHistory(user.id)}"
)
call.respond(HttpStatusCode.Accepted, betDataSource.getHistory(user.username))
call.respond(HttpStatusCode.Accepted, betDataSource.getHistory(user.id))
}
}
}
@ -313,9 +313,9 @@ fun Application.betRouter() {
verifyUserFromToken(userDataSource, principal) { user, _ ->
logManager.log(
"Routing",
"ACCEPTED /bets/toConfirm\t${betDataSource.getCurrent(user.username)}"
"ACCEPTED /bets/toConfirm\t${betDataSource.getCurrent(user.id)}"
)
call.respond(HttpStatusCode.Accepted, betDataSource.getCurrent(user.username))
call.respond(HttpStatusCode.Accepted, betDataSource.getCurrent(user.id))
}
}
}
@ -378,7 +378,7 @@ fun Application.betRouter() {
val id = call.receive<Map<String, String>>()["id"] ?: ""
val participations = participationDataSource.getParticipationFromBetId(id)
val users =
participations.map { userDataSource.getUserByUsername(it.username).first }.toSet().take(4)
participations.map { userDataSource.getUserById(it.id) }.toSet().take(4)
.toList()
call.respond(HttpStatusCode.Accepted, users)
}

@ -47,13 +47,13 @@ fun Application.participationRouter() {
}
}) {
logManager.log("Routing","POST /participations/add")
logManager.log("Routing", "POST /participations/add")
hasToken { principal ->
val participation = call.receive<ParticipationRequest>()
verifyUserFromToken(userDataSource, principal) { user, _ ->
if(betDataSource.getBetById(participation.betId)== null){
logManager.log("Routing","${ApiMessage.BET_NOT_FOUND} /participations/add")
if (betDataSource.getBetById(participation.betId) == null) {
logManager.log("Routing", "${ApiMessage.BET_NOT_FOUND} /participations/add")
call.respond(HttpStatusCode.NotFound, ApiMessage.BET_NOT_FOUND)
}
@ -62,18 +62,19 @@ fun Application.participationRouter() {
Participation(
id = UUID.randomUUID().toString(),
betId = participation.betId,
username = user.username,
userId = user.id,
answer = participation.answer,
stake = participation.stake
stake = participation.stake,
username = user.username
)
)
userDataSource.removeCoins(username = user.username, amount = participation.stake)
betDataSource.updatePopularityScore(participation.betId)
logManager.log("Routing","CREATED /participations/add")
logManager.log("Routing", "CREATED /participations/add")
call.respond(HttpStatusCode.Created)
} else {
logManager.log("Routing","${ApiMessage.NOT_ENOUGH_COINS} /participations/add")
logManager.log("Routing", "${ApiMessage.NOT_ENOUGH_COINS} /participations/add")
call.respond(HttpStatusCode.Forbidden, ApiMessage.NOT_ENOUGH_COINS)
}
}
@ -97,14 +98,14 @@ fun Application.participationRouter() {
}
}
}) {
logManager.log("Routing","DELETE /participations/delete")
logManager.log("Routing", "DELETE /participations/delete")
hasToken {
val participationId = call.receive<String>()
if (participationDataSource.deleteParticipation(participationId)) {
logManager.log("Routing","ACCEPTED /participations/delete")
logManager.log("Routing", "ACCEPTED /participations/delete")
call.respond(HttpStatusCode.NoContent)
} else {
logManager.log("Routing","${ApiMessage.PARTICIPATION_NOT_FOUND} /participations/delete")
logManager.log("Routing", "${ApiMessage.PARTICIPATION_NOT_FOUND} /participations/delete")
call.respond(HttpStatusCode.NotFound, ApiMessage.PARTICIPATION_NOT_FOUND)
}
}

@ -1,5 +1,10 @@
package allin.utils
import allin.data.postgres.entities.usersimage
import allin.routing.imageManagerUser
import org.ktorm.database.Database
import org.ktorm.dsl.eq
import org.ktorm.entity.find
import java.io.File
import java.util.*
@ -20,6 +25,15 @@ class ImageManager {
file.writeBytes(base64Image)
}
fun getImage(userId: String, database: Database): String? {
val imageByte = database.usersimage.find { it.id eq userId }?.image ?: return null
val urlfile = "images/$userId"
if (!imageManagerUser.imageAvailable(urlfile)) {
imageManagerUser.saveImage(urlfile, imageByte)
}
return "${AppConfig.urlManager.getURL()}users/${urlfile}"
}
fun imageAvailable(urlfile: String) = File(urlfile).exists()
fun cleanBase64(base64Image: String) = base64Image.replace("\n", "").replace("\r", "")

Loading…
Cancel
Save