54 lines
1.5 KiB
Kotlin
54 lines
1.5 KiB
Kotlin
package com.dowstats.service.user
|
|
|
|
import com.dowstats.configuration.SteamConfig
|
|
import com.dowstats.data.entities.User
|
|
import com.dowstats.data.repositories.UserRepository
|
|
import com.fasterxml.jackson.databind.JsonNode
|
|
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.stereotype.Service;
|
|
import java.net.URL
|
|
|
|
@Service
|
|
class SteamService @Autowired constructor(
|
|
val steamConfig: SteamConfig,
|
|
val userRepo: UserRepository
|
|
) {
|
|
|
|
data class UserData(
|
|
val name: String,
|
|
val avatarUrl: String,
|
|
)
|
|
|
|
val mapper = jacksonObjectMapper()
|
|
|
|
fun updateUserBySteamId(steamId: String): User {
|
|
|
|
val userInfo = getUserData(steamId)
|
|
|
|
val userToSaveOrUpdate = userRepo.findBySteamId(steamId).singleOrNull() ?: User().apply {
|
|
this.avatarUrl = userInfo.avatarUrl
|
|
this.name = userInfo.name
|
|
this.steamId = steamId
|
|
}
|
|
|
|
|
|
return userRepo.save(userToSaveOrUpdate)
|
|
}
|
|
|
|
|
|
private fun getUserData(steamId: String): UserData {
|
|
val userDetails = URL("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/" +
|
|
"?key=${steamConfig.key}" +
|
|
"&steamids=$steamId").readText()
|
|
|
|
val model: JsonNode = mapper.readTree(userDetails)
|
|
|
|
return UserData(model["response"]["players"].get(0)["personaname"].textValue(),
|
|
model["response"]["players"].get(0)["avatarmedium"].textValue())
|
|
|
|
}
|
|
|
|
|
|
}
|