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: Siri, Shortcuts and the Action button run Like, Karaoke and playback

My-Name-Is-Jeff3cfbd33de37f
diff --git a/docs/tweaks.md b/docs/tweaks.md
index cd188d37..d40a1502 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -283,7 +283,16 @@ Shared:
by the attributes' type in LiveActivityShared.swift, compiled into both. It starts only with Spotify
in front; its settings apply at once. It ends when Spotify is swiped away while running; killed
while suspended, Spotify cannot end it, so each state goes stale a minute on (an unchanged card is
- sent again every 20 s) and a launch ends any left over before it starts a new one
+ sent again every 20 s) and a launch ends any left over before it starts a new one. The same folder
+ gives Siri, the Shortcuts app and the Action button Like This Song, Play or Pause, Next and Previous
+ Track, Sing and Sleep Timer (AppShortcuts.swift lists them as Spotify's App Shortcuts), and iOS 18
+ controls for Control Center and the lock screen of Like, Sing and the sleep timer
+ (extension/LiveActivity/Controls.swift), buttons, as the extension cannot read Sing's state. Each is
+ a LiveActivityIntent or AudioPlaybackIntent, so it runs inside Spotify, launched in the background
+ when needed, and LiveActivity.x answers it with the activity on or off, Like through
+ HeadGestures.x's collection platform and Sing through SGSetSingOn; a sleep timer set with the
+ activity off keeps a clock of its own. The intent asks again for 8 s while the player is not up,
+ then tells Siri to open Spotify. Checked in the simulator against harness/shortcuts/
ListeningStats/ listening stats kept on the phone (ListeningStats.h lists its files): each music track timed while
it plays through PlayerState's observer and written to a text log in Application Support once it ran 30 s
diff --git a/harness/shortcuts/README.md b/harness/shortcuts/README.md
new file mode 100644
index 00000000..2f3b78f8
--- /dev/null
+++ b/harness/shortcuts/README.md
@@ -0,0 +1,17 @@
+# Shortcuts harness
+
+The shortcut intents of `Shared/LiveActivity/LiveActivityShared.swift`, as the tweak compiles them, performed
+for real in the simulator against `observer.m`, a stand-in for `LiveActivity.x`'s `SGShortcut` observer
+registered the same way:
+
+- Like with the player not up for three posts: asked again every 250 ms and done on the fourth.
+- Sing on refused: thrown at once, the message read out as the observer wrote it.
+- Sleep timer, Next and Play or pause: each answered on the first post.
+- Previous never answered: given up after 32 posts, about 8 s, with "Spotify isn't ready yet".
+
+It checks that the post is made on the main thread and that the reply is a mutable dictionary the
+observer can write into, which is how the answer gets back. What Spotify does with each action is not
+here: that needs Spotify's player.
+
+ xcrun simctl boot <udid>
+ SIM=<udid> harness/shortcuts/build.sh
diff --git a/harness/shortcuts/build.sh b/harness/shortcuts/build.sh
new file mode 100755
index 00000000..2e740f24
--- /dev/null
+++ b/harness/shortcuts/build.sh
@@ -0,0 +1,14 @@
+#!/bin/sh
+# Builds the shortcuts harness for the simulator, LiveActivityShared.swift as the tweak compiles it with
+# main.swift and observer.m, and runs it on the simulator named by SIM (a UDID), which must be booted.
+set -e
+cd "$(dirname "$0")"
+mkdir -p build
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios18.0-simulator -isysroot "$SDK" -fobjc-arc -Wall -Werror \
+ -c observer.m -o build/observer.o
+xcrun -sdk iphonesimulator swiftc -target arm64-apple-ios18.0-simulator -sdk "$SDK" -parse-as-library \
+ -import-objc-header observer.h main.swift ../../tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift \
+ build/observer.o -o build/shortcuts
+echo "built build/shortcuts"
+if [ -n "$SIM" ]; then xcrun simctl spawn "$SIM" "$PWD/build/shortcuts"; fi
diff --git a/harness/shortcuts/main.swift b/harness/shortcuts/main.swift
new file mode 100644
index 00000000..8ed09480
--- /dev/null
+++ b/harness/shortcuts/main.swift
@@ -0,0 +1,56 @@
+// The shortcut intents of LiveActivityShared.swift, performed for real against observer.m: an answer after
+// the player comes up, a failure that reaches Siri as the error's message, and the give-up when Spotify
+// never answers.
+import Foundation
+
+@MainActor
+func check(_ ok: Bool, _ what: String) {
+ print(ok ? "ok \(what)" : "FAIL \(what)")
+ if !ok { exit(1) }
+}
+
+@main
+struct Harness {
+ @MainActor
+ static func main() async {
+ SGHarnessObserve(3)
+
+ // Like: three posts unanswered while the player loads, the fourth answered.
+ do {
+ _ = try await SGLikeIntent().perform()
+ check(SGHarnessPosts == 4, "like asked again until answered (\(SGHarnessPosts) posts)")
+ } catch {
+ check(false, "like threw \(error)")
+ }
+
+ SGHarnessPosts = 0
+ do {
+ _ = try await SGSingIntent(.on).perform()
+ check(false, "sing:on should fail")
+ } catch let error as SGShortcutError {
+ check(error.message == "Sing needs its voice model." && SGHarnessPosts == 1, "a failure is thrown at once with its message")
+ check(String(localized: error.localizedStringResource) == error.message, "the message reads out as it is")
+ } catch {
+ check(false, "sing threw \(error)")
+ }
+
+ SGHarnessPosts = 0
+ _ = try? await SGSleepTimerIntent(.endOfTrack).perform()
+ _ = try? await SGNextTrackIntent().perform()
+ _ = try? await SGPlayPauseIntent().perform()
+ check(SGHarnessPosts == 3, "timer, next and play or pause each answered first time")
+
+ SGHarnessPosts = 0
+ let start = Date()
+ do {
+ _ = try await SGPreviousTrackIntent().perform()
+ check(false, "previous should give up")
+ } catch let error as SGShortcutError {
+ let took = Date().timeIntervalSince(start)
+ check(SGHarnessPosts == 32 && took > 7.5 && took < 10, "gives up after 32 posts in \(String(format: "%.1f", took)) s: \(error.message)")
+ } catch {
+ check(false, "previous threw \(error)")
+ }
+ print("all passed")
+ }
+}
diff --git a/harness/shortcuts/observer.h b/harness/shortcuts/observer.h
new file mode 100644
index 00000000..3f76be4f
--- /dev/null
+++ b/harness/shortcuts/observer.h
@@ -0,0 +1,6 @@
+#import <Foundation/Foundation.h>
+
+// How many times the stand-in was asked since the count was last reset.
+extern NSInteger SGHarnessPosts;
+// Registers the stand-in, which leaves the first `waitPosts` posts unanswered and never answers previous.
+void SGHarnessObserve(NSInteger waitPosts);
diff --git a/harness/shortcuts/observer.m b/harness/shortcuts/observer.m
new file mode 100644
index 00000000..1a0a4786
--- /dev/null
+++ b/harness/shortcuts/observer.m
@@ -0,0 +1,23 @@
+// A stand-in for LiveActivity.x's SGShortcut observer, registered the same way (no queue, the reply read out
+// of userInfo and checked as it is there), answering from a script instead of Spotify's player.
+#import <Foundation/Foundation.h>
+#import "observer.h"
+
+NSInteger SGHarnessPosts;
+
+void SGHarnessObserve(NSInteger waitPosts) {
+ [NSNotificationCenter.defaultCenter addObserverForName:@"SGShortcut" object:nil queue:nil usingBlock:^(NSNotification *note) {
+ NSMutableDictionary *reply = note.userInfo[@"reply"];
+ if (!NSThread.isMainThread || ![note.object isKindOfClass:NSString.class] || ![reply isKindOfClass:NSMutableDictionary.class]) {
+ NSLog(@"FAIL: posted off the main thread or without a mutable reply");
+ exit(1);
+ }
+ NSString *action = note.object;
+ SGHarnessPosts++;
+ static NSInteger total;
+ // The player not up for the first posts: no answer, as runShortcut gives none without a track.
+ if (++total <= waitPosts ||[action isEqualToString:@"previous"]) return;
+ if ([action isEqualToString:@"sing:on"]) reply[@"failed"] = @"Sing needs its voice model.";
+ else reply[@"said"] = [action isEqualToString:@"like"] ? @"Added Song to Liked Songs." : @"";
+ }];
+}
diff --git a/scripts/build-extension.sh b/scripts/build-extension.sh
index c0fdc83e..96b4e359 100755
--- a/scripts/build-extension.sh
+++ b/scripts/build-extension.sh
@@ -16,6 +16,8 @@ NAME=SpotifyGlassLiveActivity
APPEX="$OUT/$NAME.appex"
SHARED="$ROOT/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift"
WIDGET="$ROOT/extension/LiveActivity/LiveActivityWidget.swift"
+# Spotify's App Shortcuts, which only the app's metadata may carry.
+SHORTCUTS="$ROOT/tweak/Sources/Shared/LiveActivity/AppShortcuts.swift"
SDK="$(xcrun --sdk iphoneos --show-sdk-path)"
TOOLCHAIN="$(dirname "$(dirname "$(dirname "$(xcrun --find swiftc)")")")"
@@ -55,9 +57,9 @@ sed -e "s/HOST_BUNDLE_ID/$(plutil -extract CFBundleIdentifier raw -o - "$HOST_PL
"$ROOT/extension/LiveActivity/Info.plist" > "$APPEX/Info.plist"
plutil -convert binary1 "$APPEX/Info.plist"
-# The taps' 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"
+# The taps', the shortcuts' and the controls' 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" "$SHORTCUTS"
codesign -f -s - "$APPEX" >/dev/null 2>&1
rm -rf "$WORK"
diff --git a/scripts/merge-appintents.py b/scripts/merge-appintents.py
index 5287654f..33186bf0 100755
--- a/scripts/merge-appintents.py
+++ b/scripts/merge-appintents.py
@@ -1,10 +1,12 @@
#!/usr/bin/env python3
-"""Adds the actions of a Metadata.appintents to the app's own inside an IPA, in place.
+"""Adds the actions, enums and App Shortcuts 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.
+runs in the app, so the widget's intents have to be listed in Spotify's file next to its own. Spotify
+9.1.78 has no file, so ours goes in whole; with one, each list and table gets ours added, and the rest
+(an App Shortcuts provider among it) stays the app's where it has its own.
"""
import json
import os
@@ -23,7 +25,16 @@ with zipfile.ZipFile(ipa) as z:
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"]}}
+def merge(key):
+ mine, app = added[key], theirs.get(key)
+ if isinstance(mine, dict) and isinstance(app, dict):
+ return {**app, **mine}
+ if isinstance(mine, list) and isinstance(app, list):
+ return app + mine
+ return mine if app is None else app
+
+
+merged = added if theirs is None else {**theirs, **{key: merge(key) for key in added}}
with tempfile.TemporaryDirectory() as tmp:
os.makedirs(os.path.join(tmp, os.path.dirname(member)))
diff --git a/tweak/Sources/Shared/HeadGestures/HeadGestures.h b/tweak/Sources/Shared/HeadGestures/HeadGestures.h
index 4d60d85c..1e5d8a2d 100644
--- a/tweak/Sources/Shared/HeadGestures/HeadGestures.h
+++ b/tweak/Sources/Shared/HeadGestures/HeadGestures.h
@@ -55,6 +55,11 @@ typedef NS_ENUM(NSInteger, SGHeadCue) {
};
void SGHeadGesturesCue(SGHeadCue cue);
+// Adds the playing track to Liked Songs, never takes it out, through the collection platform kept here: the
+// nod's Like, and the Like shortcut's (Shared/LiveActivity). NO when what plays is no track or the platform
+// was not reached yet. Spotify's toast shows only with Spotify in front.
+BOOL SGLikePlayingTrack(void);
+
// From the switch, the sensitivity, the actions and learning: listens or stops, and reads the thresholds again.
void SGHeadGesturesSettingsChanged(void);
// Whether this iPhone can read headphone motion at all (iOS 14 and up; the headphones are another matter).
diff --git a/tweak/Sources/Shared/HeadGestures/HeadGestures.x b/tweak/Sources/Shared/HeadGestures/HeadGestures.x
index 0cf628ae..8bd7ce95 100644
--- a/tweak/Sources/Shared/HeadGestures/HeadGestures.x
+++ b/tweak/Sources/Shared/HeadGestures/HeadGestures.x
@@ -178,7 +178,7 @@ void SGSetHeadGestureAction(SGHeadGesture gesture, SGHeadAction action) {
SGHeadGesturesSettingsChanged();
}
-static BOOL like(void) {
+BOOL SGLikePlayingTrack(void) {
NSString *uri = SGURIString(SGPlayerState().track.URI);
id platform = sg_platform;
// Only a track: an episode is saved another way, and an ad is nothing to save.
@@ -196,7 +196,7 @@ static BOOL like(void) {
// Whether it was sent: the player answers later, if at all.
static BOOL perform(SGHeadAction action) {
- if (action == SGHeadActionLike) return like();
+ if (action == SGHeadActionLike) return SGLikePlayingTrack();
id<SPTPlayer> player = SGKaraokePlayer();
SPTPlayerState *state = [player respondsToSelector:@selector(state)] ? player.state : nil;
if (!state) {
diff --git a/tweak/Sources/Shared/LiveActivity/AppShortcuts.swift b/tweak/Sources/Shared/LiveActivity/AppShortcuts.swift
new file mode 100644
index 00000000..17a75f5c
--- /dev/null
+++ b/tweak/Sources/Shared/LiveActivity/AppShortcuts.swift
@@ -0,0 +1,34 @@
+// Spotify's App Shortcuts: what Siri answers to, what the Shortcuts app shows under Spotify before any
+// shortcut is made, and what the Action button lists under Shortcut > Spotify. An app has one provider, and
+// Spotify 9.1.78 has none of its own. Tweak only: the system reads it from the App Intents metadata
+// scripts/build-extension.sh makes for Spotify, and a widget extension may not carry one.
+// Every phrase names the app; the system's own media commands already own "next song" and "pause".
+import AppIntents
+
+@available(iOS 17.0, *)
+struct SGAppShortcuts: AppShortcutsProvider {
+ static var appShortcuts: [AppShortcut] {
+ AppShortcut(intent: SGLikeIntent(), phrases: [
+ "Like this song in \(.applicationName)",
+ "Add this song to Liked Songs in \(.applicationName)",
+ ], shortTitle: "Like This Song", systemImageName: "heart")
+ AppShortcut(intent: SGPlayPauseIntent(), phrases: [
+ "Play or pause \(.applicationName)",
+ ], shortTitle: "Play or Pause", systemImageName: "playpause")
+ AppShortcut(intent: SGNextTrackIntent(), phrases: [
+ "Skip this song in \(.applicationName)",
+ "Next track in \(.applicationName)",
+ ], shortTitle: "Next Track", systemImageName: "forward")
+ AppShortcut(intent: SGPreviousTrackIntent(), phrases: [
+ "Previous track in \(.applicationName)",
+ ], shortTitle: "Previous Track", systemImageName: "backward")
+ AppShortcut(intent: SGSingIntent(), phrases: [
+ "\(\.$mode) Sing in \(.applicationName)",
+ "Sing along in \(.applicationName)",
+ ], shortTitle: "Sing", systemImageName: "music.mic")
+ AppShortcut(intent: SGSleepTimerIntent(), phrases: [
+ "Set a sleep timer in \(.applicationName)",
+ "Sleep timer \(\.$length) in \(.applicationName)",
+ ], shortTitle: "Sleep Timer", systemImageName: "moon.zzz")
+ }
+}
diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.h b/tweak/Sources/Shared/LiveActivity/LiveActivity.h
index 64cb56a7..3928840e 100644
--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.h
+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.h
@@ -7,7 +7,12 @@
//
// LiveActivity.x polls the player, sends the activity a new state when what it shows changes
// LiveActivityBridge.swift ActivityKit, which is Swift only
-// LiveActivityShared.swift the attributes and the taps' intents, compiled into the extension too
+// LiveActivityShared.swift the attributes and the taps' intents, compiled into the extension too, and
+// the shortcuts' intents: Like This Song, Play or Pause, Next and Previous Track,
+// Sing and Sleep Timer, for Siri, the Shortcuts app, the Action button and the
+// controls (extension/LiveActivity/Controls.swift), answered by LiveActivity.x
+// with the activity on or off; checked in the simulator (harness/shortcuts)
+// AppShortcuts.swift Spotify's App Shortcuts, tweak only
// LiveActivitySettings.m its page, opened from the root of Mod Settings
//
// Every tap in the card runs an intent inside Spotify and takes a second or two to show on the card.
@@ -17,7 +22,7 @@
// the clock come from Shared/Lyrics, the queue from the player's state. The switch and the view apply at
// once: iOS lets an activity start only while the app is in front, which it is when the switch is flipped.
//
-// The Swift names crossing into the widget (SGLyricsAttributes, the two intents, the notifications)
+// The Swift names crossing into the widget (SGLyricsAttributes, the intents and their enums, the notifications)
// are a contract with extension/LiveActivity and with the App Intents metadata merged into Spotify:
// ActivityKit and App Intents pair the two processes by type name, so a change here is a change there.
// Threading: main thread only.
diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.x b/tweak/Sources/Shared/LiveActivity/LiveActivity.x
index 88d81f3c..9382727e 100644
--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.x
+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.x
@@ -4,6 +4,10 @@
// playing in the background, so the timer keeps running there too. The sleep timer is
// Shared/Player/SleepTimer's, which keeps its own time; the card only sets it and shows it.
// The activity is started only while the app is in front, the one place ActivityKit allows it.
+//
+// The shortcuts (LiveActivityShared.swift's SGShortcutNotification) are answered here too, with the
+// activity on or off: the control menu's actions, the like, Sing, and the same sleep timer, whose own clock
+// runs whether anything here ticks or not.
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import <MediaPlayer/MediaPlayer.h>
@@ -12,6 +16,8 @@
#import "Shared/Player/SleepTimer.h"
#import "Headers/SPTPlayer.h"
#import "Shared/Lyrics/Lyrics.h"
+#import "Shared/HeadGestures/HeadGestures.h"
+#import "Shared/Sing/Sing.h"
#import "LiveActivity.h"
API_AVAILABLE(ios(17.0))
@@ -341,6 +347,58 @@ static void runAction(NSString *action) {
SGLog(@"live activity: %@ -> %@", action, result);
}
+// What a shortcut set the sleep timer to, for Siri to say.
+static NSString *sleepTimerText(void) {
+ switch (SGSleepTimerCurrentMode()) {
+ case SGSleepTimerEndOfTrack: return @"Spotify will pause at the end of this track.";
+ case SGSleepTimerEndOfAlbum: return @"Spotify will pause at the end of this album or playlist.";
+ case SGSleepTimerAtTime: {
+ NSInteger minutes = lround(SGSleepTimerEnd().timeIntervalSinceNow / 60);
+ return [NSString stringWithFormat:@"Spotify will pause in %ld minutes.", (long)minutes];
+ }
+ default: return @"The sleep timer is off.";
+ }
+}
+
+// A shortcut's action, LiveActivityShared.swift's SGShortcutNotification: done, and answered in `reply`
+// with "said" or "failed"; left unanswered while the player has no track, which a launch in the background
+// takes a moment to load, and the intent asks again.
+static void runShortcut(NSString *action, NSMutableDictionary *reply) API_AVAILABLE(ios(17.0)) {
+ id<SPTPlayer> player = SGKaraokePlayer();
+ NSString *title = player.state.track.trackTitle;
+ if ([action hasPrefix:@"sing:"]) {
+ NSString *mode = [action substringFromIndex:5];
+ BOOL on = [mode isEqualToString:@"toggle"] ? !SGSingOn() : [mode isEqualToString:@"on"];
+ NSString *missing = on ? SGSingMissing() : nil;
+ if (missing) {
+ reply[@"failed"] = missing;
+ } else {
+ if (on != SGSingOn()) SGSetSingOn(on);
+ reply[@"said"] = on ? @"Sing is on." : @"Sing is off.";
+ }
+ } else if (!title.length) {
+ SGLog(@"shortcut: %@ waits for the player", action);
+ return;
+ } else if ([action isEqualToString:@"like"]) {
+ // The like reads the shared player state and the collection platform, which a launch in the background
+ // can reach after the player has a track: only what is surely no track fails, the rest waits.
+ NSString *uri = SGURIString(SGPlayerState().track.URI);
+ if (SGLikePlayingTrack()) {
+ reply[@"said"] = [NSString stringWithFormat:@"Added %@ to Liked Songs.", title];
+ } else if (uri.length && ![uri hasPrefix:@"spotify:track:"]) {
+ reply[@"failed"] = @"What's playing can't be added to Liked Songs.";
+ } else {
+ SGLog(@"shortcut: like waits for the player state and the collection platform");
+ return;
+ }
+ } else {
+ runAction(action);
+ if (sg_timer) tick();
+ reply[@"said"] = [action hasPrefix:@"timer:"] ? sleepTimerText() : @"";
+ }
+ SGLog(@"shortcut: %@ -> %@", action, reply);
+}
+
void SGSetLiveActivityEnabled(BOOL on) {
if (@available(iOS 17.0, *)) {
[sg_timer invalidate];
@@ -386,6 +444,12 @@ void SGSetLiveActivityEnabled(BOOL on) {
SGMigrateKey(SGKeyLiveActivityWas, SGKeyLiveActivity);
SGMigrateKey(SGKeyLiveActivityViewWas, SGKeyLiveActivityView);
BOOL on = SGFlag(SGKeyLiveActivity, NO);
+ // Answered inside the post, which the intent makes on the main thread, so the reply is there when it returns.
+ [NSNotificationCenter.defaultCenter addObserverForName:@"SGShortcut" object:nil queue:nil usingBlock:^(NSNotification *note) {
+ NSMutableDictionary *reply = note.userInfo[@"reply"];
+ if (!NSThread.isMainThread || ![note.object isKindOfClass:NSString.class] || ![reply isKindOfClass:NSMutableDictionary.class]) return;
+ runShortcut(note.object, reply);
+ }];
// One left from the launch before is ended, on or off: Spotify may have been killed under it, so it
// shows a moment long gone. On, a fresh one starts once it is: until then the first ticks update
// the leftover, which is harmless, an update after the end being ignored.
diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift b/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift
index 0addb93e..abdc5a89 100644
--- a/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift
+++ b/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift
@@ -111,3 +111,155 @@ struct SGLiveActivityActionIntent: LiveActivityIntent {
return .result()
}
}
+
+// The shortcuts: Siri, the Shortcuts app and the Action button run these, as do the controls in Control
+// Center and on the lock screen (extension/LiveActivity). A LiveActivityIntent or an AudioPlaybackIntent
+// is performed in the app's process wherever it is run from, so each lands in Spotify, launched in the
+// background when it is not running, where LiveActivity.x acts on SGShortcutNotification. Its observer
+// runs on the main thread inside the post and writes what it did into the reply: "said", a line for Siri,
+// or "failed", why it could not. No answer at all means Spotify's player is not up yet, which a launch in
+// the background takes a moment for, so the intent asks again.
+let SGShortcutNotification = Notification.Name("SGShortcut")
+
+struct SGShortcutError: Error, CustomLocalizedStringResourceConvertible {
+ let message: String
+ var localizedStringResource: LocalizedStringResource { "\(message)" }
+}
+
+// What Spotify answered `action` with: one of SGLiveActivityActionIntent's actions, like, or sing:MODE.
+@MainActor
+private func askSpotify(_ action: String) async throws -> String {
+ // ponytail: 8 s of asking, untimed on a phone; raise it if a launch in the background takes longer.
+ for _ in 0..<32 {
+ let reply = NSMutableDictionary()
+ NotificationCenter.default.post(name: SGShortcutNotification, object: action, userInfo: ["reply": reply])
+ if let failed = reply["failed"] as? String { throw SGShortcutError(message: failed) }
+ if let said = reply["said"] as? String { return said }
+ try await Task.sleep(nanoseconds: 250_000_000)
+ }
+ throw SGShortcutError(message: "Spotify isn't ready yet. Open it and try again.")
+}
+
+@available(iOS 16.0, *)
+enum SGSleepTimerLength: String, AppEnum {
+ // The raw values are the timer action's, timer:VALUE.
+ case fifteen = "15", thirty = "30", hour = "60", endOfTrack = "track", off = "cancel"
+
+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Sleep Timer"
+ static let caseDisplayRepresentations: [SGSleepTimerLength: DisplayRepresentation] = [
+ .fifteen: "15 Minutes",
+ .thirty: "30 Minutes",
+ .hour: "1 Hour",
+ .endOfTrack: "End of Track",
+ .off: "Off",
+ ]
+}
+
+@available(iOS 16.0, *)
+enum SGSingMode: String, AppEnum {
+ case toggle, on, off
+
+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Sing"
+ static let caseDisplayRepresentations: [SGSingMode: DisplayRepresentation] = [
+ .toggle: "Toggle",
+ .on: "Turn On",
+ .off: "Turn Off",
+ ]
+}
+
+@available(iOS 17.0, *)
+struct SGLikeIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Like This Song"
+ static let description = IntentDescription("Adds the song playing in Spotify to Liked Songs.")
+
+ init() {}
+
+ func perform() async throws -> some IntentResult & ProvidesDialog {
+ .result(dialog: "\(try await askSpotify("like"))")
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGPlayPauseIntent: AudioPlaybackIntent {
+ static let title: LocalizedStringResource = "Play or Pause"
+ static let description = IntentDescription("Pauses Spotify, or plays it when it is paused.")
+
+ init() {}
+
+ func perform() async throws -> some IntentResult {
+ _ = try await askSpotify("toggle")
+ return .result()
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGNextTrackIntent: AudioPlaybackIntent {
+ static let title: LocalizedStringResource = "Next Track"
+ static let description = IntentDescription("Skips to the next track in Spotify.")
+
+ init() {}
+
+ func perform() async throws -> some IntentResult {
+ _ = try await askSpotify("next")
+ return .result()
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGPreviousTrackIntent: AudioPlaybackIntent {
+ static let title: LocalizedStringResource = "Previous Track"
+ static let description = IntentDescription("Goes back a track in Spotify, or to the start of this one.")
+
+ init() {}
+
+ func perform() async throws -> some IntentResult {
+ _ = try await askSpotify("previous")
+ return .result()
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGSingIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Sing"
+ static let description = IntentDescription("Turns the vocals down in Spotify so you can sing along, or brings them back.")
+
+ @Parameter(title: "Sing", default: .toggle)
+ var mode: SGSingMode
+
+ init() {}
+
+ init(_ mode: SGSingMode) {
+ self.mode = mode
+ }
+
+ static var parameterSummary: some ParameterSummary {
+ Summary("\(\.$mode) Sing")
+ }
+
+ func perform() async throws -> some IntentResult & ProvidesDialog {
+ .result(dialog: "\(try await askSpotify("sing:\(mode.rawValue)"))")
+ }
+}
+
+@available(iOS 17.0, *)
+struct SGSleepTimerIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Sleep Timer"
+ static let description = IntentDescription("Pauses Spotify after a while or at the end of the track, or turns the timer off.")
+
+ @Parameter(title: "Length")
+ var length: SGSleepTimerLength
+
+ init() {}
+
+ init(_ length: SGSleepTimerLength) {
+ self.length = length
+ }
+
+ static var parameterSummary: some ParameterSummary {
+ Summary("Set the sleep timer to \(\.$length)")
+ }
+
+ func perform() async throws -> some IntentResult & ProvidesDialog {
+ .result(dialog: "\(try await askSpotify("timer:\(length.rawValue)"))")
+ }
+}