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: port eevee ad blocking

Vojtěch Škopeke58425feac63
diff --git a/README.md b/README.md
index d4443c95..d2f72c3c 100644
--- a/README.md
+++ b/README.md
@@ -42,12 +42,15 @@ jailbreak. Every piece sits behind its own switch in Settings → Mod Settings.
- Speed control and trim silence for music, not only podcasts
- Picture in picture, in the app and out of it
- No ad on app open, no upsells, no tooltips, no DJ badge
+- EeveeSpotify's ad blocking, ported: ad services, upsells and a Premium product state, each behind its own switch
- Telemetry blocked, with a count of what it stopped
- Hide anything: Home shortcuts, playlist header, player buttons and the cards under them
- Unreleased features Spotify built and never shipped
- Every remote-config flag Spotify ships, searchable, Auto / Off / On
-Purely cosmetic. It does not unlock Premium.
+Cosmetic until asked otherwise. The Ad blocking page holds EeveeSpotify's layers, every one off by default;
+the Premium one rewrites what the server says about the account, is the part Spotify's takedowns have
+gone after, and is untested here.
## Get it
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 9460bd22..500d31b5 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -40,6 +40,9 @@ app:
Appearance/ AMOLED (Amoled.x), the glass search field (SearchField.x), and Repaint.x, which keeps stripped areas transparent
Flags/ Spotify's remote-config flags: the provider hook, the generated table, the All flags page and the topic pages
Privacy/ telemetry blocking and its counters
+ AdBlock/ EeveeSpotify's ad blocking: the ad and upsell services silenced (AdServices.x), ad components out of the
+ Hub JSON (AdHubs.x) and the feeds (Feeds.m), Premium pop-ups dropped (AdPopups.x), and the responses
+ rewritten on the way in (AdNetwork.x, Premium.m over the protobuf walker in Protobuf.m)
About/ the update check and the About section of the root page
A hook reads its switch when it runs (`SGEnabled`, `SGHidden`, `SGFlag` from Core/SGPrefs.h), so a
@@ -65,7 +68,9 @@ tab and Spotify's home and library flags), Playlist (hide the cover, the
header's text and buttons, the curation pills), Now Playing (glass, Spotify's player flags, hide
buttons and cards of the full screen player, and a Lyrics page under it), Lock screen widget,
Playback (speed, queue, the player and the now playing bar), Ads & nags (every switch forces a flag
-Spotify ships on to off: the ad on app open, upsells, tooltips, the DJ badge), Unreleased (features
+Spotify ships on to off: the ad on app open, upsells, tooltips, the DJ badge; and an Ad blocking page
+under it, EeveeSpotify's layers behind three switches that start off: hide ads, hide upsells and
+pretend to be Premium, with a count of what each stopped), Unreleased (features
Spotify built and did not ship) and Experimental, which holds AI Chat (Martini). Then Privacy,
telemetry blocking with a count of what it has stopped; Navbar, the tab bar's own composition; and
All flags, Spotify's remote-config flags with a search field and an Auto / Off / On control per flag
diff --git a/tweak/Sources/Features/AdBlock/AdBlock.h b/tweak/Sources/Features/AdBlock/AdBlock.h
new file mode 100644
index 00000000..f3bd5013
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdBlock.h
@@ -0,0 +1,32 @@
+// Ad blocking: EeveeSpotify's layers, ported. Three switches, each off until asked for. Hide ads
+// keeps the ad services from starting (AdServices.x), takes ad components out of Home and Search
+// before they render (AdHubs.x, Feeds.m) and answers the requests behind them empty (AdNetwork.x).
+// Hide upsells drops the Premium prompts (AdPopups.x, AdServices.x) and forces the flags that show
+// them off (AdBlock.m, through Flags.x). Pretend to be Premium rewrites the product state and remote
+// config as they arrive (Premium.m) and keeps the session alive when the server disagrees
+// (AdNetwork.x).
+#import <UIKit/UIKit.h>
+
+#define SGKeyHideAds @"spotifyglass.adblock.ads"
+#define SGKeyHideUpsells @"spotifyglass.adblock.upsells"
+#define SGKeyFakePremium @"spotifyglass.adblock.premium"
+
+// A flag the ads or upsells switch forces off while it is on. Flags.x asks, and the row for it locks.
+BOOL SGAdBlockForcesFlagOff(NSString *key);
+
+// What the hooks stopped, by kind, for the Ad blocking page (nil label for all of them).
+void SGAdBlockCountOne(NSString *label);
+NSArray<NSString *> *SGAdBlockLabels(void);
+NSUInteger SGAdBlockCount(NSString *label);
+void SGResetAdBlock(void);
+
+// Premium.m: the body of v1/customize, or the bootstrap message that wraps one, rewritten to a
+// Premium account's. nil when the bytes do not parse.
+NSData *SGPatchCustomize(NSData *body);
+NSData *SGPatchBootstrap(NSData *body);
+
+// Feeds.m: a browsita, casita or scrollsita feed with its ad sections taken out; nil when there
+// were none, or the bytes were not the shape expected.
+NSData *SGStripFeed(NSData *body);
+
+UIViewController *SGAdBlockSettingsPage(void);
diff --git a/tweak/Sources/Features/AdBlock/AdBlock.m b/tweak/Sources/Features/AdBlock/AdBlock.m
new file mode 100644
index 00000000..d1202387
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdBlock.m
@@ -0,0 +1,97 @@
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+
+#pragma mark - flags
+
+// Both lists are EeveeSpotify's, kept to the flags this Spotify has.
+static NSString *const adFlags[] = {
+ @"ios-feature-adonappopen.enabled",
+ @"ios-feature-adonappopen.cta_card_enabled",
+ @"ios-nowplaying-scroll-impl.unified_leavebehind_npv_scroll_music_enabled",
+ @"ios-nowplaying-scroll-impl.unified_leavebehind_npv_scroll_podcast_enabled",
+ @"ios-feature-embeddedplaylist.use_unified_leavebehind_fetch",
+ @"ios-adsnowplaying-embeddednpv-impl.foreground_enabled",
+ @"ios-adsnowplaying-embeddednpv-impl.music_track_change_enabled",
+ @"ios-adsnowplaying-embeddednpv-impl.enable_ads_on_podcast",
+ @"ios-feature-adsbase.enable_ads_connect_state_observer",
+ @"ios-feature-adsbase.enable_minimal_preroll_management",
+ @"ios-feature-adsnowplayingui.embedded_npv_video_show_with_canvas",
+ @"ios-feature-adssponsoredcontext.sponsored_playlist_v2_enabled",
+ @"ios-feature-adssponsoredcontext.sponsored_context_mismatch_aderror_enabled",
+ @"ios-feature-adssponsoredcontextnpbattachment.sponsored_npb_slot_fetch_enabled",
+};
+
+static NSString *const upsellFlags[] = {
+ @"ios-feature-shuffletoggleupsell.is_enabled_pt2",
+ @"ios-feature-shuffletoggleupsell.linear_upsell_new_style_experiment_enabled",
+ @"ios-feature-shuffletoggleupsell.play_modes_upsell_new_style_experiment_enabled",
+ @"ios-feature-nowplaying-modes.video_first_shuffle_upsell_enabled",
+ @"ios-jam-freeusershuffleupsellsheetpage-impl.free_user_shuffle_upsell_sheet_enabled",
+ @"ios-jam-freeuserskipupsellpage-impl.free_user_skip_upsell_sheet_enabled",
+ @"ios-jam-freehostedjamsupsell-impl.free_hosted_jams_upsell_enabled",
+ @"ios-reinventfree-contextualupsellpremiumpromo-impl.is_promo_cta_enabled",
+ @"ios-reinventfree-contextualupsellpremiumpromo-impl.show_time_cap_upsell_with_premium_badge",
+ @"ios-reinventfree-controllerui-impl.enable_video_time_cap_upsell",
+ @"ios-reinventfree-controllerui-impl.enable_video_time_cap_upsell_on_search",
+ @"ios-reinventfree-timecappivot-impl.music_video_upsell_enabled",
+ @"ios-settings-mediaqualitypageplugin-impl.is_gbb_upsell_enabled",
+ @"ios-settings-mediaqualitypageplugin-impl.should_show_pigeon_upsell",
+ @"ios-system-listeningparties.preview_ended_upsell_enabled",
+};
+
+static BOOL listed(NSString *key, NSString *const list[], size_t count) {
+ for (size_t i = 0; i < count; i++) {
+ if ([key isEqualToString:list[i]]) return YES;
+ }
+ return NO;
+}
+
+BOOL SGAdBlockForcesFlagOff(NSString *key) {
+ if (SGHidden(SGKeyHideAds) && listed(key, adFlags, sizeof(adFlags) / sizeof(adFlags[0]))) return YES;
+ return SGHidden(SGKeyHideUpsells) && listed(key, upsellFlags, sizeof(upsellFlags) / sizeof(upsellFlags[0]));
+}
+
+#pragma mark - counters
+
+static NSString *const kCounts = @"spotifyglass.adblock.counts";
+static NSString *const labels[] = {
+ @"Ad services", @"Upsell services", @"Popups", @"Page components", @"Feed sections", @"Requests", @"Config rewrites",
+};
+static NSMutableDictionary<NSString *, NSNumber *> *sg_counts;
+
+// Counting happens on whichever thread the hook ran on, the page reads on the main one.
+static NSMutableDictionary<NSString *, NSNumber *> *countsLocked(void) {
+ if (!sg_counts) {
+ sg_counts = [[NSUserDefaults.standardUserDefaults dictionaryForKey:kCounts] mutableCopy] ?: [NSMutableDictionary dictionary];
+ }
+ return sg_counts;
+}
+
+void SGAdBlockCountOne(NSString *label) {
+ @synchronized (kCounts) {
+ NSMutableDictionary<NSString *, NSNumber *> *counts = countsLocked();
+ counts[label] = @(counts[label].unsignedIntegerValue + 1);
+ [NSUserDefaults.standardUserDefaults setObject:counts forKey:kCounts];
+ }
+}
+
+NSArray<NSString *> *SGAdBlockLabels(void) {
+ return [NSArray arrayWithObjects:labels count:sizeof(labels) / sizeof(labels[0])];
+}
+
+NSUInteger SGAdBlockCount(NSString *label) {
+ @synchronized (kCounts) {
+ NSDictionary<NSString *, NSNumber *> *counts = countsLocked();
+ if (label) return counts[label].unsignedIntegerValue;
+ NSUInteger total = 0;
+ for (NSNumber *count in counts.allValues) total += count.unsignedIntegerValue;
+ return total;
+ }
+}
+
+void SGResetAdBlock(void) {
+ @synchronized (kCounts) {
+ sg_counts = [NSMutableDictionary dictionary];
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:kCounts];
+ }
+}
diff --git a/tweak/Sources/Features/AdBlock/AdBlockSettings.m b/tweak/Sources/Features/AdBlock/AdBlockSettings.m
new file mode 100644
index 00000000..47d331a7
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdBlockSettings.m
@@ -0,0 +1,27 @@
+#import "Settings/SGModPage.h"
+#import "AdBlock.h"
+
+UIViewController *SGAdBlockSettingsPage(void) {
+ NSMutableArray<SGModRow *> *counts = [NSMutableArray array];
+ for (NSString *label in SGAdBlockLabels()) {
+ [counts addObject:SGStatRow(label, ^NSString *{
+ return @(SGAdBlockCount(label)).stringValue;
+ })];
+ }
+ [counts addObject:SGStatRow(@"Total", ^NSString *{
+ return @(SGAdBlockCount(nil)).stringValue;
+ })];
+ SGModRow *fakePremium = SGOptionRow(@"Pretend to be Premium", @"Rewrite the product state and config the server sends to a Premium account's, and answer the logout it sends back as done. Free accounts only", SGKeyFakePremium);
+ fakePremium.warning = @"This is the part of EeveeSpotify Spotify's takedown went after, and it has not been tested here. It can end in a forced logout or worse for the account. A Premium account gains nothing from it.";
+ return [[SGModPage alloc] initWithTitle:@"Ad blocking" intro:SGRestartNote sections:@[
+ SGSection(@"From EeveeSpotify", @[
+ SGOptionRow(@"Hide ads", @"The ad services never start, ad components leave Home and Search before they render, and the requests behind them are answered empty", SGKeyHideAds),
+ SGOptionRow(@"Hide upsells", @"Premium prompts, banners and sheets dropped, and the flags that show them forced off", SGKeyHideUpsells),
+ fakePremium,
+ ]),
+ SGSection(@"Blocked so far", counts),
+ SGSection(nil, @[
+ SGActionRow(@"Reset the counters", @"Start counting from zero", ^{ SGResetAdBlock(); }),
+ ]),
+ ] footer:@"All three are off until switched on, and none is needed on a Premium account, which has no ads to block. Audio ads between songs are the Premium switch's to stop; the other two only reach what is drawn."];
+}
diff --git a/tweak/Sources/Features/AdBlock/AdHubs.x b/tweak/Sources/Features/AdBlock/AdHubs.x
new file mode 100644
index 00000000..b9dbda1c
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdHubs.x
@@ -0,0 +1,120 @@
+// Ad components taken out of the Hub JSON Home, Browse and Search pages are built from, before
+// the builder renders them (EeveeSpotify's HubsAdBlocker). A component is an ad when its
+// namespace, name, id, type or the keys of its metadata, logging or custom dictionaries say so;
+// its title never counts, "Billboard Hot 100" is a playlist. The plain ad words go with the ads
+// switch, a promotion word next to a surface word with the upsells one.
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+
+// Bare "ad" and "ads" are absent on purpose: as substrings they hit made-for-you and release-radar.
+static NSString *const adWords[] = {
+ @"sponsored", @"upsell", @"campaign", @"promoted", @"premium-upsell", @"billboard", @"interstitial", @"marquee",
+ @"leavebehind", @"leave-behind", @"displayad", @"display-ad", @"fullbleed", @"full-bleed", @"leaderboard",
+ @"advertisement", @"sponsor", @"native-ad", @"mobile-ads", @"on-surface", @"onsurface", @"search-ad", @"home-ad",
+ @"sponsored-content", @"sponsored-ad", @"ad-card", @"native-ad-home-shelf", @"sponsored-shelf", @"sponsored-row",
+ @"ad-shelf", @"ad-row", @"sponsored-item", @"ad-item", @"upgrade-component", @"mobile-display-ad-card",
+ @"mobile-ads-display-ad-element",
+};
+static NSString *const intentWords[] = {@"premium", @"upgrade", @"offer", @"marketing", @"promo", @"promotion", @"subscribe", @"subscription"};
+static NSString *const surfaceWords[] = {@"banner", @"card", @"popup", @"pop-up", @"sheet", @"overlay", @"component", @"message"};
+
+#define COUNT(list) (sizeof(list) / sizeof(list[0]))
+
+static BOOL ads, upsells;
+
+static BOOL containsAny(NSString *text, NSString *const words[], size_t count) {
+ for (size_t i = 0; i < count; i++) {
+ if ([text containsString:words[i]]) return YES;
+ }
+ return NO;
+}
+
+static BOOL adWord(NSString *text) {
+ if (![text isKindOfClass:NSString.class]) return NO;
+ text = text.lowercaseString;
+ if (ads && containsAny(text, adWords, COUNT(adWords))) return YES;
+ return upsells && containsAny(text, intentWords, COUNT(intentWords)) && containsAny(text, surfaceWords, COUNT(surfaceWords));
+}
+
+static BOOL anyKey(NSDictionary *dictionary) {
+ if (![dictionary isKindOfClass:NSDictionary.class]) return NO;
+ for (NSString *key in dictionary) {
+ if (adWord(key)) return YES;
+ }
+ return NO;
+}
+
+static BOOL isAd(NSDictionary *component) {
+ id kind = component[@"component"];
+ if ([kind isKindOfClass:NSDictionary.class]) {
+ NSString *ns = kind[@"namespace"], *name = kind[@"name"];
+ if (adWord(ns) || adWord(name) || adWord([NSString stringWithFormat:@"%@:%@", ns, name])) return YES;
+ } else if (adWord(kind)) {
+ return YES;
+ }
+ if (adWord(component[@"id"]) || adWord(component[@"type"])) return YES;
+ NSDictionary *metadata = component[@"metadata"];
+ if ([metadata isKindOfClass:NSDictionary.class]) {
+ for (NSString *key in @[@"ad", @"is_ad", @"is_sponsored"]) {
+ if ([metadata[key] respondsToSelector:@selector(boolValue)] && [metadata[key] boolValue]) return YES;
+ }
+ }
+ if (anyKey(metadata) || anyKey(component[@"custom"])) return YES;
+ NSDictionary *logging = component[@"logging"];
+ return [logging isKindOfClass:NSDictionary.class] && (adWord(logging[@"type"]) || anyKey(logging));
+}
+
+static NSArray *filtered(NSArray *components) {
+ if (![components isKindOfClass:NSArray.class]) return components;
+ NSMutableArray *kept = [NSMutableArray array];
+ for (NSDictionary *component in components) {
+ if (![component isKindOfClass:NSDictionary.class]) {
+ [kept addObject:component];
+ continue;
+ }
+ if (isAd(component)) {
+ SGAdBlockCountOne(@"Page components");
+ SGLog(@"dropped page component %@", component[@"id"] ?: component[@"component"]);
+ continue;
+ }
+ NSMutableDictionary *copy = [component mutableCopy];
+ for (NSString *key in @[@"children", @"rows", @"body"]) {
+ if (copy[key]) copy[key] = filtered(copy[key]);
+ }
+ [kept addObject:copy];
+ }
+ return kept;
+}
+
+%hook HUBViewModelBuilderImplementation
+- (void)addJSONDictionary:(NSDictionary *)dictionary {
+ if (![dictionary isKindOfClass:NSDictionary.class]) {
+ %orig;
+ return;
+ }
+ NSMutableDictionary *copy = [dictionary mutableCopy];
+ for (NSString *key in @[@"body", @"overlays", @"sections"]) {
+ if (copy[key]) copy[key] = filtered(copy[key]);
+ }
+ NSDictionary *header = copy[@"header"];
+ if ([header isKindOfClass:NSDictionary.class]) {
+ if (isAd(header)) {
+ SGAdBlockCountOne(@"Page components");
+ [copy removeObjectForKey:@"header"];
+ } else if (header[@"children"]) {
+ NSMutableDictionary *headerCopy = [header mutableCopy];
+ headerCopy[@"children"] = filtered(header[@"children"]);
+ copy[@"header"] = headerCopy;
+ }
+ }
+ %orig(copy);
+}
+%end
+
+%ctor {
+ ads = SGHidden(SGKeyHideAds);
+ upsells = SGHidden(SGKeyHideUpsells);
+ if (!ads && !upsells) return;
+ %init;
+ SGRequireClasses(@[@"HUBViewModelBuilderImplementation"]);
+}
diff --git a/tweak/Sources/Features/AdBlock/AdNetwork.x b/tweak/Sources/Features/AdBlock/AdNetwork.x
new file mode 100644
index 00000000..2a8ace30
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdNetwork.x
@@ -0,0 +1,250 @@
+// Spotify's responses on their way in, through the URLSession delegates it reads them by:
+// SPTDataLoaderService for most of spclient, HttpClientURLSession for what some regions route the
+// other way. A request for an ad is answered empty. With Pretend to be Premium on, the bootstrap
+// and customize bodies are rewritten by Premium.m before the client sees them, the endpoints the
+// server would use to log the account out are answered as if they succeeded, and past the first
+// thirty seconds the re-fetches that could bring the real state back are cancelled before they
+// leave. Feeds go through Feeds.m. Everything here is EeveeSpotify's, less its Ably hooks, which
+// it does not turn on for 9.1 either.
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+
+static BOOL ads, premium;
+static NSDate *started;
+static NSObject *cacheLock;
+static NSData *cachedCustomize; // the last rewritten customize body, for a 304 and the re-fetches
+static char kBufferKey, kServedKey, kPassKey;
+
+typedef NS_ENUM(NSInteger, SGNet) { SGNetPass, SGNetBlock, SGNetPatch };
+
+static NSTimeInterval elapsed(void) {
+ return -started.timeIntervalSinceNow;
+}
+
+static BOOL has(NSString *text, NSString *needle) {
+ return [text containsString:needle];
+}
+
+static BOOL isBootstrap(NSString *path) { return has(path, @"v1/bootstrap"); }
+static BOOL isCustomize(NSString *path) { return has(path, @"v1/customize"); }
+
+// The feeds Home, Search and the page under the player are built from. casita/v1/feeds is the flat
+// list of tab chips, not sections.
+static BOOL isFeed(NSString *path) {
+ if (has(path, @"/casita/v1/feeds")) return NO;
+ return has(path, @"/browsita/") || has(path, @"/casita/") || has(path, @"/scrollsita/");
+}
+
+static BOOL isLogout(NSString *path) {
+ return has(path, @"logout") || has(path, @"sign-out") || has(path, @"session/purge") || has(path, @"token/revoke")
+ || has(path, @"auth/expire") || (has(path, @"melody") && has(path, @"check")) || has(path, @"product-state")
+ || (has(path, @"license") && has(path, @"check")) || has(path, @"deletetoken");
+}
+
+static NSString *const adPaths[] = {
+ @"/ads/", @"/ad-logic/", @"/dac/view/v1/", @"/ad-slot/", @"/ad-inventory/", @"/ad-on-app-open", @"/sponsored/",
+ @"/promoted/", @"/upsell/", @"/premium-upsell", @"/upsell-banner", @"/upsell-card", @"/referrals/upsell",
+ @"/campaign/", @"/billboard/", @"/banner/", @"/interstitial/", @"/overlay/", @"/popup/", @"/pop-up/",
+ @"/search-ad/", @"/home-ad/", @"/marquee/", @"/leavebehind", @"/leave-behind", @"/display-ad/", @"/fullbleed/",
+ @"/leaderboard/", @"/ad-card/", @"/sponsored-content/", @"/sponsored-ad/", @"/native-ad/", @"/sponsored-shelf/",
+ @"/sponsored-row/", @"/ad-shelf/", @"/ad-row/", @"/sponsored-item/", @"/ad-item/", @"/merchandising/",
+ @"/upgrade-component/", @"/marketing/", @"/home-ads/", @"/search-ads/",
+};
+
+static BOOL isAd(NSURL *url, NSString *path) {
+ for (size_t i = 0; i < sizeof(adPaths) / sizeof(adPaths[0]); i++) {
+ if (has(path, adPaths[i])) return YES;
+ }
+ if (has(path, @"/esperanto/") && (has(path, @"ad") || has(path, @"slot"))) return YES;
+ NSString *host = url.host.lowercaseString ?: @"";
+ return has(host, @"doubleclick") || has(host, @"googlesyndication") || [host hasPrefix:@"aet."]
+ || [@[@"ad.spotify.com", @"ads.spotify.com", @"aet.spotify.com"] containsObject:host];
+}
+
+// The first thirty seconds are a fresh login's: signup/public and customize are part of it, and
+// answering them broke first launch.
+static BOOL isRefetch(NSString *path) {
+ return has(path, @"signup/public") || has(path, @"select-ondemand-set") || has(path, @"trials-facade/start-trial")
+ || has(path, @"premium-marketing/upselloffer") || (has(path, @"pendragon") && has(path, @"fetchmessagelist"))
+ || has(path, @"pushka-tokens") || has(path, @"apresolve") || has(path, @"pses/screenconfig") || isCustomize(path);
+}
+
+static SGNet classify(NSURL *url) {
+ NSString *path = url.path.lowercaseString ?: @"";
+ if (premium && isLogout(path)) return SGNetBlock;
+ if (ads && isAd(url, path)) return SGNetBlock;
+ if (premium && elapsed() > 30 && isRefetch(path)) return SGNetBlock;
+ if (premium && (isBootstrap(path) || isCustomize(path))) return SGNetPatch;
+ if (ads && isFeed(path)) return SGNetPatch;
+ return SGNetPass;
+}
+
+static NSData *cached(void) {
+ @synchronized (cacheLock) { return cachedCustomize; }
+}
+
+static NSData *json(NSString *text) {
+ return [text dataUsingEncoding:NSUTF8StringEncoding];
+}
+
+// The body a blocked request is answered with: what its reader parses for, so that nothing is
+// retried and no logout path taken.
+static NSData *blockedReply(NSString *path) {
+ if (has(path, @"signup/public")) return json(@"{\"status\":1,\"country\":\"US\",\"is_country_launched\":true}");
+ if (has(path, @"trials-facade")) return json(@"{\"result\":\"NOT_ELIGIBLE\"}");
+ if (has(path, @"premium-marketing") || has(path, @"pses/screenconfig")) return json(@"{}");
+ if (isLogout(path) || has(path, @"apresolve")) return json(@"{\"status\":\"OK\"}");
+ if (isCustomize(path) && cached()) return cached();
+ return [NSData data];
+}
+
+static NSData *patched(NSURL *url, NSData *body) {
+ NSString *path = url.path.lowercaseString ?: @"";
+ if (isFeed(path)) return SGStripFeed(body);
+ NSData *result = isBootstrap(path) ? SGPatchBootstrap(body) : SGPatchCustomize(body);
+ if (!result) {
+ SGLog(@"could not rewrite %@, passed through", path);
+ return nil;
+ }
+ if (isCustomize(path)) {
+ @synchronized (cacheLock) { cachedCustomize = result; }
+ }
+ SGAdBlockCountOne(@"Config rewrites");
+ SGLog(@"rewrote %@, %lu -> %lu bytes", path, (unsigned long)body.length, (unsigned long)result.length);
+ return result;
+}
+
+#pragma mark - the delegate's three calls
+
+// Data handed to the delegate by the mod goes through its hooked didReceiveData like Spotify's own,
+// with the pass mark on the task so the hook lets it by.
+static void deliver(id<NSURLSessionDataDelegate> delegate, NSURLSession *session, NSURLSessionTask *task, NSData *data) {
+ objc_setAssociatedObject(task, &kPassKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ [delegate URLSession:session dataTask:(NSURLSessionDataTask *)task didReceiveData:data];
+ objc_setAssociatedObject(task, &kPassKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+// A customize the server says has not changed, answered with the rewritten one from last time.
+static NSHTTPURLResponse *replayFor(NSURLSessionTask *task, NSURLResponse *response) {
+ if (!premium || ![response isKindOfClass:NSHTTPURLResponse.class] || ((NSHTTPURLResponse *)response).statusCode != 304) return nil;
+ NSURL *url = task.currentRequest.URL;
+ if (!isCustomize(url.path.lowercaseString ?: @"") || !cached()) return nil;
+ objc_setAssociatedObject(task, &kServedKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ return [[NSHTTPURLResponse alloc] initWithURL:url statusCode:200 HTTPVersion:@"HTTP/2.0" headerFields:@{}];
+}
+
+// YES when the data is not the delegate's to see yet: dropped for a blocked request, kept back for
+// one whose reply is rewritten when it finishes.
+static BOOL holds(NSURLSessionTask *task, NSData *data) {
+ if (objc_getAssociatedObject(task, &kPassKey)) return NO;
+ switch (classify(task.currentRequest.URL)) {
+ case SGNetBlock:
+ return YES;
+ case SGNetPatch: {
+ NSMutableData *buffer = objc_getAssociatedObject(task, &kBufferKey);
+ if (!buffer) objc_setAssociatedObject(task, &kBufferKey, (buffer = [NSMutableData data]), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ [buffer appendData:data];
+ return YES;
+ }
+ default:
+ return NO;
+ }
+}
+
+static void complete(id<NSURLSessionDataDelegate> delegate, NSURLSession *session, NSURLSessionTask *task, NSError *error, void (^finish)(NSError *)) {
+ NSURL *url = task.currentRequest.URL;
+ NSString *path = url.path.lowercaseString ?: @"";
+ NSMutableData *buffer = objc_getAssociatedObject(task, &kBufferKey);
+ objc_setAssociatedObject(task, &kBufferKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ if (objc_getAssociatedObject(task, &kServedKey)) {
+ finish(nil);
+ return;
+ }
+ switch (classify(url)) {
+ case SGNetBlock:
+ SGAdBlockCountOne(@"Requests");
+ SGLog(@"answered %@ empty", path);
+ deliver(delegate, session, task, blockedReply(path));
+ finish(nil);
+ return;
+ case SGNetPatch:
+ if (error) {
+ finish(error);
+ return;
+ }
+ // Nothing to rewrite: a 304, or a body of no bytes. The delegate is told of a body either
+ // way, since a completion with none hangs some readers.
+ if (!buffer) {
+ deliver(delegate, session, task, (isCustomize(path) ? cached() : nil) ?: [NSData data]);
+ finish(nil);
+ return;
+ }
+ deliver(delegate, session, task, patched(url, buffer) ?: buffer);
+ finish(nil);
+ return;
+ default:
+ finish(error);
+ }
+}
+
+%hook SPTDataLoaderService
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))handler {
+ NSHTTPURLResponse *replay = replayFor(task, response);
+ %orig(session, task, replay ?: response, handler);
+ if (replay) deliver((id)self, session, task, cached());
+}
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
+ if (!holds(task, data)) %orig;
+}
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
+ complete((id)self, session, task, error, ^(NSError *passed) { %orig(session, task, passed); });
+}
+%end
+
+%hook _TtC26Connectivity_HttpClientKit20HttpClientURLSession
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))handler {
+ NSHTTPURLResponse *replay = replayFor(task, response);
+ %orig(session, task, replay ?: response, handler);
+ if (replay) deliver((id)self, session, task, cached());
+}
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
+ if (!holds(task, data)) %orig;
+}
+- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
+ complete((id)self, session, task, error, ^(NSError *passed) { %orig(session, task, passed); });
+}
+%end
+
+#pragma mark - before a request leaves
+
+// The re-fetches that could put the real product state back, or drop the push token, use sessions
+// of their own that the delegate hooks do not see; they are cancelled at the task. login5 and the
+// Google token stay: blocking those was a crash loop.
+%group Premium
+%hook NSURLSessionTask
+- (void)resume {
+ NSURL *url = self.currentRequest.URL ?: self.originalRequest.URL;
+ NSString *host = url.host.lowercaseString ?: @"", *path = url.path.lowercaseString ?: @"";
+ BOOL spotify = has(host, @"spotify") || has(host, @"spclient");
+ if (spotify && elapsed() > 30 && (has(path, @"deletetoken") || has(path, @"signup/public") || has(path, @"pses/screenconfig")
+ || isCustomize(path) || has(host, @"apresolve"))) {
+ SGAdBlockCountOne(@"Requests");
+ SGLog(@"cancelled %@%@ before it left", host, path);
+ [self cancel];
+ return;
+ }
+ %orig;
+}
+%end
+%end
+
+%ctor {
+ ads = SGHidden(SGKeyHideAds);
+ premium = SGHidden(SGKeyFakePremium);
+ if (!ads && !premium) return;
+ started = NSDate.date;
+ cacheLock = [NSObject new];
+ %init;
+ if (premium) %init(Premium);
+ SGRequireClasses(@[@"SPTDataLoaderService", @"_TtC26Connectivity_HttpClientKit20HttpClientURLSession"]);
+}
diff --git a/tweak/Sources/Features/AdBlock/AdPopups.x b/tweak/Sources/Features/AdBlock/AdPopups.x
new file mode 100644
index 00000000..2cfaa108
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdPopups.x
@@ -0,0 +1,72 @@
+// The Premium prompts Spotify presents as Encore pop-ups, dropped when their words sell Premium
+// (EeveeSpotify's UpsellPopupBlocker). The words are read where the dialog model is made, since
+// the dialog handed to the presenter does not expose them on every build; the presenter reads
+// them itself as a fallback.
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+
+static NSString *const words[] = {
+ @"premium", @"upgrade", @"subscribe", @"subscription", @"listening without limits", @"unlimited skips",
+ @"play the songs you love", @"go premium", @"like listening", @"free account", @"ad-free", @"ad free", @"try free",
+ @"get premium", @"start premium", @"upsell", @"paywall", @"free tier", @"limited listening",
+ @"předplatn", @"bez reklam",
+};
+
+static char kUpsellKey;
+
+static BOOL sells(NSString *text) {
+ if (![text isKindOfClass:NSString.class]) return NO;
+ text = text.lowercaseString;
+ for (size_t i = 0; i < sizeof(words) / sizeof(words[0]); i++) {
+ if ([text containsString:words[i]]) return YES;
+ }
+ return NO;
+}
+
+static void mark(id object) {
+ objc_setAssociatedObject(object, &kUpsellKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+static BOOL marked(id object) {
+ return objc_getAssociatedObject(object, &kUpsellKey) != nil;
+}
+
+// valueForKey: on a key the object lacks raises, so it is only asked what it answers to.
+static id readKey(id object, NSString *key) {
+ return [object respondsToSelector:NSSelectorFromString(key)] ? [object valueForKey:key] : nil;
+}
+
+%hook SPTEncorePopUpDialogModel
+- (id)initWithTitle:(NSString *)title description:(NSString *)description image:(id)image primaryButtonTitle:(NSString *)primary secondaryButtonTitle:(NSString *)secondary {
+ id model = %orig;
+ if (model && (sells(title) || sells(description) || sells(primary) || sells(secondary))) mark(model);
+ return model;
+}
+%end
+
+%hook SPTEncorePopUpDialog
+- (void)update:(id)model {
+ if (marked(model)) mark(self);
+ %orig;
+}
+%end
+
+%hook SPTEncorePopUpPresenter
+- (void)presentPopUp:(id)popUp {
+ id model = readKey(popUp, @"model") ?: popUp;
+ NSString *title = readKey(model, @"title") ?: readKey(model, @"dialogTitle");
+ NSString *body = readKey(model, @"descriptionText") ?: readKey(model, @"body") ?: readKey(model, @"subtitle");
+ if (marked(popUp) || sells(title) || sells(body)) {
+ SGAdBlockCountOne(@"Popups");
+ SGLog(@"dropped pop-up %@", title ?: @"(marked at its model)");
+ return;
+ }
+ %orig;
+}
+%end
+
+%ctor {
+ if (!SGHidden(SGKeyHideUpsells)) return;
+ %init;
+ SGRequireClasses(@[@"SPTEncorePopUpDialogModel", @"SPTEncorePopUpDialog", @"SPTEncorePopUpPresenter"]);
+}
diff --git a/tweak/Sources/Features/AdBlock/AdServices.x b/tweak/Sources/Features/AdBlock/AdServices.x
new file mode 100644
index 00000000..3ea83879
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/AdServices.x
@@ -0,0 +1,120 @@
+// The services behind every ad surface and Premium prompt, each an SPTService Spotify starts by
+// sending it -load. Hooked to do nothing, the surface is never built: the brand ad on Home, the card
+// under the player, the sponsored playlist header, the sponsorship on the now playing bar, the
+// in-stream ad, and the sheets and cards that sell Premium. The two views are a fallback for a
+// header or banner already on screen before its service was silenced.
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+
+static void takeDown(UIView *view) {
+ view.hidden = YES;
+ view.userInteractionEnabled = NO;
+ if (view.superview) [view removeFromSuperview];
+}
+
+%group Ads
+
+%hook _TtC19AdsPlatform_AdsImpl14AdsServiceImpl
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC29AdsNowPlaying_InStreamAdsImpl18InStreamAdsService
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC29AdsNowPlaying_EmbeddedNPVImpl22EmbeddedNPVServiceImpl
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC36AdsStandalone_LeavebehindAdsBaseImpl25LeavebehindAdsBaseService
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC36AdsStandalone_LeavebehindAdsBaseImpl33LeavebehindAdsBaseInternalService
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC35AdsEmbedded_AdsSponsoredContextImpl30AdsSponsoredContextServiceImpl
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC48AdsEmbedded_AdsSponsoredContextNPBAttachmentImpl43AdsSponsoredContextNPBAttachmentServiceImpl
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC42AdsEmbedded_AdsSponsoredPlaylistHeaderImpl37AdsSponsoredPlaylistHeaderServiceImpl
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+%hook _TtC20NativeAds_LoggerImpl26NativeAdsLoggerServiceImpl
+- (void)load { SGAdBlockCountOne(@"Ad services"); }
+%end
+
+%hook _TtC18AdsPlatform_ECMKit37AdsSponsoredPlaylistHeaderCentralView
+- (void)didMoveToSuperview {
+ %orig;
+ takeDown((UIView *)self);
+}
+%end
+
+%end
+
+%group Upsells
+
+%hook _TtC19Upsells_ServiceImpl18UpsellsServiceImpl
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC31PremiumUpsell_UpsellServiceImpl17UpsellServiceImpl
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC45ReinventFree_ContextualUpsellPremiumPromoImpl39ContextualUpsellPremiumPromoServiceImpl
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC40Referrals_ReferralsUpsellCardElementImpl37ReferralsUpsellCardElementServiceImpl
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC31ReinventFree_DownloadUpsellImpl21DownloadUpsellService
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC28Jam_FreeHostedJamsUpsellImpl31FreeHostedJamsUpsellServiceImpl
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC30Jam_FreeUserSkipUpsellPageImpl29FreeUserSkipUpsellPageService
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+%hook _TtC38Jam_FreeUserShuffleUpsellSheetPageImpl37FreeUserShuffleUpsellSheetPageService
+- (void)load { SGAdBlockCountOne(@"Upsell services"); }
+%end
+
+%hook _TtC13Upsells_UIKit29SelfLoadingUpsellBannerUIView
+- (void)didMoveToSuperview {
+ %orig;
+ takeDown((UIView *)self);
+}
+%end
+
+%end
+
+%ctor {
+ if (SGHidden(SGKeyHideAds)) {
+ %init(Ads);
+ SGRequireClasses(@[
+ @"_TtC19AdsPlatform_AdsImpl14AdsServiceImpl",
+ @"_TtC29AdsNowPlaying_InStreamAdsImpl18InStreamAdsService",
+ @"_TtC29AdsNowPlaying_EmbeddedNPVImpl22EmbeddedNPVServiceImpl",
+ @"_TtC36AdsStandalone_LeavebehindAdsBaseImpl25LeavebehindAdsBaseService",
+ @"_TtC36AdsStandalone_LeavebehindAdsBaseImpl33LeavebehindAdsBaseInternalService",
+ @"_TtC35AdsEmbedded_AdsSponsoredContextImpl30AdsSponsoredContextServiceImpl",
+ @"_TtC48AdsEmbedded_AdsSponsoredContextNPBAttachmentImpl43AdsSponsoredContextNPBAttachmentServiceImpl",
+ @"_TtC42AdsEmbedded_AdsSponsoredPlaylistHeaderImpl37AdsSponsoredPlaylistHeaderServiceImpl",
+ @"_TtC20NativeAds_LoggerImpl26NativeAdsLoggerServiceImpl",
+ @"_TtC18AdsPlatform_ECMKit37AdsSponsoredPlaylistHeaderCentralView",
+ ]);
+ }
+ if (SGHidden(SGKeyHideUpsells)) {
+ %init(Upsells);
+ SGRequireClasses(@[
+ @"_TtC19Upsells_ServiceImpl18UpsellsServiceImpl",
+ @"_TtC31PremiumUpsell_UpsellServiceImpl17UpsellServiceImpl",
+ @"_TtC45ReinventFree_ContextualUpsellPremiumPromoImpl39ContextualUpsellPremiumPromoServiceImpl",
+ @"_TtC40Referrals_ReferralsUpsellCardElementImpl37ReferralsUpsellCardElementServiceImpl",
+ @"_TtC31ReinventFree_DownloadUpsellImpl21DownloadUpsellService",
+ @"_TtC28Jam_FreeHostedJamsUpsellImpl31FreeHostedJamsUpsellServiceImpl",
+ @"_TtC30Jam_FreeUserSkipUpsellPageImpl29FreeUserSkipUpsellPageService",
+ @"_TtC38Jam_FreeUserShuffleUpsellSheetPageImpl37FreeUserShuffleUpsellSheetPageService",
+ @"_TtC13Upsells_UIKit29SelfLoadingUpsellBannerUIView",
+ ]);
+ }
+}
diff --git a/tweak/Sources/Features/AdBlock/Feeds.m b/tweak/Sources/Features/AdBlock/Feeds.m
new file mode 100644
index 00000000..e38d30bb
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/Feeds.m
@@ -0,0 +1,65 @@
+// Ad sections taken out of the feeds Home, Search and the page under the player are built from
+// (EeveeSpotify's BrowsitaSectionStripper). A feed is one container field of sections, each a
+// field 1 message; a section goes when its bytes name an ad, or a promotion and a surface for it.
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+#import "Protobuf.h"
+
+static const char *const hardMarkers[] = {
+ "spotify:ad:", "ad-formats", "advertisement", "brand-ad", "sponsored", "marquee", "promoted", "home-ads",
+ "adsproduct", "leavebehind", "leave-behind", "premium-upsell", "premium_upsell", "premiumupsell",
+ "referralsupsellcard",
+};
+static const char *const intentMarkers[] = {
+ "upsell", "upgrade", "subscribe", "premium", "promo", "promotion", "marketing", "offer",
+};
+static const char *const surfaceMarkers[] = {
+ "banner", "card", "popup", "pop-up", "sheet", "interstitial", "promotion", "promo",
+};
+// The filter chips of Search carry "browse" and "chip" in their ids and are never the ad.
+static const char *const keepMarkers[] = {"filter", "chip", "pillar", "browse:chips"};
+
+#define COUNT(list) (sizeof(list) / sizeof(list[0]))
+
+// ASCII, case-insensitive; the markers are lower case.
+static BOOL contains(NSData *data, const char *needle) {
+ const uint8_t *bytes = data.bytes;
+ size_t length = data.length, n = strlen(needle);
+ for (size_t i = 0; i + n <= length; i++) {
+ size_t k = 0;
+ while (k < n && tolower(bytes[i + k]) == needle[k]) k++;
+ if (k == n) return YES;
+ }
+ return NO;
+}
+
+static BOOL containsAny(NSData *data, const char *const markers[], size_t count) {
+ for (size_t i = 0; i < count; i++) {
+ if (contains(data, markers[i])) return YES;
+ }
+ return NO;
+}
+
+static BOOL adSection(NSData *section) {
+ if (containsAny(section, hardMarkers, COUNT(hardMarkers))) return YES;
+ if (containsAny(section, keepMarkers, COUNT(keepMarkers))) return NO;
+ return containsAny(section, intentMarkers, COUNT(intentMarkers)) && containsAny(section, surfaceMarkers, COUNT(surfaceMarkers));
+}
+
+NSData *SGStripFeed(NSData *body) {
+ NSMutableArray<SGPBField *> *fields = SGPBParse(body);
+ SGPBField *container = fields.firstObject;
+ if (container.number != 1 || container.wire != 2) return nil;
+ NSMutableArray<SGPBField *> *sections = SGPBParse(container.payload);
+ if (!sections) return nil;
+ NSMutableArray<SGPBField *> *kept = [NSMutableArray array];
+ for (SGPBField *section in sections) {
+ if (section.number != 1 || section.wire != 2) return nil;
+ if (adSection(section.payload)) SGAdBlockCountOne(@"Feed sections");
+ else [kept addObject:section];
+ }
+ if (kept.count == sections.count) return nil;
+ SGLog(@"dropped %lu of %lu feed sections", (unsigned long)(sections.count - kept.count), (unsigned long)sections.count);
+ container.payload = SGPBSerialize(kept);
+ return SGPBSerialize(fields);
+}
diff --git a/tweak/Sources/Features/AdBlock/Premium.m b/tweak/Sources/Features/AdBlock/Premium.m
new file mode 100644
index 00000000..356f44e3
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/Premium.m
@@ -0,0 +1,421 @@
+// Pretend to be Premium: the UCS response, which carries the account's product state and its remote
+// config, rewritten as it arrives. The attributes and the flag rules are EeveeSpotify's. Offline,
+// audio quality and the social session attributes are left alone: the server still decides those,
+// and a spoofed one only shows UI the request behind it will fail.
+//
+// UcsResponse: 1 ResolveResponse { 1 ResolveConfiguration { 3 repeated AssignedValue } },
+// 3 AccountAttributesResponse { 1 repeated entry { 1 key, 2 AccountAttribute { 2 bool, 4 string } } }
+// AssignedValue: 1 { 1 scope, 2 name }, 3 BoolValue { 1 }, 4 IntValue { 1 }, 5 EnumValue { 1 }
+// A customize body is CustomizeMessage { 1 UcsResponse }; bootstrap wraps that in 2 { 1 { 1 { it } } }.
+#import "Core/SGCore.h"
+#import "AdBlock.h"
+#import "Protobuf.h"
+
+#pragma mark - account attributes
+
+// A string goes in as one, a number as a bool.
+static NSDictionary<NSString *, id> *forcedAttributes(void) {
+ NSISO8601DateFormatter *iso = [NSISO8601DateFormatter new];
+ iso.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
+ NSString *yearOn = [iso stringFromDate:[NSCalendar.currentCalendar dateByAddingUnit:NSCalendarUnitYear value:1 toDate:NSDate.date options:0]];
+ return @{
+ @"ads": @NO,
+ @"ab-ad-player-targeting": @"0",
+ @"allow-advertising-id-transmission": @NO,
+ @"restrict-advertising-id-transmission": @YES,
+ @"can_use_superbird": @YES,
+ @"enable-crossfade-product-state": @"1",
+ @"enable-gapless-product-state": @"1",
+ @"catalogue": @"premium",
+ @"financial-product": @"pr:premium,tc:0",
+ @"is-eligible-premium-unboxing": @YES,
+ @"name": @"Spotify Premium",
+ @"nft-disabled": @"1",
+ @"on-demand": @YES,
+ @"payments-initial-campaign": @"default",
+ @"player-license": @"premium",
+ @"player-license-v2": @"premium",
+ @"product-expiry": yearOn,
+ @"shuffle-eligible": @YES,
+ @"streaming-rules": @"",
+ @"subscription-enddate": yearOn,
+ @"type": @"premium",
+ @"unrestricted": @YES,
+ @"high-bitrate": @YES,
+ @"loudness-levels": @"1:-5.0,0.0,3.0:-2.0",
+ @"pick-and-shuffle": @NO,
+ @"mixing-tools": @"EDIT",
+ @"your-library-tags": @YES,
+ @"libspotify": @YES,
+ @"mobile": @YES,
+ };
+}
+
+// Attributes that would have the client validate the state against the server, or offer a trial.
+static NSString *const strippedAttributes[] = {
+ @"payment-state", @"last-premium-activation-date", @"on-demand-trial", @"on-demand-trial-in-progress",
+ @"smart-shuffle", @"at-signal", @"feature-set-id-masked", @"strider-key", @"is-eligible-for-trial",
+ @"is-eligible-for-upsell", @"upsell-state", @"ad-session-persistence", @"ad-formats-preroll-video",
+};
+
+static BOOL stripped(NSString *key) {
+ if ([key hasPrefix:@"is-premium-eligible"]) return YES;
+ for (size_t i = 0; i < sizeof(strippedAttributes) / sizeof(strippedAttributes[0]); i++) {
+ if ([key isEqualToString:strippedAttributes[i]]) return YES;
+ }
+ return NO;
+}
+
+static SGPBField *attributeEntry(NSString *key, id value) {
+ SGPBField *attribute = [value isKindOfClass:NSString.class] ? SGPBString(4, value) : SGPBVarint(2, [value boolValue]);
+ return SGPBBytes(1, SGPBSerialize(@[SGPBString(1, key), SGPBBytes(2, SGPBSerialize(@[attribute]))]));
+}
+
+static NSData *patchAttributes(NSData *response) {
+ NSMutableArray<SGPBField *> *fields = SGPBParse(response);
+ if (!fields) return nil;
+ NSDictionary<NSString *, id> *forced = forcedAttributes();
+ NSMutableArray<SGPBField *> *out = [NSMutableArray array];
+ NSMutableSet<NSString *> *seen = [NSMutableSet set];
+ for (SGPBField *field in fields) {
+ NSString *key = field.number == 1 && field.wire == 2 ? SGPBText(SGPBFirst(SGPBParse(field.payload), 1)) : nil;
+ if (!key || (!forced[key] && !stripped(key))) {
+ [out addObject:field];
+ continue;
+ }
+ if (!forced[key]) continue;
+ [seen addObject:key];
+ [out addObject:attributeEntry(key, forced[key])];
+ }
+ for (NSString *key in forced) {
+ if (![seen containsObject:key]) [out addObject:attributeEntry(key, forced[key])];
+ }
+ return SGPBSerialize(out);
+}
+
+#pragma mark - remote config
+
+typedef NS_ENUM(NSInteger, SGRuleKind) { SGRuleRemove, SGRuleSet, SGRuleForce, SGRuleEnum };
+// A NULL scope or name matches any. Set changes a value that is there, Force adds it when it is not.
+typedef struct { const char *scope, *name; SGRuleKind kind; BOOL on; const char *text; } SGRule;
+
+static const SGRule rules[] = {
+ {NULL, "enable_common_capping", SGRuleRemove, NO, NULL},
+ {NULL, "enable_pns_common_capping", SGRuleRemove, NO, NULL},
+ {NULL, "enable_pick_and_shuffle_common_capping", SGRuleRemove, NO, NULL},
+ {NULL, "enable_pick_and_shuffle_dynamic_cap", SGRuleRemove, NO, NULL},
+ {NULL, "pick_and_shuffle_timecap", SGRuleRemove, NO, NULL},
+ {"ios-feature-queue", NULL, SGRuleRemove, NO, NULL},
+ {NULL, "enable_free_on_demand_experiment", SGRuleRemove, NO, NULL},
+ {NULL, "enable_free_on_demand_context_menu_experiment", SGRuleRemove, NO, NULL},
+ {NULL, "enable_mft_plus_queue", SGRuleRemove, NO, NULL},
+ {NULL, "enable_mft_plus_extended_queue", SGRuleRemove, NO, NULL},
+ {NULL, "enable_playback_timeout_service", SGRuleSet, NO, NULL},
+ {NULL, "enable_playback_timeout_error_ui", SGRuleSet, NO, NULL},
+ {NULL, "playback_timeout_action", SGRuleEnum, NO, "Nothing"},
+ {NULL, "is_remove_from_queue_enabled_for_mft_plus", SGRuleRemove, NO, NULL},
+ {NULL, "is_reordering_for_mft_plus_allowed", SGRuleRemove, NO, NULL},
+ {NULL, "ads", SGRuleSet, NO, NULL},
+ {NULL, "ad_metadata", SGRuleRemove, NO, NULL},
+ {NULL, "ad_slots", SGRuleRemove, NO, NULL},
+ {NULL, "enable_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_audio_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_display_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_video_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_premium_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_upsell", SGRuleSet, NO, NULL},
+ {NULL, "show_upsell", SGRuleSet, NO, NULL},
+ {NULL, "show_premium_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_campaigns", SGRuleSet, NO, NULL},
+ {NULL, "enable_promotions", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_upsell", SGRuleSet, NO, NULL},
+ {"ios-feature-shuffletoggleupsell", "is_enabled_pt2", SGRuleForce, NO, NULL},
+ {"ios-feature-shuffletoggleupsell", "linear_upsell_new_style_experiment_enabled", SGRuleForce, NO, NULL},
+ {"ios-feature-shuffletoggleupsell", "play_modes_upsell_new_style_experiment_enabled", SGRuleForce, NO, NULL},
+ {"ios-jam-freeusershuffleupsellsheetpage-impl", "free_user_shuffle_upsell_sheet_enabled", SGRuleForce, NO, NULL},
+ {"ios-jam-freeuserskipupsellpage-impl", "free_user_skip_upsell_sheet_enabled", SGRuleForce, NO, NULL},
+ {"ios-jam-freehostedjamsupsell-impl", "free_hosted_jams_upsell_enabled", SGRuleForce, NO, NULL},
+ {"ios-reinventfree-contextualupsellpremiumpromo-impl", "is_promo_cta_enabled", SGRuleForce, NO, NULL},
+ {"ios-reinventfree-contextualupsellpremiumpromo-impl", "show_time_cap_upsell_with_premium_badge", SGRuleForce, NO, NULL},
+ {"ios-reinventfree-controllerui-impl", "enable_video_time_cap_upsell", SGRuleForce, NO, NULL},
+ {"ios-reinventfree-controllerui-impl", "enable_video_time_cap_upsell_on_search", SGRuleForce, NO, NULL},
+ {"ios-reinventfree-timecappivot-impl", "music_video_upsell_enabled", SGRuleForce, NO, NULL},
+ {"ios-settings-mediaqualitypageplugin-impl", "is_gbb_upsell_enabled", SGRuleForce, NO, NULL},
+ {"ios-settings-mediaqualitypageplugin-impl", "should_show_pigeon_upsell", SGRuleForce, NO, NULL},
+ {"ios-system-listeningparties", "preview_ended_upsell_enabled", SGRuleForce, NO, NULL},
+ {NULL, "enable_now_playing_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_now_playing_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_now_playing_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_now_playing_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_now_playing_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_now_playing_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_now_playing_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_artist_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_playlist_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_album_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_library_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_audiobook_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_banner_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_banner_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_podcast_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_content", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_playlists", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_sessions", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_stories", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_videos", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_artist", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_artists", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_album", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_albums", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_track", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_tracks", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_show", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_shows", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_episode", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_episodes", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_audiobook", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_audiobooks", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_podcast", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_podcasts", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search_results", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_home", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_home_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_home_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_now_playing", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_now_playing_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_now_playing_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_artist_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_artist_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_playlist_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_playlist_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_album_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_album_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_library_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_library_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_audiobook_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_audiobook_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_podcast_banner", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_podcast_banners", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_home_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_home_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_now_playing_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_now_playing_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_artist_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_artist_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_playlist_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_playlist_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_album_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_album_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_library_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_library_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_audiobook_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_audiobook_sponsored_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_podcast_sponsored_ad", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_podcast_sponsored_ads", SGRuleSet, NO, NULL},
+ {"ios-ad-on-app-open", NULL, SGRuleRemove, NO, NULL},
+ {"ios-feature-adonappopen", NULL, SGRuleRemove, NO, NULL},
+ {"ios-feature-adonappopen", "enabled", SGRuleSet, NO, NULL},
+ {"ios-feature-adonappopen", "background_refresh_frequency_seconds", SGRuleSet, NO, NULL},
+ {NULL, "is_ad_on_app_open_enabled", SGRuleSet, NO, NULL},
+ {NULL, "ad_on_app_open_enabled", SGRuleSet, NO, NULL},
+ {NULL, "adonappopen_enabled", SGRuleSet, NO, NULL},
+ {NULL, "marquee", SGRuleRemove, NO, NULL},
+ {"ios-feature-marquee", NULL, SGRuleRemove, NO, NULL},
+ {NULL, "leavebehindadsbase", SGRuleRemove, NO, NULL},
+ {"ios-feature-leavebehindadsbase", NULL, SGRuleRemove, NO, NULL},
+ {"ios-nowplaying-scroll-impl", "unified_leavebehind_npv_scroll_music_enabled", SGRuleForce, NO, NULL},
+ {"ios-nowplaying-scroll-impl", "unified_leavebehind_npv_scroll_podcast_enabled", SGRuleForce, NO, NULL},
+ {"ios-feature-embeddedplaylist", "use_unified_leavebehind_fetch", SGRuleForce, NO, NULL},
+ {"ios-adsnowplaying-embeddednpv-impl", "foreground_enabled", SGRuleForce, NO, NULL},
+ {"ios-adsnowplaying-embeddednpv-impl", "music_track_change_enabled", SGRuleForce, NO, NULL},
+ {"ios-adsnowplaying-embeddednpv-impl", "enable_ads_on_podcast", SGRuleForce, NO, NULL},
+ {"ios-feature-instreamads", NULL, SGRuleRemove, NO, NULL},
+ {"ios-adsembedded-embeddedctaelements-impl", NULL, SGRuleRemove, NO, NULL},
+ {"ios-adsnowplaying-embeddednpv-impl", NULL, SGRuleRemove, NO, NULL},
+ {"ios-adsplatform-elementimpl", NULL, SGRuleRemove, NO, NULL},
+ {"ios-system-adssponsoredcontext", NULL, SGRuleRemove, NO, NULL},
+ {"ios-feature-adsbase", "enable_ads_connect_state_observer", SGRuleSet, NO, NULL},
+ {"ios-feature-adsbase", "enable_minimal_preroll_management", SGRuleSet, NO, NULL},
+ {"ios-feature-adsbase", "enable_swift_ads_base_movement_logger", SGRuleSet, NO, NULL},
+ {"ios-feature-adsswift", NULL, SGRuleRemove, NO, NULL},
+ {"ios-feature-adsnowplayingui", "embedded_npv_video_show_with_canvas", SGRuleForce, NO, NULL},
+ {"ios-feature-adssponsoredcontext", "sponsored_context_mismatch_aderror_enabled", SGRuleSet, NO, NULL},
+ {"ios-feature-adssponsoredcontext", "sponsored_playlist_v2_enabled", SGRuleSet, NO, NULL},
+ {"ios-feature-adssponsoredcontextnpbattachment", "sponsored_npb_slot_fetch_enabled", SGRuleSet, NO, NULL},
+ {"ios-feature-adsidentitytracking", NULL, SGRuleRemove, NO, NULL},
+ {NULL, "enable_popups", SGRuleSet, NO, NULL},
+ {NULL, "enable_leave_behind_ads_card_element", SGRuleSet, NO, NULL},
+ {NULL, "music_npv_leavebehinds_enabled", SGRuleSet, NO, NULL},
+ {NULL, "enable_ads_on_podcast", SGRuleSet, NO, NULL},
+ {NULL, "enable_display_element", SGRuleSet, NO, NULL},
+ {NULL, "enable_video_element", SGRuleSet, NO, NULL},
+ {NULL, "is_promo_cta_enabled", SGRuleSet, NO, NULL},
+ {NULL, "show_time_cap_upsell_with_premium_badge", SGRuleSet, NO, NULL},
+ {NULL, "enable_video_time_cap_upsell", SGRuleSet, NO, NULL},
+ {NULL, "enable_video_time_cap_upsell_on_search", SGRuleSet, NO, NULL},
+ {NULL, "music_video_upsell_enabled", SGRuleSet, NO, NULL},
+ {NULL, "is_gbb_upsell_enabled", SGRuleSet, NO, NULL},
+ {NULL, "should_show_pigeon_upsell", SGRuleSet, NO, NULL},
+ {NULL, "disable_suggested_tracks_upsell", SGRuleSet, YES, NULL},
+ {NULL, "is_enabled_pt2", SGRuleSet, NO, NULL},
+ {NULL, "show_skip_button_during_skippable_ads", SGRuleSet, YES, NULL},
+ {NULL, "sponsored_playlist_v2_header_dismissible", SGRuleSet, YES, NULL},
+ {NULL, "use_mock_sponsorship_endpoint", SGRuleSet, NO, NULL},
+ {NULL, "enable_popup", SGRuleSet, NO, NULL},
+ {NULL, "show_popups", SGRuleSet, NO, NULL},
+ {NULL, "show_popup", SGRuleSet, NO, NULL},
+ {NULL, "enable_interstitials", SGRuleSet, NO, NULL},
+ {NULL, "enable_interstitial", SGRuleSet, NO, NULL},
+ {NULL, "enable_overlays", SGRuleSet, NO, NULL},
+ {NULL, "enable_overlay", SGRuleSet, NO, NULL},
+ {NULL, "enable_promotions_on_home", SGRuleSet, NO, NULL},
+ {NULL, "enable_promotions_on_search", SGRuleSet, NO, NULL},
+ {NULL, "enable_search_page_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_home_page_ads", SGRuleSet, NO, NULL},
+ {NULL, "enable_billboard", SGRuleSet, NO, NULL},
+ {NULL, "enable_billboards", SGRuleSet, NO, NULL},
+ {NULL, "enable_audio_ads_player", SGRuleSet, NO, NULL},
+ {NULL, "enable_display_ads_player", SGRuleSet, NO, NULL},
+ {NULL, "enable_video_ads_player", SGRuleSet, NO, NULL},
+ {NULL, "enable_audio_ads_player_v2", SGRuleSet, NO, NULL},
+ {NULL, "enable_display_ads_player_v2", SGRuleSet, NO, NULL},
+ {NULL, "enable_video_ads_player_v2", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_search_results_v2", SGRuleSet, NO, NULL},
+ {NULL, "enable_sponsored_home_results_v2", SGRuleSet, NO, NULL},
+ {NULL, "should_nova_scroll_use_scrollsita", SGRuleRemove, NO, NULL},
+ {"ios-sociallistening-configuration-impl", "premium_gated_start_jam_buttons_enabled", SGRuleForce, NO, NULL},
+};
+static const size_t ruleCount = sizeof(rules) / sizeof(rules[0]);
+
+static BOOL ruleMatches(const SGRule *rule, NSString *scope, NSString *name) {
+ if (rule->scope && ![scope isEqualToString:@(rule->scope)]) return NO;
+ return !rule->name || [name isEqualToString:@(rule->name)];
+}
+
+// A false BoolValue is an empty message, as protobuf writes it.
+static NSData *boolValue(BOOL on) {
+ return on ? SGPBSerialize(@[SGPBVarint(1, 1)]) : [NSData data];
+}
+
+static void setValue(NSMutableArray<SGPBField *> *value, SGPBField *replacement) {
+ [value filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(SGPBField *field, NSDictionary *bindings) {
+ return field.number < 3 || field.number > 5;
+ }]];
+ [value addObject:replacement];
+}
+
+static NSData *patchConfiguration(NSData *configuration) {
+ NSMutableArray<SGPBField *> *fields = SGPBParse(configuration);
+ if (!fields) return nil;
+ NSMutableArray<SGPBField *> *out = [NSMutableArray array];
+ NSMutableSet<NSString *> *present = [NSMutableSet set];
+ for (SGPBField *field in fields) {
+ NSMutableArray<SGPBField *> *value = field.number == 3 && field.wire == 2 ? SGPBParse(field.payload) : nil;
+ SGPBField *identifier = SGPBFirst(value, 1);
+ NSArray<SGPBField *> *parts = identifier ? SGPBParse(identifier.payload) : nil;
+ if (!parts) {
+ [out addObject:field];
+ continue;
+ }
+ NSString *scope = SGPBText(SGPBFirst(parts, 1)) ?: @"", *name = SGPBText(SGPBFirst(parts, 2)) ?: @"";
+ BOOL removed = NO;
+ for (size_t i = 0; i < ruleCount && !removed; i++) {
+ if (!ruleMatches(&rules[i], scope, name)) continue;
+ switch (rules[i].kind) {
+ case SGRuleRemove: removed = YES; break;
+ case SGRuleSet:
+ case SGRuleForce: setValue(value, SGPBBytes(3, boolValue(rules[i].on))); break;
+ case SGRuleEnum: setValue(value, SGPBBytes(5, SGPBSerialize(@[SGPBString(1, @(rules[i].text))]))); break;
+ }
+ }
+ if (removed) continue;
+ [present addObject:[NSString stringWithFormat:@"%@.%@", scope, name]];
+ field.payload = SGPBSerialize(value);
+ [out addObject:field];
+ }
+ for (size_t i = 0; i < ruleCount; i++) {
+ if (rules[i].kind != SGRuleForce || !rules[i].scope || !rules[i].name) continue;
+ if ([present containsObject:[NSString stringWithFormat:@"%s.%s", rules[i].scope, rules[i].name]]) continue;
+ NSData *identifier = SGPBSerialize(@[SGPBString(1, @(rules[i].scope)), SGPBString(2, @(rules[i].name))]);
+ [out addObject:SGPBBytes(3, SGPBSerialize(@[SGPBBytes(1, identifier), SGPBBytes(3, boolValue(rules[i].on))]))];
+ }
+ return SGPBSerialize(out);
+}
+
+#pragma mark - the response
+
+static NSData *patchUcs(NSData *ucs) {
+ NSMutableArray<SGPBField *> *fields = SGPBParse(ucs);
+ if (!fields) return nil;
+ SGPBField *resolve = SGPBFirst(fields, 1);
+ if (resolve.wire == 2) {
+ NSData *edited = SGPBEdit(resolve.payload, @[@1], ^NSData *(NSData *configuration) {
+ return patchConfiguration(configuration);
+ });
+ if (edited) resolve.payload = edited;
+ }
+ SGPBField *attributes = SGPBFirst(fields, 3);
+ if (!attributes) [fields addObject:(attributes = SGPBBytes(3, nil))];
+ if (attributes.wire == 2) attributes.payload = patchAttributes(attributes.payload) ?: attributes.payload;
+ return SGPBSerialize(fields);
+}
+
+NSData *SGPatchCustomize(NSData *body) {
+ return SGPBEdit(body, @[@1], ^NSData *(NSData *ucs) { return patchUcs(ucs); });
+}
+
+NSData *SGPatchBootstrap(NSData *body) {
+ return SGPBEdit(body, @[@2, @1, @1, @1], ^NSData *(NSData *ucs) { return patchUcs(ucs); });
+}
diff --git a/tweak/Sources/Features/AdBlock/Protobuf.h b/tweak/Sources/Features/AdBlock/Protobuf.h
new file mode 100644
index 00000000..9dbda88c
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/Protobuf.h
@@ -0,0 +1,22 @@
+// The protobuf wire format, just enough to walk into a message, change a few fields and write it
+// back with everything else untouched. Premium.m and Feeds.m read Spotify's responses through it.
+#import <Foundation/Foundation.h>
+
+// A field as it sits on the wire: a varint carries its value, everything else its raw payload.
+@interface SGPBField : NSObject
+@property (nonatomic) uint32_t number;
+@property (nonatomic) uint8_t wire; // 0 varint, 1 fixed64, 2 length-delimited, 5 fixed32
+@property (nonatomic) uint64_t varint;
+@property (nonatomic, copy) NSData *payload;
+@end
+
+NSMutableArray<SGPBField *> *SGPBParse(NSData *data); // nil when the bytes are not a message
+NSData *SGPBSerialize(NSArray<SGPBField *> *fields);
+SGPBField *SGPBFirst(NSArray<SGPBField *> *fields, uint32_t number);
+SGPBField *SGPBVarint(uint32_t number, uint64_t value);
+SGPBField *SGPBBytes(uint32_t number, NSData *payload);
+SGPBField *SGPBString(uint32_t number, NSString *text);
+NSString *SGPBText(SGPBField *field); // the payload read as UTF-8, nil for any other field
+// The message at `path` (field numbers, outermost first) handed to `edit`, whose result takes its
+// place; nil when a field of the path is missing, the bytes do not parse or `edit` returns nil.
+NSData *SGPBEdit(NSData *message, NSArray<NSNumber *> *path, NSData *(^edit)(NSData *inner));
diff --git a/tweak/Sources/Features/AdBlock/Protobuf.m b/tweak/Sources/Features/AdBlock/Protobuf.m
new file mode 100644
index 00000000..178d4478
--- /dev/null
+++ b/tweak/Sources/Features/AdBlock/Protobuf.m
@@ -0,0 +1,118 @@
+#import "Protobuf.h"
+
+@implementation SGPBField
+@end
+
+static BOOL readVarint(const uint8_t *bytes, NSUInteger length, NSUInteger *at, uint64_t *out) {
+ uint64_t value = 0;
+ for (int shift = 0; *at < length && shift < 64; shift += 7) {
+ uint8_t byte = bytes[(*at)++];
+ value |= (uint64_t)(byte & 0x7f) << shift;
+ if (!(byte & 0x80)) {
+ *out = value;
+ return YES;
+ }
+ }
+ return NO;
+}
+
+static void appendVarint(NSMutableData *data, uint64_t value) {
+ while (value >= 0x80) {
+ uint8_t byte = (value & 0x7f) | 0x80;
+ [data appendBytes:&byte length:1];
+ value >>= 7;
+ }
+ uint8_t byte = value;
+ [data appendBytes:&byte length:1];
+}
+
+NSMutableArray<SGPBField *> *SGPBParse(NSData *data) {
+ const uint8_t *bytes = data.bytes;
+ NSUInteger length = data.length, at = 0;
+ NSMutableArray<SGPBField *> *fields = [NSMutableArray array];
+ while (at < length) {
+ uint64_t key, value;
+ if (!readVarint(bytes, length, &at, &key) || !(key >> 3)) return nil;
+ SGPBField *field = [SGPBField new];
+ field.number = (uint32_t)(key >> 3);
+ field.wire = key & 7;
+ NSUInteger size;
+ switch (field.wire) {
+ case 0:
+ if (!readVarint(bytes, length, &at, &value)) return nil;
+ field.varint = value;
+ break;
+ case 1: case 5:
+ size = field.wire == 1 ? 8 : 4;
+ if (at + size > length) return nil;
+ field.payload = [NSData dataWithBytes:bytes + at length:size];
+ at += size;
+ break;
+ case 2:
+ if (!readVarint(bytes, length, &at, &value) || at + value > length) return nil;
+ field.payload = [NSData dataWithBytes:bytes + at length:(NSUInteger)value];
+ at += value;
+ break;
+ default:
+ return nil;
+ }
+ [fields addObject:field];
+ }
+ return fields;
+}
+
+NSData *SGPBSerialize(NSArray<SGPBField *> *fields) {
+ NSMutableData *data = [NSMutableData data];
+ for (SGPBField *field in fields) {
+ appendVarint(data, ((uint64_t)field.number << 3) | field.wire);
+ if (field.wire == 0) {
+ appendVarint(data, field.varint);
+ continue;
+ }
+ if (field.wire == 2) appendVarint(data, field.payload.length);
+ [data appendData:field.payload];
+ }
+ return data;
+}
+
+SGPBField *SGPBFirst(NSArray<SGPBField *> *fields, uint32_t number) {
+ for (SGPBField *field in fields) {
+ if (field.number == number) return field;
+ }
+ return nil;
+}
+
+SGPBField *SGPBVarint(uint32_t number, uint64_t value) {
+ SGPBField *field = [SGPBField new];
+ field.number = number;
+ field.varint = value;
+ return field;
+}
+
+SGPBField *SGPBBytes(uint32_t number, NSData *payload) {
+ SGPBField *field = [SGPBField new];
+ field.number = number;
+ field.wire = 2;
+ field.payload = payload ?: [NSData data];
+ return field;
+}
+
+SGPBField *SGPBString(uint32_t number, NSString *text) {
+ return SGPBBytes(number, [text dataUsingEncoding:NSUTF8StringEncoding]);
+}
+
+NSString *SGPBText(SGPBField *field) {
+ if (!field || field.wire != 2) return nil;
+ return [[NSString alloc] initWithData:field.payload encoding:NSUTF8StringEncoding];
+}
+
+NSData *SGPBEdit(NSData *message, NSArray<NSNumber *> *path, NSData *(^edit)(NSData *inner)) {
+ if (!path.count) return edit(message);
+ NSMutableArray<SGPBField *> *fields = SGPBParse(message);
+ SGPBField *field = SGPBFirst(fields, path.firstObject.unsignedIntValue);
+ if (!field || field.wire != 2) return nil;
+ NSData *inner = SGPBEdit(field.payload, [path subarrayWithRange:NSMakeRange(1, path.count - 1)], edit);
+ if (!inner) return nil;
+ field.payload = inner;
+ return SGPBSerialize(fields);
+}
diff --git a/tweak/Sources/Features/Appearance/SearchField.x b/tweak/Sources/Features/Appearance/SearchField.x
index 511c2036..edabf551 100644
--- a/tweak/Sources/Features/Appearance/SearchField.x
+++ b/tweak/Sources/Features/Appearance/SearchField.x
@@ -55,6 +55,45 @@ static void traceField(UIView *button, NSString *when) {
dim ? NSStringFromClass(dim.class) : @"nothing");
}
+// traceField only says what the field looked like at a layout pass, and the second it is invisible
+// for holds no layout pass at all: coming back from the full screen search the last pass before it
+// lands is 1077ms earlier (a log of three trips in and out). So the field is put on a clock of its
+// own as well, sampled every 50ms for the two seconds after it comes back into a window, which is
+// the window the glitch lives in. Debug builds only, like the rest of the tracing.
+static void sampleField(__weak UIView *weakButton, int step) {
+ UIView *button = weakButton;
+ if (!button || step > 40) return;
+ UIWindow *window = button.window;
+ UIView *dim = nil;
+ for (UIView *v = button; v && !dim; v = v.superview) {
+ if (v.hidden || v.alpha < 0.99) dim = v;
+ }
+ UIView *pane = nil;
+ for (UIView *sub in button.subviews) {
+ if ([sub isKindOfClass:UIVisualEffectView.class]) pane = sub;
+ }
+ CGColorRef fill = button.layer.backgroundColor;
+ SGLog(@"search field +%4dms: window %d, in window %@, alpha %.2f hidden %d, dimmed by %@, pane %@ alpha %.2f, fill alpha %.2f, radius %.1f",
+ step * 50, window != nil,
+ NSStringFromCGRect([button convertRect:button.bounds toView:window]),
+ button.alpha, button.hidden, dim ? NSStringFromClass(dim.class) : @"nothing",
+ pane ? @"attached" : @"missing", pane ? pane.alpha : -1,
+ fill ? CGColorGetAlpha(fill) : -1, button.layer.cornerRadius);
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ sampleField(weakButton, step + 1);
+ });
+}
+
+// One burst per arrival, so three trips in and out read as three bursts rather than three overlaid.
+static void traceFieldArriving(UIView *button) {
+ if (!SGIsDebugBuild() || !button.window) return;
+ static NSTimeInterval last;
+ NSTimeInterval now = NSDate.timeIntervalSinceReferenceDate;
+ if (now - last < 2.5) return;
+ last = now;
+ sampleField(button, 0);
+}
+
static void styleSearchField(UIView *button) {
if (!SGEnabled(SGKeySearchField)) return;
CGSize size = button.bounds.size;
@@ -84,7 +123,10 @@ static void styleSearchField(UIView *button) {
// Back from the full screen search the field is styled before it draws, not a layout pass later.
- (void)didMoveToWindow {
%orig;
- if (isSearchField((UIView *)self)) traceField((UIView *)self, @"moved");
+ if (isSearchField((UIView *)self)) {
+ traceField((UIView *)self, @"moved");
+ traceFieldArriving((UIView *)self);
+ }
styleSearchField((UIView *)self);
}
// Spotify builds the field's content again when the page comes back, which can take the pane out
diff --git a/tweak/Sources/Features/Flags/FlagPages.m b/tweak/Sources/Features/Flags/FlagPages.m
index cc022c48..12d4f4a2 100644
--- a/tweak/Sources/Features/Flags/FlagPages.m
+++ b/tweak/Sources/Features/Flags/FlagPages.m
@@ -1,6 +1,7 @@
// Pages that list Spotify's flags by topic; every row forces one flag.
#import "Settings/SGModPage.h"
#import "Flags.h"
+#import "Features/AdBlock/AdBlock.h"
UIViewController *SGLockScreenSettingsPage(void) {
return [[SGModPage alloc] initWithTitle:@"Lock screen widget" intro:SGRestartNote sections:@[
@@ -38,6 +39,9 @@ UIViewController *SGPlaybackSettingsPage(void) {
// Every switch here forces a flag Spotify ships on to off, so the switch off is Spotify's own value.
UIViewController *SGAdsSettingsPage(void) {
return [[SGModPage alloc] initWithTitle:@"Ads & nags" intro:SGRestartNote sections:@[
+ SGSection(nil, @[
+ SGPageRow(@"Ad blocking", ^UIViewController *{ return SGAdBlockSettingsPage(); }),
+ ]),
SGSection(@"Ads", @[
SGKillRow(@"Ad when the app opens", @"ios-feature-adonappopen.enabled"),
SGKillRow(@"Its CTA card", @"ios-feature-adonappopen.cta_card_enabled"),
diff --git a/tweak/Sources/Features/Flags/Flags.x b/tweak/Sources/Features/Flags/Flags.x
index 93842675..fc7f82ce 100644
--- a/tweak/Sources/Features/Flags/Flags.x
+++ b/tweak/Sources/Features/Flags/Flags.x
@@ -3,6 +3,7 @@
// Glass switch then forces the flags of Spotify's own newer design, which it ships switched off.
#import "Core/SGCore.h"
#import "Flags.h"
+#import "Features/AdBlock/AdBlock.h"
BOOL SGGlassOwnsFlag(NSString *key) {
static NSSet<NSString *> *owned;
@@ -25,6 +26,7 @@ BOOL SGGlassOwnsFlag(NSString *key) {
static id forced(NSString *key) {
id value = SGFlagOverride(key);
if (!value && SGEnabled(SGKeySpotifyGlass) && SGGlassOwnsFlag(key)) value = @YES;
+ if (!value && SGAdBlockForcesFlagOff(key)) value = @NO;
return value;
}
diff --git a/tweak/Sources/Settings/SGModPage.m b/tweak/Sources/Settings/SGModPage.m
index 839f6274..3ae6b56d 100644
--- a/tweak/Sources/Settings/SGModPage.m
+++ b/tweak/Sources/Settings/SGModPage.m
@@ -3,6 +3,7 @@
#import "Core/SGCore.h"
#import "Features/Flags/Flags.h"
#import "Features/About/About.h"
+#import "Features/AdBlock/AdBlock.h"
NSString *const SGRestartNote = @"Changes apply after you restart Spotify.";
@@ -221,7 +222,8 @@ static BOOL flagRowOn(SGModRow *row) {
// A flag the Spotify's own Liquid Glass switch owns: its row shows what that switch forces and
// takes no touch, so the flag has one place to change. An override from All flags still wins.
static BOOL flagRowLocked(SGModRow *row) {
- return row.flag && SGGlassOwnsFlag(row.key) && SGEnabled(SGKeySpotifyGlass);
+ if (!row.flag) return NO;
+ return (SGGlassOwnsFlag(row.key) && SGEnabled(SGKeySpotifyGlass)) || (row.forceOff && SGAdBlockForcesFlagOff(row.key));
}
@implementation SGModPage {