├── .github └── workflows │ └── release.yml ├── .gitignore ├── .idea ├── .gitignore ├── .name ├── gradle.xml ├── misc.xml ├── uiDesigner.xml └── vcs.xml ├── LICENSE ├── README.md ├── application ├── build.gradle.kts └── src │ └── main │ └── java │ └── me │ └── duncte123 │ └── lyrics │ ├── GeniusClient.java │ ├── HttpClientProvider.java │ ├── LyricsClient.java │ ├── lavalink │ └── Config.java │ └── utils │ ├── JsonUtils.java │ └── YouTubeUtils.java ├── build.gradle.kts ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml ├── lavalyrics ├── build.gradle.kts └── src │ └── main │ └── java │ └── me │ └── duncte123 │ └── lyrics │ └── lavalink │ ├── JavaAudioLyricsManager.java │ └── JavaLyricsManagerConfiguration.java ├── protocol ├── build.gradle.kts └── src │ └── main │ └── java │ └── me │ └── duncte123 │ └── lyrics │ ├── exception │ └── LyricsNotFoundException.java │ └── model │ ├── AlbumArt.java │ ├── Client.java │ ├── Context.java │ ├── Line.java │ ├── LongRange.java │ ├── Lyrics.java │ ├── SearchTrack.java │ ├── TextLyrics.java │ ├── TimedLyrics.java │ ├── Track.java │ └── request │ ├── BrowseRequest.java │ ├── NextRequest.java │ └── SearchRequest.java ├── settings.gradle.kts └── src └── main └── java └── me └── duncte123 └── lyrics └── lavalink └── RestHandler.java /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | push: 4 | release: 5 | types: [ published ] 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | env: 10 | LAVALINK_MAVEN_USERNAME: ${{ secrets.LAVALINK_MAVEN_USERNAME }} 11 | LAVALINK_MAVEN_PASSWORD: ${{ secrets.LAVALINK_MAVEN_PASSWORD }} 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v3 15 | with: 16 | fetch-depth: 0 17 | 18 | - name: Setup Java 19 | uses: actions/setup-java@v3 20 | with: 21 | distribution: zulu 22 | java-version: 17 23 | cache: gradle 24 | 25 | - name: Setup Gradle 26 | uses: gradle/gradle-build-action@v2 27 | 28 | - name: Build and Publish 29 | run: ./gradlew build publish --no-daemon 30 | 31 | - name: Upload main Artifact 32 | uses: actions/upload-artifact@v3 33 | with: 34 | name: java-lyrics-plugin.zip 35 | path: | 36 | build/libs/lyrics-*.jar 37 | 38 | - name: Upload plugin Artifact 39 | uses: actions/upload-artifact@v3 40 | with: 41 | name: java-lyrics-lavalyrics.zip 42 | path: | 43 | lavalyrics/build/libs/lavalyrics-*.jar 44 | 45 | release: 46 | needs: build 47 | runs-on: ubuntu-latest 48 | if: github.event_name == 'release' 49 | steps: 50 | - name: Checkout 51 | uses: actions/checkout@v3 52 | 53 | - name: Download main Artifact 54 | uses: actions/download-artifact@v3 55 | with: 56 | name: java-lyrics-plugin.zip 57 | 58 | - name: Download plugin Artifact 59 | uses: actions/download-artifact@v3 60 | with: 61 | name: java-lyrics-lavalyrics.zip 62 | 63 | - name: Upload Artifacts to GitHub Release 64 | uses: ncipollo/release-action@v1 65 | with: 66 | artifacts: | 67 | lyrics-*.jar 68 | lavalyrics-*.jar 69 | allowUpdates: true 70 | omitBodyDuringUpdate: true 71 | omitDraftDuringUpdate: true 72 | omitNameDuringUpdate: true 73 | omitPrereleaseDuringUpdate: true 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/modules.xml 9 | .idea/jarRepositories.xml 10 | .idea/compiler.xml 11 | .idea/libraries/ 12 | *.iws 13 | *.iml 14 | *.ipr 15 | out/ 16 | !**/src/main/**/out/ 17 | !**/src/test/**/out/ 18 | 19 | ### Eclipse ### 20 | .apt_generated 21 | .classpath 22 | .factorypath 23 | .project 24 | .settings 25 | .springBeans 26 | .sts4-cache 27 | bin/ 28 | !**/src/main/**/bin/ 29 | !**/src/test/**/bin/ 30 | 31 | ### NetBeans ### 32 | /nbproject/private/ 33 | /nbbuild/ 34 | /dist/ 35 | /nbdist/ 36 | /.nb-gradle/ 37 | 38 | ### VS Code ### 39 | .vscode/ 40 | 41 | ### Mac OS ### 42 | .DS_Store 43 | 44 | application.yml 45 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | java-lyrics-plugin -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Michael Rittmeister & Duncan Sterken 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [VERSION]: https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Fmaven.lavalink.dev%2Freleases%2Fme%2Fduncte123%2Fjava-lyrics-plugin%2Fmaven-metadata.xml 2 | 3 | # Lyrics.java 4 | A very simple lyrics client based on YouTube and [Lyrics.Kt](https://github.com/DRSchlaubi/lyrics.kt) 5 | 6 | ## Differences from Lyrics.kt 7 | The biggest difference between this version and the kotlin version is the filesize. 8 | At the time of writing, lyrics.kt plugin is about `696 KiB` in size, while this plugin is about `34 KiB` in size. A massive reduction. 9 | 10 | The second difference is the search endpoint. 11 | Instead of putting the query into the path of the url, this plugin opted to use query parameters for it. 12 | Making the endpoint more restfull. 13 | 14 | # Feature overview 15 | - Small plugin size 16 | - Lyrics from YouTube 17 | - Uses IP-rotation 18 | - Automatically get lyrics based on the currently playing track 19 | - Timestamped lyrics so you can highlight the current line. 20 | - Optional support for genius lyrics if none are found on YouTube. 21 | - Support for [LavaLyrics](https://github.com/topi314/LavaLyrics) (see the end of the readme) 22 | 23 | # Using with Lavalink 24 | 25 | Replace x.y.z with the current version ![Plugin version][VERSION] (remove the v prefix) 26 | 27 | ```yaml 28 | lavalink: 29 | plugins: 30 | - dependency: "me.duncte123:java-lyrics-plugin:x.y.z" 31 | repository: "https://maven.lavalink.dev/releases" # (optional) 32 | plugins: 33 | lyrics: 34 | countryCode: de #country code for resolving isrc tracks 35 | geniusApiKey: "Your Genius Client Access Token" # leave this out to disable genius searching. Get your api key (Client Access Token) from https://genius.com/api-clients 36 | ``` 37 | 38 | ## API for clients 39 | ```json5 40 | // GET /v4/lyrics/{videoId} (youtube lyrics only) 41 | // GET /v4/sessions/{sessionId}/players/{guildId}/lyrics 42 | // /v4/lyrics/search?query=...&source=genius (genius will always return the first result of text lyrics, default source is YouTube see below for different response) 43 | // Please note that the "album" key will be null for genius. 44 | 45 | { 46 | // can also be text 47 | "type": "timed", 48 | "track": { 49 | "title": "We Got the Moves", 50 | "author": "Electric Callboy", 51 | "album": "We Got the Moves", 52 | "albumArt": [ 53 | { 54 | "url": "https://lh3.googleusercontent.com/rDaGBvVRyBbHKJuQFFfIUuCLU36OuHHTjDz2u9xDwbIgD2MWM_P6L2L01IOOtoJvi7ks43OFeCqx0cRp=w60-h60-l90-rj", 55 | "height": 60, 56 | "width": 60 57 | } 58 | ] 59 | }, 60 | "source": "LyricFind", 61 | // Only present for type text 62 | "text": "", 63 | // Only present for type timed 64 | "lines": [ 65 | { 66 | "line": "♪", 67 | "range": { 68 | "start": 0, 69 | // start timestamp in ms since track start 70 | "end": 6510 71 | // end timestamp in ms since track start 72 | } 73 | }, 74 | { 75 | "line": "Summer mood", 76 | "range": { 77 | "start": 6510, 78 | "end": 7330 79 | } 80 | } 81 | ] 82 | } 83 | ``` 84 | ```json5 85 | // /v4/lyrics/search?query=... 86 | // /v4/lyrics/search?query=...&source=youtube (youtube is default) 87 | 88 | [ 89 | {"videoId": "UVXvQtm6ji0", "title": "We Got The moves"} 90 | ] 91 | ``` 92 | 93 | ## Using in your clients 94 | This plugin comes with a protocol library that allows you to use jackson for deserialization of the JSON. 95 | You can include the library as follows with gradle: 96 | 97 | ```gradle 98 | repositories { 99 | maven("https://jitpack.io") 100 | } 101 | 102 | dependencies { 103 | implementation(group = "com.github.DuncteBot.java-timed-lyrics", name = "protocol", version = "x.y.x") 104 | } 105 | ``` 106 | 107 | replace x.y.x with this version: [![](https://jitpack.io/v/DuncteBot/java-timed-lyrics.svg)](https://jitpack.io/#DuncteBot/java-timed-lyrics) 108 | 109 | # Using with lavalyrics 110 | 111 | To use this plugin with lavalyrics you need to include a different plugin. Please do not include both the main plugin and the lavalyrics plugin as they will conflict with each other. 112 | The Yml is as follows: 113 | 114 | ```yaml 115 | lavalink: 116 | plugins: 117 | - dependency: "me.duncte123.java-lyrics-plugin:lavalyrics:x.y.z" 118 | repository: "https://maven.lavalink.dev/releases" 119 | plugins: 120 | lyrics: 121 | countryCode: de #country code for resolving isrc tracks 122 | geniusApiKey: "Your Genius Client Access Token" # leave this out to disable genius searching. Get your api key (Client Access Token) from https://genius.com/api-clients 123 | ``` 124 | -------------------------------------------------------------------------------- /application/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | // `maven-publish` 4 | } 5 | 6 | group = "me.duncte123" 7 | version = rootProject.version 8 | 9 | java { 10 | toolchain { 11 | languageVersion = JavaLanguageVersion.of(17) 12 | } 13 | } 14 | 15 | tasks { 16 | compileJava { 17 | options.encoding = "UTF-8" 18 | } 19 | } 20 | 21 | dependencies { 22 | // LL holds all our versions 23 | compileOnly(libs.lavalink.api) 24 | compileOnly(libs.lavalink.server) 25 | compileOnly(libs.lavaplayer) 26 | compileOnly(libs.lavaplayer.rotator) 27 | compileOnly(libs.http) 28 | compileOnly(libs.jackson.annotations) 29 | compileOnly(libs.jsoup) 30 | compileOnly(libs.commons.io) 31 | 32 | implementation(projects.protocol) 33 | } 34 | 35 | //publishing { 36 | // publications { 37 | // create("maven") { 38 | // groupId = "me.duncte123.java-lyrics-plugin" 39 | // artifactId = "protocol" 40 | // from(components["java"]) 41 | // } 42 | // } 43 | //} 44 | -------------------------------------------------------------------------------- /application/src/main/java/me/duncte123/lyrics/GeniusClient.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics; 2 | 3 | import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser; 4 | import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface; 5 | import com.sedmelluq.discord.lavaplayer.track.AudioTrack; 6 | import me.duncte123.lyrics.exception.LyricsNotFoundException; 7 | import me.duncte123.lyrics.model.AlbumArt; 8 | import me.duncte123.lyrics.model.Lyrics; 9 | import me.duncte123.lyrics.model.TextLyrics; 10 | import me.duncte123.lyrics.model.Track; 11 | import org.apache.commons.io.IOUtils; 12 | import org.apache.http.client.methods.HttpGet; 13 | import org.jsoup.Jsoup; 14 | 15 | import java.io.IOException; 16 | import java.net.URLEncoder; 17 | import java.nio.charset.StandardCharsets; 18 | import java.util.List; 19 | import java.util.concurrent.ExecutorService; 20 | import java.util.concurrent.Executors; 21 | import java.util.concurrent.Future; 22 | 23 | public class GeniusClient implements AutoCloseable { 24 | private static final ExecutorService executor = Executors.newSingleThreadExecutor(); 25 | private final HttpClientProvider httpInterfaceManager; 26 | private final String apiKey; 27 | 28 | public GeniusClient(String apiKey, HttpClientProvider httpProvider) { 29 | this.apiKey = apiKey; 30 | this.httpInterfaceManager = httpProvider; 31 | } 32 | 33 | public Future findLyrics(AudioTrack track) { 34 | return search( 35 | "%s - %s".formatted(track.getInfo().title, track.getInfo().author) 36 | ); 37 | } 38 | 39 | public Future search(String query) { 40 | return executor.submit(() -> { 41 | try { 42 | final var geniusData = findGeniusData(query); 43 | final var lyricsText = loadLyrics(geniusData.url()); 44 | 45 | return new TextLyrics( 46 | new Track( 47 | geniusData.title(), 48 | geniusData.author(), 49 | null, 50 | List.of( 51 | new AlbumArt( 52 | geniusData.artwork(), 53 | -1, -1 54 | ) 55 | ) 56 | ), 57 | "genius.com", 58 | lyricsText 59 | ); 60 | } catch (IOException e) { 61 | throw new RuntimeException(e); 62 | } 63 | }); 64 | } 65 | 66 | public HttpInterface getHttpInterface() { 67 | return this.httpInterfaceManager.getHttpInterface(); 68 | } 69 | 70 | private GeniusData findGeniusData(String query) throws IOException { 71 | final var request = new HttpGet("https://api.genius.com/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)); 72 | 73 | request.setHeader("Authorization", "Bearer " + this.apiKey); 74 | 75 | try (final var response = getHttpInterface().execute(request)) { 76 | final var browser = JsonBrowser.parse(response.getEntity().getContent()); 77 | final long httpStatus = browser.get("meta").get("status").asLong(-1L); 78 | 79 | if (httpStatus != 200L) { 80 | throw new LyricsNotFoundException(); 81 | } 82 | 83 | final var hits = browser.get("response").get("hits"); 84 | 85 | // wat?? 86 | if (!hits.isList()) { 87 | throw new LyricsNotFoundException(); 88 | } 89 | 90 | final var hitValues = hits.values(); 91 | 92 | if (hitValues.isEmpty()) { 93 | throw new LyricsNotFoundException(); 94 | } 95 | 96 | final var firstHit = hitValues.stream() 97 | .filter((it) -> "song".equals(it.get("type").text())) 98 | .findFirst() 99 | .orElseThrow(LyricsNotFoundException::new); 100 | 101 | final var result = firstHit.get("result"); 102 | 103 | return new GeniusData( 104 | result.get("url").text(), 105 | result.get("title").text(), 106 | result.get("artist_names").text(), 107 | result.get("song_art_image_url").text() 108 | ); 109 | } 110 | } 111 | 112 | private String loadLyrics(String geniusUrl) throws IOException { 113 | final var request = new HttpGet(geniusUrl); 114 | 115 | try (final var response = getHttpInterface().execute(request)) { 116 | final String html = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); 117 | final var doc = Jsoup.parse(html); 118 | 119 | final var lyricsContainer = doc.select("div[data-lyrics-container]").first(); 120 | 121 | if (lyricsContainer == null) { 122 | throw new RuntimeException("Could not find lyrics container, please report this to the developer"); 123 | } 124 | 125 | return lyricsContainer.wholeText() 126 | .replace("

", "\n") 127 | .replace("
", "\n") 128 | .replace("\n\n\n", "\n") 129 | .trim(); 130 | } 131 | } 132 | 133 | @Override 134 | public void close() { 135 | executor.shutdown(); 136 | } 137 | 138 | private record GeniusData( 139 | String url, 140 | String title, 141 | String author, 142 | String artwork 143 | ) { 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /application/src/main/java/me/duncte123/lyrics/HttpClientProvider.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics; 2 | 3 | import com.sedmelluq.discord.lavaplayer.tools.ExceptionTools; 4 | import com.sedmelluq.discord.lavaplayer.tools.io.HttpClientTools; 5 | import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface; 6 | import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterfaceManager; 7 | import com.sedmelluq.lava.extensions.youtuberotator.YoutubeIpRotatorSetup; 8 | import com.sedmelluq.lava.extensions.youtuberotator.planner.*; 9 | import lavalink.server.config.RateLimitConfig; 10 | import lavalink.server.config.ServerConfig; 11 | 12 | import java.util.Optional; 13 | 14 | public class HttpClientProvider implements AutoCloseable { 15 | private final HttpInterfaceManager httpInterfaceManager; 16 | 17 | public HttpClientProvider(AbstractRoutePlanner routePlanner, ServerConfig serverConfig) { 18 | this.httpInterfaceManager = HttpClientTools.createDefaultThreadLocalManager(); 19 | 20 | if (routePlanner != null) { 21 | final int retryLimit = Optional.ofNullable(serverConfig.getRatelimit()) 22 | .map(RateLimitConfig::getRetryLimit) 23 | .orElse(-1); 24 | 25 | final YoutubeIpRotatorSetup rotator; 26 | 27 | if (retryLimit < 0) { 28 | rotator = new YoutubeIpRotatorSetup(routePlanner); 29 | } else if (retryLimit == 0) { 30 | rotator = new YoutubeIpRotatorSetup(routePlanner).withRetryLimit(Integer.MAX_VALUE); 31 | } else { 32 | rotator = new YoutubeIpRotatorSetup(routePlanner).withRetryLimit(retryLimit); 33 | } 34 | 35 | rotator.forConfiguration(this.httpInterfaceManager, false) 36 | // Necessary to avoid NPEs. 37 | .withMainDelegateFilter(null) 38 | .setup(); 39 | } 40 | } 41 | 42 | public HttpInterface getHttpInterface() { 43 | return httpInterfaceManager.getInterface(); 44 | } 45 | 46 | @Override 47 | public void close() { 48 | ExceptionTools.closeWithWarnings(this.httpInterfaceManager); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /application/src/main/java/me/duncte123/lyrics/LyricsClient.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics; 2 | 3 | import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser; 4 | import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface; 5 | import com.sedmelluq.discord.lavaplayer.track.AudioTrack; 6 | import me.duncte123.lyrics.exception.LyricsNotFoundException; 7 | import me.duncte123.lyrics.model.*; 8 | import me.duncte123.lyrics.model.request.BrowseRequest; 9 | import me.duncte123.lyrics.model.request.NextRequest; 10 | import me.duncte123.lyrics.model.request.SearchRequest; 11 | import me.duncte123.lyrics.utils.JsonUtils; 12 | import org.apache.http.client.methods.HttpPost; 13 | import org.apache.http.entity.StringEntity; 14 | 15 | import java.io.IOException; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | import java.util.concurrent.*; 19 | 20 | import static me.duncte123.lyrics.utils.JsonUtils.getRunningText; 21 | import static me.duncte123.lyrics.utils.YouTubeUtils.*; 22 | 23 | public class LyricsClient implements AutoCloseable { 24 | private static final String API_URL = "https://music.youtube.com/youtubei/v1"; 25 | private static final String BROWSE_URL = API_URL + "/browse"; 26 | private static final String NEXT_URL = API_URL + "/next"; 27 | private static final String SEARCH_URL = API_URL + "/search"; 28 | 29 | private static final ExecutorService executor = Executors.newSingleThreadExecutor(); 30 | private final HttpClientProvider httpInterfaceManager; 31 | 32 | public LyricsClient(HttpClientProvider httpProvider) { 33 | this.httpInterfaceManager = httpProvider; 34 | } 35 | 36 | public HttpInterface getHttpInterface() { 37 | return this.httpInterfaceManager.getHttpInterface(); 38 | } 39 | 40 | @Override 41 | public void close() throws Exception { 42 | executor.shutdown(); 43 | } 44 | 45 | public Future findLyrics(AudioTrack track) { 46 | try { 47 | final String videoId; 48 | 49 | if ("youtube".equalsIgnoreCase(track.getSourceManager().getSourceName())) { 50 | videoId = track.getInfo().identifier; 51 | } else if (track.getInfo().isrc != null) { 52 | // So, turns out that yt needs the ISRC in quotes. Whoops 53 | final var searched = search( 54 | '"' + track.getInfo().isrc + '"' 55 | ).get(); 56 | 57 | if (searched.isEmpty()) { 58 | throw new LyricsNotFoundException(); 59 | } 60 | 61 | videoId = searched.get(0).videoId(); 62 | } else { 63 | final var searched = search( 64 | "%s - %s".formatted(track.getInfo().title, track.getInfo().author) 65 | ).get(); 66 | 67 | if (searched.isEmpty()) { 68 | throw new LyricsNotFoundException(); 69 | } 70 | 71 | videoId = searched.get(0).videoId(); 72 | } 73 | 74 | return requestLyrics(videoId); 75 | } catch (InterruptedException | ExecutionException e) { 76 | return CompletableFuture.failedFuture(e); 77 | } 78 | } 79 | 80 | public Future requestLyrics(String videoId) { 81 | return executor.submit(() -> { 82 | final var nextPage = requestNextPage(videoId); 83 | final var browseId = getBrowseEndpoint(nextPage); 84 | 85 | if (browseId == null) throw new LyricsNotFoundException(); 86 | 87 | final var browseResult = request(BROWSE_URL, new BrowseRequest(Context.DEFAULT_MOBILE_REQUEST, browseId)); 88 | 89 | final var lyricsData = getLyricsData(browseResult); 90 | final var albumArt = getThumbnails(nextPage); 91 | 92 | if (lyricsData.isNull()) { 93 | final var renderer = getMusicDescriptionShelfRenderer(browseResult); 94 | 95 | if (renderer.isNull()) throw new LyricsNotFoundException(); 96 | 97 | final var text = getRunningText(renderer, "description"); 98 | final var source = getRunningText(renderer, "footer"); 99 | 100 | return new TextLyrics(getTrack(nextPage, albumArt), source, text); 101 | } 102 | 103 | final var source = getSource(lyricsData); 104 | final var lines = getLines(lyricsData); 105 | 106 | return new TimedLyrics(getTrack(nextPage, albumArt), source, lines); 107 | }); 108 | } 109 | 110 | public Future> search(String query) { 111 | return search(query, null); 112 | } 113 | 114 | public Future> search(String query, String region) { 115 | return executor.submit(() -> { 116 | final var resList = new ArrayList(); 117 | 118 | final var result = request(SEARCH_URL, new SearchRequest( 119 | Context.DEFAULT_MOBILE_REQUEST_WITH_REGION.apply(region), 120 | query, 121 | ONLY_TRACKS_SEARCH_PARAMS 122 | )); 123 | 124 | // /contents/tabbedSearchResultsRenderer/tabs/0/tabRenderer/content/sectionListRenderer/contents/1/musicCardShelfRenderer/title/runs/0/navigationEndpoint/watchEndpoint/videoId 125 | final var contents = result 126 | .get("contents") 127 | .get("tabbedSearchResultsRenderer") 128 | .get("tabs") 129 | .index(0) 130 | .get("tabRenderer") 131 | .get("content") 132 | .get("sectionListRenderer") 133 | .get("contents"); 134 | 135 | // Top result, seems to be empty with the new param 136 | /*contents.values() 137 | .stream() 138 | .filter((it) -> !it.get("musicCardShelfRenderer").isNull()) 139 | .findFirst() 140 | .ifPresent((it) -> { 141 | final var renderer = it.get("musicCardShelfRenderer"); 142 | 143 | final var title = getRunningText(renderer, "title"); 144 | final var videoId = renderer.get("buttons") 145 | .index(0) 146 | .get("buttonRenderer") 147 | .get("command") 148 | .get("watchEndpoint") 149 | .get("videoId") 150 | .text(); 151 | 152 | if (title != null && videoId != null) { 153 | resList.add(new SearchTrack(videoId, title)); 154 | } 155 | });*/ 156 | 157 | contents.values() 158 | .stream() 159 | .filter( 160 | (it) -> it.get("musicShelfRenderer") 161 | .get("contents") 162 | .values() 163 | .stream() 164 | .anyMatch( 165 | (content) -> content.get("musicTwoColumnItemRenderer") 166 | .get("navigationEndpoint") 167 | .get("watchEndpoint") 168 | .get("videoId") 169 | .text() != null 170 | ) 171 | ) 172 | .findFirst() 173 | .ifPresent((it) -> 174 | it.get("musicShelfRenderer") 175 | .get("contents") 176 | .values() 177 | .forEach((item) -> { 178 | final var renderer = item.get("musicTwoColumnItemRenderer"); 179 | 180 | final var title = getRunningText(renderer, "title"); 181 | final var videoId = renderer.get("navigationEndpoint") 182 | .get("watchEndpoint") 183 | .get("videoId") 184 | .text(); 185 | 186 | if (title != null && videoId != null) { 187 | resList.add(new SearchTrack(videoId, title)); 188 | } 189 | }) 190 | ); 191 | 192 | return resList; 193 | }); 194 | } 195 | 196 | private JsonBrowser request(String url, Object body) throws IOException { 197 | final var request = new HttpPost(url); 198 | 199 | request.setHeader("Content-Type", "application/json"); 200 | 201 | final var encodedBody = JsonUtils.toJsonString(body); 202 | 203 | request.setEntity(new StringEntity(encodedBody, "UTF-8")); 204 | 205 | try (final var response = getHttpInterface().execute(request)) { 206 | return JsonBrowser.parse(response.getEntity().getContent()); 207 | } 208 | } 209 | 210 | private JsonBrowser requestNextPage(String videoId) throws IOException { 211 | return request(NEXT_URL, new NextRequest(Context.DEFAULT_MOBILE_REQUEST, videoId)); 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /application/src/main/java/me/duncte123/lyrics/lavalink/Config.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.lavalink; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties(prefix = "plugins.lyrics") 8 | public class Config { 9 | private String countryCode = null; 10 | private String geniusApiKey = null; 11 | 12 | public String getCountryCode() { 13 | return countryCode; 14 | } 15 | 16 | public void setCountryCode(String countryCode) { 17 | this.countryCode = countryCode; 18 | } 19 | 20 | public String getGeniusApiKey() { 21 | return geniusApiKey; 22 | } 23 | 24 | public void setGeniusApiKey(String geniusApiKey) { 25 | this.geniusApiKey = geniusApiKey; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /application/src/main/java/me/duncte123/lyrics/utils/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.utils; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser; 6 | 7 | import java.util.stream.Collectors; 8 | 9 | public class JsonUtils { 10 | private static final ObjectMapper MAPPER = new ObjectMapper(); 11 | 12 | public static String toJsonString(Object object) { 13 | try { 14 | return MAPPER.writeValueAsString(object); 15 | } catch (JsonProcessingException e) { 16 | throw new RuntimeException(e); 17 | } 18 | } 19 | 20 | public static String getRunningText(JsonBrowser browser, String key) { 21 | final var runs = browser.get(key).get("runs"); 22 | 23 | if (runs.isNull() || !runs.isList()) { 24 | return null; 25 | } 26 | 27 | return runs.values() 28 | .stream() 29 | .map((it) -> it.get("text").text()) 30 | .collect(Collectors.joining(" ")); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /application/src/main/java/me/duncte123/lyrics/utils/YouTubeUtils.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.utils; 2 | 3 | import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser; 4 | import jakarta.annotation.Nullable; 5 | import me.duncte123.lyrics.exception.LyricsNotFoundException; 6 | import me.duncte123.lyrics.model.AlbumArt; 7 | import me.duncte123.lyrics.model.Line; 8 | import me.duncte123.lyrics.model.LongRange; 9 | import me.duncte123.lyrics.model.Track; 10 | 11 | import java.util.List; 12 | 13 | import static me.duncte123.lyrics.utils.JsonUtils.getRunningText; 14 | 15 | public final class YouTubeUtils { 16 | public static final String ONLY_TRACKS_SEARCH_PARAMS = "EgWKAQIIAWoQEAMQBBAJEAoQBRAREBAQFQ%3D%3D"; 17 | 18 | @Nullable 19 | public static String getBrowseEndpoint(JsonBrowser browser) { 20 | return browser.get("contents") 21 | .get("singleColumnMusicWatchNextResultsRenderer") 22 | .get("tabbedRenderer") 23 | .get("watchNextTabbedResultsRenderer") 24 | .get("tabs") 25 | .index(1) 26 | .get("tabRenderer") 27 | .get("endpoint") 28 | .get("browseEndpoint") 29 | .get("browseId") 30 | .text(); 31 | } 32 | 33 | public static JsonBrowser getLyricsData(JsonBrowser browser) { 34 | return browser.get("contents") 35 | .get("elementRenderer") 36 | .get("newElement") 37 | .get("type") 38 | .get("componentType") 39 | .get("model") 40 | .get("timedLyricsModel") 41 | .get("lyricsData"); 42 | } 43 | 44 | public static String getSource(JsonBrowser browser) { 45 | final var sourceMessage = browser.get("sourceMessage").text(); 46 | 47 | if (sourceMessage == null) { 48 | throw new LyricsNotFoundException(); 49 | } 50 | 51 | final var semiIndex = sourceMessage.indexOf(": "); 52 | 53 | return sourceMessage.substring(semiIndex + 2); 54 | } 55 | 56 | public static Track getTrack(JsonBrowser browser, List albumArt) { 57 | final var lockScreen = browser.get("lockScreen").get("lockScreenRenderer"); 58 | 59 | if (lockScreen.isNull()) { 60 | throw new LyricsNotFoundException(); 61 | } 62 | 63 | final var title = getRunningText(lockScreen, "title"); 64 | final var author = getRunningText(lockScreen, "shortBylineText"); 65 | final var album = getRunningText(lockScreen, "albumText"); 66 | 67 | if (title == null || author == null || album == null) { 68 | throw new LyricsNotFoundException(); 69 | } 70 | 71 | return new Track(title, author, album, albumArt); 72 | } 73 | 74 | public static JsonBrowser getMusicDescriptionShelfRenderer(JsonBrowser browser) { 75 | return browser.get("contents") 76 | .get("sectionListRenderer") 77 | .get("contents") 78 | .index(0) 79 | .get("musicDescriptionShelfRenderer"); 80 | } 81 | 82 | public static List getThumbnails(JsonBrowser browser) { 83 | final var thumbnails = browser.get("contents") 84 | .get("singleColumnMusicWatchNextResultsRenderer") 85 | .get("tabbedRenderer") 86 | .get("watchNextTabbedResultsRenderer") 87 | .get("tabs") 88 | .index(0) 89 | .get("tabRenderer") 90 | .get("content") 91 | .get("musicQueueRenderer") 92 | .get("content") 93 | .get("playlistPanelRenderer") 94 | .get("contents") 95 | .index(0) 96 | .get("playlistPanelVideoRenderer") 97 | .get("thumbnail") 98 | .get("thumbnails"); 99 | 100 | if (thumbnails.isList()) { 101 | return thumbnails.values() 102 | .stream() 103 | .map((it) -> it.as(AlbumArt.class)) 104 | .toList(); 105 | } else { 106 | return List.of(); 107 | } 108 | } 109 | 110 | public static List getLines(JsonBrowser browser) { 111 | final var linesData = browser.get("timedLyricsData"); 112 | 113 | if (linesData.isNull() || !linesData.isList()) { 114 | throw new LyricsNotFoundException(); 115 | } 116 | 117 | return linesData.values() 118 | .stream() 119 | .map((it) -> { 120 | final var line = it.get("lyricLine").text(); 121 | 122 | final var cueRange = it.get("cueRange"); 123 | final var start = cueRange.get("startTimeMilliseconds"); 124 | final var end = cueRange.get("endTimeMilliseconds"); 125 | 126 | if (start.isNull() || end.isNull()) { 127 | throw new RuntimeException("Could not calculate range"); 128 | } 129 | 130 | final var range = new LongRange(start.asLong(-1), end.asLong(-1)); 131 | 132 | return new Line(line, range); 133 | }) 134 | .toList(); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.ajoberstar.grgit.Grgit 2 | 3 | plugins { 4 | java 5 | `maven-publish` 6 | alias(libs.plugins.lavalink) 7 | alias(libs.plugins.grgit) 8 | } 9 | 10 | val (gitVersion, release) = versionFromGit() 11 | logger.lifecycle("Version: $gitVersion (release: $release)") 12 | 13 | group = "me.duncte123" 14 | version = gitVersion 15 | 16 | lavalinkPlugin { 17 | name = "java-lyrics-plugin" 18 | path = "$group.lyrics.lavalink" 19 | configurePublishing = false 20 | apiVersion = libs.versions.lavalink.api 21 | serverVersion = libs.versions.lavalink.server 22 | } 23 | 24 | val isLavalinkMavenDefined = System.getenv("LAVALINK_MAVEN_USERNAME") != null && System.getenv("LAVALINK_MAVEN_PASSWORD") != null 25 | 26 | val lavalinkMavenUrl: String 27 | get() { 28 | if (release) { 29 | return "https://maven.lavalink.dev/releases" 30 | } 31 | 32 | return "https://maven.lavalink.dev/snapshots" 33 | } 34 | 35 | subprojects { 36 | apply(plugin = "java") 37 | apply(plugin = "maven-publish") 38 | apply(plugin = "org.ajoberstar.grgit") 39 | 40 | tasks.compileJava { 41 | options.encoding = "UTF-8" 42 | } 43 | 44 | publishing { 45 | repositories { 46 | if (isLavalinkMavenDefined && name == "lavalyrics") { 47 | maven { 48 | name = "lavalink" 49 | url = uri(lavalinkMavenUrl) 50 | credentials { 51 | username = System.getenv("LAVALINK_MAVEN_USERNAME") 52 | password = System.getenv("LAVALINK_MAVEN_PASSWORD") 53 | } 54 | } 55 | } 56 | } 57 | } 58 | } 59 | 60 | allprojects { 61 | repositories { 62 | mavenCentral() 63 | 64 | maven("https://maven.lavalink.dev/releases") 65 | maven("https://maven.lavalink.dev/snapshots") 66 | maven("https://maven.topi.wtf/releases") 67 | maven("https://maven.topi.wtf/snapshots") 68 | } 69 | } 70 | 71 | java { 72 | toolchain { 73 | languageVersion = JavaLanguageVersion.of(17) 74 | } 75 | } 76 | 77 | tasks { 78 | compileJava { 79 | options.encoding = "UTF-8" 80 | } 81 | } 82 | 83 | dependencies { 84 | compileOnly(libs.jackson.databind) 85 | compileOnly(libs.jackson.annotations) 86 | compileOnly(libs.lavalink.server) 87 | compileOnly(libs.lavaplayer) 88 | compileOnly(libs.lavaplayer.rotator) 89 | 90 | implementation(projects.protocol) 91 | implementation(projects.application) 92 | } 93 | 94 | tasks.jar { 95 | archiveBaseName.set("lyrics") 96 | duplicatesStrategy = DuplicatesStrategy.EXCLUDE 97 | } 98 | 99 | tasks.wrapper { 100 | gradleVersion = "8.5" 101 | distributionType = Wrapper.DistributionType.BIN 102 | } 103 | 104 | publishing { 105 | repositories { 106 | if (isLavalinkMavenDefined) { 107 | maven { 108 | name = "lavalink" 109 | url = uri(lavalinkMavenUrl) 110 | credentials { 111 | username = System.getenv("LAVALINK_MAVEN_USERNAME") 112 | password = System.getenv("LAVALINK_MAVEN_PASSWORD") 113 | } 114 | } 115 | } 116 | } 117 | 118 | publications { 119 | create("maven") { 120 | groupId = "me.duncte123" 121 | artifactId = "java-lyrics-plugin" 122 | from(components["java"]) 123 | } 124 | } 125 | } 126 | 127 | fun versionFromGit(): Pair { 128 | Grgit.open(mapOf("currentDir" to project.rootDir)).use { git -> 129 | val headTag = git.tag 130 | .list() 131 | .find { it.commit.id == git.head().id } 132 | 133 | val clean = git.status().isClean || System.getenv("CI") != null 134 | if (!clean) { 135 | logger.lifecycle("Git state is dirty, version is a snapshot.") 136 | } 137 | 138 | return if (headTag != null && clean) headTag.name to true else "${git.head().id}-SNAPSHOT" to false 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | lavalink-api = "4.0.0" 3 | lavalink-server = "4.0.0" 4 | lavalyrics = "1.0.0" 5 | lavaplayer = "2.1.0" 6 | 7 | [libraries] 8 | # No versions? That is correct, lavalink server has the version for lavaplayer. 9 | # And lavaplayer has the version for jackson and httpclient. 10 | http = { group = "org.apache.httpcomponents", name = "httpclient" } 11 | jackson-databind = { group = "com.fasterxml.jackson.core", name = "jackson-databind" } 12 | jackson-annotations = { group = "com.fasterxml.jackson.core", name = "jackson-annotations" } 13 | lavaplayer = { group = "dev.arbjerg", name = "lavaplayer" } 14 | lavaplayer-rotator = { group = "dev.arbjerg", name = "lavaplayer-ext-youtube-rotator", version.ref = "lavaplayer" } 15 | commons-io = { group = "commons-io", name = "commons-io", version = "2.13.0" } 16 | jsoup = { group = "org.jsoup", name = "jsoup", version = "1.16.1" } 17 | lavalink-server = { group = "dev.arbjerg.lavalink", name = "Lavalink-Server", version.ref = "lavalink-server" } 18 | lavalink-api = { group = "dev.arbjerg.lavalink", name = "plugin-api", version.ref = "lavalink-api" } 19 | lavalyrics = { group = "com.github.topi314.lavalyrics", name = "lavalyrics", version.ref = "lavalyrics" } 20 | lavalyrics-api = { group = "com.github.topi314.lavalyrics", name = "lavalyrics-plugin-api", version.ref = "lavalyrics" } 21 | 22 | [plugins] 23 | lavalink = { id = "dev.arbjerg.lavalink.gradle-plugin", version = "1.0.15" } 24 | grgit = { id = "org.ajoberstar.grgit", version = "5.2.0" } 25 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DuncteBot/java-timed-lyrics/157e4e9e7399b7a72d3c0741e9c09475ca422e61/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Dec 23 16:18:09 CET 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk17 3 | install: 4 | - ./gradlew clean publishToMavenLocal 5 | -------------------------------------------------------------------------------- /lavalyrics/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | `maven-publish` 4 | alias(libs.plugins.lavalink) 5 | } 6 | 7 | group = "me.duncte123" 8 | version = rootProject.version 9 | 10 | lavalinkPlugin { 11 | name = "java-lavalyrics" 12 | path = "$group.lyrics.lavalink" 13 | configurePublishing = false 14 | apiVersion = libs.versions.lavalink.api 15 | serverVersion = libs.versions.lavalink.server 16 | } 17 | 18 | java { 19 | toolchain { 20 | languageVersion = JavaLanguageVersion.of(17) 21 | } 22 | } 23 | 24 | tasks { 25 | compileJava { 26 | options.encoding = "UTF-8" 27 | } 28 | } 29 | 30 | dependencies { 31 | // LL holds all our versions 32 | compileOnly(libs.lavalink.api) 33 | compileOnly(libs.lavalink.server) 34 | compileOnly(libs.lavaplayer) 35 | compileOnly(libs.lavaplayer.rotator) 36 | 37 | compileOnly(libs.lavalyrics) 38 | 39 | implementation(libs.lavalyrics.api) 40 | implementation(projects.protocol) 41 | implementation(projects.application) 42 | } 43 | 44 | publishing { 45 | publications { 46 | create("maven") { 47 | groupId = "me.duncte123.java-lyrics-plugin" 48 | artifactId = "lavalyrics" 49 | from(components["java"]) 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /lavalyrics/src/main/java/me/duncte123/lyrics/lavalink/JavaAudioLyricsManager.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.lavalink; 2 | 3 | import com.github.topi314.lavalyrics.AudioLyricsManager; 4 | import com.github.topi314.lavalyrics.lyrics.AudioLyrics; 5 | import com.github.topi314.lavalyrics.lyrics.BasicAudioLyrics; 6 | import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; 7 | import com.sedmelluq.discord.lavaplayer.tools.FriendlyException.Severity; 8 | import com.sedmelluq.discord.lavaplayer.track.AudioTrack; 9 | import com.sedmelluq.lava.extensions.youtuberotator.planner.AbstractRoutePlanner; 10 | import lavalink.server.config.ServerConfig; 11 | import me.duncte123.lyrics.GeniusClient; 12 | import me.duncte123.lyrics.HttpClientProvider; 13 | import me.duncte123.lyrics.LyricsClient; 14 | import me.duncte123.lyrics.exception.LyricsNotFoundException; 15 | import me.duncte123.lyrics.model.Lyrics; 16 | import me.duncte123.lyrics.model.TextLyrics; 17 | import me.duncte123.lyrics.model.TimedLyrics; 18 | import org.jetbrains.annotations.NotNull; 19 | import org.jetbrains.annotations.Nullable; 20 | 21 | import java.time.Duration; 22 | import java.time.temporal.ChronoUnit; 23 | import java.util.List; 24 | import java.util.Optional; 25 | import java.util.stream.Collectors; 26 | 27 | public class JavaAudioLyricsManager implements AudioLyricsManager { 28 | private final LyricsClient youtubeClient; 29 | private final GeniusClient geniusClient; 30 | private final HttpClientProvider httpProvider; 31 | 32 | public JavaAudioLyricsManager(Config config, AbstractRoutePlanner routePlanner, ServerConfig serverConfig) { 33 | this.httpProvider = new HttpClientProvider(routePlanner, serverConfig); 34 | final String geniusApiKey = config.getGeniusApiKey(); 35 | 36 | this.youtubeClient = new LyricsClient(this.httpProvider); 37 | 38 | if (geniusApiKey == null || geniusApiKey.isBlank()) { 39 | geniusClient = null; 40 | } else { 41 | geniusClient = new GeniusClient(geniusApiKey, this.httpProvider); 42 | } 43 | } 44 | 45 | @Override 46 | public @NotNull String getSourceName() { 47 | return "java-timed-lyrics-plugin"; 48 | } 49 | 50 | private Lyrics attemptYoutubeLoad(AudioTrack track) { 51 | try { 52 | return this.youtubeClient.findLyrics(track).get(); 53 | } catch (Exception e) { 54 | if (e.getCause() instanceof LyricsNotFoundException) { 55 | return null; 56 | } 57 | 58 | throw new FriendlyException("Failure when searching for youtube lyrics", Severity.COMMON, e); 59 | } 60 | } 61 | 62 | private Lyrics attemptGeniusLoad(AudioTrack track) { 63 | if (this.geniusClient == null) { 64 | return null; 65 | } 66 | 67 | try { 68 | return this.geniusClient.findLyrics(track).get(); 69 | } catch (Exception e) { 70 | if (e.getCause() instanceof LyricsNotFoundException) { 71 | return null; 72 | } 73 | 74 | throw new FriendlyException("Failure when searching for genius lyrics", Severity.COMMON, e); 75 | } 76 | } 77 | 78 | @Override 79 | public @Nullable AudioLyrics loadLyrics(@NotNull AudioTrack audioTrack) { 80 | Lyrics lyrics = attemptYoutubeLoad(audioTrack); 81 | 82 | if (lyrics == null) { 83 | lyrics = attemptGeniusLoad(audioTrack); 84 | } 85 | 86 | return Optional.ofNullable(lyrics) 87 | .map((it) -> { 88 | if (it instanceof TextLyrics tl) { 89 | return new BasicAudioLyrics( 90 | tl.source(), 91 | tl.source(), 92 | tl.text(), 93 | List.of() 94 | ); 95 | } else if (it instanceof TimedLyrics tl) { 96 | return new BasicAudioLyrics( 97 | tl.source(), 98 | tl.source(), 99 | null, 100 | tl.lines() 101 | .stream() 102 | .map((line) -> new BasicAudioLyrics.BasicLine( 103 | Duration.of(line.range().start(), ChronoUnit.MILLIS), 104 | Duration.of(line.range().end(), ChronoUnit.MILLIS), 105 | line.line() 106 | )) 107 | .collect(Collectors.toList()) 108 | ); 109 | } 110 | 111 | return null; 112 | }) 113 | .orElse(null); 114 | } 115 | 116 | @Override 117 | public void shutdown() { 118 | try { 119 | this.httpProvider.close(); 120 | this.youtubeClient.close(); 121 | 122 | if (this.geniusClient != null) { 123 | this.geniusClient.close(); 124 | } 125 | } catch (Exception e) { 126 | throw new RuntimeException(e); 127 | } 128 | 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /lavalyrics/src/main/java/me/duncte123/lyrics/lavalink/JavaLyricsManagerConfiguration.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.lavalink; 2 | 3 | import com.github.topi314.lavalyrics.LyricsManager; 4 | import com.github.topi314.lavalyrics.api.LyricsManagerConfiguration; 5 | import com.sedmelluq.lava.extensions.youtuberotator.planner.AbstractRoutePlanner; 6 | import lavalink.server.config.ServerConfig; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class JavaLyricsManagerConfiguration implements LyricsManagerConfiguration { 12 | private final JavaAudioLyricsManager javaAudioLyricsManager; 13 | 14 | public JavaLyricsManagerConfiguration(Config config, AbstractRoutePlanner routePlanner, ServerConfig serverConfig) { 15 | this.javaAudioLyricsManager = new JavaAudioLyricsManager(config, routePlanner, serverConfig); 16 | } 17 | 18 | @NotNull 19 | @Override 20 | public LyricsManager configure(@NotNull LyricsManager lyricsManager) { 21 | lyricsManager.registerLyricsManager(this.javaAudioLyricsManager); 22 | 23 | return lyricsManager; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /protocol/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | `maven-publish` 4 | } 5 | 6 | group = "me.duncte123" 7 | version = rootProject.version 8 | 9 | java { 10 | toolchain { 11 | languageVersion = JavaLanguageVersion.of(17) 12 | } 13 | } 14 | 15 | tasks { 16 | compileJava { 17 | options.encoding = "UTF-8" 18 | } 19 | } 20 | 21 | dependencies { 22 | // LL holds all our versions 23 | compileOnly(libs.lavalink.api) 24 | 25 | // add your dependencies here 26 | compileOnly(libs.jackson.annotations) 27 | } 28 | 29 | publishing { 30 | publications { 31 | create("maven") { 32 | groupId = "me.duncte123.java-lyrics-plugin" 33 | artifactId = "protocol" 34 | from(components["java"]) 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/exception/LyricsNotFoundException.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.exception; 2 | 3 | public class LyricsNotFoundException extends RuntimeException { 4 | public LyricsNotFoundException() { 5 | super("Lyrics were not found"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/AlbumArt.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | public record AlbumArt(String url, int height, int width) { 4 | } 5 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/Client.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | public record Client(String clientName, String clientVersion, String hl) { 4 | public Client(String clientName, String clientVersion) { 5 | this(clientName, clientVersion, null); 6 | } 7 | 8 | public Client(String hl) { 9 | this("ANDROID_MUSIC", "6.31.55", hl); 10 | } 11 | 12 | public Client() { 13 | this(null); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/Context.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | import java.util.function.Function; 4 | 5 | public record Context(Client client) { 6 | public static final Context DEFAULT_MOBILE_REQUEST = new Context(new Client()); 7 | public static final Function DEFAULT_MOBILE_REQUEST_WITH_REGION = (hl) -> new Context(new Client(hl)); 8 | } 9 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/Line.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | public record Line(String line, LongRange range) { 4 | } 5 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/LongRange.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | public record LongRange(long start, long end) { 4 | } 5 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/Lyrics.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonSubTypes; 4 | 5 | // @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type") 6 | @JsonSubTypes({ 7 | @JsonSubTypes.Type(name="text", value=TextLyrics.class), 8 | @JsonSubTypes.Type(name="timed", value=TimedLyrics.class) 9 | }) 10 | public interface Lyrics { 11 | String getType(); 12 | } 13 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/SearchTrack.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | public record SearchTrack(String videoId, String title) { 4 | } 5 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/TextLyrics.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | @JsonIgnoreProperties(ignoreUnknown = true) 6 | public record TextLyrics(Track track, String source, String text) implements Lyrics { 7 | @Override 8 | public String getType() { 9 | return "text"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/TimedLyrics.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import java.util.List; 6 | 7 | @JsonIgnoreProperties(ignoreUnknown = true) 8 | public record TimedLyrics(Track track, String source, List lines) implements Lyrics { 9 | @Override 10 | public String getType() { 11 | return "timed"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/Track.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model; 2 | 3 | import java.util.List; 4 | 5 | public record Track(String title, String author, String album, List albumArt) { 6 | } 7 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/request/BrowseRequest.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model.request; 2 | 3 | import me.duncte123.lyrics.model.Context; 4 | 5 | public record BrowseRequest(Context context, String browseId) { 6 | } 7 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/request/NextRequest.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model.request; 2 | 3 | import me.duncte123.lyrics.model.Context; 4 | 5 | public record NextRequest(Context context, String videoId) { 6 | } 7 | -------------------------------------------------------------------------------- /protocol/src/main/java/me/duncte123/lyrics/model/request/SearchRequest.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.model.request; 2 | 3 | import me.duncte123.lyrics.model.Context; 4 | 5 | public record SearchRequest(Context context, String query, String params) { 6 | } 7 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") 2 | 3 | include( 4 | ":application", 5 | ":lavalyrics", 6 | ":protocol" 7 | ) 8 | 9 | rootProject.name = "java-lyrics-plugin" 10 | 11 | -------------------------------------------------------------------------------- /src/main/java/me/duncte123/lyrics/lavalink/RestHandler.java: -------------------------------------------------------------------------------- 1 | package me.duncte123.lyrics.lavalink; 2 | 3 | import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; 4 | import com.sedmelluq.lava.extensions.youtuberotator.planner.AbstractRoutePlanner; 5 | import lavalink.server.config.ServerConfig; 6 | import lavalink.server.io.SocketServer; 7 | import me.duncte123.lyrics.GeniusClient; 8 | import me.duncte123.lyrics.HttpClientProvider; 9 | import me.duncte123.lyrics.LyricsClient; 10 | import me.duncte123.lyrics.exception.LyricsNotFoundException; 11 | import me.duncte123.lyrics.model.Lyrics; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.RequestParam; 16 | import org.springframework.web.bind.annotation.RestController; 17 | import org.springframework.web.server.ResponseStatusException; 18 | 19 | import java.util.Locale; 20 | 21 | import static lavalink.server.util.UtilKt.socketContext; 22 | 23 | @RestController 24 | public class RestHandler { 25 | private final LyricsClient ytClient; 26 | private final GeniusClient geniusClient; 27 | 28 | private final SocketServer socketServer; 29 | private final Config config; 30 | 31 | public RestHandler(SocketServer socketServer, Config config, AbstractRoutePlanner routePlanner, ServerConfig serverConfig) { 32 | this.socketServer = socketServer; 33 | this.config = config; 34 | 35 | final HttpClientProvider httpProvider = new HttpClientProvider(routePlanner, serverConfig); 36 | 37 | this.ytClient = new LyricsClient(httpProvider); 38 | 39 | final String geniusApiKey = config.getGeniusApiKey(); 40 | 41 | if (geniusApiKey == null || geniusApiKey.isBlank()) { 42 | geniusClient = null; 43 | } else { 44 | geniusClient = new GeniusClient(geniusApiKey, httpProvider); 45 | } 46 | } 47 | 48 | @GetMapping(value = "/v4/lyrics/{videoId}") 49 | public Lyrics getLyrics(@PathVariable("videoId") String videoId) { 50 | try { 51 | return ytClient.requestLyrics(videoId).get(); 52 | } catch (Exception e) { 53 | if (e.getCause() instanceof LyricsNotFoundException lnfe) { 54 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, lnfe.getMessage()); 55 | } 56 | 57 | throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e); 58 | } 59 | } 60 | 61 | @GetMapping(value = "/v4/lyrics/search") 62 | public Object search( 63 | @RequestParam("query") String query, 64 | @RequestParam(name = "source", required = false, defaultValue = "youtube") String source 65 | ) { 66 | try { 67 | return switch (source.toLowerCase(Locale.ROOT)) { 68 | case "youtube" -> ytClient.search(query, config.getCountryCode()).get(); 69 | case "genius" -> geniusClient.search(query).get(); 70 | default -> throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown source type: " + source); 71 | }; 72 | } catch (Exception e) { 73 | if (e.getCause() instanceof LyricsNotFoundException lnfe) { 74 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, lnfe.getMessage()); 75 | } 76 | 77 | if (e instanceof ResponseStatusException rse) { 78 | throw rse; 79 | } 80 | 81 | throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e); 82 | } 83 | } 84 | 85 | @GetMapping(value = "/v4/sessions/{sessionId}/players/{guildId}/lyrics") 86 | public Lyrics getLyricsOfPlayingTrack(@PathVariable("sessionId") String sessionId, @PathVariable("guildId") long guildId) throws Exception { 87 | final var playingTrack = socketContext(socketServer, sessionId) 88 | .getPlayer(guildId) 89 | .getTrack(); 90 | 91 | if (playingTrack == null) { 92 | throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Not currently playing anything"); 93 | } 94 | 95 | try { 96 | return ytClient.findLyrics(playingTrack).get(); 97 | } catch (Exception e) { 98 | if (e.getCause() instanceof LyricsNotFoundException lnfe) { 99 | if (geniusClient != null) { 100 | return geniusClient.findLyrics(playingTrack).get(); 101 | } 102 | 103 | throw new ResponseStatusException(HttpStatus.NOT_FOUND, lnfe.getMessage()); 104 | } 105 | 106 | throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e); 107 | } 108 | } 109 | 110 | 111 | } 112 | --------------------------------------------------------------------------------