Add synchronized lyrics (#126)

This commit is contained in:
vfsfitvnm
2022-08-03 21:08:40 +02:00
parent 4a16bc6960
commit 194864bcb4
16 changed files with 866 additions and 38 deletions

1
synchronized-lyrics/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

View File

@@ -0,0 +1,12 @@
plugins {
kotlin("jvm")
}
sourceSets.all {
java.srcDir("src/$name/kotlin")
}
dependencies {
implementation(libs.kotlin.coroutines)
testImplementation(testLibs.junit)
}

View File

@@ -0,0 +1,26 @@
package it.vfsfitvnm.synchronizedlyrics
import java.io.FileNotFoundException
import java.net.URL
import java.net.URLEncoder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
object LujjjhLyrics {
suspend fun forSong(artist: String, title: String): Result<String?>? {
return withContext(Dispatchers.IO) {
runCatching {
val artistParameter = URLEncoder.encode(artist, "UTF-8")
val titleParameter = URLEncoder.encode(title, "UTF-8")
URL("https://lyrics-api.lujjjh.com?artist=$artistParameter&name=$titleParameter")
.openConnection()
.getInputStream()
.bufferedReader()
.readText()
}.recoverIfCancelled()?.recoverCatching { throwable ->
if (throwable is FileNotFoundException) null else throw throwable
}
}
}
}

View File

@@ -0,0 +1,24 @@
package it.vfsfitvnm.synchronizedlyrics
fun parseSentences(text: String): List<Pair<Long, String>> {
return mutableListOf(0L to "").apply {
for (line in text.trim().lines()) {
val sentence = line.substring(10)
if (sentence.startsWith(" 作词 : ") || sentence.startsWith(" 作曲 : ")) {
continue
}
val position = line.take(10).run {
get(8).digitToInt() * 10L +
get(7).digitToInt() * 100 +
get(5).digitToInt() * 1000 +
get(4).digitToInt() * 10000 +
get(2).digitToInt() * 60 * 1000 +
get(1).digitToInt() * 600 * 1000
}
add(position to sentence)
}
}
}

View File

@@ -0,0 +1,10 @@
package it.vfsfitvnm.synchronizedlyrics
import kotlin.coroutines.cancellation.CancellationException
internal fun <T> Result<T>.recoverIfCancelled(): Result<T>? {
return when (exceptionOrNull()) {
is CancellationException -> null
else -> this
}
}

View File

@@ -0,0 +1,11 @@
import kotlinx.coroutines.runBlocking
import org.junit.Test
class Test {
@Test
@Throws(Exception::class)
fun test() {
runBlocking {
}
}
}