Skip to content

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 returns timed lines and translations with your own key

My-Name-Is-Jeff6bd497dfa5b6
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 2965ce0c..b409f21a 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -85,7 +85,9 @@ Shared:
backing vocals, and in its head Apple's translation and its pronunciation of a line, the pronunciation
timed word by word (the translation taken in the Lyrics page's language); Musixmatch.m, matched by
Spotify'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 and
- keyless and timed by the line, the floor under the rest. color-lyrics is answered with whichever won
+ keyless 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/. 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
its request sent to a donor track that does, so the reply is a real 200 (a 404 answered as a 200 in the
delegate alone never showed the card on 9.1.78); a 404 for a track not seen yet is held until the chain
diff --git a/harness/spicy-lyrics/README.md b/harness/spicy-lyrics/README.md
new file mode 100644
index 00000000..c7a4c254
--- /dev/null
+++ b/harness/spicy-lyrics/README.md
@@ -0,0 +1,9 @@
+# Spicy Lyrics check
+
+`./build.sh` reads made-up responses of the Spicy Lyrics API (a Syllable sync with a duet, a
+backing 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
+Mac 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.
diff --git a/harness/spicy-lyrics/build.sh b/harness/spicy-lyrics/build.sh
new file mode 100755
index 00000000..d67a2fbf
--- /dev/null
+++ b/harness/spicy-lyrics/build.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# build.sh: builds check.m against this checkout's SpicyLyrics.m as a Mac Catalyst binary and runs it,
+# so no simulator is needed.
+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/SpicyLyrics.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/Lyrics/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.m
new file mode 100644
index 00000000..24ab7801
--- /dev/null
+++ b/harness/spicy-lyrics/check.m
@@ -0,0 +1,82 @@
+// Reads made-up Spicy Lyrics API responses through the real SGSpicyLyricsResult and checks the lines
+// and the credit. The responses follow the shapes in developers.spicylyrics.org's Get Lyrics reference;
+// the words are filler. Exits non-zero on the first wrong answer.
+#import <UIKit/UIKit.h>
+#import "Shared/LyricsSources/LyricsSources.h"
+
+// What SpicyLyrics.m reaches outside the parser for; none of it but the result class is used here.
+@implementation SGLyricsResult
+@end
+void 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); }
+NSArray<NSString *> *SGLyricsOrder(void) { return @[]; }
+void SGLyricsSetOrder(NSArray<NSString *> *keys) {}
+SGModRow *SGStatActionRow(NSString *t, NSString *s, NSString *(^v)(void), void (^a)(void)) { return nil; }
+UIViewController *SGTopController(void) { return nil; }
+static NSString *sg_language; // the Lyrics page's translation language, nil for Any
+NSString *SGLyricsTranslationLanguage(void) { return sg_language; }
+
+#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "FAILED line %d: %s\n", __LINE__, #cond); exit(1); } } while (0)
+
+static SGLyricsResult *parse(NSString *json) {
+ return SGSpicyLyricsResult([NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]);
+}
+
+int main(void) {
+ @autoreleasepool {
+ SGLyricsResult *syllable = parse(@"{\"Body\":{\"Type\":\"Syllable\",\"source\":\"spicy_lyrics\",\"StartTime\":1.5,\"EndTime\":9,"
+ "\"UploadAttribution\":{\"Uploader\":{\"username\":\"up\"},\"Maker\":{\"username\":\"mk\"}},"
+ "\"Content\":["
+ "{\"Type\":\"Vocal\",\"OppositeAligned\":false,\"Lead\":{\"StartTime\":1.5,\"EndTime\":3,\"TranslatedText\":\"tr\",\"Syllables\":["
+ "{\"Text\":\"Ev\",\"StartTime\":1.5,\"EndTime\":1.8,\"IsPartOfWord\":true},"
+ "{\"Text\":\"ery\",\"StartTime\":1.8,\"EndTime\":2.2,\"IsPartOfWord\":false},"
+ "{\"Text\":\"day\",\"StartTime\":2.2,\"EndTime\":3,\"IsPartOfWord\":false}]},"
+ "\"Background\":[{\"StartTime\":2.5,\"EndTime\":3.5,\"Syllables\":[{\"Text\":\"(oh)\",\"StartTime\":2.5,\"EndTime\":3.5}]},"
+ "{\"StartTime\":3.6,\"EndTime\":3.9,\"Syllables\":[{\"Text\":\"(yeah)\",\"StartTime\":3.6,\"EndTime\":3.9}]}]},"
+ "{\"Type\":\"Vocal\",\"OppositeAligned\":true,\"Lead\":{\"StartTime\":4,\"EndTime\":9,\"Syllables\":["
+ "{\"Text\":\"two\",\"StartTime\":4,\"EndTime\":9}]}}]},\"Status\":200,\"Type\":\"object\"}");
+ CHECK(syllable.karaokeLines.count == 2);
+ CHECK(syllable.wordTimed && syllable.synced);
+ SGKaraokeLine *first = syllable.karaokeLines[0];
+ CHECK([SGKaraokeLineText(first) isEqualToString:@"Every day"]);
+ CHECK(first.words[0].start == 1500 && first.words[1].end == 2200);
+ CHECK(first.words[1].joined && !first.words[2].joined);
+ CHECK(first.start == 1500 && first.end == 3000);
+ CHECK([first.translation isEqualToString:@"tr"]);
+ 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"]);
+
+ SGLyricsResult *line = parse(@"{\"Body\":{\"Type\":\"Line\",\"source\":\"spotify\",\"Content\":["
+ "{\"Type\":\"Vocal\",\"Text\":\"one line\",\"StartTime\":10.81,\"EndTime\":12,\"OppositeAligned\":false},"
+ "{\"Type\":\"Vocal\",\"Text\":\"\",\"StartTime\":12,\"EndTime\":20},"
+ "{\"Type\":\"Vocal\",\"Text\":\"two line\",\"StartTime\":20,\"EndTime\":23,\"OppositeAligned\":true,\"TranslatedText\":\"zwei\"}]}}");
+ CHECK(line.karaokeLines.count == 2);
+ CHECK(line.synced && !line.wordTimed);
+ CHECK(line.karaokeLines[0].start == 10810 && line.karaokeLines[0].end <= 12000);
+ 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"]);
+
+ // With a language chosen, a translation the API names no language for is left out of both syncs.
+ sg_language = @"es";
+ CHECK(!parse(@"{\"Body\":{\"Type\":\"Line\",\"Content\":[{\"Text\":\"two line\",\"StartTime\":20,\"EndTime\":23,"
+ "\"TranslatedText\":\"zwei\"}]}}").karaokeLines[0].translation);
+ CHECK(!parse(@"{\"Body\":{\"Type\":\"Syllable\",\"Content\":[{\"Lead\":{\"TranslatedText\":\"tr\",\"Syllables\":["
+ "{\"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\"}]}}");
+ CHECK(plain.karaokeLines.count == 2 && !plain.synced);
+ CHECK([plain.texts isEqualToArray:(@[@"a b", @"c"])] && [plain.starts isEqualToArray:(@[@0, @0])]);
+ CHECK([plain.provider isEqualToString:@"Apple Music via Spicy Lyrics"]);
+
+ CHECK(!parse(@"{\"Body\":{\"Type\":\"Syllable\",\"Content\":[]}}"));
+ CHECK(!parse(@"{\"error\":\"not found\"}"));
+ puts("spicy lyrics: all checks passed");
+ }
+ return 0;
+}
diff --git a/tweak/Sources/Shared/Lyrics/LyricsSettings.m b/tweak/Sources/Shared/Lyrics/LyricsSettings.m
index aac07160..cd7b66e9 100644
--- a/tweak/Sources/Shared/Lyrics/LyricsSettings.m
+++ b/tweak/Sources/Shared/Lyrics/LyricsSettings.m
@@ -13,7 +13,7 @@ SGModSection *SGLyricsSourcesSection(BOOL namingSource) {
return names.count ? [names componentsJoinedByString:@", "] : @"Off";
};
NSMutableArray<SGModRow *> *rows = [NSMutableArray arrayWithObjects:sources,
- SGOptionRow(@"Lyrics for every track", @"Even where Spotify has none", SGKeyLyricsAllTracks), nil];
+ SGOptionRow(@"Lyrics for every track", @"Even where Spotify has none", SGKeyLyricsAllTracks), SGSpicyLyricsKeyRow(), nil];
if (namingSource) [rows addObject:SGOptionRow(@"Show source", nil, SGKeyLyricsCredit)];
return SGSection(@"Sources", rows);
}
diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.h b/tweak/Sources/Shared/LyricsSources/LyricsSources.h
index bdc5b676..5cb0ac28 100644
--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.h
+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.h
@@ -21,7 +21,8 @@
// What a source answers with, and what the chain merges several of into one.
@interface SGLyricsResult : NSObject
-@property (nonatomic, copy) NSString *provider; // the key of the source the lines came from
+// What the credit names: the source's name, unless it gave a fuller credit of its own.
+@property (nonatomic, copy) NSString *provider;
@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
@@ -127,5 +128,14 @@ extern SGLyricsAsk SGMusixmatchAsk;
extern SGLyricsAsk SGUnisonAsk;
extern SGLyricsAsk SGNetEaseAsk;
extern SGLyricsAsk SGLrcLibAsk;
+extern SGLyricsAsk SGSpicyLyricsAsk;
+
+// 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.
+extern NSString *const SGSpicyLyricsKey;
+BOOL SGSpicyLyricsKeySet(void);
+@class SGModRow;
+SGModRow *SGSpicyLyricsKeyRow(void);
+SGLyricsResult *SGSpicyLyricsResult(id root);
UIViewController *SGLyricsSourcesPage(void); // the ordered list on the Lyrics page
diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.m b/tweak/Sources/Shared/LyricsSources/LyricsSources.m
index aeb4f952..9eb8690c 100644
--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.m
+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.m
@@ -148,7 +148,7 @@ NSArray<SGLyricsProvider *> *SGLyricsAllProviders(void) {
provider.detail = detail;
// A source that matches by Spotify's own track id has everything it needs from the
// start; the rest wait for the player to name the track before they can search.
- provider.needsName = ![key isEqualToString:@"musixmatch"];
+ provider.needsName = ![key isEqualToString:@"musixmatch"] && ![key isEqualToString:SGSpicyLyricsKey];
provider.ask = ask;
return provider;
};
@@ -158,6 +158,7 @@ NSArray<SGLyricsProvider *> *SGLyricsAllProviders(void) {
make(@"unison", @"Unison", @"Hand-timed, few tracks", SGUnisonAsk),
make(@"netease", @"NetEase", @"Word timing, censored", SGNetEaseAsk),
make(@"lrclib", @"LRCLIB", @"Line timing, open fallback", SGLrcLibAsk),
+ make(SGSpicyLyricsKey, @"Spicy Lyrics", @"Community word syncs, your own key", SGSpicyLyricsAsk),
];
});
return all;
@@ -367,13 +368,13 @@ static void step(SGLyricsWalk *walk) {
if (betterLines(merged, fresh)) {
merged.karaokeLines = fresh.karaokeLines;
merged.wordTimed = fresh.wordTimed;
- merged.provider = provider.name;
+ merged.provider = fresh.provider ?: provider.name;
}
if (betterTexts(merged, fresh)) {
merged.starts = fresh.starts;
merged.texts = fresh.texts;
merged.synced = fresh.synced;
- if (!merged.provider) merged.provider = provider.name;
+ if (!merged.provider) merged.provider = fresh.provider ?: provider.name;
}
step(walk);
});
diff --git a/tweak/Sources/Shared/LyricsSources/SpicyLyrics.m b/tweak/Sources/Shared/LyricsSources/SpicyLyrics.m
new file mode 100644
index 00000000..2f45ea4a
--- /dev/null
+++ b/tweak/Sources/Shared/LyricsSources/SpicyLyrics.m
@@ -0,0 +1,263 @@
+// Spicy Lyrics, through its Developer Platform (developers.spicylyrics.org) on the user's own key.
+// One request by Spotify's track id answers with the best sync there is: a community one made by
+// hand, else Apple Music's or Spotify's. Syllable syncs time every syllable and carry duets and
+// backing vocals. The key lives in the Keychain, not in the settings, so a settings export never
+// 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.
+#import <Security/Security.h>
+#import "Core/SGCore.h"
+#import "Settings/SGModPage.h"
+#import "Settings/SGPageStyle.h"
+#import "LyricsSources.h"
+
+static NSString *const kAPI = @"https://api.spicylyrics.org/v1/lyrics/";
+static NSString *const kService = @"Vitrine.SpicyLyrics", *const kAccount = @"api-key";
+NSString *const SGSpicyLyricsKey = @"spicylyrics";
+
+#pragma mark - the key
+
+static NSDictionary *keyQuery(void) {
+ return @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
+ (__bridge id)kSecAttrService: kService, (__bridge id)kSecAttrAccount: kAccount};
+}
+
+static NSString *storedKey(void) {
+ NSMutableDictionary *query = [keyQuery() mutableCopy];
+ query[(__bridge id)kSecReturnData] = @YES;
+ query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
+ CFTypeRef data = NULL;
+ if (SecItemCopyMatching((__bridge CFDictionaryRef)query, &data) != errSecSuccess || !data) return nil;
+ NSString *key = [[NSString alloc] initWithData:(__bridge_transfer NSData *)data encoding:NSUTF8StringEncoding];
+ return key.length ? key : nil;
+}
+
+static void storeKey(NSString *key) {
+ SecItemDelete((__bridge CFDictionaryRef)keyQuery());
+ if (!key.length) return;
+ NSMutableDictionary *item = [keyQuery() mutableCopy];
+ item[(__bridge id)kSecValueData] = [key dataUsingEncoding:NSUTF8StringEncoding];
+ item[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly;
+ OSStatus status = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
+ if (status != errSecSuccess) SGLog(@"spicy lyrics: the key could not be kept (%d)", (int)status);
+}
+
+BOOL SGSpicyLyricsKeySet(void) {
+ return storedKey() != nil;
+}
+
+#pragma mark - the response
+
+static NSInteger ms(id seconds) {
+ return [seconds respondsToSelector:@selector(doubleValue)] ? (NSInteger)llround([seconds doubleValue] * 1000) : 0;
+}
+
+static NSString *stringIn(NSDictionary *object, NSString *name) {
+ id value = [object isKindOfClass:NSDictionary.class] ? object[name] : nil;
+ 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) {
+ NSMutableArray<SGKaraokeWord *> *words = [NSMutableArray array];
+ BOOL runsOn = NO;
+ for (NSDictionary *syllable in arrayIn(part, @"Syllables")) {
+ NSString *text = [stringIn(syllable, @"Text") stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
+ if (!text.length) continue;
+ SGKaraokeWord *word = [SGKaraokeWord new];
+ word.text = text;
+ word.start = ms(syllable[@"StartTime"]);
+ word.end = MAX(ms(syllable[@"EndTime"]), word.start);
+ word.joined = words.count && runsOn;
+ [words addObject:word];
+ runsOn = [syllable[@"IsPartOfWord"] boolValue];
+ }
+ 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);
+ return line;
+}
+
+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"]);
+ 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.
+ NSMutableArray *backing = [NSMutableArray array];
+ for (NSDictionary *group in arrayIn(item, @"Background")) [backing addObjectsFromArray:arrayIn(group, @"Syllables")];
+ line.backing = syllableLine(@{@"Syllables": backing});
+ [lines addObject:line];
+ }
+ return lines.count ? lines : nil;
+}
+
+static BOOL isBreak(NSString *text) {
+ NSString *trimmed = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
+ return !trimmed.length || [trimmed isEqualToString:@"♪"];
+}
+
+// Starts only; the words inside are estimated. A line that ends well before the next begins gets an
+// empty line at its end, so the estimate does not stretch it over the pause.
+static NSArray<SGKaraokeLine *> *lineLines(NSArray *content) {
+ NSMutableArray<NSDictionary *> *kept = [NSMutableArray array];
+ for (NSDictionary *item in content) {
+ if (!isBreak(stringIn(item, @"Text"))) [kept addObject:item];
+ }
+ NSMutableArray<NSNumber *> *starts = [NSMutableArray array];
+ NSMutableArray<NSString *> *texts = [NSMutableArray array];
+ for (NSUInteger i = 0; i < kept.count; i++) {
+ [starts addObject:@(ms(kept[i][@"StartTime"]))];
+ [texts addObject:kept[i][@"Text"]];
+ NSInteger end = ms(kept[i][@"EndTime"]);
+ if (end > 0 && i + 1 < kept.count && ms(kept[i + 1][@"StartTime"]) > end) {
+ [starts addObject:@(end)];
+ [texts addObject:@""];
+ }
+ }
+ NSArray<SGKaraokeLine *> *lines = SGKaraokeEstimatedLines(starts, texts);
+ // 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]);
+ }
+ return lines;
+}
+
+static NSArray<SGKaraokeLine *> *staticLines(NSArray *rows) {
+ NSMutableArray<NSString *> *texts = [NSMutableArray array];
+ for (NSDictionary *row in rows) {
+ NSString *text = stringIn(row, @"Text");
+ if (text) [texts addObject:text];
+ }
+ return SGKaraokeStaticLines(texts);
+}
+
+// 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) {
+ 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 (maker && uploader && ![maker isEqualToString:uploader]) {
+ return [NSString stringWithFormat:@"Spicy Lyrics, synced by %@, uploaded by %@", maker, uploader];
+ }
+ if (maker ?: uploader) return [NSString stringWithFormat:@"Spicy Lyrics, synced by %@", maker ?: uploader];
+ return @"Spicy Lyrics";
+}
+
+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<SGKaraokeLine *> *lines = [type isEqualToString:@"Syllable"] ? syllableLines(arrayIn(body, @"Content"))
+ : [type isEqualToString:@"Line"] ? lineLines(arrayIn(body, @"Content"))
+ : [type isEqualToString:@"Static"] ? staticLines(arrayIn(body, @"Lines"))
+ : nil;
+ if (!lines) return nil;
+ SGLyricsResult *result = [SGLyricsResult new];
+ result.provider = creditFor(body);
+ result.karaokeLines = lines;
+ result.wordTimed = SGKaraokeLinesTiming(lines) == SGKaraokeTimingWords;
+ result.synced = SGKaraokeLinesTiming(lines) != SGKaraokeTimingNone;
+ NSArray<NSNumber *> *starts;
+ NSArray<NSString *> *texts;
+ if (result.synced) {
+ SGLyricsPageLines(lines, &starts, &texts);
+ } else {
+ NSMutableArray<NSNumber *> *zeros = [NSMutableArray array];
+ NSMutableArray<NSString *> *plain = [NSMutableArray array];
+ for (SGKaraokeLine *line in lines) {
+ [zeros addObject:@0];
+ [plain addObject:SGKaraokeLineText(line)];
+ }
+ starts = zeros;
+ texts = plain;
+ }
+ result.starts = starts;
+ result.texts = texts;
+ return result;
+}
+
+#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) {
+ 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
+ ? [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");
+ done(result);
+ });
+};
+
+#pragma mark - the row
+
+// 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.
+static void setKey(NSString *key) {
+ storeKey(key);
+ 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."
+ preferredStyle:UIAlertControllerStyleAlert];
+ [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {
+ field.placeholder = @"sl_sk_...";
+ field.secureTextEntry = YES;
+ field.autocorrectionType = UITextAutocorrectionTypeNo;
+ field.autocapitalizationType = UITextAutocapitalizationTypeNone;
+ }];
+ [alert addAction:[UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
+ NSString *key = [alert.textFields.firstObject.text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
+ if (key.length) setKey(key);
+ }]];
+ if (SGSpicyLyricsKeySet()) {
+ [alert addAction:[UIAlertAction actionWithTitle:@"Remove" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+ setKey(nil);
+ }]];
+ }
+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
+ [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(); });
+}