How I wrote a YouTube video downloader on Ktor + HTMX. React killer?
import kotlinx.html.*
fun HTML.head(title : String, description : String) = head {
meta {
charset = "utf-8"
}
meta {
name = "description"
content = description
}
title {
+title
}
//Подключаем библиотеки
script { src = "https://cdn.tailwindcss.com" }
script { src = "https://unpkg.com/htmx.org@2.0.0" }
}
This way we can build a tree structure, like in Compose.
Tailwind styles are specified in classes.
get("/") {
call.respondHtml(HttpStatusCode.OK) {
lang = "ru-RU"
head(
title = "Загрузчик видео и аудио с YouTube",
description = "FlowTube - удобный сервис для быстрого скачивания видео и аудио из YouTube по ссылке."
)
body {
classes = setOf("bg-white dark:bg-white")
navbar()
searchForm()
rustoreBanner()
}
}
}
Now directly about using HTMLX.
The downloader has a form with a text field for entering a link.
After clicking the button, a request should be made to the server, we receive the data and give it to the user in the form of a ready-made html piece.
import kotlinx.html.*
fun FlowContent.searchForm() = div {
id = "content"
form {
attributes["hx-post"] = "/searchvideo"
attributes["hx-target"] = "#search-content"
label {
+"Search"
}
div {
div {
unsafe {
raw(
"""<svg class="w-4 h-4 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"/>
</svg>""".trimIndent()
)
}
}
input {
type = InputType.search
id = "url"
name = "url"
placeholder = "Введите ссылку на видео"
required = true
}
button {
type = ButtonType.submit
+"Найти"
}
}
}
//Потом мы вставим html cюда
div {
id = "search-content"
}
}
Attribute hx-post means that we are making a POST request to /searchvideo, passing the url parameter from input.
hx-target indicates the place where we will insert our html piece.
post("/searchvideo") {
val videoUrl = call.receiveParameters()["url"].toString()
val videoInfo = InnerTubeRepository().getVideoInfo(videoId = exactYouTubeId(videoUrl))
call.respondHtml {
body {
///Генерируем html
}
}
}
Works. But let's add another loading indicator.
To do this, we will use the attribute htmx-indicator
form {
attributes["hx-indicator"] = "#spinner-indicator"
//Остальной код
}
//Наша крутилка
div {
role = "status"
id= "spinner-indicator"
classes = setOf("htmx-indicator", "py-2")
attributes["hx-trigger"] = "load"
unsafe {
raw("""
<svg aria-hidden="true" class="mx-auto w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
<path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
</svg>
<span class="sr-only">Loading...</span>
""".trimIndent())
}
}
How to bypass youtube restriction via proxy
Well, one last thing.
It's likely that you'll want to run the service somewhere in the cloud.
I encountered that every time I make a request, YouTube gives an error “Get the best YouTube experience. Sign in to save videos, subscribe, and more” or another similar message “if you are not a bot, then log in”
The simplest solution:
fun create() : InnerTubeApiImpl {
return InnerTubeApiImpl(client = HttpClient(CIO) {
engine {
// Меняем на свой адрес прокси
proxy = ProxyBuilder.http("http://0.0.0.0:8000/")
}
defaultRequest {
//Авторируемся через Username и password
val credentials = Base64.getEncoder().encodeToString("USERNAME:PASSWORD".toByteArray())
header(HttpHeaders.ProxyAuthorization, "Basic $credentials")
}
})
Thank you for your attention.
I hope this article was helpful to you!