Compare commits
212
Commits
No files matched your search
+17
-10
@@ -3,8 +3,12 @@
|
||||
# Keeps Docker builds fast, lean, and free of development files.
|
||||
############################################################
|
||||
|
||||
# Dependencies (installed inside Docker, never copied)
|
||||
node_modules/
|
||||
# Dependencies (installed inside Docker, never copied).
|
||||
# Use **/ so nested workspace installs (apps/web/node_modules, etc.) are
|
||||
# excluded — a bare "node_modules/" only matches the repo root and would
|
||||
# let host symlinks overwrite the image install during COPY.
|
||||
**/node_modules
|
||||
**/node_modules/**
|
||||
.pnpm-store/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
@@ -13,7 +17,8 @@ pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Next.js build outputs (always generated during `next build`)
|
||||
.next/
|
||||
**/.next
|
||||
**/.next/**
|
||||
out/
|
||||
dist/
|
||||
build/
|
||||
@@ -49,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*
|
||||
@@ -131,4 +135,7 @@ AGENTS.md
|
||||
*.claude*
|
||||
*.gemini*
|
||||
*.openai*
|
||||
*.anthropic*
|
||||
*.anthropic*
|
||||
|
||||
# Expo mobile app (not needed in web Docker image)
|
||||
apps/mobile/
|
||||
+15
-12
@@ -1,19 +1,20 @@
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
node_modules/
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
apps/web/.next/
|
||||
apps/web/out/
|
||||
|
||||
# expo
|
||||
apps/mobile/.expo/
|
||||
apps/mobile/dist/
|
||||
apps/mobile/web-build/
|
||||
apps/mobile/expo-env.d.ts
|
||||
apps/mobile/ios/
|
||||
apps/mobile/android/
|
||||
|
||||
# production
|
||||
/build
|
||||
@@ -33,9 +34,11 @@ pnpm-debug.log*
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
apps/web/next-env.d.ts
|
||||
|
||||
/.idea
|
||||
|
||||
/.convex
|
||||
/.cursor
|
||||
/.cursor
|
||||
/database
|
||||
docker-compose.yml
|
||||
+1
-1
@@ -6,6 +6,6 @@
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 80,
|
||||
"plugins": ["prettier-plugin-tailwindcss"],
|
||||
"tailwindStylesheet": "app/globals.css",
|
||||
"tailwindStylesheet": "apps/web/app/globals.css",
|
||||
"tailwindFunctions": ["cn", "cva"]
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `apps/web/node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
|
||||
|
||||
The Next.js web app lives in `apps/web`.
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
+182
-71
@@ -1,3 +1,5 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ============================================
|
||||
# Stage 1: Dependencies Installation Stage
|
||||
# ============================================
|
||||
@@ -7,108 +9,217 @@
|
||||
# To ensure security and compatibility, regularly update the NODE_VERSION ARG to the latest LTS version.
|
||||
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/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.
|
||||
ARG FFMPEG_VERSION=7.1.5
|
||||
ARG FFMPEG_SHA256=de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f
|
||||
|
||||
FROM node:${NODE_VERSION} AS node
|
||||
|
||||
FROM node:${NODE_VERSION} AS dependencies
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package-related files first to leverage Docker's caching mechanism
|
||||
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./
|
||||
# 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 ./
|
||||
# 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/
|
||||
|
||||
# Install project dependencies with frozen lockfile for reproducible builds
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
--mount=type=cache,target=/usr/local/share/.cache/yarn \
|
||||
--mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
if [ -f package-lock.json ]; then \
|
||||
npm ci --no-audit --no-fund; \
|
||||
elif [ -f yarn.lock ]; then \
|
||||
corepack enable yarn && yarn install --frozen-lockfile --production=false; \
|
||||
elif [ -f pnpm-lock.yaml ]; then \
|
||||
corepack enable pnpm && pnpm install --frozen-lockfile; \
|
||||
else \
|
||||
echo "No lockfile found." && exit 1; \
|
||||
fi
|
||||
# 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' \
|
||||
'supportedArchitectures.os=current' \
|
||||
'supportedArchitectures.cpu=current' \
|
||||
'supportedArchitectures.libc=current' \
|
||||
>> .npmrc
|
||||
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
corepack enable pnpm && \
|
||||
pnpm install --frozen-lockfile --filter @otunes/web...
|
||||
|
||||
# ============================================
|
||||
# Stage 2: Build Next.js application in standalone mode
|
||||
# ============================================
|
||||
|
||||
FROM node:${NODE_VERSION} AS builder
|
||||
# Reuse the installed workspace. Copying node_modules into a new layer retars
|
||||
# hundreds of thousands of files on every source change.
|
||||
FROM dependencies AS builder
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy project dependencies from dependencies stage
|
||||
COPY --from=dependencies /app/node_modules ./node_modules
|
||||
COPY apps/web /tmp/src/apps/web
|
||||
COPY packages/convex /tmp/src/packages/convex
|
||||
|
||||
# Copy application source code
|
||||
COPY . .
|
||||
# Merge sources onto the install. cp does not remove the existing
|
||||
# node_modules tree, and the build context already dockerignores it.
|
||||
RUN cp -a /tmp/src/apps/web/. ./apps/web/ \
|
||||
&& cp -a /tmp/src/packages/convex/. ./packages/convex/ \
|
||||
&& rm -rf /tmp/src
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Next.js collects completely anonymous telemetry data about general usage.
|
||||
# Learn more here: https://nextjs.org/telemetry
|
||||
# Uncomment the following line in case you want to disable telemetry during the build.
|
||||
# ENV NEXT_TELEMETRY_DISABLED=1
|
||||
WORKDIR /app/apps/web
|
||||
|
||||
# Build Next.js application
|
||||
# If you want to speed up Docker rebuilds, you can cache the build artifacts
|
||||
# by adding: --mount=type=cache,target=/app/.next/cache
|
||||
# This caches the .next/cache directory across builds, but it also prevents
|
||||
# .next/cache/fetch-cache from being included in the final image, meaning
|
||||
# cached fetch responses from the build won't be available at runtime.
|
||||
RUN if [ -f package-lock.json ]; then \
|
||||
npm run build; \
|
||||
elif [ -f yarn.lock ]; then \
|
||||
corepack enable yarn && yarn build; \
|
||||
elif [ -f pnpm-lock.yaml ]; then \
|
||||
corepack enable pnpm && pnpm build; \
|
||||
else \
|
||||
echo "No lockfile found." && exit 1; \
|
||||
fi
|
||||
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
|
||||
corepack enable pnpm && pnpm build
|
||||
|
||||
# ============================================
|
||||
# Stage 3: Run Next.js application
|
||||
# Stage 3: Convex functions, deployed to the bundled backend on boot
|
||||
# ============================================
|
||||
|
||||
FROM node:${NODE_VERSION} AS runner
|
||||
FROM node:${NODE_VERSION} AS convex-functions
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Set production environment variables
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
COPY package.json pnpm-lock.yaml .npmrc ./
|
||||
COPY patches ./patches
|
||||
COPY packages/convex/package.json ./packages/convex/
|
||||
|
||||
# Next.js collects completely anonymous telemetry data about general usage.
|
||||
# Learn more here: https://nextjs.org/telemetry
|
||||
# Uncomment the following line in case you want to disable telemetry during the run time.
|
||||
# ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN printf '%s\n' \
|
||||
'packages:' \
|
||||
' - "packages/convex"' \
|
||||
> pnpm-workspace.yaml \
|
||||
&& printf '\n%s\n' \
|
||||
'supportedArchitectures.os=current' \
|
||||
'supportedArchitectures.cpu=current' \
|
||||
'supportedArchitectures.libc=current' \
|
||||
>> .npmrc
|
||||
|
||||
RUN mkdir /data
|
||||
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||
corepack enable pnpm && \
|
||||
pnpm install --frozen-lockfile --prod --filter @otunes/convex...
|
||||
|
||||
# Copy production assets
|
||||
COPY --from=builder --chown=node:node /app/public ./public
|
||||
COPY packages/convex ./packages/convex
|
||||
|
||||
# Set the correct permission for prerender cache
|
||||
RUN mkdir .next
|
||||
RUN chown node:node .next
|
||||
# Source maps and the Convex package's TypeScript sources are not used at runtime.
|
||||
RUN find /app -type f -name '*.map' -delete \
|
||||
&& rm -rf /app/node_modules/.pnpm/convex@*/node_modules/convex/src
|
||||
|
||||
# Automatically leverage output traces to reduce image size
|
||||
# https://nextjs.org/docs/advanced-features/output-file-tracing
|
||||
COPY --from=builder --chown=node:node /app/.next/standalone ./
|
||||
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
|
||||
# ============================================
|
||||
# Stage 4: Audio-only ffmpeg
|
||||
# ============================================
|
||||
|
||||
# If you want to persist the fetch cache generated during the build so that
|
||||
# cached responses are available immediately on startup, uncomment this line:
|
||||
# COPY --from=builder --chown=node:node /app/.next/cache ./.next/cache
|
||||
FROM ubuntu:24.04 AS ffmpeg
|
||||
|
||||
# Switch to non-root user for security best practices
|
||||
USER node
|
||||
ARG FFMPEG_VERSION
|
||||
ARG FFMPEG_SHA256
|
||||
|
||||
# Expose port 3000 to allow HTTP traffic
|
||||
EXPOSE 3000
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential ca-certificates curl nasm pkg-config xz-utils zlib1g-dev && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Start Next.js standalone server
|
||||
CMD ["node", "server.js"]
|
||||
WORKDIR /src
|
||||
|
||||
RUN curl -fsSL -o ffmpeg.tar.xz "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \
|
||||
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
|
||||
&& tar -xJf ffmpeg.tar.xz --strip-components=1 \
|
||||
&& rm ffmpeg.tar.xz
|
||||
|
||||
# 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.
|
||||
RUN ./configure \
|
||||
--prefix=/opt/ffmpeg \
|
||||
--disable-shared \
|
||||
--enable-static \
|
||||
--disable-debug \
|
||||
--disable-doc \
|
||||
--disable-ffplay \
|
||||
--disable-ffprobe \
|
||||
--disable-network \
|
||||
--disable-autodetect \
|
||||
--disable-everything \
|
||||
--enable-ffmpeg \
|
||||
--enable-protocol=file,pipe \
|
||||
--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-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
|
||||
--enable-bsf=aac_adtstoasc \
|
||||
--enable-filter=aresample,aformat \
|
||||
--enable-zlib \
|
||||
--extra-cflags="-Os" \
|
||||
--extra-ldflags="-static" \
|
||||
--pkg-config-flags="--static" \
|
||||
&& make -j"$(nproc)" \
|
||||
&& make install \
|
||||
&& strip /opt/ffmpeg/bin/ffmpeg
|
||||
|
||||
# ============================================
|
||||
# Stage 5: Run Convex and Next.js together
|
||||
# ============================================
|
||||
|
||||
FROM ${CONVEX_BACKEND_IMAGE} AS convex-backend
|
||||
|
||||
# Fresh Ubuntu instead of the Convex image. That image installs libclang,
|
||||
# which pulls LLVM (~200MB) even though the backend only links libstdc++.
|
||||
FROM ubuntu:24.04 AS runner
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends ca-certificates curl openssl tini && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /convex
|
||||
|
||||
COPY --from=convex-backend --chmod=755 \
|
||||
/convex/convex-local-backend \
|
||||
/convex/generate_key \
|
||||
/convex/run_backend.sh \
|
||||
/convex/generate_admin_key.sh \
|
||||
/convex/read_credentials.sh \
|
||||
./
|
||||
|
||||
COPY --from=node --chmod=755 /usr/local/bin/node /usr/local/bin/node
|
||||
COPY --from=ffmpeg --chmod=755 /opt/ffmpeg/bin/ffmpeg /usr/local/bin/ffmpeg
|
||||
|
||||
# Fail the build if a binary is missing a shared library.
|
||||
RUN node --version \
|
||||
&& ffmpeg -hide_banner -version \
|
||||
&& openssl version \
|
||||
&& command -v tini \
|
||||
&& command -v curl \
|
||||
&& ldd /convex/convex-local-backend \
|
||||
&& ldd /convex/generate_key \
|
||||
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
|
||||
|
||||
# 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
|
||||
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/otunes-entrypoint
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/public ./apps/web/public
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/standalone ./
|
||||
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/static ./apps/web/.next/static
|
||||
|
||||
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
|
||||
|
||||
ENV PATH="/usr/local/bin:${PATH}"
|
||||
|
||||
EXPOSE 3000 3210
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
|
||||
CMD curl -fsS http://127.0.0.1:3210/version && curl -fsS -o /dev/null http://127.0.0.1:3000/signin
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/otunes-entrypoint"]
|
||||
CMD []
|
||||
@@ -2,58 +2,94 @@
|
||||
|
||||
Your music, my music, _**our**_ music. Self-hosted music streaming app and server.
|
||||
|
||||
## Monorepo
|
||||
|
||||
This project uses [pnpm workspaces](https://pnpm.io/workspaces):
|
||||
|
||||
| Package | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| `@otunes/web` | `apps/web` | Next.js web app |
|
||||
| `@otunes/mobile` | `apps/mobile` | Expo React Native mobile app |
|
||||
| `@otunes/convex` | `packages/convex` | Shared Convex backend and client types |
|
||||
|
||||
### Development
|
||||
|
||||
Install dependencies from the repository root:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Run the web app:
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
# or
|
||||
pnpm dev:web
|
||||
```
|
||||
|
||||
Run the mobile app:
|
||||
|
||||
```bash
|
||||
pnpm dev:mobile
|
||||
```
|
||||
|
||||
Run the Convex backend (from the shared package):
|
||||
|
||||
```bash
|
||||
pnpm dev:convex
|
||||
```
|
||||
|
||||
Point the dev deployment at your music folder (it defaults to `/data`):
|
||||
|
||||
```bash
|
||||
cd packages/convex && npx convex env set DATA "/path/to/Music"
|
||||
```
|
||||
|
||||
Other commands:
|
||||
|
||||
```bash
|
||||
pnpm build # build web app
|
||||
pnpm lint # lint all packages
|
||||
pnpm typecheck # typecheck all packages
|
||||
pnpm format # format with Prettier
|
||||
```
|
||||
|
||||
## Hosting with Docker
|
||||
|
||||
Here's an example `docker-compose.yml` file to get you started:
|
||||
The image runs both the web app and its Convex backend, so there is nothing to configure. Here's an example `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
name: music
|
||||
services:
|
||||
otunes:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- /SomeAttachedStorage/Music:/data
|
||||
environment:
|
||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
||||
- CONVEX_SELF_HOSTED_URL=http://127.0.0.1:3210
|
||||
- CONVEX_SELF_HOSTED_ADMIN_KEY=REPLACE_ME
|
||||
restart: unless-stopped
|
||||
image: git.abunchofknowitalls.com/joshuafhiggins/otunes:latest
|
||||
backend:
|
||||
stop_grace_period: 10s
|
||||
stop_signal: SIGINT
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3210:3210"
|
||||
- "3211:3211"
|
||||
- "3000:3000" # web app
|
||||
- "3210:3210" # Convex
|
||||
volumes:
|
||||
- ./database:/convex/data
|
||||
environment:
|
||||
- CONVEX_CLOUD_ORIGIN=http://127.0.0.1:3210
|
||||
- CONVEX_SITE_ORIGIN=http://127.0.0.1:3211
|
||||
- APPLICATION_MAX_CONCURRENT_MUTATIONS=16
|
||||
- APPLICATION_MAX_CONCURRENT_NODE_ACTIONS=16
|
||||
- APPLICATION_MAX_CONCURRENT_QUERIES=16
|
||||
- APPLICATION_MAX_CONCURRENT_V8_ACTIONS=16
|
||||
- DISABLE_BEACON=true
|
||||
- DISABLE_METRICS_ENDPOINT=true
|
||||
- DOCUMENT_RETENTION_DELAY=172800
|
||||
- DO_NOT_REQUIRE_SSL=true
|
||||
- REDACT_LOGS_TO_CLIENT=true
|
||||
- RUST_LOG=info
|
||||
image: ghcr.io/get-convex/convex-backend:latest
|
||||
healthcheck:
|
||||
test: curl -f http://localhost:3210/version
|
||||
interval: 5s
|
||||
start_period: 10s
|
||||
- ./otunes-data:/convex/data
|
||||
- /SomeAttachedStorage/Music:/data
|
||||
stop_grace_period: 10s
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
First run `docker compose up -d backend` and `docker compose exec backend ./generate_admin_key.sh` to generate the admin key needed for the frontend. Take this key and put it in the `CONVEX_SELF_HOSTED_ADMIN_KEY` environment variable for the `otunes` service.
|
||||
Change `/SomeAttachedStorage/Music` to the folder containing your `lossless`, `normal`, and `atmos` libraries, then run `docker compose up -d`. The first account you create becomes the admin.
|
||||
|
||||
`CONVEX_SELF_HOSTED_URL`, `CONVEX_CLOUD_ORIGIN`, and `NEXT_PUBLIC_CONVEX_URL` should be changed to the same reversed proxied, SSL protected, domain and `CONVEX_SITE_ORIGIN` on a different domain.
|
||||
On first boot the container generates its own Convex instance secret and sign-in keys and stores them in `./otunes-data`, so no two installs share secrets. Back up that folder: it holds your database and keys.
|
||||
|
||||
Then change `/SomeAttachedStorage/Music` to the path where your music is stored and run `docker compose down && docker compose up -d` to start the whole app together.
|
||||
### Reverse proxy
|
||||
|
||||
The web app finds Convex from the address you open it at:
|
||||
|
||||
| You open | Convex is expected at |
|
||||
| --- | --- |
|
||||
| `https://music.example.com` | `https://convex.music.example.com` |
|
||||
| `http://192.168.1.5:3000` or `http://localhost:3000` | port `3210` on the same host |
|
||||
|
||||
So for a domain, point `music.example.com` at port `3000` and `convex.music.example.com` at port `3210` (WebSockets must be allowed). The mobile app uses the same convention.
|
||||
|
||||
If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container to its public URL.
|
||||
|
||||
## Downloads
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumView } from "@/components/album-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowseAlbumDetail } from "@/convex/library"
|
||||
|
||||
export default function Page() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const album = useQuery(api.library.browseAlbumDetail, {
|
||||
id: id as Id<"albums">,
|
||||
})
|
||||
|
||||
if (album === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (album === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Album not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <AlbumView album={album} />
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { ArtistView } from "@/components/artist-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
|
||||
export default function Page() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const data = useQuery(api.library.browseArtistDetail, {
|
||||
id: id as Id<"artists">,
|
||||
})
|
||||
|
||||
if (data === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (data === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Artist not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ArtistView
|
||||
artist={data.artist}
|
||||
albums={data.albums}
|
||||
recentlyAdded={data.recentlyAdded}
|
||||
recentlyPlayed={data.recentlyPlayed}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const albums = useQuery(api.library.browseAlbums)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Albums</h1>
|
||||
</header>
|
||||
|
||||
{albums === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{albums.map((album) => (
|
||||
<AlbumCard key={album.id} album={album} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const artists = useQuery(api.library.browseArtists)
|
||||
const albums = useQuery(api.library.browseAlbums)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Artists</h1>
|
||||
</header>
|
||||
|
||||
{artists === undefined || albums === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<ArtistsView artists={artists} albums={albums} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { SongsView } from "@/components/songs-view"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const songs = useQuery(api.library.browseSongs)
|
||||
|
||||
if (songs === undefined) {
|
||||
return <LibraryLoading />
|
||||
}
|
||||
|
||||
return <SongsView songs={songs} />
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const recentlyAdded = useQuery(api.library.browseRecentlyAdded)
|
||||
const recentlyPlayed = useQuery(api.library.browseAlbums)
|
||||
|
||||
if (recentlyAdded === undefined || recentlyPlayed === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Home</h1>
|
||||
</header>
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Home</h1>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="flex flex-col gap-10">
|
||||
<ContentCarousel
|
||||
title="Recently Played"
|
||||
href="/recently-played"
|
||||
content={recentlyPlayed.slice(0, 9)}
|
||||
/>
|
||||
<ContentCarousel
|
||||
title="Recently Added"
|
||||
href="/recently-added"
|
||||
content={recentlyAdded.slice(0, 9)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowsePlaylistDetail } from "@/convex/library"
|
||||
|
||||
export default function Page() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const playlist = useQuery(api.playlists.browsePlaylistDetail, {
|
||||
id: id as Id<"playlists">,
|
||||
})
|
||||
|
||||
if (playlist === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (playlist === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Playlist not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={playlist} />
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||
|
||||
if (favorites === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (favorites === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign in to view your favorites.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={favorites} />
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { PlaylistSummary } from "@/convex/library"
|
||||
import {
|
||||
albumGridCarouselContentClassName,
|
||||
albumGridCarouselSlideClassName,
|
||||
albumGridClassName,
|
||||
} from "@/lib/album-grid-classes"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { PlaylistCard } from "@/components/playlist-card"
|
||||
|
||||
export default function Page() {
|
||||
const playlists = useQuery(api.playlists.listAllPlaylists)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Playlists</h1>
|
||||
</header>
|
||||
|
||||
{playlists === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{playlists.map((playlist) => (
|
||||
<PlaylistCard key={playlist.id} playlist={playlist} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const albums = useQuery(api.library.browseRecentlyAdded)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Recently Added</h1>
|
||||
</header>
|
||||
|
||||
{albums === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{albums.map((album) => (
|
||||
<AlbumCard key={album.id} album={album} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const albums = useQuery(api.library.browseAlbums)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Recently Played</h1>
|
||||
</header>
|
||||
|
||||
{albums === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{albums.map((album) => (
|
||||
<AlbumCard key={album.id} album={album} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useDeferredValue, useState } from "react"
|
||||
import { useQuery } from "convex/react"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { SearchSongItem } from "@/components/search-song-item"
|
||||
import { SearchTopResultCard, type TopResult } from "@/components/search-top-result-card"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseArtist,
|
||||
BrowseSong,
|
||||
PlaylistSummary,
|
||||
} from "@/convex/library"
|
||||
|
||||
export default function Page() {
|
||||
const [query, setQuery] = useState("")
|
||||
const deferredQuery = useDeferredValue(query.trim())
|
||||
const hasQuery = deferredQuery.length > 0
|
||||
|
||||
const results = useQuery(
|
||||
api.library.searchLibrary,
|
||||
hasQuery ? { query: deferredQuery } : "skip"
|
||||
)
|
||||
const playlistResults = useQuery(
|
||||
api.playlists.searchPlaylists,
|
||||
hasQuery ? { query: deferredQuery } : "skip"
|
||||
)
|
||||
|
||||
const showPlaylists =
|
||||
hasQuery && playlistResults !== undefined && playlistResults.length > 0
|
||||
const isSearching = hasQuery && results === undefined
|
||||
const hasLibraryResults =
|
||||
results &&
|
||||
(results.topResults.length > 0 ||
|
||||
results.artists.length > 0 ||
|
||||
results.albums.length > 0 ||
|
||||
results.songs.length > 0)
|
||||
const showResults = hasQuery && results !== undefined
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center justify-center border-b px-4 py-3">
|
||||
<div className="relative w-full max-w-xl">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
type="search"
|
||||
data-slot="input"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Search"
|
||||
className="h-10 w-full min-w-0 rounded-full border border-input bg-input/30 pr-3 pl-9 text-sm text-foreground transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{isSearching ? (
|
||||
<LibraryLoading />
|
||||
) : !hasQuery ? (
|
||||
<div className="flex flex-1 items-center justify-center px-6 pb-28">
|
||||
<p className="text-center text-muted-foreground">
|
||||
Search for songs, albums, artists, and playlists in your library.
|
||||
</p>
|
||||
</div>
|
||||
) : !showResults ? null : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="mx-auto flex max-w-6xl flex-col gap-10">
|
||||
{!hasLibraryResults && (
|
||||
<p className="text-muted-foreground">
|
||||
No library results for “{deferredQuery}”
|
||||
</p>
|
||||
)}
|
||||
|
||||
{results.topResults.length > 0 && (
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-xl font-bold tracking-tight">Top Results</h2>
|
||||
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{results.topResults.map((result) => (
|
||||
<SearchTopResultCard
|
||||
key={`${result.kind}-${result.item.id}`}
|
||||
result={result as TopResult}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{results.artists.length > 0 && (
|
||||
<ContentCarousel
|
||||
title="Artists"
|
||||
content={results.artists}
|
||||
/>
|
||||
)}
|
||||
|
||||
{results.albums.length > 0 && (
|
||||
<ContentCarousel
|
||||
title="Albums"
|
||||
content={results.albums}
|
||||
/>
|
||||
)}
|
||||
|
||||
{results.songs.length > 0 && (
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-xl font-bold tracking-tight">Songs</h2>
|
||||
<div className="grid gap-x-6 gap-y-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{results.songs.map((song) => (
|
||||
<SearchSongItem key={song.id} song={song} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{showPlaylists && (
|
||||
<ContentCarousel
|
||||
title="Playlists"
|
||||
content={playlistResults ?? []}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { serveCoverFile } from "@/lib/serve-cover"
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const playlist = await getConvexClient().query(api.library.getPlaylist, {
|
||||
id: id as Id<"playlists">,
|
||||
})
|
||||
return serveCoverFile(playlist?.cover)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { audioContentTypeForPath } from "@/lib/audio-content-type"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
|
||||
import fs from "node:fs/promises"
|
||||
|
||||
const DATA_DIR = process.env.NEXT_PUBLIC_CONVEX_URL?.includes("127.0.0.1")
|
||||
? "/Users/joshuafhiggins/Downloads/test"
|
||||
: process.env.DATA || "/data"
|
||||
|
||||
function ffmpegToReadableStream(ffmpegProcess: ChildProcessWithoutNullStreams) {
|
||||
let closed = false
|
||||
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
const finalize = (err?: Error) => {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
closed = true
|
||||
|
||||
try {
|
||||
if (err) {
|
||||
controller.error(err)
|
||||
} else {
|
||||
controller.close()
|
||||
}
|
||||
} catch {
|
||||
// Consumer may have already closed the stream (e.g. track change).
|
||||
}
|
||||
}
|
||||
|
||||
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
controller.enqueue(new Uint8Array(chunk))
|
||||
} catch {
|
||||
closed = true
|
||||
ffmpegProcess.kill("SIGKILL")
|
||||
}
|
||||
})
|
||||
|
||||
ffmpegProcess.stderr.on("data", (data) => {
|
||||
//console.error(`FFmpeg log: ${data.toString()}`)
|
||||
})
|
||||
|
||||
ffmpegProcess.stdout.on("end", () => finalize())
|
||||
ffmpegProcess.stdout.on("error", (err) => finalize(err))
|
||||
|
||||
ffmpegProcess.on("close", (code) => {
|
||||
if (code !== 0 && !closed) {
|
||||
finalize(new Error(`ffmpeg exited with code ${code}`))
|
||||
} else {
|
||||
finalize()
|
||||
}
|
||||
})
|
||||
|
||||
ffmpegProcess.on("error", (err) => finalize(err))
|
||||
},
|
||||
cancel() {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
closed = true
|
||||
ffmpegProcess.kill("SIGKILL")
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const song = (await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!
|
||||
const album = (await getConvexClient().query(api.library.getAlbum, {
|
||||
id: song.album,
|
||||
}))!
|
||||
const artist = (await getConvexClient().query(api.library.getArtist, {
|
||||
id: song.albumArtist,
|
||||
}))!
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality") as
|
||||
| "low"
|
||||
| "medium"
|
||||
| "high"
|
||||
| "lossless"
|
||||
| null
|
||||
|
||||
const preferAtmos =
|
||||
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
||||
|
||||
let kbps = 0
|
||||
if (quality === "low") {
|
||||
kbps = 64
|
||||
} else if (quality === "medium") {
|
||||
kbps = 128
|
||||
} else if (quality === "high") {
|
||||
kbps = 256
|
||||
}
|
||||
|
||||
let originalCodec = "lossless" in song.files ? "lossless" : "normal"
|
||||
|
||||
let transcodeNeeded = true
|
||||
if (preferAtmos && "atmos" in song.files) {
|
||||
originalCodec = "atmos"
|
||||
transcodeNeeded = false
|
||||
} else if (kbps === 0 && "lossless" in song.files) {
|
||||
originalCodec = "lossless"
|
||||
transcodeNeeded = false
|
||||
} else if (kbps === 0) {
|
||||
transcodeNeeded = false
|
||||
}
|
||||
|
||||
const file = `${DATA_DIR}/${originalCodec}/${artist.name}/${album.name}/${song.files[originalCodec]}`
|
||||
if (!transcodeNeeded) {
|
||||
const data = await fs.readFile(file)
|
||||
return new NextResponse(data, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": audioContentTypeForPath(file),
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const ffmpegArgs = [
|
||||
"-nostdin",
|
||||
"-i",
|
||||
file,
|
||||
"-c:a",
|
||||
`${quality === "low" ? "libfdk_aac" : "aac"}`,
|
||||
"-b:a",
|
||||
`${kbps}k`,
|
||||
"-f",
|
||||
"adts",
|
||||
"pipe:1",
|
||||
]
|
||||
|
||||
try {
|
||||
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
||||
const stream = ffmpegToReadableStream(ffmpegProcess)
|
||||
|
||||
return new NextResponse(stream, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "audio/aac",
|
||||
"Transfer-Encoding": "chunked",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
return new Response("Server Error", { status: 500 })
|
||||
}
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB |
@@ -1,51 +0,0 @@
|
||||
import { Geist, Geist_Mono, Inter } from "next/font/google"
|
||||
|
||||
import "./globals.css"
|
||||
import { ConvexAuthNextjsServerProvider } from "@convex-dev/auth/nextjs/server"
|
||||
import { ConvexClientProvider } from "@/components/convex-client-provider"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import type { Metadata } from "next"
|
||||
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
||||
|
||||
const fontMono = Geist_Mono({
|
||||
subsets: ["latin"],
|
||||
variable: "--font-mono",
|
||||
})
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "oTunes",
|
||||
description: "Our Music",
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
suppressHydrationWarning
|
||||
className={cn(
|
||||
"antialiased",
|
||||
fontMono.variable,
|
||||
"font-sans",
|
||||
inter.variable
|
||||
)}
|
||||
>
|
||||
<body className={"overflow-x-hidden"}>
|
||||
<ConvexAuthNextjsServerProvider>
|
||||
<ConvexClientProvider>
|
||||
<ThemeProvider>
|
||||
{children}
|
||||
<Toaster />
|
||||
</ThemeProvider>
|
||||
</ConvexClientProvider>
|
||||
</ConvexAuthNextjsServerProvider>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/ios/
|
||||
/android/
|
||||
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
|
||||
# The following patterns were generated by expo-cli
|
||||
|
||||
expo-env.d.ts
|
||||
# @end expo-cli
|
||||
@@ -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.")
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -0,0 +1,64 @@
|
||||
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 ?? []),
|
||||
...(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`,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "oTunes",
|
||||
"slug": "otunes",
|
||||
"version": "0.0.1",
|
||||
"orientation": "portrait",
|
||||
"scheme": "otunes",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"icon": "./assets/icon.png",
|
||||
"ios": {
|
||||
"icon": "./assets/oTunes.icon",
|
||||
"supportsTablet": true,
|
||||
"bundleIdentifier": "com.abunchofknowitalls.otunes",
|
||||
"infoPlist": {
|
||||
"ITSAppUsesNonExemptEncryption": false
|
||||
}
|
||||
},
|
||||
"android": {
|
||||
"package": "com.abunchofknowitalls.otunes",
|
||||
"predictiveBackGestureEnabled": false,
|
||||
"permissions": [
|
||||
"android.permission.MODIFY_AUDIO_SETTINGS",
|
||||
"android.permission.FOREGROUND_SERVICE",
|
||||
"android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"
|
||||
],
|
||||
"adaptiveIcon": {
|
||||
"monochromeImage": "./assets/android-icon-monochrome.png",
|
||||
"foregroundImage": "./assets/android-icon-foreground.png",
|
||||
"backgroundImage": "./assets/android-icon-background.png"
|
||||
},
|
||||
"userInterfaceStyle": "dark",
|
||||
"softwareKeyboardLayoutMode": "resize",
|
||||
"icon": "./assets/android-icon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
"expo-secure-store",
|
||||
[
|
||||
"expo-audio",
|
||||
{
|
||||
"enableBackgroundPlayback": true
|
||||
}
|
||||
],
|
||||
"expo-sharing",
|
||||
"expo-font",
|
||||
"expo-asset",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
"backgroundColor": "#000000"
|
||||
}
|
||||
],
|
||||
"expo-image",
|
||||
"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,
|
||||
"inlineModules": {
|
||||
"watchedDirectories": [
|
||||
"app-intents",
|
||||
"native"
|
||||
]
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"router": {},
|
||||
"eas": {
|
||||
"projectId": "98b83584-d757-4da0-9bec-050c8336643f"
|
||||
}
|
||||
},
|
||||
"owner": "joshuafhiggins"
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { Stack } from "expo-router"
|
||||
|
||||
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}>
|
||||
<Stack
|
||||
screenLayout={renderTabScreenContent}
|
||||
screenOptions={({ route }) => ({
|
||||
...options,
|
||||
title:
|
||||
route.name === "index"
|
||||
? section?.title
|
||||
: tabStackScreenTitles[route.name],
|
||||
})}
|
||||
/>
|
||||
</TabletSectionContext>
|
||||
)
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/album/[id]"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/artist/[id]"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/browse/albums"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/browse/artists"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/browse/playlists"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/browse/songs"
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
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 { TabletSectionContext } from "@/lib/tablet-navigation"
|
||||
|
||||
const screens = {
|
||||
albums: Albums,
|
||||
artists: Artists,
|
||||
songs: Songs,
|
||||
playlists: Playlists,
|
||||
favorites: Favorites,
|
||||
recent: RecentlyPlayed,
|
||||
}
|
||||
|
||||
export default function TabletSectionScreen() {
|
||||
const section = useContext(TabletSectionContext)
|
||||
const Screen = screens[section?.name ?? "albums"]
|
||||
return <Screen />
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/playlist/[id]"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../../library/playlist/favorites"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../library/recently-added"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../library/recently-played"
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { default } from "../library/settings"
|
||||
@@ -0,0 +1,236 @@
|
||||
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/native-tabs"
|
||||
import { DynamicColorIOS, Platform } from "react-native"
|
||||
import { useMemo } from "react"
|
||||
|
||||
import { AndroidMiniPlayer, TabBottomAccessory } from "@/components/mini-player"
|
||||
import { useAndroidKeyboardVisible } from "@/hooks/use-android-keyboard-visible"
|
||||
import { usePlaybackQueue } from "@/contexts/playback"
|
||||
import { appleMusic, colors, miniPlayerHeight, useIsDark } from "@/lib/theme"
|
||||
|
||||
export const unstable_settings = { anchor: "library" }
|
||||
|
||||
function useRouterTheme() {
|
||||
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: 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, androidPalette])
|
||||
}
|
||||
|
||||
function useNativeTabColors() {
|
||||
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 =
|
||||
Platform.OS === "ios"
|
||||
? {
|
||||
default: DynamicColorIOS({ dark: inactive, light: "#636366" }),
|
||||
selected: appleMusic.pink,
|
||||
}
|
||||
: {
|
||||
default: androidPalette.secondaryForeground,
|
||||
selected: selectedColor,
|
||||
}
|
||||
|
||||
const labelColor =
|
||||
Platform.OS === "ios"
|
||||
? DynamicColorIOS({ dark: inactive, light: "#636366" })
|
||||
: androidPalette.secondaryForeground
|
||||
|
||||
return {
|
||||
isDark,
|
||||
tintColor: Platform.OS === "android" ? selectedColor : appleMusic.pink,
|
||||
iconColor,
|
||||
labelStyle: {
|
||||
default: { color: labelColor, fontSize: 10 },
|
||||
selected: {
|
||||
color: Platform.OS === "android" ? selectedColor : appleMusic.pink,
|
||||
fontSize: 10,
|
||||
fontWeight: "600" as const,
|
||||
},
|
||||
},
|
||||
blurEffect: isDark
|
||||
? "systemChromeMaterialDark"
|
||||
: "systemChromeMaterialLight",
|
||||
backgroundColor:
|
||||
Platform.OS === "ios" ? undefined : androidPalette.background,
|
||||
}
|
||||
}
|
||||
|
||||
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}>
|
||||
<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
|
||||
contentStyle={androidContentStyle}
|
||||
>
|
||||
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
|
||||
<NativeTabs.Trigger.Label>Home</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
|
||||
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="(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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { renderTabScreenContent } from "@/components/tab-screen-content"
|
||||
import { Stack } from "expo-router"
|
||||
|
||||
import { ProfileHeaderButton } from "@/components/profile-header-button"
|
||||
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
}
|
||||
|
||||
export default function HomeLayout() {
|
||||
const baseOptions = useStackScreenOptions({ title: "Home" })
|
||||
|
||||
return (
|
||||
<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,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
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 { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import {
|
||||
MediaActionMenu,
|
||||
MediaContextMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
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 { 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"
|
||||
|
||||
export default function AlbumScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>()
|
||||
const { push } = useAppNavigation()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const album = useCachedQuery(
|
||||
api.library.browseAlbumDetail,
|
||||
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
|
||||
)
|
||||
const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } =
|
||||
useFavorites()
|
||||
const {
|
||||
handleAlbumDetailAction,
|
||||
handleAlbumTrackAction,
|
||||
isAlbumFavorite: isAlbumFav,
|
||||
} = useMediaMenuActions()
|
||||
const swipeGroup = useSwipeRowGroup()
|
||||
const isFocused = useIsFocused()
|
||||
const coverUri =
|
||||
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
|
||||
const heroLayout = useCollectionHeroLayout()
|
||||
const { palette: artworkPalette, settled } = useCoverPalette(
|
||||
coverUri,
|
||||
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]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (album) {
|
||||
rememberSongs(albumDetailSongs(album))
|
||||
}
|
||||
}, [album])
|
||||
|
||||
const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album])
|
||||
|
||||
const playTrack = useCallback(
|
||||
(songId: Id<"songs">, ids: Id<"songs">[]) =>
|
||||
playFromSong(songId, ids, `album:${id}`),
|
||||
[id, 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
|
||||
variant="album"
|
||||
onLayout={onLayout}
|
||||
style={backgroundStyle}
|
||||
backgroundColor={
|
||||
Platform.OS === "android" ? palette.background : undefined
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (album === null) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<View style={[styles.empty, { backgroundColor: colors.background }]}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Album not found.
|
||||
</Text>
|
||||
</View>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
const favorited = isAlbumFavorite(album.id)
|
||||
|
||||
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, title: album.title }}
|
||||
onAction={(action) =>
|
||||
void handleAlbumDetailAction(
|
||||
album.id as Id<"albums">,
|
||||
songIds,
|
||||
action,
|
||||
album.artist.id as Id<"artists">
|
||||
)
|
||||
}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<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>
|
||||
<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
|
||||
onPress={() => void toggleAlbumFavorite(album.id)}
|
||||
hitSlop={8}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{ backgroundColor: palette.surface },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={favorited ? "star" : "star-outline"}
|
||||
size={24}
|
||||
color={favorited ? palette.accent : palette.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playAlbum(album.id, songIds)}
|
||||
style={styles.playButton}
|
||||
tint={{
|
||||
background: palette.accent,
|
||||
foreground: palette.accentForeground,
|
||||
}}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playAlbumShuffled(album.id, songIds)}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{ backgroundColor: palette.surface },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="shuffle"
|
||||
size={24}
|
||||
color={palette.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
}
|
||||
>
|
||||
<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>
|
||||
</CollectionHero>
|
||||
</MusicEntityView>
|
||||
<CollectionDivider color={palette.divider} />
|
||||
</View>
|
||||
}
|
||||
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()
|
||||
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}
|
||||
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")}
|
||||
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>
|
||||
<Text style={{ color: palette.secondaryForeground }}>
|
||||
{formatDuration(track.durationSeconds)}
|
||||
</Text>
|
||||
</View>
|
||||
</Row>
|
||||
</MusicEntityView>
|
||||
</MediaContextMenu>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
cover: {
|
||||
width: 220,
|
||||
height: 220,
|
||||
borderRadius: radius.lg,
|
||||
},
|
||||
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
|
||||
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",
|
||||
justifyContent: "center",
|
||||
gap: spacing.sm,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
playButton: { borderRadius: 999, minWidth: 160 },
|
||||
iconAction: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 22,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
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: 52,
|
||||
paddingVertical: 12,
|
||||
marginRight: collectionInset,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
trackMeta: { flex: 1, minWidth: 0 },
|
||||
trackTitle: { fontSize: 16, fontWeight: "500" },
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
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"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaActionMenu } from "@/components/media-context-menu"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
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 { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { artistCoverUrl } from "@/lib/urls"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
export default function ArtistScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const data = useCachedQuery(
|
||||
api.library.browseArtistDetail,
|
||||
typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
|
||||
)
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { handleArtistAction, isArtistFavorite: isArtistFav } =
|
||||
useMediaMenuActions()
|
||||
|
||||
if (data === undefined || !config) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<CollectionDetailSkeleton variant="artist" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (data === null) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<View style={[styles.empty, { backgroundColor: colors.background }]}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Artist not found.
|
||||
</Text>
|
||||
</View>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={data.albums.length}
|
||||
favorited={isArtistFav(data.artist.id)}
|
||||
share={{
|
||||
type: "artist",
|
||||
artistId: data.artist.id,
|
||||
title: data.artist.name,
|
||||
}}
|
||||
onAction={(action) =>
|
||||
void handleArtistAction(data.artist, action)
|
||||
}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<MediaGridList
|
||||
content={data.albums}
|
||||
paddingBottom={contentBottomInset}
|
||||
contentInset={false}
|
||||
ListHeaderComponent={
|
||||
<MusicEntityView
|
||||
kind="artist"
|
||||
id={data.artist.id}
|
||||
style={styles.hero}
|
||||
>
|
||||
<CoverImage
|
||||
uri={artistCoverUrl(config.serverUrl, data.artist.id)}
|
||||
hasCover={data.artist.photo != null}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{data.artist.name}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleArtistFavorite(data.artist.id)}
|
||||
hitSlop={8}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={
|
||||
isArtistFavorite(data.artist.id) ? "star" : "star-outline"
|
||||
}
|
||||
size={24}
|
||||
color={
|
||||
isArtistFavorite(data.artist.id)
|
||||
? colors.primary
|
||||
: colors.foreground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playArtist(data.artist.id)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playArtistShuffled(data.artist.id)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</MusicEntityView>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
|
||||
avatar: {
|
||||
width: 180,
|
||||
height: 180,
|
||||
borderRadius: 90,
|
||||
},
|
||||
title: { fontSize: 28, fontWeight: "800", textAlign: "center" },
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.sm,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
playButton: { borderRadius: 999, minWidth: 160 },
|
||||
iconAction: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 22,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Stack } from "expo-router"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function AlbumsScreen() {
|
||||
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
api.library.browseAlbumsPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const searchResults = useCachedQuery(
|
||||
api.library.searchLibrary,
|
||||
searchQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
const albums = searchQuery
|
||||
? searchResults?.albums
|
||||
: status === "LoadingFirstPage" && !isCached
|
||||
? undefined
|
||||
: results
|
||||
|
||||
const handleChangeText = useCallback(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
onQueryChange(event.nativeEvent.text)
|
||||
},
|
||||
[onQueryChange]
|
||||
)
|
||||
|
||||
const searchBar = (
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search",
|
||||
onChangeText: handleChangeText,
|
||||
onSearchButtonPress: onSearchSubmit,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
if (albums === undefined) {
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
<MediaGridSkeleton />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
|
||||
<MediaGridList
|
||||
content={albums}
|
||||
paddingBottom={contentBottomInset}
|
||||
onEndReached={() => {
|
||||
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { Stack } from "expo-router"
|
||||
import { memo, useCallback } from "react"
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
|
||||
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"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
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"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function ArtistsScreen() {
|
||||
const { push } = useAppNavigation()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
api.library.browseArtistsPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const searchResults = useCachedQuery(
|
||||
api.library.searchLibrary,
|
||||
searchQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
const { handleArtistAction, isArtistFavorite } = useMediaMenuActions()
|
||||
const artists = searchQuery
|
||||
? searchResults?.artists
|
||||
: status === "LoadingFirstPage" && !isCached
|
||||
? 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)
|
||||
},
|
||||
[onQueryChange]
|
||||
)
|
||||
|
||||
const searchBar = (
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search",
|
||||
onChangeText: handleChangeText,
|
||||
onSearchButtonPress: onSearchSubmit,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
if (artists === undefined || !config) {
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
<ArtistListSkeleton />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={artists}
|
||||
keyExtractor={artistKey}
|
||||
renderItem={renderItem}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
onEndReachedThreshold={0.5}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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",
|
||||
gap: spacing.md,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
avatar: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 22,
|
||||
},
|
||||
name: { flex: 1, fontSize: 16, fontWeight: "600" },
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Pressable } from "react-native"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { useThemeColors } from "@/lib/theme"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { Stack } from "expo-router"
|
||||
import { SymbolView } from "expo-symbols"
|
||||
import { useAddToPlaylist } from "@/contexts/add-to-playlist"
|
||||
|
||||
export default function PlaylistsTabScreen() {
|
||||
const colors = useThemeColors()
|
||||
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
|
||||
const { openCreatePlaylist } = useAddToPlaylist()
|
||||
|
||||
if (playlists === undefined) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Playlists",
|
||||
headerLargeTitle: true,
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
onPress={openCreatePlaylist}
|
||||
accessibilityLabel="New playlist"
|
||||
hitSlop={4}
|
||||
>
|
||||
<SymbolView
|
||||
name="plus"
|
||||
size={24}
|
||||
tintColor={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<MediaGridSkeleton />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Playlists",
|
||||
headerLargeTitle: true,
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
onPress={openCreatePlaylist}
|
||||
accessibilityLabel="New playlist"
|
||||
hitSlop={4}
|
||||
>
|
||||
<SymbolView name="plus" size={24} tintColor={colors.foreground} />
|
||||
</Pressable>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<MediaGridList
|
||||
content={playlists}
|
||||
paddingBottom={tabContentBottomInset}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Stack } from "expo-router"
|
||||
import { useCallback, useState } from "react"
|
||||
import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native"
|
||||
|
||||
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"
|
||||
import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { longListProps } from "@/lib/list"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function SongsScreen() {
|
||||
const { playFromLibrarySong } = usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
|
||||
const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title")
|
||||
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc")
|
||||
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
api.library.browseSongsPaginated,
|
||||
{ sortKey, sortDirection },
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const searchResults = useCachedQuery(
|
||||
api.library.searchLibrary,
|
||||
searchQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
const songs = searchQuery
|
||||
? searchResults?.songs
|
||||
: status === "LoadingFirstPage" && !isCached
|
||||
? 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)
|
||||
},
|
||||
[onQueryChange]
|
||||
)
|
||||
|
||||
const searchBar = (
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search",
|
||||
onChangeText: handleChangeText,
|
||||
onSearchButtonPress: onSearchSubmit,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
if (songs === undefined) {
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
<SongListSkeleton />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{searchBar}
|
||||
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
onEndReachedThreshold={0.5}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function songKey(song: BrowseSong) {
|
||||
return song.id
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { memo } from "react"
|
||||
import { ScrollView, StyleSheet } from "react-native"
|
||||
|
||||
import { ContentCarousel } from "@/components/media-cards"
|
||||
import { HomeSkeleton } from "@/components/skeletons"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
const CAROUSEL_ITEM_LIMIT = 10
|
||||
|
||||
const HomeCarousels = memo(function HomeCarousels({
|
||||
recentlyAdded,
|
||||
recentlyPlayed,
|
||||
}: {
|
||||
recentlyAdded: BrowseAlbum[]
|
||||
recentlyPlayed: (BrowseAlbum | PlaylistSummary)[]
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{recentlyPlayed.length > 0 ? (
|
||||
<ContentCarousel
|
||||
title="Recently Played"
|
||||
href="/recently-played"
|
||||
content={recentlyPlayed}
|
||||
/>
|
||||
) : null}
|
||||
<ContentCarousel
|
||||
title="Recently Added"
|
||||
href="/recently-added"
|
||||
content={recentlyAdded}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
})
|
||||
|
||||
export default function HomeScreen() {
|
||||
const colors = useThemeColors()
|
||||
const recentlyAdded = useCachedPaginatedQuery(
|
||||
api.library.browseRecentlyAddedPaginated,
|
||||
{},
|
||||
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
||||
)
|
||||
const recentlyPlayed = useCachedPaginatedQuery(
|
||||
api.library.browseRecentlyPlayedPaginated,
|
||||
{},
|
||||
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
||||
)
|
||||
|
||||
const isLoading = [recentlyAdded, recentlyPlayed].some(
|
||||
(result) => result.status === "LoadingFirstPage" && !result.isCached
|
||||
)
|
||||
if (isLoading) {
|
||||
return <HomeSkeleton />
|
||||
}
|
||||
|
||||
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
|
||||
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={[
|
||||
styles.content,
|
||||
{ paddingBottom: tabContentBottomInset },
|
||||
]}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
>
|
||||
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
|
||||
</ScrollView>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
content: {
|
||||
padding: spacing.lg,
|
||||
gap: spacing.xl,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,656 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import {
|
||||
CollectionHero,
|
||||
useCollectionHeroLayout,
|
||||
} from "@/components/collection-hero"
|
||||
import Animated from "react-native-reanimated"
|
||||
import {
|
||||
PlaylistSearchBar,
|
||||
usePlaylistSearch,
|
||||
} from "@/components/playlist-search-bar"
|
||||
import { useScreenPalette } from "@/contexts/android-tab-theme"
|
||||
import { MusicEntityView } from "@/components/music-entity-view"
|
||||
import { useMutation } from "convex/react"
|
||||
import { memo, useCallback, useEffect, useMemo } from "react"
|
||||
import {
|
||||
Link,
|
||||
Stack,
|
||||
useIsFocused,
|
||||
useLocalSearchParams,
|
||||
useRouter,
|
||||
} from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import {
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
|
||||
|
||||
import { CollectionDivider } from "@/components/collection-list"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import {
|
||||
useSwipeRowGroup,
|
||||
type SwipeRowGroup,
|
||||
} from "@/components/ios-swipe-to-remove-row"
|
||||
|
||||
import {
|
||||
MediaActionMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongListRow } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
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 { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
|
||||
import type { CoverPalette } from "@/lib/cover-palette"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import { rememberSongs } from "@/lib/song-cache"
|
||||
import { showError } from "@/lib/toast"
|
||||
import { playlistCoverUrl } from "@/lib/urls"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
const PLAYLIST_LABEL = "Add to Another Playlist"
|
||||
const OWNER_MENU_ACTIONS: MediaAction[] = [
|
||||
"share",
|
||||
"playlist",
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"favorite",
|
||||
"change-cover",
|
||||
"delete-playlist",
|
||||
]
|
||||
|
||||
export default function PlaylistScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
|
||||
const playlist = useCachedQuery(
|
||||
api.playlists.browsePlaylistDetail,
|
||||
playlistId ? { id: playlistId } : "skip"
|
||||
)
|
||||
const songs = playlist?.songs
|
||||
const coverUri =
|
||||
config && playlistId
|
||||
? playlistCoverUrl(
|
||||
config.serverUrl,
|
||||
playlist?.id ?? playlistId,
|
||||
playlist?.cover ?? null
|
||||
)
|
||||
: ""
|
||||
const { palette: artworkPalette, settled } = useCoverPalette(
|
||||
coverUri,
|
||||
playlist ? playlist.cover != null : playlist === null ? false : undefined
|
||||
)
|
||||
const { palette, onLayout, backgroundStyle } =
|
||||
useScreenPalette(artworkPalette)
|
||||
|
||||
useEffect(() => {
|
||||
if (songs) rememberSongs(songs)
|
||||
}, [songs])
|
||||
|
||||
if (playlist === undefined || !config || !settled) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
...(Platform.OS === "android"
|
||||
? {
|
||||
headerStyle: { backgroundColor: palette.background },
|
||||
headerTintColor: palette.foreground,
|
||||
}
|
||||
: {}),
|
||||
}}
|
||||
/>
|
||||
<CollectionDetailSkeleton
|
||||
variant="playlist"
|
||||
onLayout={onLayout}
|
||||
style={backgroundStyle}
|
||||
backgroundColor={
|
||||
Platform.OS === "android" ? palette.background : undefined
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (playlist === null) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<View style={[styles.empty, { backgroundColor: colors.background }]}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Playlist not found.
|
||||
</Text>
|
||||
</View>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PlaylistContent
|
||||
backgroundStyle={backgroundStyle}
|
||||
onLayout={onLayout}
|
||||
playlist={playlist}
|
||||
songs={playlist.songs}
|
||||
coverUri={coverUri}
|
||||
palette={palette}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PlaylistContent({
|
||||
backgroundStyle,
|
||||
onLayout,
|
||||
playlist,
|
||||
songs,
|
||||
coverUri,
|
||||
palette,
|
||||
}: {
|
||||
onLayout?: () => void
|
||||
backgroundStyle: ReturnType<typeof useScreenPalette>["backgroundStyle"]
|
||||
playlist: BrowsePlaylistDetail
|
||||
songs: BrowseSong[]
|
||||
coverUri: string
|
||||
palette: CoverPalette
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const isFocused = useIsFocused()
|
||||
const colors = useThemeColors()
|
||||
const { playPlaylist, playPlaylistShuffled, playFromSong } =
|
||||
usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions()
|
||||
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
|
||||
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
||||
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
|
||||
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
||||
|
||||
const playlistId = playlist.id
|
||||
const isSubscribed = playlist.isSubscribed
|
||||
const canEdit = playlist.isOwner && playlistId !== null
|
||||
const songIds = useMemo(() => songs.map((song) => song.id), [songs])
|
||||
const { filteredSongs, onQueryChange, onSearchSubmit } =
|
||||
usePlaylistSearch(songs)
|
||||
const swipeGroup = useSwipeRowGroup()
|
||||
|
||||
const handlePlaySong = useCallback(
|
||||
(song: BrowseSong) =>
|
||||
void playFromSong(song.id, songIds, `playlist:${playlistId}`),
|
||||
[playFromSong, songIds, playlistId]
|
||||
)
|
||||
|
||||
const handleRemoveSong = useCallback(
|
||||
async (songId: Id<"songs">) => {
|
||||
if (!playlistId) return false
|
||||
try {
|
||||
await removeSongs({ playlistId, songIds: [songId] })
|
||||
return true
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to remove from playlist"
|
||||
)
|
||||
return false
|
||||
}
|
||||
},
|
||||
[playlistId, removeSongs]
|
||||
)
|
||||
|
||||
const handleSongMenuAction = useCallback(
|
||||
(song: BrowseSong, action: MediaAction) => {
|
||||
if (action === "remove-from-playlist") void handleRemoveSong(song.id)
|
||||
else void handleSongAction(song, action)
|
||||
},
|
||||
[handleRemoveSong, handleSongAction]
|
||||
)
|
||||
|
||||
const handlePlay = useCallback(() => {
|
||||
if (playlistId) void playPlaylist(playlistId, songIds)
|
||||
}, [playPlaylist, playlistId, songIds])
|
||||
|
||||
const handleShuffle = useCallback(() => {
|
||||
if (playlistId) void playPlaylistShuffled(playlistId, songIds)
|
||||
}, [playPlaylistShuffled, playlistId, songIds])
|
||||
|
||||
const handleSubscribeToggle = useCallback(async () => {
|
||||
if (!playlistId) return
|
||||
try {
|
||||
if (isSubscribed) {
|
||||
await unsubscribe({ playlistId })
|
||||
} else {
|
||||
await subscribe({ playlistId })
|
||||
}
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update subscription"
|
||||
)
|
||||
}
|
||||
}, [isSubscribed, playlistId, subscribe, unsubscribe])
|
||||
|
||||
const screenOptions = useMemo(() => {
|
||||
async function handleDelete() {
|
||||
if (!playlistId) return
|
||||
try {
|
||||
await deletePlaylist({ playlistId })
|
||||
router.back()
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to delete playlist"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function handlePlaylistMenuAction(action: MediaAction) {
|
||||
if (action === "delete-playlist") {
|
||||
void handleDelete()
|
||||
return
|
||||
}
|
||||
if (action === "change-cover") {
|
||||
if (playlistId) {
|
||||
router.push({
|
||||
pathname: "/playlist-cover",
|
||||
params: { id: playlistId },
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
void handlePlaylistDetailAction(songIds, action)
|
||||
}
|
||||
|
||||
return {
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerTintColor: palette.foreground,
|
||||
...(Platform.OS === "android"
|
||||
? {
|
||||
headerStyle: { backgroundColor: palette.background },
|
||||
statusBarStyle: palette.isDark
|
||||
? ("light" as const)
|
||||
: ("dark" as const),
|
||||
}
|
||||
: {}),
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={songIds.length}
|
||||
playlistLabel={PLAYLIST_LABEL}
|
||||
share={{
|
||||
type: "playlist",
|
||||
playlistId: playlistId ?? "favorites",
|
||||
title: playlist?.title ?? "oTunes",
|
||||
}}
|
||||
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
|
||||
onAction={handlePlaylistMenuAction}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}
|
||||
}, [
|
||||
canEdit,
|
||||
colors.foreground,
|
||||
deletePlaylist,
|
||||
handlePlaylistDetailAction,
|
||||
palette.foreground,
|
||||
palette.isDark,
|
||||
playlistId,
|
||||
playlist?.title,
|
||||
router,
|
||||
songIds,
|
||||
])
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
|
||||
<PlaylistSongRow
|
||||
song={song}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
removable={canEdit}
|
||||
palette={palette}
|
||||
swipeGroup={swipeGroup}
|
||||
onPlay={handlePlaySong}
|
||||
onAction={handleSongMenuAction}
|
||||
onRemove={handleRemoveSong}
|
||||
/>
|
||||
),
|
||||
[
|
||||
canEdit,
|
||||
handlePlaySong,
|
||||
handleRemoveSong,
|
||||
handleSongMenuAction,
|
||||
isSongFavorite,
|
||||
palette,
|
||||
swipeGroup,
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{isFocused ? (
|
||||
<StatusBar style={palette.isDark ? "light" : "dark"} />
|
||||
) : null}
|
||||
<Stack.Screen options={screenOptions} />
|
||||
<PlaylistSearchBar
|
||||
onQueryChange={onQueryChange}
|
||||
onSearchSubmit={onSearchSubmit}
|
||||
/>
|
||||
<Animated.FlatList
|
||||
onLayout={onLayout}
|
||||
{...longListProps}
|
||||
data={filteredSongs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
style={[
|
||||
{ flex: 1, backgroundColor: palette.background },
|
||||
backgroundStyle,
|
||||
]}
|
||||
indicatorStyle={palette.isDark ? "white" : "black"}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onScrollBeginDrag={swipeGroup.closeOpenRow}
|
||||
ListEmptyComponent={
|
||||
<Text
|
||||
style={[
|
||||
styles.emptyResults,
|
||||
{ color: palette.secondaryForeground },
|
||||
]}
|
||||
>
|
||||
{songs.length ? "No songs found." : "No songs in this playlist."}
|
||||
</Text>
|
||||
}
|
||||
ListHeaderComponent={
|
||||
<PlaylistHero
|
||||
entityId={playlistId ?? "otunes:favorites"}
|
||||
coverUri={coverUri}
|
||||
hasCover={playlist.cover != null}
|
||||
title={playlist.title}
|
||||
ownerName={playlist.owner.name}
|
||||
palette={palette}
|
||||
isSubscribed={isSubscribed}
|
||||
showSubscribe={!playlist.isOwner && playlistId !== null}
|
||||
onSubscribeToggle={handleSubscribeToggle}
|
||||
onPlay={handlePlay}
|
||||
onShuffle={handleShuffle}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function songKey(song: BrowseSong) {
|
||||
return song.id
|
||||
}
|
||||
|
||||
const PlaylistSongRow = memo(function PlaylistSongRow({
|
||||
song,
|
||||
favorited,
|
||||
removable,
|
||||
palette,
|
||||
swipeGroup,
|
||||
onPlay,
|
||||
onAction,
|
||||
onRemove,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
favorited: boolean
|
||||
removable: boolean
|
||||
palette: CoverPalette
|
||||
swipeGroup: SwipeRowGroup
|
||||
onPlay: (song: BrowseSong) => void
|
||||
onAction: (song: BrowseSong, action: MediaAction) => void
|
||||
onRemove: (songId: Id<"songs">) => Promise<boolean>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const handleRemove = useCallback(() => onRemove(song.id), [onRemove, song.id])
|
||||
const row = (
|
||||
<SongListRow
|
||||
song={song}
|
||||
favorited={favorited}
|
||||
playlistLabel={PLAYLIST_LABEL}
|
||||
palette={palette}
|
||||
inset
|
||||
removable={removable}
|
||||
swipe={
|
||||
Platform.OS !== "web"
|
||||
? {
|
||||
group: swipeGroup,
|
||||
backgroundColor: palette.background,
|
||||
onPlayNext: () => onAction(song, "play-next"),
|
||||
onAddToQueue: () => onAction(song, "play-last"),
|
||||
onRemove: removable ? () => void handleRemove() : undefined,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onPlay={onPlay}
|
||||
onAction={onAction}
|
||||
/>
|
||||
)
|
||||
|
||||
if (Platform.OS !== "web" || !removable) {
|
||||
return row
|
||||
}
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
friction={2}
|
||||
rightThreshold={56}
|
||||
overshootRight={false}
|
||||
enableTrackpadTwoFingerGesture
|
||||
containerStyle={{ backgroundColor: colors.destructive }}
|
||||
childrenContainerStyle={{ backgroundColor: palette.background }}
|
||||
renderRightActions={(_progress, _translation, swipeable) => (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Remove ${song.title} from playlist`}
|
||||
onPress={() => {
|
||||
swipeable.close()
|
||||
void handleRemove()
|
||||
}}
|
||||
style={[styles.removeAction, { backgroundColor: colors.destructive }]}
|
||||
>
|
||||
<Ionicons name="trash" size={22} color={colors.primaryForeground} />
|
||||
<Text
|
||||
style={[
|
||||
styles.removeActionText,
|
||||
{ color: colors.primaryForeground },
|
||||
]}
|
||||
>
|
||||
Remove
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
>
|
||||
{row}
|
||||
</ReanimatedSwipeable>
|
||||
)
|
||||
})
|
||||
|
||||
const PlaylistHero = memo(function PlaylistHero({
|
||||
entityId,
|
||||
coverUri,
|
||||
hasCover,
|
||||
title,
|
||||
ownerName,
|
||||
palette,
|
||||
isSubscribed,
|
||||
showSubscribe = false,
|
||||
onSubscribeToggle,
|
||||
onPlay,
|
||||
onShuffle,
|
||||
}: {
|
||||
entityId: string
|
||||
coverUri: string
|
||||
hasCover: boolean
|
||||
title: string
|
||||
ownerName: string
|
||||
palette: CoverPalette
|
||||
isSubscribed?: boolean
|
||||
showSubscribe?: boolean
|
||||
onSubscribeToggle?: () => void
|
||||
onPlay: () => void
|
||||
onShuffle: () => void
|
||||
}) {
|
||||
const heroLayout = useCollectionHeroLayout()
|
||||
return (
|
||||
<MusicEntityView kind="playlist" id={entityId}>
|
||||
<CollectionHero
|
||||
artwork={
|
||||
<Link.AppleZoomTarget>
|
||||
<View collapsable={false}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
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" },
|
||||
]}
|
||||
>
|
||||
{showSubscribe ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
|
||||
accessibilityState={{ selected: isSubscribed }}
|
||||
hitSlop={8}
|
||||
onPress={onSubscribeToggle}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{
|
||||
backgroundColor: isSubscribed
|
||||
? palette.surface
|
||||
: palette.accent,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isSubscribed ? "checkmark" : "add"}
|
||||
size={24}
|
||||
color={
|
||||
isSubscribed ? palette.foreground : palette.accentForeground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={onPlay}
|
||||
style={styles.playButton}
|
||||
tint={{
|
||||
background: palette.accent,
|
||||
foreground: palette.accentForeground,
|
||||
}}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={onShuffle}
|
||||
style={[styles.iconAction, { backgroundColor: palette.surface }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={palette.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.title,
|
||||
heroLayout.landscape && styles.titleLandscape,
|
||||
{ color: palette.foreground },
|
||||
]}
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
<Text
|
||||
style={{
|
||||
color: palette.foreground,
|
||||
fontSize: heroLayout.landscape ? 22 : 16,
|
||||
}}
|
||||
>
|
||||
{ownerName}
|
||||
</Text>
|
||||
</CollectionHero>
|
||||
<CollectionDivider color={palette.divider} />
|
||||
</MusicEntityView>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
emptyResults: { padding: spacing.lg, textAlign: "center" },
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
cover: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
borderRadius: radius.lg,
|
||||
},
|
||||
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
|
||||
titleLandscape: { textAlign: "left", fontSize: 22 },
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.sm,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
playButton: { borderRadius: 999, minWidth: 160 },
|
||||
iconAction: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 22,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
removeAction: {
|
||||
width: 96,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
removeActionText: {
|
||||
fontSize: 12,
|
||||
fontWeight: "600",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
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, SongListRow } from "@/components/player"
|
||||
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 }
|
||||
|
||||
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 { filteredSongs, onQueryChange, onSearchSubmit } =
|
||||
usePlaylistSearch(songs)
|
||||
|
||||
useEffect(() => {
|
||||
rememberSongs(songs)
|
||||
}, [songs])
|
||||
|
||||
const handlePlaySong = useCallback(
|
||||
(song: BrowseSong) => void playFromSong(song.id, songIds),
|
||||
[playFromSong, songIds]
|
||||
)
|
||||
const handleSongMenuAction = useCallback(
|
||||
(song: BrowseSong, action: MediaAction) =>
|
||||
void handleSongAction(song, action),
|
||||
[handleSongAction]
|
||||
)
|
||||
const handlePlay = useCallback(
|
||||
() => void playInOrder(songIds),
|
||||
[playInOrder, songIds]
|
||||
)
|
||||
const handleShuffle = useCallback(
|
||||
() => void playShuffled(songIds),
|
||||
[playShuffled, songIds]
|
||||
)
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
|
||||
<SongListRow
|
||||
song={song}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
playlistLabel="Add to Another Playlist"
|
||||
inset
|
||||
onPlay={handlePlaySong}
|
||||
onAction={handleSongMenuAction}
|
||||
/>
|
||||
),
|
||||
[handlePlaySong, handleSongMenuAction, isSongFavorite]
|
||||
)
|
||||
|
||||
if (favorites === undefined || !config) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<CollectionDetailSkeleton variant="favorites" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (favorites === null) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<View style={[styles.empty, { backgroundColor: colors.background }]}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Sign in to view your favorites.
|
||||
</Text>
|
||||
</View>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<PlaylistSearchBar
|
||||
onQueryChange={onQueryChange}
|
||||
onSearchSubmit={onSearchSubmit}
|
||||
/>
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={filteredSongs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
ListEmptyComponent={
|
||||
<Text
|
||||
style={[styles.emptyResults, { color: colors.mutedForeground }]}
|
||||
>
|
||||
{songs.length ? "No songs found." : "No songs in this playlist."}
|
||||
</Text>
|
||||
}
|
||||
ListHeaderComponent={
|
||||
<FavoritesHero
|
||||
title={favorites.title}
|
||||
onPlay={handlePlay}
|
||||
onShuffle={handleShuffle}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function songKey(song: BrowseSong) {
|
||||
return song.id
|
||||
}
|
||||
|
||||
const FavoritesHero = memo(function FavoritesHero({
|
||||
title,
|
||||
onPlay,
|
||||
onShuffle,
|
||||
}: {
|
||||
title: string
|
||||
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>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={onPlay}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={onShuffle}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</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",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.sm,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
playButton: { borderRadius: 999, minWidth: 160 },
|
||||
iconAction: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 22,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const PAGE_SIZE = 16
|
||||
|
||||
export default function RecentlyAddedScreen() {
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
api.library.browseRecentlyAddedPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return <MediaGridSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<MediaGridList
|
||||
content={results}
|
||||
paddingBottom={contentBottomInset}
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function RecentlyPlayedScreen() {
|
||||
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||
api.library.browseRecentlyPlayedPaginated,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return <MediaGridSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<MediaGridList
|
||||
content={results}
|
||||
paddingBottom={contentBottomInset}
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
import { atmosEnabled, 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 { useState } from "react"
|
||||
import { router } from "expo-router"
|
||||
import {
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Switch,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native"
|
||||
import type { StyleProp, ViewStyle } from "react-native"
|
||||
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
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 { 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 } 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 CurrentUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
image?: string
|
||||
email: string
|
||||
isAdmin?: boolean
|
||||
playbackQuality?: PlaybackQuality
|
||||
preferAtmos?: boolean
|
||||
}
|
||||
|
||||
type AdminUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
email: string
|
||||
isAdmin?: boolean
|
||||
}
|
||||
|
||||
type SectionConfig = {
|
||||
id: Section
|
||||
label: string
|
||||
icon: React.ComponentProps<typeof Ionicons>["name"]
|
||||
admin?: boolean
|
||||
}
|
||||
|
||||
const QUALITY_OPTIONS: {
|
||||
value: PlaybackQuality
|
||||
label: string
|
||||
description: string
|
||||
}[] = [
|
||||
{ value: "low", label: "Low", description: "AAC 64kb/s" },
|
||||
{ value: "medium", label: "Medium", description: "AAC 128kb/s" },
|
||||
{ value: "high", label: "High", description: "AAC 256kb/s" },
|
||||
{ value: "lossless", label: "Lossless", description: "ALAC or FLAC" },
|
||||
]
|
||||
|
||||
const SECTIONS: SectionConfig[] = [
|
||||
{ id: "profile", label: "Profile", icon: "person-circle-outline" },
|
||||
{ id: "quality", label: "Playback", icon: "volume-high-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 user = useCachedQuery(api.auth.currentUser)
|
||||
const { invalidateSession } = useInvalidateAuthSession()
|
||||
const { clearServer } = useServerConfig()
|
||||
const [section, setSection] = useState<Section>("profile")
|
||||
const allUsers = useQuery(
|
||||
api.users.listUsers,
|
||||
user?.isAdmin === true && section === "users" ? {} : "skip"
|
||||
)
|
||||
|
||||
if (!user) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
const isAdmin = user.isAdmin === true
|
||||
const visibleSections = SECTIONS.filter((item) => !item.admin || isAdmin)
|
||||
|
||||
async function handleSignOut() {
|
||||
try {
|
||||
await signOut(invalidateSession)
|
||||
} catch {
|
||||
showError("Could not clear all local data.")
|
||||
}
|
||||
}
|
||||
|
||||
async function handleChangeServer() {
|
||||
try {
|
||||
await changeServer(invalidateSession, clearServer)
|
||||
} catch {
|
||||
showError("Could not clear all local data.")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={[
|
||||
styles.container,
|
||||
{ paddingBottom: contentBottomInset + spacing.xl },
|
||||
]}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
>
|
||||
<View style={[styles.pillGroup, { backgroundColor: colors.card }]}>
|
||||
{visibleSections.map((item) => {
|
||||
const selected = section === item.id
|
||||
return (
|
||||
<Pressable
|
||||
key={item.id}
|
||||
accessibilityLabel={item.label}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
onPress={() => setSection(item.id)}
|
||||
style={[
|
||||
styles.pill,
|
||||
{ backgroundColor: selected ? colors.primary : "transparent" },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={item.icon}
|
||||
size={26}
|
||||
color={
|
||||
selected ? colors.primaryForeground : colors.mutedForeground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
|
||||
{section === "profile" ? (
|
||||
<>
|
||||
<AppearanceSection />
|
||||
<ProfileSection user={user} />
|
||||
</>
|
||||
) : null}
|
||||
{section === "quality" ? <QualitySection user={user} /> : null}
|
||||
{section === "library" && isAdmin ? <LibrarySection /> : null}
|
||||
{section === "users" && isAdmin && allUsers ? (
|
||||
<UsersSection users={allUsers} currentUserId={user._id} />
|
||||
) : null}
|
||||
|
||||
{section === "profile" ? (
|
||||
<SessionSection
|
||||
onChangeServer={() => void handleChangeServer()}
|
||||
onSignOut={() => void handleSignOut()}
|
||||
/>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
)
|
||||
}
|
||||
|
||||
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)
|
||||
const updateEmail = useMutation(api.users.updateProfileEmail)
|
||||
const updateImage = useMutation(api.users.updateProfileImage)
|
||||
const updatePassword = useAction(api.users.updateOwnPassword)
|
||||
const [name, setName] = useState(user.name)
|
||||
const [email, setEmail] = useState(user.email)
|
||||
const [newPassword, setNewPassword] = useState("")
|
||||
const [confirmPassword, setConfirmPassword] = useState("")
|
||||
const [changingPassword, setChangingPassword] = useState(false)
|
||||
|
||||
async function pickImage() {
|
||||
const result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
quality: 0.8,
|
||||
base64: true,
|
||||
})
|
||||
if (result.canceled || !result.assets[0]?.base64) return
|
||||
|
||||
const mime = result.assets[0].mimeType ?? "image/jpeg"
|
||||
try {
|
||||
await updateImage({
|
||||
image: `data:${mime};base64,${result.assets[0].base64}`,
|
||||
})
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update photo"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeImage() {
|
||||
try {
|
||||
await updateImage({ image: null })
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to remove photo"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePasswordChange() {
|
||||
if (newPassword !== confirmPassword) {
|
||||
showError("Passwords do not match")
|
||||
return
|
||||
}
|
||||
|
||||
setChangingPassword(true)
|
||||
try {
|
||||
await updatePassword({ newPassword })
|
||||
setNewPassword("")
|
||||
setConfirmPassword("")
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update password"
|
||||
)
|
||||
} finally {
|
||||
setChangingPassword(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsCard
|
||||
title="Profile Photo"
|
||||
subtitle="This is the avatar shown in the app header and shared spaces."
|
||||
>
|
||||
<View style={styles.photoRow}>
|
||||
<ProfileAvatar user={user} size={76} />
|
||||
<View style={styles.photoActions}>
|
||||
<Button
|
||||
title="Choose Photo"
|
||||
variant="secondary"
|
||||
icon="image-outline"
|
||||
onPress={() => void pickImage()}
|
||||
/>
|
||||
{user.image ? (
|
||||
<Button
|
||||
title="Remove"
|
||||
variant="ghost"
|
||||
icon="trash-outline"
|
||||
onPress={() => void removeImage()}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard
|
||||
title="Account Details"
|
||||
subtitle="Keep your profile information up to date."
|
||||
>
|
||||
<Field label="Name">
|
||||
<Input value={name} onChangeText={setName} placeholder="Name" />
|
||||
</Field>
|
||||
<Button
|
||||
title="Save Name"
|
||||
variant="secondary"
|
||||
disabled={name.trim() === user.name}
|
||||
onPress={() =>
|
||||
void updateName({ name: name.trim() }).catch((error: Error) =>
|
||||
showError(error.message)
|
||||
)
|
||||
}
|
||||
/>
|
||||
<View style={[styles.divider, { backgroundColor: colors.border }]} />
|
||||
<Field label="Email">
|
||||
<Input
|
||||
value={email}
|
||||
onChangeText={setEmail}
|
||||
placeholder="Email"
|
||||
autoCapitalize="none"
|
||||
keyboardType="email-address"
|
||||
/>
|
||||
</Field>
|
||||
<Button
|
||||
title="Save Email"
|
||||
variant="secondary"
|
||||
disabled={email.trim() === user.email}
|
||||
onPress={() =>
|
||||
void updateEmail({ email: email.trim() }).catch((error: Error) =>
|
||||
showError(error.message)
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard
|
||||
title="Password"
|
||||
subtitle="Choose a new password for this account."
|
||||
>
|
||||
<Field label="New Password">
|
||||
<Input
|
||||
value={newPassword}
|
||||
onChangeText={setNewPassword}
|
||||
placeholder="New password"
|
||||
secureTextEntry
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Confirm Password">
|
||||
<Input
|
||||
value={confirmPassword}
|
||||
onChangeText={setConfirmPassword}
|
||||
placeholder="Confirm password"
|
||||
secureTextEntry
|
||||
/>
|
||||
</Field>
|
||||
<Button
|
||||
title="Update Password"
|
||||
loading={changingPassword}
|
||||
disabled={!newPassword || newPassword !== confirmPassword}
|
||||
onPress={() => void handlePasswordChange()}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function QualitySection({ user }: { user: CurrentUser }) {
|
||||
const colors = useThemeColors()
|
||||
const updateQuality = useMutation(api.users.updatePlaybackQuality)
|
||||
const updateAtmos = useMutation(api.users.updatePreferAtmos)
|
||||
const quality = user.playbackQuality ?? "medium"
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsCard
|
||||
title="Streaming Quality"
|
||||
subtitle="Pick the default audio quality for playback."
|
||||
>
|
||||
{QUALITY_OPTIONS.map((option) => {
|
||||
const selected = quality === option.value
|
||||
return (
|
||||
<Pressable
|
||||
key={option.value}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
onPress={() =>
|
||||
void updateQuality({ playbackQuality: option.value }).catch(
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
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.description}
|
||||
</Text>
|
||||
</View>
|
||||
{selected ? (
|
||||
<Ionicons
|
||||
name="checkmark-circle"
|
||||
size={22}
|
||||
color={colors.primary}
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
)
|
||||
})}
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard title="Spatial Audio">
|
||||
<SwitchRow
|
||||
title="Prefer Dolby Atmos"
|
||||
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)
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function LibrarySection() {
|
||||
const updateLibrary = useAction(api.actions.updateLibrary)
|
||||
const cleanupHlsStreams = useAction(api.actions.adminCleanupHlsStreams)
|
||||
const [updating, setUpdating] = useState(false)
|
||||
const [cleaningHls, setCleaningHls] = useState(false)
|
||||
|
||||
return (
|
||||
<SettingsCard
|
||||
title="Library Maintenance"
|
||||
subtitle="Run administrative jobs for the shared music library."
|
||||
>
|
||||
<Button
|
||||
title="Update Library"
|
||||
icon="refresh-outline"
|
||||
loading={updating}
|
||||
onPress={async () => {
|
||||
setUpdating(true)
|
||||
try {
|
||||
await updateLibrary({})
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to update library"
|
||||
)
|
||||
} finally {
|
||||
setUpdating(false)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
title="Clean HLS Streams"
|
||||
variant="secondary"
|
||||
icon="sparkles-outline"
|
||||
loading={cleaningHls}
|
||||
onPress={async () => {
|
||||
setCleaningHls(true)
|
||||
try {
|
||||
await cleanupHlsStreams({})
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to clean HLS streams"
|
||||
)
|
||||
} finally {
|
||||
setCleaningHls(false)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
|
||||
function UsersSection({
|
||||
users,
|
||||
currentUserId,
|
||||
}: {
|
||||
users: AdminUser[]
|
||||
currentUserId: Id<"users">
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const appSettings = useQuery(api.users.getAppSettings)
|
||||
const setDisableCreation = useMutation(api.users.setDisableAccountCreation)
|
||||
const setAdmin = useMutation(api.users.setUserAdmin)
|
||||
const deleteUserMutation = useMutation(api.users.deleteUser)
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsCard title="Sign Up">
|
||||
<SwitchRow
|
||||
title="Disable account creation"
|
||||
subtitle="Stop people from registering themselves. Admins can still create accounts."
|
||||
value={appSettings?.disableAccountCreation ?? false}
|
||||
onValueChange={(checked) =>
|
||||
void setDisableCreation({ disabled: checked }).catch(
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard
|
||||
title="People"
|
||||
subtitle="Manage who can access this server."
|
||||
>
|
||||
<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}
|
||||
>
|
||||
{user.name}
|
||||
</Text>
|
||||
{user.isAdmin ? (
|
||||
<View
|
||||
style={[
|
||||
styles.badge,
|
||||
{ backgroundColor: colors.muted },
|
||||
]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.badgeText,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
Admin
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<Text
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.email}
|
||||
</Text>
|
||||
</View>
|
||||
</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>
|
||||
))}
|
||||
</View>
|
||||
</SettingsCard>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function SessionSection({
|
||||
onChangeServer,
|
||||
onSignOut,
|
||||
}: {
|
||||
onChangeServer: () => void
|
||||
onSignOut: () => void
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<SettingsCard title="Session">
|
||||
<ActionRow
|
||||
icon="server-outline"
|
||||
title="Change Server"
|
||||
subtitle="Disconnect from this server and choose another."
|
||||
onPress={onChangeServer}
|
||||
/>
|
||||
<View style={[styles.divider, { backgroundColor: colors.border }]} />
|
||||
<ActionRow
|
||||
icon="log-out-outline"
|
||||
title="Sign Out"
|
||||
subtitle="Return to the sign-in screen."
|
||||
destructive
|
||||
onPress={onSignOut}
|
||||
/>
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
|
||||
function SettingsCard({
|
||||
title,
|
||||
subtitle,
|
||||
children,
|
||||
}: {
|
||||
title: string
|
||||
subtitle?: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<View style={[styles.card, { backgroundColor: colors.card }]}>
|
||||
<View style={styles.cardHeader}>
|
||||
<Text style={[styles.cardTitle, { color: colors.foreground }]}>
|
||||
{title}
|
||||
</Text>
|
||||
{subtitle ? (
|
||||
<Text
|
||||
style={[styles.cardSubtitle, { color: colors.mutedForeground }]}
|
||||
>
|
||||
{subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<View style={styles.field}>
|
||||
<Text style={[styles.fieldLabel, { color: colors.mutedForeground }]}>
|
||||
{label}
|
||||
</Text>
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function SwitchRow({
|
||||
title,
|
||||
subtitle,
|
||||
value,
|
||||
onValueChange,
|
||||
disabled,
|
||||
}: {
|
||||
title: string
|
||||
subtitle?: string
|
||||
value: boolean
|
||||
disabled?: boolean
|
||||
onValueChange: (checked: boolean) => void
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<View style={styles.switchRow}>
|
||||
<View style={styles.optionCopy}>
|
||||
<Text style={[styles.optionTitle, { color: colors.foreground }]}>
|
||||
{title}
|
||||
</Text>
|
||||
{subtitle ? (
|
||||
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Switch
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onValueChange={onValueChange}
|
||||
{...(Platform.OS === "android"
|
||||
? {
|
||||
trackColor: { false: colors.muted, true: colors.primary },
|
||||
thumbColor: colors.foreground,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function ActionRow({
|
||||
icon,
|
||||
title,
|
||||
subtitle,
|
||||
destructive,
|
||||
onPress,
|
||||
}: {
|
||||
icon: React.ComponentProps<typeof Ionicons>["name"]
|
||||
title: string
|
||||
subtitle: string
|
||||
destructive?: boolean
|
||||
onPress: () => void
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const tint = destructive ? colors.destructive : colors.foreground
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [
|
||||
styles.actionRow,
|
||||
{ opacity: pressed ? 0.75 : 1 },
|
||||
]}
|
||||
>
|
||||
<View style={[styles.actionIcon, { backgroundColor: colors.muted }]}>
|
||||
<Ionicons name={icon} size={20} color={tint} />
|
||||
</View>
|
||||
<View style={styles.optionCopy}>
|
||||
<Text style={[styles.optionTitle, { color: tint }]}>{title}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
|
||||
</View>
|
||||
<Ionicons
|
||||
name="chevron-forward"
|
||||
size={18}
|
||||
color={colors.mutedForeground}
|
||||
/>
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
function ProfileAvatar({
|
||||
user,
|
||||
size,
|
||||
style,
|
||||
}: {
|
||||
user: Pick<CurrentUser, "name" | "image">
|
||||
size: number
|
||||
style?: StyleProp<ViewStyle>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const imageUrl = useProfileImageUrl(user.image)
|
||||
const avatarStyle = [
|
||||
styles.avatar,
|
||||
{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: size / 2,
|
||||
backgroundColor: colors.muted,
|
||||
},
|
||||
style,
|
||||
]
|
||||
|
||||
if (imageUrl) {
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Image
|
||||
source={{ uri: imageUrl }}
|
||||
style={styles.avatarImage}
|
||||
contentFit="cover"
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Text
|
||||
style={[
|
||||
styles.avatarInitials,
|
||||
{ color: colors.foreground, fontSize: size * 0.34 },
|
||||
]}
|
||||
>
|
||||
{initialsFromName(user.name)}
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
gap: spacing.lg,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingTop: spacing.md,
|
||||
},
|
||||
badge: {
|
||||
alignSelf: "flex-start",
|
||||
borderRadius: radius.full,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 2,
|
||||
},
|
||||
badgeText: {
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
},
|
||||
pillGroup: {
|
||||
borderRadius: radius.xl,
|
||||
padding: spacing.xs,
|
||||
flexDirection: "row",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
pill: {
|
||||
flex: 1,
|
||||
minHeight: 48,
|
||||
borderRadius: radius.full,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
card: {
|
||||
borderRadius: radius.xl,
|
||||
padding: spacing.lg,
|
||||
gap: spacing.md,
|
||||
},
|
||||
cardHeader: {
|
||||
gap: spacing.xs,
|
||||
},
|
||||
cardTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: "800",
|
||||
},
|
||||
cardSubtitle: {
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
},
|
||||
photoRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.lg,
|
||||
},
|
||||
photoActions: {
|
||||
flex: 1,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
field: {
|
||||
gap: spacing.sm,
|
||||
},
|
||||
fieldLabel: {
|
||||
fontSize: 13,
|
||||
fontWeight: "700",
|
||||
textTransform: "uppercase",
|
||||
},
|
||||
divider: {
|
||||
height: StyleSheet.hairlineWidth,
|
||||
},
|
||||
optionRow: {
|
||||
borderWidth: 1,
|
||||
borderRadius: radius.lg,
|
||||
padding: spacing.md,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
},
|
||||
optionCopy: {
|
||||
flex: 1,
|
||||
gap: 3,
|
||||
},
|
||||
optionTitle: {
|
||||
fontSize: 16,
|
||||
fontWeight: "700",
|
||||
},
|
||||
switchRow: {
|
||||
minHeight: 56,
|
||||
flexDirection: "row",
|
||||
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",
|
||||
gap: spacing.md,
|
||||
},
|
||||
userCopy: {
|
||||
flex: 1,
|
||||
gap: 3,
|
||||
},
|
||||
userNameRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
userName: {
|
||||
flexShrink: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: "700",
|
||||
},
|
||||
userActions: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.sm,
|
||||
},
|
||||
userActionButton: {
|
||||
flex: 1,
|
||||
},
|
||||
actionRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
},
|
||||
actionIcon: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
avatar: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
avatarImage: {
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
},
|
||||
avatarInitials: {
|
||||
fontWeight: "800",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useTabletLayout } from "@/hooks/use-tablet-layout"
|
||||
import { renderTabScreenContent } from "@/components/tab-screen-content"
|
||||
import { Stack } from "expo-router"
|
||||
|
||||
import { ProfileHeaderButton } from "@/components/profile-header-button"
|
||||
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
}
|
||||
|
||||
export default function LibraryLayout() {
|
||||
const tabletLayout = useTabletLayout()
|
||||
const baseOptions = useStackScreenOptions({ title: "Library" })
|
||||
|
||||
return (
|
||||
<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,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/album/[id]"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/artist/[id]"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/albums"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/artists"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/playlists"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/songs"
|
||||
@@ -0,0 +1,165 @@
|
||||
import { useTabletLayout } from "@/hooks/use-tablet-layout"
|
||||
import { useMemo } from "react"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { SymbolView } from "expo-symbols"
|
||||
import { Platform } from "react-native"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
const PAGE_SIZE = 24
|
||||
|
||||
const links = [
|
||||
{
|
||||
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: "Favorites", href: "/playlist/favorites", icon: "star" as const },
|
||||
]
|
||||
|
||||
function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
|
||||
if (Platform.OS === "ios") {
|
||||
return (
|
||||
<SymbolView
|
||||
name={name}
|
||||
size={22}
|
||||
tintColor={appleMusic.pink}
|
||||
weight="semibold"
|
||||
/>
|
||||
)
|
||||
}
|
||||
const ionMap: Record<string, keyof typeof Ionicons.glyphMap> = {
|
||||
"music.note.list": "list",
|
||||
"mic.fill": "mic",
|
||||
"square.stack": "albums",
|
||||
"music.note": "musical-notes",
|
||||
clock: "time",
|
||||
sparkles: "sparkles",
|
||||
star: "star",
|
||||
}
|
||||
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,
|
||||
{},
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
const listHeader = useMemo(
|
||||
() => (
|
||||
<View>
|
||||
{!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>
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
),
|
||||
[colors.border, colors.foreground, colors.mutedForeground, push, isTablet]
|
||||
)
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return <MediaGridSkeleton contentInset={false} header={listHeader} />
|
||||
}
|
||||
|
||||
return (
|
||||
<MediaGridList
|
||||
content={results}
|
||||
paddingBottom={tabContentBottomInset}
|
||||
contentInset={false}
|
||||
ListHeaderComponent={listHeader}
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
paddingHorizontal: spacing.lg,
|
||||
},
|
||||
rowContent: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
paddingVertical: 14,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
rowTitle: {
|
||||
flex: 1,
|
||||
fontSize: 20,
|
||||
fontWeight: "400",
|
||||
},
|
||||
section: {
|
||||
paddingTop: spacing.xl,
|
||||
paddingBottom: spacing.md,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 22,
|
||||
fontWeight: "700",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/playlist/[id]"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/playlist/favorites"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../home/recently-added"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../home/recently-played"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../home/settings"
|
||||
@@ -0,0 +1,35 @@
|
||||
import { renderTabScreenContent } from "@/components/tab-screen-content"
|
||||
import { Stack } from "expo-router"
|
||||
|
||||
import { ProfileHeaderButton } from "@/components/profile-header-button"
|
||||
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
}
|
||||
|
||||
export default function SearchLayout() {
|
||||
const baseOptions = useStackScreenOptions({ title: "Search" })
|
||||
|
||||
return (
|
||||
<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,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/album/[id]"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/artist/[id]"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/albums"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/artists"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/browse/songs"
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Platform } from "react-native"
|
||||
import { useThemeColors } from "@/lib/theme"
|
||||
import { Stack } from "expo-router"
|
||||
import { useCallback } from "react"
|
||||
|
||||
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(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
onQueryChange(event.nativeEvent.text)
|
||||
},
|
||||
[onQueryChange]
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.SearchBar
|
||||
placeholder="Artists, Albums, Songs, and More"
|
||||
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} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/playlist/[id]"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../../home/playlist/favorites"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../home/recently-added"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../home/recently-played"
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from "../home/settings"
|
||||
@@ -0,0 +1,144 @@
|
||||
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 { Stack } from "expo-router"
|
||||
import { Platform } from "react-native"
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
import { AppIntentBridge } from "@/components/app-intent-bridge"
|
||||
import { ConvexAuthRecovery } from "@/components/convex-auth-recovery"
|
||||
import { AddToPlaylistProvider } from "@/contexts/add-to-playlist"
|
||||
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
|
||||
import { FavoritesProvider } from "@/contexts/favorites"
|
||||
import { PlaybackProvider } from "@/contexts/playback"
|
||||
import { useStackScreenOptions } from "@/lib/navigation"
|
||||
import { AppNavigationSync } from "@/lib/app-navigation"
|
||||
|
||||
const AUTH_HANDSHAKE_TIMEOUT_MS = 15_000
|
||||
|
||||
export default function AppLayout() {
|
||||
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 (
|
||||
!localAuth?.isAuthenticated ||
|
||||
serverAuth?.isAuthenticated ||
|
||||
!isWebSocketConnected
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Only a reachable server that never accepts the session counts as a
|
||||
// failed handshake; offline launches keep the session and cached data.
|
||||
const timer = setTimeout(() => {
|
||||
void invalidateSession()
|
||||
}, AUTH_HANDSHAKE_TIMEOUT_MS)
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}, [
|
||||
invalidateSession,
|
||||
isWebSocketConnected,
|
||||
localAuth?.isAuthenticated,
|
||||
serverAuth?.isAuthenticated,
|
||||
])
|
||||
|
||||
// Convex holds queries until the stored token is confirmed, so the app can
|
||||
// render cached data while the server handshake is still in progress.
|
||||
|
||||
return (
|
||||
<ConvexAuthRecovery onInvalidate={invalidateSession}>
|
||||
<PlaybackProvider>
|
||||
<AppNavigationSync />
|
||||
<AddToPlaylistProvider>
|
||||
<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>
|
||||
</AddToPlaylistProvider>
|
||||
</PlaybackProvider>
|
||||
</ConvexAuthRecovery>
|
||||
)
|
||||
}
|
||||
@@ -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 },
|
||||
})
|
||||
@@ -0,0 +1,783 @@
|
||||
import { useTabletLayout } from "@/hooks/use-tablet-layout"
|
||||
import { TabletNowPlaying } from "@/components/tablet-now-playing"
|
||||
import { atmosEnabled } from "@/lib/playback-capabilities"
|
||||
import { NavigationBar } from "expo-navigation-bar"
|
||||
import { MusicEntityView } from "@/components/music-entity-view"
|
||||
import { Stack, useRouter, useLocalSearchParams } from "expo-router"
|
||||
import * as Haptics from "expo-haptics"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler"
|
||||
import {
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native"
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeOut,
|
||||
interpolate,
|
||||
LayoutAnimationConfig,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withSpring,
|
||||
withTiming,
|
||||
} from "react-native-reanimated"
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context"
|
||||
import { scheduleOnRN } from "react-native-worklets"
|
||||
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { playbackFormat } from "@otunes/convex/playback-stream"
|
||||
|
||||
import { AudioFormatBadge } from "@/components/audio-format-badge"
|
||||
import { AudioOutputButton } from "@/components/audio-output-button"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { MarqueeText } from "@/components/marquee-text"
|
||||
import {
|
||||
MediaActionMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import {
|
||||
NowPlayingQueue,
|
||||
QUEUE_HORIZONTAL_INSET,
|
||||
} from "@/components/now-playing-queue"
|
||||
import { PlayerArtistMenu } from "@/components/player-artist-menu"
|
||||
import { PlayerProgress } from "@/components/player-progress"
|
||||
import { PlayerSlider } from "@/components/player-slider"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { useSystemVolume } from "@/hooks/use-system-volume"
|
||||
import {
|
||||
nowPlayingColors,
|
||||
type NowPlayingColors,
|
||||
} from "@/lib/now-playing-colors"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
import { radius, spacing } from "@/lib/theme"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
|
||||
const HORIZONTAL_INSET = QUEUE_HORIZONTAL_INSET
|
||||
const META_HEIGHT = 64
|
||||
const PAUSED_ARTWORK_SCALE = 0.77
|
||||
const ARTWORK_SPRING = { duration: 550, dampingRatio: 0.72 }
|
||||
const BACKGROUND_FADE = { duration: 450 }
|
||||
const MODE_FADE_IN = FadeIn.duration(220)
|
||||
const MODE_FADE_OUT = FadeOut.duration(140)
|
||||
const DISMISS_DISTANCE = 140
|
||||
const DISMISS_VELOCITY = 900
|
||||
const DISMISS_CORNER_RADIUS = 48
|
||||
|
||||
export default function PlayerScreen() {
|
||||
const tabletLayout = useTabletLayout()
|
||||
const router = useRouter()
|
||||
const hadSongRef = useRef(false)
|
||||
const insets = useSafeAreaInsets()
|
||||
const { width: windowWidth, height: windowHeight } = useWindowDimensions()
|
||||
// Unfolded iPhones retain the phone idiom but have room for the iPad player.
|
||||
const isTablet =
|
||||
tabletLayout ||
|
||||
(Platform.OS === "ios" && Math.min(windowWidth, windowHeight) >= 600)
|
||||
const { config } = useServerConfig()
|
||||
const {
|
||||
currentSong,
|
||||
isPlaying,
|
||||
shuffleEnabled,
|
||||
repeatEnabled,
|
||||
queueSongIds,
|
||||
} = usePlaybackQueue()
|
||||
const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions()
|
||||
const { queue } = useLocalSearchParams<{ queue?: string }>()
|
||||
const [showQueue, setShowQueue] = useState(queue === "1")
|
||||
const [isDismissing, setIsDismissing] = useState(false)
|
||||
const [stageHeight, setStageHeight] = useState(0)
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const playbackInfo = useCachedQuery(
|
||||
api.library.getSongPlaybackInfo,
|
||||
currentSong ? { id: currentSong.id } : "skip"
|
||||
)
|
||||
const format =
|
||||
user && playbackInfo
|
||||
? playbackFormat(
|
||||
playbackInfo.files,
|
||||
user.playbackQuality,
|
||||
atmosEnabled(user)
|
||||
)
|
||||
: null
|
||||
|
||||
const coverUri =
|
||||
currentSong && config
|
||||
? albumCoverUrl(config.serverUrl, currentSong.album.id)
|
||||
: ""
|
||||
const { palette } = useCoverPalette(
|
||||
coverUri,
|
||||
currentSong ? currentSong.album.cover != null : undefined
|
||||
)
|
||||
const colors = useMemo(() => nowPlayingColors(palette), [palette])
|
||||
|
||||
const background = useSharedValue(colors.background)
|
||||
useEffect(() => {
|
||||
background.value = withTiming(colors.background, BACKGROUND_FADE)
|
||||
}, [background, colors.background])
|
||||
const backgroundStyle = useAnimatedStyle(() => ({
|
||||
backgroundColor: background.value,
|
||||
}))
|
||||
|
||||
const artworkScale = useSharedValue(isPlaying ? 1 : PAUSED_ARTWORK_SCALE)
|
||||
useEffect(() => {
|
||||
artworkScale.value = withSpring(
|
||||
isPlaying ? 1 : PAUSED_ARTWORK_SCALE,
|
||||
ARTWORK_SPRING
|
||||
)
|
||||
}, [artworkScale, isPlaying])
|
||||
const artworkStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ scale: artworkScale.value }],
|
||||
shadowOpacity: interpolate(
|
||||
artworkScale.value,
|
||||
[PAUSED_ARTWORK_SCALE, 1],
|
||||
[0.18, 0.4]
|
||||
),
|
||||
}))
|
||||
|
||||
const dismissY = useSharedValue(0)
|
||||
const dismissStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateY: dismissY.value }],
|
||||
borderRadius: dismissY.value > 0 ? DISMISS_CORNER_RADIUS : 0,
|
||||
}))
|
||||
|
||||
// The player covers the status bar, so it can't use the native sheet's
|
||||
// swipe to dismiss. Each GestureDetector needs its own gesture instance.
|
||||
const makeDismissGesture = useCallback(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.activeOffsetY(12)
|
||||
.failOffsetY(-12)
|
||||
.failOffsetX([-20, 20])
|
||||
.onUpdate((event) => {
|
||||
dismissY.value = Math.max(0, event.translationY)
|
||||
})
|
||||
.onEnd((event) => {
|
||||
if (
|
||||
event.translationY > DISMISS_DISTANCE ||
|
||||
event.velocityY > DISMISS_VELOCITY
|
||||
) {
|
||||
scheduleOnRN(setIsDismissing, true)
|
||||
dismissY.value = withTiming(
|
||||
windowHeight,
|
||||
{ duration: 220 },
|
||||
(finished) => {
|
||||
if (finished) scheduleOnRN(router.back)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
dismissY.value = withSpring(0, {
|
||||
duration: 350,
|
||||
dampingRatio: 0.85,
|
||||
})
|
||||
}
|
||||
}),
|
||||
[dismissY, router, windowHeight]
|
||||
)
|
||||
const handleGesture = useMemo(makeDismissGesture, [makeDismissGesture])
|
||||
const controlsGesture = useMemo(makeDismissGesture, [makeDismissGesture])
|
||||
const stageGesture = useMemo(
|
||||
() => makeDismissGesture().enabled(!showQueue),
|
||||
[makeDismissGesture, showQueue]
|
||||
)
|
||||
|
||||
const hasCover = currentSong ? currentSong.album.cover != null : false
|
||||
const queueHeader = useMemo(
|
||||
() =>
|
||||
currentSong ? (
|
||||
<View style={styles.queueHeader}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={styles.queueArtwork}
|
||||
/>
|
||||
<SongMeta song={currentSong} colors={colors} compact />
|
||||
</View>
|
||||
) : null,
|
||||
[colors, coverUri, currentSong, hasCover]
|
||||
)
|
||||
const songMeta = useMemo(
|
||||
() =>
|
||||
currentSong ? <SongMeta song={currentSong} colors={colors} /> : null,
|
||||
[colors, currentSong]
|
||||
)
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
|
||||
useEffect(() => {
|
||||
if (hasQueue) {
|
||||
hadSongRef.current = true
|
||||
return
|
||||
}
|
||||
|
||||
if (hadSongRef.current) {
|
||||
router.back()
|
||||
}
|
||||
}, [hasQueue, router])
|
||||
|
||||
if (!currentSong || !config) {
|
||||
return null
|
||||
}
|
||||
|
||||
const bottomInset = Math.max(insets.bottom, spacing.md)
|
||||
const artworkSize = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
windowWidth - HORIZONTAL_INSET * 2,
|
||||
stageHeight > 0 ? stageHeight - META_HEIGHT - spacing.xl : Infinity
|
||||
)
|
||||
)
|
||||
|
||||
function togglePlayback() {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
|
||||
setIsPlaying(!isPlaying)
|
||||
}
|
||||
|
||||
function toggleQueue() {
|
||||
void Haptics.selectionAsync()
|
||||
setShowQueue((value) => !value)
|
||||
}
|
||||
|
||||
if (isTablet) {
|
||||
return (
|
||||
<MusicEntityView kind="song" id={currentSong.id} style={{ flex: 1 }}>
|
||||
<TabletNowPlaying
|
||||
colors={colors}
|
||||
backgroundStyle={backgroundStyle}
|
||||
dismissStyle={dismissStyle}
|
||||
dismissGestures={{ handle: handleGesture, artwork: controlsGesture }}
|
||||
showQueue={showQueue}
|
||||
toggleQueue={toggleQueue}
|
||||
metadata={songMeta}
|
||||
/>
|
||||
</MusicEntityView>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Animated.View style={[styles.root, backgroundStyle, dismissStyle]}>
|
||||
<StatusBar style={colors.isDark ? "light" : "dark"} />
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
statusBarStyle: colors.isDark ? "light" : "dark",
|
||||
// The swipe already animates the player offscreen.
|
||||
animation: isDismissing ? "none" : "slide_from_bottom",
|
||||
}}
|
||||
/>
|
||||
<NavigationBar style={colors.isDark ? "light" : "dark"} />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<MusicEntityView
|
||||
kind="song"
|
||||
id={currentSong.id}
|
||||
style={[styles.safe, { paddingTop: insets.top }]}
|
||||
>
|
||||
<GestureDetector gesture={handleGesture}>
|
||||
<Pressable
|
||||
onPress={() => router.back()}
|
||||
hitSlop={12}
|
||||
style={styles.handleRow}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close player"
|
||||
>
|
||||
<View
|
||||
style={[styles.handle, { backgroundColor: colors.sliderTrack }]}
|
||||
/>
|
||||
</Pressable>
|
||||
</GestureDetector>
|
||||
|
||||
<GestureDetector gesture={stageGesture}>
|
||||
<View
|
||||
style={styles.stage}
|
||||
onLayout={(event) =>
|
||||
setStageHeight(event.nativeEvent.layout.height)
|
||||
}
|
||||
>
|
||||
<LayoutAnimationConfig skipEntering>
|
||||
{showQueue ? (
|
||||
stageHeight > 0 ? (
|
||||
<Animated.View
|
||||
key="queue"
|
||||
entering={MODE_FADE_IN}
|
||||
exiting={MODE_FADE_OUT}
|
||||
style={styles.fill}
|
||||
>
|
||||
<NowPlayingQueue
|
||||
colors={colors}
|
||||
viewportHeight={stageHeight}
|
||||
currentHeader={queueHeader}
|
||||
/>
|
||||
</Animated.View>
|
||||
) : null
|
||||
) : (
|
||||
<Animated.View
|
||||
key="artwork"
|
||||
entering={MODE_FADE_IN}
|
||||
exiting={MODE_FADE_OUT}
|
||||
style={[styles.fill, styles.artworkMode]}
|
||||
>
|
||||
<View style={styles.artworkArea}>
|
||||
<Animated.View style={[styles.artworkShadow, artworkStyle]}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={{
|
||||
width: artworkSize,
|
||||
height: artworkSize,
|
||||
borderRadius: radius.md,
|
||||
}}
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
<View style={styles.meta}>{songMeta}</View>
|
||||
</Animated.View>
|
||||
)}
|
||||
</LayoutAnimationConfig>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
|
||||
<GestureDetector gesture={controlsGesture}>
|
||||
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
|
||||
<PlayerProgress
|
||||
colors={colors}
|
||||
timeStyle={styles.time}
|
||||
center={
|
||||
format ? (
|
||||
<AudioFormatBadge
|
||||
format={format}
|
||||
color={colors.secondaryForeground}
|
||||
backgroundColor={colors.background}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
<View style={styles.transport}>
|
||||
<TransportButton
|
||||
colors={colors}
|
||||
accessibilityLabel="Previous"
|
||||
onPress={() => void skipPrevious()}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="backward.fill"
|
||||
fallback="play-back"
|
||||
size={34}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</TransportButton>
|
||||
<TransportButton
|
||||
colors={colors}
|
||||
accessibilityLabel={isPlaying ? "Pause" : "Play"}
|
||||
onPress={togglePlayback}
|
||||
large
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={isPlaying ? "pause.fill" : "play.fill"}
|
||||
fallback={isPlaying ? "pause" : "play"}
|
||||
size={44}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</TransportButton>
|
||||
<TransportButton
|
||||
colors={colors}
|
||||
accessibilityLabel="Next"
|
||||
onPress={() => void skipNext()}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="forward.fill"
|
||||
fallback="play-forward"
|
||||
size={34}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</TransportButton>
|
||||
</View>
|
||||
|
||||
<VolumeSlider colors={colors} />
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Pressable
|
||||
disabled
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Lyrics"
|
||||
accessibilityState={{ disabled: true }}
|
||||
style={[styles.queueButton, styles.unavailable]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="quote.bubble"
|
||||
fallback={{ material: "lyrics" }}
|
||||
size={27}
|
||||
weight="semibold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<AudioOutputButton
|
||||
color={colors.foreground}
|
||||
style={styles.queueButton}
|
||||
/>
|
||||
<Pressable
|
||||
onPress={toggleQueue}
|
||||
hitSlop={8}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
|
||||
accessibilityState={{ selected: showQueue }}
|
||||
style={[
|
||||
styles.queueButton,
|
||||
showQueue && { backgroundColor: colors.selected },
|
||||
]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="list.bullet"
|
||||
fallback="list"
|
||||
size={25}
|
||||
weight="semibold"
|
||||
color={
|
||||
showQueue ? colors.selectedForeground : colors.foreground
|
||||
}
|
||||
/>
|
||||
{!showQueue && (shuffleEnabled || repeatEnabled !== "none") ? (
|
||||
<View
|
||||
style={[styles.badge, { backgroundColor: colors.control }]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={
|
||||
shuffleEnabled
|
||||
? "shuffle"
|
||||
: repeatEnabled === "once"
|
||||
? "repeat.1"
|
||||
: "repeat"
|
||||
}
|
||||
fallback={shuffleEnabled ? "shuffle" : "repeat"}
|
||||
size={14}
|
||||
weight="bold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
</MusicEntityView>
|
||||
</Animated.View>
|
||||
)
|
||||
}
|
||||
|
||||
/** Phone volume slider. Owns the volume listener so volume changes stay local. */
|
||||
function VolumeSlider({ colors }: { colors: NowPlayingColors }) {
|
||||
const { volume, setVolume, available } = useSystemVolume()
|
||||
if (!available) return null
|
||||
return (
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Volume"
|
||||
commitHoldMs={0}
|
||||
animateValueChanges
|
||||
value={volume}
|
||||
maximumValue={1}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setVolume}
|
||||
leading={
|
||||
<PlayerSymbol
|
||||
name="speaker.fill"
|
||||
fallback="volume-low"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
trailing={
|
||||
<PlayerSymbol
|
||||
name="speaker.wave.3.fill"
|
||||
fallback="volume-high"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Title and artist with the favorite and more buttons. */
|
||||
function SongMeta({
|
||||
song,
|
||||
colors,
|
||||
compact = false,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
colors: NowPlayingColors
|
||||
compact?: boolean
|
||||
}) {
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const favorited = isSongFavorite(song.id)
|
||||
|
||||
async function handleAction(action: MediaAction) {
|
||||
await handleSongAction(song, action)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.metaRow}>
|
||||
<View style={styles.metaText}>
|
||||
<MarqueeText
|
||||
text={song.title}
|
||||
style={[
|
||||
compact ? styles.compactTitle : styles.title,
|
||||
{ color: colors.foreground },
|
||||
]}
|
||||
/>
|
||||
<PlayerArtistMenu song={song} onAction={handleAction}>
|
||||
<MarqueeText
|
||||
text={song.artist.name}
|
||||
style={[
|
||||
compact ? styles.compactArtist : styles.artist,
|
||||
{ color: colors.secondaryForeground },
|
||||
]}
|
||||
/>
|
||||
</PlayerArtistMenu>
|
||||
</View>
|
||||
<Pressable
|
||||
onPress={() => void toggleSongFavorite(song.id)}
|
||||
hitSlop={10}
|
||||
style={styles.metaButton}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={favorited ? "Unfavorite" : "Favorite"}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={favorited ? "star.fill" : "star"}
|
||||
fallback={favorited ? "star" : "star-outline"}
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<MediaActionMenu
|
||||
share={{
|
||||
type: "song",
|
||||
songId: song.id,
|
||||
albumId: song.album.id,
|
||||
title: song.title,
|
||||
}}
|
||||
stationArtistId={song.artist.id}
|
||||
favorited={favorited}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
includeActions={[
|
||||
"share",
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"create-station",
|
||||
"favorite",
|
||||
"go-artist",
|
||||
"go-album",
|
||||
]}
|
||||
onAction={handleAction}
|
||||
style={styles.menu}
|
||||
>
|
||||
<Pressable
|
||||
hitSlop={10}
|
||||
style={styles.metaButton}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="More"
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="ellipsis"
|
||||
fallback="ellipsis-horizontal"
|
||||
size={20}
|
||||
weight="semibold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function TransportButton({
|
||||
colors,
|
||||
large = false,
|
||||
accessibilityLabel,
|
||||
onPress,
|
||||
children,
|
||||
}: {
|
||||
colors: NowPlayingColors
|
||||
large?: boolean
|
||||
accessibilityLabel: string
|
||||
onPress: () => void
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
onPress={onPress}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
style={({ pressed }) => [
|
||||
large ? styles.playButton : styles.skipButton,
|
||||
pressed && {
|
||||
backgroundColor: colors.controlPressed,
|
||||
transform: [{ scale: 0.9 }],
|
||||
},
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
overflow: "hidden",
|
||||
},
|
||||
safe: {
|
||||
flex: 1,
|
||||
},
|
||||
fill: {
|
||||
flex: 1,
|
||||
},
|
||||
handleRow: {
|
||||
alignItems: "center",
|
||||
paddingTop: spacing.sm,
|
||||
paddingBottom: spacing.sm,
|
||||
},
|
||||
handle: {
|
||||
width: 36,
|
||||
height: 5,
|
||||
borderRadius: radius.full,
|
||||
},
|
||||
stage: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
artworkMode: {
|
||||
paddingHorizontal: HORIZONTAL_INSET,
|
||||
},
|
||||
artworkArea: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
artworkShadow: {
|
||||
borderRadius: radius.md,
|
||||
shadowColor: "#000",
|
||||
shadowRadius: 24,
|
||||
shadowOffset: { width: 0, height: 14 },
|
||||
},
|
||||
meta: {
|
||||
height: META_HEIGHT,
|
||||
justifyContent: "center",
|
||||
},
|
||||
queueHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 14,
|
||||
},
|
||||
queueArtwork: {
|
||||
width: 64,
|
||||
height: 64,
|
||||
borderRadius: 8,
|
||||
},
|
||||
metaRow: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
},
|
||||
metaText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
title: {
|
||||
fontSize: 20,
|
||||
fontWeight: "600",
|
||||
},
|
||||
artist: {
|
||||
fontSize: 20,
|
||||
marginTop: 1,
|
||||
},
|
||||
compactTitle: {
|
||||
fontSize: 17,
|
||||
fontWeight: "600",
|
||||
},
|
||||
compactArtist: {
|
||||
fontSize: 15,
|
||||
marginTop: 1,
|
||||
},
|
||||
menu: {
|
||||
alignSelf: "center",
|
||||
},
|
||||
metaButton: {
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderRadius: 15,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
controls: {
|
||||
flexShrink: 0,
|
||||
paddingHorizontal: HORIZONTAL_INSET,
|
||||
paddingTop: spacing.md,
|
||||
},
|
||||
time: { fontWeight: "600" },
|
||||
transport: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 28,
|
||||
marginVertical: spacing.xl,
|
||||
},
|
||||
skipButton: {
|
||||
width: 72,
|
||||
height: 72,
|
||||
borderRadius: 36,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
playButton: {
|
||||
width: 84,
|
||||
height: 84,
|
||||
borderRadius: 42,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
footer: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
paddingTop: spacing.md,
|
||||
paddingHorizontal: 40,
|
||||
},
|
||||
unavailable: {
|
||||
opacity: 0.35,
|
||||
},
|
||||
queueButton: {
|
||||
width: 38,
|
||||
height: 38,
|
||||
borderRadius: 19,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
badge: {
|
||||
position: "absolute",
|
||||
top: -10,
|
||||
right: -11,
|
||||
width: 21,
|
||||
height: 21,
|
||||
borderRadius: 10.5,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
})
|
||||
@@ -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 },
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Stack } from "expo-router"
|
||||
|
||||
export const unstable_settings = { anchor: "signin" }
|
||||
|
||||
export default function AuthLayout() {
|
||||
return <Stack screenOptions={{ headerShown: false }} />
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
"use client"
|
||||
|
||||
import { AuthForm } from "@/components/auth-form"
|
||||
|
||||
export default function SignInPage() {
|
||||
export default function SignInScreen() {
|
||||
return <AuthForm flow="signIn" />
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
"use client"
|
||||
|
||||
import { AuthForm } from "@/components/auth-form"
|
||||
|
||||
export default function SignUpPage() {
|
||||
export default function SignUpScreen() {
|
||||
return <AuthForm flow="signUp" />
|
||||
}
|
||||
@@ -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 "/"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useConvexAuth } from "@convex-dev/auth/react"
|
||||
import { DarkTheme, Stack, ThemeProvider } from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
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, useServerConfig } from "@/contexts/server-config"
|
||||
|
||||
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 (
|
||||
<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={isDark ? "light" : "dark"} />
|
||||
<ThemeProvider value={navigationTheme}>
|
||||
<HandoffBridge />
|
||||
<RootNavigator />
|
||||
</ThemeProvider>
|
||||
<Toaster />
|
||||
</ConvexAppProvider>
|
||||
</ServerConfigProvider>
|
||||
</SafeAreaProvider>
|
||||
</GestureHandlerRootView>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 538 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user