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

refactor: the lyrics hook is written anew from a description of its behaviour

Vojtěch Škopekee06eaa6209b
diff --git a/tweak/Sources/Shared/LyricsSources/LyricsHook.x b/tweak/Sources/Shared/LyricsSources/LyricsHook.x
index f9ef3cfc..ce3f86ba 100644
--- a/tweak/Sources/Shared/LyricsSources/LyricsHook.x
+++ b/tweak/Sources/Shared/LyricsSources/LyricsHook.x
@@ -1,551 +1,610 @@
-// Spotify's /color-lyrics/v2/track/<id> answered with the chain's lyrics, in the URLSession delegates
-// Spotify reads the reply through, SPTDataLoaderService and HttpClientURLSession, the way
-// EeveeSpotify Reincarnated answers it on 9.1 (DataLoaderServiceHooks.x.swift). Three cases:
-//
-// Spotify has lyrics of its own (a 200). The body is read in whole and handed on with the chain's
-// lines in place of Spotify's when they are timed, on the main queue, which 9.1.60 and later require
-// of these callbacks. This is the path that is known to put the lyrics card under the player.
-//
-// Spotify's own metadata says the track has none. Its request is sent to a donor track instead, one
-// that has lyrics everywhere, and the 200 that comes back has its lines swapped for the chain's as
-// above: a 404 turned into a 200 in the delegate alone never showed a card on 9.1.78, however fast
-// it came, while a real 200 with our lines in it always did. The donor's own lines are never shown:
-// with nothing from the chain the request ends in a 404, as Spotify's would have. The player-track
-// hook below notes what the metadata said, and forces has_lyrics on so the request is made at all.
-//
-// A 404 for a track the metadata has not been seen for. The reply is held where it arrives, its
-// completion handler with it, until the chain has answered; the delegate is then told of a 200, the
-// lyrics and the end, and the task's own response answers the same 200, since Spotify's client may
-// read the status from either. Spotify's real 404 body that follows is dropped, so the task is
-// answered exactly once.
-//
-// Whichever lines win go to the karaoke page as well, and the source that supplied them is credited
-// there.
-//
-// None of that shows a card on its own. The cards under the player are a list the server sends per
-// track, scrollsita's NpvScrollResponse, and it holds a lyrics section only for tracks Spotify has
-// lyrics for; the lyrics provider is asked for a track only when its section is in the list. So the
-// list is read on the way in and a lyrics section is put at its top for any track without one that
-// a source may have lyrics for. The section's shape is copied from the last list that carried one,
-// with the track's own URI inside; before any has passed, it is the URI alone. The player then asks
-// for the lyrics as it would for any track, and the reply is answered as above.
+// Puts the sources' lines on Spotify's lyrics page. Spotify's own color-lyrics 200 gets them swapped in;
+// a track Spotify has none for is asked for as the donor track and its 200 carries them instead; the card
+// list gets a lyrics section, without which the player never asks for lyrics at all.
#import "Core/SGCore.h"
#import "LyricsSources.h"
#import "Shared/Lyrics/Protobuf.h"
#import "Headers/SPTPlayer.h"
+#import <os/lock.h>
-// Blinding Lights, The Weeknd: lyrics in every market Spotify serves them in.
+// Its lyrics are offered wherever Spotify offers lyrics at all.
static NSString *const kDonorTrack = @"0VjIjW4GlUZAMYd2vXMi3b";
-// On a request sent to the donor: the track it was made for.
-static NSString *const kTrackProperty = @"spotifyglass.lyricsTrack";
static NSString *const kLyricsPath = @"/color-lyrics/v2/track/";
-// NpvScrollResponse { 1 structure: { 1 repeated section: Section { oneof section_type: 5 lyrics: { 1 entity_uri } } } }
-// The oneof's cases, in the order Spotify declares them: comments, creator_bio, discovery_feed,
-// credits, lyrics, merch and on, which is the order proto fields are numbered in.
-static const uint32_t kStructureField = 1, kSectionField = 1, kLyricsSectionField = 5, kEntityURIField = 1;
-// The page's colours when Spotify sent none to keep, ARGB.
-static const uint32_t kBackground = 0xFF535353, kLine = 0xFF000000, kActiveLine = 0xFFFFFFFF;
-
-static NSString *trackInURL(NSURL *url) {
+static NSString *const kCardListPath = @"/scrollsita/";
+static NSString *const kTrackPrefix = @"spotify:track:";
+// On a request sent to the donor, the track it really asks for.
+static NSString *const kDonorForKey = @"spotifyglass.lyricsDonorFor";
+static NSString *const kUnnamedProvider = @"spoti.pw";
+
+typedef void (^SGDisposition)(NSURLSessionResponseDisposition disposition);
+typedef void (^SGForwardResponse)(NSURLResponse *response, SGDisposition handler);
+typedef void (^SGForwardEnd)(NSError *error);
+
+typedef NS_ENUM(NSInteger, SGLyricsTaskKind) {
+ SGLyricsTaskCardList, // scrollsita, answered 200
+ SGLyricsTaskSpotify, // Spotify's own 200
+ SGLyricsTaskDonor, // the donor's 200, for a track Spotify has none for
+ SGLyricsTaskMissing, // anything but a 200
+};
+
+// What a task is and where it stands. The first five are set before the state is attached to its task
+// and never change; the rest are read and written under @synchronized on the state, from URLSession's
+// delegate queue and the main queue both.
+@interface SGLyricsTaskState : NSObject
+@property (nonatomic) SGLyricsTaskKind kind;
+@property (nonatomic, copy) NSString *track;
+@property (nonatomic) NSInteger status;
+@property (nonatomic) BOOL donor, artwork;
+@property (nonatomic, strong) NSMutableData *body; // collected, none of it forwarded
+@property (nonatomic) BOOL dropping; // the server's bytes go nowhere
+@property (nonatomic) BOOL held, delivering, ended;
+@property (nonatomic, strong) SGLyricsResult *chain; // what a donor 200 was let through on
+@property (nonatomic, strong) NSData *handing; // the body this file is giving Spotify's delegate
+@property (nonatomic, copy) SGDisposition realHandler;
+@property (nonatomic) BOOL bodyGiven, chose;
+@property (nonatomic) NSURLSessionResponseDisposition choice;
+@end
+
+@implementation SGLyricsTaskState
+@end
+
+static char kStateKey, kAnswerKey;
+static NSData *sg_sectionTemplate;
+static os_unfair_lock sg_templateLock = OS_UNFAIR_LOCK_INIT;
+
+#pragma mark - reading requests
+
+static NSString *lyricsTrack(NSURL *url) {
NSString *path = url.path;
NSRange marker = [path rangeOfString:kLyricsPath];
if (marker.location == NSNotFound) return nil;
- NSString *track = [[path substringFromIndex:NSMaxRange(marker)] componentsSeparatedByString:@"/"].firstObject;
+ NSString *rest = [path substringFromIndex:NSMaxRange(marker)];
+ NSRange slash = [rest rangeOfString:@"/"];
+ NSString *track = slash.location == NSNotFound ? rest : [rest substringToIndex:slash.location];
return track.length ? track : nil;
}
-// The track a request was made for: the one it was sent to the donor for, else the one in its URL.
-static NSString *trackFor(NSURLRequest *request) {
- id kept = [NSURLProtocol propertyForKey:kTrackProperty inRequest:request];
- return [kept isKindOfClass:NSString.class] ? kept : trackInURL(request.URL);
-}
-
-static NSString *trackOf(NSURLSessionTask *task) {
- return trackFor(task.originalRequest) ?: trackFor(task.currentRequest);
-}
-
-static BOOL sentToDonor(NSURLSessionTask *task) {
- return [NSURLProtocol propertyForKey:kTrackProperty inRequest:task.originalRequest] != nil
- || [NSURLProtocol propertyForKey:kTrackProperty inRequest:task.currentRequest] != nil;
+static NSString *cardListTrack(NSURL *url) {
+ if (![url.path containsString:kCardListPath]) return nil;
+ for (NSString *component in url.pathComponents) {
+ NSString *uri = component.stringByRemovingPercentEncoding ?: component;
+ if ([uri hasPrefix:kTrackPrefix] && uri.length > kTrackPrefix.length) return [uri substringFromIndex:kTrackPrefix.length];
+ }
+ return nil;
}
-static NSInteger statusOf(NSURLResponse *response) {
- return [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
+static NSString *donorFor(NSURLRequest *request) {
+ id track = request ? [NSURLProtocol propertyForKey:kDonorForKey inRequest:request] : nil;
+ return [track isKindOfClass:NSString.class] && [track length] ? track : nil;
}
-// Lyrics { 1 data: { 1 time_synchronized, 2 repeated line { 1 offset_ms, 2 content }, 5 provided_by },
-// 2 colors { 1 background, 2 line, 3 active_line } }
-static NSData *lyricsBody(SGLyricsResult *lyrics, NSData *spotify) {
- NSMutableArray<SGPBField *> *data = [NSMutableArray array];
- if (lyrics.synced) [data addObject:SGPBVarint(1, 1)];
- for (NSUInteger i = 0; i < lyrics.texts.count; i++) {
- NSData *line = SGPBSerialize(@[SGPBVarint(1, (uint64_t)MAX(lyrics.starts[i].integerValue, 0)), SGPBString(2, lyrics.texts[i])]);
- [data addObject:SGPBBytes(2, line)];
- }
- [data addObject:SGPBString(5, lyrics.provider ?: @"Musixmatch")];
- SGPBField *colors = SGPBFirst(SGPBParse(spotify), 2);
- if (colors.wire != 2) colors = SGPBBytes(2, SGPBSerialize(@[SGPBVarint(1, kBackground), SGPBVarint(2, kLine), SGPBVarint(3, kActiveLine)]));
- return SGPBSerialize(@[SGPBBytes(1, SGPBSerialize(data)), colors]);
+static NSString *trackOf(SPTPlayerTrack *track) {
+ id uri = track.URI;
+ NSString *text = [uri isKindOfClass:NSURL.class] ? [uri absoluteString] : [uri description];
+ return [text hasPrefix:kTrackPrefix] && text.length > kTrackPrefix.length ? [text substringFromIndex:kTrackPrefix.length] : nil;
}
-// The chain's body, or nil to hand Spotify's reply on as it came. `spotify` is Spotify's own 200
-// body when it has one; a donor's carries no lines of the track's and only lends its colours, and
-// only when the server made them from the track's own artwork, which it names in the URL.
-static NSData *chosenBody(NSString *track, SGLyricsResult *lyrics, NSData *spotify, BOOL donor, BOOL donorColors) {
- NSArray<SGKaraokeLine *> *spotifyLines = donor ? nil : SGKaraokeLinesFromBody(spotify);
- SGKaraokeTiming spotifyTiming = SGKaraokeLinesTiming(spotifyLines);
- // Spotify's own page keeps its own lines when they are timed and the chain's are not.
- BOOL ours = lyrics.texts.count && (lyrics.synced || spotifyTiming == SGKaraokeTimingNone);
- // The lyrics view takes the more finely timed of the two, the chain's on a tie.
- BOOL oursFiner = lyrics.karaokeLines.count && (!spotifyLines || SGKaraokeLinesTiming(lyrics.karaokeLines) <= spotifyTiming);
- NSArray<SGKaraokeLine *> *karaoke = oursFiner ? lyrics.karaokeLines : spotifyLines;
- if (karaoke) SGKaraokeKeepLines(track, karaoke);
- SGLyricsSetCredit(track, karaoke == lyrics.karaokeLines ? lyrics.provider : @"Spotify");
- // Plain text for the view while Spotify has lyrics of its own: its JSON may still have them timed.
- if (!donor && spotify.length && SGKaraokeLinesTiming(karaoke) == SGKaraokeTimingNone) SGKaraokeAskSpotifyForTiming(track);
- SGLog(@"lyrics: page of %@ gets %@; the lyrics view %@'s, %@", track, ours ? [NSString stringWithFormat:@"%@'s lines", lyrics.provider] : spotifyLines ? @"Spotify's own lines" : @"no lyrics",
- oursFiner ? lyrics.provider : @"Spotify", SGKaraokeLinesTiming(karaoke) == SGKaraokeTimingWords ? @"word timed"
- : SGKaraokeLinesTiming(karaoke) == SGKaraokeTimingLine ? @"line timed" : @"untimed");
- return ours ? lyricsBody(lyrics, donor && !donorColors ? nil : spotify) : nil;
-}
-
-#pragma mark - the card list, given a lyrics section
-
-// The track a scrollsita request is for: .../scrollsita/v1/scroll/spotify:track:<id>, the URI
-// escaped or not.
-static NSString *scrollTrackOf(NSURLSessionTask *task) {
- NSURL *url = task.currentRequest.URL ?: task.originalRequest.URL;
- NSString *path = url.path;
- if (![path containsString:@"/scrollsita/"]) return nil;
- for (NSString *part in [path componentsSeparatedByString:@"/"]) {
- NSString *piece = part.stringByRemovingPercentEncoding ?: part;
- if ([piece hasPrefix:@"spotify:track:"]) {
- NSString *track = [piece substringFromIndex:@"spotify:track:".length];
- return track.length ? track : nil;
- }
- }
- return nil;
+static NSURL *urlOf(NSURLSessionTask *task) {
+ return task.currentRequest.URL ?: task.originalRequest.URL;
}
-// The last lyrics section the server sent, whole, so an added one has every field the client may
-// want beyond the URI. Any thread, under its lock.
-static NSData *sg_lyricsSectionTemplate;
-static NSObject *sg_templateLock;
+#pragma mark - the donor
-static NSData *lyricsSectionFor(NSString *track) {
- NSString *uri = [@"spotify:track:" stringByAppendingString:track];
- NSData *lyrics = SGPBSerialize(@[SGPBString(kEntityURIField, uri)]);
- NSData *template;
- @synchronized (sg_templateLock) { template = sg_lyricsSectionTemplate; }
- NSMutableArray<SGPBField *> *fields = template ? SGPBParse(template) : nil;
- if (!fields) return SGPBSerialize(@[SGPBBytes(kLyricsSectionField, lyrics)]);
- for (SGPBField *field in fields) {
- if (field.number == kLyricsSectionField) field.payload = lyrics;
- }
- return SGPBSerialize(fields);
-}
-
-// The list with a lyrics section at its top, or nil to hand it on as it came: it has one, or the
-// track is one no source has lyrics for, or the bytes are not what they should be.
-static NSData *listWithLyrics(NSData *body, NSString *track) {
- NSMutableArray<SGPBField *> *fields = SGPBParse(body);
- SGPBField *structure = SGPBFirst(fields, kStructureField);
- if (structure.wire != 2) {
- SGLog(@"scrollsita: list for %@ not read, %lu bytes", track, (unsigned long)body.length);
- return nil;
- }
- NSMutableArray<SGPBField *> *sections = SGPBParse(structure.payload);
- for (SGPBField *section in sections) {
- if (section.number != kSectionField || section.wire != 2) continue;
- SGPBField *kind = SGPBParse(section.payload).firstObject;
- if (kind.number == kLyricsSectionField && kind.wire == 2) {
- @synchronized (sg_templateLock) { sg_lyricsSectionTemplate = section.payload; }
- return nil;
- }
- }
- if (!SGLyricsMayHave(track)) return nil;
- SGPBField *added = SGPBBytes(kSectionField, lyricsSectionFor(track));
- NSMutableArray<SGPBField *> *withLyrics = [NSMutableArray arrayWithObject:added];
- [withLyrics addObjectsFromArray:sections];
- structure.payload = SGPBSerialize(withLyrics);
- SGLog(@"scrollsita: lyrics section added to the card list of %@", track);
- return SGPBSerialize(fields);
-}
-
-#pragma mark - the request, sent to the donor when Spotify has nothing
-
-// The same request for the donor track, or nil to let this one go as it is: Spotify has lyrics for
-// the track, or has not said yet, or every source has already said it has none, or the mod made it.
-static NSURLRequest *donorRequest(NSURLRequest *request) {
- if (!request.URL || [NSURLProtocol propertyForKey:SGLyricsOwnRequestKey inRequest:request]) return nil;
- if ([NSURLProtocol propertyForKey:kTrackProperty inRequest:request]) return nil;
- NSString *track = trackInURL(request.URL);
+// Only a real 200 makes the lyrics card show, so a track Spotify has none for is asked for as the
+// donor, whose reply then carries the sources' lines. Everything but the id stays as Spotify sent it.
+static NSURLRequest *donorRequestFor(NSURLRequest *request) {
+ NSString *address = request.URL.absoluteString;
+ if (![address containsString:kLyricsPath]) return nil;
+ if ([NSURLProtocol propertyForKey:SGLyricsOwnRequestKey inRequest:request] || donorFor(request)) return nil;
+ NSString *track = lyricsTrack(request.URL);
if (!track || [track isEqualToString:kDonorTrack]) return nil;
if (SGLyricsSpotifyHas(track) != 0 || !SGLyricsMayHave(track)) return nil;
- NSString *absolute = request.URL.absoluteString;
- NSRange marker = [absolute rangeOfString:[kLyricsPath stringByAppendingString:track]];
- if (marker.location == NSNotFound) return nil;
- NSRange idRange = NSMakeRange(NSMaxRange(marker) - track.length, track.length);
- NSURL *url = [NSURL URLWithString:[absolute stringByReplacingCharactersInRange:idRange withString:kDonorTrack]];
+ NSRange range = [address rangeOfString:[kLyricsPath stringByAppendingString:track]];
+ if (range.location == NSNotFound) return nil;
+ NSString *donorAddress = [address stringByReplacingCharactersInRange:range withString:[kLyricsPath stringByAppendingString:kDonorTrack]];
+ NSURL *url = [NSURL URLWithString:donorAddress];
if (!url) return nil;
NSMutableURLRequest *donor = [request mutableCopy];
donor.URL = url;
- [NSURLProtocol setProperty:track forKey:kTrackProperty inRequest:donor];
+ [NSURLProtocol setProperty:track forKey:kDonorForKey inRequest:donor];
SGLog(@"lyrics: Spotify has none for %@, its request goes to the donor", track);
SGLyricsPrefetch(track);
return donor;
}
-%group Sessions
-%hook NSURLSession
-- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request {
- NSURLRequest *donor = donorRequest(request);
- return %orig(donor ?: request);
+#pragma mark - bodies
+
+static NSData *defaultColours(void) {
+ return SGPBSerialize(@[SGPBVarint(1, 0xFF535353u), SGPBVarint(2, 0xFF000000u), SGPBVarint(3, 0xFFFFFFFFu)]);
}
-%end
-%end
-// The sessions Spotify makes are __NSURLSessionLocal; hooked as well only when that class answers
-// dataTaskWithRequest: itself, since a hook on an inherited method would sit on NSURLSession's twice.
-%group LocalSessions
-%hook __NSURLSessionLocal
-- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request {
- NSURLRequest *donor = donorRequest(request);
- return %orig(donor ?: request);
+static NSData *coloursIn(NSData *body) {
+ SGPBField *colours = SGPBFirst(SGPBParse(body), 2);
+ return colours.wire == 2 ? colours.payload : nil;
}
-%end
-%end
-#pragma mark - the reply
+static BOOL isJSON(NSData *body) {
+ return body.length && ((const uint8_t *)body.bytes)[0] == '{';
+}
-// What the hook knows of one lyrics task it answers. The delegate hears of a task on Spotify's own
-// queue and of the answer on the main queue, so everything here is read and written under its lock.
-@interface SGLyricsTask : NSObject
-@property (nonatomic, copy) NSString *track;
-@property (nonatomic) BOOL scroll; // a card list, not lyrics: read in whole and given its section
-@property (nonatomic) BOOL donor; // the request went to the donor; the 200 is not the track's
-@property (nonatomic) BOOL donorColors; // and the server coloured it from the track's own artwork
-@property (nonatomic) BOOL held; // Spotify's server said no; the reply is the chain's
-@property (nonatomic) BOOL answered; // the 200 and the lyrics went out
-@property (nonatomic) BOOL gone; // the task ended before the lyrics were in
-@property (nonatomic, strong) NSHTTPURLResponse *fake; // the 200 the task itself answers with
-@property (nonatomic, strong) NSMutableData *buffer; // Spotify's own 200, read in whole
-@property (nonatomic, strong) NSData *ours; // the body handed on, let through by identity
-@end
+static NSData *pageBody(SGLyricsResult *chain, NSData *colours) {
+ NSMutableArray<SGPBField *> *lyrics = [NSMutableArray array];
+ if (chain.synced) [lyrics addObject:SGPBVarint(1, 1)];
+ NSArray<NSNumber *> *starts = chain.starts;
+ [chain.texts enumerateObjectsUsingBlock:^(NSString *text, NSUInteger i, BOOL *stop) {
+ NSInteger start = i < starts.count ? [starts[i] integerValue] : 0;
+ NSData *line = SGPBSerialize(@[SGPBVarint(1, (uint64_t)MAX(start, 0)),
+ SGPBString(2, [text isKindOfClass:NSString.class] ? text : @"")]);
+ [lyrics addObject:SGPBBytes(2, line)];
+ }];
+ [lyrics addObject:SGPBString(5, chain.provider.length ? chain.provider : kUnnamedProvider)];
+ return SGPBSerialize(@[SGPBBytes(1, SGPBSerialize(lyrics)), SGPBBytes(2, colours ?: defaultColours())]);
+}
-@implementation SGLyricsTask
-@end
+static NSString *timingName(NSArray<SGKaraokeLine *> *lines) {
+ switch (SGKaraokeLinesTiming(lines)) {
+ case SGKaraokeTimingWords: return @"word timed";
+ case SGKaraokeTimingLine: return @"line timed";
+ default: return @"untimed";
+ }
+}
+
+// Which lines Spotify's page and the lyrics view get, the view's kept and credited. The body returned
+// is the page's when the sources' lines replace Spotify's, nil when they do not.
+static NSData *decide(NSString *track, SGLyricsResult *chain, NSData *spotifyBody, BOOL donor, NSData *colours) {
+ NSArray<SGKaraokeLine *> *spotifyLines = spotifyBody ? SGKaraokeLinesFromBody(spotifyBody) : nil;
+ if (!spotifyLines.count) spotifyLines = nil;
+ SGKaraokeTiming spotifyTiming = SGKaraokeLinesTiming(spotifyLines);
+ BOOL replace = chain.texts.count && (chain.synced || spotifyTiming == SGKaraokeTimingNone);
+ NSData *page = replace ? pageBody(chain, colours) : nil;
+
+ NSArray<SGKaraokeLine *> *viewLines = nil;
+ NSString *credit = chain.provider;
+ if (chain.karaokeLines.count && (!spotifyLines || SGKaraokeLinesTiming(chain.karaokeLines) <= spotifyTiming)) {
+ viewLines = chain.karaokeLines;
+ } else if (spotifyLines) {
+ viewLines = spotifyLines;
+ credit = @"Spotify";
+ }
+ if (viewLines) SGKaraokeKeepLines(track, viewLines);
+ SGLyricsSetCredit(track, credit);
+ // Spotify's JSON may have the song timed where its page does not.
+ if (!donor && spotifyBody.length && SGKaraokeLinesTiming(viewLines) == SGKaraokeTimingNone) SGKaraokeAskSpotifyForTiming(track);
+
+ NSString *provider = chain.provider.length ? chain.provider : kUnnamedProvider;
+ NSString *pageGets = page ? [NSString stringWithFormat:@"%@'s lines", provider] : spotifyBody ? @"Spotify's own" : @"none";
+ NSString *viewGets = viewLines ? [NSString stringWithFormat:@"%@'s lines, %@", viewLines == spotifyLines ? @"Spotify" : provider, timingName(viewLines)] : @"nothing";
+ SGLog(@"lyrics: page of %@ gets %@; the lyrics view gets %@", track, pageGets, viewGets);
+ return page;
+}
+
+#pragma mark - the card list
+
+static NSData *sectionTemplate(NSData *latest) {
+ os_unfair_lock_lock(&sg_templateLock);
+ if (latest) sg_sectionTemplate = [latest copy];
+ NSData *template = sg_sectionTemplate;
+ os_unfair_lock_unlock(&sg_templateLock);
+ return template;
+}
-static char kTaskKey;
+static BOOL isLyricsSection(NSData *section) {
+ for (SGPBField *field in SGPBParse(section)) {
+ if (field.number == 5 && field.wire == 2) return YES;
+ }
+ return NO;
+}
-static SGLyricsTask *stateOf(NSURLSessionTask *task) {
- return objc_getAssociatedObject(task, &kTaskKey);
+// A lyrics section Spotify sent for another track carries whatever else a section holds; one made from
+// nothing has only the track.
+static NSData *lyricsSection(NSString *track) {
+ NSData *lyrics = SGPBSerialize(@[SGPBString(1, [kTrackPrefix stringByAppendingString:track])]);
+ NSMutableArray<SGPBField *> *fields = SGPBParse(sectionTemplate(nil));
+ for (SGPBField *field in fields) {
+ if (field.number != 5 || field.wire != 2) continue;
+ field.payload = lyrics;
+ return SGPBSerialize(fields);
+ }
+ return SGPBSerialize(@[SGPBBytes(5, lyrics)]);
+}
+
+// The player asks for lyrics only when the list has a lyrics section, which the server sends only
+// for tracks Spotify has lyrics for.
+static NSData *amendedCardList(NSData *body, NSString *track) {
+ NSMutableArray<SGPBField *> *top = SGPBParse(body);
+ SGPBField *structure = SGPBFirst(top, 1);
+ NSArray<SGPBField *> *sections = structure.wire == 2 ? SGPBParse(structure.payload) : nil;
+ if (!sections) {
+ SGLog(@"scrollsita: the card list of %@ could not be read, %lu bytes", track, (unsigned long)body.length);
+ return body;
+ }
+ for (SGPBField *section in sections) {
+ if (section.number != 1 || section.wire != 2 || !isLyricsSection(section.payload)) continue;
+ sectionTemplate(section.payload);
+ return body;
+ }
+ if (!SGLyricsMayHave(track)) return body;
+ NSMutableData *amended = [SGPBSerialize(@[SGPBBytes(1, lyricsSection(track))]) mutableCopy];
+ [amended appendData:structure.payload];
+ structure.payload = amended;
+ SGLog(@"scrollsita: lyrics section added for %@", track);
+ return SGPBSerialize(top);
}
-// A held task's own -response answers with the 200 the delegate was told of. The class that
-// implements -response is found from the first held task, so every task of it goes through here;
-// one not held answers as before.
-static IMP sg_origResponse;
+#pragma mark - the task's own -response
-static id ownResponse(id self, SEL _cmd) {
- SGLyricsTask *state = stateOf(self);
- NSHTTPURLResponse *fake = nil;
- if (state) {
- @synchronized (state) { fake = state.fake; }
+static Method ownMethod(Class cls, SEL selector) {
+ unsigned int count = 0;
+ Method *methods = class_copyMethodList(cls, &count);
+ Method own = NULL;
+ for (unsigned int i = 0; i < count && !own; i++) {
+ if (method_getName(methods[i]) == selector) own = methods[i];
}
- return fake ?: ((id (*)(id, SEL))sg_origResponse)(self, _cmd);
+ free(methods);
+ return own;
}
-static void answerResponseOf(NSURLSessionTask *task) {
+// Spotify may read the status off the task as well as the delegate argument. The task classes are
+// private and differ between OS versions, so the one answering is taken from the first task that needs it.
+static void answerAs(NSURLSessionTask *task, NSHTTPURLResponse *response) {
static dispatch_once_t once;
dispatch_once(&once, ^{
SEL selector = @selector(response);
- Class owner = object_getClass(task);
- while (owner) {
- unsigned count = 0;
- Method *methods = class_copyMethodList(owner, &count);
- BOOL found = NO;
- for (unsigned i = 0; i < count && !found; i++) found = method_getName(methods[i]) == selector;
- free(methods);
- if (found) break;
- owner = class_getSuperclass(owner);
+ for (Class cls = object_getClass(task); cls; cls = class_getSuperclass(cls)) {
+ Method method = ownMethod(cls, selector);
+ if (!method) continue;
+ NSURLResponse *(*original)(id, SEL) = (NSURLResponse *(*)(id, SEL))method_getImplementation(method);
+ method_setImplementation(method, imp_implementationWithBlock(^NSURLResponse *(id me) {
+ return objc_getAssociatedObject(me, &kAnswerKey) ?: original(me, selector);
+ }));
+ SGLog(@"lyrics: -response answered on %s", class_getName(cls));
+ return;
}
- Method method = class_getInstanceMethod(owner ?: object_getClass(task), selector);
- if (!method) return;
- sg_origResponse = method_setImplementation(method, (IMP)ownResponse);
- SGLog(@"lyrics: -response of %@ answers for held tasks", NSStringFromClass(owner ?: object_getClass(task)));
});
+ objc_setAssociatedObject(task, &kAnswerKey, response, OBJC_ASSOCIATION_RETAIN);
}
-// The body goes to the delegate as any data would, through every hook on the way, and the hook here
-// knows it by the very object it handed over.
-static void handOn(id delegate, NSURLSession *session, NSURLSessionTask *task, SGLyricsTask *state, NSData *body) {
- @synchronized (state) { state.ours = body; }
- [delegate URLSession:session dataTask:(NSURLSessionDataTask *)task didReceiveData:body];
+#pragma mark - replies
+
+static SGLyricsTaskState *stateOf(NSURLSessionTask *task) {
+ id state = objc_getAssociatedObject(task, &kStateKey);
+ return [state isKindOfClass:SGLyricsTaskState.class] ? state : nil;
}
-static NSHTTPURLResponse *okFor(NSURL *url, NSData *body) {
- return [[NSHTTPURLResponse alloc] initWithURL:url statusCode:200 HTTPVersion:@"HTTP/2.0"
- headerFields:@{@"Content-Type": @"application/protobuf", @"Content-Length": @(body.length).stringValue}];
+// Received by a normal message send, so every hook on the selector sees it; this file's own lets it
+// through by the object, since the server's bytes may be the same.
+static void give(id delegate, NSURLSession *session, NSURLSessionDataTask *task, SGLyricsTaskState *state, NSData *body) {
+ if (!body.length) return;
+ @synchronized (state) { state.handing = body; }
+ [delegate URLSession:session dataTask:task didReceiveData:body];
+ @synchronized (state) { state.handing = nil; }
}
-// Never NSURLErrorCancelled: Spotify drops a cancelled request without telling whoever waits on it.
-static NSError *noLyricsError(void) {
- return [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable
- userInfo:@{NSLocalizedDescriptionKey: @"no lyrics for this track from any source"}];
+// Under @synchronized on the state. None once the task has ended.
+static SGDisposition takeHandler(SGLyricsTaskState *state) {
+ SGDisposition handler = state.ended ? nil : state.realHandler;
+ state.realHandler = nil;
+ return handler;
}
-typedef void (^SGDisposition)(NSURLSessionResponseDisposition);
+static SGLyricsTaskState *classify(NSURLSessionTask *task, NSURLResponse *response) {
+ NSURLRequest *original = task.originalRequest, *current = task.currentRequest;
+ NSString *originalAddress = original.URL.absoluteString, *currentAddress = current.URL.absoluteString;
+ BOOL lyrics = [originalAddress containsString:kLyricsPath] || [currentAddress containsString:kLyricsPath];
+ BOOL cards = [(currentAddress ?: originalAddress) containsString:kCardListPath];
+ if (!lyrics && !cards) return nil;
+
+ SGLyricsTaskState *state = [SGLyricsTaskState new];
+ state.status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
+ NSString *cardTrack = cards ? cardListTrack(urlOf(task)) : nil;
+ if (cardTrack) {
+ if (state.status != 200) return nil;
+ state.kind = SGLyricsTaskCardList;
+ state.track = cardTrack;
+ state.body = [NSMutableData data];
+ return state;
+ }
-// The response callback. `orig` hands a response and a completion handler on to Spotify's delegate.
-static void onResponse(id delegate, NSURLSession *session, NSURLSessionDataTask *task, NSURLResponse *response,
- SGDisposition handler, void (^orig)(NSURLResponse *, SGDisposition)) {
- if (stateOf(task)) {
- orig(response, handler);
- return;
+ NSString *track = donorFor(original) ?: donorFor(current);
+ state.donor = track != nil;
+ if (!track) track = lyricsTrack(original.URL) ?: lyricsTrack(current.URL);
+ if (!track) return nil;
+ state.track = track;
+ SGLog(@"lyrics: Spotify answered %ld for %@%@", (long)state.status, track, state.donor ? @" through the donor" : @"");
+ if (state.status == 200 && !state.donor) {
+ state.kind = SGLyricsTaskSpotify;
+ state.body = [NSMutableData data];
+ return state;
}
- NSString *scroll = scrollTrackOf(task);
- if (scroll) {
- if (statusOf(response) == 200) {
- SGLyricsTask *state = [SGLyricsTask new];
- state.track = scroll;
- state.scroll = YES;
- state.buffer = [NSMutableData data];
- objc_setAssociatedObject(task, &kTaskKey, state, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ state.kind = state.status == 200 ? SGLyricsTaskDonor : SGLyricsTaskMissing;
+ state.artwork = state.donor && [current.URL.path containsString:@"/image/"];
+ state.held = YES;
+ state.dropping = YES;
+ return state;
+}
+
+// A donor 200 goes through only with lines to put in it: once Spotify has seen a 200 it cannot be
+// turned into "no lyrics", and the donor's own lines must never show.
+static void answerDonor(NSURLSessionDataTask *task, SGLyricsTaskState *state, SGLyricsResult *chain,
+ NSURLResponse *response, SGDisposition handler, SGForwardResponse forward) {
+ if (chain.texts.count) {
+ @synchronized (state) {
+ state.chain = chain;
+ state.body = [NSMutableData data];
}
- orig(response, handler);
+ forward(response, handler);
return;
}
- NSString *track = trackOf(task);
- if (!track) {
- orig(response, handler);
+ decide(state.track, chain, nil, YES, nil);
+ SGLog(@"lyrics: no source has lyrics for %@, it ends in a 404", state.track);
+ NSHTTPURLResponse *notFound = [[NSHTTPURLResponse alloc] initWithURL:urlOf(task) statusCode:404 HTTPVersion:@"HTTP/2.0" headerFields:nil];
+ answerAs(task, notFound);
+ forward(notFound, handler);
+}
+
+// URLSession's handler waits until the body is in and Spotify's delegate has chosen, so none of the
+// server's own bytes can reach the delegate ahead of it.
+static void answerMissing(id delegate, NSURLSession *session, NSURLSessionDataTask *task, SGLyricsTaskState *state,
+ SGLyricsResult *chain, NSURLResponse *response, SGDisposition handler, SGForwardResponse forward) {
+ NSData *page = decide(state.track, chain, nil, state.donor, nil);
+ if (!page) {
+ SGLog(@"lyrics: no source has lyrics for %@ either, it ends in Spotify's own %ld", state.track, (long)state.status);
+ @synchronized (state) { state.dropping = NO; }
+ forward(response, handler);
return;
}
- SGLyricsTask *state = [SGLyricsTask new];
- state.track = track;
- state.donor = sentToDonor(task);
- state.donorColors = state.donor && [task.currentRequest.URL.path containsString:@"/image/"];
- objc_setAssociatedObject(task, &kTaskKey, state, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- NSInteger status = statusOf(response);
- SGLog(@"lyrics: Spotify answered %ld for %@%@", (long)status, track, state.donor ? @" through the donor" : @"");
- if (status == 200 && state.donor) {
- // Held until the chain answers: with nothing from it the request ends in the 404 Spotify's own
- // would have, and a 200 already handed on cannot be taken back.
- @synchronized (state) { state.held = YES; }
- dispatch_async(dispatch_get_main_queue(), ^{
- SGLyricsFetch(track, ^(SGLyricsResult *lyrics) {
- @synchronized (state) {
- if (state.gone) return;
- }
- if (lyrics.texts.count) {
- @synchronized (state) {
- state.held = NO;
- state.buffer = [NSMutableData data];
- }
- orig(response, handler);
- return;
- }
- chosenBody(track, lyrics, nil, YES, NO);
- SGLog(@"lyrics: no lyrics for %@ from any source, its request ends in a 404 as Spotify's did", track);
- NSHTTPURLResponse *missing = [[NSHTTPURLResponse alloc] initWithURL:task.currentRequest.URL statusCode:404
- HTTPVersion:@"HTTP/2.0" headerFields:@{}];
- answerResponseOf(task);
- @synchronized (state) {
- state.fake = missing;
- state.answered = YES;
- }
- orig(missing, handler);
- });
- });
+ NSDictionary<NSString *, NSString *> *headers = @{
+ @"Content-Type": @"application/protobuf",
+ @"Content-Length": [NSString stringWithFormat:@"%lu", (unsigned long)page.length],
+ };
+ NSHTTPURLResponse *found = [[NSHTTPURLResponse alloc] initWithURL:urlOf(task) statusCode:200 HTTPVersion:@"HTTP/2.0" headerFields:headers];
+ @synchronized (state) { state.realHandler = handler; }
+ answerAs(task, found);
+ forward(found, ^(NSURLSessionResponseDisposition choice) {
+ SGDisposition release = nil;
+ @synchronized (state) {
+ if (state.chose) return;
+ state.chose = YES;
+ state.choice = choice;
+ if (state.bodyGiven) release = takeHandler(state);
+ }
+ if (release) release(choice);
+ });
+ give(delegate, session, task, state, page);
+ SGDisposition release = nil;
+ NSURLSessionResponseDisposition choice;
+ @synchronized (state) {
+ state.bodyGiven = YES;
+ choice = state.choice;
+ if (state.chose) release = takeHandler(state);
+ }
+ if (release) release(choice);
+}
+
+// Main queue, when the chain has answered for a held task. A task that ended meanwhile gets nothing.
+static void answerHeld(id delegate, NSURLSession *session, NSURLSessionDataTask *task, SGLyricsTaskState *state,
+ SGLyricsResult *chain, NSURLResponse *response, SGDisposition handler, SGForwardResponse forward) {
+ BOOL ended, cancelled = NO;
+ @synchronized (state) {
+ ended = state.ended;
+ if (!ended) cancelled = task.state == NSURLSessionTaskStateCanceling || task.state == NSURLSessionTaskStateCompleted;
+ if (!ended && !cancelled) {
+ state.held = NO;
+ state.delivering = YES;
+ }
+ }
+ if (ended || cancelled) {
+ SGLog(@"lyrics: the request for %@ ended before the sources answered, nothing delivered", state.track);
+ // URLSession holds the end of a cancelled task back until it has a disposition.
+ if (cancelled) handler(NSURLSessionResponseCancel);
+ return;
+ }
+ if (state.kind == SGLyricsTaskDonor) answerDonor(task, state, chain, response, handler, forward);
+ else answerMissing(delegate, session, task, state, chain, response, handler, forward);
+ @synchronized (state) { state.delivering = NO; }
+}
+
+static void receivedResponse(id delegate, NSURLSession *session, NSURLSessionDataTask *task, NSURLResponse *response,
+ SGDisposition handler, SGForwardResponse forward) {
+ if (objc_getAssociatedObject(task, &kStateKey)) {
+ forward(response, handler);
return;
}
- if (status == 200) {
- @synchronized (state) { state.buffer = [NSMutableData data]; }
- orig(response, handler);
+ SGLyricsTaskState *state = classify(task, response);
+ BOOL held = state.held;
+ objc_setAssociatedObject(task, &kStateKey, state ?: NSNull.null, OBJC_ASSOCIATION_RETAIN);
+ if (!held) {
+ forward(response, handler);
return;
}
- @synchronized (state) { state.held = YES; }
- dispatch_async(dispatch_get_main_queue(), ^{
- SGLyricsFetch(track, ^(SGLyricsResult *lyrics) {
- @synchronized (state) {
- if (state.gone) return;
- }
- NSData *body = chosenBody(track, lyrics, nil, NO, NO);
- if (!body) {
- @synchronized (state) { state.held = NO; }
- orig(response, handler);
- return;
- }
- // Spotify decides on the 200 with a handler of the hook's; the real one is only called once
- // the lyrics are with the delegate, so the 404 body the server still sends comes after them
- // and is dropped.
- __block BOOL decided = NO, delivered = NO;
- __block NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
- SGDisposition decide = ^(NSURLSessionResponseDisposition chosen) {
- BOOL now;
- @synchronized (state) {
- decided = YES;
- disposition = chosen;
- now = delivered;
- }
- if (now) handler(chosen);
- };
- NSHTTPURLResponse *ok = okFor(task.currentRequest.URL, body);
- answerResponseOf(task);
- @synchronized (state) {
- state.fake = ok;
- state.answered = YES;
- }
- orig(ok, decide);
- handOn(delegate, session, task, state, body);
- BOOL now;
- @synchronized (state) {
- delivered = YES;
- now = decided;
- }
- if (now) handler(disposition);
- });
+ SGLyricsFetch(state.track, ^(SGLyricsResult *chain) {
+ answerHeld(delegate, session, task, state, chain, response, handler, forward);
});
}
-// The data callback: YES when the data goes on to Spotify's delegate.
-static BOOL onData(NSURLSessionTask *task, NSData *data) {
- SGLyricsTask *state = stateOf(task);
+static BOOL forwardsData(NSURLSessionTask *task, NSData *data) {
+ SGLyricsTaskState *state = stateOf(task);
if (!state) return YES;
@synchronized (state) {
- if (data == state.ours) {
- state.ours = nil;
- return YES;
- }
- if (state.held && state.answered) return NO; // Spotify's own 404 body, after the chain's lyrics
- if (state.buffer) {
- [state.buffer appendData:data];
+ if (data == state.handing) return YES;
+ if (state.body) {
+ [state.body appendData:data];
return NO;
}
+ return !state.dropping;
}
- return YES;
}
-// The completion callback. `orig` ends the task at Spotify's delegate.
-static void onComplete(id delegate, NSURLSession *session, NSURLSessionTask *task, NSError *error, void (^orig)(NSError *)) {
- SGLyricsTask *state = stateOf(task);
- NSData *spotify = nil;
- if (state) {
- @synchronized (state) {
- if (state.held && !state.answered) state.gone = YES;
- if (state.buffer && !error) spotify = [state.buffer copy];
- state.buffer = nil;
- }
+// Main queue.
+static void finishSpotify(id delegate, NSURLSession *session, NSURLSessionDataTask *task, SGLyricsTaskState *state,
+ NSData *body, NSError *error, SGForwardEnd forward) {
+ if (error) {
+ forward(error);
+ return;
}
- if (!spotify) {
- orig(error);
+ if (isJSON(body)) {
+ give(delegate, session, task, state, body);
+ forward(nil);
return;
}
- NSString *track = state.track;
- if (state.scroll) {
- handOn(delegate, session, task, state, listWithLyrics(spotify, track) ?: spotify);
- orig(nil);
+ SGLyricsFetch(state.track, ^(SGLyricsResult *chain) {
+ NSData *page = decide(state.track, chain, body, NO, coloursIn(body));
+ give(delegate, session, task, state, page ?: body);
+ forward(nil);
+ });
+}
+
+// Main queue.
+static void finishDonor(id delegate, NSURLSession *session, NSURLSessionDataTask *task, SGLyricsTaskState *state,
+ NSData *body, NSError *error, SGForwardEnd forward) {
+ SGLyricsResult *chain;
+ @synchronized (state) { chain = state.chain; }
+ if (error || !chain) {
+ forward(error);
return;
}
- BOOL json = spotify.length && ((const uint8_t *)spotify.bytes)[0] == '{';
- dispatch_async(dispatch_get_main_queue(), ^{
- void (^finish)(NSData *) = ^(NSData *body) {
- handOn(delegate, session, task, state, body);
- orig(nil);
- };
- if (json && !state.donor) {
- finish(spotify);
- return;
- }
- SGLyricsFetch(track, ^(SGLyricsResult *lyrics) {
- NSData *body = chosenBody(track, lyrics, spotify, state.donor, state.donorColors);
- if (body) {
- finish(body);
- return;
- }
- if (!state.donor) {
- finish(spotify);
- return;
- }
- // Nothing from anyone: the donor's lines must not show for the track, so the request
- // fails as Spotify's own would have.
- SGLog(@"lyrics: no lyrics for %@ from any source, its request fails as Spotify's did", track);
- orig(noLyricsError());
+ // The donor's colours are the track's own only when they were worked out from its artwork.
+ NSData *page = decide(state.track, chain, nil, YES, state.artwork ? coloursIn(body) : nil);
+ if (!page) {
+ SGLog(@"lyrics: no source has lyrics for %@ any more, its request fails", state.track);
+ NSString *reason = [NSString stringWithFormat:@"No lyrics source has lyrics for %@", state.track];
+ forward([NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:@{NSLocalizedDescriptionKey: reason}]);
+ return;
+ }
+ give(delegate, session, task, state, page);
+ forward(nil);
+}
+
+static void completed(id delegate, NSURLSession *session, NSURLSessionTask *task, NSError *error, SGForwardEnd forward) {
+ SGLyricsTaskState *state = stateOf(task);
+ if (!state) {
+ forward(error);
+ return;
+ }
+ NSURLSessionDataTask *dataTask = (NSURLSessionDataTask *)task;
+ NSData *body;
+ BOOL held, delivering;
+ @synchronized (state) {
+ body = state.body;
+ state.body = nil;
+ held = state.held;
+ delivering = state.delivering;
+ state.ended = YES;
+ }
+ if (state.kind == SGLyricsTaskCardList) {
+ if (!error) give(delegate, session, dataTask, state, amendedCardList(body, state.track));
+ forward(error);
+ } else if (state.kind == SGLyricsTaskSpotify) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ finishSpotify(delegate, session, dataTask, state, body, error, forward);
});
- });
+ } else if (held) {
+ // Ended while the sources walk: the end goes through now, and their answer to nobody.
+ forward(error);
+ } else if (state.kind == SGLyricsTaskDonor) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ finishDonor(delegate, session, dataTask, state, body, error, forward);
+ });
+ } else if (delivering) {
+ // Behind the response and body the main queue is handing over.
+ dispatch_async(dispatch_get_main_queue(), ^{ forward(error); });
+ } else {
+ forward(error);
+ }
}
-%group Delegates
+#pragma mark - hooks
+
+%group SGLyricsReplies
+
%hook SPTDataLoaderService
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(SGDisposition)handler {
- onResponse(self, session, task, response, handler, ^(NSURLResponse *passed, SGDisposition decide) { %orig(session, task, passed, decide); });
+ receivedResponse(self, session, task, response, handler, ^(NSURLResponse *given, SGDisposition then) {
+ %orig(session, task, given, then);
+ });
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
- if (onData(task, data)) %orig;
+ if (forwardsData(task, data)) %orig;
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
- onComplete(self, session, task, error, ^(NSError *passed) { %orig(session, task, passed); });
+ completed(self, session, task, error, ^(NSError *given) {
+ %orig(session, task, given);
+ });
}
%end
%hook _TtC26Connectivity_HttpClientKit20HttpClientURLSession
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(SGDisposition)handler {
- onResponse(self, session, task, response, handler, ^(NSURLResponse *passed, SGDisposition decide) { %orig(session, task, passed, decide); });
+ receivedResponse(self, session, task, response, handler, ^(NSURLResponse *given, SGDisposition then) {
+ %orig(session, task, given, then);
+ });
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
- if (onData(task, data)) %orig;
+ if (forwardsData(task, data)) %orig;
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
- onComplete(self, session, task, error, ^(NSError *passed) { %orig(session, task, passed); });
+ completed(self, session, task, error, ^(NSError *given) {
+ %orig(session, task, given);
+ });
}
%end
+
%end
-#pragma mark - the track
-
-// The player offers the lyrics card by the track's has_lyrics. What Spotify's metadata said is
-// noted first, since it is what sends the request to the donor, and the track is remembered so the
-// chain has its name before the player reports it.
-%group AllTracks
-// What the metadata is answered with: has_lyrics on for a track a source may have lyrics for.
-static NSDictionary *markedMetadata(SPTPlayerTrack *self, NSDictionary *metadata) {
- BOOL has = [metadata[@"has_lyrics"] isEqual:@"true"];
- id uri = self.URI;
- NSString *text = [uri isKindOfClass:NSURL.class] ? [(NSURL *)uri absoluteString] : [uri description];
- if (![text hasPrefix:@"spotify:track:"]) return metadata;
- NSString *track = [text substringFromIndex:@"spotify:track:".length];
+%group SGLyricsEveryTrack
+
+// Spotify's own verdict is noted before it is overridden, for the donor to go by. The getter runs for
+// every track in every list many times a second, so it does a few lookups and nothing more.
+%hook SPTPlayerTrack
+- (NSDictionary *)metadata {
+ NSDictionary *metadata = %orig;
+ NSString *track = trackOf(self);
+ if (!track) return metadata;
+ BOOL has = [@"true" isEqual:metadata[@"has_lyrics"]];
SGLyricsNoteSpotifyHas(track, has);
SGKaraokeRememberTrack(self);
if (has || !SGLyricsMayHave(track)) return metadata;
static dispatch_once_t once;
- dispatch_once(&once, ^{ SGLog(@"lyrics: marking tracks without Spotify lyrics as having some, first %@", text); });
- NSMutableDictionary *marked = [metadata mutableCopy] ?: [NSMutableDictionary dictionary];
- marked[@"has_lyrics"] = @"true";
- return marked;
+ dispatch_once(&once, ^{ SGLog(@"lyrics: has_lyrics forced on, first for spotify:track:%@", track); });
+ NSMutableDictionary *forced = metadata ? [metadata mutableCopy] : [NSMutableDictionary dictionary];
+ forced[@"has_lyrics"] = @"true";
+ return forced;
}
+%end
-%hook SPTPlayerTrack
-- (NSDictionary *)metadata {
- NSDictionary *metadata = %orig;
- return markedMetadata(self, metadata);
+%hook NSURLSession
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request {
+ return %orig(donorRequestFor(request) ?: request);
}
%end
+
+%end
+
+%group SGLyricsLocalSession
+
+%hook __NSURLSessionLocal
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request {
+ return %orig(donorRequestFor(request) ?: request);
+}
+%end
+
%end
%ctor {
SGLyricsMigrateLegacyKeys();
if (!SGLyricsEnabled()) return;
- sg_templateLock = [NSObject new];
- %init(Delegates);
- BOOL allTracks = SGFlag(SGKeyLyricsAllTracks, NO);
- if (allTracks) {
- %init(AllTracks);
- %init(Sessions);
+ %init(SGLyricsReplies);
+ BOOL everyTrack = SGFlag(SGKeyLyricsAllTracks, NO);
+ if (everyTrack) {
+ // The generator gives a class that only inherits the method an override of its own, which would
+ // put a second hook in front of NSURLSession's.
SEL selector = @selector(dataTaskWithRequest:);
Class local = objc_getClass("__NSURLSessionLocal");
- Method own = local ? class_getInstanceMethod(local, selector) : NULL;
- if (own && own != class_getInstanceMethod(NSURLSession.class, selector)) %init(LocalSessions);
+ Method own = local ? ownMethod(local, selector) : NULL;
+ BOOL hookLocal = own && method_getImplementation(own) != method_getImplementation(class_getInstanceMethod(NSURLSession.class, selector));
+ %init(SGLyricsEveryTrack);
+ if (hookLocal) %init(SGLyricsLocalSession);
}
- SGLog(@"lyrics: sources %@, every track %@", [SGLyricsOrder() componentsJoinedByString:@", "], allTracks ? @"on" : @"off");
+ SGLog(@"lyrics: sources %@, every track %@", [SGLyricsOrder() componentsJoinedByString:@", "], everyTrack ? @"on" : @"off");
SGRequireClasses(@[@"SPTPlayerTrack", @"SPTDataLoaderService", @"_TtC26Connectivity_HttpClientKit20HttpClientURLSession"]);
}