Compare commits

..
411 changed files with 35913 additions and 11144 deletions

No files matched your search

+5 -6
View File
@@ -54,12 +54,11 @@ playwright.config.*
*~
*.log
# Environment variables (only commit template files)
.env
.env*.local
.env.development
.env.test
.env.production.local
# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values
# into the bundle and the Convex CLI reads .env.local on deploy.
**/.env
**/.env.*
!**/.env.example
# Docker configuration files (not needed inside build context)
Dockerfile*
+6 -1
View File
@@ -41,4 +41,9 @@ apps/web/next-env.d.ts
/.convex
/.cursor
/database
docker-compose.yml
docker-compose.yml
**/credentials.json
**/credentials/
**/*.ipa
**/*.apk
+19 -19
View File
@@ -11,7 +11,7 @@ ARG NODE_VERSION=24.13.0-slim
# The Convex backend runs inside the oTunes image. Pin to a commit tag from
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
ARG CONVEX_BACKEND_IMAGE=ghcr.io/convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
# Audio-only static ffmpeg. The distro package links video filters that pull
# in LLVM and Mesa (~420MB) for codecs this app never uses.
@@ -25,18 +25,16 @@ FROM node:${NODE_VERSION} AS dependencies
WORKDIR /app
# Only manifests needed for @otunes/web and its workspace dependency (@otunes/convex).
# Mobile is intentionally omitted so its deps are never installed.
COPY package.json pnpm-lock.yaml .npmrc ./
# Mobile's manifest is never copied, so the workspace globs cannot discover it.
# The workspace file must be the real one: its overrides and patches are
# checked against the lockfile.
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
# pnpm validates patches even when their packages are outside the install filter.
COPY patches ./patches
COPY apps/web/package.json ./apps/web/
COPY packages/convex/package.json ./packages/convex/
# Explicit workspace — do not use apps/* so mobile cannot be discovered.
RUN printf '%s\n' \
'packages:' \
' - "apps/web"' \
' - "packages/convex"' \
>> pnpm-workspace.yaml \
&& printf '\n%s\n' \
RUN printf '\n%s\n' \
'supportedArchitectures.os=current' \
'supportedArchitectures.cpu=current' \
'supportedArchitectures.libc=current' \
@@ -80,14 +78,11 @@ FROM node:${NODE_VERSION} AS convex-functions
WORKDIR /app
COPY package.json pnpm-lock.yaml .npmrc ./
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
COPY patches ./patches
COPY packages/convex/package.json ./packages/convex/
RUN printf '%s\n' \
'packages:' \
' - "packages/convex"' \
> pnpm-workspace.yaml \
&& printf '\n%s\n' \
RUN printf '\n%s\n' \
'supportedArchitectures.os=current' \
'supportedArchitectures.cpu=current' \
'supportedArchitectures.libc=current' \
@@ -126,7 +121,7 @@ RUN curl -fsSL -o ffmpeg.tar.xz "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VER
# Decoders cover the library formats (FLAC, ALAC/AAC in m4a, MP3, Opus,
# Vorbis, WavPack, WMA, E-AC-3/TrueHD for Atmos). Encoders are only the two
# the app writes: AAC (HLS and ADTS) and FLAC.
# the app writes: AAC (HLS, ADTS and .m4a downloads) and FLAC.
RUN ./configure \
--prefix=/opt/ffmpeg \
--disable-shared \
@@ -143,7 +138,7 @@ RUN ./configure \
--enable-demuxer=aac,ac3,aiff,ape,asf,au,caf,dsf,flac,matroska,mov,mp3,ogg,wav,wv \
--enable-decoder=aac,aac_latm,ac3,alac,ape,dsd_lsbf,dsd_msbf,eac3,flac,mlp,mp3,opus,pcm_f32le,pcm_s16be,pcm_s16le,pcm_s24be,pcm_s24le,pcm_s32be,pcm_s32le,pcm_u8,truehd,vorbis,wavpack,wmav1,wmav2 \
--enable-encoder=aac,flac \
--enable-muxer=adts,flac,hls,mpegts \
--enable-muxer=adts,flac,hls,ipod,mpegts \
--enable-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
--enable-bsf=aac_adtstoasc \
--enable-filter=aresample,aformat \
@@ -192,7 +187,12 @@ RUN node --version \
&& ldd /convex/generate_key \
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
# The backend gets its own user so the web server cannot read the database or
# instance secret. It joins the otunes group to clean up the web server's HLS
# cache in /tmp/otunes.
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \
&& useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \
--shell /usr/sbin/nologin convex
COPY --from=convex-functions /app /opt/otunes/convex
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
+3 -3
View File
@@ -1,7 +1,7 @@
ios/
android/
/ios/
/android/
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
# The following patterns were generated by expo-cli
expo-env.d.ts
# @end expo-cli
# @end expo-cli
+87
View File
@@ -0,0 +1,87 @@
# Mobile build variants
EAS profiles set `APP_VARIANT` to select the app identity in `app.config.ts`.
Both iOS bundle identifiers and Android package names use these values:
| Profile | App name | Identifier |
| --- | --- | --- |
| development | oTunes (Development) | com.abunchofknowitalls.otunes.development |
| preview | oTunes (Preview) | com.abunchofknowitalls.otunes.preview |
| production | oTunes | com.abunchofknowitalls.otunes |
Build with `eas build --profile development`, `--profile preview`, or
`--profile production` from this directory.
For local builds and Metro, select the same variant explicitly:
```sh
APP_VARIANT=development pnpm ios
APP_VARIANT=development pnpm android
APP_VARIANT=development pnpm start
```
An unset `APP_VARIANT` keeps the production identity. Unknown variants fail
configuration. URL schemes are `otunes-development`, `otunes-preview`, and
`otunes` respectively, allowing the apps to be installed together.
### Shared links and artwork
Shared URLs stay as ordinary HTTPS links. The web page's "Open App" action
opens `otunes://open?url=<encoded HTTPS URL>`, including the server address and
album, artist, or playlist destination. No domain association files, signing
settings, or per-server mobile builds are needed.
The app checks the link's server against its configured server before opening
media. Links for another server do not switch the current server. On a fresh
installation, the server address is prefilled in setup. The destination is kept
in memory through setup and sign-in, and is opened after authentication.
The browser may ask before opening the app. If the app is absent, the web page
remains available. Native changes still require a new mobile build.
Native sharing supplies media titles and artwork through iOS link metadata and Android's chooser
thumbnail, while sharing the original HTTPS URL. Receiving apps control whether
they display previews. If artwork cannot load, the URL is still shared. Existing
builds without the native sharing module fall back to URL-only sharing.
### iPad sidebar
Expo Router owns navigation through `NativeTabs sidebarAdaptable`.
`native/TabletSidebar.swift` adds UIKit Library and Playlists groups and the pinned
account footer, which the current Expo Router API does not expose. The bridge
reuses the router's tab instances so each destination retains its navigation stack.
The `react-native-screens` patch checks the selected leaf controller rather than
the group's root controller. It also notifies the sidebar bridge after each native
tab reconciliation, so startup updates cannot replace the Library and Playlists
sections with a flat tab list. Keep both behaviors when updating the dependency.
After changing native modules or dependency patches, run `pod install` in `ios`
and rebuild the development app.
### Mac Catalyst
On a Mac with Xcode and CocoaPods installed, generate the iOS project with
Catalyst enabled. Use a separate checkout for Catalyst builds, since prebuild
changes the generated iOS project and its dependency configuration.
```sh
MAC_CATALYST=1 APP_VARIANT=development pnpm exec expo prebuild --platform ios --clean
open ios/*.xcworkspace
```
In Xcode, select the app scheme and the **My Mac (Mac Catalyst)** destination,
select your signing team, then build and run. For a Release build, use Xcode's
Archive action with the Catalyst destination. EAS's existing iOS profiles still
build iPhone/iPad apps.
Don't enable Catalyst by hand in Xcode; the plugin configures everything during
prebuild. It enables the Xcode target and React Native's CocoaPods patches,
raises pod deployment targets to the app's, and disables precompiled React
Native and Expo modules so dependencies can compile for Catalyst. System volume
stays under macOS control.
The Mac app uses the same bundle identifier as the iOS app, so sign both with the
same team. Handoff only pairs apps with a matching team and activity type, which
`app.config.ts` declares once per build profile in `NSUserActivityTypes`.
To return a checkout to ordinary iOS builds, rerun prebuild without
`MAC_CATALYST=1`. Keep `APP_VARIANT` consistent when starting Metro.
@@ -0,0 +1,42 @@
import Foundation
import AppIntents
internal import ExpoAppIntents
internal import ExpoModulesCore
/// Registers the app-owned intent types and their system integrations.
enum MusicAppIntents {
static func register() {
Task {
await AppIntentDispatcher.shared.setShortcutsRefreshHandler {
AppShortcuts.updateAppShortcutParameters()
}
AppShortcuts.updateAppShortcutParameters()
}
}
}
/// Registered Expo inline module that wires app-target App Intents code to expo-app-intents.
/// Do not change the name of this class.
final class AppIntentsSetup: Module {
public func definition() -> ExpoModulesCore.ModuleDefinition {
Name("AppIntentsSetup")
AsyncFunction("replaceCatalog") { (kind: String, json: String) in
try await MusicCatalogStorage.shared.replace(kind: kind, json: json)
}
AsyncFunction("catalogJSON") { (kind: String) in
let records = try await MusicCatalogStorage.shared.records(kind: kind)
return String(decoding: try JSONEncoder().encode(records), as: UTF8.self)
}
AsyncFunction("completeInvocation") { (token: String, error: String?) in
await MusicIntentExecution.shared.complete(token: token, error: error)
}
OnCreate {
MusicAppIntents.register()
MusicEntityRegistration.register()
}
}
}
@@ -0,0 +1,96 @@
import AppIntents
/// Phrases compiled into the app. Each one includes the app name, and each
/// phrase fills at most one parameter. Siri asks for anything a phrase leaves out.
struct AppShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: PlayMusicIntent(),
phrases: [
"Play music in \(.applicationName)",
"Play \(\.$song) in \(.applicationName)",
"Play the album \(\.$album) in \(.applicationName)",
"Play \(\.$artist) in \(.applicationName)",
"Play the playlist \(\.$playlist) in \(.applicationName)",
],
shortTitle: "Play Music",
systemImageName: "play.fill"
)
AppShortcut(
intent: AddToPlaylistIntent(),
phrases: [
"Add to a playlist in \(.applicationName)",
"Add \(\.$song) to a playlist in \(.applicationName)",
],
shortTitle: "Add to Playlist",
systemImageName: "text.badge.plus"
)
AppShortcut(
intent: AddToUpNextIntent(),
phrases: [
"Play \(\.$song) next in \(.applicationName)",
"Add to Up Next in \(.applicationName)",
],
shortTitle: "Add to Up Next",
systemImageName: "text.line.first.and.arrowtriangle.forward"
)
AppShortcut(
intent: ClearUpNextIntent(),
phrases: [
"Clear Up Next in \(.applicationName)",
],
shortTitle: "Clear Up Next",
systemImageName: "clear"
)
AppShortcut(
intent: CreatePlaylistIntent(),
phrases: [
"Create a playlist in \(.applicationName)",
],
shortTitle: "Create Playlist",
systemImageName: "music.note.list"
)
AppShortcut(
intent: GetCurrentSongIntent(),
phrases: [
"What's playing in \(.applicationName)",
],
shortTitle: "Get Current Song",
systemImageName: "music.note"
)
AppShortcut(
intent: LoveSongIntent(),
phrases: [
"Love this song in \(.applicationName)",
"Favorite this song in \(.applicationName)",
"Favorite song in \(.applicationName)",
],
shortTitle: "Love Song",
systemImageName: "heart.fill"
)
AppShortcut(
intent: PauseMusicIntent(),
phrases: [
"Pause \(.applicationName)",
],
shortTitle: "Pause",
systemImageName: "pause.fill"
)
AppShortcut(
intent: ResumeMusicIntent(),
phrases: [
"Resume \(.applicationName)",
],
shortTitle: "Resume",
systemImageName: "play.fill"
)
AppShortcut(
intent: SkipMusicIntent(),
phrases: [
"Skip this song in \(.applicationName)",
],
shortTitle: "Skip",
systemImageName: "forward.fill"
)
}
}
@@ -0,0 +1,625 @@
#if compiler(>=6.4)
import AppIntents
internal import ExpoAppIntents
import Foundation
import MediaIntents
/// Apple's audio schemas are what Siri and Shortcuts use for Music.app actions
/// such as play, add to library, add to playlist, love, and create station.
/// They require the iOS 27 SDK. Older compilers keep the custom intents in
/// `MusicIntents.swift`.
@available(iOS 27.0, *)
@AppEnum(schema: .audio.playbackAttributes)
enum PlaybackAttributes: String {
case shuffle
case `repeat`
static let caseDisplayRepresentations: [PlaybackAttributes: DisplayRepresentation] = [
.shuffle: "Shuffle",
.`repeat`: "Repeat",
]
}
@available(iOS 27.0, *)
@AppEnum(schema: .audio.queueInsertionLocation)
enum QueueInsertionLocation: String {
case next
case tail
static let caseDisplayRepresentations: [QueueInsertionLocation: DisplayRepresentation] = [
.next: "Play Next",
.tail: "Play Last",
]
}
@available(iOS 27.0, *)
@AppEnum(schema: .audio.affinityState)
enum AffinityState: String {
case like
case dislike
case unset
static let caseDisplayRepresentations: [AffinityState: DisplayRepresentation] = [
.like: "Like",
.dislike: "Dislike",
.unset: "Unset",
]
}
@available(iOS 27.0, *)
@UnionValue
enum PlaylistOwner {
case name(String)
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.artist)
struct AudioArtistEntity {
static let defaultQuery = AudioArtistQuery()
var id: String
var name: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(name)")
}
init(record: AppIntentEntityRecord) {
id = record.id
name = record.title
}
}
@available(iOS 27.0, *)
struct AudioArtistQuery: EntityStringQuery {
func entities(for identifiers: [AudioArtistEntity.ID]) async throws -> [AudioArtistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.artistKind, matching: identifiers)
.map(AudioArtistEntity.init(record:))
}
func suggestedEntities() async throws -> [AudioArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AudioArtistEntity.init(record:))
}
func entities(matching string: String) async throws -> [AudioArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
if string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AudioArtistEntity.init(record:))
}
return MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.nameScore)
.map(AudioArtistEntity.init(record:))
}
}
@available(iOS 27.0, *)
extension AudioArtistQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioArtistEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
return try await artists(for: urls)
@unknown default:
return []
}
}
private func artists(for urls: [URL]) async throws -> [AudioArtistEntity] {
let identifiers = urls.compactMap { url -> String? in
guard case .artist(let id) = MusicCatalog.linkTarget(from: url) else {
return nil
}
return id
}
return try await entities(for: identifiers)
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.album)
struct AudioAlbumEntity {
static let defaultQuery = AudioAlbumQuery()
var id: String
var title: String
var artistName: String
var artists: [AudioArtistEntity]
var universalProductCode: String?
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(record: AppIntentEntityRecord, artistsById: [String: AudioArtistEntity]) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? ""
universalProductCode = nil
if let artist = artistsById[record.metadata["artistId"] ?? ""] {
artists = [artist]
} else {
artists = []
}
}
}
@available(iOS 27.0, *)
struct AudioAlbumQuery: EntityStringQuery {
func entities(for identifiers: [AudioAlbumEntity.ID]) async throws -> [AudioAlbumEntity] {
let artistsById = try await Self.artistsById()
return try await MusicCatalog.records(ofKind: MusicCatalog.albumKind, matching: identifiers)
.map { AudioAlbumEntity(record: $0, artistsById: artistsById) }
}
func suggestedEntities() async throws -> [AudioAlbumEntity] {
let artistsById = try await Self.artistsById()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map { AudioAlbumEntity(record: $0, artistsById: artistsById) }
}
func entities(matching string: String) async throws -> [AudioAlbumEntity] {
let artistsById = try await Self.artistsById()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
let matches = string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
: MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.albumScore)
return matches.map { AudioAlbumEntity(record: $0, artistsById: artistsById) }
}
fileprivate static func artistsById() async throws -> [String: AudioArtistEntity] {
let artists = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
.map(AudioArtistEntity.init(record:))
return Dictionary(uniqueKeysWithValues: artists.map { ($0.id, $0) })
}
}
@available(iOS 27.0, *)
extension AudioAlbumQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioAlbumEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
let identifiers = urls.compactMap { url -> String? in
guard case .album(let id) = MusicCatalog.linkTarget(from: url) else {
return nil
}
return id
}
return try await entities(for: identifiers)
@unknown default:
return []
}
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.song)
struct AudioSongEntity {
static let defaultQuery = AudioSongQuery()
var id: String
var title: String
var artistName: String
var composerName: String?
var albumTitle: String?
var artists: [AudioArtistEntity]
var album: AudioAlbumEntity?
var composers: [AudioArtistEntity]
var internationalStandardRecordingCode: String?
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(
record: AppIntentEntityRecord,
artistsById: [String: AudioArtistEntity],
albumsById: [String: AudioAlbumEntity]
) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? ""
composerName = nil
albumTitle = record.metadata["albumTitle"]
composers = []
internationalStandardRecordingCode = nil
if let artist = artistsById[record.metadata["artistId"] ?? ""] {
artists = [artist]
} else {
artists = []
}
album = albumsById[record.metadata["albumId"] ?? ""]
}
}
@available(iOS 27.0, *)
struct AudioSongQuery: EntityStringQuery {
func entities(for identifiers: [AudioSongEntity.ID]) async throws -> [AudioSongEntity] {
let context = try await AudioLibraryContext.load()
return try await MusicCatalog.records(ofKind: MusicCatalog.songKind, matching: identifiers)
.map { context.song(from: $0) }
}
func suggestedEntities() async throws -> [AudioSongEntity] {
let context = try await AudioLibraryContext.load()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true).map {
context.song(from: $0)
}
}
func entities(matching string: String) async throws -> [AudioSongEntity] {
let context = try await AudioLibraryContext.load()
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
let matches = string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
: MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.songScore)
return matches.map { context.song(from: $0) }
}
}
@available(iOS 27.0, *)
extension AudioSongQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioSongEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
let context = try await AudioLibraryContext.load()
var matches: [AppIntentEntityRecord] = []
for url in urls {
guard let target = MusicCatalog.linkTarget(from: url) else {
continue
}
matches.append(contentsOf: try await MusicCatalog.songs(for: target))
}
return matches.map { context.song(from: $0) }
@unknown default:
return []
}
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.playlist)
struct AudioPlaylistEntity {
static let defaultQuery = AudioPlaylistQuery()
var id: String
var title: String
var owner: PlaylistOwner?
var createdByMe: Bool?
var curatedForMe: Bool?
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
let ownerName = record.metadata["ownerName"] ?? ""
owner = ownerName.isEmpty ? nil : .name(ownerName)
createdByMe = record.metadata["createdByMe"] == "1"
curatedForMe = nil
}
}
@available(iOS 27.0, *)
struct AudioPlaylistQuery: EntityStringQuery {
func entities(for identifiers: [AudioPlaylistEntity.ID]) async throws -> [AudioPlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind, matching: identifiers)
.map(AudioPlaylistEntity.init(record:))
}
func suggestedEntities() async throws -> [AudioPlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
.map(AudioPlaylistEntity.init(record:))
}
func entities(matching string: String) async throws -> [AudioPlaylistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
if string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return records.map(AudioPlaylistEntity.init(record:))
}
return MusicCatalog.rank(records, query: string, limit: 50, score: MusicCatalog.nameScore)
.map(AudioPlaylistEntity.init(record:))
}
}
@available(iOS 27.0, *)
extension AudioPlaylistQuery: IntentValueQuery {
func values(for audioSearch: AudioSearch) async throws -> [AudioPlaylistEntity] {
switch audioSearch.criteria {
case .searchQuery(let query):
return try await entities(matching: query)
case .unspecified:
return try await suggestedEntities()
case .url(let urls):
let identifiers = urls.compactMap { url -> String? in
guard case .playlist(let id) = MusicCatalog.linkTarget(from: url) else {
return nil
}
return id
}
return try await entities(for: identifiers)
@unknown default:
return []
}
}
}
@available(iOS 27.0, *)
@AppEntity(schema: .audio.warmupAudioQueueResult)
struct WarmupAudioQueueResultEntity {
static let defaultQuery = WarmupAudioQueueResultQuery()
var id: String
var title: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)")
}
}
@available(iOS 27.0, *)
struct WarmupAudioQueueResultQuery: EntityStringQuery {
func entities(for identifiers: [WarmupAudioQueueResultEntity.ID]) async throws -> [WarmupAudioQueueResultEntity] {
identifiers.compactMap { id in
guard let entry = WarmupAudioStore.entry(id: id) else {
return nil
}
return WarmupAudioQueueResultEntity(id: entry.id, title: entry.title)
}
}
func suggestedEntities() async throws -> [WarmupAudioQueueResultEntity] {
WarmupAudioStore.all().map { WarmupAudioQueueResultEntity(id: $0.id, title: $0.title) }
}
func entities(matching string: String) async throws -> [WarmupAudioQueueResultEntity] {
let query = MusicCatalog.normalized(string)
return WarmupAudioStore.all().compactMap { entry in
if query.isEmpty || MusicCatalog.normalized(entry.title).contains(query) {
return WarmupAudioQueueResultEntity(id: entry.id, title: entry.title)
}
return nil
}
}
}
@available(iOS 27.0, *)
enum WarmupAudioStore {
private static let defaultsKey = "otunes.warmupAudioQueue"
struct Entry: Codable {
var id: String
var title: String
}
static func remember(id: String, title: String) {
var entries = all()
entries.removeAll { $0.id == id }
entries.append(Entry(id: id, title: title))
if entries.count > 20 {
entries = Array(entries.suffix(20))
}
if let data = try? JSONEncoder().encode(entries) {
UserDefaults.standard.set(data, forKey: defaultsKey)
}
}
static func entry(id: String) -> Entry? {
all().first { $0.id == id }
}
static func all() -> [Entry] {
guard let data = UserDefaults.standard.data(forKey: defaultsKey),
let entries = try? JSONDecoder().decode([Entry].self, from: data)
else {
return []
}
return entries
}
}
@available(iOS 27.0, *)
@UnionValue
enum AudioItem {
case song(AudioSongEntity)
case album(AudioAlbumEntity)
case artist(AudioArtistEntity)
case playlist(AudioPlaylistEntity)
var kind: String {
switch self {
case .song:
return "song"
case .album:
return "album"
case .artist:
return "artist"
case .playlist:
return "playlist"
}
}
var itemId: String {
switch self {
case .song(let song):
return song.id
case .album(let album):
return album.id
case .artist(let artist):
return artist.id
case .playlist(let playlist):
return playlist.id
}
}
var itemTitle: String {
switch self {
case .song(let song):
return song.title
case .album(let album):
return album.title
case .artist(let artist):
return artist.name
case .playlist(let playlist):
return playlist.title
}
}
}
@available(iOS 27.0, *)
private struct AudioLibraryContext {
var artistsById: [String: AudioArtistEntity]
var albumsById: [String: AudioAlbumEntity]
static func load() async throws -> AudioLibraryContext {
let artistsById = try await AudioAlbumQuery.artistsById()
let albums = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind).map {
AudioAlbumEntity(record: $0, artistsById: artistsById)
}
return AudioLibraryContext(
artistsById: artistsById,
albumsById: Dictionary(uniqueKeysWithValues: albums.map { ($0.id, $0) })
)
}
func song(from record: AppIntentEntityRecord) -> AudioSongEntity {
AudioSongEntity(record: record, artistsById: artistsById, albumsById: albumsById)
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.playAudio)
struct PlayAudioIntent: AudioStartingIntent {
static let openAppWhenRun = true
var audioEntity: AudioItem
var playbackAttributes: Set<PlaybackAttributes>
var warmupAudioQueueResult: WarmupAudioQueueResultEntity?
var queueLocation: QueueInsertionLocation?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let queue: String
switch queueLocation {
case .next:
queue = "next"
case .tail:
queue = "tail"
case nil:
queue = "now"
}
try await MusicCommands.play(
kind: audioEntity.kind,
id: audioEntity.itemId,
title: audioEntity.itemTitle,
shuffle: playbackAttributes.contains(.shuffle),
repeatMode: playbackAttributes.contains(.`repeat`) ? "all" : "none",
queue: queue,
warmupId: warmupAudioQueueResult?.id
)
return .result(dialog: "Playing \(audioEntity.itemTitle).")
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.warmupAudioQueue)
struct WarmupAudioQueueIntent {
static let openAppWhenRun = true
var audioEntity: AudioItem
var playbackAttributes: Set<PlaybackAttributes>
@MainActor
func perform() async throws -> some IntentResult & ReturnsValue<WarmupAudioQueueResultEntity> {
let id = try await MusicCommands.warmup(
kind: audioEntity.kind,
id: audioEntity.itemId,
title: audioEntity.itemTitle,
shuffle: playbackAttributes.contains(.shuffle)
)
WarmupAudioStore.remember(id: id, title: audioEntity.itemTitle)
let result = WarmupAudioQueueResultEntity(id: id, title: audioEntity.itemTitle)
return .result(value: result)
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.addToPlaylist)
struct AddAudioToPlaylistIntent {
static let openAppWhenRun = true
var audioEntity: AudioItem
var playlist: AudioPlaylistEntity
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
if audioEntity.kind == "playlist" && audioEntity.itemId == playlist.id {
throw MusicIntentFailure("Choose a different playlist.")
}
try await MusicCommands.addToPlaylist(
playlistId: playlist.id,
sources: [(kind: audioEntity.kind, id: audioEntity.itemId)]
)
return .result(dialog: "Adding to \(playlist.title).")
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.updateAudioAffinity)
struct UpdateAudioAffinityIntent {
static let openAppWhenRun = true
var affinityState: AffinityState
var target: AudioItem
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
if affinityState == .dislike {
throw MusicIntentFailure("oTunes doesn't keep dislikes. You can unlike it instead.")
}
if target.kind == "playlist" {
throw MusicIntentFailure("oTunes can love songs, albums, and artists.")
}
let state = affinityState == .like ? "like" : "unset"
try await MusicCommands.updateAffinity(kind: target.kind, id: target.itemId, state: state)
let verb = affinityState == .like ? "Loving" : "Unliking"
return .result(dialog: "\(verb) \(target.itemTitle).")
}
}
@available(iOS 27.0, *)
@AppIntent(schema: .audio.createStation)
struct CreateAudioStationIntent {
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
if song.artistId.isEmpty {
throw MusicIntentFailure("oTunes can't find an artist for this song.")
}
try await MusicCommands.createStation(artistId: song.artistId, artistName: song.artistName)
let artist = song.artistName.isEmpty ? "this artist" : song.artistName
return .result(dialog: "Playing more by \(artist).")
}
}
#endif
@@ -0,0 +1,332 @@
import AppIntents
internal import ExpoAppIntents
import Foundation
struct MusicIntentFailure: Error, CustomLocalizedStringResourceConvertible {
let localizedStringResource: LocalizedStringResource
init(_ message: String) {
localizedStringResource = LocalizedStringResource(stringLiteral: message)
}
}
enum MusicLinkTarget {
case song(String)
case album(String)
case artist(String)
case playlist(String)
}
/// Reads the full disk-backed catalogs JavaScript publishes and turns
/// spoken requests into those records. The same kinds back Shortcuts pickers and,
/// on iOS 27, the audio schemas Siri uses for Apple Music-style requests.
enum MusicCatalog {
static let songKind = "song"
static let albumKind = "album"
static let artistKind = "artist"
static let playlistKind = "playlist"
static let nowPlayingKind = "nowPlaying"
/// Kept in sync with the catalog query and the JavaScript bridge.
static let favoritesPlaylistId = "otunes:favorites"
static func records(ofKind kind: String) async throws -> [AppIntentEntityRecord] {
try await MusicCatalogStorage.shared.records(kind: kind)
}
static func records(ofKind kind: String, matching identifiers: [String]) async throws -> [AppIntentEntityRecord] {
try await records(ofKind: kind).filter { identifiers.contains($0.id) }
}
static func currentSong() async throws -> SongEntity? {
guard let current = try await records(ofKind: nowPlayingKind).first else {
return nil
}
if let song = try await SongQuery().entities(for: [current.id]).first {
return song
}
return SongEntity(record: current)
}
static func normalized(_ value: String) -> String {
value
.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
.trimmingCharacters(in: .whitespacesAndNewlines)
}
static func cleanedQuery(_ query: String) -> String {
var text = normalized(query)
let prefixes = [
"the song ", "the album ", "the artist ", "the playlist ",
"songs by ", "music by ", "song ", "album ", "artist ", "playlist ", "some ",
]
var didStrip = true
while didStrip {
didStrip = false
for prefix in prefixes where text.hasPrefix(prefix) {
text = String(text.dropFirst(prefix.count))
.trimmingCharacters(in: .whitespacesAndNewlines)
didStrip = true
}
}
return text
}
static func rank(
_ records: [AppIntentEntityRecord],
query: String,
limit: Int,
score: (AppIntentEntityRecord, String) -> Int
) -> [AppIntentEntityRecord] {
let cleaned = cleanedQuery(query)
guard !cleaned.isEmpty else {
return []
}
return records
.compactMap { record -> (AppIntentEntityRecord, Int)? in
let value = score(record, cleaned)
return value > 0 ? (record, value) : nil
}
.sorted { lhs, rhs in
if lhs.1 != rhs.1 {
return lhs.1 > rhs.1
}
return lhs.0.title.localizedCaseInsensitiveCompare(rhs.0.title) == .orderedAscending
}
.prefix(limit)
.map(\.0)
}
static func songScore(_ record: AppIntentEntityRecord, _ query: String) -> Int {
let title = normalized(record.title)
let artist = normalized(record.metadata["artistName"] ?? "")
if title == query {
return 100
}
if let range = query.range(of: " by ") {
let titlePart = normalized(String(query[..<range.lowerBound]))
let artistPart = normalized(String(query[range.upperBound...]))
var score = 0
if !titlePart.isEmpty && (title == titlePart || title.contains(titlePart)) {
score += title == titlePart ? 70 : 50
}
if !artistPart.isEmpty && (artist == artistPart || artist.contains(artistPart)) {
score += artist == artistPart ? 30 : 20
}
return score >= 50 ? score : 0
}
if title.contains(query) || (query.contains(title) && title.count > 2) {
return title.contains(query) ? 80 : 60
}
return 0
}
static func albumScore(_ record: AppIntentEntityRecord, _ query: String) -> Int {
let title = normalized(record.title)
let artist = normalized(record.metadata["artistName"] ?? "")
if title == query {
return 100
}
if title.contains(query) || (query.contains(title) && title.count > 2) {
return 80
}
if artist == query {
return 45
}
if artist.contains(query) && query.count > 2 {
return 30
}
return 0
}
static func nameScore(_ record: AppIntentEntityRecord, _ query: String) -> Int {
let name = normalized(record.title)
let synonyms = record.synonyms.map(normalized)
if name == query || synonyms.contains(query) {
return 100
}
if name.contains(query) || synonyms.contains(where: { $0.contains(query) }) {
return 80
}
if query.contains(name) && name.count > 2 {
return 60
}
return 0
}
static func suggested(
_ records: [AppIntentEntityRecord],
limit: Int,
favoritesFirst: Bool
) -> [AppIntentEntityRecord] {
let pool: [AppIntentEntityRecord]
if favoritesFirst {
let favorites = records.filter { $0.metadata["favorite"] == "1" }
pool = favorites.isEmpty ? records : favorites
} else {
pool = records
}
return Array(pool.prefix(limit))
}
static func linkTarget(from url: URL) -> MusicLinkTarget? {
let parts = url.path.split(separator: "/").map(String.init).filter { !$0.isEmpty }
guard let kind = parts.first, parts.count >= 2 else {
return nil
}
let id = parts[1]
switch kind {
case "album":
if let songId = URLComponents(url: url, resolvingAgainstBaseURL: false)?
.queryItems?
.first(where: { $0.name == "s" })?
.value,
!songId.isEmpty
{
return .song(songId)
}
return .album(id)
case "artist":
return .artist(id)
case "playlist":
return .playlist(id == "favorites" ? favoritesPlaylistId : id)
default:
return nil
}
}
static func songs(for target: MusicLinkTarget) async throws -> [AppIntentEntityRecord] {
let songs = try await records(ofKind: songKind)
switch target {
case .song(let id):
return songs.filter { $0.id == id }
case .album(let id):
return Array(songs.filter { $0.metadata["albumId"] == id }.prefix(25))
case .artist(let id):
return Array(songs.filter { $0.metadata["artistId"] == id }.prefix(25))
case .playlist:
return []
}
}
static func formatDuration(_ seconds: Int) -> String {
guard seconds > 0 else {
return ""
}
return String(format: "%d:%02d", seconds / 60, seconds % 60)
}
}
enum MusicCommands {
static func play(
kind: String,
id: String,
title: String,
shuffle: Bool?,
repeatMode: String?,
queue: String,
warmupId: String?
) async throws -> String {
let params: AppIntentParams = [
"kind": .string(kind),
"id": .string(id),
"title": .string(title),
"queue": .string(queue),
"shuffle": shuffle.map { .string($0 ? "songs" : "off") } ?? .null,
"repeat": repeatMode.map(AppIntentValue.string) ?? .null,
"warmupId": warmupId.map(AppIntentValue.string) ?? .null,
]
return try await MusicIntentExecution.shared.run(name: "playMusic", params: params)
}
static func warmup(kind: String, id: String, title: String, shuffle: Bool) async throws -> String {
try await MusicIntentExecution.shared.run(
name: "warmupAudio",
params: [
"kind": .string(kind),
"id": .string(id),
"title": .string(title),
"shuffle": .string(shuffle ? "songs" : "off"),
]
)
}
static func addToPlaylist(playlistId: String, sources: [(kind: String, id: String)]) async throws {
try await MusicIntentExecution.shared.run(
name: "addToPlaylist",
params: [
"playlistId": .string(playlistId),
"sources": .array(sources.map { source in
.object([
"kind": .string(source.kind),
"id": .string(source.id),
])
}),
]
)
}
static func addToUpNext(
position: String,
sources: [(kind: String, id: String)]
) async throws {
try await MusicIntentExecution.shared.run(
name: "addToUpNext",
params: [
"position": .string(position),
"sources": .array(sources.map { source in
.object([
"kind": .string(source.kind),
"id": .string(source.id),
])
}),
]
)
}
static func createPlaylist(name: String, sources: [(kind: String, id: String)]) async throws {
try await MusicIntentExecution.shared.run(
name: "createPlaylist",
params: [
"name": .string(name),
"sources": .array(sources.map { source in
.object([
"kind": .string(source.kind),
"id": .string(source.id),
])
}),
]
)
}
static func clearUpNext() async throws {
try await MusicIntentExecution.shared.run(name: "clearUpNext")
}
static func createStation(artistId: String, artistName: String) async throws {
try await MusicIntentExecution.shared.run(
name: "createStation",
params: [
"artistId": .string(artistId),
"title": .string(artistName),
]
)
}
static func updateAffinity(kind: String, id: String, state: String) async throws {
try await MusicIntentExecution.shared.run(
name: "updateAffinity",
params: [
"kind": .string(kind),
"id": .string(id),
"state": .string(state),
]
)
}
static func transport(_ command: String) async throws {
try await MusicIntentExecution.shared.run(
name: "transport",
params: ["command": .string(command)]
)
}
}
@@ -0,0 +1,245 @@
import AppIntents
@preconcurrency import CoreSpotlight
internal import ExpoAppIntents
internal import ExpoModulesCore
import UniformTypeIdentifiers
enum MusicEntityRegistration {
static func register() {
AppIntentDonationRegistry.shared.register("playMusic", as: PlayMusicIntent.self)
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("song", as: SongEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("song", as: SongEntity.self)
}
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("album", as: AlbumEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("album", as: AlbumEntity.self)
}
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("artist", as: ArtistEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("artist", as: ArtistEntity.self)
}
if #available(iOS 18.0, *) {
AppEntityIdentifierRegistry.shared.registerIndexed("playlist", as: PlaylistEntity.self)
} else {
AppEntityIdentifierRegistry.shared.register("playlist", as: PlaylistEntity.self)
}
}
}
extension SongEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension SongEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = title
attributes.displayName = title
attributes.contentDescription = "\(artistName) · \(albumTitle)"
attributes.keywords = [title, artistName, albumTitle, "music", "song"]
return attributes
}
}
struct OpenSongIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Song"
static let openAppWhenRun = true
@Parameter(title: "Song")
var target: SongEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("song"), "id": .string(target.id)]
)
return .result()
}
}
extension AlbumEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension AlbumEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = title
attributes.displayName = title
attributes.contentDescription = artistName
attributes.keywords = [title, artistName, "music", "album"]
return attributes
}
}
struct OpenAlbumIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Album"
static let openAppWhenRun = true
@Parameter(title: "Album")
var target: AlbumEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("album"), "id": .string(target.id)]
)
return .result()
}
}
extension ArtistEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension ArtistEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = name
attributes.displayName = name
attributes.contentDescription = "oTunes artist"
attributes.keywords = [name, "music", "artist"]
return attributes
}
}
struct OpenArtistIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Artist"
static let openAppWhenRun = true
@Parameter(title: "Artist")
var target: ArtistEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("artist"), "id": .string(target.id)]
)
return .result()
}
}
extension PlaylistEntity: AppIntentEntityRecordConvertible {}
@available(iOS 18.0, *)
extension PlaylistEntity: IndexedEntity {
var attributeSet: CSSearchableItemAttributeSet {
let attributes = CSSearchableItemAttributeSet(contentType: .text)
attributes.title = title
attributes.displayName = title
attributes.contentDescription = "oTunes playlist"
attributes.keywords = [title, "music", "playlist"]
return attributes
}
}
struct OpenPlaylistIntent: OpenIntent {
static let title: LocalizedStringResource = "Open Playlist"
static let openAppWhenRun = true
@Parameter(title: "Playlist")
var target: PlaylistEntity
@MainActor
func perform() async throws -> some IntentResult {
_ = try await MusicIntentExecution.shared.run(
name: "openMusic", params: ["kind": .string("playlist"), "id": .string(target.id)]
)
return .result()
}
}
extension PlayMusicIntent: DonatableAppIntent {
struct DonationParams: Record {
@Field(.required) var kind: String = ""
@Field(.required) var id: String = ""
@Field var shuffle: Bool = false
}
init(donationParams: DonationParams) async throws {
self.init()
shuffle = donationParams.shuffle ? .songs : .off
switch donationParams.kind {
case "song":
guard let value = try await SongQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This song is no longer available.")
}
song = value
case "album":
guard let value = try await AlbumQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This album is no longer available.")
}
album = value
case "artist":
guard let value = try await ArtistQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This artist is no longer available.")
}
artist = value
case "playlist":
guard let value = try await PlaylistQuery().entities(for: [donationParams.id]).first else {
throw MusicIntentFailure("This playlist is no longer available.")
}
playlist = value
default:
throw MusicIntentFailure("Unknown music type.")
}
}
}
// The system can recover an evicted Spotlight index without waiting for the next
// catalog refresh. Rebuild only the compact catalog published to expo-app-intents.
#if compiler(>=6.4)
@available(iOS 27.0, *)
extension SongQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [SongEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "song", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "song")
}
}
@available(iOS 27.0, *)
extension AlbumQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [AlbumEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "album", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "album")
}
}
@available(iOS 27.0, *)
extension ArtistQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [ArtistEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "artist", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "artist")
}
}
@available(iOS 27.0, *)
extension PlaylistQuery: IndexedEntityQuery {
func reindexEntities(
for identifiers: [PlaylistEntity.ID], indexDescription: CSSearchableIndexDescription
) async throws {
try await AppEntityIdentifierRegistry.shared.updateIndexFromCatalog(kind: "playlist", matching: identifiers)
}
func reindexAllEntities(indexDescription: CSSearchableIndexDescription) async throws {
try await AppEntityIdentifierRegistry.shared.replaceIndexFromCatalog(kind: "playlist")
}
}
#endif
@@ -0,0 +1,301 @@
import AppIntents
internal import ExpoAppIntents
import Foundation
struct SongEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Song")
static let defaultQuery = SongQuery()
var id: String
var title: String
var artistName: String
var artistId: String
var albumTitle: String
var albumId: String
var durationSeconds: Int
var genres: String
var year: String
var trackNumber: String
var discNumber: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? record.subtitle ?? ""
artistId = record.metadata["artistId"] ?? ""
albumTitle = record.metadata["albumTitle"] ?? ""
albumId = record.metadata["albumId"] ?? ""
durationSeconds = Int(record.metadata["duration"] ?? "") ?? 0
genres = record.metadata["genres"] ?? ""
year = record.metadata["year"] ?? ""
trackNumber = record.metadata["track"] ?? ""
discNumber = record.metadata["disk"] ?? ""
}
}
struct SongQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [SongEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.songKind, matching: identifiers)
.map(SongEntity.init(record:))
}
func suggestedEntities() async throws -> [SongEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(SongEntity.init(record:))
}
func entities(matching string: String) async throws -> [SongEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.songKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(SongEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.songScore)
.map(SongEntity.init(record:))
}
}
struct AlbumEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Album")
static let defaultQuery = AlbumQuery()
var id: String
var title: String
var artistName: String
var artistId: String
var year: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)", subtitle: "\(artistName)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
artistName = record.metadata["artistName"] ?? record.subtitle ?? ""
artistId = record.metadata["artistId"] ?? ""
year = record.metadata["year"] ?? ""
}
}
struct AlbumQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [AlbumEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.albumKind, matching: identifiers)
.map(AlbumEntity.init(record:))
}
func suggestedEntities() async throws -> [AlbumEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AlbumEntity.init(record:))
}
func entities(matching string: String) async throws -> [AlbumEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.albumKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(AlbumEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.albumScore)
.map(AlbumEntity.init(record:))
}
}
struct ArtistEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Artist")
static let defaultQuery = ArtistQuery()
var id: String
var name: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(name)")
}
init(record: AppIntentEntityRecord) {
id = record.id
name = record.title
}
}
struct ArtistQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [ArtistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.artistKind, matching: identifiers)
.map(ArtistEntity.init(record:))
}
func suggestedEntities() async throws -> [ArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(ArtistEntity.init(record:))
}
func entities(matching string: String) async throws -> [ArtistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.artistKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return MusicCatalog.suggested(records, limit: 25, favoritesFirst: true)
.map(ArtistEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.nameScore)
.map(ArtistEntity.init(record:))
}
}
struct PlaylistEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Playlist")
static let defaultQuery = PlaylistQuery()
var id: String
var title: String
var ownerName: String
var createdByMe: Bool
var displayRepresentation: DisplayRepresentation {
if ownerName.isEmpty {
return DisplayRepresentation(title: "\(title)")
}
return DisplayRepresentation(title: "\(title)", subtitle: "\(ownerName)")
}
init(record: AppIntentEntityRecord) {
id = record.id
title = record.title
ownerName = record.metadata["ownerName"] ?? record.subtitle ?? ""
createdByMe = record.metadata["createdByMe"] == "1"
}
}
struct PlaylistQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [PlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind, matching: identifiers)
.map(PlaylistEntity.init(record:))
}
func suggestedEntities() async throws -> [PlaylistEntity] {
try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
.map(PlaylistEntity.init(record:))
}
func entities(matching string: String) async throws -> [PlaylistEntity] {
let records = try await MusicCatalog.records(ofKind: MusicCatalog.playlistKind)
let query = string.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isEmpty {
return records.map(PlaylistEntity.init(record:))
}
return MusicCatalog.rank(records, query: query, limit: 50, score: MusicCatalog.nameScore)
.map(PlaylistEntity.init(record:))
}
}
enum MusicShuffle: String, AppEnum {
case off
case songs
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Shuffle")
static let caseDisplayRepresentations: [MusicShuffle: DisplayRepresentation] = [
.off: "Off",
.songs: "Songs",
]
}
enum MusicRepeat: String, AppEnum {
case none
case one
case all
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Repeat")
static let caseDisplayRepresentations: [MusicRepeat: DisplayRepresentation] = [
.none: "None",
.one: "One",
.all: "All",
]
}
enum UpNextPosition: String, AppEnum {
case next
case last
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Position")
static let caseDisplayRepresentations: [UpNextPosition: DisplayRepresentation] = [
.next: "Play Next",
.last: "Play Last",
]
}
enum MusicDetail: String, AppEnum {
case title
case artist
case album
case albumArtist
case genre
case duration
case year
case trackNumber
case discNumber
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Detail")
static let caseDisplayRepresentations: [MusicDetail: DisplayRepresentation] = [
.title: "Title",
.artist: "Artist",
.album: "Album",
.albumArtist: "Album Artist",
.genre: "Genre",
.duration: "Duration",
.year: "Year",
.trackNumber: "Track Number",
.discNumber: "Disc Number",
]
}
enum MusicSelection {
static func sources(
song: SongEntity?,
album: AlbumEntity?,
artist: ArtistEntity?,
playlist: PlaylistEntity?
) throws -> [(kind: String, id: String, title: String)] {
var sources: [(kind: String, id: String, title: String)] = []
if let song {
sources.append(("song", song.id, song.title))
}
if let album {
sources.append(("album", album.id, album.title))
}
if let artist {
sources.append(("artist", artist.id, artist.name))
}
if let playlist {
sources.append(("playlist", playlist.id, playlist.title))
}
if sources.isEmpty {
throw MusicIntentFailure("Choose a song, album, artist, or playlist.")
}
return sources
}
static func singleTarget(
song: SongEntity?,
album: AlbumEntity?,
artist: ArtistEntity?,
playlist: PlaylistEntity?
) throws -> (kind: String, id: String, title: String)? {
let sources = [
song.map { (kind: "song", id: $0.id, title: $0.title) },
album.map { (kind: "album", id: $0.id, title: $0.title) },
artist.map { (kind: "artist", id: $0.id, title: $0.name) },
playlist.map { (kind: "playlist", id: $0.id, title: $0.title) },
].compactMap { $0 }
if sources.count > 1 {
throw MusicIntentFailure("Choose one song, album, artist, or playlist.")
}
return sources.first
}
}
@@ -0,0 +1,425 @@
import AppIntents
import Foundation
// Actions that use the React player or authenticated mutations open the app and
// wait for its acknowledgment. Native catalog reads can run without opening it.
struct PlayMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Play Music"
static let description = IntentDescription("Plays music using oTunes.")
static let openAppWhenRun = true
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@Parameter(title: "Shuffle")
var shuffle: MusicShuffle?
@Parameter(title: "Repeat")
var repeatMode: MusicRepeat?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let target = try MusicSelection.singleTarget(
song: song,
album: album,
artist: artist,
playlist: playlist
)
let kind = target?.0 ?? "resume"
let id = target?.1 ?? ""
let name = target?.2 ?? "your music"
try await MusicCommands.play(
kind: kind,
id: id,
title: name,
shuffle: shuffle.map { $0 == .songs },
repeatMode: repeatMode?.rawValue,
queue: "now",
warmupId: nil
)
return .result(dialog: "Playing \(name).")
}
}
struct AddToPlaylistIntent: AppIntent {
static let title: LocalizedStringResource = "Add to Playlist"
static let description = IntentDescription(
"Adds the items passed as input to the specified playlist."
)
static let openAppWhenRun = true
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Music")
var sourcePlaylist: PlaylistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let sources = try MusicSelection.sources(
song: song,
album: album,
artist: artist,
playlist: sourcePlaylist
)
if sources.contains(where: { $0.id == playlist.id && $0.kind == "playlist" }) {
throw MusicIntentFailure("Choose a different playlist.")
}
try await MusicCommands.addToPlaylist(
playlistId: playlist.id,
sources: sources.map { (kind: $0.kind, id: $0.id) }
)
return .result(dialog: "Adding to \(playlist.title).")
}
}
struct AddToUpNextIntent: AppIntent {
static let title: LocalizedStringResource = "Add to Up Next"
static let description = IntentDescription(
"Adds the music passed as input to your Up Next queue."
)
static let openAppWhenRun = true
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@Parameter(title: "Position", default: .next)
var position: UpNextPosition
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let sources = try MusicSelection.sources(
song: song,
album: album,
artist: artist,
playlist: playlist
)
try await MusicCommands.addToUpNext(
position: position.rawValue,
sources: sources.map { (kind: $0.kind, id: $0.id) }
)
let placement = position == .next ? "Playing this next." : "Adding this to the end of Up Next."
return .result(dialog: "\(placement)")
}
}
struct ClearUpNextIntent: AppIntent {
static let title: LocalizedStringResource = "Clear Up Next"
static let description = IntentDescription("Clears the Up Next queue.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.clearUpNext()
return .result(dialog: "Clearing Up Next.")
}
}
struct CreatePlaylistIntent: AppIntent {
static let title: LocalizedStringResource = "Create Playlist"
static let description = IntentDescription(
"Creates a new playlist, adding any items passed as input."
)
static let openAppWhenRun = true
@Parameter(title: "Name")
var name: String
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
throw MusicIntentFailure("A playlist needs a name.")
}
let sources = [
song.map { (kind: "song", id: $0.id) },
album.map { (kind: "album", id: $0.id) },
artist.map { (kind: "artist", id: $0.id) },
playlist.map { (kind: "playlist", id: $0.id) },
].compactMap { $0 }
try await MusicCommands.createPlaylist(name: trimmed, sources: sources)
return .result(dialog: "Creating \(trimmed).")
}
}
struct GetCurrentSongIntent: AppIntent {
static let title: LocalizedStringResource = "Get Current Song"
static let description = IntentDescription(
"Returns the song that is currently playing in oTunes, if any."
)
static let openAppWhenRun = false
@MainActor
func perform() async throws -> some IntentResult & ReturnsValue<SongEntity> & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
return .result(value: song, dialog: "\(song.title)")
}
}
struct GetDetailsOfMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Get Details of Music"
static let description = IntentDescription(
"Gets a specific piece of information from the music passed into the action."
)
static let openAppWhenRun = false
@Parameter(title: "Song")
var song: SongEntity?
@Parameter(title: "Album")
var album: AlbumEntity?
@Parameter(title: "Artist")
var artist: ArtistEntity?
@Parameter(title: "Playlist")
var playlist: PlaylistEntity?
@Parameter(title: "Detail")
var detail: MusicDetail
@MainActor
func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
let value = try await detailValue()
return .result(value: value, dialog: value.isEmpty ? "Not available." : "\(value)")
}
private func detailValue() async throws -> String {
if let target = try MusicSelection.singleTarget(
song: song,
album: album,
artist: artist,
playlist: playlist
) {
return try value(for: target)
}
guard let current = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Choose music, or play a song in oTunes first.")
}
return Self.value(detail, song: current)
}
private func value(for target: (kind: String, id: String, title: String)) throws -> String {
switch target.kind {
case "song":
guard let song else {
throw MusicIntentFailure("That song is no longer in your library.")
}
return Self.value(detail, song: song)
case "album":
guard let album else {
throw MusicIntentFailure("That album is no longer in your library.")
}
return Self.value(detail, album: album)
case "artist":
guard let artist else {
throw MusicIntentFailure("That artist is no longer in your library.")
}
return Self.value(detail, artist: artist)
case "playlist":
guard let playlist else {
throw MusicIntentFailure("That playlist is no longer in your library.")
}
return Self.value(detail, playlist: playlist)
default:
throw MusicIntentFailure("oTunes can't read that.")
}
}
private static func value(_ detail: MusicDetail, song: SongEntity) -> String {
switch detail {
case .title:
return song.title
case .artist, .albumArtist:
return song.artistName
case .album:
return song.albumTitle
case .genre:
return song.genres
case .duration:
return MusicCatalog.formatDuration(song.durationSeconds)
case .year:
return song.year == "0" ? "" : song.year
case .trackNumber:
return song.trackNumber
case .discNumber:
return song.discNumber
}
}
private static func value(_ detail: MusicDetail, album: AlbumEntity) -> String {
switch detail {
case .title, .album:
return album.title
case .artist, .albumArtist:
return album.artistName
case .year:
return album.year == "0" ? "" : album.year
case .genre, .duration, .trackNumber, .discNumber:
return ""
}
}
private static func value(_ detail: MusicDetail, artist: ArtistEntity) -> String {
switch detail {
case .title, .artist, .albumArtist:
return artist.name
case .album, .genre, .duration, .year, .trackNumber, .discNumber:
return ""
}
}
private static func value(_ detail: MusicDetail, playlist: PlaylistEntity) -> String {
switch detail {
case .title:
return playlist.title
case .artist, .albumArtist:
return playlist.ownerName
case .album, .genre, .duration, .year, .trackNumber, .discNumber:
return ""
}
}
}
struct LoveSongIntent: AppIntent {
static let title: LocalizedStringResource = "Love Song"
static let description = IntentDescription(
"Loves the song that is playing in oTunes. Also used for Favorite Song."
)
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
try await MusicCommands.updateAffinity(kind: "song", id: song.id, state: "like")
return .result(dialog: "Loving \(song.title).")
}
}
struct UnlikeSongIntent: AppIntent {
static let title: LocalizedStringResource = "Unlike Song"
static let description = IntentDescription("Removes the love from the song that is playing.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
try await MusicCommands.updateAffinity(kind: "song", id: song.id, state: "unset")
return .result(dialog: "Unliking \(song.title).")
}
}
struct CreateStationIntent: AppIntent {
static let title: LocalizedStringResource = "Create Station"
static let description = IntentDescription(
"Plays more music by the artist of the song that is playing."
)
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let song = try await MusicCatalog.currentSong() else {
throw MusicIntentFailure("Nothing is playing in oTunes.")
}
if song.artistId.isEmpty {
throw MusicIntentFailure("oTunes can't find an artist for this song.")
}
try await MusicCommands.createStation(artistId: song.artistId, artistName: song.artistName)
let artist = song.artistName.isEmpty ? "this artist" : song.artistName
return .result(dialog: "Playing more by \(artist).")
}
}
struct PauseMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Pause Music"
static let description = IntentDescription("Pauses playback in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("pause")
return .result(dialog: "Pausing.")
}
}
struct ResumeMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Resume Music"
static let description = IntentDescription("Resumes playback in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("resume")
return .result(dialog: "Resuming.")
}
}
struct SkipMusicIntent: AppIntent {
static let title: LocalizedStringResource = "Skip Song"
static let description = IntentDescription("Skips to the next song in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("next")
return .result(dialog: "Skipping.")
}
}
struct PreviousTrackIntent: AppIntent {
static let title: LocalizedStringResource = "Previous Song"
static let description = IntentDescription("Goes back to the previous song in oTunes.")
static let openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
try await MusicCommands.transport("previous")
return .result(dialog: "Going back.")
}
}
@@ -0,0 +1,70 @@
import Foundation
internal import ExpoAppIntents
/// Full catalogs live in Application Support, never in UserDefaults. The package
/// catalog contains only a bounded selection for shortcut suggestions and Spotlight.
actor MusicCatalogStorage {
static let shared = MusicCatalogStorage()
private func location(_ kind: String) throws -> URL {
guard ["song", "album", "artist", "playlist", "nowPlaying"].contains(kind) else {
throw MusicIntentFailure("Unknown music catalog.")
}
let directory = try FileManager.default.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true
).appendingPathComponent("MusicIntents", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
return directory.appendingPathComponent("\(kind).json")
}
func replace(kind: String, json: String) throws {
let data = Data(json.utf8)
let records = try JSONDecoder().decode([AppIntentEntityRecord].self, from: data)
guard Set(records.map(\.id)).count == records.count,
records.allSatisfy({ !$0.id.isEmpty && !$0.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty })
else { throw MusicIntentFailure("Invalid music catalog.") }
try data.write(to: location(kind), options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
}
func records(kind: String) throws -> [AppIntentEntityRecord] {
let url = try location(kind)
guard FileManager.default.fileExists(atPath: url.path) else { return [] }
return try JSONDecoder().decode([AppIntentEntityRecord].self, from: Data(contentsOf: url))
}
}
/// App-owned completion channel. Expo's dispatcher itself remains one-way.
actor MusicIntentExecution {
static let shared = MusicIntentExecution()
private var waiting = Set<String>()
private var results: [String: String] = [:]
func complete(token: String, error: String?) {
guard waiting.contains(token) else { return }
results[token] = error ?? ""
}
func run(name: String, params: AppIntentParams = [:]) async throws -> String {
let token = UUID().uuidString
let deadline = Date().addingTimeInterval(25)
waiting.insert(token)
defer {
waiting.remove(token)
results.removeValue(forKey: token)
}
var payload = params
payload["completionToken"] = .string(token)
payload["deadline"] = .double(deadline.timeIntervalSince1970 * 1000)
let id = await AppIntentDispatcher.shared.dispatch(name: name, params: payload)
while Date() < deadline {
try Task.checkCancellation()
if let error = results.removeValue(forKey: token) {
if !error.isEmpty { throw MusicIntentFailure(error) }
return id
}
try await Task.sleep(for: .milliseconds(100))
}
throw MusicIntentFailure("oTunes did not finish in time. Open the app, check your connection, and try again.")
}
}
+35
View File
@@ -0,0 +1,35 @@
# Siri and Shortcuts
This integration uses Expo 58 inline modules and `expo-app-intents`. Rebuild the native app after changing Swift declarations or registrations. An OTA JavaScript update cannot add these capabilities.
Playback and library changes open oTunes because they need its authenticated React runtime. Swift dispatches a request and waits for an app-owned completion acknowledgment. Playback waits for the native audio player to load the requested track; warmup waits for it to load while paused. Errors reach Siri, and requests that have expired are discarded before starting a side effect. Native catalog reads do not open the app.
The full entity catalog lives in Application Support. Expo's UserDefaults catalog holds at most 100 suggestions per kind, with favorites first, and mirrors those suggestions into Spotlight. Siri's native queries search the full disk catalog.
Sync is incremental. The app subscribes to `intentCatalog.head`, the newest insert, rename or deletion per kind, and fetches a kind only when it moves past the cursor stored in AsyncStorage. `intentCatalog.page` then returns records created after the cursor plus renames and deletions from the `intentCatalogChanges` log. The log keeps 30 days; older cursors, or more than 2,000 changes, rebuild that kind from scratch. Favorites are stamped onto records on device from the favorites subscription, so liking a song costs no catalog queries. Playlists come from the live `intentCatalog.playlists` query. Code lives in `components/app-intents/`: `catalog-sync.ts`, `now-playing.ts`, and `dispatch.ts`.
Songs, albums, artists, and playlists have Spotlight open intents and on-screen entity associations. Associations require iOS 18.4 and Xcode 27; Spotlight indexing requires iOS 18. Playback donations are made after the player starts, preserve shuffle, and resolve real catalog entities. Removed records trigger donation cleanup. Sign-out clears catalogs, Spotlight entries, donations, and pending invocations. On iOS 27, the query types also handle system requests to rebuild Spotlight indexes.
Audio schema intents require Xcode 27 and iOS 27. Custom intents remain available on earlier supported versions and remain visible on iOS 27 because intent discovery metadata must be a compile-time constant.
## Backend rollout
Deploy the companion Convex changes before installing the new mobile build:
- `intentCatalog.head`, `intentCatalog.page` and `intentCatalog.playlists` supply the entity catalog. Library mutations record renames and deletions in `intentCatalogChanges`, pruned daily.
- `appIntentPlaylists` records playlist-creation request IDs in the same transaction as creation. Replaying a request returns the original playlist ID.
- `playlists.createPlaylist` accepts an optional `invocationId`; existing callers can omit it.
## Verification
Run from the repository root:
```sh
pnpm --filter @otunes/mobile typecheck
pnpm --filter @otunes/convex typecheck
node --test apps/mobile/lib/app-intents.test.cjs packages/convex/convex/app-intent-playlists.test.cjs
```
Build iOS with Xcode and verify the app target's `ExtractAppIntentsMetadata` phase. TypeScript checks alone do not validate Swift declarations or Apple's schema contracts.
On a suitable device, verify cold and warm playback, paused warmup followed by playback, offline errors, request expiry, playlist replay, and a saved shortcut after upgrading. Check entity resolution after rename/delete and sign-out. Verify Spotlight opening, on-screen requests, and donations separately; metadata extraction does not establish system discovery or successful runtime execution.
+71
View File
@@ -0,0 +1,71 @@
import type { ConfigContext, ExpoConfig } from "expo/config"
export default ({ config }: ConfigContext): ExpoConfig => {
const variant: string =
process.env.APP_VARIANT ?? process.env.EAS_BUILD_PROFILE ?? "production"
if (
variant !== "development" &&
variant !== "preview" &&
variant !== "production"
) {
throw new Error(`Unsupported APP_VARIANT: ${variant}`)
}
const suffix = variant === "production" ? "" : `.${variant}`
const iconSuffix = variant === "production" ? "" : `-${variant}`
const nameSuffix =
variant === "development"
? " (Development)"
: variant === "preview"
? " (Preview)"
: ""
// Expo writes this filename into Xcode build settings without quoting it.
const composer = {
development: "oTunesDev",
preview: "oTunesPreview",
production: "oTunes",
}[variant]
const bundleIdentifier = `${config.ios!.bundleIdentifier}${suffix}`
return {
...config,
plugins: [
...(config.plugins ?? []),
[
"react-native-continued-task",
{
// Matches TASK_PREFIX in hooks/use-background-downloads.ts.
identifierPrefixes: [`${bundleIdentifier}.downloads`],
},
],
...(process.env.MAC_CATALYST === "1"
? ["./plugins/with-mac-catalyst"]
: []),
],
name: `${config.name}${nameSuffix}`,
slug: config.slug!,
scheme: variant === "production" ? "otunes" : `otunes-${variant}`,
icon: `./assets/icon${iconSuffix}.png`,
ios: {
...config.ios,
bundleIdentifier,
icon: `./assets/${composer}.icon`,
infoPlist: {
...config.ios?.infoPlist,
// HandoffModule publishes this `.media` type; Catalyst shares this bundle ID.
NSUserActivityTypes: [`${bundleIdentifier}.media`],
},
},
android: {
...config.android,
package: `${config.android!.package}${suffix}`,
icon: `./assets/android-icon${iconSuffix}.png`,
adaptiveIcon: {
monochromeImage: "./assets/android-icon-monochrome.png",
foregroundImage: `./assets/android-icon-foreground${iconSuffix}.png`,
backgroundImage: `./assets/android-icon-background${iconSuffix}.png`,
},
},
}
}
+24 -22
View File
@@ -26,8 +26,11 @@
"adaptiveIcon": {
"monochromeImage": "./assets/android-icon-monochrome.png",
"foregroundImage": "./assets/android-icon-foreground.png",
"backgroundColor": "#C60322"
}
"backgroundImage": "./assets/android-icon-background.png"
},
"userInterfaceStyle": "dark",
"softwareKeyboardLayoutMode": "resize",
"icon": "./assets/android-icon.png"
},
"plugins": [
"expo-router",
@@ -44,31 +47,30 @@
[
"expo-splash-screen",
{
"ios": {
"backgroundColor": "#ffffff",
"image": "./assets/ios-icon.png",
"dark": {
"image": "./assets/ios-icon-dark.png",
"backgroundColor": "#000000"
},
"imageWidth": 200
},
"android": {
"backgroundColor": "#ffffff",
"image": "./assets/icon.png",
"dark": {
"image": "./assets/icon-dark.png",
"backgroundColor": "#000000"
},
"imageWidth": 200
}
"backgroundColor": "#000000"
}
],
"expo-image",
"expo-status-bar"
"expo-status-bar",
"expo-app-intents",
"./plugins/with-android-colors",
"./plugins/with-android-fast-fade",
[
"expo-navigation-bar",
{
"enforceContrast": false,
"style": "light"
}
]
],
"experiments": {
"typedRoutes": true
"typedRoutes": true,
"inlineModules": {
"watchedDirectories": [
"app-intents",
"native"
]
}
},
"extra": {
"router": {},
@@ -0,0 +1,28 @@
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { useStackScreenOptions, tabStackScreenTitles } from "@/lib/navigation"
import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation"
export default function TabletSectionLayout({ segment }: { segment: string }) {
const section = tabletSections.find((item) => item.group === segment)
const options = useStackScreenOptions()
return (
<TabletSectionContext value={section}>
<TabStackContext value={section?.group}>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
</TabStackContext>
</TabletSectionContext>
)
}
@@ -0,0 +1 @@
export { default } from "../../library/album/[id]"
@@ -0,0 +1 @@
export { default } from "../../library/artist/[id]"
@@ -0,0 +1 @@
export { default } from "../../library/browse/albums"
@@ -0,0 +1 @@
export { default } from "../../library/browse/artists"
@@ -0,0 +1 @@
export { default } from "../../library/browse/playlists"
@@ -0,0 +1 @@
export { default } from "../../library/browse/songs"
@@ -0,0 +1 @@
export { default } from "../../home/downloads"
@@ -0,0 +1 @@
export { default } from "../../home/downloads/other"
@@ -0,0 +1,25 @@
import { useContext } from "react"
import Albums from "../home/browse/albums"
import Artists from "../home/browse/artists"
import Songs from "../home/browse/songs"
import Playlists from "../home/browse/playlists"
import Favorites from "../home/playlist/favorites"
import RecentlyPlayed from "../home/recently-played"
import Downloads from "../home/downloads"
import { TabletSectionContext } from "@/lib/tablet-navigation"
const screens = {
albums: Albums,
artists: Artists,
songs: Songs,
playlists: Playlists,
favorites: Favorites,
recent: RecentlyPlayed,
downloads: Downloads,
}
export default function TabletSectionScreen() {
const section = useContext(TabletSectionContext)
const Screen = screens[section?.name ?? "albums"]
return <Screen />
}
@@ -0,0 +1 @@
export { default } from "../../library/playlist/[id]"
@@ -0,0 +1 @@
export { default } from "../../library/playlist/favorites"
@@ -0,0 +1 @@
export { default } from "../library/recently-added"
@@ -0,0 +1 @@
export { default } from "../library/recently-played"
@@ -0,0 +1 @@
export { default } from "../library/settings"
+178 -55
View File
@@ -1,35 +1,58 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { TabletMiniPlayer } from "@/components/tablet-mini-player"
import { TabletPlayerLayoutProvider } from "@/contexts/tablet-player-layout"
import Animated from "react-native-reanimated"
import { NavigationBar } from "expo-navigation-bar"
import {
ScreenPaletteProvider,
useAndroidTabPalette,
useAndroidTabHasArtworkPalette,
useTabletBackgroundStyle,
} from "@/contexts/android-tab-theme"
import { DarkTheme, DefaultTheme, ThemeProvider } from "expo-router"
import { NativeTabs } from "expo-router/unstable-native-tabs"
import { DynamicColorIOS, Platform, useColorScheme } from "react-native"
import { NativeTabs } from "expo-router/native-tabs"
import { DynamicColorIOS, Platform } from "react-native"
import { useMemo } from "react"
import { TabBottomAccessory } from "@/components/mini-player"
import { AndroidMiniPlayer, TabBottomAccessory } from "@/components/mini-player"
import { useAndroidKeyboardVisible } from "@/hooks/use-android-keyboard-visible"
import { usePlaybackQueue } from "@/contexts/playback"
import { appleMusic, colors } from "@/lib/theme"
import { appleMusic, colors, miniPlayerHeight, useIsDark } from "@/lib/theme"
export const unstable_settings = { anchor: "library" }
function useRouterTheme() {
const isDark = useColorScheme() === "dark"
const themeIsDark = useIsDark()
const androidPalette = useAndroidTabPalette()
const isDark = Platform.OS === "android" ? androidPalette.isDark : themeIsDark
return useMemo(() => {
const palette = isDark ? colors.dark : colors.light
const android = Platform.OS === "android" ? androidPalette : null
const base = isDark ? DarkTheme : DefaultTheme
return {
...base,
colors: {
...base.colors,
background: palette.background,
card: palette.card,
text: palette.foreground,
border: palette.border,
primary: palette.primary,
background: android?.background ?? palette.background,
card: android?.surface ?? palette.card,
text: android?.foreground ?? palette.foreground,
border: android?.divider ?? palette.border,
primary: android?.accentText ?? palette.primary,
},
}
}, [isDark])
}, [isDark, androidPalette])
}
function useNativeTabColors() {
const isDark = useColorScheme() === "dark"
const themeIsDark = useIsDark()
const androidPalette = useAndroidTabPalette()
const hasArtworkPalette = useAndroidTabHasArtworkPalette()
const selectedColor = hasArtworkPalette
? androidPalette.foreground
: androidPalette.accentText
const isDark = Platform.OS === "android" ? androidPalette.isDark : themeIsDark
const inactive = appleMusic.tabInactive
const iconColor =
@@ -39,24 +62,23 @@ function useNativeTabColors() {
selected: appleMusic.pink,
}
: {
default: isDark ? inactive : "#636366",
selected: appleMusic.pink,
default: androidPalette.secondaryForeground,
selected: selectedColor,
}
const labelColor =
Platform.OS === "ios"
? DynamicColorIOS({ dark: inactive, light: "#636366" })
: isDark
? inactive
: "#636366"
: androidPalette.secondaryForeground
return {
isDark,
tintColor: Platform.OS === "android" ? selectedColor : appleMusic.pink,
iconColor,
labelStyle: {
default: { color: labelColor, fontSize: 10 },
selected: {
color: appleMusic.pink,
color: Platform.OS === "android" ? selectedColor : appleMusic.pink,
fontSize: 10,
fontWeight: "600" as const,
},
@@ -65,57 +87,158 @@ function useNativeTabColors() {
? "systemChromeMaterialDark"
: "systemChromeMaterialLight",
backgroundColor:
Platform.OS === "ios"
? undefined
: isDark
? appleMusic.background
: colors.light.background,
Platform.OS === "ios" ? undefined : androidPalette.background,
}
}
export default function TabsLayout() {
function TabsContent() {
const tabletLayout = useTabletLayout()
const keyboardVisible = useAndroidKeyboardVisible()
const routerTheme = useRouterTheme()
const tabColors = useNativeTabColors()
const backgroundStyle = useTabletBackgroundStyle()
const { currentSong, queueSongIds } = usePlaybackQueue()
const showBottomAccessory = Boolean(currentSong && queueSongIds.length > 0)
// NativeTabs already owns the tab bar and system navigation insets.
const androidContentStyle =
Platform.OS === "android"
? {
paddingBottom:
showBottomAccessory && !keyboardVisible ? miniPlayerHeight : 0,
}
: undefined
return (
<ThemeProvider value={routerTheme}>
<NativeTabs
blurEffect={
tabColors.blurEffect as
"systemChromeMaterialDark" | "systemChromeMaterialLight"
}
backgroundColor={tabColors.backgroundColor}
iconColor={tabColors.iconColor}
labelStyle={tabColors.labelStyle}
tintColor={appleMusic.pink}
minimizeBehavior="onScrollDown"
>
{showBottomAccessory ? (
<NativeTabs.BottomAccessory>
<TabBottomAccessory />
</NativeTabs.BottomAccessory>
<Animated.View style={[{ flex: 1 }, backgroundStyle]}>
{Platform.OS === "android" ? (
<NavigationBar style={tabColors.isDark ? "light" : "dark"} />
) : null}
<NativeTabs
sidebarAdaptable
blurEffect={
tabColors.blurEffect as
"systemChromeMaterialDark" | "systemChromeMaterialLight"
}
backgroundColor={tabColors.backgroundColor}
iconColor={tabColors.iconColor}
labelStyle={tabColors.labelStyle}
tintColor={tabColors.tintColor}
minimizeBehavior="onScrollDown"
{...(Platform.OS === "android"
? // A new ripple color rebuilds Material's item backgrounds and
// cuts off the in-flight ripple, so it must not follow the palette.
{ disableIndicator: true, rippleColor: appleMusic.tabInactive }
: {})}
>
{Platform.OS === "ios" && !tabletLayout && showBottomAccessory ? (
<NativeTabs.BottomAccessory>
<TabBottomAccessory />
</NativeTabs.BottomAccessory>
) : null}
<NativeTabs.Trigger name="home" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="home"
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="library" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon
sf="music.note.square.stack.fill"
md="library_music"
/>
<NativeTabs.Trigger.Label>Library</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="library"
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
<NativeTabs.Trigger.Icon
sf="music.note.square.stack.fill"
md="library_music"
/>
<NativeTabs.Trigger.Label>
{tabletLayout ? "Recently Added" : "Library"}
</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="search" disableTransparentOnScrollEdge>
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
<NativeTabs.Trigger
name="search"
disableTransparentOnScrollEdge
contentStyle={androidContentStyle}
>
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(albums)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="square.stack" />
<NativeTabs.Trigger.Label>Albums</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(artists)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="mic" />
<NativeTabs.Trigger.Label>Artists</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(songs)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="music.note" />
<NativeTabs.Trigger.Label>Songs</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(downloads)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="arrow.down.circle" />
<NativeTabs.Trigger.Label>Downloads</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(playlists)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="music.note.list" />
<NativeTabs.Trigger.Label>All Playlists</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(favorites)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="star" />
<NativeTabs.Trigger.Label>Favorites</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(recent)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="clock" />
<NativeTabs.Trigger.Label>Recently Played</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
{!keyboardVisible ? <AndroidMiniPlayer /> : null}
{tabletLayout ? <TabletMiniPlayer /> : null}
</Animated.View>
</ThemeProvider>
)
}
export default function TabsLayout() {
return (
<ScreenPaletteProvider>
<TabletPlayerLayoutProvider>
<TabsContent />
</TabletPlayerLayoutProvider>
</ScreenPaletteProvider>
)
}
+24 -19
View File
@@ -1,33 +1,38 @@
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
initialRouteName: "index",
anchor: "index",
}
export default function HomeLayout() {
const baseOptions = useStackScreenOptions({ title: "Home" })
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
],
})}
/>
<TabStackContext value="home">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
)
}
+493 -133
View File
@@ -1,14 +1,46 @@
import { Stack, useLocalSearchParams } from "expo-router"
import { useEffect } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { SongSwipeRow } from "@/components/song-swipe-row"
import {
useSwipeRowGroup,
type SwipeRowGroup,
} from "@/components/ios-swipe-to-remove-row"
import {
CollectionHero,
useCollectionHeroLayout,
} from "@/components/collection-hero"
import Animated from "react-native-reanimated"
import { useScreenPalette } from "@/contexts/android-tab-theme"
import { MusicEntityView } from "@/components/music-entity-view"
import { Link, Stack, useIsFocused, useLocalSearchParams } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
import {
CollectionDivider,
collectionInset,
DiscHeader,
} from "@/components/collection-list"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import {
CollectionDownloadButton,
DownloadedQuality,
} from "@/components/collection-download-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import {
useDownloads,
useIsCollectionDownloaded,
useSongDownloadState,
useToggleSongDownload,
} from "@/contexts/downloads"
import { CoverImage } from "@/components/cover-image"
import {
MediaActionMenu,
MediaContextMenu,
} from "@/components/media-actions-sheet"
type MediaAction,
} from "@/components/media-context-menu"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
@@ -16,13 +48,15 @@ import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumTrack } from "@otunes/convex/types"
import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration, formatMetadata } from "@/lib/format"
import { useAppNavigation } from "@/lib/app-navigation"
import { longListProps } from "@/lib/list"
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
import { albumCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme"
@@ -36,21 +70,49 @@ export default function AlbumScreen() {
api.library.browseAlbumDetail,
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
)
const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions()
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } =
useFavorites()
const {
playAlbum,
playAlbumShuffled,
playFromSong,
playInOrder,
playShuffled,
} = usePlaybackActions()
const fromDownloads = useOpenedFromDownloads()
const playOrigin = fromDownloads
? downloadsQueueOrigin(`album:${id}`)
: `album:${id}`
const { isSongFavorite } = useFavorites()
const {
handleAlbumDetailAction,
handleAlbumTrackAction,
isAlbumFavorite: isAlbumFav,
} = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup()
const isFocused = useIsFocused()
const coverUri =
config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
const backgroundColor = useCoverBackgroundColor(
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
const heroLayout = useCollectionHeroLayout()
const { palette: artworkPalette, settled } = useCoverPalette(
coverUri,
album?.cover != null,
colors.background
album ? album.cover != null : album === null ? false : undefined
)
const { palette, onLayout, backgroundStyle } =
useScreenPalette(artworkPalette)
const songIds = useMemo(
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
[album]
)
const { requestDownload, removeDownload } = useDownloads()
const downloadTarget = useMemo(
() => ({
kind: "album" as const,
id: typeof id === "string" ? id : "",
title: album?.title ?? "",
songIds,
}),
[album?.title, id, songIds]
)
const albumDownloaded = useIsCollectionDownloaded(downloadTarget)
useEffect(() => {
if (album) {
@@ -58,16 +120,67 @@ export default function AlbumScreen() {
}
}, [album])
if (album === undefined || !config) {
const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album])
const playTrack = useCallback(
(songId: Id<"songs">, ids: Id<"songs">[]) =>
playFromSong(songId, ids, playOrigin),
[playOrigin, playFromSong]
)
const renderItem = useCallback(
({ item }: { item: AlbumListItem }) => {
if (item.type === "disc") {
return <DiscHeader label={item.label} color={palette.foreground} />
}
return album ? (
<AlbumTrackRow
swipeGroup={swipeGroup}
track={item.track}
number={item.number}
album={album}
songIds={songIds}
palette={palette}
favorited={isSongFavorite(item.track.id)}
onPlay={playTrack}
onAction={handleAlbumTrackAction}
/>
) : null
},
[
album,
handleAlbumTrackAction,
isSongFavorite,
palette,
playTrack,
songIds,
swipeGroup,
]
)
if (album === undefined || !config || !settled) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: palette.background },
headerTintColor: palette.foreground,
}
: {}),
}}
/>
<CollectionDetailSkeleton />
<CollectionDetailSkeleton
variant="album"
onLayout={onLayout}
style={backgroundStyle}
backgroundColor={
Platform.OS === "android" ? palette.background : undefined
}
/>
</>
)
}
@@ -90,29 +203,47 @@ export default function AlbumScreen() {
)
}
const songIds = album.tracks.map(
(track: BrowseAlbumTrack) => track.id as Id<"songs">
)
const metadata = formatMetadata(album.genre, album.year)
return (
<>
{isFocused ? (
<StatusBar style={palette.isDark ? "light" : "dark"} />
) : null}
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
headerTintColor: palette.foreground,
...(Platform.OS === "android"
? {
headerStyle: { backgroundColor: palette.background },
statusBarStyle: palette.isDark
? ("light" as const)
: ("dark" as const),
}
: {}),
headerRight: () => (
<MediaActionMenu
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
share={{ type: "album", albumId: album.id }}
onAction={(action) =>
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action
)
}
downloaded={albumDownloaded}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) => {
if (action === "download") {
void requestDownload(downloadTarget)
} else if (action === "remove-download") {
void removeDownload(downloadTarget)
} else {
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action,
album.artist.id as Id<"artists">
)
}
}}
>
<Pressable hitSlop={8}>
<Ionicons
@@ -125,130 +256,350 @@ export default function AlbumScreen() {
),
}}
/>
<FlatList
data={album.tracks}
keyExtractor={(track) => track.id}
style={{ flex: 1, backgroundColor }}
<Animated.FlatList
onScrollBeginDrag={swipeGroup.closeOpenRow}
onLayout={onLayout}
{...longListProps}
data={listItems}
keyExtractor={albumListItemKey}
style={[
{ flex: 1, backgroundColor: palette.background },
backgroundStyle,
]}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
indicatorStyle={palette.isDark ? "white" : "black"}
ListHeaderComponent={
<View style={styles.hero}>
<CoverImage
uri={coverUri}
hasCover={album.cover != null}
style={styles.cover}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
{album.title}
</Text>
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
<Text style={[styles.artist, { color: colors.mutedForeground }]}>
{album.artist.name}
</Text>
</Pressable>
{metadata ? (
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
) : null}
<View style={styles.actions}>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
<View>
<MusicEntityView kind="album" id={album.id}>
<CollectionHero
artwork={
<Link.AppleZoomTarget>
<View collapsable={false}>
<CoverImage
uri={coverUri}
hasCover={album.cover != null}
style={[
styles.cover,
heroLayout.coverSize
? {
width: heroLayout.coverSize,
height: heroLayout.coverSize,
}
: undefined,
]}
/>
</View>
</Link.AppleZoomTarget>
}
actions={
<View
style={[
styles.actions,
heroLayout.landscape && { flexDirection: "row-reverse" },
]}
>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() =>
void (fromDownloads
? playShuffled(songIds, playOrigin)
: playAlbumShuffled(album.id, songIds))
}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name="shuffle"
size={24}
color={palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() =>
void (fromDownloads
? playInOrder(songIds, playOrigin)
: playAlbum(album.id, songIds))
}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<CollectionDownloadButton
target={downloadTarget}
color={palette.foreground}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
/>
</View>
}
>
<Ionicons
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
size={24}
color={
isAlbumFavorite(album.id)
? colors.primary
: colors.foreground
}
<Text
style={[
styles.title,
heroLayout.landscape && styles.titleLandscape,
{ color: palette.foreground },
]}
>
{album.title}
</Text>
<Pressable
onPress={() => push(`/artist/${album.artist.id}`)}
style={styles.artistPressable}
>
<Text
style={[
styles.artist,
heroLayout.landscape && styles.artistLandscape,
{ color: palette.accentText },
]}
>
{album.artist.name}
</Text>
</Pressable>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: heroLayout.landscape
? "flex-start"
: "center",
flexWrap: "wrap",
gap: 8,
}}
>
{metadata ? (
<Text style={{ color: palette.secondaryForeground }}>
{metadata}
</Text>
) : null}
{album.hasLossless ? (
<>
{metadata ? (
<Text style={{ color: palette.secondaryForeground }}>
·
</Text>
) : null}
<AudioFormatBadge
format="lossless"
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</>
) : null}
{album.hasAtmos ? (
<>
{metadata || album.hasLossless ? (
<Text style={{ color: palette.secondaryForeground }}>
·
</Text>
) : null}
<AudioFormatBadge
format="atmos"
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</>
) : null}
</View>
<DownloadedQuality
collection={downloadTarget}
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playAlbum(album.id, songIds)}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</CollectionHero>
</MusicEntityView>
<CollectionDivider color={palette.divider} />
</View>
}
renderItem={({ item: track, index }) => (
<MediaContextMenu
favorited={isSongFavorite(track.id)}
navigation={{
artist: { id: album.artist.id },
album: { id: album.id },
}}
share={{
type: "song",
albumId: album.id,
songId: track.id,
}}
onAction={(action) =>
void handleAlbumTrackAction(track, album, action)
}
>
<Pressable
style={[styles.trackRow, { borderBottomColor: colors.border }]}
onPress={() => void playFromSong(track.id, songIds)}
>
<Text
style={[styles.trackNumber, { color: colors.mutedForeground }]}
>
{track.track || index + 1}
</Text>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: colors.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
<Text style={{ color: colors.mutedForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</Pressable>
</MediaContextMenu>
)}
renderItem={renderItem}
/>
</>
)
}
type AlbumListItem =
| { type: "disc"; key: string; label: string }
| { type: "track"; track: BrowseAlbumTrack; number: number }
/**
* Tracks arrive sorted by disc then track number. Disc headers are only
* inserted when the album spans more than one disc.
*/
function albumListItems(tracks: BrowseAlbumTrack[]): AlbumListItem[] {
const multiDisc = new Set(tracks.map((track) => track.diskNumber)).size > 1
const items: AlbumListItem[] = []
let currentDisc: number | null | undefined
let positionInDisc = 0
for (const track of tracks) {
if (track.diskNumber !== currentDisc) {
currentDisc = track.diskNumber
positionInDisc = 0
if (multiDisc) {
items.push({
type: "disc",
key: `disc-${currentDisc ?? "unknown"}`,
label: currentDisc == null ? "Other" : `Disc ${currentDisc}`,
})
}
}
positionInDisc += 1
items.push({
type: "track",
track,
number: track.track || positionInDisc,
})
}
return items
}
function albumListItemKey(item: AlbumListItem) {
return item.type === "disc" ? item.key : item.track.id
}
const AlbumTrackRow = memo(function AlbumTrackRow({
track,
swipeGroup,
number,
album,
songIds,
palette,
favorited,
onPlay,
onAction,
}: {
track: BrowseAlbumTrack
swipeGroup: SwipeRowGroup
number: number
album: BrowseAlbumDetail
songIds: Id<"songs">[]
palette: CoverPalette
favorited: boolean
onPlay: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
onAction: (
track: BrowseAlbumTrack,
album: BrowseAlbumDetail,
action: MediaAction
) => Promise<void>
}) {
const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable
const { config } = useServerConfig()
const downloadRef = useMemo(
() => ({ kind: "album" as const, id: album.id }),
[album.id]
)
const downloadState = useSongDownloadState(track.id, downloadRef)
const downloaded = downloadState === "here"
const toggleDownload = useToggleSongDownload()
return (
<MediaContextMenu
preview={
config
? {
kind: "song",
title: track.title,
artist: album.artist.name,
album: album.title,
artworkUrl: albumCoverUrl(config.serverUrl, album.id),
hasArtwork: album.cover != null,
}
: undefined
}
stationArtistId={album.artist.id}
favorited={favorited}
downloaded={downloaded}
navigation={{
artist: { id: album.artist.id },
album: { id: album.id },
}}
share={{
type: "song",
albumId: album.id,
songId: track.id,
title: `${track.title} - ${album.title}`,
}}
onAction={(action) => void onAction(track, album, action)}
>
<MusicEntityView kind="song" id={track.id}>
<Row
group={swipeGroup}
backgroundColor={palette.background}
onPlayNext={() => void onAction(track, album, "play-next")}
onAddToQueue={() => void onAction(track, album, "play-last")}
downloaded={downloaded}
onDownload={() => toggleDownload(track, downloaded, downloadRef)}
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
<Text
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
>
{number}
</Text>
<View
style={[
styles.trackContent,
{ borderBottomColor: palette.divider },
]}
>
<View style={styles.trackMeta}>
<Text
style={[styles.trackTitle, { color: palette.foreground }]}
numberOfLines={1}
>
{track.title}
</Text>
{track.artists ? (
<Text
style={{ color: palette.secondaryForeground }}
numberOfLines={1}
>
{track.artists.join(", ")}
</Text>
) : null}
</View>
{downloaded || downloadState === "device" ? (
<Ionicons
name="arrow-down-circle"
size={14}
color={palette.secondaryForeground}
accessibilityLabel="Downloaded"
/>
) : null}
<Text style={{ color: palette.secondaryForeground }}>
{formatDuration(track.durationSeconds)}
</Text>
</View>
</Row>
</MusicEntityView>
</MediaContextMenu>
)
})
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
hero: {
alignItems: "center",
padding: spacing.lg,
gap: spacing.sm,
},
cover: {
width: 220,
height: 220,
borderRadius: radius.lg,
},
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
artist: { fontSize: 16, fontWeight: "600" },
titleLandscape: { textAlign: "left", fontSize: 22 },
artistLandscape: { textAlign: "left", fontSize: 22, fontWeight: "400" },
artistPressable: { alignSelf: "stretch" },
artist: { fontSize: 16, fontWeight: "600", textAlign: "center" },
actions: {
flexDirection: "row",
alignItems: "center",
@@ -267,13 +618,22 @@ const styles = StyleSheet.create({
trackRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
paddingLeft: collectionInset,
},
trackNumber: { width: 24, fontSize: 16, textAlign: "center" },
trackContent: {
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
gap: spacing.md,
minHeight: 60,
paddingHorizontal: spacing.lg,
minHeight: 52,
paddingVertical: 12,
marginRight: collectionInset,
borderBottomWidth: StyleSheet.hairlineWidth,
},
trackNumber: { width: 24, textAlign: "center" },
trackMeta: { flex: 1, minWidth: 0 },
trackTitle: { fontSize: 16, fontWeight: "500" },
})
@@ -1,3 +1,4 @@
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useLocalSearchParams } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons"
@@ -5,7 +6,7 @@ import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image"
import { MediaGridList } from "@/components/media-cards"
import { MediaActionMenu } from "@/components/media-actions-sheet"
import { MediaActionMenu } from "@/components/media-context-menu"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
@@ -41,7 +42,7 @@ export default function ArtistScreen() {
headerLargeTitle: false,
}}
/>
<CollectionDetailSkeleton round />
<CollectionDetailSkeleton variant="artist" />
</>
)
}
@@ -74,7 +75,11 @@ export default function ArtistScreen() {
<MediaActionMenu
selectedCount={data.albums.length}
favorited={isArtistFav(data.artist.id)}
share={{ type: "artist", artistId: data.artist.id }}
share={{
type: "artist",
artistId: data.artist.id,
title: data.artist.name,
}}
onAction={(action) =>
void handleArtistAction(data.artist, action)
}
@@ -95,7 +100,11 @@ export default function ArtistScreen() {
paddingBottom={contentBottomInset}
contentInset={false}
ListHeaderComponent={
<View style={styles.hero}>
<MusicEntityView
kind="artist"
id={data.artist.id}
style={styles.hero}
>
<CoverImage
uri={artistCoverUrl(config.serverUrl, data.artist.id)}
hasCover={data.artist.photo != null}
@@ -138,7 +147,7 @@ export default function ArtistScreen() {
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
</MusicEntityView>
}
/>
</>
@@ -1,9 +1,18 @@
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { useCallback } from "react"
import { FlatList, Pressable, StyleSheet, Text } from "react-native"
import { memo, useCallback } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
type ListRenderItemInfo,
} from "react-native"
import { MediaContextMenu } from "@/components/media-context-menu"
import {
MediaContextMenu,
type MediaAction,
} from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image"
import { ArtistListSkeleton } from "@/components/skeletons"
import { contentBottomInset } from "@/components/player"
@@ -17,6 +26,7 @@ import { useAppNavigation } from "@/lib/app-navigation"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { BrowseArtist } from "@otunes/convex/types"
import { longListProps } from "@/lib/list"
import { artistCoverUrl } from "@/lib/urls"
import { spacing, useThemeColors } from "@/lib/theme"
@@ -43,6 +53,24 @@ export default function ArtistsScreen() {
? undefined
: results
const serverUrl = config?.serverUrl ?? ""
const handleOpenArtist = useCallback(
(artistId: string) => push(`/artist/${artistId}`),
[push]
)
const renderItem = useCallback(
({ item: artist }: ListRenderItemInfo<BrowseArtist>) => (
<ArtistRow
artist={artist}
serverUrl={serverUrl}
favorited={isArtistFavorite(artist.id)}
onOpen={handleOpenArtist}
onAction={handleArtistAction}
/>
),
[handleArtistAction, handleOpenArtist, isArtistFavorite, serverUrl]
)
const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
@@ -76,46 +104,80 @@ export default function ArtistsScreen() {
{searchBar}
<FlatList
{...longListProps}
data={artists}
keyExtractor={(artist) => artist.id}
keyExtractor={artistKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
renderItem={({ item: artist }: { item: BrowseArtist }) => (
<MediaContextMenu
favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id }}
onAction={(action) => void handleArtistAction(artist, action)}
>
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => push(`/artist/${artist.id}`)}
>
<CoverImage
uri={artistCoverUrl(config.serverUrl, artist.id)}
hasCover={artist.photo != null}
style={styles.avatar}
/>
<Text
style={[styles.name, { color: colors.foreground }]}
numberOfLines={1}
>
{artist.name}
</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
</MediaContextMenu>
)}
/>
</>
)
}
function artistKey(artist: BrowseArtist) {
return artist.id
}
const ArtistRow = memo(function ArtistRow({
artist,
serverUrl,
favorited,
onOpen,
onAction,
}: {
artist: BrowseArtist
serverUrl: string
favorited: boolean
onOpen: (artistId: string) => void
onAction: (artist: BrowseArtist, action: MediaAction) => Promise<void>
}) {
const colors = useThemeColors()
return (
<MediaContextMenu
preview={{
kind: "artist",
title: artist.name,
artworkUrl: artistCoverUrl(serverUrl, artist.id),
hasArtwork: artist.photo != null,
}}
favorited={favorited}
share={{ type: "artist", artistId: artist.id, title: artist.name }}
onAction={(action) => void onAction(artist, action)}
>
<Pressable
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => onOpen(artist.id)}
>
<CoverImage
uri={artistCoverUrl(serverUrl, artist.id)}
hasCover={artist.photo != null}
style={styles.avatar}
/>
<Text
style={[styles.name, { color: colors.foreground }]}
numberOfLines={1}
>
{artist.name}
</Text>
<Ionicons
name="chevron-forward"
size={16}
color={colors.mutedForeground}
/>
</Pressable>
</MediaContextMenu>
)
})
const styles = StyleSheet.create({
listContent: { paddingBottom: contentBottomInset },
row: {
flexDirection: "row",
alignItems: "center",
@@ -1,8 +1,9 @@
import { Stack } from "expo-router"
import { useCallback, useState } from "react"
import { FlatList, StyleSheet } from "react-native"
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
import { contentBottomInset, SongRow } from "@/components/player"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
@@ -13,8 +14,8 @@ import {
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { spacing } from "@/lib/theme"
import type { BrowseSong } from "@otunes/convex/types"
import { longListProps } from "@/lib/list"
const PAGE_SIZE = 50
@@ -41,6 +42,28 @@ export default function SongsScreen() {
? undefined
: results
const handlePlaySong = useCallback(
(song: BrowseSong) =>
void playFromLibrarySong(song.id, { sortKey, sortDirection }),
[playFromLibrarySong, sortDirection, sortKey]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action),
[handleSongAction]
)
const renderItem = useCallback(
({ item }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={item}
favorited={isSongFavorite(item.id)}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
),
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => {
onQueryChange(event.nativeEvent.text)
@@ -74,49 +97,25 @@ export default function SongsScreen() {
{searchBar}
<FlatList
{...longListProps}
data={songs}
keyExtractor={(item) => item.id}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
keyExtractor={songKey}
renderItem={renderItem}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
onEndReached={() => {
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
onEndReachedThreshold={0.5}
renderItem={({ item }) => (
<SongRow
song={item}
onPress={() =>
void playFromLibrarySong(item.id as Id<"songs">, {
sortKey,
sortDirection,
})
}
contextMenu={{
favorited: isSongFavorite(item.id),
navigation: {
artist: { id: item.artist.id },
album: { id: item.album.id },
},
share: {
type: "song",
albumId: item.album.id,
songId: item.id,
},
onAction: (action) => void handleSongAction(item, action),
}}
/>
)}
/>
</>
)
}
function songKey(song: BrowseSong) {
return song.id
}
const styles = StyleSheet.create({
sortRow: {
flexDirection: "row",
justifyContent: "space-around",
paddingVertical: spacing.sm,
borderBottomWidth: StyleSheet.hairlineWidth,
},
sortButton: { padding: spacing.sm },
listContent: { paddingBottom: contentBottomInset },
})
@@ -0,0 +1,176 @@
import { useMemo } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { Stack } from "expo-router"
import { CoverImage } from "@/components/cover-image"
import { tabContentBottomInset } from "@/components/player"
import {
FAVORITES_DOWNLOAD_ID,
useDownloads,
useDownloadsVersion,
} from "@/contexts/downloads"
import { useServerConfig } from "@/contexts/server-config"
import { useMediaGridLayout } from "@/hooks/use-media-grid-layout"
import { useAppNavigation } from "@/lib/app-navigation"
import {
FROM_DOWNLOADS_PARAM,
OTHER_DOWNLOADS_TITLE,
} from "@/lib/downloads-navigation"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { albumCoverUrl, playlistCoverUrl } from "@/lib/urls"
import type { DownloadedCollection } from "@otunes/convex/client/download-queue"
import { formatBytes } from "@otunes/convex/download-quality"
type Card =
| { kind: "other"; songCount: number; bytes: number }
| { kind: "collection"; collection: DownloadedCollection; bytes: number }
function songCount(count: number) {
return count === 1 ? "1 song" : `${count} songs`
}
function collectionPath({ kind, id }: DownloadedCollection) {
if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}`
if (id === FAVORITES_DOWNLOAD_ID) {
return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}`
}
return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}`
}
/** Downloaded albums and playlists, newest first, after Other Downloaded Songs. */
export default function DownloadsScreen() {
const colors = useThemeColors()
const { config } = useServerConfig()
const { queue } = useDownloads()
const version = useDownloadsVersion()
const { push } = useAppNavigation()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
useMediaGridLayout()
const cards = useMemo<Card[]>(() => {
if (!queue) return []
const breakdown = queue.breakdown()
const bytesByCollection = new Map(
breakdown.collections.map((row) => [row.collection, row.bytes])
)
const other: Card[] =
breakdown.otherSongs.songIds.length > 0
? [
{
kind: "other",
songCount: breakdown.otherSongs.songIds.length,
bytes: breakdown.otherSongs.bytes,
},
]
: []
return [
...other,
...queue
.collections()
.reverse()
.map((collection): Card => ({
kind: "collection",
collection,
bytes: bytesByCollection.get(collection) ?? 0,
})),
]
// version invalidates the lookup when downloads change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [queue, version])
function renderItem({ item }: ListRenderItemInfo<Card>) {
if (!config) return null
const isOther = item.kind === "other"
const collection = isOther ? null : item.collection
const isFavorites = collection?.id === FAVORITES_DOWNLOAD_ID
const title = collection?.title ?? OTHER_DOWNLOADS_TITLE
const subtitle = isOther
? `${songCount(item.songCount)} · ${formatBytes(item.bytes)}`
: `${collection!.kind === "album" ? "Album" : "Playlist"} · ${formatBytes(item.bytes)}`
const coverUri = !collection
? ""
: collection.kind === "album"
? albumCoverUrl(config.serverUrl, collection.id)
: playlistCoverUrl(config.serverUrl, collection.id, null)
return (
<Pressable
accessibilityRole="button"
style={[styles.card, { width: cardWidth }]}
onPress={() =>
push(collection ? collectionPath(collection) : "/downloads/other")
}
>
<CoverImage
uri={coverUri}
hasCover={collection !== null && !isFavorites}
placeholderIcon={isOther ? "arrow-down" : "star"}
style={{
width: cardWidth,
height: cardWidth,
borderRadius: radius.md,
}}
/>
<Text
style={[styles.title, { color: colors.foreground }]}
numberOfLines={1}
>
{title}
</Text>
<Text
style={[styles.subtitle, { color: colors.mutedForeground }]}
numberOfLines={1}
>
{subtitle}
</Text>
</Pressable>
)
}
return (
<>
<Stack.Screen options={{ title: "Downloads", headerLargeTitle: true }} />
<FlatList
key={columns}
onLayout={onLayout}
data={cards}
keyExtractor={(card) =>
card.kind === "other"
? "other"
: `${card.collection.kind}:${card.collection.id}`
}
renderItem={renderItem}
numColumns={columns}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{
paddingTop: spacing.lg,
paddingHorizontal: horizontalPadding,
paddingBottom: tabContentBottomInset,
gap,
}}
columnWrapperStyle={columns > 1 ? { gap } : undefined}
contentInsetAdjustmentBehavior="automatic"
ListEmptyComponent={
<View style={styles.empty}>
<Text style={{ color: colors.mutedForeground }}>
Nothing downloaded on this device.
</Text>
</View>
}
/>
</>
)
}
const styles = StyleSheet.create({
card: { gap: spacing.xs },
title: { fontSize: 14, fontWeight: "600" },
subtitle: { fontSize: 12, fontVariant: ["tabular-nums"] },
empty: { alignItems: "center", paddingTop: spacing.xl },
})
@@ -0,0 +1,153 @@
import { useCallback, useMemo } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
import { useSwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
import type { MediaAction } from "@/components/media-context-menu"
import { contentBottomInset, SongListRow } from "@/components/player"
import { Button } from "@/components/ui/primitives"
import { useDownloads, useDownloadsVersion } from "@/contexts/downloads"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { OTHER_DOWNLOADS_TITLE } from "@/lib/downloads-navigation"
import { longListProps } from "@/lib/list"
import { useSongs } from "@/lib/song-cache"
import { spacing, useThemeColors } from "@/lib/theme"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import type { BrowseSong } from "@otunes/convex/types"
const PLAY_ORIGIN = downloadsQueueOrigin("other")
/** Songs downloaded on their own. Playback here always uses the downloads. */
export default function OtherDownloadsScreen() {
const colors = useThemeColors()
const { queue } = useDownloads()
const version = useDownloadsVersion()
const songIds = useMemo(
() =>
(queue?.otherSongIds() ?? [])
.filter((songId) => queue?.getDownloaded(songId))
.reverse() as Id<"songs">[],
// version invalidates the lookup when downloads change.
// eslint-disable-next-line react-hooks/exhaustive-deps
[queue, version]
)
const cachedSongs = useSongs(songIds)
const songs = useMemo(
() => cachedSongs.filter((song): song is BrowseSong => song != null),
[cachedSongs]
)
const playableIds = useMemo(() => songs.map((song) => song.id), [songs])
const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup()
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, playableIds, PLAY_ORIGIN),
[playFromSong, playableIds]
)
const handleAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action, "other"),
[handleSongAction]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
downloadFrom="other"
swipe={{
group: swipeGroup,
backgroundColor: colors.background,
onPlayNext: () => handleAction(song, "play-next"),
onAddToQueue: () => handleAction(song, "play-last"),
}}
onPlay={handlePlaySong}
onAction={handleAction}
/>
),
[
colors.background,
handleAction,
handlePlaySong,
isSongFavorite,
swipeGroup,
]
)
return (
<>
<Stack.Screen
options={{ title: OTHER_DOWNLOADS_TITLE, headerLargeTitle: false }}
/>
<FlatList
{...longListProps}
data={songs}
keyExtractor={(song) => song.id}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
onScrollBeginDrag={swipeGroup.closeOpenRow}
ListHeaderComponent={
songs.length > 0 ? (
<View style={styles.actions}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.playButton}
/>
</View>
) : undefined
}
ListEmptyComponent={
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
Songs you download on their own appear here.
</Text>
}
/>
</>
)
}
const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
padding: spacing.lg,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
alignItems: "center",
justifyContent: "center",
},
empty: { padding: spacing.lg, textAlign: "center" },
})
+4 -1
View File
@@ -62,7 +62,10 @@ export default function HomeScreen() {
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[styles.content, { paddingBottom: tabContentBottomInset }]}
contentContainerStyle={[
styles.content,
{ paddingBottom: tabContentBottomInset },
]}
contentInsetAdjustmentBehavior="automatic"
>
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
File diff suppressed because it is too large. Load diff
@@ -1,45 +1,112 @@
import { useEffect } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import {
PlaylistSearchBar,
usePlaylistSearch,
} from "@/components/playlist-search-bar"
import { memo, useCallback, useEffect, useMemo } from "react"
import {
FlatList,
Pressable,
StyleSheet,
Text,
View,
type ListRenderItemInfo,
} from "react-native"
import { CollectionDivider } from "@/components/collection-list"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player"
import { contentBottomInset, SongListRow } from "@/components/player"
import {
CollectionDownloadButton,
type CollectionDownloadTarget,
DownloadedQuality,
} from "@/components/collection-download-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import { FAVORITES_DOWNLOAD_ID } from "@/contexts/downloads"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { MediaAction } from "@/components/media-context-menu"
import type { BrowseSong } from "@otunes/convex/types"
import { longListProps } from "@/lib/list"
import { rememberSongs } from "@/lib/song-cache"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router"
const SCREEN_OPTIONS = { title: "", headerLargeTitle: false }
const DOWNLOAD_REF = { kind: "playlist", id: FAVORITES_DOWNLOAD_ID } as const
export default function FavoritesScreen() {
const colors = useThemeColors()
const { config } = useServerConfig()
const favorites = useCachedQuery(api.favorites.browseFavoritesPlaylistDetail)
const songs = useMemo(() => favorites?.songs.flat() ?? [], [favorites])
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions()
const songIds = useMemo(() => songs.map((song) => song.id), [songs])
const fromDownloads = useOpenedFromDownloads()
const playOrigin = fromDownloads
? downloadsQueueOrigin("playlist:favorites")
: undefined
const downloadTarget = useMemo(
() => ({
...DOWNLOAD_REF,
title: favorites?.title ?? "Favorites",
songIds,
}),
[favorites?.title, songIds]
)
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
useEffect(() => {
if (favorites) {
rememberSongs(favorites.songs)
}
}, [favorites])
rememberSongs(songs)
}, [songs])
const handlePlaySong = useCallback(
(song: BrowseSong) => void playFromSong(song.id, songIds, playOrigin),
[playFromSong, playOrigin, songIds]
)
const handleSongMenuAction = useCallback(
(song: BrowseSong, action: MediaAction) =>
void handleSongAction(song, action, DOWNLOAD_REF),
[handleSongAction]
)
const handlePlay = useCallback(
() => void playInOrder(songIds, playOrigin),
[playInOrder, playOrigin, songIds]
)
const handleShuffle = useCallback(
() => void playShuffled(songIds, playOrigin),
[playShuffled, playOrigin, songIds]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
playlistLabel="Add to Another Playlist"
inset
downloadFrom={DOWNLOAD_REF}
onPlay={handlePlaySong}
onAction={handleSongMenuAction}
/>
),
[handlePlaySong, handleSongMenuAction, isSongFavorite]
)
if (favorites === undefined || !config) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<CollectionDetailSkeleton />
<Stack.Screen options={SCREEN_OPTIONS} />
<CollectionDetailSkeleton variant="favorites" />
</>
)
}
@@ -47,12 +114,7 @@ export default function FavoritesScreen() {
if (favorites === null) {
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
/>
<Stack.Screen options={SCREEN_OPTIONS} />
<View style={[styles.empty, { backgroundColor: colors.background }]}>
<Text style={{ color: colors.mutedForeground }}>
Sign in to view your favorites.
@@ -62,92 +124,121 @@ export default function FavoritesScreen() {
)
}
const songIds = favorites.songs.map((song: BrowseSong) => song.id)
return (
<>
<Stack.Screen
options={{
title: "",
headerLargeTitle: false,
}}
<Stack.Screen options={SCREEN_OPTIONS} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
/>
<FlatList
data={favorites.songs}
keyExtractor={(song) => song.id}
{...longListProps}
data={filteredSongs}
keyExtractor={songKey}
renderItem={renderItem}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentContainerStyle={styles.listContent}
contentInsetAdjustmentBehavior="automatic"
ListHeaderComponent={
<View style={styles.hero}>
<View
style={[
styles.cover,
{
backgroundColor: colors.coverPlaceholder,
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>
{favorites.title}
</Text>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(songIds)}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(songIds)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
</View>
</View>
ListEmptyComponent={
<Text
style={[styles.emptyResults, { color: colors.mutedForeground }]}
>
{songs.length ? "No songs found." : "No songs in this playlist."}
</Text>
}
renderItem={({ item: song }: { item: BrowseSong }) => (
<SongRow
song={song}
onPress={() => void playFromSong(song.id, songIds)}
contextMenu={{
favorited: isSongFavorite(song.id),
playlistLabel: "Add to Another Playlist",
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
onAction: (action) => void handleSongAction(song, action),
}}
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
downloadTarget={downloadTarget}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
)}
}
/>
</>
)
}
function songKey(song: BrowseSong) {
return song.id
}
const FavoritesHero = memo(function FavoritesHero({
title,
downloadTarget,
onPlay,
onShuffle,
}: {
title: string
downloadTarget: CollectionDownloadTarget
onPlay: () => void
onShuffle: () => void
}) {
const colors = useThemeColors()
return (
<View>
<View style={styles.hero}>
<View
style={[
styles.cover,
styles.coverPlaceholder,
{ backgroundColor: colors.coverPlaceholder },
]}
>
<Ionicons name="star" size={120} color={colors.primary} />
</View>
<Text style={[styles.title, { color: colors.foreground }]}>
{title}
</Text>
<DownloadedQuality
collection={DOWNLOAD_REF}
color={colors.mutedForeground}
backgroundColor={colors.background}
/>
<View style={styles.actions}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<CollectionDownloadButton
target={downloadTarget}
color={colors.foreground}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
/>
</View>
</View>
<CollectionDivider />
</View>
)
})
const styles = StyleSheet.create({
emptyResults: { padding: spacing.lg, textAlign: "center" },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
listContent: { paddingBottom: contentBottomInset },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
cover: {
width: 200,
height: 200,
borderRadius: radius.lg,
},
coverPlaceholder: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
title: { fontSize: 24, fontWeight: "800" },
actions: {
flexDirection: "row",
-175
View File
@@ -1,175 +0,0 @@
import { Stack, useRouter } from "expo-router"
import { memo, useCallback, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player"
import { SongRowSkeleton } from "@/components/skeletons"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { useSong, useSongs } from "@/lib/song-cache"
import { spacing, useThemeColors } from "@/lib/theme"
type QueueItem = { songId: Id<"songs">; queueIndex: number }
const QueueRow = memo(function QueueRow({
songId,
queueIndex,
isLast,
isCurrent,
onSkipTo,
onMove,
}: QueueItem & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
onMove: (index: number, direction: -1 | 1) => void
}) {
const colors = useThemeColors()
const song = useSong(songId)
return (
<View>
{song ? (
<SongRow song={song} onPress={() => onSkipTo(queueIndex)} />
) : (
<SongRowSkeleton />
)}
<View style={styles.queueActions}>
<Pressable
disabled={queueIndex === 0}
onPress={() => onMove(queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable disabled={isLast} onPress={() => onMove(queueIndex, 1)}>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{isCurrent ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)
})
export default function QueueScreen() {
const router = useRouter()
const colors = useThemeColors()
const { queueSongIds, queueHistorySongIds } = usePlaybackQueue()
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const historySongs = useSongs(queueHistorySongIds)
const items = useMemo<QueueItem[]>(
() => queueSongIds.map((songId, queueIndex) => ({ songId, queueIndex })),
[queueSongIds]
)
const moveSong = useCallback(
(fromIndex: number, direction: -1 | 1) => {
const toIndex = fromIndex + direction
if (toIndex < 0 || toIndex >= queueSongIds.length) return
const next = [...queueSongIds]
const [item] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, item)
void reorderQueue(next)
},
[queueSongIds, reorderQueue]
)
function handleClearQueue() {
if (router.canGoBack()) {
router.back()
setTimeout(() => {
void clearQueue()
}, 0)
return
}
void clearQueue()
}
return (
<>
<Stack.Screen
options={{
headerRight: () =>
queueSongIds.length > 0 ? (
<Button
title="Clear"
variant="ghost"
onPress={handleClearQueue}
/>
) : null,
}}
/>
<FlatList
style={{ flex: 1, backgroundColor: colors.background }}
ListHeaderComponent={
<View>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
Up Next
</Text>
{queueSongIds.length === 0 ? (
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
Queue is empty
</Text>
) : null}
</View>
}
data={items}
keyExtractor={(item) => `${item.songId}-${item.queueIndex}`}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
initialNumToRender={15}
renderItem={({ item }) => (
<QueueRow
{...item}
isLast={item.queueIndex === queueSongIds.length - 1}
isCurrent={item.queueIndex === 0}
onSkipTo={skipToQueueIndex}
onMove={moveSong}
/>
)}
ListFooterComponent={
queueHistorySongIds.length > 0 ? (
<View style={styles.history}>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
History
</Text>
{historySongs.map((song, index) =>
song ? (
<SongRow key={`${song.id}-${index}`} song={song} />
) : (
<SongRowSkeleton
key={`${queueHistorySongIds[index]}-${index}`}
/>
)
)}
</View>
) : null
}
/>
</>
)
}
const styles = StyleSheet.create({
section: {
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
fontSize: 12,
fontWeight: "700",
textTransform: "uppercase",
},
empty: { padding: spacing.lg },
queueActions: {
flexDirection: "row",
gap: spacing.lg,
paddingHorizontal: spacing.lg,
paddingBottom: spacing.sm,
},
history: { marginTop: spacing.lg },
})
+505 -96
View File
@@ -1,10 +1,17 @@
import {
atmosEnabled,
deviceDownloadQualities,
dolbyAtmosSupported,
} from "@/lib/playback-capabilities"
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
import * as ImagePicker from "expo-image-picker"
import { useRouter } from "expo-router"
import { useState } from "react"
import { useEffect, useMemo, useState } from "react"
import { router } from "expo-router"
import {
Alert,
Platform,
Pressable,
ScrollView,
StyleSheet,
@@ -14,20 +21,38 @@ import {
} from "react-native"
import type { StyleProp, ViewStyle } from "react-native"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { contentBottomInset } from "@/components/player"
import { useDownloads, useDownloadsVersion } from "@/contexts/downloads"
import {
readRememberedDownloadQuality,
writeRememberedDownloadQuality,
} from "@/lib/downloads"
import {
DOWNLOAD_QUALITY_DETAILS,
DOWNLOAD_QUALITY_LABELS,
formatBytes,
type DownloadQuality,
} from "@otunes/convex/download-quality"
import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { useServerConfig } from "@/contexts/server-config"
import {
setArtworkColorsEnabled,
useArtworkColorsEnabled,
} from "@/lib/artwork-color-preference"
import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { clearLocalData, signOutToSignIn } from "@/lib/session"
import { clearCoverPaletteCache } from "@/hooks/use-cover-palette"
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
import { changeServer, signOut } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError, showSuccess } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls"
import { showError } from "@/lib/toast"
import type { PlaybackQuality } from "@otunes/convex/playback-stream"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
type Section = "profile" | "quality" | "library" | "users"
type Section = "profile" | "quality" | "downloads" | "library" | "users"
type CurrentUser = {
_id: Id<"users">
@@ -67,13 +92,13 @@ const QUALITY_OPTIONS: {
const SECTIONS: SectionConfig[] = [
{ id: "profile", label: "Profile", icon: "person-circle-outline" },
{ id: "quality", label: "Playback", icon: "volume-high-outline" },
{ id: "downloads", label: "Downloads", icon: "arrow-down-circle-outline" },
{ id: "library", label: "Library", icon: "library-outline", admin: true },
{ id: "users", label: "Users", icon: "people-outline", admin: true },
]
export default function SettingsScreen() {
const colors = useThemeColors()
const router = useRouter()
const user = useCachedQuery(api.auth.currentUser)
const { invalidateSession } = useInvalidateAuthSession()
const { clearServer } = useServerConfig()
@@ -91,14 +116,19 @@ export default function SettingsScreen() {
const visibleSections = SECTIONS.filter((item) => !item.admin || isAdmin)
async function handleSignOut() {
await signOutToSignIn(router, invalidateSession)
try {
await signOut(invalidateSession)
} catch {
showError("Could not clear all local data.")
}
}
async function handleChangeServer() {
await invalidateSession()
await clearLocalData()
await clearServer()
router.replace("/server")
try {
await changeServer(invalidateSession, clearServer)
} catch {
showError("Could not clear all local data.")
}
}
return (
@@ -137,8 +167,14 @@ export default function SettingsScreen() {
})}
</View>
{section === "profile" ? <ProfileSection user={user} /> : null}
{section === "profile" ? (
<>
<AppearanceSection />
<ProfileSection user={user} />
</>
) : null}
{section === "quality" ? <QualitySection user={user} /> : null}
{section === "downloads" ? <DownloadsSection /> : null}
{section === "library" && isAdmin ? <LibrarySection /> : null}
{section === "users" && isAdmin && allUsers ? (
<UsersSection users={allUsers} currentUserId={user._id} />
@@ -154,6 +190,33 @@ export default function SettingsScreen() {
)
}
function AppearanceSection() {
const enabled = useArtworkColorsEnabled()
const [saving, setSaving] = useState(false)
return (
<SettingsCard title="Appearance">
<SwitchRow
title="New artwork colors"
subtitle="Use the new color algorithm on this device."
value={enabled ?? false}
disabled={enabled === undefined || saving}
onValueChange={async (checked) => {
setSaving(true)
try {
await setArtworkColorsEnabled(checked)
clearCoverPaletteCache()
} catch {
showError("Could not save artwork colors preference.")
} finally {
setSaving(false)
}
}}
/>
</SettingsCard>
)
}
function ProfileSection({ user }: { user: CurrentUser }) {
const colors = useThemeColors()
const updateName = useMutation(api.users.updateProfileName)
@@ -179,7 +242,6 @@ function ProfileSection({ user }: { user: CurrentUser }) {
await updateImage({
image: `data:${mime};base64,${result.assets[0].base64}`,
})
showSuccess("Profile photo updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update photo"
@@ -190,7 +252,6 @@ function ProfileSection({ user }: { user: CurrentUser }) {
async function removeImage() {
try {
await updateImage({ image: null })
showSuccess("Profile photo removed")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to remove photo"
@@ -209,7 +270,6 @@ function ProfileSection({ user }: { user: CurrentUser }) {
await updatePassword({ newPassword })
setNewPassword("")
setConfirmPassword("")
showSuccess("Password updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update password"
@@ -258,9 +318,8 @@ function ProfileSection({ user }: { user: CurrentUser }) {
variant="secondary"
disabled={name.trim() === user.name}
onPress={() =>
void updateName({ name: name.trim() }).then(
() => showSuccess("Name updated"),
(error: Error) => showError(error.message)
void updateName({ name: name.trim() }).catch((error: Error) =>
showError(error.message)
)
}
/>
@@ -279,9 +338,8 @@ function ProfileSection({ user }: { user: CurrentUser }) {
variant="secondary"
disabled={email.trim() === user.email}
onPress={() =>
void updateEmail({ email: email.trim() }).then(
() => showSuccess("Email updated"),
(error: Error) => showError(error.message)
void updateEmail({ email: email.trim() }).catch((error: Error) =>
showError(error.message)
)
}
/>
@@ -375,8 +433,13 @@ function QualitySection({ user }: { user: CurrentUser }) {
<SettingsCard title="Spatial Audio">
<SwitchRow
title="Prefer Dolby Atmos"
subtitle="Use Atmos versions when they are available."
value={user.preferAtmos ?? false}
subtitle={
dolbyAtmosSupported
? "Use Atmos versions when they are available."
: "This device does not support Dolby Atmos playback."
}
disabled={!dolbyAtmosSupported}
value={atmosEnabled(user)}
onValueChange={(checked) =>
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
showError(error.message)
@@ -388,6 +451,299 @@ function QualitySection({ user }: { user: CurrentUser }) {
)
}
/** Shades of the text color, faintest for the smallest files. */
const QUALITY_OPACITY: Record<DownloadQuality, number> = {
low: 0.2,
medium: 0.35,
high: 0.5,
lossless: 0.75,
atmos: 1,
}
function songCount(count: number) {
return count === 1 ? "1 song" : `${count} songs`
}
function QualityName({
quality,
color,
backgroundColor,
}: {
quality: DownloadQuality
color: string
backgroundColor: string
}) {
if (quality === "lossless" || quality === "atmos") {
return (
<AudioFormatBadge
format={quality}
color={color}
backgroundColor={backgroundColor}
/>
)
}
return (
<Text style={{ color, fontSize: 13, fontWeight: "500" }}>
{DOWNLOAD_QUALITY_LABELS[quality]}
</Text>
)
}
function confirm(title: string, onConfirm: () => void) {
Alert.alert(title, undefined, [
{ text: "Cancel", style: "cancel" },
{ text: "Remove", style: "destructive", onPress: onConfirm },
])
}
function RememberedQualityCard() {
const colors = useThemeColors()
// undefined until read; null means ask every time.
const [remembered, setRemembered] = useState<DownloadQuality | null>()
useEffect(() => {
void readRememberedDownloadQuality().then((quality) =>
setRemembered(quality ?? null)
)
}, [])
const options: {
value: DownloadQuality | null
label: string
detail: string
}[] = [
{ value: null, label: "Ask every time", detail: "Choose when downloading" },
...deviceDownloadQualities.map((quality) => ({
value: quality,
label: DOWNLOAD_QUALITY_LABELS[quality],
detail: DOWNLOAD_QUALITY_DETAILS[quality],
})),
]
return (
<SettingsCard title="Download Quality">
{options.map((option) => {
const selected = remembered === option.value
return (
<Pressable
key={option.value ?? "ask"}
accessibilityRole="button"
accessibilityState={{ selected }}
onPress={() => {
setRemembered(option.value)
void writeRememberedDownloadQuality(option.value ?? undefined)
}}
style={[
styles.optionRow,
{
borderColor: selected ? colors.primary : colors.border,
backgroundColor: selected ? colors.muted : colors.card,
},
]}
>
<View style={styles.optionCopy}>
<Text style={[styles.optionTitle, { color: colors.foreground }]}>
{option.label}
</Text>
<Text style={{ color: colors.mutedForeground }}>
{option.detail}
</Text>
</View>
{selected ? (
<Ionicons
name="checkmark-circle"
size={22}
color={colors.primary}
/>
) : null}
</Pressable>
)
})}
</SettingsCard>
)
}
function DownloadsSection() {
const colors = useThemeColors()
const { queue } = useDownloads()
const version = useDownloadsVersion()
const breakdown = useMemo(
() => queue?.breakdown(),
// version invalidates the breakdown when downloads change.
// eslint-disable-next-line react-hooks/exhaustive-deps
[queue, version]
)
if (!queue || !breakdown) return null
const qualities = breakdown.byQuality.filter((entry) => entry.songs > 0)
return (
<>
<SettingsCard title="Storage">
<Text style={{ color: colors.foreground, fontSize: 15 }}>
{formatBytes(breakdown.bytes)} · {songCount(breakdown.songs)}
{breakdown.queued > 0 ? ` · ${breakdown.queued} downloading` : ""}
</Text>
{breakdown.songs > 0 ? (
<>
<View
style={[styles.storageBar, { backgroundColor: colors.muted }]}
>
{qualities.map((entry) => (
<View
key={entry.quality}
style={{
flex: entry.bytes,
backgroundColor: colors.foreground,
opacity: QUALITY_OPACITY[entry.quality],
}}
/>
))}
</View>
{qualities.map((entry) => (
<View key={entry.quality} style={styles.storageRow}>
<View
style={[
styles.storageDot,
{
backgroundColor: colors.foreground,
opacity: QUALITY_OPACITY[entry.quality],
},
]}
/>
<View style={{ flex: 1 }}>
<QualityName
quality={entry.quality}
color={colors.foreground}
backgroundColor={colors.card}
/>
</View>
<Text style={{ color: colors.mutedForeground, fontSize: 13 }}>
{songCount(entry.songs)}
</Text>
<Text
style={[styles.storageSize, { color: colors.foreground }]}
>
{formatBytes(entry.bytes)}
</Text>
</View>
))}
</>
) : null}
</SettingsCard>
<RememberedQualityCard />
{breakdown.collections.length > 0 ||
breakdown.otherSongs.songIds.length > 0 ? (
<SettingsCard title="Downloaded">
{breakdown.collections.map(
({ collection, bytes, status, fallbackCount }) => (
<View
key={`${collection.kind}:${collection.id}`}
style={styles.storageRow}
>
<View style={styles.optionCopy}>
<Text
style={{ color: colors.foreground, fontSize: 15 }}
numberOfLines={1}
>
{collection.title}
</Text>
<View style={styles.collectionMeta}>
<Text
style={{ color: colors.mutedForeground, fontSize: 13 }}
>
{collection.kind === "album" ? "Album" : "Playlist"} ·
</Text>
<QualityName
quality={collection.quality}
color={colors.mutedForeground}
backgroundColor={colors.card}
/>
{fallbackCount > 0 ? (
<Text
style={{ color: colors.mutedForeground, fontSize: 13 }}
>
({fallbackCount} in High)
</Text>
) : null}
{status.downloaded < status.total ? (
<Text
style={{ color: colors.mutedForeground, fontSize: 13 }}
>
· {status.downloaded} of {status.total}
</Text>
) : null}
</View>
</View>
<Text
style={[styles.storageSize, { color: colors.foreground }]}
>
{formatBytes(bytes)}
</Text>
<Pressable
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={`Remove download of ${collection.title}`}
onPress={() =>
confirm(
`Remove ${collection.title}?`,
() => void queue.removeCollection(collection)
)
}
>
<Ionicons
name="trash-outline"
size={20}
color={colors.mutedForeground}
/>
</Pressable>
</View>
)
)}
{breakdown.otherSongs.songIds.length > 0 ? (
<View style={styles.storageRow}>
<View style={styles.optionCopy}>
<Text style={{ color: colors.foreground, fontSize: 15 }}>
Other Downloaded Songs
</Text>
<Text style={{ color: colors.mutedForeground, fontSize: 13 }}>
{songCount(breakdown.otherSongs.songIds.length)}
</Text>
</View>
<Text style={[styles.storageSize, { color: colors.foreground }]}>
{formatBytes(breakdown.otherSongs.bytes)}
</Text>
<Pressable
hitSlop={8}
accessibilityRole="button"
accessibilityLabel="Remove Other Downloaded Songs"
onPress={() =>
confirm(
"Remove Other Downloaded Songs?",
() => void queue.removeOtherSongs()
)
}
>
<Ionicons
name="trash-outline"
size={20}
color={colors.mutedForeground}
/>
</Pressable>
</View>
) : null}
<Button
title="Remove All Downloads"
variant="destructive"
onPress={() =>
confirm("Remove all downloads?", () => void queue.removeAll())
}
/>
</SettingsCard>
) : null}
</>
)
}
function LibrarySection() {
const updateLibrary = useAction(api.actions.updateLibrary)
const cleanupHlsStreams = useAction(api.actions.adminCleanupHlsStreams)
@@ -407,7 +763,6 @@ function LibrarySection() {
setUpdating(true)
try {
await updateLibrary({})
showSuccess("Library updated")
} catch (error) {
showError(
error instanceof Error
@@ -427,8 +782,7 @@ function LibrarySection() {
onPress={async () => {
setCleaningHls(true)
try {
const result = await cleanupHlsStreams({})
showSuccess(`Removed ${result.removed} idle HLS streams`)
await cleanupHlsStreams({})
} catch (error) {
showError(
error instanceof Error
@@ -462,7 +816,7 @@ function UsersSection({
<SettingsCard title="Sign Up">
<SwitchRow
title="Disable account creation"
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
subtitle="Stop people from registering themselves. Admins can still create accounts."
value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch(
@@ -476,77 +830,85 @@ function UsersSection({
title="People"
subtitle="Manage who can access this server."
>
{users.map((user, index) => (
<View key={user._id}>
{index > 0 ? (
<View
style={[styles.divider, { backgroundColor: colors.border }]}
/>
) : null}
<View style={styles.userRow}>
<ProfileAvatar user={user} size={44} />
<View style={styles.userCopy}>
<View style={styles.userNameRow}>
<Text
style={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[styles.badge, { backgroundColor: colors.muted }]}
<Button
title="Create account"
onPress={() => router.push("/(app)/create-account")}
/>
<View style={styles.userList}>
{users.map((user, index) => (
<View
key={user._id}
style={[
styles.userBlock,
index > 0
? [styles.userBlockSpaced, { borderTopColor: colors.border }]
: null,
]}
>
<View style={styles.userRow}>
<ProfileAvatar user={user} size={44} />
<View style={styles.userCopy}>
<View style={styles.userNameRow}>
<Text
style={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
<Text
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[
styles.badgeText,
{ color: colors.mutedForeground },
styles.badge,
{ backgroundColor: colors.muted },
]}
>
Admin
</Text>
</View>
) : null}
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View>
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{user.email}
</Text>
</View>
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{user.email}
</Text>
</View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).catch((error: Error) => showError(error.message))
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).catch(
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).then(
() => showSuccess("Updated permissions"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).then(
() => showSuccess("User deleted"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
))}
))}
</View>
</SettingsCard>
</>
)
@@ -635,10 +997,12 @@ function SwitchRow({
subtitle,
value,
onValueChange,
disabled,
}: {
title: string
subtitle?: string
value: boolean
disabled?: boolean
onValueChange: (checked: boolean) => void
}) {
const colors = useThemeColors()
@@ -653,7 +1017,17 @@ function SwitchRow({
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
) : null}
</View>
<Switch value={value} onValueChange={onValueChange} />
<Switch
value={value}
disabled={disabled}
onValueChange={onValueChange}
{...(Platform.OS === "android"
? {
trackColor: { false: colors.muted, true: colors.primary },
thumbColor: colors.foreground,
}
: {})}
/>
</View>
)
}
@@ -709,6 +1083,7 @@ function ProfileAvatar({
style?: StyleProp<ViewStyle>
}) {
const colors = useThemeColors()
const imageUrl = useProfileImageUrl(user.image)
const avatarStyle = [
styles.avatar,
{
@@ -720,11 +1095,11 @@ function ProfileAvatar({
style,
]
if (user.image) {
if (imageUrl) {
return (
<View style={avatarStyle}>
<Image
source={{ uri: user.image }}
source={{ uri: imageUrl }}
style={styles.avatarImage}
contentFit="cover"
/>
@@ -811,6 +1186,31 @@ const styles = StyleSheet.create({
divider: {
height: StyleSheet.hairlineWidth,
},
storageBar: {
height: 8,
borderRadius: 4,
overflow: "hidden",
flexDirection: "row",
},
storageRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
minHeight: 36,
},
storageDot: { width: 8, height: 8, borderRadius: 4 },
storageSize: {
minWidth: 56,
textAlign: "right",
fontSize: 13,
fontVariant: ["tabular-nums"],
},
collectionMeta: {
flexDirection: "row",
alignItems: "center",
flexWrap: "wrap",
gap: 4,
},
optionRow: {
borderWidth: 1,
borderRadius: radius.lg,
@@ -833,6 +1233,16 @@ const styles = StyleSheet.create({
alignItems: "center",
gap: spacing.md,
},
userList: {
gap: spacing.lg,
},
userBlock: {
gap: spacing.md,
},
userBlockSpaced: {
paddingTop: spacing.lg,
borderTopWidth: StyleSheet.hairlineWidth,
},
userRow: {
flexDirection: "row",
alignItems: "center",
@@ -855,7 +1265,6 @@ const styles = StyleSheet.create({
userActions: {
flexDirection: "row",
gap: spacing.sm,
marginTop: spacing.md,
},
userActionButton: {
flex: 1,
@@ -1,33 +1,42 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
initialRouteName: "index",
anchor: "index",
}
export default function LibraryLayout() {
const tabletLayout = useTabletLayout()
const baseOptions = useStackScreenOptions({ title: "Library" })
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Library",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
],
})}
/>
<TabStackContext value="library">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
)
}
@@ -0,0 +1 @@
export { default } from "../../home/downloads"
@@ -0,0 +1 @@
export { default } from "../../home/downloads/other"
+71 -30
View File
@@ -1,3 +1,4 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { useMemo } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { SymbolView } from "expo-symbols"
@@ -12,14 +13,27 @@ import { useAppNavigation } from "@/lib/app-navigation"
import { api } from "@otunes/convex/_generated/api"
import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
const PAGE_SIZE = 16
const PAGE_SIZE = 24
const links = [
{ title: "Playlists", href: "/browse/playlists", icon: "music.note.list" as const },
{
title: "Playlists",
href: "/browse/playlists",
icon: "music.note.list" as const,
},
{ title: "Artists", href: "/browse/artists", icon: "mic.fill" as const },
{ title: "Albums", href: "/browse/albums", icon: "square.stack" as const },
{ title: "Songs", href: "/browse/songs", icon: "music.note" as const },
{ title: "Recently Played", href: "/recently-played", icon: "clock" as const },
{
title: "Downloads",
href: "/downloads",
icon: "arrow.down.circle" as const,
},
{
title: "Recently Played",
href: "/recently-played",
icon: "clock" as const,
},
{ title: "Favorites", href: "/playlist/favorites", icon: "star" as const },
]
@@ -42,12 +56,21 @@ function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
clock: "time",
sparkles: "sparkles",
star: "star",
"arrow.down.circle": "arrow-down-circle",
}
return <Ionicons name={ionMap[name] ?? "musical-notes"} size={22} color={appleMusic.pink} />
return (
<Ionicons
name={ionMap[name] ?? "musical-notes"}
size={22}
color={appleMusic.pink}
/>
)
}
export default function LibraryScreen() {
const tabletLayout = useTabletLayout()
const { push } = useAppNavigation()
const isTablet = tabletLayout
const colors = useThemeColors()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
api.library.browseRecentlyAddedPaginated,
@@ -58,38 +81,50 @@ export default function LibraryScreen() {
const listHeader = useMemo(
() => (
<View>
{links.map((link) => (
<Pressable
key={link.href}
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => push(link.href)}
>
<LibraryIcon name={link.icon} />
<Text style={[styles.rowTitle, { color: colors.foreground }]}>{link.title}</Text>
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
</Pressable>
))}
{!isTablet ? (
<>
{links.map((link) => (
<Pressable
key={link.href}
style={styles.row}
onPress={() => push(link.href)}
>
<LibraryIcon name={link.icon} />
<View
style={[
styles.rowContent,
{ borderBottomColor: colors.border },
]}
>
<Text style={[styles.rowTitle, { color: colors.foreground }]}>
{link.title}
</Text>
<Ionicons
name="chevron-forward"
size={16}
color={colors.mutedForeground}
/>
</View>
</Pressable>
))}
<Pressable
style={[styles.section, { paddingHorizontal: spacing.lg }]}
onPress={() => push("/recently-added")}
>
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
Recently Added
</Text>
</Pressable>
<Pressable
style={[styles.section, { paddingHorizontal: spacing.lg }]}
onPress={() => push("/recently-added")}
>
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
Recently Added
</Text>
</Pressable>
</>
) : null}
</View>
),
[colors.border, colors.foreground, colors.mutedForeground, push]
[colors.border, colors.foreground, colors.mutedForeground, push, isTablet]
)
if (status === "LoadingFirstPage" && !isCached) {
return (
<View style={{ flex: 1, backgroundColor: colors.background }}>
{listHeader}
<MediaGridSkeleton contentInset={false} />
</View>
)
return <MediaGridSkeleton contentInset={false} header={listHeader} />
}
return (
@@ -111,6 +146,12 @@ const styles = StyleSheet.create({
alignItems: "center",
gap: spacing.md,
paddingHorizontal: spacing.lg,
},
rowContent: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingVertical: 14,
borderBottomWidth: StyleSheet.hairlineWidth,
},
@@ -1 +0,0 @@
export { default } from "../home/queue"
+24 -19
View File
@@ -1,33 +1,38 @@
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
export const unstable_settings = {
initialRouteName: "index",
anchor: "index",
}
export default function SearchLayout() {
const baseOptions = useStackScreenOptions({ title: "Search" })
return (
<Stack
initialRouteName="index"
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
unstable_headerRightItems:
route.name === "settings"
? undefined
: () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
],
})}
/>
<TabStackContext value="search">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
)
}
@@ -0,0 +1 @@
export { default } from "../../home/downloads"
@@ -0,0 +1 @@
export { default } from "../../home/downloads/other"
@@ -1,3 +1,5 @@
import { Platform } from "react-native"
import { useThemeColors } from "@/lib/theme"
import { Stack } from "expo-router"
import { useCallback } from "react"
@@ -5,6 +7,7 @@ import { SearchResults } from "@/components/search-results"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
export default function SearchScreen() {
const colors = useThemeColors()
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const handleChangeText = useCallback(
@@ -21,6 +24,15 @@ export default function SearchScreen() {
onChangeText={handleChangeText}
onSearchButtonPress={onSearchSubmit}
autoCapitalize="none"
{...(Platform.OS === "android"
? {
barTintColor: colors.background,
textColor: colors.foreground,
tintColor: colors.primary,
hintTextColor: colors.mutedForeground,
headerIconColor: colors.foreground,
}
: {})}
/>
<SearchResults searchQuery={searchQuery} />
@@ -1 +0,0 @@
export { default } from "../home/queue"
+87 -43
View File
@@ -1,31 +1,49 @@
import { router, type Href } from "expo-router"
import { useServerConfig } from "@/contexts/server-config"
import {
incomingMediaLink,
subscribeIncomingMediaLink,
takeIncomingMediaLink,
} from "@/lib/incoming-media-link"
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import {
useConvexAuth as useServerConvexAuth,
useConvexConnectionState,
} from "convex/react"
import { Redirect, Stack } from "expo-router"
import { Stack } from "expo-router"
import { Platform } from "react-native"
import { useEffect } from "react"
import { useEffect, useSyncExternalStore } from "react"
import { AppIntentBridge } from "@/components/app-intent-bridge"
import { ConvexAuthRecovery } from "@/components/convex-auth-recovery"
import { LoadingView } from "@/components/ui/primitives"
import { AddToPlaylistProvider } from "@/contexts/add-to-playlist"
import { DownloadsProvider } from "@/contexts/downloads"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { FavoritesProvider } from "@/contexts/favorites"
import { PlaybackProvider } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useStackScreenOptions } from "@/lib/navigation"
import { AppNavigationSync } from "@/lib/app-navigation"
const AUTH_HANDSHAKE_TIMEOUT_MS = 15_000
export default function AppLayout() {
const { config } = useServerConfig()
const localAuth = useLocalConvexAuth()
const serverAuth = useServerConvexAuth()
const { isWebSocketConnected } = useConvexConnectionState()
const { invalidateSession } = useInvalidateAuthSession()
const stackOptions = useStackScreenOptions()
const { config } = useServerConfig()
const pendingDestination = useSyncExternalStore(
subscribeIncomingMediaLink,
() => (config ? incomingMediaLink(config.serverUrl) : null),
() => null
)
useEffect(() => {
if (!config || !pendingDestination) return
const destination = takeIncomingMediaLink(config.serverUrl)
if (destination) router.replace(destination as Href)
}, [config, pendingDestination])
useEffect(() => {
if (
@@ -50,18 +68,6 @@ export default function AppLayout() {
serverAuth?.isAuthenticated,
])
if (!config) {
return <Redirect href="/server" />
}
if (!localAuth || localAuth.isLoading) {
return <LoadingView />
}
if (!localAuth.isAuthenticated) {
return <Redirect href="/signin" />
}
// Convex holds queries until the stored token is confirmed, so the app can
// render cached data while the server handshake is still in progress.
@@ -70,32 +76,70 @@ export default function AppLayout() {
<PlaybackProvider>
<AppNavigationSync />
<AddToPlaylistProvider>
<FavoritesProvider>
<Stack screenOptions={stackOptions}>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="settings"
options={{
headerShown: false,
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
}}
/>
<Stack.Screen
name="player"
options={{
headerShown: false,
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
fullScreenGestureEnabled: true,
}}
/>
</Stack>
</FavoritesProvider>
<DownloadsProvider>
<FavoritesProvider>
<AppIntentBridge />
<Stack screenOptions={stackOptions}>
<Stack.Screen
name="(tabs)"
options={{ headerShown: false, animation: "none" }}
/>
<Stack.Screen
name="settings"
options={{
headerShown: Platform.OS === "android",
title: "Settings",
presentation:
Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
}}
/>
<Stack.Screen
name="create-account"
options={{
title: "Create account",
presentation: "modal",
headerLargeTitle: false,
headerTransparent: false,
headerStyle: { backgroundColor: "#000" },
headerTintColor: "#fff",
contentStyle: { backgroundColor: "#000" },
}}
/>
<Stack.Screen
name="playlist-cover"
options={{
title: "Cover",
headerTitleAlign: "center",
presentation:
Platform.OS === "ios" ? "modal" : "fullScreenModal",
animation: "slide_from_bottom",
headerLargeTitle: false,
headerTransparent: false,
headerShadowVisible: false,
headerStyle: { backgroundColor: "#000" },
headerTintColor: "#fff",
contentStyle: { backgroundColor: "#000" },
}}
/>
<Stack.Screen
name="player"
options={{
headerShown: false,
// Keep the library visible behind the custom swipe animation.
presentation: "transparentModal",
contentStyle: { backgroundColor: "transparent" },
animation: "slide_from_bottom",
gestureEnabled: true,
gestureDirection: "vertical",
fullScreenGestureEnabled: true,
}}
/>
</Stack>
</FavoritesProvider>
</DownloadsProvider>
</AddToPlaylistProvider>
</PlaybackProvider>
</ConvexAuthRecovery>
+199
View File
@@ -0,0 +1,199 @@
import { useAction, useQuery } from "convex/react"
import { ConvexError } from "convex/values"
import { router, Stack } from "expo-router"
import { useEffect, useRef, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet,
Switch,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { toast } from "sonner-native"
import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { colors, spacing } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api"
export default function CreateAccountScreen() {
const user = useQuery(api.auth.currentUser)
const createUser = useAction(api.users.adminCreateUser)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [isAdmin, setIsAdmin] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const pending = useRef(false)
const mounted = useRef(true)
useEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
async function handleCreate() {
if (pending.current || !user?.isAdmin) return
setError(null)
if (!name.trim() || !email.trim().includes("@") || password.length < 8) {
setError(
"Enter a name, valid email, and password of at least 8 characters."
)
return
}
pending.current = true
setSubmitting(true)
try {
await createUser({
name: name.trim(),
email: email.trim().toLowerCase(),
password,
isAdmin,
})
toast.success("Account created")
if (mounted.current) router.back()
} catch (error) {
if (!mounted.current) return
setError(
error instanceof ConvexError && typeof error.data === "string"
? error.data
: "Could not create account. Try again."
)
} finally {
pending.current = false
if (mounted.current) setSubmitting(false)
}
}
return (
<SafeAreaView edges={["bottom", "left", "right"]} style={styles.screen}>
<Stack.Screen
options={{
gestureEnabled: !submitting,
}}
/>
{user === undefined ? (
<LoadingView />
) : !user?.isAdmin ? (
<Text style={[styles.text, styles.message]}>
Admin access required.
</Text>
) : (
<KeyboardAvoidingView
style={styles.screen}
behavior={Platform.OS === "ios" ? "padding" : undefined}
keyboardVerticalOffset={Platform.OS === "ios" ? 100 : 0}
>
<ScrollView
contentContainerStyle={styles.form}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<View style={styles.field}>
<Text style={styles.label}>Name</Text>
<Input
accessibilityLabel="Name"
value={name}
onChangeText={setName}
autoCapitalize="words"
autoComplete="off"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.field}>
<Text style={styles.label}>Email</Text>
<Input
accessibilityLabel="Email"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
autoComplete="off"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.field}>
<Text style={styles.label}>Password</Text>
<Input
accessibilityLabel="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
autoCapitalize="none"
autoCorrect={false}
autoComplete="new-password"
placeholder="At least 8 characters"
editable={!submitting}
style={styles.input}
/>
</View>
<View style={styles.row}>
<Text style={styles.text}>Grant admin access</Text>
<Switch
accessibilityLabel="Grant admin access"
trackColor={{
false: colors.dark.muted,
true: colors.dark.primary,
}}
thumbColor={colors.dark.foreground}
value={isAdmin}
onValueChange={setIsAdmin}
disabled={submitting}
/>
</View>
{error ? (
<Text accessibilityRole="alert" style={styles.error}>
{error}
</Text>
) : null}
<Button
title={submitting ? "Creating account…" : "Create account"}
disabled={submitting}
onPress={() => void handleCreate()}
tint={{
background: colors.dark.primary,
foreground: colors.dark.primaryForeground,
}}
/>
</ScrollView>
</KeyboardAvoidingView>
)}
</SafeAreaView>
)
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: "#000" },
form: { padding: spacing.lg, gap: spacing.lg },
field: { gap: spacing.sm },
label: {
color: colors.dark.mutedForeground,
fontSize: 12,
fontWeight: "600",
textTransform: "uppercase",
letterSpacing: 0.6,
},
text: { color: colors.dark.foreground, fontSize: 16, flexShrink: 1 },
input: {
backgroundColor: colors.dark.muted,
color: colors.dark.foreground,
borderColor: colors.dark.border,
},
row: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: spacing.md,
minHeight: 48,
},
message: { padding: spacing.lg },
error: { color: colors.dark.destructive, fontSize: 14, lineHeight: 20 },
})
-5
View File
@@ -1,5 +0,0 @@
import { Redirect } from "expo-router"
export default function AppIndex() {
return <Redirect href="/(app)/(tabs)/home" />
}
File diff suppressed because it is too large. Load diff
+391
View File
@@ -0,0 +1,391 @@
import { useMutation } from "convex/react"
import { Image } from "expo-image"
import * as ImagePicker from "expo-image-picker"
import { router, Stack, useLocalSearchParams } from "expo-router"
import { useMemo, useState, type ReactNode } from "react"
import {
Pressable,
ScrollView,
StyleSheet,
Text,
useWindowDimensions,
View,
} from "react-native"
import { CoverImage } from "@/components/cover-image"
import { Button, LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { showError } from "@/lib/toast"
import { albumCoverUrl, playlistCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
COVER_GRID_ALBUMS,
playlistCoverAlbums,
randomPlaylistCovers,
} from "@otunes/convex/client/playlist-cover"
type Choice =
| { kind: "current" }
| { kind: "albums"; albumIds: Id<"albums">[] }
| { kind: "upload"; uri: string; image: string }
const STRIP_GAP = spacing.sm
/** Selection border and padding around each thumb, both sides. */
const THUMB_CHROME = 6
/**
* Full screen cover editor for a playlist owner: a large preview of the
* selected cover, the current cover pinned apart from four random album
* grids, and Save in the header. Opened from the playlist's menu.
*/
export default function PlaylistCoverScreen() {
const { id } = useLocalSearchParams<{ id: string }>()
const playlistId = id as Id<"playlists">
const playlist = useCachedQuery(api.playlists.browsePlaylistDetail, {
id: playlistId,
})
const { config } = useServerConfig()
const colors = useThemeColors()
const { width } = useWindowDimensions()
const setCoverAlbums = useMutation(api.playlists.setPlaylistCoverAlbums)
const uploadCover = useMutation(api.playlists.uploadPlaylistCover)
const albums = useMemo(
() => (playlist ? playlistCoverAlbums(playlist.songs) : []),
[playlist]
)
const [options, setOptions] = useState<Id<"albums">[][] | null>(null)
const [selected, setSelected] = useState<Choice | null>(null)
const [saving, setSaving] = useState(false)
// Draw options once the songs arrive.
if (options === null && playlist) {
setOptions(randomPlaylistCovers(albums))
}
const hasCurrent = playlist?.cover != null
const choice: Choice | null =
selected ??
(hasCurrent
? { kind: "current" }
: options?.[0]
? { kind: "albums", albumIds: options[0] }
: null)
async function pickImage() {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsEditing: true,
aspect: [1, 1],
quality: 0.7,
base64: true,
})
const asset = result.canceled ? undefined : result.assets[0]
if (!asset?.base64) return
setSelected({
kind: "upload",
uri: asset.uri,
image: `data:${asset.mimeType ?? "image/jpeg"};base64,${asset.base64}`,
})
}
async function save() {
if (!choice || choice.kind === "current") {
router.back()
return
}
setSaving(true)
try {
if (choice.kind === "albums") {
await setCoverAlbums({ playlistId, albumIds: choice.albumIds })
} else {
await uploadCover({ playlistId, image: choice.image })
}
router.back()
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to change cover"
)
setSaving(false)
}
}
const header = (
<Stack.Screen
options={{
headerLeft: () => (
<HeaderButton label="Cancel" onPress={() => router.back()} />
),
headerRight: () => (
<HeaderButton
label="Save"
bold
disabled={saving || !choice}
onPress={() => void save()}
/>
),
}}
/>
)
if (!playlist || !config || !options) {
return (
<>
{header}
<LoadingView />
</>
)
}
const serverUrl = config.serverUrl
const currentUri = playlistCoverUrl(serverUrl, playlistId, playlist.cover)
const previewSize = Math.min(width - spacing.lg * 2, 360)
// One row: current | uploaded? | options, thumbs at most 72pt.
const thumbCount =
options.length + (hasCurrent ? 1 : 0) + (choice?.kind === "upload" ? 1 : 0)
const rowItems = thumbCount + (hasCurrent ? 1 : 0)
const thumbSize = Math.min(
72,
Math.floor(
(width - spacing.lg * 2 - STRIP_GAP * (rowItems - 1) - 1) /
Math.max(thumbCount, 1)
) - THUMB_CHROME
)
function renderChoice(item: Choice, size: number) {
if (item.kind === "current") {
return (
<CoverImage
uri={currentUri}
hasCover
style={{ width: size, height: size }}
/>
)
}
if (item.kind === "upload") {
return (
<Image
source={{ uri: item.uri }}
style={{ width: size, height: size }}
/>
)
}
return (
<AlbumGrid serverUrl={serverUrl} albumIds={item.albumIds} size={size} />
)
}
const isSelected = (item: Choice) =>
choice?.kind === item.kind &&
(item.kind !== "albums" ||
(choice.kind === "albums" && choice.albumIds === item.albumIds))
return (
<ScrollView
style={{ backgroundColor: colors.background }}
contentContainerStyle={styles.content}
>
{header}
<View
style={[
styles.preview,
{
width: previewSize,
height: previewSize,
backgroundColor: colors.coverPlaceholder,
},
]}
>
{choice ? renderChoice(choice, previewSize) : null}
</View>
<View style={styles.strip}>
{hasCurrent ? (
<>
<Thumb
size={thumbSize}
selected={isSelected({ kind: "current" })}
label="Current cover"
onPress={() => setSelected({ kind: "current" })}
>
{renderChoice({ kind: "current" }, thumbSize)}
</Thumb>
<View
style={[styles.separator, { backgroundColor: colors.border }]}
/>
</>
) : null}
{choice?.kind === "upload" ? (
<Thumb size={thumbSize} selected label="Uploaded image">
{renderChoice(choice, thumbSize)}
</Thumb>
) : null}
{options.map((albumIds) => {
const item: Choice = { kind: "albums", albumIds }
return (
<Thumb
key={albumIds.join(",")}
size={thumbSize}
selected={isSelected(item)}
label="Album cover option"
onPress={() => setSelected(item)}
>
{renderChoice(item, thumbSize)}
</Thumb>
)
})}
</View>
{albums.length === 0 ? (
<Text style={{ color: colors.mutedForeground, textAlign: "center" }}>
No album artwork in this playlist yet.
</Text>
) : null}
<View style={styles.actions}>
{albums.length >= COVER_GRID_ALBUMS ? (
<Button
title="Shuffle"
icon="shuffle"
variant="secondary"
onPress={() => {
setOptions(randomPlaylistCovers(albums))
if (selected?.kind === "albums") setSelected(null)
}}
/>
) : null}
<Button
title="Upload"
icon="arrow-up"
variant="secondary"
onPress={() => void pickImage()}
/>
</View>
</ScrollView>
)
}
function HeaderButton({
label,
bold = false,
disabled = false,
onPress,
}: {
label: string
bold?: boolean
disabled?: boolean
onPress: () => void
}) {
const colors = useThemeColors()
return (
<Pressable
accessibilityRole="button"
hitSlop={8}
disabled={disabled}
onPress={onPress}
style={{ opacity: disabled ? 0.4 : 1, paddingHorizontal: spacing.xs }}
>
<Text
style={{
color: colors.foreground,
fontSize: 17,
fontWeight: bold ? "600" : "400",
}}
>
{label}
</Text>
</Pressable>
)
}
function Thumb({
size,
selected,
label,
onPress,
children,
}: {
size: number
selected: boolean
label: string
onPress?: () => void
children: ReactNode
}) {
const colors = useThemeColors()
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={label}
accessibilityState={{ selected }}
onPress={onPress}
style={[
styles.thumb,
{
width: size + THUMB_CHROME,
height: size + THUMB_CHROME,
borderColor: selected ? colors.foreground : "transparent",
},
]}
>
<View style={styles.thumbInner}>{children}</View>
</Pressable>
)
}
/** A generated cover option: one album alone, or four tiled 2x2. */
function AlbumGrid({
serverUrl,
albumIds,
size,
}: {
serverUrl: string
albumIds: Id<"albums">[]
size: number
}) {
const tile = albumIds.length > 1 ? size / 2 : size
return (
<View
style={{
width: size,
height: size,
flexDirection: "row",
flexWrap: "wrap",
}}
>
{albumIds.map((albumId) => (
<CoverImage
key={albumId}
uri={albumCoverUrl(serverUrl, albumId)}
hasCover
style={{ width: tile, height: tile }}
/>
))}
</View>
)
}
const styles = StyleSheet.create({
content: {
alignItems: "center",
gap: spacing.xl,
padding: spacing.lg,
},
preview: { borderRadius: radius.lg, overflow: "hidden" },
strip: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: STRIP_GAP,
},
separator: { width: StyleSheet.hairlineWidth, alignSelf: "stretch" },
thumb: {
borderWidth: 2,
borderRadius: radius.sm + 2,
padding: 1,
},
thumbInner: { flex: 1, borderRadius: radius.sm, overflow: "hidden" },
actions: { flexDirection: "row", gap: spacing.sm },
})
+16 -1
View File
@@ -1 +1,16 @@
export { default } from "./(tabs)/home/settings"
import { Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import SettingsScreen from "./(tabs)/home/settings"
export default function Settings() {
if (Platform.OS !== "android") return <SettingsScreen />
return (
<SafeAreaView
edges={["bottom", "left", "right"]}
style={{ flex: 1, backgroundColor: "#000" }}
>
<SettingsScreen />
</SafeAreaView>
)
}
+2 -23
View File
@@ -1,28 +1,7 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect, Stack } from "expo-router"
import { Stack } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
export const unstable_settings = { anchor: "signin" }
export default function AuthLayout() {
const { config, isLoading: serverLoading } = useServerConfig()
const auth = useConvexAuth()
if (serverLoading) {
return <LoadingView />
}
if (!config) {
return <Redirect href="/server" />
}
if (!auth || auth.isLoading) {
return <LoadingView />
}
if (auth.isAuthenticated) {
return <Redirect href="/(app)/(tabs)/home" />
}
return <Stack screenOptions={{ headerShown: false }} />
}
+57
View File
@@ -0,0 +1,57 @@
import { loadServerConfig, parseServerHostname } from "@/lib/server-config"
import { secureGetItem } from "@/lib/auth-storage"
import {
isMediaRoute,
rememberIncomingMediaLink,
} from "@/lib/incoming-media-link"
import { showError } from "@/lib/toast"
export async function redirectSystemPath({
path,
}: {
path: string
initial: boolean
}) {
try {
const link = new URL(path, "otunes:///")
if (
!["otunes:", "otunes-development:", "otunes-preview:"].includes(
link.protocol
) ||
link.hostname !== "open"
) {
return path
}
const target = new URL(link.searchParams.get("url") ?? "")
const server = parseServerHostname(target.host)
if (
!server ||
!["https:", "http:"].includes(target.protocol) ||
target.username ||
target.password ||
new URL(server.serverUrl).origin !== target.origin ||
!isMediaRoute(target.pathname)
) {
return "/"
}
const config = await loadServerConfig(secureGetItem)
if (config && new URL(config.serverUrl).origin !== target.origin) {
showError("This link belongs to a different oTunes server")
return "/"
}
const query = new URLSearchParams()
const songId = target.searchParams.get("s")
if (target.pathname.startsWith("/album/") && songId) query.set("s", songId)
const suffix = query.size ? `?${query}` : ""
const destination = `/(app)/(tabs)/home${target.pathname}${suffix}`
rememberIncomingMediaLink(destination, target.origin)
return config
? destination
: `/server?hostname=${encodeURIComponent(server.hostname)}`
} catch {
return "/"
}
}
+51 -13
View File
@@ -1,28 +1,66 @@
import { Stack } from "expo-router"
import { useConvexAuth } from "@convex-dev/auth/react"
import { DarkTheme, Stack, ThemeProvider } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { useColorScheme } from "react-native"
import { useIsDark } from "@/lib/theme"
import { GestureHandlerRootView } from "react-native-gesture-handler"
import { SafeAreaProvider } from "react-native-safe-area-context"
import { Toaster } from "@/components/ui/toaster"
import { ConvexAppProvider } from "@/contexts/convex-app"
import { ServerConfigProvider } from "@/contexts/server-config"
import { ServerConfigProvider, useServerConfig } from "@/contexts/server-config"
export default function RootLayout() {
const colorScheme = useColorScheme()
import { HandoffBridge } from "@/components/handoff-bridge"
const navigationTheme = {
...DarkTheme,
colors: { ...DarkTheme.colors, background: "#000", card: "#000" },
}
function RootNavigator() {
const { config, isLoading } = useServerConfig()
const auth = useConvexAuth()
if (isLoading || (config && (!auth || auth.isLoading))) {
return null
}
const isAuthenticated = Boolean(config && auth?.isAuthenticated)
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<Stack
screenOptions={{
headerShown: false,
animation: "none",
contentStyle: { backgroundColor: "#000" },
}}
>
<Stack.Screen name="index" />
<Stack.Protected guard={isAuthenticated}>
<Stack.Screen name="(app)" />
</Stack.Protected>
<Stack.Protected guard={Boolean(config) && !isAuthenticated}>
<Stack.Screen name="(auth)" />
</Stack.Protected>
<Stack.Protected guard={!config}>
<Stack.Screen name="server" />
</Stack.Protected>
</Stack>
)
}
export default function RootLayout() {
const isDark = useIsDark()
return (
<GestureHandlerRootView style={{ flex: 1, backgroundColor: "#000" }}>
<SafeAreaProvider>
<ServerConfigProvider>
<ConvexAppProvider>
<StatusBar style={colorScheme === "dark" ? "light" : "dark"} />
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" />
<Stack.Screen name="server" />
<Stack.Screen name="(auth)" />
<Stack.Screen name="(app)" />
</Stack>
<StatusBar style={isDark ? "light" : "dark"} />
<ThemeProvider value={navigationTheme}>
<HandoffBridge />
<RootNavigator />
</ThemeProvider>
<Toaster />
</ConvexAppProvider>
</ServerConfigProvider>
+17 -9
View File
@@ -1,19 +1,27 @@
import { Redirect } from "expo-router"
import { useConvexAuth } from "@convex-dev/auth/react"
import { incomingMediaLink } from "@/lib/incoming-media-link"
import { Redirect, type Href } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { AuthenticatedRedirect } from "@/components/authenticated-redirect"
export default function Index() {
const { config, isLoading } = useServerConfig()
if (isLoading) {
return <LoadingView />
}
const { config } = useServerConfig()
const auth = useConvexAuth()
if (!config) {
return <Redirect href="/server" />
}
return <AuthenticatedRedirect />
const destination = auth?.isAuthenticated
? incomingMediaLink(config.serverUrl)
: null
return (
<Redirect
href={
(destination as Href) ??
(auth?.isAuthenticated ? "/(app)/(tabs)/library" : "/signin")
}
/>
)
}
+15 -27
View File
@@ -1,32 +1,28 @@
import { useRouter } from "expo-router"
import { useLocalSearchParams } from "expo-router"
import { useEffect, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
StyleSheet,
Text,
View,
} from "react-native"
import { StyleSheet, Text, View } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { KeyboardForm } from "@/components/keyboard-form"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { spacing, useThemeColors } from "@/lib/theme"
export default function ServerScreen() {
const router = useRouter()
const colors = useThemeColors()
const { config, isLoading, setServerHostname } = useServerConfig()
const [hostname, setHostname] = useState("")
const { setServerHostname } = useServerConfig()
const { hostname: linkedHostname } = useLocalSearchParams<{
hostname?: string
}>()
const [hostname, setHostname] = useState(linkedHostname ?? "")
useEffect(() => {
if (linkedHostname) setHostname(linkedHostname)
}, [linkedHostname])
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (config?.hostname) {
setHostname(config.hostname)
}
}, [config?.hostname])
async function handleContinue() {
setError(null)
setSubmitting(true)
@@ -38,7 +34,6 @@ export default function ServerScreen() {
)
return
}
router.replace("/signin")
} catch {
setError(
"Could not save the server address. Check device storage and try again."
@@ -48,16 +43,9 @@ export default function ServerScreen() {
}
}
if (isLoading) {
return null
}
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<KeyboardForm style={styles.container}>
<View style={styles.hero}>
<Text style={[styles.brand, { color: colors.foreground }]}>
oTunes
@@ -95,7 +83,7 @@ export default function ServerScreen() {
onPress={() => void handleContinue()}
/>
</Card>
</KeyboardAvoidingView>
</KeyboardForm>
</SafeAreaView>
)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 284 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 963 KiB

After

Width:  |  Height:  |  Size: 284 KiB

+1 -1
View File
@@ -26,7 +26,7 @@
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1,
"scale" : 1.5,
"translation-in-points" : [
0,
0
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

@@ -0,0 +1,53 @@
{
"fill" : {
"linear-gradient" : [
"display-p3:0.00000,0.55106,0.91748,1.00000",
"display-p3:0.00320,0.24546,0.91602,1.00000"
]
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"value" : "automatic"
},
{
"appearance" : "dark",
"value" : {
"linear-gradient" : [
"display-p3:0.00000,0.55106,0.91748,1.00000",
"display-p3:0.00320,0.24546,0.91602,1.00000"
]
}
}
],
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1.5,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.6
},
"translucency" : {
"enabled" : false,
"value" : 0.2
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

@@ -0,0 +1,53 @@
{
"fill" : {
"linear-gradient" : [
"display-p3:0.03297,0.65562,0.91748,1.00000",
"display-p3:0.01787,0.85470,0.91602,1.00000"
]
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"value" : "automatic"
},
{
"appearance" : "dark",
"value" : {
"linear-gradient" : [
"display-p3:0.03297,0.65562,0.91748,1.00000",
"display-p3:0.01787,0.85470,0.91602,1.00000"
]
}
}
],
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1.5,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.6
},
"translucency" : {
"enabled" : false,
"value" : 0.2
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
-1
View File
@@ -2,6 +2,5 @@ module.exports = function (api) {
api.cache(true)
return {
presets: ["babel-preset-expo"],
plugins: ["react-native-reanimated/plugin"],
}
}
+15
View File
@@ -0,0 +1,15 @@
import type { PropsWithChildren } from "react"
import { KeyboardAvoidingView, Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
/** RN modals have their own window; protect their actions from navigation and IME. */
export function AndroidSheet({ children }: PropsWithChildren) {
if (Platform.OS !== "android") return children
return (
<KeyboardAvoidingView behavior="height" style={{ flex: 1 }}>
<SafeAreaView edges={["bottom", "left", "right"]} style={{ flex: 1 }}>
{children}
</SafeAreaView>
</KeyboardAvoidingView>
)
}
@@ -0,0 +1,35 @@
import { useQuery } from "convex/react"
import * as AppIntents from "expo-app-intents"
import { useMemo, useSyncExternalStore } from "react"
import { useMusicCatalogSync } from "@/components/app-intents/catalog-sync"
import { useIntentDispatch } from "@/components/app-intents/dispatch"
import { useNowPlayingCatalog } from "@/components/app-intents/now-playing"
import {
ANONYMOUS_CACHE_SCOPE,
useCacheScope,
} from "@/contexts/persistent-cache"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import { api } from "@otunes/convex/_generated/api"
/**
* Siri and Shortcuts integration: the on-device entity catalog, the current
* song, and intent dispatch. Must render inside `FavoritesProvider`.
*/
export function AppIntentBridge() {
const scope = useCacheScope()
const store = useMemo(
() => getPlaybackStore(scope === ANONYMOUS_CACHE_SCOPE ? null : scope),
[scope]
)
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
const user = useQuery(api.auth.currentUser)
return user && snapshot.hydrated ? <ReadyAppIntentBridge key={scope} /> : null
}
function ReadyAppIntentBridge() {
useMusicCatalogSync()
useNowPlayingCatalog()
useIntentDispatch()
return null
}
@@ -0,0 +1,195 @@
import { useConvex, useQuery } from "convex/react"
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity } from "expo-app-intents"
import { useEffect, useRef } from "react"
import { AppState } from "react-native"
import { useCacheScope } from "@/contexts/persistent-cache"
import {
loadCatalogCursors,
saveCatalogCursors,
type CatalogCursors,
} from "@/lib/app-intent-handled"
import {
publishMusicCatalog,
readMusicCatalog,
trackMusicCatalogSync,
} from "@/lib/app-intents"
import { api } from "@otunes/convex/_generated/api"
import type { FunctionReturnType } from "convex/server"
const LIBRARY_KINDS = ["artist", "album", "song"] as const
type LibraryKind = (typeof LIBRARY_KINDS)[number]
const PAGE_SIZE = 500
type CatalogPage = FunctionReturnType<typeof api.intentCatalog.page>
type Favorites = FunctionReturnType<typeof api.favorites.getUserFavorites>
function favoriteIds(favorites: Favorites, kind: LibraryKind) {
return new Set<string>(
(kind === "song"
? favorites.favoriteSongs
: kind === "album"
? favorites.favoriteAlbums
: favorites.favoriteArtists
).flat()
)
}
/** Stamps `metadata.favorite`, which Siri uses to rank suggestions. */
function withFavorite(entity: AppIntentEntity, favorite: boolean) {
const flag = favorite ? "1" : "0"
return entity.metadata?.favorite === flag
? entity
: { ...entity, metadata: { ...entity.metadata, favorite: flag } }
}
/**
* Keeps the on-device Siri catalog in step with the server. `intentCatalog.head`
* is a live subscription, so the library is fetched only when it changes, and
* then only the records changed since the stored cursor. Favorites are applied
* locally from the existing favorites subscription.
*/
export function useMusicCatalogSync() {
const convex = useConvex()
const scope = useCacheScope()
const head = useQuery(api.intentCatalog.head)
const favorites = useQuery(api.favorites.getUserFavorites)
const playlists = useQuery(api.intentCatalog.playlists)
const latest = useRef({ head, favorites, playlists })
latest.current = { head, favorites, playlists }
const schedule = useRef<() => void>(() => undefined)
useEffect(() => {
if (!AppIntents.isAvailable()) return
let stopped = false
let running = false
let dirty = false
let cursors: CatalogCursors | null = null
// What the disk catalog reflects, to skip no-op republishes.
const appliedFavorites = new Map<LibraryKind, Set<string>>()
let publishedPlaylists: string | null = null
async function fetchChanges(kind: LibraryKind, since: number | undefined) {
const upserts: AppIntentEntity[] = []
let removed: string[] = []
let head = 0
let cursor: string | null = null
do {
const result: CatalogPage = await convex.query(api.intentCatalog.page, {
kind,
since,
paginationOpts: { cursor, numItems: PAGE_SIZE },
})
if (stopped) return null
if (cursor === null) {
if (result.reset) return fetchChanges(kind, undefined)
head = result.head ?? 0
removed = result.removed
}
upserts.push(...result.page)
cursor = result.isDone ? null : result.continueCursor
} while (cursor !== null)
return { upserts, removed, head, full: since === undefined }
}
async function syncKind(
kind: LibraryKind,
serverHead: number,
favorites: Favorites
) {
if (!cursors) return
const since = cursors[kind]
const stale = since === undefined || serverHead > since
const liked = favoriteIds(favorites, kind)
const previousLiked = appliedFavorites.get(kind)
const likesChanged =
!previousLiked ||
previousLiked.size !== liked.size ||
[...liked].some((id) => !previousLiked.has(id))
if (!stale && !likesChanged) return
const changes = stale ? await fetchChanges(kind, since) : null
if (stopped) return
const records = new Map<string, AppIntentEntity>()
if (!changes?.full) {
for (const entity of await readMusicCatalog(kind)) {
records.set(entity.id, entity)
}
}
for (const id of changes?.removed ?? []) records.delete(id)
for (const entity of changes?.upserts ?? [])
records.set(entity.id, entity)
let modified = changes !== null
for (const [id, entity] of records) {
const next = withFavorite(entity, liked.has(id))
if (next !== entity) {
records.set(id, next)
modified = true
}
}
if (stopped) return
if (modified) await publishMusicCatalog(kind, [...records.values()])
appliedFavorites.set(kind, liked)
if (changes && !stopped) {
cursors = { ...cursors, [kind]: changes.head }
await saveCatalogCursors(scope, cursors)
}
}
async function syncOnce() {
const { head, favorites, playlists } = latest.current
cursors ??= await loadCatalogCursors(scope)
if (head && favorites) {
for (const kind of LIBRARY_KINDS) {
if (stopped) return
await syncKind(kind, head[kind], favorites)
}
}
if (playlists && !stopped) {
const json = JSON.stringify(playlists)
if (json !== publishedPlaylists) {
await publishMusicCatalog("playlist", playlists)
publishedPlaylists = json
}
}
}
schedule.current = () => {
if (stopped) return
if (running) {
dirty = true
return
}
running = true
const sync = (async () => {
do {
dirty = false
await syncOnce()
} while (dirty && !stopped)
})()
.catch((error) =>
console.warn("Could not publish music catalog.", error)
)
.finally(() => {
running = false
})
trackMusicCatalogSync(sync)
}
schedule.current()
// Retries a failed sync; a no-op without server queries when current.
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") schedule.current()
})
return () => {
stopped = true
schedule.current = () => undefined
subscription.remove()
}
}, [convex, scope])
useEffect(() => {
schedule.current()
}, [head, favorites, playlists])
}
@@ -0,0 +1,633 @@
import { useConvex } from "convex/react"
import * as AppIntents from "expo-app-intents"
import type { AppIntentInvocation } from "expo-app-intents"
import { useMemo, useRef } from "react"
import { useFavorites, type FavoriteKind } from "@/contexts/favorites"
import {
ANONYMOUS_CACHE_SCOPE,
useCacheScope,
} from "@/contexts/persistent-cache"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import {
FAVORITES_PLAYLIST_ID,
loadHandledIntentIds,
rememberHandledIntentId,
} from "@/lib/app-intent-handled"
import { completeMusicInvocation } from "@/lib/app-intents"
import { useAppNavigation } from "@/lib/app-navigation"
import { showError } from "@/lib/toast"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { publishNowPlaying } from "./now-playing"
const warmedAudioIds = new Set<string>()
class IntentRejected extends Error {}
const KNOWN_INTENTS = new Set([
"playMusic",
"warmupAudio",
"addToPlaylist",
"addToUpNext",
"clearUpNext",
"createPlaylist",
"createStation",
"updateAffinity",
"transport",
"openMusic",
])
type MusicSource = {
kind: string
id: string
}
function readString(value: unknown) {
return typeof value === "string" && value.trim() ? value : null
}
function readSources(value: unknown): MusicSource[] {
if (!Array.isArray(value)) {
return []
}
return value.flatMap((entry) => {
if (!entry || typeof entry !== "object") {
return []
}
const source = entry as { kind?: unknown; id?: unknown }
if (typeof source.kind !== "string" || typeof source.id !== "string") {
return []
}
if (!source.kind || !source.id) {
return []
}
return [{ kind: source.kind, id: source.id }]
})
}
function isFavoriteKind(kind: string): kind is FavoriteKind {
return kind === "song" || kind === "album" || kind === "artist"
}
function shuffleChoice(value: unknown, fallback: boolean) {
if (value === "songs") return true
if (value === "off") return false
if (value == null) return fallback
throw new IntentRejected("Shuffle must be Off or Songs.")
}
function repeatChoice(value: unknown): RepeatMode | null {
if (value == null) return null
if (value === "none") return "none"
if (value === "one") return "once"
if (value === "all") return "always"
throw new IntentRejected("Repeat must be None, One, or All.")
}
function ensureActive(invocation: AppIntentInvocation) {
const deadline = invocation.params.deadline
if (typeof deadline === "number" && Date.now() >= deadline) {
throw new IntentRejected("This request expired. Please try again.")
}
}
function isTransient(error: unknown) {
const message = (
error instanceof Error ? error.message : String(error)
).toLowerCase()
return (
message.includes("not authenticated") ||
message.includes("network") ||
message.includes("fetch") ||
message.includes("connection") ||
message.includes("timed out") ||
message.includes("timeout")
)
}
/** Runs Siri and Shortcuts invocations queued by the native intents. */
export function useIntentDispatch() {
const convex = useConvex()
const cacheScope = useCacheScope()
const playback = { ...usePlaybackQueue(), ...usePlaybackActions() }
const favorites = useFavorites()
const navigation = useAppNavigation()
const store = useMemo(
() =>
getPlaybackStore(
cacheScope === ANONYMOUS_CACHE_SCOPE ? null : cacheScope
),
[cacheScope]
)
const handledIds = useRef<Set<string> | null>(null)
const playbackRef = useRef(playback)
playbackRef.current = playback
/** Intent ids arrive as strings; the server validates them. */
function setFavorite(kind: FavoriteKind, id: string, favorite: boolean) {
return kind === "song"
? favorites.setFavorite(kind, id as Id<"songs">, favorite)
: kind === "album"
? favorites.setFavorite(kind, id as Id<"albums">, favorite)
: favorites.setFavorite(kind, id as Id<"artists">, favorite)
}
AppIntents.useAppIntents(async (pendingIntents) => {
if (!handledIds.current) {
handledIds.current = await loadHandledIntentIds()
}
const handled = handledIds.current
for (const invocation of pendingIntents) {
if (handled.has(invocation.id)) {
const token = readString(invocation.params.completionToken)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
if (!KNOWN_INTENTS.has(invocation.name)) {
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
const token = readString(invocation.params.completionToken)
try {
ensureActive(invocation)
await performInvocation(invocation)
if (
["playMusic", "warmupAudio", "transport", "createStation"].includes(
invocation.name
)
) {
await publishNowPlaying(
store.getState().queue[0] ?? null,
playbackRef.current.currentSong
)
}
await rememberHandledIntentId(handled, invocation.id)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (error) {
if (token) {
await completeMusicInvocation(
token,
error instanceof Error ? error.message : "oTunes couldn't do that."
)
}
if (token || error instanceof IntentRejected || !isTransient(error)) {
const message =
error instanceof Error ? error.message : "oTunes couldn't do that."
if (!(error instanceof IntentRejected) || message) {
showError(message)
}
try {
await rememberHandledIntentId(handled, invocation.id)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (removeError) {
console.warn(
"App Intent remains pending",
invocation.id,
removeError
)
}
continue
}
console.warn("App Intent remains pending", invocation.id, error)
}
}
async function songIdsFor(kind: string, id: string) {
if (kind === "song") {
return [id as Id<"songs">]
}
if (kind === "album") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{
albumId: id as Id<"albums">,
}
)
}
if (kind === "artist") {
const chunks = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: id as Id<"artists"> }
)
return chunks.flat()
}
if (kind === "playlist") {
if (id === FAVORITES_PLAYLIST_ID) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
return favorites.favoriteSongs.flat()
}
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{ playlistId: id as Id<"playlists"> }
)
}
throw new IntentRejected("Choose a song, album, artist, or playlist.")
}
async function uniqueSongIds(sources: MusicSource[]) {
const ids: Id<"songs">[] = []
for (const source of sources) {
ids.push(...(await songIdsFor(source.kind, source.id)))
}
return [...new Set(ids)]
}
async function performInvocation(invocation: AppIntentInvocation) {
const actions = playbackRef.current
switch (invocation.name) {
case "openMusic": {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!id || !kind) throw new IntentRejected("Choose music to open.")
if (kind === "song") {
const song = await convex.query(api.library.getSong, {
id: id as Id<"songs">,
})
if (!song)
throw new IntentRejected("This song is no longer available.")
navigation.push(`/album/${song.album}`)
} else if (kind === "playlist" && id === FAVORITES_PLAYLIST_ID) {
navigation.push("/playlist/favorites")
} else if (["album", "artist", "playlist"].includes(kind)) {
navigation.push(`/${kind}/${id}`)
} else throw new IntentRejected("Unknown music type.")
return
}
case "playMusic":
await playMusic(invocation)
if (!["next", "tail"].includes(String(invocation.params.queue))) {
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
}
return
case "warmupAudio":
await warmup(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(false)
warmedAudioIds.add(invocation.id)
return
case "addToPlaylist":
await addToPlaylist(invocation)
return
case "addToUpNext":
await addToUpNext(invocation)
return
case "clearUpNext":
ensureActive(invocation)
await actions.clearUpNext()
return
case "createPlaylist":
await createPlaylist(invocation)
return
case "createStation":
await createStation(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
return
case "updateAffinity":
await updateAffinity(invocation)
return
case "transport":
await transport(invocation)
if (store.getState().queue.length > 0) {
const command = invocation.params.command
await playbackRef.current.waitForPlaybackReady(
command === "resume"
? true
: command === "pause"
? false
: undefined
)
}
return
default:
return
}
}
async function playMusic(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const queue = readString(invocation.params.queue) ?? "now"
const warmupId = readString(invocation.params.warmupId)
const repeat = repeatChoice(invocation.params.repeat)
if (repeat) {
ensureActive(invocation)
await actions.setRepeatMode(repeat)
}
if (queue === "next" || queue === "tail") {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
if (queue === "next") {
ensureActive(invocation)
await actions.addToQueueNext(ids)
} else {
ensureActive(invocation)
await actions.addToQueueLast(ids)
}
return
}
if (warmupId && warmedAudioIds.has(warmupId)) {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const kind = readString(invocation.params.kind) ?? "resume"
if (kind === "resume") {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
if (actions.queueSongIds.length === 0) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
const favoriteSongs = favorites.favoriteSongs.flat()
if (favoriteSongs.length === 0) {
throw new IntentRejected(
"Nothing is queued, and your favorites are empty."
)
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(favoriteSongs)
} else {
ensureActive(invocation)
await actions.playInOrder(favoriteSongs)
}
return
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const id = readString(invocation.params.id)
if (!id) {
throw new IntentRejected("Choose music to play.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await actions.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
true
)
return
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to play.")
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(ids)
} else {
ensureActive(invocation)
await actions.playInOrder(ids)
}
}
async function warmup(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to get ready.")
}
const shuffled = shuffleChoice(invocation.params.shuffle, false)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await playbackRef.current.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
false
)
} else {
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to get ready.")
}
ensureActive(invocation)
await playbackRef.current.prepareQueue(ids, shuffled)
}
}
async function addToPlaylist(invocation: AppIntentInvocation) {
const playlistId = readString(invocation.params.playlistId)
const sources = readSources(invocation.params.sources)
if (!playlistId || sources.length === 0) {
throw new IntentRejected("Choose music and a playlist.")
}
const songIds = await uniqueSongIds(sources)
if (songIds.length === 0) {
throw new IntentRejected("Those items have no songs to add.")
}
if (playlistId === FAVORITES_PLAYLIST_ID) {
for (const source of sources) {
if (isFavoriteKind(source.kind)) {
ensureActive(invocation)
await setFavorite(source.kind, source.id, true)
} else if (source.kind === "playlist") {
const ids = await songIdsFor(source.kind, source.id)
ensureActive(invocation)
await favorites.addFavoriteSongs(ids)
} else {
throw new IntentRejected(
"Choose a song, album, artist, or playlist."
)
}
}
return
}
ensureActive(invocation)
await convex.mutation(api.playlists.addSongsToPlaylist, {
playlistId: playlistId as Id<"playlists">,
songIds,
})
}
async function addToUpNext(invocation: AppIntentInvocation) {
const sources = readSources(invocation.params.sources)
if (sources.length === 0) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const ids = await uniqueSongIds(sources)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
const position =
readString(invocation.params.position) === "last" ? "last" : "next"
if (position === "last") {
ensureActive(invocation)
await playbackRef.current.addToQueueLast(ids)
} else {
ensureActive(invocation)
await playbackRef.current.addToQueueNext(ids)
}
}
async function createPlaylist(invocation: AppIntentInvocation) {
const name = readString(invocation.params.name)
if (!name) {
throw new IntentRejected("A playlist needs a name.")
}
const songIds = await uniqueSongIds(
readSources(invocation.params.sources)
)
ensureActive(invocation)
await convex.mutation(api.playlists.createPlaylist, {
name,
songIds,
invocationId: invocation.id,
})
}
async function createStation(invocation: AppIntentInvocation) {
const artistId = readString(invocation.params.artistId)
if (!artistId) {
throw new IntentRejected("Nothing is playing in oTunes.")
}
const ids = await songIdsFor("artist", artistId)
if (ids.length === 0)
throw new IntentRejected("This artist has no songs to play.")
ensureActive(invocation)
await playbackRef.current.playShuffled(ids)
}
async function updateAffinity(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
const state = readString(invocation.params.state)
if (!kind || !id || (state !== "like" && state !== "unset")) {
throw new IntentRejected(
"oTunes can love or unlike a song, album, or artist."
)
}
if (!isFavoriteKind(kind)) {
throw new IntentRejected("oTunes can love songs, albums, and artists.")
}
ensureActive(invocation)
await setFavorite(kind, id, state === "like")
}
async function transport(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const command = readString(invocation.params.command)
if (command === "pause") {
ensureActive(invocation)
actions.setIsPlaying(false)
return
}
if (command === "resume") {
if (actions.queueSongIds.length === 0) {
throw new IntentRejected("Nothing is queued in oTunes.")
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
if (command === "next") {
ensureActive(invocation)
await actions.skipNext()
return
}
if (command === "previous") {
ensureActive(invocation)
await actions.skipPrevious()
return
}
throw new IntentRejected("oTunes doesn't know that playback control.")
}
})
}
@@ -0,0 +1,59 @@
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity } from "expo-app-intents"
import { useEffect } from "react"
import { usePlaybackQueue } from "@/contexts/playback"
import { publishMusicCatalog } from "@/lib/app-intents"
type CurrentSong = NonNullable<
ReturnType<typeof usePlaybackQueue>["currentSong"]
>
function nowPlayingEntity(song: CurrentSong): AppIntentEntity {
const artistName = song.artist.name
return {
id: song.id,
title: song.title,
subtitle: artistName,
synonyms: artistName ? [artistName] : undefined,
metadata: {
artistName,
artistId: song.artist.id,
albumTitle: song.album.title,
albumId: song.album.id,
duration: String(song.durationSeconds),
genres: "",
year: "",
track: "",
disk: "",
favorite: "0",
},
}
}
/**
* Publishes the "nowPlaying" catalog Siri reads for the current song. With an
* id but no matching `song` it leaves the catalog alone until the song loads.
*/
export async function publishNowPlaying(
queueHeadId: string | null,
song: CurrentSong | null
) {
if (!queueHeadId) await publishMusicCatalog("nowPlaying", [])
else if (song?.id === queueHeadId)
await publishMusicCatalog("nowPlaying", [nowPlayingEntity(song)])
}
/** Keeps the "nowPlaying" catalog in step with the playback queue. */
export function useNowPlayingCatalog() {
const playback = usePlaybackQueue()
const queueHeadId = playback.queueSongIds[0] ?? null
const song = playback.currentSong
useEffect(() => {
if (!AppIntents.isAvailable()) return
void publishNowPlaying(queueHeadId, song).catch((error) => {
console.warn("Could not publish the current song.", error)
})
}, [queueHeadId, song])
}
@@ -0,0 +1,102 @@
import { StyleSheet, Text, View } from "react-native"
import Svg, { G, Path } from "react-native-svg"
import {
DOLBY_PATHS,
DOLBY_VIEW_BOX,
DOLBY_WIDTH,
LOSSLESS_FALL,
LOSSLESS_FALL_GAP,
LOSSLESS_PEAKS,
LOSSLESS_STROKES,
LOSSLESS_THIN_WIDTH,
LOSSLESS_VIEW_BOX,
LOSSLESS_WIDTH,
MARK_HEIGHT,
} from "@otunes/convex/client/audio-format-marks"
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
const LABEL_SIZE = 13
function DolbyMark({ color }: { color: string }) {
return (
<Svg width={DOLBY_WIDTH} height={MARK_HEIGHT} viewBox={DOLBY_VIEW_BOX}>
{DOLBY_PATHS.map((d) => (
<Path key={d} d={d} fill={color} />
))}
</Svg>
)
}
/**
* Three overlapping waves. Each thick downstroke is outlined in the
* background color so it reads as passing over the strokes behind it.
*/
function LosslessMark({
color,
backgroundColor,
}: {
color: string
backgroundColor: string
}) {
return (
<Svg
width={LOSSLESS_WIDTH}
height={MARK_HEIGHT}
viewBox={LOSSLESS_VIEW_BOX}
>
{LOSSLESS_STROKES.map(([peak, d], index) => (
<Path
key={index}
d={d}
x={peak}
stroke={color}
strokeWidth={LOSSLESS_THIN_WIDTH}
strokeLinecap="round"
fill="none"
/>
))}
{LOSSLESS_PEAKS.map((peak) => (
<G key={peak} x={peak}>
<Path d={LOSSLESS_FALL_GAP} fill={backgroundColor} />
<Path d={LOSSLESS_FALL} fill={color} />
</G>
))}
</Svg>
)
}
/** The Dolby Atmos or Lossless label shown under the progress bar. */
export function AudioFormatBadge({
format,
color,
backgroundColor,
}: {
format: PlaybackFormat
color: string
backgroundColor: string
}) {
const label = format === "atmos" ? "Dolby Atmos" : "Lossless"
return (
<View style={styles.badge} accessibilityLabel={label}>
{format === "atmos" ? (
<DolbyMark color={color} />
) : (
<LosslessMark color={color} backgroundColor={backgroundColor} />
)}
<Text style={[styles.label, { color }]}>{label}</Text>
</View>
)
}
const styles = StyleSheet.create({
badge: {
flexDirection: "row",
alignItems: "center",
gap: 3,
},
label: {
fontSize: LABEL_SIZE,
fontWeight: "500",
},
})
@@ -0,0 +1,71 @@
import {
requireNativeView,
requireOptionalNativeModule,
type NativeModule,
} from "expo"
import {
Platform,
Pressable,
type StyleProp,
type ViewProps,
type ViewStyle,
} from "react-native"
import { PlayerSymbol } from "@/components/player-symbol"
import { showError } from "@/lib/toast"
type AudioOutputModule = NativeModule & {
showPicker: () => Promise<boolean>
}
const audioOutput =
requireOptionalNativeModule<AudioOutputModule>("AudioOutput")
const AirPlayPicker =
Platform.OS === "ios" && audioOutput
? requireNativeView<ViewProps & { tint: string }>("AudioOutput")
: null
export function AudioOutputButton({
color,
style,
}: {
color: string
style: StyleProp<ViewStyle>
}) {
if (AirPlayPicker) {
return <AirPlayPicker tint={color} style={style} />
}
const available =
Platform.OS === "android" && Platform.Version >= 33 && audioOutput !== null
async function showPicker() {
try {
if (!(await audioOutput?.showPicker())) {
showError("Audio output selection is unavailable on this device.")
}
} catch {
showError("Audio output selection could not be opened.")
}
}
return (
<Pressable
onPress={showPicker}
disabled={!available}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={Platform.OS === "ios" ? "AirPlay" : "Audio output"}
accessibilityState={{ disabled: !available }}
style={[style, !available && { opacity: 0.35 }]}
>
<PlayerSymbol
name="airplay.audio"
fallback={{ material: "cast" }}
size={27}
weight="semibold"
color={color}
/>
</Pressable>
)
}
+45 -39
View File
@@ -1,21 +1,17 @@
import { useAuthActions, useConvexAuth } from "@convex-dev/auth/react"
import { Link, useRouter } from "expo-router"
import { useAuthActions } from "@convex-dev/auth/react"
import { Link } from "expo-router"
import { useQuery } from "convex/react"
import { useEffect, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { useState } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { KeyboardForm } from "@/components/keyboard-form"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { api } from "@otunes/convex/_generated/api"
import { spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
type AuthFlow = "signIn" | "signUp"
@@ -50,10 +46,8 @@ const copy: Record<
export function AuthForm({ flow }: { flow: AuthFlow }) {
const { signIn } = useAuthActions()
const auth = useConvexAuth()
const router = useRouter()
const colors = useThemeColors()
const { config } = useServerConfig()
const { config, clearServer } = useServerConfig()
const appSettings = useQuery(api.users.getAppSettings)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
@@ -61,12 +55,6 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (auth.isAuthenticated) {
router.replace("/(app)/(tabs)/home")
}
}, [auth.isAuthenticated, router])
const text = copy[flow]
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
const signupsDisabled = flow === "signUp" && accountCreationDisabled
@@ -99,14 +87,15 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<KeyboardForm style={styles.container}>
<Card>
<View style={styles.header}>
<Text style={[styles.title, { color: colors.foreground }]}>{text.title}</Text>
<Text style={[styles.description, { color: colors.mutedForeground }]}>
<Text style={[styles.title, { color: colors.foreground }]}>
{text.title}
</Text>
<Text
style={[styles.description, { color: colors.mutedForeground }]}
>
{text.description}
</Text>
{config ? (
@@ -118,8 +107,8 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
{signupsDisabled ? (
<Text style={{ color: colors.mutedForeground }}>
New account registration is currently disabled. Contact an administrator if you need
access.
New account registration is currently disabled. Contact an
administrator if you need access.
</Text>
) : (
<View style={styles.form}>
@@ -144,16 +133,28 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
onChangeText={setPassword}
placeholder="Password"
secureTextEntry
autoComplete={flow === "signIn" ? "current-password" : "new-password"}
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
/>
{error ? (
<Text style={{ color: colors.destructive }}>{error}</Text>
) : null}
<Button
title={text.submit}
loading={submitting}
onPress={() => void handleSubmit()}
/>
{error ? <Text style={{ color: colors.destructive }}>{error}</Text> : null}
<Button title={text.submit} loading={submitting} onPress={() => void handleSubmit()} />
{!hideSignUpLink ? (
<View style={styles.switchRow}>
<Text style={{ color: colors.mutedForeground }}>{text.switchPrompt} </Text>
<Text style={{ color: colors.mutedForeground }}>
{text.switchPrompt}{" "}
</Text>
<Link href={text.switchHref} asChild>
<Pressable>
<Text style={{ color: colors.foreground, fontWeight: "600" }}>
<Text
style={{ color: colors.foreground, fontWeight: "600" }}
>
{text.switchLabel}
</Text>
</Pressable>
@@ -164,12 +165,17 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
)}
</Card>
<Link href="/server" asChild>
<Pressable style={styles.changeServer}>
<Text style={{ color: colors.mutedForeground }}>Change server</Text>
</Pressable>
</Link>
</KeyboardAvoidingView>
<Pressable
style={styles.changeServer}
onPress={() =>
void clearServer().catch(() =>
showError("Could not clear the server address.")
)
}
>
<Text style={{ color: colors.mutedForeground }}>Change server</Text>
</Pressable>
</KeyboardForm>
</SafeAreaView>
)
}
@@ -1,24 +0,0 @@
import { useConvexAuth } from "@convex-dev/auth/react"
import { Redirect } from "expo-router"
import { LoadingView } from "@/components/ui/primitives"
export function AuthenticatedRedirect() {
const auth = useConvexAuth()
if (!auth) {
return <LoadingView />
}
const { isLoading, isAuthenticated } = auth
if (isLoading) {
return <LoadingView />
}
if (!isAuthenticated) {
return <Redirect href="/signin" />
}
return <Redirect href="/(app)/(tabs)/home" />
}
@@ -0,0 +1,172 @@
import { Ionicons } from "@expo/vector-icons"
import {
Alert,
Pressable,
StyleSheet,
Text,
View,
type StyleProp,
type ViewStyle,
} from "react-native"
import Svg, { Circle, Rect } from "react-native-svg"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import {
useDownloads,
useDownloadsVersion,
useIsCollectionDownloaded,
type DownloadTarget,
} from "@/contexts/downloads"
import type { CollectionRef } from "@otunes/convex/client/download-queue"
import { DOWNLOAD_QUALITY_LABELS } from "@otunes/convex/download-quality"
const SIZE = 22
const RADIUS = 9
const RING_LENGTH = 2 * Math.PI * RADIUS
/** Static ring that fills as songs finish; the square means "tap to stop". */
function ProgressRing({
fraction,
color,
}: {
fraction: number
color: string
}) {
return (
<Svg width={SIZE} height={SIZE} viewBox="0 0 22 22">
<Circle
cx={11}
cy={11}
r={RADIUS}
fill="none"
stroke={color}
strokeOpacity={0.3}
strokeWidth={2}
/>
<Circle
cx={11}
cy={11}
r={RADIUS}
fill="none"
stroke={color}
strokeWidth={2}
strokeDasharray={RING_LENGTH}
strokeDashoffset={RING_LENGTH * (1 - fraction)}
transform="rotate(-90 11 11)"
/>
<Rect x={8} y={8} width={6} height={6} fill={color} />
</Svg>
)
}
export type CollectionDownloadTarget = Exclude<
DownloadTarget,
{ kind: "songs" }
>
/** Download, progress, and downloaded states for an album or playlist hero, beside Play. */
export function CollectionDownloadButton({
target,
color,
style,
}: {
target: CollectionDownloadTarget
color: string
style?: StyleProp<ViewStyle>
}) {
const { queue, requestDownload, removeDownload } = useDownloads()
useDownloadsVersion()
const collection = queue?.getCollection(target)
const status = queue?.status(target.songIds)
const inProgress = collection !== undefined && (status?.queued ?? 0) > 0
const done = collection !== undefined && !inProgress
function handlePress() {
if (inProgress) {
void removeDownload(target)
} else if (done) {
Alert.alert("Remove download?", undefined, [
{ text: "Cancel", style: "cancel" },
{
text: "Remove",
style: "destructive",
onPress: () => void removeDownload(target),
},
])
} else {
void requestDownload(target)
}
}
return (
<Pressable
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={
inProgress
? "Stop downloading"
: done
? `Remove download of ${target.title}`
: `Download ${target.title}`
}
disabled={target.songIds.length === 0}
onPress={handlePress}
style={style}
>
{inProgress && status ? (
<ProgressRing
fraction={status.downloaded / status.total}
color={color}
/>
) : (
<Ionicons
name={done ? "checkmark" : "arrow-down"}
size={24}
color={color}
/>
)}
</Pressable>
)
}
/** The quality an album or playlist was downloaded in, once downloaded. */
export function DownloadedQuality({
collection,
color,
backgroundColor,
}: {
collection: CollectionRef
color: string
backgroundColor: string
}) {
const { queue } = useDownloads()
const downloaded = useIsCollectionDownloaded(collection)
const quality = downloaded
? queue?.getCollection(collection)?.quality
: undefined
if (!quality) return null
return (
<View
style={styles.quality}
accessible
accessibilityLabel={`Downloaded in ${DOWNLOAD_QUALITY_LABELS[quality]}`}
>
<Ionicons name="arrow-down-circle" size={14} color={color} />
{quality === "lossless" || quality === "atmos" ? (
<AudioFormatBadge
format={quality}
color={color}
backgroundColor={backgroundColor}
/>
) : (
<Text style={{ color, fontSize: 13 }}>
{DOWNLOAD_QUALITY_LABELS[quality]}
</Text>
)}
</View>
)
}
const styles = StyleSheet.create({
quality: { flexDirection: "row", alignItems: "center", gap: 4 },
})
@@ -0,0 +1,66 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import type { ReactNode } from "react"
import { Platform, StyleSheet, useWindowDimensions, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
export function useCollectionHeroLayout() {
const tabletLayout = useTabletLayout()
const { width, height } = useWindowDimensions()
const insets = useSafeAreaInsets()
const paneWidth = width - insets.left - insets.right
const isTablet =
Platform.OS === "ios" ? tabletLayout : Math.min(width, height) >= 600
const landscape = isTablet && width > height && paneWidth >= 640
return {
landscape,
coverSize: landscape
? Math.min(300, Math.max(180, (paneWidth - 100) * 0.4))
: undefined,
}
}
/** Tablet artwork and controls share a bottom edge, with metadata above the controls. */
export function CollectionHero({
artwork,
actions,
children,
}: {
artwork: ReactNode
actions: ReactNode
children: ReactNode
}) {
const { landscape } = useCollectionHeroLayout()
return (
<View style={[styles.hero, landscape && styles.landscape]}>
{artwork}
<View style={[styles.details, landscape && styles.landscapeDetails]}>
<View style={[styles.metadata, landscape && styles.landscapeMetadata]}>
{children}
</View>
{actions}
</View>
</View>
)
}
const styles = StyleSheet.create({
hero: { padding: 16, gap: 8, alignItems: "center" },
landscape: {
flexDirection: "row",
alignItems: "stretch",
paddingHorizontal: 32,
paddingTop: 34,
paddingBottom: 40,
gap: 34,
},
details: { alignItems: "center", gap: 8, alignSelf: "stretch" },
landscapeDetails: {
flex: 1,
minWidth: 0,
paddingTop: 64,
justifyContent: "space-between",
alignItems: "flex-start",
},
metadata: { gap: 8, alignSelf: "stretch", alignItems: "center" },
landscapeMetadata: { alignItems: "flex-start", gap: 4 },
})
@@ -0,0 +1,46 @@
import { memo } from "react"
import { StyleSheet, Text, View } from "react-native"
import { useThemeColors } from "@/lib/theme"
/** Horizontal inset for rows and dividers in album and playlist track lists. */
export const collectionInset = 20
/** Separates a collection's header from its track list. */
export function CollectionDivider({ color }: { color?: string }) {
const colors = useThemeColors()
return (
<View
style={[styles.divider, { backgroundColor: color ?? colors.border }]}
/>
)
}
export const DiscHeader = memo(function DiscHeader({
label,
color,
}: {
label: string
color?: string
}) {
const colors = useThemeColors()
return (
<Text style={[styles.discHeader, { color: color ?? colors.foreground }]}>
{label}
</Text>
)
})
const styles = StyleSheet.create({
divider: {
height: StyleSheet.hairlineWidth,
marginHorizontal: collectionInset,
},
discHeader: {
fontSize: 17,
fontWeight: "700",
paddingHorizontal: collectionInset,
paddingTop: 24,
paddingBottom: 8,
},
})
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff. Show more