tgbotapi/tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/utils/TelegramAPIUrlsKeeper.kt

64 lines
2.0 KiB
Kotlin
Raw Normal View History

2020-10-04 11:06:30 +00:00
package dev.inmo.tgbotapi.utils
2019-07-25 08:25:18 +00:00
2023-05-27 12:19:14 +00:00
import korlibs.crypto.*
import io.ktor.http.decodeURLQueryComponent
import io.ktor.utils.io.core.toByteArray
2020-11-06 06:07:46 +00:00
const val telegramBotAPIDefaultUrl = "https://api.telegram.org"
private inline val String.withoutLastSlash: String
get() {
var correctedUrl = this
while (true) {
val withoutSuffix = correctedUrl.removeSuffix("/")
if (withoutSuffix == correctedUrl) {
return correctedUrl
}
correctedUrl = withoutSuffix
}
}
2019-07-25 08:25:18 +00:00
class TelegramAPIUrlsKeeper(
token: String,
2022-05-02 07:21:43 +00:00
hostUrl: String = telegramBotAPIDefaultUrl,
urlsSuffixes: String = ""
2019-07-25 08:25:18 +00:00
) {
val webAppDataSecretKeyHash by lazy {
HMAC.hmacSHA256("WebAppData".toByteArray(), token.toByteArray())
}
val webAppDataSecretKey
get() = webAppDataSecretKeyHash.hexLower
val commonAPIUrl: String
val fileBaseUrl: String
2022-05-02 07:21:43 +00:00
constructor(token: String, testServer: Boolean, hostUrl: String = telegramBotAPIDefaultUrl) : this(
token,
hostUrl,
"/test".takeIf { testServer } ?: ""
)
init {
val correctedHost = hostUrl.withoutLastSlash
2022-05-02 07:21:43 +00:00
commonAPIUrl = "$correctedHost/bot$token$urlsSuffixes"
fileBaseUrl = "$correctedHost/file/bot$token$urlsSuffixes"
}
2021-08-09 17:22:08 +00:00
fun createFileLinkUrl(filePath: String) = "${fileBaseUrl}/$filePath"
/**
* @param rawData Data from [dev.inmo.tgbotapi.webapps.WebApp.initData]
* @param hash Data from [dev.inmo.tgbotapi.webapps.WebApp.initDataUnsafe] from the field [dev.inmo.tgbotapi.webapps.WebAppInitData.hash]
*/
2022-05-18 10:31:14 +00:00
fun checkWebAppData(rawData: String, hash: String): Boolean {
val preparedData = rawData
.decodeURLQueryComponent()
.split("&")
.filterNot { it.startsWith("hash=") }
.sorted()
.joinToString("\n")
return HMAC.hmacSHA256(webAppDataSecretKeyHash.bytes, preparedData.toByteArray()).hexLower == hash.lowercase()
}
2019-07-25 08:25:18 +00:00
}