Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Spicy Lyrics supports publishable keys, pronunciations and linked credits
My-Name-Is-Jeff67f74313c165
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex e8a0b3bc..3c82f5b2 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -98,8 +98,11 @@ Shared:timed word by word (the translation taken in the Lyrics page's language); Musixmatch.m, matched bySpotify's track id with an anonymous token, word timed where it has richsync; NetEase.m, word timing from yrc for what the others only line time; LrcLib.m, open andkeyless and timed by the line, the floor under the rest. SpicyLyrics.m, Spicy Lyrics' Developer Platform- by track id on the user's own key (Keychain), syllable timed where it has a sync; checked on the Mac- against harness/spicy-lyrics/. QQMusic.m (line timed LRC) and KuGou.m (word timed KRC, unpacked with+ by track id on the user's own publishable key (Keychain), syllable timed where it has a sync, with+ its pronunciations and translations; its credit, which its terms require, shows whatever Show source+ says and opens the uploader's and maker's pages from a tap (both looks), its answers and misses are+ kept per track, a rate limit is waited out and a refused key is left for 10 min, its reason on the+ source'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, singerand length; checked on the Mac against harness/lyrics-sources/. 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 has@@ -289,7 +292,8 @@ Native:on either side of the cover that plays at 2x until the finger lifts (PlayerGestures.x), the list's pullheld off while the progress bar is scrubbed (PlayerScrub.x), the Queue & devices flags. The scrub andthe cover's room are checked in the simulator against harness/native-player/- Lyrics/ the full screen lyrics page on glass (LyricsPage.x)+ Lyrics/ the full screen lyrics page on glass, and a tap on the lyrics' footer opening the pages a credit+ links to (LyricsPage.x)LocalFiles/ a lyrics button on the player's footer for a local file with an LRC file linked to it, a fifth of theway in from the leading edge, which opens a page of the lines on black that follows the song(LocalLyrics.h lists its files); the file's metadata says has_lyrics. Checked in the simulatordiff --git a/harness/lyrics/stubs.m b/harness/lyrics/stubs.mindex eb4dc6d4..a68df503 100644--- a/harness/lyrics/stubs.m+++ b/harness/lyrics/stubs.m@@ -12,7 +12,29 @@ CFTimeInterval SGPlayerTransitionEnds(void) { return 0; }void SGRPlayFeedback(NSInteger feedback) {}void SGPlayFeedback(NSInteger feedback) {} // the name it has had since Haptics moved to Shared-NSString *SGLyricsCreditFor(NSString *trackID) { return @"the harness"; }+// -credit names the source (Show source is -spotifyglass.lyricsCredit 1); one naming Spicy Lyrics is+// required, so it shows either way, and links to two people, as SpicyLyrics.m's community syncs do.+NSString *SGLyricsCreditFor(NSString *trackID) { return [NSUserDefaults.standardUserDefaults stringForKey:@"credit"] ?: @"the harness"; }+// LyricsSources.h's, declared here: that header's SPTPlayerTrack clashes with the track stub below.+@interface SGLyricsLink : NSObject+@property (nonatomic, copy) NSString *title;+@property (nonatomic, copy) NSURL *url;+@end+@implementation SGLyricsLink+@end+BOOL SGLyricsCreditRequired(NSString *credit) { return [credit hasPrefix:@"Spicy Lyrics"]; }+NSArray<SGLyricsLink *> *SGLyricsCreditLinks(NSString *text) {+ if (![text containsString:@"Spicy Lyrics"]) return nil;+ NSMutableArray<SGLyricsLink *> *links = [NSMutableArray array];+ for (NSString *who in @[@"Uploader", @"Maker"]) {+ SGLyricsLink *link = [SGLyricsLink new];+ link.title = [who stringByAppendingString:@": harness"];+ link.url = [NSURL URLWithString:@"https://example.org/"];+ [links addObject:link];+ }+ return links;+}+void SGLyricsOpenCreditLinks(NSArray<SGLyricsLink *> *links, UIView *from) { NSLog(@"harness: credit opens %lu links", (unsigned long)links.count); }// -translateTo es: the language the Lyrics page would ask translations for.NSString *SGLyricsTranslationLanguage(void) { return [NSUserDefaults.standardUserDefaults stringForKey:@"translateTo"]; }diff --git a/harness/player/stubs.m b/harness/player/stubs.mindex 9dd299de..d6092968 100644--- a/harness/player/stubs.m+++ b/harness/player/stubs.m@@ -94,6 +94,9 @@ void SGPrepareFeedback(NSInteger feedback) {}#pragma mark - Shared/LyricsSourcesNSString *SGLyricsCreditFor(NSString *trackID) { return @"the harness"; }+BOOL SGLyricsCreditRequired(NSString *credit) { return NO; }+NSArray *SGLyricsCreditLinks(NSString *text) { return nil; }+void SGLyricsOpenCreditLinks(NSArray *links, UIView *from) {}#pragma mark - Shared/Lyrics/KaraokeSource.xdiff --git a/harness/spicy-lyrics/README.md b/harness/spicy-lyrics/README.mdindex c7a4c254..0843cfc9 100644--- a/harness/spicy-lyrics/README.md+++ b/harness/spicy-lyrics/README.md@@ -3,7 +3,13 @@`./build.sh` reads made-up responses of the Spicy Lyrics API (a Syllable sync with a duet, abacking vocal, a split word and a translation; a Line sync with a gap; a Static one) through the real`SGSpicyLyricsResult` and checks the lines and the credit each one gets, and that a translation is-left out once the Lyrics page asks for a language. It runs on the Mac as a+left out once the Lyrics page asks for a language. It also checks the pronunciations (from each syllable, estimated from+the line's, left out when they read the same), the translations joined from the backing groups, the+credit's links, the ♪ between a Static sync's stanzas, the key check (publishable only), the wait a+429, 503 or spent RateLimit-Remaining asks for, and the ask itself on a stubbed reply: ids that are not+base62 never sent, answers and misses kept, a rate limit skipped and counted as lost, a refused key left+alone. It runs on the Mac as aMac Catalyst binary, with no simulator and no network.-It does not cover the request itself, the key in the Keychain, or the lines on the lyrics view.+It does not cover the real request, the key in the Keychain, the reason a refused key shows on its+row, or the credit on the lyrics view (harness/lyrics/ with `-credit "Spicy Lyrics, ..."` shows it).diff --git a/harness/spicy-lyrics/build.sh b/harness/spicy-lyrics/build.shindex fc5e02a2..cbb8ccdd 100755--- a/harness/spicy-lyrics/build.sh+++ b/harness/spicy-lyrics/build.sh@@ -6,6 +6,6 @@ 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/SpicyLyrics.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \+ "$HERE/check.m" "$SRC/Shared/LyricsSources/SpicyLyrics.m" "$SRC/Shared/LyricsSources/SGTTML.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \-framework UIKit -framework Security -framework Foundation -o "$HERE/build/check""$HERE/build/check"diff --git a/harness/spicy-lyrics/check.m b/harness/spicy-lyrics/check.mindex 24ab7801..16c9bad8 100644--- a/harness/spicy-lyrics/check.m+++ b/harness/spicy-lyrics/check.m@@ -7,11 +7,26 @@// What SpicyLyrics.m reaches outside the parser for; none of it but the result class is used here.@implementation SGLyricsResult@end+@implementation SGLyricsLink+@endvoid SGLyricsPageLines(NSArray<SGKaraokeLine *> *lines, NSArray<NSNumber *> **starts, NSArray<NSString *> **texts) {*starts = [lines valueForKey:@"start"];*texts = @[];}void SGLyricsGetJSON(NSURL *url, NSDictionary *headers, void (^done)(id root)) { done(nil); }+@implementation SGLyricsQuery+@end+// The reply the next request gets, and how many were sent and lost.+static NSHTTPURLResponse *sg_reply;+static id sg_body;+static NSUInteger sg_sent, sg_lost;+static NSDictionary *sg_headers;+void SGLyricsGetJSONReply(NSURL *url, NSDictionary *headers, void (^done)(id root, NSHTTPURLResponse *response)) {+ sg_sent++;+ sg_headers = headers;+ done(sg_body, sg_reply);+}+void SGLyricsNoteReply(NSURLResponse *response, NSError *error) { if (error) sg_lost++; }NSArray<NSString *> *SGLyricsOrder(void) { return @[]; }void SGLyricsSetOrder(NSArray<NSString *> *keys) {}SGModRow *SGStatActionRow(NSString *t, NSString *s, NSString *(^v)(void), void (^a)(void)) { return nil; }@@ -19,8 +34,27 @@ UIViewController *SGTopController(void) { return nil; }static NSString *sg_language; // the Lyrics page's translation language, nil for AnyNSString *SGLyricsTranslationLanguage(void) { return sg_language; }+// SpicyLyrics.m's ask with the key passed in, its wait and its key check.+void SGSpicyLyricsAskWith(NSString *key, SGLyricsQuery *query, void (^done)(SGLyricsResult *result));+NSTimeInterval SGSpicyLyricsWait(NSHTTPURLResponse *reply, NSDate *now);+NSString *SGSpicyLyricsKeyProblem(NSString *key);+#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)+static NSHTTPURLResponse *reply(NSInteger status, NSDictionary *headers) {+ return [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://api.spicylyrics.org/"] statusCode:status HTTPVersion:@"HTTP/1.1" headerFields:headers];+}++// Asks for a track and says what came back: the result, or nil, at once since the stub answers at once.+static SGLyricsResult *ask(NSString *trackID) {+ SGLyricsQuery *query = [SGLyricsQuery new];+ query.trackID = trackID;+ __block SGLyricsResult *answer = (id)@"unanswered";+ SGSpicyLyricsAskWith(@"sl_pk_harness_key", query, ^(SGLyricsResult *result) { answer = result; });+ CHECK(![(id)answer isEqual:@"unanswered"]);+ return answer;+}+static SGLyricsResult *parse(NSString *json) {return SGSpicyLyricsResult([NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]);}@@ -49,6 +83,39 @@ int main(void) {CHECK([SGKaraokeLineText(first.backing) isEqualToString:@"(oh) (yeah)"] && first.backing.start == 2500 && first.backing.end == 3900);CHECK(first.align == SGKaraokeAlignLeading && syllable.karaokeLines[1].align == SGKaraokeAlignTrailing);CHECK([syllable.provider isEqualToString:@"Spicy Lyrics, synced by mk, uploaded by up"]);+ CHECK(syllable.creditRequired && !syllable.creditLinks); // no addresses, nothing to open++ // The required credit's links, uploader first; a person with no http address has none.+ SGLyricsResult *linked = parse(@"{\"Body\":{\"Type\":\"Static\",\"source\":\"spicy_lyrics\",\"Lines\":[{\"Text\":\"a\"}],"+ "\"UploadAttribution\":{\"Uploader\":{\"username\":\"up\",\"url\":\"https://spicylyrics.org/u/up\"},"+ "\"Maker\":{\"username\":\"mk\",\"url\":\"https://spicylyrics.org/u/mk\"}}}}");+ CHECK(linked.creditLinks.count == 2 && [linked.creditLinks[0].title isEqualToString:@"Uploader: up"]+ && [linked.creditLinks[1].url.absoluteString isEqualToString:@"https://spicylyrics.org/u/mk"]);+ CHECK(parse(@"{\"Body\":{\"Type\":\"Static\",\"source\":\"spicy_lyrics\",\"Lines\":[{\"Text\":\"a\"}],"+ "\"UploadAttribution\":{\"Uploader\":{\"username\":\"up\",\"url\":\"javascript:x\"},"+ "\"Maker\":{\"username\":\"mk\",\"url\":\"https://spicylyrics.org/u/mk\"}}}}").creditLinks.count == 1);+ CHECK([parse(@"{\"Body\":{\"Type\":\"Static\",\"source\":\"other\",\"Lines\":[{\"Text\":\"a\"}]}}").provider+ isEqualToString:@"Spicy Lyrics, source unknown"]);++ // Pronunciation from each syllable's spelling, timed with it; the backing's from its own; the+ // translations of the lead and every background group joined; the line timed by the Lead.+ SGLyricsResult *spelt = parse(@"{\"Body\":{\"Type\":\"Syllable\",\"source\":\"spotify\",\"Content\":[{\"Lead\":{"+ "\"StartTime\":1,\"EndTime\":4,\"TranslatedText\":\"I\",\"Syllables\":["+ "{\"Text\":\"私\",\"TransliteratedText\":\"wata\",\"StartTime\":1.2,\"EndTime\":1.6,\"IsPartOfWord\":true},"+ "{\"Text\":\"は\",\"TransliteratedText\":\"shi wa\",\"StartTime\":1.6,\"EndTime\":2}]},"+ "\"Background\":[{\"TranslatedText\":\"oh\",\"Syllables\":[{\"Text\":\"ああ\",\"TransliteratedText\":\"aa\",\"StartTime\":2,\"EndTime\":3}]},"+ "{\"TranslatedText\":\"yes\",\"Syllables\":[{\"Text\":\"はい\",\"StartTime\":3,\"EndTime\":3.5}]}]},"+ "{\"Lead\":{\"TransliteratedText\":\"ko re\",\"Syllables\":[{\"Text\":\"これ\",\"StartTime\":5,\"EndTime\":6}]}},"+ "{\"Lead\":{\"TransliteratedText\":\"same\",\"TranslatedText\":\"Same!\",\"Syllables\":[{\"Text\":\"same\",\"StartTime\":7,\"EndTime\":8}]}}]}}");+ SGKaraokeLine *jp = spelt.karaokeLines[0];+ CHECK(jp.start == 1000 && jp.end == 4000);+ CHECK([SGKaraokeLineText(jp.pronunciation) isEqualToString:@"watashi wa"] && jp.pronunciation.words[1].start == 1600);+ CHECK([SGKaraokeLineText(jp.backing.pronunciation) isEqualToString:@"aa"]);+ CHECK([jp.translation isEqualToString:@"I oh yes"]);+ SGKaraokeLine *estimated = spelt.karaokeLines[1];+ CHECK([SGKaraokeLineText(estimated.pronunciation) isEqualToString:@"ko re"] && estimated.pronunciation.start == 5000);+ SGKaraokeLine *same = spelt.karaokeLines[2];+ CHECK(!same.pronunciation && !same.translation); // both read the same as the lineSGLyricsResult *line = parse(@"{\"Body\":{\"Type\":\"Line\",\"source\":\"spotify\",\"Content\":[""{\"Type\":\"Vocal\",\"Text\":\"one line\",\"StartTime\":10.81,\"EndTime\":12,\"OppositeAligned\":false},"@@ -60,6 +127,8 @@ int main(void) {CHECK(line.karaokeLines[1].align == SGKaraokeAlignTrailing);CHECK(!line.karaokeLines[0].translation && [line.karaokeLines[1].translation isEqualToString:@"zwei"]);CHECK([line.provider isEqualToString:@"Spotify via Spicy Lyrics"]);+ CHECK([SGKaraokeLineText(parse(@"{\"Body\":{\"Type\":\"Line\",\"Content\":[{\"Text\":\"東京\",\"TransliteratedText\":\"Tokyo\","+ "\"StartTime\":1,\"EndTime\":3}]}}").karaokeLines[0].pronunciation) isEqualToString:@"Tokyo"]);// With a language chosen, a translation the API names no language for is left out of both syncs.sg_language = @"es";@@ -69,13 +138,57 @@ int main(void) {"{\"Text\":\"day\",\"StartTime\":2.2,\"EndTime\":3}]}}]}}").karaokeLines[0].translation);sg_language = nil;- SGLyricsResult *plain = parse(@"{\"Body\":{\"Type\":\"Static\",\"source\":\"apple_music\",\"Lines\":[{\"Text\":\"a b\"},{\"Text\":\"\"},{\"Text\":\"c\"}]}}");+ SGLyricsResult *plain = parse(@"{\"Body\":{\"Type\":\"Static\",\"source\":\"apple_music\",\"Lines\":[{\"Text\":\"\"},{\"Text\":\"a b\"},{\"Text\":\"\"},"+ "{\"Text\":\"\"},{\"Text\":\"c\",\"TranslatedText\":\"ce\"},{\"Text\":\"\"}]}}");CHECK(plain.karaokeLines.count == 2 && !plain.synced);- CHECK([plain.texts isEqualToArray:(@[@"a b", @"c"])] && [plain.starts isEqualToArray:(@[@0, @0])]);+ // An empty row between lines is a ♪ on Spotify's page; one at either end is left off.+ CHECK([plain.texts isEqualToArray:(@[@"a b", @"♪", @"c"])] && [plain.starts isEqualToArray:(@[@0, @0, @0])]);+ CHECK(!plain.karaokeLines[0].translation && [plain.karaokeLines[1].translation isEqualToString:@"ce"]);CHECK([plain.provider isEqualToString:@"Apple Music via Spicy Lyrics"]);CHECK(!parse(@"{\"Body\":{\"Type\":\"Syllable\",\"Content\":[]}}"));CHECK(!parse(@"{\"error\":\"not found\"}"));+ // The key: publishable only.+ CHECK(!SGSpicyLyricsKeyProblem(@"sl_pk_abcdef123"));+ CHECK([SGSpicyLyricsKeyProblem(@"sl_sk_abcdef123") containsString:@"secret"]);+ CHECK(SGSpicyLyricsKeyProblem(@"sl_pk_abc") && SGSpicyLyricsKeyProblem(@"sl_pk_abc def 12") && SGSpicyLyricsKeyProblem(@"pk_abcdefghijkl"));++ // The wait a reply asks for.+ NSDate *now = [NSDate dateWithTimeIntervalSince1970:1700000000];+ CHECK(SGSpicyLyricsWait(reply(429, @{@"Retry-After": @"30", @"RateLimit-Reset": @"90"}), now) == 30);+ CHECK(SGSpicyLyricsWait(reply(503, @{@"RateLimit-Reset": @"90"}), now) == 90);+ CHECK(SGSpicyLyricsWait(reply(429, @{}), now) == 60);+ CHECK(SGSpicyLyricsWait(reply(429, @{@"Retry-After": @"99999"}), now) == 3600);+ CHECK(SGSpicyLyricsWait(reply(429, @{@"Retry-After": @"Tue, 14 Nov 2023 22:15:20 GMT"}), now) == 120);+ CHECK(SGSpicyLyricsWait(reply(200, @{@"RateLimit-Remaining": @"0", @"RateLimit-Reset": @"12"}), now) == 12);+ CHECK(SGSpicyLyricsWait(reply(200, @{@"RateLimit-Remaining": @"0", @"RateLimit-Reset": @"1700000045"}), now) == 45);+ CHECK(SGSpicyLyricsWait(reply(200, @{@"RateLimit-Remaining": @"3", @"RateLimit-Reset": @"12"}), now) == 0);++ // Asking: a bad id is never sent; an answer and a miss are kept; the request's headers.+ sg_body = [NSJSONSerialization JSONObjectWithData:[@"{\"Body\":{\"Type\":\"Static\",\"Lines\":[{\"Text\":\"a\"}]}}" dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];+ sg_reply = reply(200, @{});+ CHECK(!ask(@"0123456789abcdefghij-_") && !ask(@"short") && sg_sent == 0);+ CHECK(ask(@"0123456789abcdefghijkA") && sg_sent == 1);+ CHECK([sg_headers[@"Authorization"] isEqualToString:@"Bearer sl_pk_harness_key"] && [sg_headers[@"Accept"] isEqualToString:@"application/json"]+ && [sg_headers[@"User-Agent"] hasPrefix:@"Vitrine/"]);+ CHECK(ask(@"0123456789abcdefghijkA") && sg_sent == 1);+ sg_reply = reply(404, @{});+ sg_body = nil;+ CHECK(!ask(@"0123456789abcdefghijkB") && !ask(@"0123456789abcdefghijkB") && sg_sent == 2);++ // A 429 is waited out, each skip counted as lost; then asked again.+ sg_reply = reply(429, @{@"Retry-After": @"1"});+ CHECK(!ask(@"0123456789abcdefghijkC") && sg_sent == 3);+ CHECK(!ask(@"0123456789abcdefghijkC") && sg_sent == 3 && sg_lost == 1);+ [NSThread sleepForTimeInterval:1.1];+ sg_reply = reply(404, @{});+ CHECK(!ask(@"0123456789abcdefghijkC") && sg_sent == 4);++ // A refused key: the reason for the row, and no request for ten minutes.+ sg_reply = reply(401, @{});+ sg_body = @{@"Body": @{@"error": @"origin_not_allowed"}};+ CHECK(!ask(@"0123456789abcdefghijkD") && sg_sent == 5);+ CHECK(!ask(@"0123456789abcdefghijkE") && sg_sent == 5 && sg_lost == 1);puts("spicy lyrics: all checks passed");}return 0;diff --git a/tweak/Sources/Native/Lyrics/LyricsPage.x b/tweak/Sources/Native/Lyrics/LyricsPage.xindex d00d490c..a544e9ca 100644--- a/tweak/Sources/Native/Lyrics/LyricsPage.x+++ b/tweak/Sources/Native/Lyrics/LyricsPage.x@@ -10,9 +10,13 @@// comes back through a path Native/Appearance/Repaint.x never sees, so a sweep at layout time loses the race.// FullscreenView is asked not to keep it at all instead. The pane goes inside FullscreenView, in// front of whatever that view still fills itself with, rather than behind the whole page.+//+// And under either kind of page, with glass or without, the footer's credit opens the pages it links to.#import "Core/SGCore.h"#import "Native/Player/NowPlaying.h"#import "Native/Appearance/Repaint.h"+#import "Shared/LyricsSources/LyricsSources.h"+#import <objc/runtime.h>static char kPageGlassKey;@@ -56,8 +60,84 @@ static UIView *clearAncestors(UIView *view) {}%end+#pragma mark - the credit++// The footer under the page's lines ("Lyrics provided by ..."), which names the source of the page's text+// (Shared/LyricsSources/LyricsHook.x). A credit that links to the people who made the lines (SpicyLyrics.m)+// opens their pages from a tap on it; any other footer's tap never begins, and passes on to Spotify.+static NSString *footerText(UIView *view) {+ if ([view isKindOfClass:UILabel.class] && ((UILabel *)view).text.length) return ((UILabel *)view).text;+ for (UIView *child in view.subviews) {+ NSString *text = footerText(child);+ if (text) return text;+ }+ return nil;+}++@interface SGFooterCreditTap : UITapGestureRecognizer <UIGestureRecognizerDelegate>+@end++@implementation SGFooterCreditTap++- (instancetype)init {+ if (!(self = [super initWithTarget:nil action:NULL])) return nil;+ [self addTarget:self action:@selector(open)];+ self.delegate = self;+ return self;+}++- (NSArray<SGLyricsLink *> *)links {+ NSString *text = footerText(self.view) ?: self.view.accessibilityLabel;+ static dispatch_once_t once;+ dispatch_once(&once, ^{ SGLog(@"lyrics page: its footer reads \"%@\"", text); });+ return SGLyricsCreditLinks(text);+}++- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)recognizer {+ return [self links].count > 0;+}++- (void)open {+ SGLyricsOpenCreditLinks([self links], self.view);+}++@end++static char kCreditTapKey;++static void tapForCredit(UIView *footer) {+ if (!footer.window || objc_getAssociatedObject(footer, &kCreditTapKey)) return;+ SGFooterCreditTap *tap = [SGFooterCreditTap new];+ [footer addGestureRecognizer:tap];+ footer.userInteractionEnabled = YES;+ objc_setAssociatedObject(footer, &kCreditTapKey, tap, OBJC_ASSOCIATION_RETAIN_NONATOMIC);+}++// The footer as the lyrics page draws it, under the card's text, and under the sing-along page's.+%hook _TtC22Lyrics_TextElementImpl16LyricsFooterView+- (void)didMoveToWindow {+ %orig;+ tapForCredit((UIView *)self);+}+%end++%hook _TtC24Lyrics_TextComponentImpl16LyricsFooterView+- (void)didMoveToWindow {+ %orig;+ tapForCredit((UIView *)self);+}+%end++%hook _TtC31Lyrics_TextElementSingalongImpl16LyricsFooterView+- (void)didMoveToWindow {+ %orig;+ tapForCredit((UIView *)self);+}+%end+%ctor {if (!SGNativeUI()) return;%init;- SGRequireClasses(@[@"_TtC32Lyrics_FullscreenElementPageImpl14FullscreenView"]);+ SGRequireClasses(@[@"_TtC32Lyrics_FullscreenElementPageImpl14FullscreenView", @"_TtC22Lyrics_TextElementImpl16LyricsFooterView",+ @"_TtC24Lyrics_TextComponentImpl16LyricsFooterView"]);}diff --git a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.mindex 11d9e69a..e3f312d1 100644--- a/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m+++ b/tweak/Sources/Redesigned/Lyrics/SGRKaraokeView.m@@ -33,8 +33,10 @@ static const CGFloat kBackingScale = 0.62, kBackingAlpha = 0.8, kBackingGap = 4;// for anyone else's.static const CGFloat kBubbleSide = 22, kBubbleGap = 8, kBubbleGlyph = 11, kBubbleAlpha = 0.75, kBubbleReach = 14;static const CGFloat kUnderlineDrop = 1, kUnderlineWidth = 2, kUnderlineAlpha = 0.35;-// The line naming the source, under the lyrics and outside the fade so it does not dim with them.-static const CGFloat kCreditSize = 12, kCreditAlpha = 0.4, kCreditBottom = 10;+// The line naming the source, under the lyrics and outside the fade so it does not dim with them. It+// wraps onto a second line rather than run under the buttons beside it, and a tap this far around it+// opens the pages it links to.+static const CGFloat kCreditSize = 12, kCreditAlpha = 0.4, kCreditBottom = 10, kCreditSlop = 8;// The button for the pronunciation and the translation, in the bottom leading corner as Apple Music// has it, and the gap between it and the credit beside it.static const CGFloat kExtrasSide = 44, kExtrasBottom = 12, kExtrasGlyph = 17, kExtrasCreditGap = 12;@@ -1218,8 +1220,10 @@ typedef struct {BOOL _showing;CAGradientLayer *_fade;UILabel *_credit;+ NSString *_creditSource; // the source the credit was settled on, nil until the lyrics name one+ NSArray<SGLyricsLink *> *_creditLinks;CGFloat _fontSize, _margin, _lineGap, _blurPerLine, _maxBlur;- BOOL _crediting; // the switch is read once: the page asks for the source on every frame until it has one+ BOOL _crediting; // Show source, read once: the page asks for the source on every frame until it has onedouble _clock;NSInteger _reported;CFTimeInterval _clockTime;@@ -1260,6 +1264,7 @@ typedef struct {_credit.font = [UIFont systemFontOfSize:kCreditSize weight:UIFontWeightSemibold];_credit.textColor = [UIColor colorWithWhite:1 alpha:kCreditAlpha];_credit.hidden = YES;+ _credit.numberOfLines = 2;_crediting = SGFlag(SGKeyLyricsCredit, NO);_sweepsEstimates = SGFlag(SGKeyLyricsSimulateWords, NO);[self addSubview:_credit];@@ -1330,6 +1335,11 @@ typedef struct {- (void)tapped:(UITapGestureRecognizer *)tap {if (_extrasBox && !_extrasBox.hidden && CGRectContainsPoint(_extrasBox.frame, [tap locationInView:self])) return;if (_sing.userInteractionEnabled && [_sing pointInside:[tap locationInView:_sing] withEvent:nil]) return;+ if (_creditLinks.count && !_credit.hidden+ && CGRectContainsPoint(CGRectInset(_credit.frame, -kCreditSlop, -kCreditSlop), [tap locationInView:self])) {+ SGLyricsOpenCreditLinks(_creditLinks, _credit);+ return;+ }CGPoint point = [tap locationInView:_scroll];for (SGRKaraokeLineView *view in _shown.allValues) {CGRect target = view.bubbleTarget;@@ -1511,15 +1521,21 @@ typedef struct {[super layoutSubviews];[self alignFade];_scroll.contentSize = self.bounds.size;- [_credit sizeToFit];- _credit.frame = CGRectMake(_margin, self.bounds.size.height - _credit.bounds.size.height - kCreditBottom,- _credit.bounds.size.width, _credit.bounds.size.height);- if (_extrasBox && !_extrasBox.hidden) {+ _sing.frame = CGRectMake(self.bounds.size.width - _margin - kExtrasSide, self.bounds.size.height - kExtrasSide - kExtrasBottom, kExtrasSide, kExtrasSide);+ BOOL extras = _extrasBox && !_extrasBox.hidden;+ // Between the pronunciation button and the mic, wrapping to fit.+ CGFloat left = extras ? _margin + kExtrasSide + kExtrasCreditGap : _margin;+ CGFloat right = _sing ? CGRectGetMinX(_sing.frame) - kExtrasCreditGap : self.bounds.size.width - _margin;+ CGFloat room = MAX(right - left, 0);+ CGSize credit = [_credit sizeThatFits:CGSizeMake(room, CGFLOAT_MAX)];+ credit.width = MIN(ceil(credit.width), room);+ credit.height = ceil(credit.height);+ _credit.frame = CGRectMake(left, self.bounds.size.height - credit.height - kCreditBottom, credit.width, credit.height);+ if (extras) {_extrasBox.frame = CGRectMake(_margin, self.bounds.size.height - kExtrasSide - kExtrasBottom, kExtrasSide, kExtrasSide);SGRShowGlass(SGRGlassInside(_extrasBox, &kExtrasGlassKey, kExtrasSide), !_extrasHidden);- _credit.center = CGPointMake(CGRectGetMaxX(_extrasBox.frame) + kExtrasCreditGap + _credit.bounds.size.width / 2, _extrasBox.center.y);+ _credit.center = CGPointMake(_credit.center.x, _extrasBox.center.y);}- _sing.frame = CGRectMake(self.bounds.size.width - _margin - kExtrasSide, self.bounds.size.height - kExtrasSide - kExtrasBottom, kExtrasSide, kExtrasSide);if (_lines && self.bounds.size.width != _builtWidth) {[self rebuild];} else if (_tops && self.bounds.size.height != _placedHeight) {@@ -1921,8 +1937,13 @@ static BOOL hasWords(SGKaraokeLine *line) {_dots.frame = CGRectMake(_margin, top, _builtWidth - 2 * _margin, _dots.bounds.size.height);}+// A credit the source's terms require shows whatever Show source says (Shared/LyricsSources/SpicyLyrics.m).- (void)creditTo:(NSString *)source {- NSString *text = source.length && _crediting ? [NSString stringWithFormat:@"Lyrics from %@", source] : nil;+ _creditSource = source;+ BOOL shown = source.length && (_crediting || SGLyricsCreditRequired(source));+ NSString *text = shown ? [NSString stringWithFormat:@"Lyrics from %@", source] : nil;+ _creditLinks = shown ? SGLyricsCreditLinks(source) : nil;+ _credit.accessibilityTraits = _creditLinks.count ? UIAccessibilityTraitLink : UIAccessibilityTraitStaticText;if (text == _credit.text || [text isEqualToString:_credit.text]) return;_credit.text = text;_credit.hidden = !_showing || !text.length;@@ -2022,7 +2043,7 @@ static BOOL hasWords(SGKaraokeLine *line) {}[self setShowing:_tops != nil];// The source is settled a moment after the lines are, so it is asked for until it answers.- if (_crediting && _lines && !_credit.text.length) [self creditTo:SGLyricsCreditFor(track)];+ if (!_sample && _lines && !_creditSource) [self creditTo:SGLyricsCreditFor(track)];if (!_tops) return;[self alignFade];if (_plain) {diff --git a/tweak/Sources/Shared/LyricsSources/LyricsHook.x b/tweak/Sources/Shared/LyricsSources/LyricsHook.xindex 24d97e15..a4ebd73f 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsHook.x+++ b/tweak/Sources/Shared/LyricsSources/LyricsHook.x@@ -148,7 +148,9 @@ static NSData *pageBody(SGLyricsResult *chain, NSData *colours) {SGPBString(2, [text isKindOfClass:NSString.class] ? text : @"")]);[lyrics addObject:SGPBBytes(2, line)];}- [lyrics addObject:SGPBString(5, chain.provider.length ? chain.provider : kUnnamedProvider)];+ // The footer names whoever's text this is, which the terms of some sources ask for (SpicyLyrics.m).+ NSString *provider = chain.pageProvider ?: chain.provider;+ [lyrics addObject:SGPBString(5, provider.length ? provider : kUnnamedProvider)];return SGPBSerialize(@[SGPBBytes(1, SGPBSerialize(lyrics)), SGPBBytes(2, colours ?: defaultColours())]);}diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.h b/tweak/Sources/Shared/LyricsSources/LyricsSources.hindex f6917b97..7325bbb7 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.h+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.h@@ -19,10 +19,22 @@// unset or 0 takes whatever translation the source has.#define SGKeyLyricsTranslationLanguage @"spotifyglass.lyricsTranslationLanguage"+// A page a credit names someone on: "Uploader: name" and the address it opens.+@interface SGLyricsLink : NSObject+@property (nonatomic, copy) NSString *title;+@property (nonatomic, copy) NSURL *url;+@end+// What a source answers with, and what the chain merges several of into one.@interface SGLyricsResult : NSObject// What the credit names: the source's name, unless it gave a fuller credit of its own.@property (nonatomic, copy) NSString *provider;+// Who made the lines, linked from the credit; and whether the source's terms ask for the credit to+// show wherever its lines do, Show source or not.+@property (nonatomic, copy) NSArray<SGLyricsLink *> *creditLinks;+@property (nonatomic) BOOL creditRequired;+// The source of the text Spotify's own page shows, when it is not the one the lines came from.+@property (nonatomic, copy) NSString *pageProvider;@property (nonatomic) BOOL synced; // the lines have starts of their own@property (nonatomic) BOOL wordTimed; // the words inside them are timed, not estimated// Every line as Spotify's lyrics page takes it: ♪ over a break and an empty last line where the@@ -92,12 +104,22 @@ extern NSString *const SGLyricsOwnRequestKey;// The name of the source the lines shown for the track came from, nil until they arrive.NSString *SGLyricsCreditFor(NSString *trackID);void SGLyricsSetCredit(NSString *trackID, NSString *name);+// What the walk learned of a credit, by its text: whether it must show, and the links it carries.+// SGLyricsCreditLinks takes the credit or any text holding it, as Spotify's "Lyrics provided by ..."+// does. Main queue.+BOOL SGLyricsCreditRequired(NSString *credit);+NSArray<SGLyricsLink *> *SGLyricsCreditLinks(NSString *text);+// Opens one link at once; two or more as an action sheet held to `from`.+void SGLyricsOpenCreditLinks(NSArray<SGLyricsLink *> *links, UIView *from);// Turns an install's old Musixmatch switches into an order. Called once, before anything reads one.void SGLyricsMigrateLegacyKeys(void);// The requests the sources share; each calls back on the main queue, with nil when it failed.NSURL *SGLyricsURL(NSString *base, NSDictionary<NSString *, NSString *> *query);void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root));+// The same with the reply's status and headers, and the body read whatever the status: an error's+// body says why. response is nil when the request never got an answer.+void SGLyricsGetJSONReply(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root, NSHTTPURLResponse *response));void SGLyricsGetText(NSURL *url, void (^done)(NSString *text));// For the one source that is asked a question rather than sent to an address. body is anything// NSJSONSerialization writes; nothing is sent at all when it is not.@@ -112,6 +134,12 @@ BOOL SGLyricsReplyFailed(NSURLResponse *response, NSError *error);// line's translation and pronunciation added where the head has them; nil when the document holds no// line the page could show.NSArray<SGKaraokeLine *> *SGTTMLLines(NSString *xml);+// The letters and digits of a text alone, lowercased: a pronunciation or a translation equal to its+// line's this way reads the same as the line and is left out.+NSString *SGLyricsBareText(NSString *text);+// A line's pronunciation: timed `words` where the source has them, else `plain` estimated across the+// line's own time; nil when it has neither or reads the same as `of`.+SGKaraokeLine *SGLyricsPronunciation(NSArray<SGKaraokeWord *> *words, NSString *plain, SGKaraokeLine *of);// The languages a translation can be asked for in, as language tags ("en", "es"), the first one ""// for whatever the source has; SGKeyLyricsTranslationLanguage indexes it, so it only ever grows at@@ -155,10 +183,13 @@ BOOL SGLyricsSameArtist(NSString *credited, NSString *artist);// KuGou.m. A download's base64 content as lines, nil when it is not KRC or holds no timed line.NSArray<SGKaraokeLine *> *SGKuGouLines(NSString *content);-// SpicyLyrics.m. Its key in the order; whether the user's own API key is in the Keychain; the-// Lyrics page's row that sets or removes it; and an API response as lines, nil when it has none.+// SpicyLyrics.m. Its key in the order; whether the user's own API key is in the Keychain; what keeps+// it from answering, for its row on the sources page ("Needs a key", why the key was refused), nil+// while nothing does; the Lyrics page's row that sets or removes the key; and an API response as+// lines, nil when it has none.extern NSString *const SGSpicyLyricsKey;BOOL SGSpicyLyricsKeySet(void);+NSString *SGSpicyLyricsStatus(void);@class SGModRow;SGModRow *SGSpicyLyricsKeyRow(void);SGLyricsResult *SGSpicyLyricsResult(id root);diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.m b/tweak/Sources/Shared/LyricsSources/LyricsSources.mindex 29a40edc..7a506bc9 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.m+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.m@@ -13,6 +13,7 @@#import "Shared/LocalFiles/LocalFiles.h"#import "Shared/LocalFiles/LocalLyrics.h"#import "Settings/SGSourcesPage.h"+#import "Settings/SGPageStyle.h"#import "Headers/SPTPlayer.h"#import <stdatomic.h>@@ -25,6 +26,9 @@ static NSString *const kLegacyMusixmatch = @"spotifyglass.musixmatchLyrics";static NSString *const kLegacyAllTracks = @"spotifyglass.musixmatchAllTracks";static NSString *const kLegacyNetEase = @"spotifyglass.neteaseWordTiming";+@implementation SGLyricsLink+@end+@implementation SGLyricsResult@end@@ -68,20 +72,27 @@ static NSMutableURLRequest *requestFor(NSURL *url, NSDictionary<NSString *, NSStreturn request;}-static void send(NSURLRequest *request, void (^done)(NSData *body)) {+// The body whatever the status, and the reply it came with; nil for both when there was none.+static void sendForReply(NSURLRequest *request, void (^done)(NSData *body, NSHTTPURLResponse *response)) {if (!request) {- dispatch_async(dispatch_get_main_queue(), ^{ done(nil); });+ dispatch_async(dispatch_get_main_queue(), ^{ done(nil, nil); });return;}NSURL *url = request.URL;[[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {- NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;+ NSHTTPURLResponse *reply = [response isKindOfClass:NSHTTPURLResponse.class] ? (NSHTTPURLResponse *)response : nil;SGLyricsNoteReply(response, error);- if (error || status >= 400) SGLog(@"lyrics: %@ answered %ld, error %@", url.host, (long)status, error);- dispatch_async(dispatch_get_main_queue(), ^{ done(status >= 400 ? nil : data); });+ if (error || reply.statusCode >= 400) SGLog(@"lyrics: %@ answered %ld, error %@", url.host, (long)reply.statusCode, error);+ dispatch_async(dispatch_get_main_queue(), ^{ done(data, reply); });}] resume];}+static void send(NSURLRequest *request, void (^done)(NSData *body)) {+ sendForReply(request, ^(NSData *body, NSHTTPURLResponse *reply) {+ done(reply.statusCode >= 400 ? nil : body);+ });+}+static id jsonIn(NSData *body) {return body.length ? [NSJSONSerialization JSONObjectWithData:body options:0 error:nil] : nil;}@@ -92,6 +103,12 @@ void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers,});}+void SGLyricsGetJSONReply(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root, NSHTTPURLResponse *response)) {+ sendForReply(requestFor(url, headers), ^(NSData *body, NSHTTPURLResponse *reply) {+ done(jsonIn(body), reply);+ });+}+void SGLyricsGetText(NSURL *url, void (^done)(NSString *text)) {send(requestFor(url, nil), ^(NSData *body) {done(body.length ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil);@@ -306,6 +323,52 @@ static BOOL named(SGLyricsQuery *query) {return query.title.length && query.artist.length;}+// The credits that carry links or must show, by their text, as their sources answered. Main queue.+static NSMutableDictionary<NSString *, SGLyricsResult *> *sg_noted;+static const NSUInteger kNotedCredits = 100;++static void noteCredit(SGLyricsResult *result) {+ if (!result.provider.length || !(result.creditRequired || result.creditLinks.count)) return;+ if (!sg_noted) sg_noted = [NSMutableDictionary dictionary];+ if (sg_noted.count >= kNotedCredits) [sg_noted removeAllObjects];+ sg_noted[result.provider] = result;+}++BOOL SGLyricsCreditRequired(NSString *credit) {+ return credit && sg_noted[credit].creditRequired;+}++NSArray<SGLyricsLink *> *SGLyricsCreditLinks(NSString *text) {+ if (!text.length) return nil;+ SGLyricsResult *exact = sg_noted[text];+ if (exact) return exact.creditLinks;+ // The longest credit the text holds, so "Spicy Lyrics, synced by a" is not read as a shorter one.+ SGLyricsResult *found = nil;+ for (NSString *credit in sg_noted) {+ if ([text containsString:credit] && credit.length > found.provider.length) found = sg_noted[credit];+ }+ return found.creditLinks;+}++void SGLyricsOpenCreditLinks(NSArray<SGLyricsLink *> *links, UIView *from) {+ if (!links.count) return;+ if (links.count == 1) {+ [UIApplication.sharedApplication openURL:links.firstObject.url options:@{} completionHandler:nil];+ return;+ }+ UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];+ for (SGLyricsLink *link in links) {+ NSURL *url = link.url;+ [sheet addAction:[UIAlertAction actionWithTitle:link.title style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil];+ }]];+ }+ [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ sheet.popoverPresentationController.sourceView = from;+ sheet.popoverPresentationController.sourceRect = from.bounds;+ [SGTopController() presentViewController:sheet animated:YES completion:nil];+}+// One walk down the order for one track.@interface SGLyricsWalk : NSObject@property (nonatomic, copy) NSArray<NSString *> *order;@@ -386,6 +449,7 @@ static void step(SGLyricsWalk *walk) {}provider.ask(query, ^(SGLyricsResult *fresh) {learnFrom(query, fresh);+ noteCredit(fresh);if (fresh.instrumental) {SGLog(@"lyrics: %@ is instrumental, by %@", query.trackID, provider.key);merged.instrumental = YES;@@ -402,6 +466,8 @@ static void step(SGLyricsWalk *walk) {merged.texts = fresh.texts;merged.synced = fresh.synced;if (!merged.provider) merged.provider = fresh.provider ?: provider.name;+ // Spotify's page names the source of its own text, which can be another than the lines'.+ merged.pageProvider = fresh.provider ?: provider.name;}step(walk);});@@ -558,7 +624,9 @@ void SGLyricsMigrateLegacyKeys(void) {UIViewController *SGLyricsSourcesPage(void) {NSMutableArray<SGSource *> *all = [NSMutableArray array];for (SGLyricsProvider *provider in SGLyricsAllProviders()) {- [all addObject:[SGSource sourceWithKey:provider.key name:provider.name detail:provider.detail]];+ // The page is made on every open, so a key refused since the last one says so here.+ NSString *detail = [provider.key isEqualToString:SGSpicyLyricsKey] ? SGSpicyLyricsStatus() ?: provider.detail : provider.detail;+ [all addObject:[SGSource sourceWithKey:provider.key name:provider.name detail:detail]];}return SGSourcesPageMake(@"Lyrics sources", @"Asked top to bottom until one has word timing. Sources get only the track, never your account.",all, ^NSArray<NSString *> * { return SGLyricsOrder(); }, ^(NSArray<NSString *> *keys) { SGLyricsSetOrder(keys); });diff --git a/tweak/Sources/Shared/LyricsSources/SGTTML.m b/tweak/Sources/Shared/LyricsSources/SGTTML.mindex b7c5d0ff..603ce22a 100644--- a/tweak/Sources/Shared/LyricsSources/SGTTML.m+++ b/tweak/Sources/Shared/LyricsSources/SGTTML.m@@ -266,7 +266,7 @@ typedef NS_ENUM(NSInteger, SGTTMLPart) {// The letters and digits alone, lowercased: a pronunciation or a translation that reads the same as its// line is the line again, as an English line of a Japanese song is spelt out as itself.-static NSString *bareText(NSString *text) {+NSString *SGLyricsBareText(NSString *text) {NSMutableString *bare = [NSMutableString string];NSCharacterSet *kept = NSCharacterSet.alphanumericCharacterSet;NSString *lower = text.lowercaseString;@@ -300,7 +300,7 @@ static NSString *pronunciationLanguage(NSArray<NSString *> *languages) {return languages.firstObject;}-static SGKaraokeLine *spoken(NSArray<SGKaraokeWord *> *words, NSString *plain, SGKaraokeLine *of) {+SGKaraokeLine *SGLyricsPronunciation(NSArray<SGKaraokeWord *> *words, NSString *plain, SGKaraokeLine *of) {NSString *said = words.count ? nil : plain;SGKaraokeLine *line = nil;if (words.count) {@@ -310,7 +310,7 @@ static SGKaraokeLine *spoken(NSArray<SGKaraokeWord *> *words, NSString *plain, S// Spelt out without spans: its words are estimated across the time of the line they spell.line = [SGKaraokeEstimatedLines(@[@(of.start), @(MAX(of.end, of.start))], @[said, @""]) firstObject];}- if (!line || [bareText(SGKaraokeLineText(line)) isEqualToString:bareText(SGKaraokeLineText(of))]) return nil;+ if (!line || [SGLyricsBareText(SGKaraokeLineText(line)) isEqualToString:SGLyricsBareText(SGKaraokeLineText(of))]) return nil;line.start = of.start;line.end = MAX(of.end, line.words.lastObject.end);line.align = of.align;@@ -329,11 +329,11 @@ static void addHead(SGTTMLReader *reader) {NSString *translation = translations[key].plain;NSString *said = SGKaraokeLineText(line);if (line.backing) said = [said stringByAppendingFormat:@" %@", SGKaraokeLineText(line.backing)];- if (translation.length && ![bareText(translation) isEqualToString:bareText(said)]) line.translation = translation;+ if (translation.length && ![SGLyricsBareText(translation) isEqualToString:SGLyricsBareText(said)]) line.translation = translation;SGTTMLText *pronunciation = pronunciations[key];if (!pronunciation) return;- line.pronunciation = spoken(pronunciation.words, pronunciation.plain, line);- if (line.backing && pronunciation.backingWords.count) line.backing.pronunciation = spoken(pronunciation.backingWords, nil, line.backing);+ line.pronunciation = SGLyricsPronunciation(pronunciation.words, pronunciation.plain, line);+ if (line.backing && pronunciation.backingWords.count) line.backing.pronunciation = SGLyricsPronunciation(pronunciation.backingWords, nil, line.backing);}];}diff --git a/tweak/Sources/Shared/LyricsSources/SpicyLyrics.m b/tweak/Sources/Shared/LyricsSources/SpicyLyrics.mindex 2f45ea4a..07205d07 100644--- a/tweak/Sources/Shared/LyricsSources/SpicyLyrics.m+++ b/tweak/Sources/Shared/LyricsSources/SpicyLyrics.m@@ -5,8 +5,12 @@// carries it; without one the source answers nothing.//// The API's terms ask for the provider to be named wherever its lyrics show, and for a community-// sync's maker and uploader to be credited with it; the credit says so, and reads where every-// source's does, under Show source.+// sync's maker and uploader to be credited and linked with it: the credit is marked required, so it+// shows under the lyrics whether Show source is on or not, and a tap on it opens their pages.+//+// An app ships its key to every user, so it takes a publishable key (sl_pk_) with the No origin header+// entry allowed, as the API's docs ask; a secret key is for a server. Answers and misses are kept per+// track for the session, a rate limit is waited out, and a refused key is not tried again for a while.#import <Security/Security.h>#import "Core/SGCore.h"#import "Settings/SGModPage.h"@@ -14,6 +18,15 @@#import "LyricsSources.h"static NSString *const kAPI = @"https://api.spicylyrics.org/v1/lyrics/";+static NSString *const kDashboard = @"https://developers.spicylyrics.org/dashboard";+#ifndef SG_VERSION+#define SG_VERSION "dev"+#endif+static NSString *const kAgent = @"Vitrine/" SG_VERSION " (Spotify for iOS lyrics, by track id)";+// A reply for this many tracks is kept; a rate limit is waited out for at most an hour, 60 s when the+// reply does not say; a refused key is tried again after ten minutes.+static const NSUInteger kKeptTracks = 100;+static const NSTimeInterval kMostWait = 3600, kDefaultWait = 60, kRefusedWait = 600;static NSString *const kService = @"Vitrine.SpicyLyrics", *const kAccount = @"api-key";NSString *const SGSpicyLyricsKey = @"spicylyrics";@@ -59,25 +72,19 @@ static NSString *stringIn(NSDictionary *object, NSString *name) {return [value isKindOfClass:NSString.class] && [value length] ? value : nil;}-// The API does not say what language a TranslatedText is in, so it is taken only while the Lyrics page-// asks for any. With a language chosen, the line is left without one for Musixmatch or Gemini to fill-// in that language, as an Apple Music translation in another language is left out (SGTTML.m).-static NSString *translationIn(NSDictionary *object) {- return SGLyricsTranslationLanguage() ? nil : stringIn(object, @"TranslatedText");-}-static NSArray *arrayIn(NSDictionary *object, NSString *name) {id value = [object isKindOfClass:NSDictionary.class] ? object[name] : nil;return [value isKindOfClass:NSArray.class] ? value : @[];}-// A Lead or Background: its syllables as words. IsPartOfWord says a syllable runs on into the next-// one, so the next is laid flush against it.-static SGKaraokeLine *syllableLine(NSDictionary *part) {+// A Lead or Background: its syllables as words, read from `field` (Text, or TransliteratedText for+// how they sound). IsPartOfWord says a syllable runs on into the next one, so the next is laid flush+// against it. The line is timed by the part's own start and end where it has them.+static SGKaraokeLine *syllableLine(NSDictionary *part, NSString *field) {NSMutableArray<SGKaraokeWord *> *words = [NSMutableArray array];BOOL runsOn = NO;for (NSDictionary *syllable in arrayIn(part, @"Syllables")) {- NSString *text = [stringIn(syllable, @"Text") stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ NSString *text = [stringIn(syllable, field) stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];if (!text.length) continue;SGKaraokeWord *word = [SGKaraokeWord new];word.text = text;@@ -90,23 +97,52 @@ static SGKaraokeLine *syllableLine(NSDictionary *part) {if (!words.count) return nil;SGKaraokeLine *line = [SGKaraokeLine new];line.words = words;- line.start = words.firstObject.start;- line.end = MAX(words.lastObject.end, line.start);- line.translation = translationIn(part);+ line.start = part[@"StartTime"] ? ms(part[@"StartTime"]) : words.firstObject.start;+ line.end = MAX(part[@"EndTime"] ? ms(part[@"EndTime"]) : words.lastObject.end, line.start);return line;}+// How the part sounds: its syllables' own spellings, timed with them, else the part's spelling+// estimated across the line.+static SGKaraokeLine *spokenLine(NSDictionary *part, NSString *spelt, SGKaraokeLine *line) {+ return SGLyricsPronunciation(syllableLine(part, @"TransliteratedText").words, spelt, line);+}++// The translation of the line and its backing, unless it reads the same as them. The API does not say+// what language a TranslatedText is in, so it is taken only while the Lyrics page asks for any. With a+// language chosen, the line is left without one for Musixmatch or Gemini to fill in that language, as an+// Apple Music translation in another language is left out (SGTTML.m).+static NSString *translationOf(NSString *translation, SGKaraokeLine *line) {+ if (!translation.length || SGLyricsTranslationLanguage()) return nil;+ NSString *said = SGKaraokeLineText(line);+ if (line.backing) said = [said stringByAppendingFormat:@" %@", SGKaraokeLineText(line.backing)];+ return [SGLyricsBareText(translation) isEqualToString:SGLyricsBareText(said)] ? nil : translation;+}+static NSArray<SGKaraokeLine *> *syllableLines(NSArray *content) {NSMutableArray<SGKaraokeLine *> *lines = [NSMutableArray array];for (NSDictionary *item in content) {if (![item isKindOfClass:NSDictionary.class]) continue;- SGKaraokeLine *line = syllableLine(item[@"Lead"]);+ NSDictionary *lead = item[@"Lead"];+ SGKaraokeLine *line = syllableLine(lead, @"Text");if (!line) continue;line.align = [item[@"OppositeAligned"] boolValue] ? SGKaraokeAlignTrailing : SGKaraokeAlignLeading;- // A line can have several background phrases; the view has one backing line, so they share it.+ // A line can have several background phrases; the view has one backing line, so they share it,+ // and their translations join the lead's.NSMutableArray *backing = [NSMutableArray array];- for (NSDictionary *group in arrayIn(item, @"Background")) [backing addObjectsFromArray:arrayIn(group, @"Syllables")];- line.backing = syllableLine(@{@"Syllables": backing});+ NSMutableArray<NSString *> *spelt = [NSMutableArray array], *translated = [NSMutableArray array];+ if (stringIn(lead, @"TranslatedText")) [translated addObject:stringIn(lead, @"TranslatedText")];+ for (NSDictionary *group in arrayIn(item, @"Background")) {+ [backing addObjectsFromArray:arrayIn(group, @"Syllables")];+ if (stringIn(group, @"TransliteratedText")) [spelt addObject:stringIn(group, @"TransliteratedText")];+ if (stringIn(group, @"TranslatedText")) [translated addObject:stringIn(group, @"TranslatedText")];+ }+ NSDictionary *background = @{@"Syllables": backing};+ line.backing = syllableLine(background, @"Text");+ line.backing.align = line.align;+ line.pronunciation = spokenLine(lead, stringIn(lead, @"TransliteratedText"), line);+ if (line.backing) line.backing.pronunciation = spokenLine(background, [spelt componentsJoinedByString:@" "], line.backing);+ line.translation = translationOf([translated componentsJoinedByString:@" "], line);[lines addObject:line];}return lines.count ? lines : nil;@@ -139,29 +175,59 @@ static NSArray<SGKaraokeLine *> *lineLines(NSArray *content) {// Breaks were left out of kept, so the lines and kept pair up one to one.for (NSUInteger i = 0; i < lines.count && i < kept.count; i++) {if ([kept[i][@"OppositeAligned"] boolValue]) lines[i].align = SGKaraokeAlignTrailing;- lines[i].translation = translationIn(kept[i]);+ lines[i].pronunciation = SGLyricsPronunciation(nil, stringIn(kept[i], @"TransliteratedText"), lines[i]);+ lines[i].translation = translationOf(stringIn(kept[i], @"TranslatedText"), lines[i]);}return lines;}-static NSArray<SGKaraokeLine *> *staticLines(NSArray *rows) {- NSMutableArray<NSString *> *texts = [NSMutableArray array];+// The lines, each with its translation, and the text for Spotify's page: an empty row between two+// lines is a ♪ there, as a stanza break.+static NSArray<SGKaraokeLine *> *staticLines(NSArray *rows, NSArray<NSString *> **pageTexts) {+ NSMutableArray<NSString *> *texts = [NSMutableArray array], *page = [NSMutableArray array];+ NSMutableArray<NSDictionary *> *kept = [NSMutableArray array];for (NSDictionary *row in rows) {NSString *text = stringIn(row, @"Text");- if (text) [texts addObject:text];+ if (isBreak(text)) {+ if (page.count && ![page.lastObject isEqualToString:@"♪"]) [page addObject:@"♪"];+ continue;+ }+ [texts addObject:text];+ [page addObject:text];+ [kept addObject:row];}- return SGKaraokeStaticLines(texts);+ if ([page.lastObject isEqualToString:@"♪"]) [page removeLastObject];+ *pageTexts = page;+ NSArray<SGKaraokeLine *> *lines = SGKaraokeStaticLines(texts);+ for (NSUInteger i = 0; i < lines.count && i < kept.count; i++) lines[i].translation = translationOf(stringIn(kept[i], @"TranslatedText"), lines[i]);+ return lines;}-// What the credit reads. A community sync names the people who made it; a catalogue's is named as-// the provider it is, reached through Spicy Lyrics.-static NSString *creditFor(NSDictionary *body) {+// What the credit reads, and the pages it links to. A community sync names the people who made it,+// each linked where the API gives an address; a catalogue's is named as the provider it is, reached+// through Spicy Lyrics.+static NSString *creditFor(NSDictionary *body, NSArray<SGLyricsLink *> **links) {+ *links = nil;NSString *source = stringIn(body, @"source");if ([source isEqualToString:@"apple_music"]) return @"Apple Music via Spicy Lyrics";if ([source isEqualToString:@"spotify"]) return @"Spotify via Spicy Lyrics";- NSDictionary *people = body[@"UploadAttribution"];- NSString *maker = stringIn([people isKindOfClass:NSDictionary.class] ? people[@"Maker"] : nil, @"username");- NSString *uploader = stringIn([people isKindOfClass:NSDictionary.class] ? people[@"Uploader"] : nil, @"username");+ if (![source isEqualToString:@"spicy_lyrics"]) return @"Spicy Lyrics, source unknown";+ NSDictionary *people = [body[@"UploadAttribution"] isKindOfClass:NSDictionary.class] ? body[@"UploadAttribution"] : nil;+ NSDictionary *makerInfo = people[@"Maker"], *uploaderInfo = people[@"Uploader"];+ NSString *maker = stringIn(makerInfo, @"username"), *uploader = stringIn(uploaderInfo, @"username");+ NSMutableArray<SGLyricsLink *> *found = [NSMutableArray array];+ for (NSArray *person in @[@[@"Uploader", uploaderInfo ?: @{}], @[@"Maker", makerInfo ?: @{}]]) {+ NSString *name = stringIn(person[1], @"username");+ NSURL *url = [NSURL URLWithString:stringIn(person[1], @"url") ?: @""];+ NSString *scheme = url.scheme.lowercaseString;+ if (!name || !url.host.length || !([scheme isEqualToString:@"https"] || [scheme isEqualToString:@"http"])) continue;+ if ([[found valueForKey:@"url"] containsObject:url]) continue; // one person both made and uploaded it+ SGLyricsLink *link = [SGLyricsLink new];+ link.title = [NSString stringWithFormat:@"%@: %@", person[0], name];+ link.url = url;+ [found addObject:link];+ }+ *links = found.count ? found : nil;if (maker && uploader && ![maker isEqualToString:uploader]) {return [NSString stringWithFormat:@"Spicy Lyrics, synced by %@, uploaded by %@", maker, uploader];}@@ -173,13 +239,17 @@ SGLyricsResult *SGSpicyLyricsResult(id root) {NSDictionary *body = [root isKindOfClass:NSDictionary.class] ? root[@"Body"] : nil;if (![body isKindOfClass:NSDictionary.class]) return nil;NSString *type = stringIn(body, @"Type");+ NSArray<NSString *> *pageTexts = nil;NSArray<SGKaraokeLine *> *lines = [type isEqualToString:@"Syllable"] ? syllableLines(arrayIn(body, @"Content")): [type isEqualToString:@"Line"] ? lineLines(arrayIn(body, @"Content"))- : [type isEqualToString:@"Static"] ? staticLines(arrayIn(body, @"Lines"))+ : [type isEqualToString:@"Static"] ? staticLines(arrayIn(body, @"Lines"), &pageTexts): nil;- if (!lines) return nil;+ if (!lines.count) return nil;SGLyricsResult *result = [SGLyricsResult new];- result.provider = creditFor(body);+ NSArray<SGLyricsLink *> *links;+ result.provider = creditFor(body, &links);+ result.creditLinks = links;+ result.creditRequired = YES;result.karaokeLines = lines;result.wordTimed = SGKaraokeLinesTiming(lines) == SGKaraokeTimingWords;result.synced = SGKaraokeLinesTiming(lines) != SGKaraokeTimingNone;@@ -195,7 +265,11 @@ SGLyricsResult *SGSpicyLyricsResult(id root) {[plain addObject:SGKaraokeLineText(line)];}starts = zeros;- texts = plain;+ texts = pageTexts ?: plain;+ if (pageTexts) {+ [zeros removeAllObjects];+ for (NSUInteger i = 0; i < pageTexts.count; i++) [zeros addObject:@0];+ }}result.starts = starts;result.texts = texts;@@ -204,49 +278,195 @@ SGLyricsResult *SGSpicyLyricsResult(id root) {#pragma mark - asking-SGLyricsAsk SGSpicyLyricsAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {- NSString *key = storedKey();- // The API takes Spotify's 22 character base62 id and nothing else.- if (!key || query.trackID.length != 22) {+// Main queue only, as the walk asks and the reply calls back there.+static NSMutableDictionary<NSString *, id> *sg_answers; // a result, or NSNull for "none"+static NSTimeInterval sg_waitUntil; // a rate limit's end, by the system's uptime+static NSString *sg_refused; // the error code of the last 401 or 403, "" when it gave none+static NSTimeInterval sg_refusedUntil;++static NSTimeInterval uptime(void) {+ return NSProcessInfo.processInfo.systemUptime;+}++// Spotify's 22 character base62 id, the only thing the API takes.+static BOOL isTrackID(NSString *trackID) {+ if (trackID.length != 22) return NO;+ NSCharacterSet *base62 = [NSCharacterSet characterSetWithCharactersInString:+ @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];+ return [trackID rangeOfCharacterFromSet:base62.invertedSet].location == NSNotFound;+}++// A header's wait in seconds: a number of seconds, a Unix time (a RateLimit-Reset some servers send),+// or an HTTP date; 0 when it says none.+static NSTimeInterval secondsIn(NSString *value, NSDate *now) {+ value = [value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ if (!value.length) return 0;+ if ([value rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789."].invertedSet].location == NSNotFound) {+ double seconds = value.doubleValue;+ return seconds > 1e9 ? seconds - now.timeIntervalSince1970 : seconds;+ }+ NSDateFormatter *format = [NSDateFormatter new];+ format.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];+ format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];+ format.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss zzz";+ NSDate *date = [format dateFromString:value];+ return date ? [date timeIntervalSinceDate:now] : 0;+}++// How long to leave the API alone after this reply: a 429 or 503 for its Retry-After, else its+// RateLimit-Reset, else a minute; any reply with no requests left until its RateLimit-Reset. Never more+// than an hour.+NSTimeInterval SGSpicyLyricsWait(NSHTTPURLResponse *reply, NSDate *now);+NSTimeInterval SGSpicyLyricsWait(NSHTTPURLResponse *reply, NSDate *now) {+ NSString *reset = [reply valueForHTTPHeaderField:@"RateLimit-Reset"];+ NSTimeInterval wait = 0;+ if (reply.statusCode == 429 || reply.statusCode == 503) {+ wait = secondsIn([reply valueForHTTPHeaderField:@"Retry-After"], now);+ if (wait <= 0) wait = secondsIn(reset, now);+ if (wait <= 0) wait = kDefaultWait;+ } else {+ NSString *left = [[reply valueForHTTPHeaderField:@"RateLimit-Remaining"] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ if ([left isEqualToString:@"0"]) wait = secondsIn(reset, now);+ }+ return MIN(MAX(wait, 0), kMostWait);+}++// What a refusal's error code means, short enough for the source's row.+static NSString *refusalReason(NSString *code) {+ if ([code isEqualToString:@"origin_not_allowed"] || [code isEqualToString:@"origins_not_configured"]) return @"Key rejected: allow No origin header";+ if ([code isEqualToString:@"application_paused"]) return @"Key rejected: paused";+ if ([code isEqualToString:@"key_revoked"]) return @"Key rejected: revoked";+ if ([code isEqualToString:@"key_not_found"] || [code isEqualToString:@"key_malformed"] || [code isEqualToString:@"malformed_authorization"]) return @"Key rejected: not found";+ for (NSString *word in @[@"suspended", @"disabled", @"deleted"]) {+ if ([code containsString:word]) return @"Key rejected: disabled";+ }+ return @"Key rejected";+}++NSString *SGSpicyLyricsStatus(void) {+ if (!SGSpicyLyricsKeySet()) return @"Needs a key";+ return sg_refused ? refusalReason(sg_refused) : nil;+}++static NSString *errorCodeIn(id root) {+ NSDictionary *body = [root isKindOfClass:NSDictionary.class] ? root[@"Body"] : nil;+ return stringIn(body, @"error") ?: stringIn(root, @"error");+}++static void keepAnswer(NSString *trackID, id answer) {+ if (!sg_answers) sg_answers = [NSMutableDictionary dictionary];+ if (sg_answers.count >= kKeptTracks) [sg_answers removeAllObjects];+ sg_answers[trackID] = answer;+}++// The ask with the key passed in, which harness/spicy-lyrics/ drives without a Keychain.+void SGSpicyLyricsAskWith(NSString *key, SGLyricsQuery *query, void (^done)(SGLyricsResult *result));+void SGSpicyLyricsAskWith(NSString *key, SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {+ NSString *trackID = query.trackID;+ if (!key.length || !isTrackID(trackID)) {done(nil);return;}- NSURL *url = [NSURL URLWithString:[kAPI stringByAppendingString:query.trackID]];- SGLyricsGetJSON(url, @{@"Authorization": [@"Bearer " stringByAppendingString:key]}, ^(id root) {- SGLyricsResult *result = SGSpicyLyricsResult(root);- SGLog(@"spicy lyrics: %@ %@", query.trackID, result+ id kept = sg_answers[trackID];+ if (kept) {+ done(kept == NSNull.null ? nil : kept);+ return;+ }+ NSTimeInterval now = uptime();+ if (sg_refused && now < sg_refusedUntil) {+ done(nil);+ return;+ }+ if (now < sg_waitUntil) {+ // Lost rather than "no lyrics", so the walk is not kept and asks again once the wait is over.+ SGLog(@"spicy lyrics: %@ skipped, rate limited for %.0fs more", trackID, sg_waitUntil - now);+ SGLyricsNoteReply(nil, [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotConnectToHost userInfo:nil]);+ done(nil);+ return;+ }+ NSURL *url = [NSURL URLWithString:[kAPI stringByAppendingString:trackID]];+ NSDictionary *headers = @{@"Authorization": [@"Bearer " stringByAppendingString:key], @"Accept": @"application/json", @"User-Agent": kAgent};+ SGLyricsGetJSONReply(url, headers, ^(id root, NSHTTPURLResponse *reply) {+ NSInteger status = reply.statusCode;+ NSTimeInterval wait = SGSpicyLyricsWait(reply, NSDate.date);+ if (wait > 0) {+ sg_waitUntil = uptime() + wait;+ SGLog(@"spicy lyrics: rate limited (%ld), leaving it alone for %.0fs", (long)status, wait);+ }+ if (status == 401 || status == 403) {+ sg_refused = errorCodeIn(root) ?: @"";+ sg_refusedUntil = uptime() + kRefusedWait;+ SGLog(@"spicy lyrics: the key was refused (%ld, %@), not asking for %.0fs", (long)status, sg_refused, kRefusedWait);+ done(nil);+ return;+ }+ if (status == 200 || status == 404) sg_refused = nil;+ SGLyricsResult *result = status == 200 ? SGSpicyLyricsResult(root) : nil;+ if (status == 200 || status == 404 || status == 400) keepAnswer(trackID, result ?: NSNull.null);+ SGLog(@"spicy lyrics: %@ %@", trackID, result? [NSString stringWithFormat:@"has %lu %@ lines, credited to %@", (unsigned long)result.karaokeLines.count,result.wordTimed ? @"word timed" : result.synced ? @"line timed" : @"untimed", result.provider]- : @"has nothing");+ : [NSString stringWithFormat:@"has nothing (%ld)", (long)status]);done(result);});+}++SGLyricsAsk SGSpicyLyricsAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {+ SGSpicyLyricsAskWith(storedKey(), query, done);};#pragma mark - the row+// What is wrong with a pasted key, nil when it looks like a publishable one: sl_pk_, then printable+// ASCII, 12 characters at the least.+NSString *SGSpicyLyricsKeyProblem(NSString *key);+NSString *SGSpicyLyricsKeyProblem(NSString *key) {+ if ([key hasPrefix:@"sl_sk_"]) return @"That is a secret key, which belongs on a server, not in an app.";+ NSCharacterSet *printable = [NSCharacterSet characterSetWithRange:NSMakeRange(0x21, 0x7E - 0x21 + 1)];+ if (![key hasPrefix:@"sl_pk_"] || key.length < 12 || [key rangeOfCharacterFromSet:printable.invertedSet].location != NSNotFound) {+ return @"That is not a publishable key.";+ }+ return nil;+}+// A key saved puts the source at the top of the order, since it was set to be used; a key removed-// takes it out, as it can answer nothing without one.+// takes it out, as it can answer nothing without one. Either way a refusal of the old key is forgotten.static void setKey(NSString *key) {storeKey(key);+ sg_refused = nil;+ sg_refusedUntil = 0;NSMutableArray<NSString *> *order = [SGLyricsOrder() mutableCopy];[order removeObject:SGSpicyLyricsKey];if (key.length) [order insertObject:SGSpicyLyricsKey atIndex:0];SGLyricsSetOrder(order);}-static void askForKey(void) {- UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Spicy Lyrics key"- message:@"Create an application at developers.spicylyrics.org and paste its secret key (sl_sk_). A publishable key does not work from an app. The key stays on this iPhone."+static void askForKey(NSString *problem) {+ NSString *how = @"Sign up at Spicy Lyrics for Developers, create an application, turn on client access with "+ @"No origin header allowed, and paste its publishable key (sl_pk_). The key stays on this iPhone.";+ NSString *refused = SGSpicyLyricsKeySet() ? SGSpicyLyricsStatus() : nil;+ NSString *lead = problem ?: refused ? [refused stringByAppendingString:@"."] : nil;+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Spicy Lyrics Key"+ message:lead ? [NSString stringWithFormat:@"%@\n\n%@", lead, how] : howpreferredStyle:UIAlertControllerStyleAlert];[alert addTextFieldWithConfigurationHandler:^(UITextField *field) {- field.placeholder = @"sl_sk_...";- field.secureTextEntry = YES;+ field.placeholder = @"sl_pk_...";+ field.keyboardType = UIKeyboardTypeASCIICapable;field.autocorrectionType = UITextAutocorrectionTypeNo;field.autocapitalizationType = UITextAutocapitalizationTypeNone;+ field.spellCheckingType = UITextSpellCheckingTypeNo;}];- [alert addAction:[UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ UIAlertAction *save = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {NSString *key = [alert.textFields.firstObject.text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];- if (key.length) setKey(key);+ if (!key.length) return;+ NSString *wrong = SGSpicyLyricsKeyProblem(key);+ // Asked again, saying what was wrong, rather than kept and failing on every track.+ if (wrong) dispatch_async(dispatch_get_main_queue(), ^{ askForKey(wrong); });+ else setKey(key);+ }];+ [alert addAction:save];+ [alert addAction:[UIAlertAction actionWithTitle:@"Open Dashboard" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ [UIApplication.sharedApplication openURL:[NSURL URLWithString:kDashboard] options:@{} completionHandler:nil];}]];if (SGSpicyLyricsKeySet()) {[alert addAction:[UIAlertAction actionWithTitle:@"Remove" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {@@ -254,10 +474,11 @@ static void askForKey(void) {}]];}[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ alert.preferredAction = save;[SGTopController() presentViewController:alert animated:YES completion:nil];}SGModRow *SGSpicyLyricsKeyRow(void) {return SGStatActionRow(@"Spicy Lyrics key", @"Community word syncs, with your own key",- ^NSString *{ return SGSpicyLyricsKeySet() ? @"Set" : @"Off"; }, ^{ askForKey(); });+ ^NSString *{ return !SGSpicyLyricsKeySet() ? @"Off" : sg_refused ? @"Rejected" : @"Set"; }, ^{ askForKey(nil); });}