feat: add HTTP stream connection with ICY header support

Made-with: Cursor
This commit is contained in:
cottongin
2026-03-10 02:13:50 -04:00
parent fd73caf181
commit 7814d682f6
2 changed files with 179 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
package xyz.cottongin.radio247.audio
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.io.InputStream
import java.time.Duration
class ConnectionFailed(message: String, cause: Throwable? = null) : Exception(message, cause)
class StreamConnection(private val url: String) {
private val client = OkHttpClient.Builder()
.readTimeout(Duration.ofSeconds(30))
.build()
var metaint: Int? = null
private set
var inputStream: InputStream? = null
private set
private var response: Response? = null
fun open() {
val request = Request.Builder()
.url(url)
.header("Icy-MetaData", "1")
.header("User-Agent", "Radio247/1.0")
.build()
try {
val resp = client.newCall(request).execute()
if (!resp.isSuccessful) {
resp.close()
throw ConnectionFailed("HTTP ${resp.code}")
}
response = resp
metaint = resp.header("icy-metaint")?.toIntOrNull()
inputStream = resp.body?.byteStream()
?: throw ConnectionFailed("Empty response body")
} catch (e: IOException) {
throw ConnectionFailed("Network error", e)
}
}
fun close() {
try {
inputStream?.close()
} catch (_: IOException) {}
try {
response?.close()
} catch (_: IOException) {}
response = null
inputStream = null
metaint = null
}
}