package dev.fyloz.musicplayer.modules.spotify import dev.fyloz.musicplayer.core.KoinModule import dev.fyloz.musicplayer.modules.Module import dev.fyloz.musicplayer.modules.spotify.config.SpotifyConfiguration import io.ktor.client.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.config.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.koin.ktor.ext.inject class SpotifyModule : Module(moduleName) { override fun setupDependencyInjection(module: KoinModule, config: ApplicationConfig) { with(module) { single { SpotifyConfiguration.fromEnvironment(config) } } } override fun configure(app: Application) { super.configure(app) val httpClient by app.inject() val config by app.inject() with(app) { authentication { oauth(oauthName) { urlProvider = { "http://localhost:8080/module/spotify/login-callback" } providerLookup = { OAuthServerSettings.OAuth2ServerSettings( name = moduleName, authorizeUrl = "https://accounts.spotify.com/authorize", accessTokenUrl = "https://accounts.spotify.com/api/token", requestMethod = HttpMethod.Post, clientId = config.clientId, clientSecret = config.clientSecret, defaultScopes = listOf("user-read-private user-read-email") ) } client = httpClient } } } } override fun getAuthorizationData(call: ApplicationCall) = SpotifyAuthorizationData( call.request.cookies["Spotify-Access-Token"]!! ) override fun Route.configureModuleRoutes() { authenticate(oauthName) { get("/login") { call.respondRedirect("https://accounts.spotify.com/authorize") } get("/login-callback") { call.principal()?.let { with(call.response.cookies) { append("Spotify-Access-Token", it.accessToken, maxAge = it.expiresIn) append("Spotify-Refresh-Token", it.refreshToken!!) } } } } } override fun getTrackFactory() = SpotifyTrackFactory() companion object { const val moduleName = "spotify" const val oauthName = "auth-oauth-spotify" } }