Skip to content

Native Android client for Spotify, built with Jetpack Compose

Extensions can romanize the lyrics shown: the new lyrics-romanize hook, unlocked by the lyrics.romanize action, is asked once a song's lyrics are found for the lines in another script than Latin that their source left without a romanization; what it answers joins the lines as it comes, under each line with the romanization switch, stays with the lyrics and never replaces a source's own; myspoti-ext runs it (--lines, scenario lines) and API.md documents it (#154)

Illumye314e58cf6969
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
index 8a756607..63fe2323 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
@@ -76,6 +76,12 @@ object LyricsApi {
/** Lyrics to show while better ones are looked for (track key → Spotify's line-timed lyrics). */
val early = kotlinx.coroutines.flow.MutableStateFlow<Pair<String, Lyrics>?>(null)
+ /** Lyrics of song [key] that got romanizations from an extension after they were shown: [before] became [after]. */
+ data class Romanized(val key: String, val before: Lyrics, val after: Lyrics)
+
+ /** The last [Romanized]: an open lyrics view still showing [Romanized.before] swaps it for [Romanized.after]. */
+ val romanized = kotlinx.coroutines.flow.MutableStateFlow<Romanized?>(null)
+
fun cached(track: Track): Lyrics? = cache[track.key] as? Lyrics
@@ -118,7 +124,7 @@ object LyricsApi {
val job = synchronized(inFlight) {
inFlight[track.key] ?: scope.async(start = kotlinx.coroutines.CoroutineStart.LAZY) {
// Read on an earlier run: from storage, not asked for again.
- LyricsDisk.read(track.key)?.also { cache[track.key] = it } ?: resolve(track)
+ (LyricsDisk.read(track.key)?.also { cache[track.key] = it } ?: resolve(track))?.also { romanizeLater(track, it) }
}.also { created ->
inFlight[track.key] = created
created.invokeOnCompletion { inFlight.remove(track.key, created) }
@@ -205,9 +211,33 @@ object LyricsApi {
cache[track.key] = chosen
LyricsDisk.write(track.key, chosen)
Log.d("LyricsApi", "${track.title}: ${chosen.lines.size} lines from ${chosen.provider} (chosen: $sourceId)")
+ romanizeLater(track, chosen)
chosen
}
+ /**
+ * Asks the romanizing extensions, off the caller's path, for the lines of [lyrics] (just found
+ * or read from storage) that their source left in another script than Latin without a
+ * romanization: the lyrics show at once and the romanizations follow ([romanized]). They are
+ * kept, in memory and storage, only while [lyrics] are still the song's.
+ */
+ private fun romanizeLater(track: Track, lyrics: Lyrics) {
+ val wanted = LyricsRomanize.wanted(lyrics)
+ if (wanted.isEmpty() || !runCatching { com.music.spotui.extensions.Extensions.hasRomanizer() }.getOrDefault(false)) return
+ scope.launch {
+ val found = runCatching {
+ com.music.spotui.extensions.Extensions.romanizeFor(
+ track.trackId, track.title, track.artist, track.album, track.durationMs, track.coverUrl, lyrics.language, wanted)
+ }.getOrDefault(emptyMap())
+ val updated = LyricsRomanize.apply(lyrics, found)
+ if (updated === lyrics) return@launch
+ // Another source picked or the song forgotten meanwhile: these were for lyrics no longer shown.
+ if (!cache.replace(track.key, lyrics, updated)) return@launch
+ LyricsDisk.write(track.key, updated)
+ romanized.value = Romanized(track.key, lyrics, updated)
+ }
+ }
+
private suspend fun resolve(track: Track): Lyrics? = coroutineScope {
// Extensions that provide lyrics are asked at the same time as the app's own sources
// (each within its time limit); the better answer is kept (LyricsMerge), Spotify's own
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsRomanize.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsRomanize.kt
new file mode 100644
index 00000000..fab5e4ee
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsRomanize.kt
@@ -0,0 +1,32 @@
+package com.music.spotui.data.api
+
+import app.myspoti.extensions.Romanize
+import com.music.spotui.data.entity.Lyrics
+
+/**
+ * Romanizations from the extensions ([com.music.spotui.extensions.Extensions.romanize]) for the
+ * lines of lyrics their source left in another script than Latin without one. What the source
+ * gave stays: an extension only fills the lines left empty.
+ */
+object LyricsRomanize {
+ /** The lines of [lyrics] a romanization is asked for: index → text. */
+ fun wanted(lyrics: Lyrics): Map<Int, String> =
+ Romanize.wanted(lyrics.lines, { it.text }, { !it.romanization.isNullOrBlank() })
+
+ /**
+ * [lyrics] with [found] (index → romanization) on its lines that have none and need one; a
+ * romanization that only repeats its line is left out, as a source's is. The same instance when
+ * nothing is added.
+ */
+ fun apply(lyrics: Lyrics, found: Map<Int, String>): Lyrics {
+ if (found.isEmpty()) return lyrics
+ var added = false
+ val lines = lyrics.lines.mapIndexed { i, line ->
+ val ro = found[i]?.takeIf {
+ line.romanization.isNullOrBlank() && Romanize.needs(line.text) && LyricsMatch.key(it) != LyricsMatch.key(line.text)
+ }
+ if (ro == null) line else line.copy(romanization = ro).also { added = true }
+ }
+ return if (added) lyrics.copy(lines = lines) else lyrics
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt
index b77b68d5..092b4215 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt
@@ -24,6 +24,7 @@ import androidx.compose.material.icons.automirrored.rounded.PlaylistAdd
import androidx.compose.material.icons.automirrored.rounded.PlaylistPlay
import androidx.compose.material.icons.automirrored.rounded.QueueMusic
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
+import androidx.compose.material.icons.rounded.Abc
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Album
import androidx.compose.material.icons.rounded.BarChart
@@ -142,6 +143,7 @@ fun actionIcon(a: Action?): ImageVector = when (a) {
Action.PLAYBACK_MIRROR -> Icons.Rounded.VolumeOff
Action.PLAYBACK_EVENTS -> Icons.Rounded.GraphicEq
Action.LYRICS_PROVIDE -> Icons.Rounded.Lyrics
+ Action.LYRICS_ROMANIZE -> Icons.Rounded.Abc
Action.TRACKINFO_PROVIDE -> Icons.Rounded.Info
Action.AUDIO_SOURCE -> Icons.Rounded.Headphones
Action.DOWNLOAD_SOURCE -> Icons.Rounded.Download
@@ -170,6 +172,7 @@ fun actionLabel(a: Action?): Int = when (a) {
Action.PLAYBACK_MIRROR -> R.string.action_playback_mirror
Action.PLAYBACK_EVENTS -> R.string.action_playback_events
Action.LYRICS_PROVIDE -> R.string.action_lyrics_provide
+ Action.LYRICS_ROMANIZE -> R.string.action_lyrics_romanize
Action.TRACKINFO_PROVIDE -> R.string.action_trackinfo_provide
Action.AUDIO_SOURCE -> R.string.action_audio_source
Action.DOWNLOAD_SOURCE -> R.string.action_download_source
diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
index 27df9a5e..5c60d4a7 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
@@ -34,6 +34,7 @@ import app.myspoti.extensions.Host
import app.myspoti.extensions.HttpRequest
import app.myspoti.extensions.HttpResponse
import app.myspoti.extensions.LyricsResult
+import app.myspoti.extensions.Romanize
import app.myspoti.extensions.Manifest
import app.myspoti.extensions.Snapshot
import app.myspoti.extensions.SpotifyCall
@@ -92,6 +93,8 @@ object Extensions {
// Every hook's time is in [HookBudgets], shared with the desktop runner (`myspoti-ext`).
/** A lyrics hook call. */
const val LYRICS_MS = HookBudgets.LYRICS
+ /** A lyrics-romanize hook call. */
+ const val ROMANIZE_MS = HookBudgets.ROMANIZE
/** An audio-source hook call. */
const val AUDIO_MS = HookBudgets.AUDIO
/** A download-source hook call (an extension may try several places). */
@@ -126,8 +129,8 @@ object Extensions {
val logTick = MutableStateFlow(0L)
/**
- * The running extensions giving songs' audio, download files and lyrics, in the order they are
- * asked; [ready]: the ones on at launch have all been started. [refreshProvided] keeps it in step
+ * The running extensions giving songs' audio, download files, lyrics and lyrics' romanizations,
+ * in the order they are asked; [ready]: the ones on at launch have all been started. [refreshProvided] keeps it in step
* when one loads or stops (installed, updated, turned on or off, removed), its status changes or
* the user's order changes; what depends on it (the player's routing, downloads, lyrics) reacts
* at once, without a restart ([providersChanged]).
@@ -135,6 +138,7 @@ object Extensions {
data class Provided(
val audio: List<String> = emptyList(), val download: List<String> = emptyList(),
val lyrics: List<String> = emptyList(), val ready: Boolean = false,
+ val romanize: List<String> = emptyList(),
)
private val _provided = MutableStateFlow(Provided())
val provided: StateFlow<Provided> = _provided.asStateFlow()
@@ -191,6 +195,7 @@ object Extensions {
val now = Provided(
providing(Hook.AUDIO_SOURCE).map { it.first }, providing(Hook.DOWNLOAD_SOURCE).map { it.first },
providing(Hook.LYRICS).map { it.first }, started.isCompleted,
+ romanize = providing(Hook.LYRICS_ROMANIZE).map { it.first },
)
if (now == _provided.value) return
if (now.audio != _provided.value.audio || now.download != _provided.value.download) misses.clear()
@@ -210,13 +215,14 @@ object Extensions {
* launch (the extensions on before load then, nothing was asked of them yet) but for the misses.
*/
private fun providersChanged(before: Provided, now: Provided) {
- Logbook.log("ext: sources now: audio ${now.audio.ifEmpty { "none" }}, downloads ${now.download.ifEmpty { "none" }}, lyrics ${now.lyrics.ifEmpty { "none" }}")
+ Logbook.log("ext: sources now: audio ${now.audio.ifEmpty { "none" }}, downloads ${now.download.ifEmpty { "none" }}, lyrics ${now.lyrics.ifEmpty { "none" }}, romanize ${now.romanize.ifEmpty { "none" }}")
if (now.audio != before.audio && before.ready) {
val added = now.audio.filter { it !in before.audio }
main.post { runCatching { com.music.spotui.di.SongPlayer.audioSourcesChanged(added, now.audio.isNotEmpty()) }
.onFailure { Logbook.log("audio: sources changed, player not updated: $it") } }
}
- if (now.lyrics != before.lyrics) com.music.spotui.data.api.LyricsApi.sourcesChanged(keepFound = !before.ready)
+ // A romanizer added or gone changes the lyrics as much as a source: they are read again with it.
+ if (now.lyrics != before.lyrics || now.romanize != before.romanize) com.music.spotui.data.api.LyricsApi.sourcesChanged(keepFound = !before.ready)
// Lists kept downloaded skipped their songs for want of a source: synced now.
if (before.ready && before.download.isEmpty() && now.download.isNotEmpty())
com.music.spotui.data.offline.OfflineCollections.refreshAll(ctx, force = true)
@@ -715,6 +721,8 @@ object Extensions {
fun hasLyrics(): Boolean { providedState.value; return isReady && providing(Hook.LYRICS).isNotEmpty() }
+ fun hasRomanizer(): Boolean { providedState.value; return isReady && providing(Hook.LYRICS_ROMANIZE).isNotEmpty() }
+
/**
* An audio-source extension is asked for songs: one runs and is not inactive, or one that is on
* is still being started at launch (the song then waits for it, see [audio]).
@@ -795,6 +803,30 @@ object Extensions {
}?.let { (c, l) -> log(c.first, "lyrics for ${track.title}: ${l.lines.size} lines"); did(Area.LYRICS, c.first, "Lyrics of ${track.title} from ${c.second.manifest.name}"); l }
}
+ /**
+ * Romanizations of [lines] (index → text) from the extensions romanizing lyrics, in the lyrics
+ * area's order: each one is sent only the lines the ones before it left without one, so
+ * romanizers of different scripts complete each other. Index → romanization, empty when none
+ * answers. Each call has its own time limit, so a slow one keeps what the others gave.
+ */
+ suspend fun romanize(track: TrackInfo, language: String?, lines: Map<Int, String>): Map<Int, String> {
+ if (!isReady || lines.isEmpty()) return emptyMap()
+ val found = LinkedHashMap<Int, String>()
+ for ((id, rt) in available(Hook.LYRICS_ROMANIZE)) {
+ val missing = lines.filterKeys { it !in found }
+ if (missing.isEmpty()) break
+ val got = withTimeoutOrNull(ROMANIZE_MS + 1_000) {
+ ask(id, rt, Hook.LYRICS_ROMANIZE, Romanize.request(track, language, missing), ROMANIZE_MS) { raw ->
+ Romanize.parse(raw).filterKeys { it in missing }.ifEmpty { null }
+ }.value
+ } ?: continue
+ found.putAll(got)
+ log(id, "romanized ${got.size} of ${missing.size} lines of ${track.title}")
+ did(Area.LYRICS, id, "Romanized ${got.size} lines of ${track.title}")
+ }
+ return found
+ }
+
/**
* Where [track]'s audio is, from the first extension (in priority order) that knows. [ahead]:
* asked before the song plays (the next one of the queue), which the extension is told. Each
@@ -1544,6 +1576,13 @@ object Extensions {
if (!hasLyrics()) null
else withTimeoutOrNull(LYRICS_MS + 1_000) { lyrics(trackInfo(trackId, title, artist, album, durationMs, cover)) }
+ /** [romanize] for the app's lyrics resolver: [lines] of the song's lyrics, in [language] when their source said it. */
+ suspend fun romanizeFor(
+ trackId: String, title: String, artist: String, album: String, durationMs: Long, cover: String?,
+ language: String?, lines: Map<Int, String>,
+ ): Map<Int, String> =
+ if (!hasRomanizer()) emptyMap() else romanize(trackInfo(trackId, title, artist, album, durationMs, cover), language, lines)
+
/** The running extensions giving lyrics, in their order: (id, name). For the "Try another source" list. */
fun lyricsSources(): List<Pair<String, String>> =
if (!isReady) emptyList() else providing(Hook.LYRICS).map { (id, rt) -> id to rt.manifest.name }
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
index 29d985d0..ac11762f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
@@ -45,6 +45,16 @@ class LyricsViewModel constructor() : ViewModel() {
private var loadedKey: String? = null
+ init {
+ // Romanizations an extension gave after the lyrics showed join the lines still shown.
+ viewModelScope.launch {
+ LyricsApi.romanized.collect { r ->
+ val cur = _state.value as? State.Loaded ?: return@collect
+ if (r != null && r.key == loadedKey && cur.lyrics == r.before) _state.value = cur.copy(lyrics = r.after)
+ }
+ }
+ }
+
// Lines picked to share (both looks): a run of consecutive lines, by index in the lyrics' lines.
// Kept here so the song options sheet of the Immersive look can open the same mode as a long press.
private val _selecting = MutableStateFlow(false)
@@ -108,7 +118,8 @@ class LyricsViewModel constructor() : ViewModel() {
// A skip meanwhile: the answer is for the previous song.
if (loadedKey == key) {
if (lyrics == null) _triedNothing.value = sourceId
- else _state.value = loadedState(lyrics)
+ // The cache holds the latest: romanizations that came while this answer was on its way.
+ else _state.value = loadedState(LyricsApi.cached(track) ?: lyrics)
}
_trying.value = null
}
@@ -132,7 +143,8 @@ class LyricsViewModel constructor() : ViewModel() {
}
}
viewModelScope.launch(Dispatchers.IO) {
- val lyrics = LyricsApi.fetch(track)
+ // The cache holds the latest: romanizations that came while this answer was on its way.
+ val lyrics = LyricsApi.fetch(track)?.let { LyricsApi.cached(track) ?: it }
earlyJob.cancel()
withContext(Dispatchers.Main) {
// A skip during the fetch: don't show the previous song's lyrics.
diff --git a/base/app/src/main/res/values-de/extensions_strings.xml b/base/app/src/main/res/values-de/extensions_strings.xml
index 4b7f2f29..f2e07cb7 100644
--- a/base/app/src/main/res/values-de/extensions_strings.xml
+++ b/base/app/src/main/res/values-de/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Die Warteschlange bearbeiten</string>
<string name="action_playback_events">Wissen, was du hörst</string>
<string name="action_lyrics_provide">Songtexte liefern</string>
+ <string name="action_lyrics_romanize">Songtexte romanisieren</string>
<string name="action_trackinfo_provide">Song-Details ergänzen</string>
<string name="action_audio_source">Audio von anderswo abspielen</string>
<string name="action_download_source">Downloads liefern</string>
diff --git a/base/app/src/main/res/values-el/extensions_strings.xml b/base/app/src/main/res/values-el/extensions_strings.xml
index b647a012..35a1ac3f 100644
--- a/base/app/src/main/res/values-el/extensions_strings.xml
+++ b/base/app/src/main/res/values-el/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Επεξεργασία της ουράς</string>
<string name="action_playback_events">Γνώση του τι ακούς</string>
<string name="action_lyrics_provide">Παροχή στίχων</string>
+ <string name="action_lyrics_romanize">Λατινοποίηση στίχων</string>
<string name="action_trackinfo_provide">Προσθήκη λεπτομερειών τραγουδιών</string>
<string name="action_audio_source">Αναπαραγωγή ήχου από αλλού</string>
<string name="action_download_source">Παροχή λήψεων</string>
diff --git a/base/app/src/main/res/values-es/extensions_strings.xml b/base/app/src/main/res/values-es/extensions_strings.xml
index f1a661e4..505bd047 100644
--- a/base/app/src/main/res/values-es/extensions_strings.xml
+++ b/base/app/src/main/res/values-es/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Editar la cola</string>
<string name="action_playback_events">Saber lo que reproduces</string>
<string name="action_lyrics_provide">Proporcionar letras</string>
+ <string name="action_lyrics_romanize">Romanizar letras</string>
<string name="action_trackinfo_provide">Añadir detalles de canciones</string>
<string name="action_audio_source">Reproducir audio de otro origen</string>
<string name="action_download_source">Proporcionar descargas</string>
diff --git a/base/app/src/main/res/values-fr/extensions_strings.xml b/base/app/src/main/res/values-fr/extensions_strings.xml
index cd6f477e..7f3b35ca 100644
--- a/base/app/src/main/res/values-fr/extensions_strings.xml
+++ b/base/app/src/main/res/values-fr/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Modifier la file d\'attente</string>
<string name="action_playback_events">Savoir ce que vous écoutez</string>
<string name="action_lyrics_provide">Fournir des paroles</string>
+ <string name="action_lyrics_romanize">Romaniser les paroles</string>
<string name="action_trackinfo_provide">Ajouter des infos sur le titre</string>
<string name="action_audio_source">Lire l\'audio d\'ailleurs</string>
<string name="action_download_source">Fournir les téléchargements</string>
diff --git a/base/app/src/main/res/values-it/extensions_strings.xml b/base/app/src/main/res/values-it/extensions_strings.xml
index f9330629..00cef01f 100644
--- a/base/app/src/main/res/values-it/extensions_strings.xml
+++ b/base/app/src/main/res/values-it/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Modificare la coda</string>
<string name="action_playback_events">Sapere cosa ascolti</string>
<string name="action_lyrics_provide">Fornire testi</string>
+ <string name="action_lyrics_romanize">Romanizzare i testi</string>
<string name="action_trackinfo_provide">Aggiungere dettagli sui brani</string>
<string name="action_audio_source">Riprodurre audio da altrove</string>
<string name="action_download_source">Fornire download</string>
diff --git a/base/app/src/main/res/values-pl/extensions_strings.xml b/base/app/src/main/res/values-pl/extensions_strings.xml
index bcb3c5fa..dc96bb81 100644
--- a/base/app/src/main/res/values-pl/extensions_strings.xml
+++ b/base/app/src/main/res/values-pl/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Edytować kolejkę</string>
<string name="action_playback_events">Wiedzieć, czego słuchasz</string>
<string name="action_lyrics_provide">Dostarczać teksty</string>
+ <string name="action_lyrics_romanize">Latynizować teksty</string>
<string name="action_trackinfo_provide">Dodawać szczegóły utworów</string>
<string name="action_audio_source">Odtwarzać dźwięk z innego źródła</string>
<string name="action_download_source">Dostarczać pliki do pobrania</string>
diff --git a/base/app/src/main/res/values-pt-rBR/extensions_strings.xml b/base/app/src/main/res/values-pt-rBR/extensions_strings.xml
index 641ecb57..3a222f1d 100644
--- a/base/app/src/main/res/values-pt-rBR/extensions_strings.xml
+++ b/base/app/src/main/res/values-pt-rBR/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Editar a fila</string>
<string name="action_playback_events">Saber o que você ouve</string>
<string name="action_lyrics_provide">Fornecer letras</string>
+ <string name="action_lyrics_romanize">Romanizar letras</string>
<string name="action_trackinfo_provide">Acrescentar detalhes das músicas</string>
<string name="action_audio_source">Tocar áudio de outro lugar</string>
<string name="action_download_source">Fornecer downloads</string>
diff --git a/base/app/src/main/res/values-pt-rPT/extensions_strings.xml b/base/app/src/main/res/values-pt-rPT/extensions_strings.xml
index 8d363950..e8d49c76 100644
--- a/base/app/src/main/res/values-pt-rPT/extensions_strings.xml
+++ b/base/app/src/main/res/values-pt-rPT/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Editar a fila</string>
<string name="action_playback_events">Saber o que ouves</string>
<string name="action_lyrics_provide">Fornecer letras</string>
+ <string name="action_lyrics_romanize">Romanizar letras</string>
<string name="action_trackinfo_provide">Acrescentar detalhes das músicas</string>
<string name="action_audio_source">Tocar áudio de outro lado</string>
<string name="action_download_source">Fornecer transferências</string>
diff --git a/base/app/src/main/res/values-pt/extensions_strings.xml b/base/app/src/main/res/values-pt/extensions_strings.xml
index 51ba51dd..68af7164 100644
--- a/base/app/src/main/res/values-pt/extensions_strings.xml
+++ b/base/app/src/main/res/values-pt/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Editar a fila</string>
<string name="action_playback_events">Saber o que você ouve</string>
<string name="action_lyrics_provide">Fornecer letras</string>
+ <string name="action_lyrics_romanize">Romanizar letras</string>
<string name="action_trackinfo_provide">Acrescentar detalhes das músicas</string>
<string name="action_audio_source">Tocar áudio de outro lado</string>
<string name="action_download_source">Fornecer downloads</string>
diff --git a/base/app/src/main/res/values-ru/extensions_strings.xml b/base/app/src/main/res/values-ru/extensions_strings.xml
index a43e61e7..d93f328d 100644
--- a/base/app/src/main/res/values-ru/extensions_strings.xml
+++ b/base/app/src/main/res/values-ru/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">Изменять очередь</string>
<string name="action_playback_events">Знать, что вы слушаете</string>
<string name="action_lyrics_provide">Предоставлять тексты</string>
+ <string name="action_lyrics_romanize">Латинизировать тексты</string>
<string name="action_trackinfo_provide">Добавлять сведения о треках</string>
<string name="action_audio_source">Воспроизводить звук из другого источника</string>
<string name="action_download_source">Предоставлять загрузки</string>
diff --git a/base/app/src/main/res/values-zh/extensions_strings.xml b/base/app/src/main/res/values-zh/extensions_strings.xml
index 8c3f8055..fcc292a3 100644
--- a/base/app/src/main/res/values-zh/extensions_strings.xml
+++ b/base/app/src/main/res/values-zh/extensions_strings.xml
@@ -96,6 +96,7 @@
<string name="action_playback_queue">编辑播放队列</string>
<string name="action_playback_events">获知你在播放什么</string>
<string name="action_lyrics_provide">提供歌词</string>
+ <string name="action_lyrics_romanize">罗马化歌词</string>
<string name="action_trackinfo_provide">添加歌曲详情</string>
<string name="action_audio_source">从其他来源播放音频</string>
<string name="action_download_source">提供下载</string>
diff --git a/base/app/src/main/res/values/extensions_strings.xml b/base/app/src/main/res/values/extensions_strings.xml
index 4dfff03a..cea43ca6 100644
--- a/base/app/src/main/res/values/extensions_strings.xml
+++ b/base/app/src/main/res/values/extensions_strings.xml
@@ -97,6 +97,7 @@
<string name="action_playback_queue">Edit the queue</string>
<string name="action_playback_events">Know what you play</string>
<string name="action_lyrics_provide">Provide lyrics</string>
+ <string name="action_lyrics_romanize">Romanize lyrics</string>
<string name="action_trackinfo_provide">Add song details</string>
<string name="action_audio_source">Play audio from elsewhere</string>
<string name="action_download_source">Provide downloads</string>
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LyricsRomanizeTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LyricsRomanizeTest.kt
new file mode 100644
index 00000000..ecd361f4
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LyricsRomanizeTest.kt
@@ -0,0 +1,48 @@
+package com.music.spotui.data.api
+
+import com.music.spotui.data.entity.LyricLine
+import com.music.spotui.data.entity.Lyrics
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertSame
+import org.junit.Test
+
+/** Romanizations from an extension: asked for the lines left without one, never over a source's own. */
+class LyricsRomanizeTest {
+ private fun line(t: Long, text: String, ro: String? = null) = LyricLine(t, text, romanization = ro)
+
+ private val lyrics = Lyrics(
+ listOf(line(0, "Intro"), line(1000, "夢ならば"), line(2000, "♪"), line(3000, "今でも", ro = "ima demo"), line(4000, "사랑해")),
+ synced = true, language = "ja",
+ )
+
+ @Test fun onlyTheLinesInAnotherScriptWithoutARomanizationAreAsked() {
+ assertEquals(mapOf(1 to "夢ならば", 4 to "사랑해"), LyricsRomanize.wanted(lyrics))
+ }
+
+ @Test fun theAnswersFillTheLinesLeftEmpty() {
+ val out = LyricsRomanize.apply(lyrics, mapOf(1 to "yume naraba", 4 to "saranghae"))
+ assertEquals(listOf(null, "yume naraba", null, "ima demo", "saranghae"), out.lines.map { it.romanization })
+ assertEquals(lyrics.lines.map { it.text }, out.lines.map { it.text })
+ assertEquals("ja", out.language)
+ }
+
+ @Test fun aSourcesOwnRomanizationIsNeverReplaced() {
+ val out = LyricsRomanize.apply(lyrics, mapOf(3 to "IMA DEMO"))
+ assertSame(lyrics, out)
+ }
+
+ @Test fun aRomanizationThatRepeatsItsLineOrAnUnknownIndexIsLeftOut() {
+ assertSame(lyrics, LyricsRomanize.apply(lyrics, mapOf(4 to "사랑해", 9 to "nothing here", -1 to "x")))
+ }
+
+ @Test fun aLineInLatinLettersGetsNoRomanization() {
+ val out = LyricsRomanize.apply(lyrics, mapOf(0 to "something else", 1 to "yume naraba"))
+ assertNull(out.lines[0].romanization)
+ assertEquals("yume naraba", out.lines[1].romanization)
+ }
+
+ @Test fun nothingFoundKeepsTheSameLyrics() {
+ assertSame(lyrics, LyricsRomanize.apply(lyrics, emptyMap()))
+ }
+}
diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
index 96cf7e53..9d053818 100644
--- a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
@@ -22,6 +22,7 @@ import app.myspoti.extensions.SpotifyDispatcher
import app.myspoti.extensions.SpotifyRaw
import app.myspoti.extensions.DownloadFile
import app.myspoti.extensions.PlaybackEvent
+import app.myspoti.extensions.Romanize
import app.myspoti.extensions.Storage
import app.myspoti.extensions.TrackInfo
import app.myspoti.host.cdp.CdpHost
@@ -54,6 +55,8 @@ private const val USAGE = """myspoti-ext: build and try Myspoti extensions on a
yes or no on this terminal first
--quality hi-res|cd|small download-source only: the quality asked (default cd)
--ahead true audio-source only: asked before the song plays (ahead: true)
+ --lines FILE [--language L] lyrics-romanize only: the song's lines, one per row (the ones in another
+ script than Latin are sent, by index), and their language (ja, ko, ru...)
run <folder|zip> track [options] delivers the "track" event (same options, and --origin, --provider)
run <folder|zip> playback [options] delivers a play of the song: start, a progress every 10 s,
[--played MS] [--leave skip|end|stop] [--context URI] [--shuffle true] [--source local|spotify]
@@ -67,8 +70,8 @@ private const val USAGE = """myspoti-ext: build and try Myspoti extensions on a
pack <folder> [out-folder] builds <id>-<version>.zip and prints its index entry
index <folder-of-zips> <name> writes index.json for a repository of packages
-Hooks: lyrics, audio-source, download-source, trackinfo, home, search (--query Q), menu (--kind track|album|
-playlist|artist), player, page, message (--data JSON), tap (--action ID), status (live or not). Each hook gets the
+Hooks: lyrics, lyrics-romanize (--lines FILE), audio-source, download-source, trackinfo, home, search (--query Q),
+menu (--kind track|album|playlist|artist), player, page, message (--data JSON), tap (--action ID), status (live or not). Each hook gets the
app's own time limit (HookBudgets). Everything the manifest asks is granted here. Without --cdp,
myspoti.spotify has no account and its calls fail."""
@@ -216,6 +219,7 @@ private fun run(path: File, hookName: String, rest: List<String>) {
if (k == "set") settings[v.substringBefore('=')] = v.substringAfter('=') else opts[k] = v
i += 2
}
+ opts["lines"]?.let { opts["text"] = File(it).readText() }
val artist = opts["artist"] ?: ""
val track = TrackInfo(
id = opts["id"] ?: "", uri = opts["id"]?.let { "spotify:track:$it" } ?: "", title = opts["title"] ?: usage(),
@@ -239,6 +243,8 @@ private fun runScript(rt: ExtensionRuntime, m: Manifest, hookName: String, track
if (!rt.provides(hook)) throw ExtensionException("this extension does not provide $hookName (or its action is not in the manifest)")
val started = System.currentTimeMillis()
val input = hookInput(hook, track, opts) ?: usage()
+ // The app asks only when a line needs it: a song all in Latin letters is never sent.
+ if (hook == Hook.LYRICS_ROMANIZE && Romanize.asked(input).isEmpty()) { println("— nothing to romanize: no line in another script than Latin"); return }
if (hook == Hook.STATUS) {
// As the app asks it: only live: false is inactive; a failure or a late answer proves nothing.
val s = ExtensionStatus.probe(rt, HookBudgets.STATUS)
@@ -291,6 +297,16 @@ private fun runScript(rt: ExtensionRuntime, m: Manifest, hookName: String, track
}
}
Hook.PAGE -> PageContent.parse(out, m.name).let { println("✓ page \"${it.title}\" ($ms ms)\n${it.html.take(2_000)}") }
+ Hook.LYRICS_ROMANIZE -> {
+ // As the app keeps them: only the lines it asked for, each line next to its romanization.
+ val asked = Romanize.asked(input)
+ val got = Romanize.parse(out).filterKeys { it in asked }
+ if (got.isEmpty()) println("— no romanization ($ms ms)")
+ else {
+ println("✓ ${got.size} of ${asked.size} line(s) romanized ($ms ms)")
+ asked.forEach { (i, text) -> println(" [$i] $text | ${got[i] ?: "—"}") }
+ }
+ }
else -> println("✓ $out ($ms ms)")
}
}
diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt
index 138ea248..abffed83 100644
--- a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt
+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt
@@ -18,6 +18,7 @@ import app.myspoti.extensions.Manifest
import app.myspoti.extensions.MemoryStorage
import app.myspoti.extensions.Outcome
import app.myspoti.extensions.PlaybackEvent
+import app.myspoti.extensions.Romanize
import app.myspoti.extensions.Storage
import app.myspoti.extensions.TrackInfo
import kotlinx.serialization.json.Json
@@ -39,8 +40,14 @@ import java.net.SocketTimeoutException
import java.net.URI
import java.net.UnknownHostException
-/** The input the app gives [hook] for [track] ([opts]: `quality`, `ahead`, `query`, `kind`, `data`, `action`); null: `tap` without an action. */
+/**
+ * The input the app gives [hook] for [track] ([opts]: `quality`, `ahead`, `query`, `kind`, `data`,
+ * `action`, and for lyrics-romanize `text`, the song's lines one per row, and `language`); null:
+ * `tap` without an action, lyrics-romanize without its lines.
+ */
internal fun hookInput(hook: Hook, track: TrackInfo, opts: Map<String, String>): String? = when (hook) {
+ // The lines the app would send: the ones in another script than Latin, by their index in the song.
+ Hook.LYRICS_ROMANIZE -> opts["text"]?.let { text -> Romanize.request(track, opts["language"], Romanize.wanted(text.lines(), { it }, { false })) }
Hook.DOWNLOAD_SOURCE -> DownloadQuery.toJson(track, opts["quality"] ?: "cd")
Hook.AUDIO_SOURCE -> AudioQuery.toJson(track, opts["ahead"] == "true")
Hook.SEARCH -> buildJsonObject { put("query", opts["query"] ?: track.title) }.toString()
@@ -66,6 +73,7 @@ internal fun classify(hook: Hook, raw: String?, name: String): Outcome = try {
Hook.AUDIO_SOURCE -> if (AudioStream.parse(raw) != null) Outcome.Found else Outcome.NotFound
Hook.DOWNLOAD_SOURCE -> if (DownloadFile.parseList(raw).isNotEmpty()) Outcome.Found else Outcome.NotFound
Hook.LYRICS -> if (LyricsResult.parse(raw, name) != null) Outcome.Found else Outcome.NotFound
+ Hook.LYRICS_ROMANIZE -> if (Romanize.parse(raw).isNotEmpty()) Outcome.Found else Outcome.NotFound
else -> Outcome.Found
}
}
@@ -242,8 +250,11 @@ class ScenarioRunner(
val opts = buildMap {
str("quality")?.let { put("quality", it) }; str("ahead")?.let { put("ahead", it) }
s["data"]?.let { put("data", it.toString()) }; str("action")?.let { put("action", it) }; str("query")?.let { put("query", it) }
+ str("language")?.let { put("language", it) }
+ (s["lines"] as? JsonArray)?.let { a -> put("text", a.joinToString("\n") { (it as? JsonPrimitive)?.contentOrNull.orEmpty() }) }
}
- val input = s["input"]?.toString() ?: hookInput(hook, track, opts) ?: return StepResult(index, "hook $name", null, 0, listOf("tap needs \"action\""))
+ val input = s["input"]?.toString() ?: hookInput(hook, track, opts)
+ ?: return StepResult(index, "hook $name", null, 0, listOf(if (hook == Hook.TAP) "tap needs \"action\"" else "$name needs \"lines\" (or \"input\")"))
val cancelAt = (s["cancelAtMs"] as? JsonPrimitive)?.longOrNull
val budget = HookBudgets.of(hook).let { b -> cancelAt?.coerceAtMost(b) ?: b }
if (hook == Hook.STATUS) {
diff --git a/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/RomanizeHookTest.kt b/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/RomanizeHookTest.kt
new file mode 100644
index 00000000..6d0e2d88
--- /dev/null
+++ b/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/RomanizeHookTest.kt
@@ -0,0 +1,38 @@
+package app.myspoti.extensions.cli
+
+import app.myspoti.extensions.Hook
+import app.myspoti.extensions.Manifest
+import app.myspoti.extensions.Romanize
+import app.myspoti.extensions.TrackInfo
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+
+/** The lyrics-romanize hook in the runner: the lines the app would send, and a script answering in the real sandbox. */
+class RomanizeHookTest {
+ private fun res(name: String) = File(javaClass.classLoader.getResource(name)!!.toURI())
+ private val dir = res("romanize-ext")
+ private val manifest = Manifest.parse(File(dir, "manifest.json").readText())
+ private val script = File(dir, manifest.main).readText()
+ private val track = TrackInfo("", "", "Title", "Artist", listOf("Artist"), "", 0)
+
+ @Test fun theInputHoldsTheLinesInAnotherScriptByTheirIndexInTheSong() {
+ val input = hookInput(Hook.LYRICS_ROMANIZE, track, mapOf("text" to "Intro\n夢ならば\n♪\n사랑해", "language" to "ja"))!!
+ assertEquals(mapOf(1 to "夢ならば", 3 to "사랑해"), Romanize.asked(input))
+ assertNull(hookInput(Hook.LYRICS_ROMANIZE, track, emptyMap()))
+ }
+
+ @Test fun aScenarioStepSendsItsLinesAndReadsTheAnswer() {
+ val r = ScenarioRunner(manifest, script, Scenario.parse("""{ "offline": true, "steps": [
+ { "hook": "lyrics-romanize", "language": "ja", "lines": ["Intro", "夢ならば"], "expect": { "outcome": "found" } },
+ { "hook": "lyrics-romanize", "lines": ["Привет"], "expect": { "outcome": "not-found" } } ] }"""), echo = {}).run()
+ assertTrue(r.joinToString("\n"), r.all { it.ok })
+ }
+
+ @Test fun aStepWithoutLinesSaysWhatItNeeds() {
+ val r = ScenarioRunner(manifest, script, Scenario.parse("""{ "offline": true, "steps": [ { "hook": "lyrics-romanize" } ] }"""), echo = {}).run()
+ assertEquals(listOf("lyrics-romanize needs \"lines\" (or \"input\")"), r.single().problems)
+ }
+}
diff --git a/base/extensions-cli/src/test/resources/romanize-ext/main.js b/base/extensions-cli/src/test/resources/romanize-ext/main.js
new file mode 100644
index 00000000..c9aa098d
--- /dev/null
+++ b/base/extensions-cli/src/test/resources/romanize-ext/main.js
@@ -0,0 +1,11 @@
+// The lines it knows, by text; an older Myspoti without the hook never calls it.
+var KNOWN = { '夢ならば': 'yume naraba', '사랑해': 'saranghae' };
+
+myspoti.provide('lyrics-romanize', function (input) {
+ if (myspoti.features.indexOf('lyrics.romanize') < 0) throw new Error('lyrics.romanize is not a feature of this Myspoti');
+ var lines = [];
+ input.lines.forEach(function (l) {
+ if (KNOWN[l.text]) lines.push({ index: l.index, romanization: KNOWN[l.text] });
+ });
+ return lines.length ? { lines: lines } : null;
+});
diff --git a/base/extensions-cli/src/test/resources/romanize-ext/manifest.json b/base/extensions-cli/src/test/resources/romanize-ext/manifest.json
new file mode 100644
index 00000000..1a0eb2c6
--- /dev/null
+++ b/base/extensions-cli/src/test/resources/romanize-ext/manifest.json
@@ -0,0 +1,10 @@
+{
+ "id": "io.github.test.romanize",
+ "name": "Sample Romanizer",
+ "version": "1.0.0",
+ "author": "Test",
+ "description": "A tiny romanizer for the runner's tests: the lines it knows, nothing for the others.",
+ "actions": [
+ { "name": "lyrics.romanize", "why": "Romanizes the few lines it knows" }
+ ]
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt
index 9eab5883..d856a018 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt
@@ -58,6 +58,8 @@ enum class Action(
"myspoti.player.current(); myspoti.on('track' | 'playback'); spotify.player state, queue, volume"),
LYRICS_PROVIDE("lyrics.provide", Level.NORMAL, Area.LYRICS, "Lyrics", "Provide lyrics",
"myspoti.provide('lyrics', fn(track) → lyrics)", takeover = true),
+ LYRICS_ROMANIZE("lyrics.romanize", Level.NORMAL, Area.LYRICS, "Abc", "Romanize lyrics",
+ "myspoti.provide('lyrics-romanize', fn({ track, language, lines }) → { lines: [{ index, romanization }] }), for the lines in another script than Latin their source left without one", takeover = true),
TRACKINFO_PROVIDE("trackinfo.provide", Level.NORMAL, Area.LYRICS, "Info", "Add song details",
"myspoti.provide('trackinfo', fn(track) → blocks), shown in the song's credits sheet", takeover = true),
AUDIO_SOURCE("audio.source", Level.CRITICAL, Area.AUDIO, "Headphones", "Play audio from elsewhere",
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Conflicts.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Conflicts.kt
index 829f8220..195e1a80 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Conflicts.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Conflicts.kt
@@ -15,7 +15,7 @@ enum class Mode { ADDITIVE, EXCLUSIVE, ORDERED, SHARED }
val Action.mode: Mode
get() = when (this) {
Action.AUDIO_SOURCE, Action.DOWNLOAD_SOURCE -> Mode.ORDERED
- Action.LYRICS_PROVIDE, Action.TRACKINFO_PROVIDE, Action.HOME_SECTIONS, Action.SEARCH_PROVIDE,
+ Action.LYRICS_PROVIDE, Action.LYRICS_ROMANIZE, Action.TRACKINFO_PROVIDE, Action.HOME_SECTIONS, Action.SEARCH_PROVIDE,
Action.MENU_ITEMS, Action.PLAYER_BUTTONS -> Mode.ADDITIVE
else -> Mode.SHARED
}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt
index ab10ebb1..12c554ff 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt
@@ -7,6 +7,8 @@ package app.myspoti.extensions
object HookBudgets {
/** A lyrics hook call. */
const val LYRICS = 8_000L
+ /** A lyrics-romanize hook call: every line of one song left to romanize. */
+ const val ROMANIZE = 8_000L
/** An audio-source hook call. */
const val AUDIO = 15_000L
/** A download-source hook call (an extension may try several places). */
@@ -29,6 +31,7 @@ object HookBudgets {
/** The budget of a call to [hook]. */
fun of(hook: Hook): Long = when (hook) {
Hook.LYRICS -> LYRICS
+ Hook.LYRICS_ROMANIZE -> ROMANIZE
Hook.AUDIO_SOURCE -> AUDIO
Hook.DOWNLOAD_SOURCE -> DOWNLOAD
Hook.PAGE -> PAGE
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt
index c9bd1001..47e37e76 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt
@@ -386,6 +386,8 @@ data class Ask(val key: String, val level: Level, val why: String = "", val host
enum class Hook(val key: String, val action: Action?) {
/** Lyrics for a song, asked along the app's own sources. */
LYRICS("lyrics", Action.LYRICS_PROVIDE),
+ /** Romanizations of the lines of a song's lyrics written in another script than Latin ([Romanize]). */
+ LYRICS_ROMANIZE("lyrics-romanize", Action.LYRICS_ROMANIZE),
/** Where a song's audio comes from; it then plays in Myspoti's own player, like a download. */
AUDIO_SOURCE("audio-source", Action.AUDIO_SOURCE),
/** The files a song can be downloaded from: the app downloads, checks, encrypts and keeps them. */
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Romanize.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Romanize.kt
new file mode 100644
index 00000000..d53748d6
--- /dev/null
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Romanize.kt
@@ -0,0 +1,86 @@
+package app.myspoti.extensions
+
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.addJsonObject
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonArray
+
+/**
+ * The `lyrics-romanize` hook: the lines of a song's lyrics written in another script than Latin
+ * (Japanese, Korean, Cyrillic...) that their source left without a romanization are sent by
+ * index, and the extension answers the romanizations it has. A romanization the source gave
+ * (Apple Music, NetEase) is never asked for nor replaced: it was written by people.
+ */
+object Romanize {
+ /** At most this many characters in a romanization, as in a line of lyrics. */
+ const val MAX_TEXT = 500
+
+ // Digits, punctuation, symbols ("♪") and combining marks belong to no script of their own.
+ private val NEUTRAL = setOf(Character.UnicodeScript.LATIN, Character.UnicodeScript.COMMON, Character.UnicodeScript.INHERITED)
+
+ /** Whether [text] has a letter of another script than Latin: what a romanization is for. */
+ fun needs(text: String): Boolean {
+ var i = 0
+ while (i < text.length) {
+ val cp = text.codePointAt(i)
+ if (Character.isLetter(cp) && Character.UnicodeScript.of(cp) !in NEUTRAL) return true
+ i += Character.charCount(cp)
+ }
+ return false
+ }
+
+ /**
+ * The lines a romanization is asked for, by their index in [lines]: the ones not [romanized]
+ * yet whose [text] [needs] one, in order.
+ */
+ fun <T> wanted(lines: List<T>, text: (T) -> String, romanized: (T) -> Boolean): Map<Int, String> = buildMap {
+ lines.forEachIndexed { i, line -> if (!romanized(line) && needs(text(line))) put(i, text(line)) }
+ }
+
+ /** The hook's input: `{ track, language?, lines: [{ index, text }] }`, [language] as the lyrics' source gives it. */
+ fun request(track: TrackInfo, language: String?, lines: Map<Int, String>): String = buildJsonObject {
+ put("track", ExtJson.encodeToJsonElement(TrackInfo.serializer(), track))
+ language?.let { put("language", it) }
+ putJsonArray("lines") { lines.forEach { (index, text) -> addJsonObject { put("index", index); put("text", text) } } }
+ }.toString()
+
+ /** The lines a [request] asks for, index → text: what the desktop runner prints the answers against. */
+ fun asked(request: String): Map<Int, String> {
+ val lines = runCatching { ExtJson.parseToJsonElement(request).jsonObject["lines"] as? JsonArray }.getOrNull() ?: return emptyMap()
+ return buildMap {
+ for (e in lines) {
+ val l = e as? JsonObject ?: continue
+ val index = (l["index"] as? JsonPrimitive)?.intOrNull ?: continue
+ put(index, (l["text"] as? JsonPrimitive)?.contentOrNull.orEmpty())
+ }
+ }
+ }
+
+ /**
+ * `{ lines: [{ index, romanization }] }` → index → romanization, trimmed, [MAX_TEXT] characters
+ * at most. A line that is not an object, an index that is not a whole number, a romanization
+ * that is not a text or is blank, and an index already answered are ignored, never an error;
+ * whether an index was asked is the caller's to check. The answer itself must be an object
+ * with `lines`.
+ */
+ fun parse(json: String): Map<Int, String> {
+ val o = runCatching { ExtJson.parseToJsonElement(json).jsonObject }.getOrNull()
+ ?: throw ExtensionException("lyrics-romanize: not an object")
+ val raw = o["lines"] as? JsonArray
+ ?: throw ExtensionException("lyrics-romanize: \"lines\" (an array of { index, romanization })")
+ val out = LinkedHashMap<Int, String>()
+ for (e in raw) {
+ val l = e as? JsonObject ?: continue
+ val index = (l["index"] as? JsonPrimitive)?.intOrNull ?: continue
+ val text = (l["romanization"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.take(MAX_TEXT)?.ifBlank { null } ?: continue
+ out.putIfAbsent(index, text)
+ }
+ return out
+ }
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Store.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Store.kt
index 1e7527f5..3286f9d1 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Store.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Store.kt
@@ -21,7 +21,7 @@ enum class Category(val key: String) {
/** The actions one of which an extension needs to be filed here (empty: any extension fits). */
val needs: Set<Action>
get() = when (this) {
- LYRICS -> setOf(Action.LYRICS_PROVIDE, Action.TRACKINFO_PROVIDE)
+ LYRICS -> setOf(Action.LYRICS_PROVIDE, Action.LYRICS_ROMANIZE, Action.TRACKINFO_PROVIDE)
PLAYBACK -> setOf(Action.PLAYBACK_CONTROL, Action.PLAYBACK_QUEUE, Action.PLAYBACK_EVENTS, Action.AUDIO_SOURCE, Action.PLAYER_BUTTONS)
LIBRARY -> setOf(Action.LIBRARY_READ, Action.LIBRARY_WRITE, Action.PLAYLISTS_WRITE)
DISCOVERY -> setOf(Action.HOME_SECTIONS, Action.SEARCH_PROVIDE, Action.SPOTIFY_CATALOG)
diff --git a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
index 25487743..78abc371 100644
--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
@@ -123,12 +123,12 @@
/**
* What this app understands beyond the first API, for an extension to adapt to: "audio.manifest",
- * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "results" (source hooks may answer { outcome }), "settings.section" (manifest section, role, perNetwork), "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.
+ * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "results" (source hooks may answer { outcome }), "settings.section" (manifest section, role, perNetwork), "lyrics.romanize" (the lyrics-romanize hook), "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.
*/
sources: Object.freeze({ race: function (hook, query, lanes) {
return parse(host.sourceRace(String(hook),JSON.stringify(query),JSON.stringify(lanes)));
} }),
- features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'results', 'download.transform', 'audio.transform', 'sources.race', 'settings.section'].concat(parse(host.info()).mirror ? ['player.localMute'] : [], parse(host.info()).attest ? ['attest'] : [])),
+ features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'results', 'download.transform', 'audio.transform', 'sources.race', 'settings.section', 'lyrics.romanize'].concat(parse(host.info()).mirror ? ['player.localMute'] : [], parse(host.info()).attest ? ['attest'] : [])),
/**
* A sign-in page (webview.auth): open({ url, callback, hidden }) shows url in a web view of its
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt
index 7e125edc..3759a0d3 100644
--- a/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt
@@ -31,7 +31,7 @@ class ActionsTest {
// ── The catalogue ──
@Test fun theCatalogueIsClosedAndComplete() {
- assertEquals(24, Action.entries.size)
+ assertEquals(25, Action.entries.size)
assertEquals(Action.entries.size, Action.entries.map { it.key }.toSet().size)
assertEquals(
setOf("audio.source", "download.source", "library.write", "playlists.write", "spotify.raw", "webview.page", "webview.auth", "playback.mirror"),
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/RomanizeTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/RomanizeTest.kt
new file mode 100644
index 00000000..3ffdf405
--- /dev/null
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/RomanizeTest.kt
@@ -0,0 +1,88 @@
+package app.myspoti.extensions
+
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The lyrics-romanize hook: which lines are asked, the input sent, and an answer read leniently. */
+class RomanizeTest {
+ private val track = TrackInfo("id1", "spotify:track:id1", "Title", "Artist", listOf("Artist"), "Album", 1000)
+
+ @Test fun aLetterOutsideLatinScriptNeedsARomanization() {
+ assertTrue(Romanize.needs("夢ならば"))
+ assertTrue(Romanize.needs("ありがとう"))
+ assertTrue(Romanize.needs("사랑해"))
+ assertTrue(Romanize.needs("Привет"))
+ assertTrue(Romanize.needs("I love you 君を"))
+ assertTrue(Romanize.needs("ガ"))
+ }
+
+ @Test fun latinLettersDigitsAndSymbolsDoNot() {
+ assertFalse(Romanize.needs("Hello, world"))
+ assertFalse(Romanize.needs("Ça va, déjà vu"))
+ assertFalse(Romanize.needs("♪"))
+ assertFalse(Romanize.needs("(ooh) 1, 2, 3!"))
+ assertFalse(Romanize.needs(""))
+ }
+
+ @Test fun wantedKeepsTheIndexOfTheLinesStillWithoutARomanization() {
+ val lines = listOf("Intro" to null, "夢ならば" to null, "♪" to null, "今でも" to "ima demo", "사랑해" to "")
+ val wanted = Romanize.wanted(lines, { it.first }, { !it.second.isNullOrBlank() })
+ assertEquals(mapOf(1 to "夢ならば", 4 to "사랑해"), wanted)
+ }
+
+ @Test fun theRequestCarriesTheTrackTheLanguageAndTheLinesByIndex() {
+ val o = Json.parseToJsonElement(Romanize.request(track, "ja", mapOf(1 to "夢ならば", 4 to "今でも"))).jsonObject
+ assertEquals("Title", o.getValue("track").jsonObject.getValue("title").jsonPrimitive.content)
+ assertEquals("ja", o.getValue("language").jsonPrimitive.content)
+ val lines = o.getValue("lines").jsonArray.map { it.jsonObject }
+ assertEquals(listOf(1, 4), lines.map { it.getValue("index").jsonPrimitive.int })
+ assertEquals(listOf("夢ならば", "今でも"), lines.map { it.getValue("text").jsonPrimitive.content })
+ assertNull(Json.parseToJsonElement(Romanize.request(track, null, emptyMap())).jsonObject["language"])
+ }
+
+ @Test fun askedReadsTheLinesOfARequestBack() {
+ assertEquals(mapOf(1 to "夢ならば", 4 to "今でも"), Romanize.asked(Romanize.request(track, "ja", mapOf(1 to "夢ならば", 4 to "今でも"))))
+ assertEquals(emptyMap<Int, String>(), Romanize.asked("not json"))
+ }
+
+ @Test fun anAnswerIsReadByIndexTrimmedAndCapped() {
+ val long = "a".repeat(Romanize.MAX_TEXT + 20)
+ val got = Romanize.parse("""{"lines":[{"index":1,"romanization":" yume naraba "},{"index":"4","romanization":"$long"}]}""")
+ assertEquals("yume naraba", got[1])
+ assertEquals(Romanize.MAX_TEXT, got[4]?.length)
+ }
+
+ @Test fun aWrongLineIsIgnoredNeverAnError() {
+ val got = Romanize.parse(
+ """{"lines":[5,{"romanization":"no index"},{"index":1.5,"romanization":"x"},{"index":2,"romanization":7},
+ {"index":3,"romanization":" "},{"index":6,"romanization":"first"},{"index":6,"romanization":"second"}]}""",
+ )
+ assertEquals(mapOf(6 to "first"), got)
+ }
+
+ @Test(expected = ExtensionException::class) fun anAnswerThatIsNotAnObjectFails() {
+ Romanize.parse("[1, 2]")
+ }
+
+ @Test(expected = ExtensionException::class) fun anAnswerWithoutLinesFails() {
+ Romanize.parse("""{"outcome":"not-found"}""")
+ }
+
+ @Test fun theHookIsUnlockedByItsOwnActionInTheLyricsArea() {
+ assertEquals(Hook.LYRICS_ROMANIZE, Hook.of("lyrics-romanize"))
+ assertEquals(Action.LYRICS_ROMANIZE, Hook.LYRICS_ROMANIZE.action)
+ assertEquals(Area.LYRICS, Action.LYRICS_ROMANIZE.area)
+ assertEquals(Level.NORMAL, Action.LYRICS_ROMANIZE.level)
+ assertEquals(Mode.ADDITIVE, Action.LYRICS_ROMANIZE.mode)
+ assertEquals(HookBudgets.ROMANIZE, HookBudgets.of(Hook.LYRICS_ROMANIZE))
+ assertTrue(Category.LYRICS.fits(setOf(Action.LYRICS_ROMANIZE)))
+ }
+}
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt
index c6165fb3..f6cfbfcf 100644
--- a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt
@@ -199,7 +199,7 @@ class SandboxTest {
}
@Test fun featuresNameWhatThisAppUnderstands() {
- assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64,results,download.transform,audio.transform,sources.race,settings.section"}""", eval("return myspoti.features.join(',');"))
+ assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64,results,download.transform,audio.transform,sources.race,settings.section,lyrics.romanize"}""", eval("return myspoti.features.join(',');"))
}
@Test fun localMuteFeatureIsListedOnlyWhenMirrorIsGranted() {
diff --git a/docs/extensions/API.md b/docs/extensions/API.md
index 05f6b01d..21918d16 100644
--- a/docs/extensions/API.md
+++ b/docs/extensions/API.md
@@ -2,7 +2,7 @@
An extension is a small JavaScript file plus a `manifest.json`. Myspoti runs it in a sandbox. What
it may do is a list of **actions** from a closed catalogue the app defines (section 4): provide
-lyrics or song details, add Home sections, search results, menu entries or player buttons (as
+lyrics, their romanization or song details, add Home sections, search results, menu entries or player buttons (as
native blocks the app draws itself, section 3), give a song's audio or download files, show its own
web page, sign in on a website, react to the song playing, and, if the user allows it, read or change the signed-in
Spotify account. Each action has a fixed icon, a short label, a level (normal or critical) and the
@@ -122,7 +122,7 @@ extensions did there ("Lyrics of X from Y", "Skipped by Z") with a one-tap Turn
| `replaces` | string[] | `[]` | Extension ids this one takes the place of (10 at most): installing it offers to turn them off. |
| `conflictsWith` | string[] | `[]` | Extension ids that must not run with this one (10 at most): the user picks which to keep. Either side declaring it is enough. |
| `icon` | string | none | A `.png` at the root of the package (square, 256 px or less). Without it, `icon.png` is used if the package has one, else a tile with the name's first letter. |
-| `category` | string | `other` | Where the store files it, one of a fixed list: `lyrics` (needs `lyrics.provide` or `trackinfo.provide`), `playback` (Playback & audio: a `playback.*`, `audio.source` or `player.buttons` action), `library` (`library.read`, `library.write` or `playlists.write`), `discovery` (`home.sections`, `search.provide` or `spotify.catalog`), `stats` (`playback.events` or `library.read`), `look` (Look & feel: a blocks action or `webview.page`), `social` (`network`, `library.read` or `spotify.catalog`), `tools`, `other`. A category the actions do not fit, or an unknown one, is filed under `other` (`myspoti-ext check` says so); an extension with `download.source` is always under `tools`. `tags` are shown and found by the search, not filtered on. |
+| `category` | string | `other` | Where the store files it, one of a fixed list: `lyrics` (needs `lyrics.provide`, `lyrics.romanize` or `trackinfo.provide`), `playback` (Playback & audio: a `playback.*`, `audio.source` or `player.buttons` action), `library` (`library.read`, `library.write` or `playlists.write`), `discovery` (`home.sections`, `search.provide` or `spotify.catalog`), `stats` (`playback.events` or `library.read`), `look` (Look & feel: a blocks action or `webview.page`), `social` (`network`, `library.read` or `spotify.catalog`), `tools`, `other`. A category the actions do not fit, or an unknown one, is filed under `other` (`myspoti-ext check` says so); an extension with `download.source` is always under `tools`. `tags` are shown and found by the search, not filtered on. |
| `tags` | string[] | `[]` | 8 at most, each 1 to 24 characters: lower case letters, digits, spaces, `-`. The store's search finds them. |
| `minAppVersion` | string | none | The oldest Myspoti it works on (`"2.0.2"`, `"2.0.2-beta.4"`), compared like semantic versions (a release is newer than its betas). An older Myspoti shows "Requires Myspoti 2.0.2 or newer" and does not install it. |
| `changelog` | string | `""` | What changed in this version, 2000 characters at most: shown on the store page and before an update. |
@@ -240,6 +240,7 @@ player.buttons action in the manifest`):
| Hook | Action | Input | Answer |
|---|---|---|---|
| `lyrics` | `lyrics.provide` | track | lyrics (below) |
+| `lyrics-romanize` | `lyrics.romanize` | `{ track, language?, lines }` | romanizations, by line (below) |
| `audio-source` | `audio.source` | track | `{ url, … }` |
| `download-source` | `download.source` | track + quality | files |
| `trackinfo` | `trackinfo.provide` | track | blocks, under the song's credits |
@@ -252,8 +253,9 @@ player.buttons action in the manifest`):
| `tap` | any blocks action | `{ action, surface, context }` | nothing (the app asks the blocks again) |
| `status` | none | `{}` | `{ live, detail? }` (below) |
-The lyrics, song details, Home, search, menu and player hooks are **additive**: every extension is
-asked, the answers merged in the area's order (lyrics: the best, ties to the higher one). Audio and
+The lyrics, romanization, song details, Home, search, menu and player hooks are **additive**: every extension is
+asked, the answers merged in the area's order (lyrics: the best, ties to the higher one;
+romanizations: each extension is sent the lines the ones before it left without one). Audio and
downloads are **ordered**: asked one after the other in the user's order until one answers (section 4.2). Registering twice replaces. Returning
`null`/`undefined` means "no answer": the app goes on without this extension. A throw is a
failure (recorded as the extension's last error, shown on its page; 3 in a row turn it off). A
@@ -308,6 +310,40 @@ simply does not read these fields.
Action: `lyrics.provide` (normal). Usually you also need `network`.
+### `lyrics-romanize`
+
+Asked once a song's lyrics are found, whatever their source, for the lines written in another
+script than Latin (Japanese, Korean, Chinese, Cyrillic, Greek...) that the source left without a
+`romanization`. The lyrics show at once; the romanizations join them when they come and are kept
+with them. A romanization the source gave (Apple Music, NetEase, a lyrics extension) is never asked
+for nor replaced.
+
+```js
+// input
+{ track: { id, uri, title, … }, // the track every hook receives
+ language: 'ja', // optional: the lyrics' language, when their source says it
+ lines: [ { index: 3, text: '夢ならば' }, … ] } // only the lines to romanize, by index in the song
+
+// answer
+{ lines: [ { index: 3, romanization: 'yume naraba' }, … ] }
+```
+
+Answer the lines you can, by `index`, and leave the others out; return `null` when you have none.
+An index that was not asked, a line that is not an object, an `index` that is not a whole number,
+a `romanization` that is not a text or is blank, and an index already answered are ignored, never
+an error; an answer that is not an object with `lines` is a failure. A romanization is trimmed, 500
+characters at most, and dropped when it only repeats its line. A line with no letter outside Latin
+(`♪`, `(ooh)`, English) is never sent, and a song without one is not asked at all. Several
+romanizers are asked in the lyrics area's order, each one sent only the lines the ones before it
+left without one: one for Japanese and one for Korean complete each other. The time limit (section
+7) covers every line of the song in one call.
+
+Feature `lyrics.romanize`. Like any action it does not know, an older Myspoti refuses a package
+that asks this one (section 2).
+
+Action: `lyrics.romanize` (normal). It needs no other action: ask `network` only if your
+romanizer calls a server.
+
### `audio-source`
Where the audio of a song is. The song then plays in Myspoti's own player, like a download;
@@ -704,6 +740,7 @@ until the user accepts them all with the same tick.
| `playback.queue` | QueueMusic | Edit the queue | normal | shared | `spotify.player` addToQueue, playNext, moveInQueue, removeFromQueue, clearQueue |
| `playback.events` | GraphicEq | Know what you play | normal | shared | `myspoti.player.current()`, `myspoti.on('track' \| 'playback')`, `spotify.player` state, queue, volume, media (`myspoti.spotify.media`) |
| `lyrics.provide` | Lyrics | Provide lyrics | normal | additive, takeover | `lyrics` hook |
+| `lyrics.romanize` | Abc | Romanize lyrics | normal | additive, takeover | `lyrics-romanize` hook |
| `trackinfo.provide` | Info | Add song details | normal | additive, takeover | `trackinfo` hook |
| `audio.source` | Headphones | Play audio from elsewhere | **critical** | ordered, takeover | `audio-source` hook |
| `download.source` | Download | Provide downloads | **critical** | ordered, takeover | `download-source` hook |
@@ -739,7 +776,7 @@ migrated the same way when the app starts.
### 4.2 Living together
-- **Additive** actions (lyrics, song details, Home, search, menus, player): every extension adds;
+- **Additive** actions (lyrics, romanizations, song details, Home, search, menus, player): every extension adds;
answers are merged in the area's order, duplicates dropped, quotas per extension (section 3).
- **Ordered** actions (`audio.source`, `download.source`): every source is asked in the order the
user sets in Settings (Playback, Downloads), each action its own order, until one answers. A new
@@ -792,7 +829,7 @@ A script that throws while loading fails to load, with `file:line` in the messag
|---|---|
| `myspoti.apiVersion` | `1`. |
| `myspoti.extension` | `{ id, name, version }` from the manifest. |
-| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `results` (section 3, "Outcomes"), `settings.section` (section 2: a setting's `section`, `role`, `perNetwork`), `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. |
+| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `results` (section 3, "Outcomes"), `settings.section` (section 2: a setting's `section`, `role`, `perNetwork`), `lyrics.romanize` (section 3, `lyrics-romanize`), `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. |
| `myspoti.provide(hook, fn)` | Section 3. |
| `myspoti.on('track' \| 'playback', fn)` | Section 3. Needs `playback.events`. |
| `myspoti.on('auth', fn)` | Section 3, sign in. Needs `webview.auth`. |
@@ -1242,7 +1279,7 @@ is. `playlists.setCover` takes a JPEG as base64.
| What | Limit |
|---|---|
| Loading the script (its top level; compiling it is not counted) | 3 s |
-| A hook call | One table for the app and the desktop runner (`HookBudgets`): 8 s for `lyrics`, 15 s for `audio-source`, 30 s for `download-source`, 3 s for blocks hooks, `tap` and `message`, 5 s for `page` and `status` |
+| A hook call | One table for the app and the desktop runner (`HookBudgets`): 8 s for `lyrics` and `lyrics-romanize`, 15 s for `audio-source`, 30 s for `download-source`, 3 s for blocks hooks, `tap` and `message`, 5 s for `page` and `status` |
| A `track` or `playback` event | 3 s |
| A `setting` or `online` event | 30 s |
| An `auth` event | 10 s |
@@ -1278,6 +1315,7 @@ to the confirmation prompt below. Give absolute paths.)
| `check <folder\|zip>` | Package validity only: prints the manifest's problems (`✗ ...`, e.g. a missing or too long `why`), says when it is an old manifest, loads the script, prints the hooks it provides and each action as the user sees it (icon name, label, level, why). It never calls a hook. Exit 1 on a problem. |
| `test <folder\|zip> --scenario file.json [--state file.json]` | Runs a scenario (below): hook calls, events and page messages in order with the app's time limits, requests answered or broken by rules, storage kept across steps. Prints each step (`✓`/`✗`, outcome, time); exit 1 when a step failed. |
| `run <folder\|zip> lyrics --title T --artist A [options]` | Calls the hook and prints what it answered, parsed the way the app parses it (lines, `synced`, `word by word`, or the audio URL and headers). |
+| `run <folder\|zip> lyrics-romanize --title T --artist A --lines FILE [--language L]` | Sends the lines of FILE (the song, one line per row) the app would send, the ones in another script than Latin by their index, and prints each next to the romanization the app keeps. |
| `run <folder\|zip> audio-source ...` | Same for the audio hook. |
| `run <folder\|zip> download-source ... [--quality hi-res\|cd\|small]` | Same for the download hook: prints the files, best first, as the app reads them (default quality `cd`). |
| `run <folder\|zip> audio-source ... [--ahead true]` | Asks for a song's audio (with `ahead: true` when given) and prints the answer as the app reads it: address or manifest, `expiresInMs`, quality. |
@@ -1367,8 +1405,9 @@ A scenario is a JSON file:
default; 429 when only `retryAfter` is given, in seconds, sent as `Retry-After`), `headers` and
`body` (text, or JSON written as text). `times: n` applies a rule to n requests only. Requests no
rule matches go to the network, or fail as a DNS error with `"offline": true`.
-- **Steps**: `{ hook, input?, track?, quality?, ahead?, data?, action?, query?, cancelAtMs? }` calls
- a hook (the input is built as the app builds it unless `input` is given); `cancelAtMs` ends the
+- **Steps**: `{ hook, input?, track?, quality?, ahead?, data?, action?, query?, lines?, language?, cancelAtMs? }` calls
+ a hook (the input is built as the app builds it unless `input` is given; `lines`, the song's lines,
+ and `language` for `lyrics-romanize`); `cancelAtMs` ends the
call at that time (outcome `cancelled`). `{ event, input? }` delivers an event. `{ message }` is
your page posting to you; what you answer or post back is the page's. `{ wait: ms }` waits.
`{ storage: { key: value \| null } }` checks your storage.