Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Genius gives untimed lyrics for a track no other source has
My-Name-Is-Jeff8572dea05843
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 04d8b3e5..183d76ea 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -124,7 +124,10 @@ Shared:kept per track, a rate limit is waited out and a refused key is left for 10 min, its reason on thesource's row; checked on the Mac against harness/spicy-lyrics/. QQMusic.m (line timed LRC) and KuGou.m (word timed KRC, unpacked withzlib and read by NetEase.m's parser) for Chinese and other Asian songs, matched by title, singer- and length; checked on the Mac against harness/lyrics-sources/. color-lyrics is answered with whichever won+ and length; checked on the Mac against harness/lyrics-sources/. Genius.m, last: untimed words for a track no+ other source has, the song found by the line meanings' search (SGGeniusSongIn in LyricsMeanings/Meanings.m)+ and the words read from its embed script, which is scraping (no API gives the text); checked on+ the Mac against harness/genius-lyrics/. color-lyrics is answered with whichever won(LyricsHook.x): Spotify's own 200 gets our lines swapped in; a track Spotify's metadata says has none hasits request sent to a donor track that does, so the reply is a real 200 (a 404 answered as a 200 in thedelegate alone never showed the card on 9.1.78); a 404 for a track not seen yet is held until the chaindiff --git a/harness/genius-lyrics/README.md b/harness/genius-lyrics/README.mdnew file mode 100644index 00000000..10003906--- /dev/null+++ b/harness/genius-lyrics/README.md@@ -0,0 +1,20 @@+# Genius lyrics check++`./build.sh` checks, on the Mac as a Mac Catalyst binary, with no simulator and no network:++- the song Genius's search reply gives a track (`SGGeniusSongIn` in `Shared/LyricsMeanings/Meanings.m`),+ on replies carrying the titles and artists genius.com really answered for these tracks: a song of the+ same name by someone else is passed over (Yesterday by a HearonTrackz featuring Queen Key is not+ Queen's), a cover gets the singer's own page and nothing when Genius has none, a remix gets the remix+ it names and a plain track the song over its remixes, an instrumental or karaoke track gets nothing,+ tracks named by their lead artist alone, as the player names them, and two leads, a comma inside a+ name and a name Genius writes twice over ("BTS (방탄소년단)", "Дора (Dora)") still match;+- the lines read out of a made-up embed script (`SGGeniusEmbedRows` in `Shared/LyricsSources/Genius.m`):+ the two layers of escaping undone, tags and [Chorus] headings gone, entities decoded, one empty row+ per gap, and nothing at all for a page that is not the embed or an embed with no words.++`./build.sh live` (it needs the network, so not inside a sandbox that blocks it) also searches+genius.com for the same tracks, reads each match's real embed, and runs the whole ask once. Only line+counts are printed, since the words are real lyrics.++It does not cover the walk down the sources, the order on the Lyrics page, or the lines on the lyrics view.diff --git a/harness/genius-lyrics/build.sh b/harness/genius-lyrics/build.shnew file mode 100755index 00000000..217c33f5--- /dev/null+++ b/harness/genius-lyrics/build.sh@@ -0,0 +1,11 @@+#!/bin/sh+# build.sh: builds check.m against this checkout's Genius.m and the Genius search in Meanings.m as a+# Mac Catalyst binary and runs it, so no simulator is needed. `./build.sh live` also asks genius.com.+set -e+HERE=$(cd "$(dirname "$0")" && pwd)+SRC=$(cd "$HERE/../../tweak/Sources" && pwd)+mkdir -p "$HERE/build"+xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$(xcrun --sdk macosx --show-sdk-path)" -iframework "$(xcrun --sdk macosx --show-sdk-path)/System/iOSSupport/System/Library/Frameworks" -fobjc-arc -g -Wall -I"$SRC" \+ "$HERE/check.m" "$SRC/Shared/LyricsSources/Genius.m" "$SRC/Shared/LyricsMeanings/Meanings.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \+ -framework UIKit -framework Foundation -o "$HERE/build/check"+"$HERE/build/check" "$@"diff --git a/harness/genius-lyrics/check.m b/harness/genius-lyrics/check.mnew file mode 100644index 00000000..7e94d1e2--- /dev/null+++ b/harness/genius-lyrics/check.m@@ -0,0 +1,212 @@+// Checks the Genius lyrics source without the phone: the search's pick of a song for a track+// (SGGeniusSongIn, Meanings.m) on replies shaped like Genius's, with the titles and artists its search+// really gave for these tracks, and the lines read out of a made-up embed script (Genius.m). With+// `live`, the same tracks are searched on genius.com, the embed of each match is read, and the whole ask+// runs once; only line counts are printed, since the words are real lyrics. Exits non-zero on the first+// wrong answer.+#import <UIKit/UIKit.h>+#import "Shared/LyricsSources/LyricsSources.h"+#import "Shared/LyricsMeanings/Meanings.h"+#import "Settings/SGModPage.h"++#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)++// What the two files reach outside themselves for. The requests go to genius.com in live mode and+// answer nothing otherwise.+@implementation SGLyricsResult+@end+@implementation SGLyricsQuery+@end+NSInteger SGInt(NSString *key, NSInteger fallback) { return fallback; }+SGModRow *SGChoiceRow(NSString *title, NSString *subtitle, NSString *key, NSArray<NSString *> *choices, NSInteger fallback) { return nil; }+SPTPlayerTrack *SGKaraokeTrackFor(NSString *trackID) { return nil; }+NSURL *SGLyricsURL(NSString *base, NSDictionary<NSString *, NSString *> *query) {+ NSURLComponents *url = [NSURLComponents componentsWithString:base];+ NSMutableArray<NSURLQueryItem *> *items = [NSMutableArray array];+ [query enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {+ [items addObject:[NSURLQueryItem queryItemWithName:name value:value]];+ }];+ url.queryItems = items;+ return url.URL;+}+static BOOL sg_live;+static NSData *fetched(NSURL *url) {+ if (!sg_live) return nil;+ __block NSData *body = nil;+ dispatch_semaphore_t got = dispatch_semaphore_create(0);+ [[NSURLSession.sharedSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if ([(NSHTTPURLResponse *)response statusCode] == 200) body = data;+ else fprintf(stderr, "%s answered %ld %s\n", url.absoluteString.UTF8String, (long)[(NSHTTPURLResponse *)response statusCode], error.description.UTF8String ?: "");+ dispatch_semaphore_signal(got);+ }] resume];+ dispatch_semaphore_wait(got, DISPATCH_TIME_FOREVER);+ return body;+}+void SGLyricsGetJSON(NSURL *url, NSDictionary *headers, void (^done)(id root)) {+ NSData *body = fetched(url);+ done(body ? [NSJSONSerialization JSONObjectWithData:body options:0 error:nil] : nil);+}+void SGLyricsGetText(NSURL *url, void (^done)(NSString *text)) {+ NSData *body = fetched(url);+ done(body ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil);+}++// A search reply holding these hits, in this order: {id, title, primary artists, instrumental, artist_names}.+static NSDictionary *reply(NSArray<NSArray *> *hits) {+ NSMutableArray *results = [NSMutableArray array];+ for (NSArray *hit in hits) {+ NSMutableArray *primaries = [NSMutableArray array];+ for (NSString *name in hit[2]) [primaries addObject:@{@"name": name}];+ [results addObject:@{@"result": @{@"id": hit[0], @"title": hit[1], @"primary_artists": primaries,+ @"instrumental": @(hit.count > 3 && [hit[3] boolValue]),+ @"artist_names": hit.count > 4 ? hit[4] : [hit[2] componentsJoinedByString:@" & "]}}];+ }+ return @{@"sections": @[@{@"type": @"song", @"hits": results}]};+}++// Each track with the song it should get, 0 for none. The player names a track by its lead artist alone+// ("Lil Nas X"); a local file can carry the whole list. The hits are what genius.com's search answered+// for the track in October 2026, cut to the ones that matter, a few moved up to make the point.+static void checkPicks(void) {+ NSArray *cohen = @[@1063905, @"Hallelujah", @[@"Leonard Cohen"]];+ NSArray *buckley = @[@84894, @"Hallelujah", @[@"Jeff Buckley"]];+ NSArray *buckleyLive = @[@8723374, @"Hallelujah (Live at Bearsville Studios, New York - 1993)", @[@"Jeff Buckley"]];+ NSArray *buckleySpanish = @[@10518208, @"Jeff Buckley - Hallelujah (Traducción al Español)", @[@"Genius Traducciones al Español"]];+ NSArray *pentatonix = @[@2888288, @"Hallelujah", @[@"Pentatonix"]];+ NSArray *pentatonixFeat = @[@7457112, @"Hallelujah (Feat. The String Mob)", @[@"Pentatonix"]];+ NSDictionary *hallelujah = reply(@[cohen, buckleySpanish, buckleyLive, buckley, pentatonixFeat, pentatonix]);+ NSDictionary *oldTownRoad = reply(@[+ @[@7746352, @"Old Town Road (8-Bit Lil Nas X & Billy Ray Cyrus Emulation)", @[@"8-Bit Arcade"], @YES],+ @[@4486068, @"Lil Nas X & Billy Ray Cyrus - Old Town Road (Young Thug & Mason Ramsey Remix) (Traducción al Español)", @[@"Genius Traducciones al Español"]],+ @[@4514622, @"Old Town Road (Diplo Remix)", @[@"Lil Nas X", @"Billy Ray Cyrus", @"Diplo"]],+ @[@4445394, @"Old Town Road (Remix)", @[@"Lil Nas X"]],+ @[@4133841, @"Old Town Road", @[@"Lil Nas X"]],+ ]);+ NSDictionary *blindingLights = reply(@[+ @[@6181749, @"Blinding Lights (Remix)", @[@"The Weeknd", @"ROSALÍA"]],+ @[@5953339, @"Blinding Lights (Instrumental)", @[@"The Weeknd"], @YES],+ @[@8879997, @"Blinding Lights (Live)", @[@"The Weeknd"]],+ @[@5049949, @"Blinding Lights", @[@"The Weeknd"]],+ ]);+ NSArray *cases = @[+ // A song of the same name by someone featuring a "Queen Key" is not Queen's.+ @[@"Yesterday", @"Queen", reply(@[@[@14401144, @"Yesterday", @[@"HearonTrackz"], @NO, @"HearonTrackz (Ft. Fat Money & Queen Key)"], @[@11550811, @"Yesterday Is Dead", @[@"Josiah Queen"]]]), @0],+ // Covers: the singer's own page, never the song's writer's, and nothing when Genius has no page for the cover.+ @[@"Hallelujah", @"Jeff Buckley", hallelujah, @84894],+ @[@"Hallelujah", @"Pentatonix", hallelujah, @2888288],+ @[@"Hallelujah", @"Some Choir", hallelujah, @0],+ // Remixes: the one named, the plain remix over another's, the song over its remixes.+ @[@"Old Town Road (feat. Billy Ray Cyrus) - Remix", @"Lil Nas X", oldTownRoad, @4445394],+ @[@"Old Town Road (feat. Billy Ray Cyrus) - Remix", @"Lil Nas X, Billy Ray Cyrus", oldTownRoad, @4445394],+ @[@"Old Town Road - Diplo Remix", @"Lil Nas X", oldTownRoad, @4514622],+ @[@"Old Town Road", @"Lil Nas X", oldTownRoad, @4133841],+ @[@"Blinding Lights", @"The Weeknd", blindingLights, @5049949],+ @[@"Blinding Lights - Instrumental", @"The Weeknd", blindingLights, @0],+ // A remaster is the song.+ @[@"Bohemian Rhapsody - Remastered 2011", @"Queen", reply(@[@[@2123526, @"Bohemian Rhapsody", @[@"The Muppets"]], @[@1063, @"Bohemian Rhapsody", @[@"Queen"]]]), @1063],+ // Two leads, a comma inside a name, a name Genius writes twice over either way.+ @[@"Under Pressure", @"Queen, David Bowie", reply(@[@[@6868363, @"Queen & David Bowie - Under Pressure (Traducción al Español)", @[@"Genius Traducciones al Español"]], @[@152350, @"Under Pressure", @[@"Queen", @"David Bowie"]]]), @152350],+ @[@"EARFQUAKE", @"Tyler, The Creator", reply(@[@[@4420287, @"EARFQUAKE", @[@"Tyler, The Creator"]]]), @4420287],+ @[@"Dynamite", @"BTS", reply(@[@[@5813592, @"Dynamite", @[@"BTS (방탄소년단)"]]]), @5813592],+ @[@"ЗНАК (SIGN)", @"Dora", reply(@[@[@13935027, @"ЗНАК (SIGN)", @[@"Toxi$", @"Дора (Dora)"]]]), @13935027],+ ];+ for (NSArray *c in cases) {+ NSNumber *song = SGGeniusSongIn(c[2], c[0], c[1]);+ printf("%s by %s: %s\n", [c[0] UTF8String], [c[1] UTF8String], song ? song.stringValue.UTF8String : "none");+ CHECK((song ?: @0).integerValue == [c[3] integerValue]);+ }+}++// A made-up embed in the shape genius.com/songs/:id/embed.js has: the HTML as a JSON string inside a+// single-quoted JavaScript string, escaped twice over.+static NSString *embedScript(NSString *html) {+ NSData *json = [NSJSONSerialization dataWithJSONObject:html options:NSJSONWritingFragmentsAllowed error:nil];+ NSString *string = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];+ string = [string stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];+ string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];+ string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];+ string = [string stringByReplacingOccurrencesOfString:@"/" withString:@"\\/"];+ return [NSString stringWithFormat:@"if (document.getElementById('rg_embed_link_1')) {\n"+ " document.write('<link rel=\"stylesheet\" href=\"x.css\" />')\n"+ " document.write(JSON.parse('%@'))\n}\n", string];+}++static void checkEmbed(void) {+ NSString *html = @"\n <div class=\"rg_embed music\" id=\"rg_embed_1\">\n <div class=\"rg_embed_header\">x</div>\n"+ " <div class=\"rg_embed_body\">\n <p><a href=\"https://genius.com/1/A\" data-id=\"1\">[Verse 1]</a><br>\n"+ "<a href=\"https://genius.com/2/B\" data-id=\"2\">Filler line one, it's here<br>\nFiller & line two</a><br>\n"+ "<i>Filler “line” three</i> "quoted" ’\n words<br>\n<br>\n<br>\n"+ "[Chorus: Someone]<br>\nFiller \\ line four <b>bold</b></p>\n\n</div>\n"+ " <div class=\"rg_embed_footer\"><div class=\"song_title\">T</div></div>\n </div>\n";+ NSArray<NSString *> *rows = SGGeniusEmbedRows(embedScript(html));+ printf("embed rows: %s\n", [rows componentsJoinedByString:@" | "].UTF8String);+ NSArray *want = @[@"Filler line one, it's here", @"Filler & line two", @"Filler “line” three \"quoted\" ’ words", @"",+ @"Filler \\ line four bold"];+ CHECK([rows isEqualToArray:want]);+ // What is not the embed's shape, or an embed of a song whose words are not out yet, has no lines.+ CHECK(!SGGeniusEmbedRows(nil));+ CHECK(!SGGeniusEmbedRows(@"<!DOCTYPE html><title>Genius</title>"));+ CHECK(!SGGeniusEmbedRows(embedScript(@"<div class=\"rg_embed_body\">\n \n</div>\n<div class=\"rg_embed_footer\"></div>")));+ CHECK(!SGGeniusEmbedRows(@"document.write(JSON.parse('\"unterminated"));+}++// The real thing, each track named as the player names it: searched on genius.com, the song it picks, and that song's embed read.+static void checkLive(void) {+ NSArray *tracks = @[+ @[@"Bohemian Rhapsody - Remastered 2011", @"Queen", @1063],+ @[@"Hallelujah", @"Jeff Buckley", @84894],+ @[@"Hallelujah", @"Pentatonix", @2888288],+ @[@"Old Town Road (feat. Billy Ray Cyrus) - Remix", @"Lil Nas X", @4445394],+ @[@"Blinding Lights", @"The Weeknd", @5049949],+ @[@"Under Pressure", @"Queen", @152350],+ @[@"Yesterday", @"Queen", @0],+ @[@"Blinding Lights - Instrumental", @"The Weeknd", @0],+ ];+ for (NSArray *t in tracks) {+ __block id root = nil;+ SGLyricsGetJSON(SGLyricsURL(SGGeniusSearchURL, SGGeniusSearchQuery(t[0], t[1])), nil, ^(id r) { root = r; });+ CHECK(root);+ NSNumber *song = SGGeniusSongIn(root[@"response"], t[0], t[1]);+ printf("live: %s by %s: %s", [t[0] UTF8String], [t[1] UTF8String], song ? song.stringValue.UTF8String : "none");+ CHECK((song ?: @0).integerValue == [t[2] integerValue]);+ if (!song) {+ printf("\n");+ continue;+ }+ __block NSString *js = nil;+ SGLyricsGetText([NSURL URLWithString:[NSString stringWithFormat:@"https://genius.com/songs/%@/embed.js", song]], ^(NSString *text) { js = text; });+ NSArray<NSString *> *rows = SGGeniusEmbedRows(js);+ NSUInteger stanzas = [rows filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length == 0"]].count;+ printf(", %lu rows in %lu stanzas\n", (unsigned long)rows.count, (unsigned long)stanzas + 1);+ CHECK(rows.count > 10);+ for (NSString *row in rows) {+ CHECK(![row containsString:@"<"] && ![row containsString:@">"] && ![row hasPrefix:@"["]);+ CHECK([row rangeOfString:@"&[a-z#0-9]+;" options:NSRegularExpressionSearch].location == NSNotFound);+ }+ }+ // The ask as the walk makes it: untimed lines, a ♪ for each gap.+ SGLyricsQuery *query = [SGLyricsQuery new];+ query.title = @"Hallelujah";+ query.artist = @"Jeff Buckley";+ __block SGLyricsResult *result = nil;+ SGGeniusAsk(query, ^(SGLyricsResult *r) { result = r; });+ printf("live ask: %lu lines, synced %d, timing %lu\n", (unsigned long)result.texts.count, result.synced,+ (unsigned long)SGKaraokeLinesTiming(result.karaokeLines));+ // The view's lines leave the ♪ out; Spotify's page keeps it.+ NSUInteger sung = [result.texts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != '♪'"]].count;+ CHECK(result.texts.count > 10 && !result.synced && result.karaokeLines.count == sung);+ CHECK(SGKaraokeLinesTiming(result.karaokeLines) == SGKaraokeTimingNone);+ CHECK([result.starts isEqualToArray:[result.starts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF == 0"]]]);+ CHECK([result.texts containsObject:@"♪"]);+}++int main(int argc, char **argv) {+ @autoreleasepool {+ sg_live = argc > 1 && !strcmp(argv[1], "live");+ checkPicks();+ checkEmbed();+ if (sg_live) checkLive();+ printf("all good\n");+ }+ return 0;+}diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.h b/tweak/Sources/Shared/LyricsMeanings/Meanings.hindex e67099f7..5e3b24f6 100644--- a/tweak/Sources/Shared/LyricsMeanings/Meanings.h+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.h@@ -36,3 +36,12 @@ SGModRow *SGLyricsMeaningsRow(void);// per track; the matching is done again for each set of lines.void SGLyricsMeaningsFor(NSString *trackID, NSArray<SGKaraokeLine *> *lines,void (^done)(NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *byLine));++// Genius's search, which the lyrics source asks too (Shared/LyricsSources/Genius.m): its address, what+// it is asked for a track, and the song in its reply that is the track. That song's title is the+// track's once a version in brackets or after " - " is set aside, and one of its own artists is the+// track's lead; of several, the same version wins, then the plain song. nil when none is, or the+// track is an instrumental or karaoke version, since Genius files the words under the song.+#define SGGeniusSearchURL @"https://genius.com/api/search/song"+NSDictionary<NSString *, NSString *> *SGGeniusSearchQuery(NSString *title, NSString *artist);+NSNumber *SGGeniusSongIn(NSDictionary *response, NSString *title, NSString *artist);diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.m b/tweak/Sources/Shared/LyricsMeanings/Meanings.mindex 7d8343ed..2166fe96 100644--- a/tweak/Sources/Shared/LyricsMeanings/Meanings.m+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.m@@ -3,7 +3,6 @@#import "Headers/SPTPlayer.h"#import "Meanings.h"-static NSString *const kSearch = @"https://genius.com/api/search/song";static NSString *const kReferents = @"https://genius.com/api/referents";static const NSUInteger kMostPages = 5, kPerPage = 50;// Shorter than this, a fragment found inside a line is more likely a common phrase than the line.@@ -126,26 +125,86 @@ static NSString *stringIn(id value) {return [value isKindOfClass:NSString.class] ? value : nil;}-// The hit whose title and artist both agree with the track's; a song only near it would explain-// lines it does not have.-static NSNumber *songIn(NSDictionary *response, NSString *title, NSString *artist) {+NSDictionary<NSString *, NSString *> *SGGeniusSearchQuery(NSString *title, NSString *artist) {+ return @{@"q": [NSString stringWithFormat:@"%@ %@", bareTitle(title), artist], @"per_page": @"10"};+}++// What a title says beyond the song's name: "Old Town Road - Remix" is {remix}, "Blinding Lights (Live)" {live}.+static NSSet<NSString *> *versionOf(NSString *title) {+ NSMutableSet<NSString *> *words = [NSMutableSet setWithArray:[folded(title) componentsSeparatedByString:@" "]];+ [words minusSet:[NSSet setWithArray:[folded(bareTitle(title)) componentsSeparatedByString:@" "]]];+ [words removeObject:@""];+ return words;+}++// The track's title without Spotify's "(feat. Billy Ray Cyrus)" or "(with Diplo)": who sings with the lead+// is not which recording it is. Genius's titles keep theirs, so a version of its own with a guest stays apart.+static NSString *withoutGuests(NSString *title) {+ static NSRegularExpression *guests;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ guests = [NSRegularExpression regularExpressionWithPattern:@"\\s*[\\(\\[](feat\\.?|ft\\.?|featuring|with)\\s[^\\)\\]]*[\\)\\]]"+ options:NSRegularExpressionCaseInsensitive error:nil];+ });+ return [guests stringByReplacingMatchesInString:title options:0 range:NSMakeRange(0, title.length) withTemplate:@""];+}++// Spotify joins a track's artists with ", ", which a name can hold too ("Tyler, The Creator"), so the+// lead artist is any run of the first names.+static NSSet<NSString *> *leadNames(NSString *artist) {+ NSMutableSet<NSString *> *names = [NSMutableSet set];+ NSString *run = @"";+ for (NSString *part in [artist componentsSeparatedByString:@", "]) {+ run = run.length ? [run stringByAppendingFormat:@" %@", folded(part)] : folded(part);+ if (run.length) [names addObject:run];+ }+ return names;+}++// Whether one of the song's own artists is the track's lead, the way Genius names them or without the+// bracket ("BTS (방탄소년단)"); a featured singer or a translation page's "Genius English Translations"+// never is.+static BOOL byLead(NSDictionary *song, NSSet<NSString *> *leads) {+ id primaries = song[@"primary_artists"];+ for (NSDictionary *primary in [primaries isKindOfClass:NSArray.class] ? primaries : @[]) {+ NSString *name = [primary isKindOfClass:NSDictionary.class] ? stringIn(primary[@"name"]) : nil;+ if (!name) continue;+ if ([leads containsObject:folded(name)] || [leads containsObject:folded(bareTitle(name))]) return YES;+ // "Дора (Dora)": the name in the bracket is the one Spotify may use.+ NSRange open = [name rangeOfString:@"("], close = [name rangeOfString:@")" options:NSBackwardsSearch];+ if (open.location != NSNotFound && close.location != NSNotFound && close.location > NSMaxRange(open)+ && [leads containsObject:folded([name substringWithRange:NSMakeRange(NSMaxRange(open), close.location - NSMaxRange(open))])]) return YES;+ }+ return NO;+}++NSNumber *SGGeniusSongIn(NSDictionary *response, NSString *title, NSString *artist) {+ if (![response isKindOfClass:NSDictionary.class] || !title.length || !artist.length) return nil;NSString *wantTitle = folded(bareTitle(title));- NSString *wantArtist = folded([artist componentsSeparatedByString:@", "].firstObject);+ NSSet<NSString *> *wantVersion = versionOf(withoutGuests(title));+ // Genius files a song's words under the song; a track with none sung would get them anyway.+ if ([wantVersion containsObject:@"instrumental"] || [wantVersion containsObject:@"karaoke"]) return nil;+ NSSet<NSString *> *leads = leadNames(artist);+ // Best first: the same version, then the plain song, then any other version of it.+ NSNumber *best = nil;+ NSInteger bestRank = 0;id sections = response[@"sections"];for (NSDictionary *section in [sections isKindOfClass:NSArray.class] ? sections : @[]) {id hits = [section isKindOfClass:NSDictionary.class] ? section[@"hits"] : nil;for (NSDictionary *hit in [hits isKindOfClass:NSArray.class] ? hits : @[]) {NSDictionary *song = [hit isKindOfClass:NSDictionary.class] ? hit[@"result"] : nil;if (![song isKindOfClass:NSDictionary.class] || ![song[@"id"] isKindOfClass:NSNumber.class]) continue;- NSString *hitTitle = folded(bareTitle(stringIn(song[@"title"])));- NSString *hitArtists = folded(stringIn(song[@"artist_names"]) ?: @"");- BOOL titled = [hitTitle isEqualToString:wantTitle];- BOOL byArtist = wantArtist.length && hitArtists.length- && ([hitArtists containsString:wantArtist] || [wantArtist containsString:hitArtists]);- if (titled && byArtist) return song[@"id"];+ NSString *hitTitle = stringIn(song[@"title"]);+ if ([song[@"instrumental"] boolValue] || ![folded(bareTitle(hitTitle)) isEqualToString:wantTitle] || !byLead(song, leads)) continue;+ NSSet<NSString *> *version = versionOf(hitTitle);+ NSInteger rank = [version isEqualToSet:wantVersion] ? 3 : version.count == 0 ? 2 : 1;+ if (rank > bestRank) {+ best = song[@"id"];+ bestRank = rank;+ }}}- return nil;+ return best;}// By the annotation, not the referent: a referent the artist spoke to is "verified" as a whole, the@@ -227,9 +286,8 @@ static void meaningsOf(NSString *trackID, void (^done)(NSArray<SGLyricsMeaning *answer(trackID, @[], NO);return;}- NSString *q = [NSString stringWithFormat:@"%@ %@", bareTitle(title), artist];- getJSON(kSearch, @{@"q": q, @"per_page": @"10"}, ^(NSDictionary *response) {- NSNumber *song = songIn(response, title, artist);+ getJSON(SGGeniusSearchURL, SGGeniusSearchQuery(title, artist), ^(NSDictionary *response) {+ NSNumber *song = SGGeniusSongIn(response, title, artist);if (!song) {SGLog(@"meanings: no Genius song for %@ by %@", title, artist);answer(trackID, @[], response != nil); // a failed search is asked again next timediff --git a/tweak/Sources/Shared/LyricsSources/Genius.m b/tweak/Sources/Shared/LyricsSources/Genius.mnew file mode 100644index 00000000..1a0aa18b--- /dev/null+++ b/tweak/Sources/Shared/LyricsSources/Genius.m@@ -0,0 +1,126 @@+// Genius, under every other source: the words as its users transcribed them, with no timing at all, for+// a track no source has lyrics for. The song is found by the same search the line meanings use+// (Shared/LyricsMeanings/Meanings.m).+//+// Genius's API gives a song's details and not its words; /api/songs/:id/lyrics wants a signed-in user.+// The words are read from the embed it offers other sites (songs/:id/embed.js, about 15 KB against the+// song page's 650): a script that writes the lyrics' HTML. That is reading a page, not an API, so a+// change to the script's shape or the rg_embed_body around the lines ends this source, quietly: it then+// has nothing for any track. Cloudflare in front of Genius turns some user agents away; the system's+// own gets through.+#import "Core/SGCore.h"+#import "LyricsSources.h"+#import "Shared/LyricsMeanings/Meanings.h"++// The string the script hands JSON.parse, its JavaScript escapes undone: a JSON string.+static NSString *scriptString(NSString *js) {+ NSRange open = [js rangeOfString:@"JSON.parse('"];+ if (open.location == NSNotFound) return nil;+ NSMutableString *json = [NSMutableString string];+ for (NSUInteger i = NSMaxRange(open); i < js.length; i++) {+ unichar c = [js characterAtIndex:i];+ if (c == '\'') return json;+ if (c == '\\' && ++i < js.length) c = [js characterAtIndex:i];+ [json appendFormat:@"%C", c];+ }+ return nil;+}++static NSString *decodedEntities(NSString *text) {+ static NSRegularExpression *entity;+ static NSDictionary<NSString *, NSString *> *named;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ entity = [NSRegularExpression regularExpressionWithPattern:@"&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-z]+);" options:0 error:nil];+ named = @{@"amp": @"&", @"lt": @"<", @"gt": @">", @"quot": @"\"", @"apos": @"'", @"nbsp": @" "};+ });+ NSMutableString *out = [text mutableCopy];+ for (NSTextCheckingResult *match in [entity matchesInString:text options:0 range:NSMakeRange(0, text.length)].reverseObjectEnumerator) {+ NSString *name = [text substringWithRange:[match rangeAtIndex:1]];+ NSString *with = named[name];+ if ([name hasPrefix:@"#"]) {+ BOOL hex = name.length > 1 && ([name characterAtIndex:1] == 'x' || [name characterAtIndex:1] == 'X');+ UTF32Char code = (UTF32Char)strtoul([name substringFromIndex:hex ? 2 : 1].UTF8String, NULL, hex ? 16 : 10);+ with = code ? [[NSString alloc] initWithBytes:&code length:4 encoding:NSUTF32LittleEndianStringEncoding] : nil;+ }+ if (with) [out replaceCharactersInRange:match.range withString:with];+ }+ return out;+}++NSArray<NSString *> *SGGeniusEmbedRows(NSString *js) {+ NSString *json = js ? scriptString(js) : nil;+ id html = json ? [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]+ options:NSJSONReadingFragmentsAllowed error:nil] : nil;+ if (![html isKindOfClass:NSString.class]) return nil;+ NSRange body = [html rangeOfString:@"rg_embed_body"];+ NSRange footer = [html rangeOfString:@"rg_embed_footer"];+ if (body.location == NSNotFound || footer.location == NSNotFound || footer.location < NSMaxRange(body)) return nil;+ // Up to the footer's own tag.+ NSUInteger end = [html rangeOfString:@"<" options:NSBackwardsSearch range:NSMakeRange(NSMaxRange(body), footer.location - NSMaxRange(body))].location;+ if (end == NSNotFound) return nil;+ NSString *lyrics = [html substringWithRange:NSMakeRange(NSMaxRange(body), end - NSMaxRange(body))];+ NSRange tagEnd = [lyrics rangeOfString:@">"];+ if (tagEnd.location == NSNotFound) return nil;+ lyrics = [lyrics substringFromIndex:NSMaxRange(tagEnd)];++ static NSRegularExpression *breaks, *tags;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ breaks = [NSRegularExpression regularExpressionWithPattern:@"<br\\s*/?>|</p>" options:NSRegularExpressionCaseInsensitive error:nil];+ tags = [NSRegularExpression regularExpressionWithPattern:@"<[^>]*>" options:0 error:nil];+ });+ // The HTML's own newlines are layout; its <br>s are the lines.+ lyrics = [[lyrics componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet] componentsJoinedByString:@""];+ lyrics = [breaks stringByReplacingMatchesInString:lyrics options:0 range:NSMakeRange(0, lyrics.length) withTemplate:@"\n"];+ lyrics = [tags stringByReplacingMatchesInString:lyrics options:0 range:NSMakeRange(0, lyrics.length) withTemplate:@""];+ lyrics = decodedEntities(lyrics);++ // [Chorus] and the like name the part, they are not sung; one empty row stands for any gap.+ NSMutableArray<NSString *> *rows = [NSMutableArray array];+ for (NSString *row in [lyrics componentsSeparatedByString:@"\n"]) {+ NSString *text = [row stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ if ([text hasPrefix:@"["] && [text hasSuffix:@"]"]) continue;+ if (!text.length && (!rows.count || !rows.lastObject.length)) continue;+ [rows addObject:text];+ }+ if (rows.count && !rows.lastObject.length) [rows removeLastObject];+ return rows.count ? rows : nil;+}++SGLyricsAsk SGGeniusAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {+ if (!query.title.length || !query.artist.length) {+ done(nil);+ return;+ }+ SGLyricsGetJSON(SGLyricsURL(SGGeniusSearchURL, SGGeniusSearchQuery(query.title, query.artist)), nil, ^(id root) {+ NSNumber *song = SGGeniusSongIn([root isKindOfClass:NSDictionary.class] ? root[@"response"] : nil, query.title, query.artist);+ if (!song) {+ SGLog(@"genius: no song for %@ by %@", query.title, query.artist);+ done(nil);+ return;+ }+ NSURL *embed = [NSURL URLWithString:[NSString stringWithFormat:@"https://genius.com/songs/%@/embed.js", song]];+ SGLyricsGetText(embed, ^(NSString *js) {+ NSArray<NSString *> *rows = SGGeniusEmbedRows(js);+ SGLog(@"genius: %@ by %@ is song %@, %@", query.title, query.artist, song,+ rows ? [NSString stringWithFormat:@"%lu untimed lines", (unsigned long)rows.count] : @"no lines in its embed");+ if (!rows) {+ done(nil);+ return;+ }+ // As LrcLib.m takes its plain lyrics: every start 0, a ♪ where a stanza ends.+ NSMutableArray<NSNumber *> *starts = [NSMutableArray array];+ NSMutableArray<NSString *> *texts = [NSMutableArray array];+ for (NSString *row in rows) {+ [starts addObject:@0];+ [texts addObject:row.length ? row : @"♪"];+ }+ SGLyricsResult *result = [SGLyricsResult new];+ result.starts = starts;+ result.texts = texts;+ result.karaokeLines = SGKaraokeStaticLines(texts);+ done(result);+ });+ });+};diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.h b/tweak/Sources/Shared/LyricsSources/LyricsSources.hindex 8b5e39c4..86514cd8 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.h+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.h@@ -168,6 +168,10 @@ extern SGLyricsAsk SGLrcLibAsk;extern SGLyricsAsk SGSpicyLyricsAsk;extern SGLyricsAsk SGQQMusicAsk;extern SGLyricsAsk SGKuGouAsk;+extern SGLyricsAsk SGGeniusAsk;+// Genius.m. The rows of the lyrics in Genius's embed script, "" between stanzas and the [Chorus]+// headings left out; nil when the script is not the shape it reads or holds no line.+NSArray<NSString *> *SGGeniusEmbedRows(NSString *js);// LrcLib.m. Timed LRC as a synced result, nil when no line in it is timed.SGLyricsResult *SGLyricsLRCResult(NSString *lrc);diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.m b/tweak/Sources/Shared/LyricsSources/LyricsSources.mindex 33829ec8..ab5b8ff9 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.m+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.m@@ -182,6 +182,7 @@ NSArray<SGLyricsProvider *> *SGLyricsAllProviders(void) {make(@"qqmusic", @"QQ Music", @"Line timing, Chinese catalog", SGQQMusicAsk),make(@"kugou", @"KuGou", @"Word timing, Chinese catalog", SGKuGouAsk),make(SGImportedLRCKey, @"Imported LRC", @"Your own .lrc files", SGImportedLRCAsk),+ make(@"genius", @"Genius", @"Untimed, when no other has lyrics", SGGeniusAsk),];});return all;@@ -204,10 +205,11 @@ static NSArray<NSString *> *fromLegacyKeys(void) {}// With nothing stored and nothing to carry over, every source is on: the user's own files first, word-// timing ahead of line timing, and the two Chinese catalogs last, asked only once the rest have missed.+// timing ahead of line timing, the two Chinese catalogs once the rest have missed, and Genius's untimed+// words under everything.// Spicy Lyrics passes straight on without its key.static NSArray<NSString *> *defaultOrder(void) {- return @[SGImportedLRCKey, SGSpicyLyricsKey, @"binilyrics", @"musixmatch", @"unison", @"netease", @"lrclib", @"qqmusic", @"kugou"];+ return @[SGImportedLRCKey, SGSpicyLyricsKey, @"binilyrics", @"musixmatch", @"unison", @"netease", @"lrclib", @"qqmusic", @"kugou", @"genius"];}NSArray<NSString *> *SGLyricsOrder(void) {