Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: local files get lyrics in the redesigned player
My-Name-Is-Jeff6ef6b054f64c
diff --git a/harness/lyrics-translation/build.sh b/harness/lyrics-translation/build.shindex 61599a53..7d7c7520 100755--- a/harness/lyrics-translation/build.sh+++ b/harness/lyrics-translation/build.sh@@ -1,12 +1,13 @@#!/bin/sh# build.sh: builds check.m against this checkout's Musixmatch.m, LyricsTranslation.m and KaraokeTiming.m-# as a Mac Catalyst binary and runs it, so no simulator is needed.+# (and LocalFiles.m, which Musixmatch.m reads a local file's names from) as a Mac Catalyst binary and runs+# it, so no simulator is needed.set -eHERE=$(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/Musixmatch.m" "$SRC/Shared/LyricsTranslation/LyricsTranslation.m" \- "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/Lyrics/Protobuf.m" \- -framework UIKit -framework Security -framework Foundation -o "$HERE/build/check"+ "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/Lyrics/Protobuf.m" "$SRC/Shared/LocalFiles/LocalFiles.m" \+ -framework UIKit -framework CoreGraphics -framework Security -framework Foundation -o "$HERE/build/check""$HERE/build/check"diff --git a/harness/player/stubs.m b/harness/player/stubs.mindex 94798a5b..348d87e1 100644--- a/harness/player/stubs.m+++ b/harness/player/stubs.m@@ -136,6 +136,10 @@ void SGLyricsTranslateWithGemini(NSString *trackID, NSArray<SGKaraokeLine *> *livoid (^done)(NSArray<NSString *> *translations, NSString *error)) { done(nil, @"harness"); }UIViewController *SGTopController(void) { return UIApplication.sharedApplication.keyWindow.rootViewController; }+// Local files: no edits in the harness, so the name is all PlayerLyrics.x needs to watch for one.+#import "Shared/LocalFiles/LocalFiles.h"+NSNotificationName const SGLocalFileEditsDidChangeNotification = @"harness.localFileEditsDidChange";+// Speed and pitch: a number the harness keeps, with no audio behind it.static double sg_speed = 1;double SGPlayerSpeed(void) { return sg_speed; }diff --git a/tweak/Sources/Shared/LocalFiles/LocalFiles.h b/tweak/Sources/Shared/LocalFiles/LocalFiles.hnew file mode 100644index 00000000..f29033c7--- /dev/null+++ b/tweak/Sources/Shared/LocalFiles/LocalFiles.h@@ -0,0 +1,50 @@+// Local files: the tracks Spotify plays from the Files app, under either look. Their URI carries their+// tags, spotify:local:<artist>:<album>:<title>:<seconds>, each part form encoded ("+" for a space), and+// Spotify's core reads them from the file once, when it scans it.+//+// LocalFiles.m the URI read back into names, and the edits the user made, kept by the mod+// LocalFileInfo.x the edits applied: the player's track metadata, the cover's image request and+// the system's now playing artwork+// EditInfoMenu.x Edit info in the player's ⋯ menu while a local file plays, and its editor+//+// The file itself is never written: Spotify read its tags when it scanned it, and writing them back+// would take a tag writer per format. So an edit is stored by URI and laid over what Spotify read.+//+// Lyrics: Spotify never asks spclient for a local file's lyrics, so the lyrics engine keeps them under+// SGLocalFileLyricsKey and asks the sources by the names here (Shared/Lyrics/KaraokeSource.x).+#import <UIKit/UIKit.h>++// URI -> {title, artist, album, cover (a file name in SGLocalFileCoversDirectory), number}.+#define SGKeyLocalFileEdits @"spotifyglass.localFiles.edits"++// A local file's URI, or a lyrics key made from one.+BOOL SGLocalFileIs(NSString *uri);+// What the lyrics engine keeps a local file under: its URI, and once it is edited the edit's number+// after a "#", so an edit reads as a new track and its lyrics are looked up again under the new names.+// nil for anything but a local file.+NSString *SGLocalFileLyricsKey(NSString *uri);+// The names a local file goes by, the user's edits over its own tags: title, artist, album (each+// present only when not empty) and seconds. Takes a URI or a lyrics key; nil for anything else.+NSDictionary<NSString *, id> *SGLocalFileInfo(NSString *uri);+// The file's own names, as its URI carries them, with no edit over them.+NSDictionary<NSString *, id> *SGLocalFileTags(NSString *uri);++// The user's edit of a local file, nil when there is none. Safe from any thread.+NSDictionary<NSString *, id> *SGLocalFileEditFor(NSString *uri);+// Stores the names (an empty or missing one, or one the file already has, falls back to the file's+// own) and a new cover when `cover` is set; `keepCover` NO drops the stored one. Main thread.+void SGLocalFileSaveEdit(NSString *uri, NSDictionary<NSString *, NSString *> *names, UIImage *cover, BOOL keepCover);+void SGLocalFileForget(NSString *uri);+// Where the stored covers are, and the one an edit names; nil when it names none.+NSString *SGLocalFileCoversDirectory(void);+NSString *SGLocalFileCoverPath(NSDictionary<NSString *, id> *edit);+// A stored cover as the image address Spotify's loader takes for a local file, spotify:localfileimage:+// and the path percent escaped, ":" too, since the loader splits the address on it; and back, nil for+// an address that is not one of these covers.+NSString *SGLocalFileCoverURL(NSString *path);+NSString *SGLocalFileCoverInURL(NSString *url);+// Posted on the main thread after an edit is stored or forgotten, object the URI.+extern NSNotificationName const SGLocalFileEditsDidChangeNotification;++// EditInfoMenu.x: the editor for a local file, presented over `presenter`.+void SGLocalFilePresentEditor(UIViewController *presenter, NSString *uri);diff --git a/tweak/Sources/Shared/LocalFiles/LocalFiles.m b/tweak/Sources/Shared/LocalFiles/LocalFiles.mnew file mode 100644index 00000000..6d5e8584--- /dev/null+++ b/tweak/Sources/Shared/LocalFiles/LocalFiles.m@@ -0,0 +1,193 @@+// LocalFiles.h says what is kept and why the file is not written.+//+// Threading: the edits are read on whatever thread Spotify reads a track's metadata on, so the table is+// swapped whole under a lock; they are written on the main thread.+#import <os/lock.h>+#import "Core/SGCore.h"+#import "LocalFiles.h"++static NSString *const kLocalPrefix = @"spotify:local:";+// A cover is kept no larger than this on its longer side; the player draws it at under half that.+static const CGFloat kCoverSide = 1200;++NSNotificationName const SGLocalFileEditsDidChangeNotification = @"spotifyglass.localFiles.editsDidChange";++static NSDictionary<NSString *, NSDictionary *> *sg_edits;+static os_unfair_lock sg_lock = OS_UNFAIR_LOCK_INIT;++BOOL SGLocalFileIs(NSString *uri) {+ return [uri isKindOfClass:NSString.class] && [uri hasPrefix:kLocalPrefix];+}++static NSDictionary<NSString *, NSDictionary *> *allEdits(void) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ id stored = [NSUserDefaults.standardUserDefaults dictionaryForKey:SGKeyLocalFileEdits];+ os_unfair_lock_lock(&sg_lock);+ sg_edits = [stored isKindOfClass:NSDictionary.class] ? stored : @{};+ os_unfair_lock_unlock(&sg_lock);+ });+ os_unfair_lock_lock(&sg_lock);+ NSDictionary *edits = sg_edits;+ os_unfair_lock_unlock(&sg_lock);+ return edits;+}++static void storeEdits(NSDictionary<NSString *, NSDictionary *> *edits) {+ os_unfair_lock_lock(&sg_lock);+ sg_edits = [edits copy];+ os_unfair_lock_unlock(&sg_lock);+ if (edits.count) [NSUserDefaults.standardUserDefaults setObject:edits forKey:SGKeyLocalFileEdits];+ else [NSUserDefaults.standardUserDefaults removeObjectForKey:SGKeyLocalFileEdits];+}++NSDictionary<NSString *, id> *SGLocalFileEditFor(NSString *uri) {+ if (!SGLocalFileIs(uri)) return nil;+ id edit = allEdits()[uri];+ return [edit isKindOfClass:NSDictionary.class] ? edit : nil;+}++NSString *SGLocalFileLyricsKey(NSString *uri) {+ if (!SGLocalFileIs(uri)) return nil;+ id number = SGLocalFileEditFor(uri)[@"number"];+ return number ? [NSString stringWithFormat:@"%@#%@", uri, number] : uri;+}++#pragma mark - the URI's own names++// Form encoded: "+" is a space and the rest percent escapes, so a part never holds a raw ":".+static NSString *decoded(NSString *part) {+ NSString *spaced = [part stringByReplacingOccurrencesOfString:@"+" withString:@" "];+ return spaced.stringByRemovingPercentEncoding ?: spaced;+}++NSDictionary<NSString *, id> *SGLocalFileTags(NSString *uri) {+ if (!SGLocalFileIs(uri)) return nil;+ NSArray<NSString *> *parts = [[uri substringFromIndex:kLocalPrefix.length] componentsSeparatedByString:@":"];+ if (parts.count != 4) return nil;+ NSMutableDictionary<NSString *, id> *tags = [NSMutableDictionary dictionary];+ NSString *artist = decoded(parts[0]), *album = decoded(parts[1]), *title = decoded(parts[2]);+ if (title.length) tags[@"title"] = title;+ if (artist.length) tags[@"artist"] = artist;+ if (album.length) tags[@"album"] = album;+ // A lyrics key carries "#<number>" after the seconds, which integerValue stops at.+ tags[@"seconds"] = @(MAX(parts[3].integerValue, 0));+ return tags;+}++NSDictionary<NSString *, id> *SGLocalFileInfo(NSString *uri) {+ NSDictionary *tags = SGLocalFileTags(uri);+ if (!tags) return nil;+ NSRange mark = [uri rangeOfString:@"#" options:NSBackwardsSearch];+ NSDictionary *edit = SGLocalFileEditFor(mark.location == NSNotFound ? uri : [uri substringToIndex:mark.location]);+ if (!edit) return tags;+ NSMutableDictionary<NSString *, id> *info = [tags mutableCopy];+ for (NSString *field in @[@"title", @"artist", @"album"]) {+ if ([edit[field] length]) info[field] = edit[field];+ }+ return info;+}++#pragma mark - storing an edit++NSString *SGLocalFileCoversDirectory(void) {+ static NSString *directory;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ // Application Support rather than Documents: Spotify scans Documents for music, and the Files app shows it.+ NSString *support = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;+ directory = [support stringByAppendingPathComponent:@"Vitrine/Local file covers"];+ });+ return directory;+}++NSString *SGLocalFileCoverPath(NSDictionary<NSString *, id> *edit) {+ NSString *name = edit[@"cover"];+ return [name isKindOfClass:NSString.class] && name.length ? [SGLocalFileCoversDirectory() stringByAppendingPathComponent:name] : nil;+}++static NSString *const kImagePrefix = @"spotify:localfileimage:";++NSString *SGLocalFileCoverURL(NSString *path) {+ static NSCharacterSet *allowed;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ NSMutableCharacterSet *set = [NSCharacterSet.URLPathAllowedCharacterSet mutableCopy];+ [set removeCharactersInString:@":"];+ allowed = set;+ });+ NSString *escaped = [path stringByAddingPercentEncodingWithAllowedCharacters:allowed];+ return escaped ? [kImagePrefix stringByAppendingString:escaped] : nil;+}++NSString *SGLocalFileCoverInURL(NSString *url) {+ if (![url isKindOfClass:NSString.class] || ![url hasPrefix:kImagePrefix]) return nil;+ NSString *path = [url substringFromIndex:kImagePrefix.length].stringByRemovingPercentEncoding;+ NSString *directory = [SGLocalFileCoversDirectory() stringByAppendingString:@"/"];+ // Only a file of the covers' own, by its name alone, so no address reaches anything else.+ if (![path hasPrefix:directory] || [path substringFromIndex:directory.length].pathComponents.count != 1) return nil;+ return path;+}++static NSString *writeCover(UIImage *image) {+ CGFloat scale = MIN(1, kCoverSide / MAX(image.size.width, image.size.height));+ CGSize size = CGSizeMake(round(image.size.width * scale), round(image.size.height * scale));+ UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];+ format.scale = 1;+ format.opaque = YES;+ UIImage *drawn = [[[UIGraphicsImageRenderer alloc] initWithSize:size format:format] imageWithActions:^(UIGraphicsImageRendererContext *context) {+ [image drawInRect:(CGRect){CGPointZero, size}];+ }];+ NSData *data = UIImageJPEGRepresentation(drawn, 0.9);+ NSString *name = [NSUUID.UUID.UUIDString stringByAppendingPathExtension:@"jpg"];+ NSError *error = nil;+ [NSFileManager.defaultManager createDirectoryAtPath:SGLocalFileCoversDirectory() withIntermediateDirectories:YES attributes:nil error:&error];+ if (!data || ![data writeToFile:[SGLocalFileCoversDirectory() stringByAppendingPathComponent:name] options:NSDataWritingAtomic error:&error]) {+ SGLog(@"local files: the cover was not written: %@", error);+ return nil;+ }+ return name;+}++static void changed(NSString *uri) {+ [NSNotificationCenter.defaultCenter postNotificationName:SGLocalFileEditsDidChangeNotification object:uri];+}++void SGLocalFileSaveEdit(NSString *uri, NSDictionary<NSString *, NSString *> *names, UIImage *cover, BOOL keepCover) {+ if (!SGLocalFileIs(uri)) return;+ NSDictionary *tags = SGLocalFileTags(uri), *old = SGLocalFileEditFor(uri);+ NSMutableDictionary<NSString *, id> *edit = [NSMutableDictionary dictionary];+ for (NSString *field in @[@"title", @"artist", @"album"]) {+ NSString *name = [names[field] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ if (name.length && ![name isEqualToString:tags[field]]) edit[field] = name;+ }+ NSString *oldCover = SGLocalFileCoverPath(old);+ NSString *newCover = cover ? writeCover(cover) : nil;+ if (newCover) edit[@"cover"] = newCover;+ else if (keepCover && oldCover) edit[@"cover"] = old[@"cover"];+ if (oldCover && ![edit[@"cover"] isEqual:old[@"cover"]]) [NSFileManager.defaultManager removeItemAtPath:oldCover error:nil];++ NSMutableDictionary *edits = [allEdits() mutableCopy];+ if (edit.count) {+ // Milliseconds, so no two edits of a track share a lyrics key, a reset in between or not.+ edit[@"number"] = @((long long)(NSDate.date.timeIntervalSince1970 * 1000));+ edits[uri] = edit;+ } else {+ [edits removeObjectForKey:uri];+ }+ storeEdits(edits);+ SGLog(@"local files: %@ %@", uri, edit.count ? [NSString stringWithFormat:@"edited: %@", edit] : @"back to its own tags");+ changed(uri);+}++void SGLocalFileForget(NSString *uri) {+ NSDictionary *old = SGLocalFileEditFor(uri);+ if (!old) return;+ NSString *cover = SGLocalFileCoverPath(old);+ if (cover) [NSFileManager.defaultManager removeItemAtPath:cover error:nil];+ NSMutableDictionary *edits = [allEdits() mutableCopy];+ [edits removeObjectForKey:uri];+ storeEdits(edits);+ SGLog(@"local files: %@ back to its own tags", uri);+ changed(uri);+}diff --git a/tweak/Sources/Shared/Lyrics/KaraokeSource.x b/tweak/Sources/Shared/Lyrics/KaraokeSource.xindex 14b84c67..e203cabd 100644--- a/tweak/Sources/Shared/Lyrics/KaraokeSource.x+++ b/tweak/Sources/Shared/Lyrics/KaraokeSource.x@@ -6,6 +6,7 @@// hands the lines over.#import "Core/SGCore.h"#import "Lyrics.h"+#import "Shared/LocalFiles/LocalFiles.h"#import "Shared/LockScreenLyrics/LockScreenLyrics.h"#import "Shared/AnimatedArtwork/AnimatedArtwork.h"#import "Shared/LyricsSources/LyricsSources.h"@@ -208,8 +209,10 @@ void SGKaraokeAskSpotifyForTiming(NSString *trackID) {void SGKaraokeRequestLyrics(NSString *trackID) {if (!trackID || sg_lyrics[trackID] || [sg_requested containsObject:trackID]) return;+ // spclient has nothing for a local file, which only the sources can name.+ BOOL local = SGLocalFileIs(trackID);if (!sg_ownSources) {- requestFromSpotify(trackID);+ if (!local) requestFromSpotify(trackID);return;}[sg_requested addObject:trackID];@@ -222,6 +225,8 @@ void SGKaraokeRequestLyrics(NSString *trackID) {// Plain text is shown while Spotify is asked whether it has the song timed.if (SGKaraokeLinesTiming(lyrics.karaokeLines) != SGKaraokeTimingNone) return;}+ // Left asked for: the readers ask on every tick, and an edit of its names gives it a new key.+ if (local) return;[sg_requested removeObject:trackID];requestFromSpotify(trackID);});@@ -237,9 +242,7 @@ static SPTPlayerState *playerState(void) {}NSString *SGKaraokePlayingTrack(void) {- id uri = playerState().track.URI;- NSString *text = [uri isKindOfClass:NSURL.class] ? ((NSURL *)uri).absoluteString : [uri description];- return [text hasPrefix:@"spotify:track:"] ? [text substringFromIndex:@"spotify:track:".length] : nil;+ return idOf(playerState().track);}NSInteger SGKaraokePositionMs(void) {@@ -254,10 +257,11 @@ void SGKaraokeSeek(NSInteger ms) {[(id<SPTPlayer>)player seekTo:ms / 1000.0];}+// A Spotify track by its base62 id, a local file by its URI (Shared/LocalFiles/LocalFiles.h).static NSString *idOf(SPTPlayerTrack *track) {id uri = track.URI;NSString *text = [uri isKindOfClass:NSURL.class] ? ((NSURL *)uri).absoluteString : [uri description];- return [text hasPrefix:@"spotify:track:"] ? [text substringFromIndex:@"spotify:track:".length] : nil;+ return [text hasPrefix:@"spotify:track:"] ? [text substringFromIndex:@"spotify:track:".length] : SGLocalFileLyricsKey(text);}// Tracks come in from the player and from every list that reads their metadata, so when the table@@ -291,7 +295,10 @@ void SGKaraokeRememberTrack(SPTPlayerTrack *track) {// in is what puts the card there. The track is named here, so no walk waits for a name.static void prefetch(SPTPlayerTrack *track, NSString *trackID, SPTPlayerState *state) {if (!sg_ownSources) return;- SGLyricsPrefetch(trackID);+ // Spotify never asks for a local file's lyrics, so they are asked for and kept here. The state is+ // read on any thread, and the kept lines are the main queue's.+ if (SGLocalFileIs(trackID)) dispatch_async(dispatch_get_main_queue(), ^{ SGKaraokeRequestLyrics(trackID); });+ else SGLyricsPrefetch(trackID);SPTPlayerTrack *next = upNextIn(state);NSString *nextID = idOf(next);if (!nextID || [nextID isEqualToString:trackID]) return;diff --git a/tweak/Sources/Shared/Lyrics/Lyrics.h b/tweak/Sources/Shared/Lyrics/Lyrics.hindex 04014cdb..0bfaf862 100644--- a/tweak/Sources/Shared/Lyrics/Lyrics.h+++ b/tweak/Sources/Shared/Lyrics/Lyrics.h@@ -103,7 +103,8 @@ void SGKaraokeRequestLyrics(NSString *trackID);// Asks Spotify's JSON lyrics for the track once, and keeps its lines only if they are more finely// timed than the ones kept: the lyrics view was left with plain text, and Spotify may have it timed.void SGKaraokeAskSpotifyForTiming(NSString *trackID);-NSString *SGKaraokePlayingTrack(void); // the base62 id, nil before the player reported+// The base62 id, a local file's lyrics key (Shared/LocalFiles), nil before the player reported.+NSString *SGKaraokePlayingTrack(void);NSInteger SGKaraokePositionMs(void); // negative when unknownvoid SGKaraokeSeek(NSInteger ms);id SGKaraokePlayer(void); // SPTEsperantoPlayer, nil before the app asked it for its statediff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.m b/tweak/Sources/Shared/LyricsSources/LyricsSources.mindex 5e4b7d68..af261003 100644--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.m+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.m@@ -10,6 +10,7 @@#import "Core/SGCore.h"#import "LyricsSources.h"#import "Shared/Lyrics/Lyrics.h"+#import "Shared/LocalFiles/LocalFiles.h"#import "Headers/SPTPlayer.h"#import <stdatomic.h>@@ -208,6 +209,15 @@ BOOL SGLyricsEnabled(void) {static SGLyricsQuery *queryFor(NSString *trackID) {SGLyricsQuery *query = [SGLyricsQuery new];query.trackID = trackID;+ // A local file is named by its own key: its tags, and the names the user gave it over them.+ NSDictionary *local = SGLocalFileInfo(trackID);+ if (local) {+ query.title = local[@"title"];+ query.artist = local[@"artist"];+ query.album = local[@"album"];+ query.seconds = [local[@"seconds"] integerValue];+ return query;+ }SPTPlayerTrack *track = SGKaraokeTrackFor(trackID);if (!track) return query;query.title = track.trackTitle;diff --git a/tweak/Sources/Shared/LyricsSources/Musixmatch.m b/tweak/Sources/Shared/LyricsSources/Musixmatch.mindex 14bfa42a..1a8a8c07 100644--- a/tweak/Sources/Shared/LyricsSources/Musixmatch.m+++ b/tweak/Sources/Shared/LyricsSources/Musixmatch.m@@ -2,9 +2,11 @@// has the time of every word (richsync), which Spotify never sends. The token is an anonymous one// asked for as Musixmatch's iOS app, so Musixmatch learns the track's id and nothing of the Spotify// account. It is the one source that matches by Spotify's own track id, so it never has to guess at-// a title, and what it learns about the track is passed to the sources asked after it.+// a title, and what it learns about the track is passed to the sources asked after it. A local file has+// no id, so for one the matcher searches by its names and length (q_track, q_artist, q_album, q_duration).#import "Core/SGCore.h"#import "LyricsSources.h"+#import "Shared/LocalFiles/LocalFiles.h"static NSString *const kAPI = @"https://apic-appmobile.musixmatch.com/ws/1.1/";static NSString *const kAppID = @"mac-ios-v2.0";@@ -272,25 +274,27 @@ static SGLyricsResult *withTrack(SGLyricsResult *lyrics, id track) {return result;}-static void ask(NSString *trackID, BOOL renewToken) {+// `match` is what the matcher goes by: Spotify's id, or a local file's names.+static void ask(NSString *trackID, NSDictionary<NSString *, NSString *> *match, BOOL renewToken) {withToken(^(NSString *token) {if (!token) {finish(trackID, nil, NO);return;}- call(@"macro.subtitles.get", @{+ NSMutableDictionary<NSString *, NSString *> *query = [@{@"usertoken": token,- @"track_spotify_id": trackID,@"namespace": @"lyrics_richsynched",@"subtitle_format": @"mxm",@"optional_calls": @"track.richsync",@"richsync_compact_type": @"words",- }, ^(NSDictionary *message) {+ } mutableCopy];+ [query addEntriesFromDictionary:match];+ call(@"macro.subtitles.get", query, ^(NSDictionary *message) {NSInteger status = [dig(message, @"header/status_code") integerValue];if (status == 401 && renewToken) {SGLog(@"musixmatch: token no longer accepted (hint %@), asking for a new one", dig(message, @"header/hint"));[NSUserDefaults.standardUserDefaults removeObjectForKey:kTokenKey];- ask(trackID, NO);+ ask(trackID, match, NO);return;}id calls = dig(message, @"body/macro_calls");@@ -309,10 +313,24 @@ static void ask(NSString *trackID, BOOL renewToken) {});}+// What the matcher goes by: Spotify's id, or for a local file, which has none, its names and length to+// search by. nil when there is nothing to go by.+static NSDictionary<NSString *, NSString *> *matchFor(NSString *trackID, NSString *title, NSString *artist, NSString *album, NSInteger seconds) {+ if (!trackID.length) return nil;+ if (!SGLocalFileIs(trackID)) return @{@"track_spotify_id": trackID};+ if (!title.length) return nil;+ NSMutableDictionary<NSString *, NSString *> *match = [NSMutableDictionary dictionaryWithObject:title forKey:@"q_track"];+ match[@"q_artist"] = artist;+ match[@"q_album"] = album;+ if (seconds > 0) match[@"q_duration"] = [NSString stringWithFormat:@"%ld", (long)seconds];+ return match;+}+SGLyricsAsk SGMusixmatchAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *lyrics)) {setUp();NSString *trackID = query.trackID;- if (!trackID.length) {+ NSDictionary<NSString *, NSString *> *match = matchFor(trackID, query.title, query.artist, query.album, query.seconds);+ if (!match) {done(nil);return;}@@ -327,7 +345,7 @@ SGLyricsAsk SGMusixmatchAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResulreturn;}sg_waiting[trackID] = [NSMutableArray arrayWithObject:[done copy]];- ask(trackID, YES);+ ask(trackID, match, YES);};#pragma mark - translations@@ -403,6 +421,13 @@ static void translationsIn(NSString *token, NSString *commontrack, NSArray<NSStr// done gets what was found, and whether it is Musixmatch's whole answer rather than one cut short.static void askTranslations(NSString *trackID, NSString *language, BOOL renewToken,void (^done)(NSDictionary<NSString *, NSString *> *found, BOOL answered)) {+ // A local file is matched by the names it goes by, its key's edit over its tags, as its lyrics were.+ NSDictionary *local = SGLocalFileInfo(trackID);+ NSDictionary<NSString *, NSString *> *match = matchFor(trackID, local[@"title"], local[@"artist"], local[@"album"], [local[@"seconds"] integerValue]);+ if (!match) {+ done(nil, YES);+ return;+ }withToken(^(NSString *token) {if (!token) {done(nil, NO);@@ -428,7 +453,9 @@ static void askTranslations(NSString *trackID, NSString *language, BOOL renewToktranslate(known);return;}- call(@"matcher.track.get", @{@"usertoken": token, @"track_spotify_id": trackID}, ^(NSDictionary *message) {+ NSMutableDictionary<NSString *, NSString *> *query = [match mutableCopy];+ query[@"usertoken"] = token;+ call(@"matcher.track.get", query, ^(NSDictionary *message) {NSInteger status = [dig(message, @"header/status_code") integerValue];noteCommontrack(trackID, dig(message, @"body/track/commontrack_id"));NSString *commontrack = status == 200 ? sg_commontracks[trackID] : nil;