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: add live activity lyrics

Vojtěch Škopek94360e98f6c1
diff --git a/extension/LiveActivity/Info.plist b/extension/LiveActivity/Info.plist
new file mode 100644
index 00000000..2294917f
--- /dev/null
+++ b/extension/LiveActivity/Info.plist
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>Spotify</string>
+ <key>CFBundleExecutable</key>
+ <string>SpotifyGlassLiveActivity</string>
+ <key>CFBundleIdentifier</key>
+ <string>HOST_BUNDLE_ID.liveactivity</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>SpotifyGlassLiveActivity</string>
+ <key>CFBundlePackageType</key>
+ <string>XPC!</string>
+ <key>CFBundleShortVersionString</key>
+ <string>HOST_SHORT_VERSION</string>
+ <key>CFBundleSupportedPlatforms</key>
+ <array>
+ <string>iPhoneOS</string>
+ </array>
+ <key>CFBundleVersion</key>
+ <string>HOST_VERSION</string>
+ <key>DTPlatformName</key>
+ <string>iphoneos</string>
+ <key>MinimumOSVersion</key>
+ <string>17.0</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.widgetkit-extension</string>
+ </dict>
+ <key>UIDeviceFamily</key>
+ <array>
+ <integer>1</integer>
+ <integer>2</integer>
+ </array>
+ <key>UIRequiredDeviceCapabilities</key>
+ <array>
+ <string>arm64</string>
+ </array>
+</dict>
+</plist>
diff --git a/extension/LiveActivity/LiveActivityWidget.swift b/extension/LiveActivity/LiveActivityWidget.swift
new file mode 100644
index 00000000..2b508b8a
--- /dev/null
+++ b/extension/LiveActivity/LiveActivityWidget.swift
@@ -0,0 +1,131 @@
+// The Live Activity's face: the playing track, the line being sung with the next one under it,
+// and previous, play/pause and next. Built with the tweak's LiveActivityShared.swift by
+// scripts/build-extension.sh.
+import ActivityKit
+import AppIntents
+import SwiftUI
+import WidgetKit
+
+private let spotifyGreen = Color(red: 0.12, green: 0.84, blue: 0.38)
+
+@main
+struct SGLiveActivityBundle: WidgetBundle {
+ var body: some Widget {
+ SGLyricsLiveActivity()
+ }
+}
+
+struct SGLyricsLiveActivity: Widget {
+ var body: some WidgetConfiguration {
+ ActivityConfiguration(for: SGLyricsAttributes.self) { context in
+ LockScreenView(state: context.state)
+ .activityBackgroundTint(Color.black.opacity(0.75))
+ .activitySystemActionForegroundColor(.white)
+ .widgetURL(URL(string: "spotify:"))
+ } dynamicIsland: { context in
+ DynamicIsland {
+ DynamicIslandExpandedRegion(.leading) {
+ TrackView(state: context.state)
+ .padding(.leading, 4)
+ }
+ DynamicIslandExpandedRegion(.trailing) {
+ ControlsView(paused: context.state.paused)
+ .padding(.trailing, 4)
+ }
+ DynamicIslandExpandedRegion(.bottom) {
+ LyricsView(state: context.state)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 4)
+ }
+ } compactLeading: {
+ Image(systemName: "music.note")
+ .foregroundStyle(spotifyGreen)
+ } compactTrailing: {
+ Image(systemName: context.state.paused ? "pause.fill" : "waveform")
+ .foregroundStyle(spotifyGreen)
+ } minimal: {
+ Image(systemName: "music.note")
+ .foregroundStyle(spotifyGreen)
+ }
+ .widgetURL(URL(string: "spotify:"))
+ }
+ }
+}
+
+private struct LockScreenView: View {
+ let state: SGLyricsAttributes.ContentState
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .center, spacing: 12) {
+ TrackView(state: state)
+ Spacer(minLength: 8)
+ ControlsView(paused: state.paused)
+ }
+ LyricsView(state: state)
+ }
+ .padding(16)
+ .foregroundStyle(.white)
+ }
+}
+
+private struct TrackView: View {
+ let state: SGLyricsAttributes.ContentState
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(state.title)
+ .font(.subheadline.weight(.semibold))
+ .lineLimit(1)
+ Text(state.artist)
+ .font(.caption)
+ .foregroundStyle(.white.opacity(0.6))
+ .lineLimit(1)
+ }
+ }
+}
+
+private struct LyricsView: View {
+ let state: SGLyricsAttributes.ContentState
+
+ var body: some View {
+ if !state.line.isEmpty || !state.nextLine.isEmpty {
+ VStack(alignment: .leading, spacing: 4) {
+ if !state.line.isEmpty {
+ Text(state.line)
+ .font(.title3.weight(.bold))
+ .lineLimit(2)
+ .minimumScaleFactor(0.8)
+ }
+ if !state.nextLine.isEmpty {
+ Text(state.nextLine)
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(.white.opacity(0.45))
+ .lineLimit(1)
+ }
+ }
+ }
+ }
+}
+
+private struct ControlsView: View {
+ let paused: Bool
+
+ var body: some View {
+ HStack(spacing: 18) {
+ Button(intent: SGPreviousTrackIntent()) {
+ Image(systemName: "backward.fill")
+ }
+ Button(intent: SGTogglePlaybackIntent()) {
+ Image(systemName: paused ? "play.fill" : "pause.fill")
+ .font(.title2)
+ }
+ Button(intent: SGNextTrackIntent()) {
+ Image(systemName: "forward.fill")
+ }
+ }
+ .buttonStyle(.plain)
+ .font(.title3)
+ .foregroundStyle(.white)
+ }
+}
diff --git a/plist/liquid-glass.plist b/plist/liquid-glass.plist
index 243a2f46..c99005f5 100644
--- a/plist/liquid-glass.plist
+++ b/plist/liquid-glass.plist
@@ -4,5 +4,7 @@
<dict>
<key>UIDesignRequiresCompatibility</key>
<false/>
+ <key>NSSupportsLiveActivities</key>
+ <true/>
</dict>
</plist>
diff --git a/scripts/build-extension.sh b/scripts/build-extension.sh
new file mode 100755
index 00000000..4fc711bb
--- /dev/null
+++ b/scripts/build-extension.sh
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+# Builds the Live Activity widget extension without an Xcode project, and the App Intents metadata
+# the host app needs for the widget's buttons.
+#
+# scripts/build-extension.sh <host Info.plist> <out dir>
+#
+# Writes <out dir>/SpotifyGlassLiveActivity.appex and <out dir>/app/Metadata.appintents, whose actions
+# pipeline.sh merges into Spotify's own. Needs Xcode (xcode-select or DEVELOPER_DIR): the metadata
+# processor ships only with it.
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+HOST_PLIST="${1:?usage: $0 <host Info.plist> <out dir>}"
+OUT="${2:?usage: $0 <host Info.plist> <out dir>}"
+NAME=SpotifyGlassLiveActivity
+APPEX="$OUT/$NAME.appex"
+SHARED="$ROOT/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift"
+WIDGET="$ROOT/extension/LiveActivity/LiveActivityWidget.swift"
+
+SDK="$(xcrun --sdk iphoneos --show-sdk-path)"
+TOOLCHAIN="$(dirname "$(dirname "$(dirname "$(xcrun --find swiftc)")")")"
+XCODE_BUILD="$(xcodebuild -version | sed -n 's/^Build version //p')"
+PROCESSOR="$(xcrun --find appintentsmetadataprocessor)"
+
+WORK="$OUT/.build"
+rm -rf "$APPEX" "$OUT/app" "$WORK"
+mkdir -p "$APPEX" "$OUT/app" "$WORK"
+
+# The protocols Xcode has swiftc record constant values for (SWIFT_EMIT_CONST_VALUE_PROTOCOLS in
+# Xcode's App Intents build rules); the metadata processor reads the intents out of those values.
+printf '%s\n' '["AppIntent","EntityQuery","AppEntity","TransientEntity","AppEnum","AppShortcutProviding","AppShortcutsProvider","AnyResolverProviding","AppIntentsPackage","DynamicOptionsProvider","_IntentValueRepresentable","_AssistantIntentsProvider","_GenerativeFunctionExtractable","IntentValueQuery","Resolver"]' > "$WORK/protocols.json"
+
+# metadata <module> <deployment target> <bundle dir> <sources...>
+metadata() {
+ local module="$1" deploy="$2" bundle="$3"; shift 3
+ local triple="arm64-apple-ios$deploy" dir="$WORK/$module"
+ mkdir -p "$dir"
+ printf '%s\n' "$@" > "$dir/sources.txt"
+ echo "$dir/$module.swiftconstvalues" > "$dir/constvals.txt"
+ xcrun --sdk iphoneos swiftc -typecheck -wmo -parse-as-library -target "$triple" -module-name "$module" \
+ -emit-const-values-path "$dir/$module.swiftconstvalues" -const-gather-protocols-list "$WORK/protocols.json" "$@"
+ "$PROCESSOR" --output "$bundle" --toolchain-dir "$TOOLCHAIN" --module-name "$module" --sdk-root "$SDK" \
+ --xcode-version "$XCODE_BUILD" --platform-family iOS --deployment-target "$deploy" --target-triple "$triple" \
+ --source-file-list "$dir/sources.txt" --swift-const-vals-list "$dir/constvals.txt" --force >/dev/null
+}
+
+echo "==> building $NAME.appex"
+xcrun --sdk iphoneos swiftc -O -wmo -parse-as-library -target arm64-apple-ios17.0 -module-name "$NAME" \
+ -Xlinker -e -Xlinker _NSExtensionMain -o "$APPEX/$NAME" "$SHARED" "$WIDGET"
+metadata "$NAME" 17.0 "$APPEX" "$SHARED" "$WIDGET"
+
+sed -e "s/HOST_BUNDLE_ID/$(plutil -extract CFBundleIdentifier raw -o - "$HOST_PLIST")/" \
+ -e "s/HOST_SHORT_VERSION/$(plutil -extract CFBundleShortVersionString raw -o - "$HOST_PLIST")/" \
+ -e "s/HOST_VERSION/$(plutil -extract CFBundleVersion raw -o - "$HOST_PLIST")/" \
+ "$ROOT/extension/LiveActivity/Info.plist" > "$APPEX/Info.plist"
+plutil -convert binary1 "$APPEX/Info.plist"
+
+# The buttons' intents run inside Spotify, so Spotify's metadata has to name them too, under the
+# module the tweak compiles them in (Theos names it after the tweak instance).
+metadata spotifyglass 16.0 "$OUT/app" "$SHARED"
+
+codesign -f -s - "$APPEX" >/dev/null 2>&1
+rm -rf "$WORK"
+echo " $APPEX"
diff --git a/scripts/merge-appintents.py b/scripts/merge-appintents.py
new file mode 100755
index 00000000..5287654f
--- /dev/null
+++ b/scripts/merge-appintents.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+"""Adds the actions of a Metadata.appintents to the app's own inside an IPA, in place.
+
+ scripts/merge-appintents.py <ipa> <Payload/X.app/> <Metadata.appintents dir>
+
+The system looks an intent up in the metadata of the bundle that runs it, and a LiveActivityIntent
+runs in the app, so the widget's intents have to be listed in Spotify's file next to its own.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+
+ipa, app_dir, ours = sys.argv[1:4]
+member = f"{app_dir}Metadata.appintents/extract.actionsdata"
+version = f"{app_dir}Metadata.appintents/version.json"
+
+with zipfile.ZipFile(ipa) as z:
+ theirs = json.loads(z.read(member)) if member in z.namelist() else None
+with open(os.path.join(ours, "extract.actionsdata")) as f:
+ added = json.load(f)
+
+merged = added if theirs is None else {**theirs, "actions": {**theirs["actions"], **added["actions"]}}
+
+with tempfile.TemporaryDirectory() as tmp:
+ os.makedirs(os.path.join(tmp, os.path.dirname(member)))
+ with open(os.path.join(tmp, member), "w") as f:
+ json.dump(merged, f)
+ entries = [member]
+ if theirs is None:
+ shutil.copy(os.path.join(ours, "version.json"), os.path.join(tmp, version))
+ entries.append(version)
+ subprocess.run(["zip", "-q", os.path.abspath(ipa), *entries], cwd=tmp, check=True)
+
+print(f" {len(added['actions'])} actions added to {len(merged['actions']) - len(added['actions'])} of the app's")
diff --git a/scripts/pipeline.sh b/scripts/pipeline.sh
index db648a59..16222f3c 100755
--- a/scripts/pipeline.sh
+++ b/scripts/pipeline.sh
@@ -82,10 +82,27 @@ echo " $TWEAK_DEB"
FILES=("$TWEAK_DEB")
[ "$WITH_FLEX" = 1 ] && FILES+=("$FLEX_DEB")
+EXT_DIR="$ROOT/out/extension"
+WITH_EXTENSION=0
+if xcrun --find appintentsmetadataprocessor >/dev/null 2>&1; then
+ unzip -p "$IN" "${APP_DIR}Info.plist" > "$ROOT/out/.info.plist"
+ "$ROOT/scripts/build-extension.sh" "$ROOT/out/.info.plist" "$EXT_DIR"
+ rm -f "$ROOT/out/.info.plist"
+ FILES+=("$EXT_DIR/SpotifyGlassLiveActivity.appex")
+ WITH_EXTENSION=1
+else
+ echo "==> no Xcode selected: building without the Live Activity extension"
+fi
+
echo "==> injecting"
# -w drops the Watch app: its companion-app key would still name com.spotify.client and block the install.
cyan -i "$IN" -o "$OUT" -f "${FILES[@]}" -l "$ROOT/plist/liquid-glass.plist" ${BUNDLE_ID:+-b "$BUNDLE_ID"} ${NAME:+-n "$NAME"} ${ICON:+-k "$ICON"} -w -s --overwrite
+if [ "$WITH_EXTENSION" = 1 ]; then
+ echo "==> adding the Live Activity intents to Spotify's App Intents metadata"
+ "$ROOT/scripts/merge-appintents.py" "$OUT" "$APP_DIR" "$EXT_DIR/app/Metadata.appintents"
+fi
+
echo "==> done: $OUT"
[ "$INSTALL" = 1 ] && exec "$ROOT/scripts/install.sh" "$OUT"
exit 0
diff --git a/tweak/Sources/Features/Karaoke/Karaoke.h b/tweak/Sources/Features/Karaoke/Karaoke.h
index 3728c166..18951061 100644
--- a/tweak/Sources/Features/Karaoke/Karaoke.h
+++ b/tweak/Sources/Features/Karaoke/Karaoke.h
@@ -22,9 +22,13 @@
NSArray<SGKaraokeLine *> *SGKaraokeLinesFromBody(NSData *body);
NSArray<SGKaraokeLine *> *SGKaraokeLinesForTrack(NSString *trackID); // nil until the lyrics came
+// Asks spclient for a track's lyrics once, with the headers of Spotify's own requests, for when no
+// page of Spotify's has asked for them, e.g. with the app in the background.
+void SGKaraokeRequestLyrics(NSString *trackID);
NSString *SGKaraokePlayingTrack(void); // the base62 id, nil before the player reported
NSInteger SGKaraokePositionMs(void); // negative when unknown
void SGKaraokeSeek(NSInteger ms);
+id SGKaraokePlayer(void); // SPTEsperantoPlayer, nil before the app asked it for its state
@interface SGKaraokeView : UIView
// Hides Spotify's own lyrics next to this view while it has lyrics to show, and brings them back when not.
diff --git a/tweak/Sources/Features/Karaoke/KaraokeSource.x b/tweak/Sources/Features/Karaoke/KaraokeSource.x
index 502fccfc..376e3fc1 100644
--- a/tweak/Sources/Features/Karaoke/KaraokeSource.x
+++ b/tweak/Sources/Features/Karaoke/KaraokeSource.x
@@ -4,11 +4,16 @@
// every frame: the player is caught the first time the app asks it, and its position runs on by itself.
#import "Core/SGCore.h"
#import "Karaoke.h"
+#import "Features/LiveActivity/LiveActivity.h"
#import "Headers/SPTPlayer.h"
static const NSUInteger kKeptTracks = 40;
+// What spclient needs from a request to answer it as the signed-in app.
+static NSString *const kSpclientHeaders[] = {@"authorization", @"client-token", @"app-platform", @"spotify-app-version", @"user-agent", @"accept-language"};
static NSMutableDictionary<NSString *, NSArray<SGKaraokeLine *> *> *sg_lyrics;
+static NSMutableSet<NSString *> *sg_requested;
+static NSDictionary<NSString *, NSString *> *sg_spclientHeaders;
static __weak id sg_player;
static char kBodyKey;
@@ -20,7 +25,33 @@ static NSString *trackInURL(NSURL *url) {
return track.length ? track : nil;
}
-static void received(NSURLSessionTask *task, NSData *data) {
+static void rememberHeaders(NSURLSession *session, NSURLRequest *request) {
+ if (![request.URL.host containsString:@"spclient"]) return;
+ NSMutableDictionary<NSString *, NSString *> *all = [NSMutableDictionary dictionary];
+ [session.configuration.HTTPAdditionalHeaders enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
+ if ([key isKindOfClass:NSString.class] && [value isKindOfClass:NSString.class]) all[[key lowercaseString]] = value;
+ }];
+ [request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
+ all[key.lowercaseString] = value;
+ }];
+ if (!all[@"authorization"]) return;
+ NSMutableDictionary<NSString *, NSString *> *headers = [NSMutableDictionary dictionary];
+ for (NSUInteger i = 0; i < sizeof(kSpclientHeaders) / sizeof(*kSpclientHeaders); i++) {
+ NSString *name = kSpclientHeaders[i];
+ if (all[name]) headers[name] = all[name];
+ }
+ dispatch_async(dispatch_get_main_queue(), ^{ sg_spclientHeaders = headers; });
+}
+
+static void keep(NSString *track, NSArray<SGKaraokeLine *> *lines) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (sg_lyrics.count >= kKeptTracks) [sg_lyrics removeAllObjects];
+ sg_lyrics[track] = lines;
+ });
+}
+
+static void received(NSURLSession *session, NSURLSessionTask *task, NSData *data) {
+ rememberHeaders(session, task.currentRequest);
if (!trackInURL(task.currentRequest.URL)) return;
NSMutableData *body = objc_getAssociatedObject(task, &kBodyKey);
if (!body) objc_setAssociatedObject(task, &kBodyKey, (body = [NSMutableData data]), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
@@ -39,17 +70,36 @@ static void completed(NSURLSessionTask *task, NSError *error) {
if (error || !track) return;
NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesFromBody(body);
SGLog(@"karaoke: lyrics for %@, %lu bytes, %lu synced lines", track, (unsigned long)body.length, (unsigned long)lines.count);
- if (!lines) return;
- dispatch_async(dispatch_get_main_queue(), ^{
- if (sg_lyrics.count >= kKeptTracks) [sg_lyrics removeAllObjects];
- sg_lyrics[track] = lines;
- });
+ if (lines) keep(track, lines);
}
NSArray<SGKaraokeLine *> *SGKaraokeLinesForTrack(NSString *trackID) {
return trackID ? sg_lyrics[trackID] : nil;
}
+void SGKaraokeRequestLyrics(NSString *trackID) {
+ if (!trackID || sg_lyrics[trackID] || [sg_requested containsObject:trackID]) return;
+ NSDictionary<NSString *, NSString *> *headers = sg_spclientHeaders;
+ if (!headers) return;
+ [sg_requested addObject:trackID];
+ NSString *address = [NSString stringWithFormat:@"https://spclient.wg.spotify.com/color-lyrics/v2/track/%@?format=json&vocalRemoval=false&market=from_token", trackID];
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:address]];
+ [headers enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {
+ [request setValue:value forHTTPHeaderField:name];
+ }];
+ [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *body, NSURLResponse *response, NSError *error) {
+ NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesFromBody(body);
+ SGLog(@"karaoke: fetched lyrics for %@: status %ld, %lu synced lines, error %@", trackID,
+ (long)[(NSHTTPURLResponse *)response statusCode], (unsigned long)lines.count, error);
+ if (lines) keep(trackID, lines);
+ }] resume];
+}
+
+id SGKaraokePlayer(void) {
+ return sg_player;
+}
+
static SPTPlayerState *playerState(void) {
id player = sg_player;
return [player respondsToSelector:@selector(state)] ? [(id<SPTPlayer>)player state] : nil;
@@ -82,7 +132,7 @@ void SGKaraokeSeek(NSInteger ms) {
%hook SPTDataLoaderService
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
- received(task, data);
+ received(session, task, data);
%orig;
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
@@ -93,7 +143,7 @@ void SGKaraokeSeek(NSInteger ms) {
%hook _TtC26Connectivity_HttpClientKit20HttpClientURLSession
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
- received(task, data);
+ received(session, task, data);
%orig;
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
@@ -103,8 +153,9 @@ void SGKaraokeSeek(NSInteger ms) {
%end
%ctor {
- if (!SGFlag(SGKeyKaraokeLyrics, NO)) return;
+ if (!SGFlag(SGKeyKaraokeLyrics, NO) && !SGFlag(SGKeyLiveActivity, NO)) return;
sg_lyrics = [NSMutableDictionary dictionary];
+ sg_requested = [NSMutableSet set];
%init;
SGLog(@"karaoke: on");
SGRequireClasses(@[
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivity.h b/tweak/Sources/Features/LiveActivity/LiveActivity.h
new file mode 100644
index 00000000..c5a86ba9
--- /dev/null
+++ b/tweak/Sources/Features/LiveActivity/LiveActivity.h
@@ -0,0 +1,6 @@
+// The playing track and the line being sung as a Live Activity on the lock screen and in the Dynamic
+// Island, with previous, play/pause and next (iOS 17+). The lines and the clock come from Karaoke, the
+// widget is extension/LiveActivity, built into the IPA by scripts/build-extension.sh.
+#import <Foundation/Foundation.h>
+
+#define SGKeyLiveActivity @"spotifyglass.liveActivity"
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivity.x b/tweak/Sources/Features/LiveActivity/LiveActivity.x
new file mode 100644
index 00000000..622b9455
--- /dev/null
+++ b/tweak/Sources/Features/LiveActivity/LiveActivity.x
@@ -0,0 +1,96 @@
+// Polls the player and pushes a new state to the activity only when what it shows changes: a new
+// line, track or pause. Spotify keeps playing in the background, so the timer keeps running there too.
+// The activity is started only while the app is in front, the one place ActivityKit allows it.
+#import <UIKit/UIKit.h>
+#import "Core/SGCore.h"
+#import "LiveActivity.h"
+#import "Features/Karaoke/Karaoke.h"
+#import "Headers/SPTPlayer.h"
+
+API_AVAILABLE(ios(17.0))
+@interface SGLiveActivityBridge : NSObject
+@property (class, nonatomic, readonly) BOOL isShowing;
++ (void)showWithTitle:(NSString *)title artist:(NSString *)artist line:(NSString *)line nextLine:(NSString *)nextLine paused:(BOOL)paused;
++ (void)end;
+@end
+
+static const NSTimeInterval kTick = 0.25;
+// Past a line's sung end by this much, with the next line at least this far off, the line gives way to a note.
+static const NSInteger kBreakMs = 4000;
+// Seconds between attempts to start one, so a refused request (activities turned off) is not retried every tick.
+static const NSTimeInterval kStartRetry = 10;
+
+static NSString *sg_shown;
+static NSString *sg_missingLyrics;
+static NSDate *sg_lastStart;
+
+static NSString *textOf(SGKaraokeLine *line) {
+ return [[line.words valueForKey:@"text"] componentsJoinedByString:@" "] ?: @"";
+}
+
+static void tick(void) API_AVAILABLE(ios(17.0)) {
+ id<SPTPlayer> player = SGKaraokePlayer();
+ SPTPlayerState *state = player.state;
+ SPTPlayerTrack *track = state.track;
+ if (!track.trackTitle.length) return;
+
+ NSString *trackID = SGKaraokePlayingTrack();
+ NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesForTrack(trackID);
+ if (!lines) {
+ SGKaraokeRequestLyrics(trackID);
+ if (trackID && ![trackID isEqualToString:sg_missingLyrics]) {
+ sg_missingLyrics = trackID;
+ SGLog(@"live activity: no lyrics yet for %@", trackID);
+ }
+ }
+
+ NSInteger position = SGKaraokePositionMs();
+ NSInteger index = -1;
+ while (index + 1 < (NSInteger)lines.count && lines[index + 1].start <= position) index++;
+ NSString *line = @"", *next = index + 1 < (NSInteger)lines.count ? textOf(lines[index + 1]) : @"";
+ if (index >= 0) {
+ SGKaraokeLine *current = lines[index];
+ BOOL nextFarOff = index + 1 == (NSInteger)lines.count || lines[index + 1].start - position > kBreakMs;
+ line = position > current.end + kBreakMs && nextFarOff ? @"♪" : textOf(current);
+ }
+
+ NSString *artist = track.artistName ?: @"";
+ NSString *shown = [@[track.trackTitle, artist, line, next, state.isPaused ? @"1" : @"0"] componentsJoinedByString:@"\n"];
+ if (SGLiveActivityBridge.isShowing) {
+ if ([shown isEqualToString:sg_shown]) return;
+ } else {
+ if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return;
+ if (sg_lastStart && -sg_lastStart.timeIntervalSinceNow < kStartRetry) return;
+ sg_lastStart = [NSDate date];
+ }
+ sg_shown = shown;
+ [SGLiveActivityBridge showWithTitle:track.trackTitle artist:artist line:line nextLine:next paused:state.isPaused];
+}
+
+static void runCommand(NSString *command) {
+ id<SPTPlayer> player = SGKaraokePlayer();
+ id result = nil;
+ if ([command isEqualToString:@"toggle"]) {
+ result = player.state.isPaused ? [player resume:nil] : [player pause:nil];
+ } else if ([command isEqualToString:@"next"]) {
+ result = [player skipToNextTrackWithOptions:nil];
+ } else if ([command isEqualToString:@"previous"]) {
+ result = [player skipToPreviousTrackWithOptions:nil];
+ }
+ SGLog(@"live activity: %@ -> %@ (player %@)", command, result, player ? NSStringFromClass([player class]) : @"nil");
+}
+
+%ctor {
+ if (@available(iOS 17.0, *)) {
+ if (!SGFlag(SGKeyLiveActivity, NO)) {
+ dispatch_async(dispatch_get_main_queue(), ^{ [SGLiveActivityBridge end]; });
+ return;
+ }
+ [NSNotificationCenter.defaultCenter addObserverForName:@"SGLiveActivityCommand" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
+ runCommand(note.object);
+ }];
+ NSTimer *timer = [NSTimer timerWithTimeInterval:kTick repeats:YES block:^(NSTimer *t) { tick(); }];
+ [NSRunLoop.mainRunLoop addTimer:timer forMode:NSRunLoopCommonModes];
+ SGLog(@"live activity: on");
+ }
+}
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivityBridge.swift b/tweak/Sources/Features/LiveActivity/LiveActivityBridge.swift
new file mode 100644
index 00000000..d53ce890
--- /dev/null
+++ b/tweak/Sources/Features/LiveActivity/LiveActivityBridge.swift
@@ -0,0 +1,42 @@
+// ActivityKit is Swift only, so LiveActivity.x reaches it through this class.
+import ActivityKit
+import Foundation
+import os
+
+@available(iOS 17.0, *)
+@objc(SGLiveActivityBridge)
+public final class SGLiveActivityBridge: NSObject {
+ private static let log = Logger(subsystem: "spotifyglass", category: "live activity")
+
+ private static var current: Activity<SGLyricsAttributes>? {
+ Activity<SGLyricsAttributes>.activities.first { $0.activityState == .active || $0.activityState == .stale }
+ }
+
+ @objc public static var isShowing: Bool { current != nil }
+
+ // A new activity can only be requested while the app is in the foreground; an update works from the background.
+ @objc public static func show(title: String, artist: String, line: String, nextLine: String, paused: Bool) {
+ let state = SGLyricsAttributes.ContentState(title: title, artist: artist, line: line, nextLine: nextLine, paused: paused)
+ let content = ActivityContent(state: state, staleDate: nil)
+ if let activity = current {
+ Task { await activity.update(content) }
+ return
+ }
+ guard ActivityAuthorizationInfo().areActivitiesEnabled else {
+ log.notice("[spotifyglass] live activity: activities are off for this app")
+ return
+ }
+ do {
+ let activity = try Activity.request(attributes: SGLyricsAttributes(), content: content, pushType: nil)
+ log.notice("[spotifyglass] live activity: started \(activity.id, privacy: .public)")
+ } catch {
+ log.error("[spotifyglass] live activity: request failed: \(String(describing: error), privacy: .public)")
+ }
+ }
+
+ @objc public static func end() {
+ for activity in Activity<SGLyricsAttributes>.activities {
+ Task { await activity.end(nil, dismissalPolicy: .immediate) }
+ }
+ }
+}
diff --git a/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift b/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift
new file mode 100644
index 00000000..9084a095
--- /dev/null
+++ b/tweak/Sources/Features/LiveActivity/LiveActivityShared.swift
@@ -0,0 +1,57 @@
+// Compiled into both the tweak and extension/LiveActivity: ActivityKit pairs the two sides by the
+// attributes' type name and App Intents by the intent's, so these must stay identical in both.
+import ActivityKit
+import AppIntents
+import Foundation
+
+@available(iOS 16.1, *)
+struct SGLyricsAttributes: ActivityAttributes {
+ struct ContentState: Codable, Hashable {
+ var title: String
+ var artist: String
+ var line: String
+ var nextLine: String
+ var paused: Bool
+ }
+}
+
+// A LiveActivityIntent runs in the app's process, where the tweak turns the notification into a player call.
+let SGLiveActivityCommandNotification = Notification.Name("SGLiveActivityCommand")
+
+@available(iOS 17.0, *)
+private func sendPlayerCommand(_ command: String) {
+ NotificationCenter.default.post(name: SGLiveActivityCommandNotification, object: command)
+}
+
+@available(iOS 17.0, *)
+struct SGPreviousTrackIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Previous track"
+ static let isDiscoverable = false
+
+ func perform() async throws -> some IntentResult {
+ sendPlayerCommand("previous")
+ return .result()
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGTogglePlaybackIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Play or pause"
+ static let isDiscoverable = false
+
+ func perform() async throws -> some IntentResult {
+ sendPlayerCommand("toggle")
+ return .result()
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGNextTrackIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Next track"
+ static let isDiscoverable = false
+
+ func perform() async throws -> some IntentResult {
+ sendPlayerCommand("next")
+ return .result()
+ }
+}
diff --git a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m
index 8e0fa67c..8ac6fa7b 100644
--- a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m
+++ b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m
@@ -5,6 +5,7 @@
#import "Features/Gestures/Gestures.h"
#import "Features/ArtistBlock/ArtistBlock.h"
#import "Features/Karaoke/Karaoke.h"
+#import "Features/LiveActivity/LiveActivity.h"
static UIViewController *nowPlayingBarPage(void) {
return [[SGModPage alloc] initWithTitle:@"Now playing bar" intro:SGRestartNote sections:@[
@@ -29,6 +30,7 @@ static UIViewController *lyricsPage(void) {
SGSection(nil, @[
SGOptionRow(@"Apple Music style", @"Word by word on the full screen page; timing inside a line is estimated", SGKeyKaraokeLyrics),
SGOptionRow(@"Glass lyrics", @"Glass card, and the page it expands into", SGKeyLyricsCard),
+ SGOptionRow(@"Live Activity", @"The line being sung and playback controls on the lock screen and in the Dynamic Island", SGKeyLiveActivity),
]),
SGSection(@"Hide in the player", @[
SGHideRow(@"Lyrics card", @"The lyrics card below the player", SGHideLyricsCard),
diff --git a/tweak/Sources/Headers/SPTPlayer.h b/tweak/Sources/Headers/SPTPlayer.h
index 537d5477..e9981de6 100644
--- a/tweak/Sources/Headers/SPTPlayer.h
+++ b/tweak/Sources/Headers/SPTPlayer.h
@@ -23,4 +23,9 @@
@property (nonatomic, readonly) SPTPlayerState *state;
- (void)skipToNextTrack;
- (void)seekTo:(double)seconds;
+// Each takes Spotify's options object, nil for the defaults, and returns the command's pending result.
+- (id)pause:(id)options;
+- (id)resume:(id)options;
+- (id)skipToNextTrackWithOptions:(id)options;
+- (id)skipToPreviousTrackWithOptions:(id)options;
@end