2022-12-16 22:14:21 +05:30
|
|
|
package com.github.libretube.extensions
|
|
|
|
|
|
|
|
import java.net.HttpURLConnection
|
|
|
|
import java.net.URL
|
2022-12-25 18:36:23 +05:30
|
|
|
import kotlinx.coroutines.Dispatchers
|
|
|
|
import kotlinx.coroutines.withContext
|
2022-12-16 22:14:21 +05:30
|
|
|
|
|
|
|
suspend fun URL.getContentLength(def: Long = -1): Long {
|
|
|
|
try {
|
|
|
|
return withContext(Dispatchers.IO) {
|
2022-12-21 21:10:48 +05:30
|
|
|
val connection = openConnection() as HttpURLConnection
|
|
|
|
connection.setRequestProperty("Range", "bytes=0-")
|
2022-12-16 22:14:21 +05:30
|
|
|
|
2022-12-21 21:10:48 +05:30
|
|
|
val value = connection.getHeaderField("content-length")
|
2022-12-16 22:14:21 +05:30
|
|
|
// If connection accepts range header, try to get total bytes
|
2022-12-21 21:10:48 +05:30
|
|
|
?: connection.getHeaderField("content-range").split("/")[1]
|
2022-12-16 22:14:21 +05:30
|
|
|
|
2022-12-21 21:10:48 +05:30
|
|
|
connection.disconnect()
|
2022-12-16 22:14:21 +05:30
|
|
|
value.toLong()
|
|
|
|
}
|
|
|
|
} catch (e: Exception) { e.printStackTrace() }
|
|
|
|
|
|
|
|
return def
|
|
|
|
}
|