Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
505ae05c53 | ||
|
|
a7929c0ac9 | ||
|
|
5efd59826b | ||
|
|
8970f29410 | ||
|
|
523318fc06 | ||
|
|
ba531b4f61 | ||
|
|
3d51f08e0b | ||
|
|
2660c124d5 | ||
|
|
d7199b4d1d | ||
|
|
c60704080b | ||
|
|
1e3e46cfdc | ||
|
|
93d4220f3a | ||
|
|
8a748f2b3a | ||
|
|
2138a4a890 | ||
|
|
94a1981a4c | ||
|
|
2272a401bb | ||
|
|
3ab43a2ef6 | ||
|
|
79698f2265 | ||
|
|
94f80c03c5 | ||
|
|
d98d01ab20 | ||
|
|
6be5c43e6d | ||
|
|
8deb762a52 | ||
|
|
fe21c19810 | ||
|
|
6e86c3d2c5 | ||
|
|
aca4b73fac | ||
|
|
078f7ac6f6 | ||
|
|
b168df6ca6 | ||
|
|
8d178884d4 | ||
|
|
cd2131ef6f | ||
|
|
d6bff15f11 | ||
|
|
b82fca0bc2 | ||
|
|
4fbd4fa81d | ||
|
|
68b5709d88 | ||
|
|
434b2c1305 | ||
|
|
9064ef687c | ||
|
|
c93f3d352c | ||
|
|
a9bfcbbe2f | ||
|
|
717e939038 | ||
|
|
dd1cb8a5d1 | ||
|
|
7c9399a342 | ||
|
|
a3ec9d19d3 | ||
|
|
5f2b5bd5a2 | ||
|
|
3bb4e66ad0 | ||
|
|
fbb102ffbd | ||
|
|
76f7535ffa | ||
|
|
7fcf0645da | ||
|
|
50618865e7 | ||
|
|
fe2f6a785a | ||
|
|
53fc24d4bc | ||
|
|
ff5fa501af | ||
|
|
6e9883018a | ||
|
|
a985ff4fb3 |
@@ -0,0 +1,115 @@
|
||||
name: CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
pull_request:
|
||||
branches: ['**']
|
||||
|
||||
concurrency:
|
||||
group: production-deploy
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
backend-tests:
|
||||
name: BackEnd
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
defaults:
|
||||
run:
|
||||
working-directory: backend
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore Musify.slnx
|
||||
|
||||
- name: Build
|
||||
run: dotnet build Musify.slnx --no-restore -c Release
|
||||
|
||||
- name: Test
|
||||
run: dotnet test Musify.slnx --no-build -c Release
|
||||
|
||||
web-player-checks:
|
||||
name: WebPlayer
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
defaults:
|
||||
run:
|
||||
working-directory: web-player
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: web-player/package-lock.json
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Type-check
|
||||
run: npm run check
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
# Runs on the production host itself, through the existing self-hosted
|
||||
# Gitea Actions runner (act_runner), which also carries a "production"
|
||||
# label registered in native (non-docker) mode so its steps see the host's
|
||||
# real Docker daemon directly (Docker socket + a bind-mounted deploy
|
||||
# directory — see deploy/README.md for how that runner is set up).
|
||||
#
|
||||
# DEPLOY_PATH is the persistent clone already on that host (the one whose
|
||||
# deploy/.env.prod is filled in and matches SharedServices/.env.prod) —
|
||||
# deploy reuses it instead of a fresh checkout, since .env.prod is
|
||||
# untracked and only lives there.
|
||||
deploy:
|
||||
name: Deploy
|
||||
needs: [backend-tests, web-player-checks]
|
||||
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
|
||||
runs-on: [production]
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
DEPLOY_PATH: /home/ubuntu/deploys/musify
|
||||
COMPOSE: docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml
|
||||
steps:
|
||||
- name: Pull latest master
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config --global --add safe.directory "$DEPLOY_PATH"
|
||||
cd "$DEPLOY_PATH"
|
||||
git fetch origin master
|
||||
git reset --hard origin/master
|
||||
|
||||
- name: Migrate database, generate keys
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE up -d wait-for-postgres keys-init migrate
|
||||
|
||||
# Both jobs verify themselves through the public auth./s3. URLs, served
|
||||
# by the shared edge nginx (Infrastructure's edge/), and are idempotent.
|
||||
- name: Create OIDC app and S3 bucket
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE up -d seaweedfs-init zitadel-init
|
||||
for job in musify-seaweedfs-init musify-zitadel-init; do
|
||||
code=$(docker wait "$job")
|
||||
if [ "$code" != "0" ]; then
|
||||
docker logs "$job"
|
||||
echo "$job exited with $code"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Build and start apps
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE --profile apps up -d --build api worker gateway web-player
|
||||
@@ -28,5 +28,4 @@ Thumbs.db
|
||||
# Deploy secrets and runtime state
|
||||
deploy/keys/
|
||||
deploy/secrets/
|
||||
deploy/nginx/certs/
|
||||
deploy/zitadel/.output/
|
||||
|
||||
@@ -37,7 +37,7 @@ namespace Musify.Infrastructure.Persistence
|
||||
}
|
||||
else if (entry.State == EntityState.Modified)
|
||||
{
|
||||
entry.Entity.UpdatedAt = now;
|
||||
entry.Property(nameof(IAuditable.UpdatedAt)).CurrentValue = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,13 @@ namespace Musify.Infrastructure.Persistence
|
||||
public class Database(DatabaseConfiguration configuration)
|
||||
: DbContext, AppIDatabase
|
||||
{
|
||||
private static readonly AuditableEntityInterceptor AuditInterceptor = new();
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.UseNpgsql(configuration.ConnectionString, o => o.MapEnum<Genre>("genre"));
|
||||
optionsBuilder
|
||||
.UseNpgsql(configuration.ConnectionString, o => o.MapEnum<Genre>("genre"))
|
||||
.AddInterceptors(AuditInterceptor);
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
|
||||
@@ -18,10 +18,7 @@ namespace Musify.Infrastructure.Persistence
|
||||
serviceDescriptors.AddSingleton(serviceProvider =>
|
||||
serviceProvider.GetRequiredService<IOptions<DatabaseConfiguration>>().Value);
|
||||
|
||||
serviceDescriptors.AddSingleton<AuditableEntityInterceptor>();
|
||||
|
||||
serviceDescriptors.AddDbContext<Database>((serviceProvider, options) =>
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<AuditableEntityInterceptor>()));
|
||||
serviceDescriptors.AddDbContext<Database>();
|
||||
|
||||
serviceDescriptors.AddScoped<IDatabase>(serviceProvider => serviceProvider.GetRequiredService<Database>());
|
||||
|
||||
|
||||
+6
@@ -1,3 +1,4 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Infrastructure.Tests.TestSupport;
|
||||
using Xunit;
|
||||
@@ -43,6 +44,11 @@ namespace Musify.Infrastructure.Tests.Persistence
|
||||
Assert.Equal(originalCreatedAt, user.CreatedAt);
|
||||
Assert.True(user.UpdatedAt > originalCreatedAt,
|
||||
$"original-created-at={originalCreatedAt:O}, final-updated-at={user.UpdatedAt:O}");
|
||||
|
||||
await using var reader = fixture.CreateDatabase();
|
||||
var stored = await reader.Users.SingleAsync(u => u.Id == user.Id, TestContext.Current.CancellationToken);
|
||||
Assert.True(stored.UpdatedAt > stored.CreatedAt,
|
||||
$"stored-created-at={stored.CreatedAt:O}, stored-updated-at={stored.UpdatedAt:O}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-11
@@ -1,11 +1,14 @@
|
||||
# Production configuration for deploy/compose.yml + compose.prod.yml.
|
||||
# Copy to deploy/.env.prod, then:
|
||||
#
|
||||
# 1. replace every `example.com` with your domain,
|
||||
# 1. replace every `*.example.com` with your actual domains (each service
|
||||
# below has its own, independent domain — they don't need to share a
|
||||
# root, e.g. for DNS providers that don't allow multi-level
|
||||
# subdomains),
|
||||
# 2. replace every CHANGE_ME with a strong random value
|
||||
# (`openssl rand -hex 24`),
|
||||
# 3. point these DNS records at the server, all proxied/TLS-terminated the
|
||||
# same way: example.com, www, api, auth, stream, s3.
|
||||
# 3. point each domain below at the server and add its vhost to the shared
|
||||
# edge (Infrastructure's edge/conf.d).
|
||||
#
|
||||
# Requires ../../../Infrastructure running first, on the same Docker host,
|
||||
# with its own `infra-net` network already created. See
|
||||
@@ -14,12 +17,13 @@
|
||||
|
||||
DOTNET_ENVIRONMENT=Production
|
||||
|
||||
# --- Domain ------------------------------------------------------------------
|
||||
# ROOT_DOMAIN drives the nginx vhosts; the URLs below must agree with it.
|
||||
ROOT_DOMAIN=example.com
|
||||
PUBLIC_WEB_URL=https://example.com
|
||||
PUBLIC_API_URL=https://api.example.com
|
||||
PUBLIC_STREAM_URL=https://stream.example.com
|
||||
# --- Domains -------------------------------------------------------------
|
||||
# Public URLs. They must match the vhosts of the shared edge nginx
|
||||
# (Infrastructure's edge/conf.d), which is what serves them; the domains are
|
||||
# independent, they don't need to share a root.
|
||||
PUBLIC_WEB_URL=https://musify.example.com
|
||||
PUBLIC_API_URL=https://musifyapi.example.com
|
||||
PUBLIC_STREAM_URL=https://musifystream.example.com
|
||||
PUBLIC_AUTH_URL=https://auth.example.com
|
||||
S3_PUBLIC_URL=https://s3.example.com
|
||||
|
||||
@@ -63,5 +67,3 @@ AUTH_ALLOW_INSECURE_HTTP=false
|
||||
|
||||
# --- Misc --------------------------------------------------------------------
|
||||
AUTH_REQUIRE_HTTPS=true
|
||||
# Largest request body nginx accepts (audio uploads go through the web player).
|
||||
MAX_UPLOAD_SIZE=1024m
|
||||
|
||||
+53
-26
@@ -13,7 +13,7 @@ wherever you actually cloned it.
|
||||
|---|---|
|
||||
| `compose.yml` | Musify's own services, including the one-shot bootstrap jobs. No published ports, no domains, no environment-specific values. |
|
||||
| `compose.dev.yml` | Development overlay: publishes Musify's ports to the host. |
|
||||
| `compose.prod.yml` | Production overlay: adds the nginx edge and joins Infrastructure's `infra-net` network. |
|
||||
| `compose.prod.yml` | Production overlay: joins Infrastructure's `infra-net` network. |
|
||||
| `.env` / `.env.prod` | The values compose interpolates. Not versioned; templates in `.env.example` / `.env.prod.example`. |
|
||||
|
||||
The four applications (`api`, `worker`, `gateway`, `web-player`) sit behind
|
||||
@@ -113,26 +113,26 @@ SeaweedFS is done from the `Infrastructure` repo instead.
|
||||
|
||||
## Production
|
||||
|
||||
On a server with a domain:
|
||||
Musify doesn't run its own nginx: the shared edge in Infrastructure
|
||||
(`edge/`) owns host ports 80/443, terminates TLS for every project's domains
|
||||
and proxies to Musify's containers over `infra-net`. On a server with
|
||||
domains:
|
||||
|
||||
1. Bring up the `Infrastructure` repo first, with its own `.env.prod` filled
|
||||
in. It creates the `infra-net` network this stack joins.
|
||||
2. From this repository's root:
|
||||
2. Bring up its `edge/` (see Infrastructure's README) and add Musify's
|
||||
vhosts and certificate there (`edge/conf.d/musify.conf`). The five
|
||||
public hostnames (web, api, stream, auth, s3) are independent: they
|
||||
don't need to share a root domain.
|
||||
3. From this repository's root:
|
||||
|
||||
```sh
|
||||
cp deploy/.env.prod.example deploy/.env.prod
|
||||
```
|
||||
|
||||
Fill it in:
|
||||
|
||||
1. Replace every `example.com` with your domain and every `CHANGE_ME` with a
|
||||
random value (`openssl rand -hex 24`). `chmod 600 deploy/.env.prod`.
|
||||
2. Drop **`deploy/nginx/certs/origin.pem` and `origin.key`**, the origin
|
||||
certificate nginx serves. The stack assumes Cloudflare in *Full (strict)*
|
||||
mode in front of it, so a Cloudflare Origin Certificate is enough; any
|
||||
certificate valid for the five hostnames works.
|
||||
3. Point `example.com`, `www`, `api`, `auth`, `stream` and `s3` at the server,
|
||||
proxied and TLS-terminated the same way.
|
||||
Replace every `*.example.com` with your domains (they must match the
|
||||
edge's vhosts) and every `CHANGE_ME` with a random value
|
||||
(`openssl rand -hex 24`). `chmod 600 deploy/.env.prod`.
|
||||
|
||||
Then:
|
||||
|
||||
@@ -141,14 +141,45 @@ docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compo
|
||||
docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml --profile apps up -d --build
|
||||
```
|
||||
|
||||
The first command starts Musify's bootstrap jobs and the nginx edge; the
|
||||
second builds and starts the applications, already wired to the OIDC client
|
||||
ids the first one produced. Both are idempotent, so running them again
|
||||
deploys a new version (`... --profile apps up -d --build` alone is enough for
|
||||
an update once the stack already exists).
|
||||
The first command starts Musify's bootstrap jobs (`zitadel-init` and
|
||||
`seaweedfs-init` reach Zitadel/SeaweedFS through the public `auth.`/`s3.`
|
||||
URLs, so the edge has to be serving them by then); the second builds and
|
||||
starts the applications, already wired to the OIDC client ids the first one
|
||||
produced. Both are idempotent, so running them again deploys a new version
|
||||
(`... --profile apps up -d --build` alone is enough for an update once the
|
||||
stack already exists).
|
||||
|
||||
Only nginx publishes ports (80/443). Every other Musify service, and all of
|
||||
Infrastructure's, is reachable only on the internal `infra-net` network.
|
||||
Nothing in this stack publishes a port; everything is reachable only on the
|
||||
internal `infra-net` network, through the edge.
|
||||
|
||||
### Continuous deployment
|
||||
|
||||
`.gitea/workflows/ci-cd.yml` runs the backend and web-player checks on every
|
||||
push/PR, and on a successful push to `master` deploys automatically. The
|
||||
deploy job runs on `gitea-runner`, the self-hosted Gitea Actions runner on
|
||||
the production host (`~/gitea/docker-compose.yml`), configured by
|
||||
`~/gitea/runner-data/config.yaml` (`CONFIG_FILE`): job containers are pinned
|
||||
to the `gitea_gitea` network so `actions/checkout` can resolve `gitea`,
|
||||
`ubuntu-latest` is `node:22` (JS actions need Node inside the job
|
||||
container), and a `production:host` label runs steps natively.
|
||||
|
||||
Native mode means the label's steps execute inside the runner container
|
||||
itself rather than a fresh one. That container has `/var/run/docker.sock`
|
||||
mounted, so `docker`/`docker compose` there still control the host's real
|
||||
Docker daemon (sibling containers, "Docker outside of Docker"). Its compose
|
||||
service also bind-mounts `/home/ubuntu/deploys` into itself at the *same*
|
||||
path, which matters because compose's own relative bind mounts (`./keys`)
|
||||
are resolved by the host daemon against that literal path; mounting it
|
||||
anywhere else would silently bind the wrong (empty) directory.
|
||||
|
||||
`DEPLOY_PATH` (hardcoded in the workflow as `/home/ubuntu/deploys/musify`)
|
||||
is a persistent clone on that host, reused instead of a fresh checkout each
|
||||
run since `deploy/.env.prod` is untracked and only lives there.
|
||||
`/home/ubuntu/deploys/SharedServices` is the sibling clone of the
|
||||
`Infrastructure` repo (shared services + `edge/`), already running; its
|
||||
`.env.prod` shares the Postgres/RabbitMQ/S3 credentials with Musify's own
|
||||
`deploy/.env.prod` by design (see that repo's README). The edge is deployed
|
||||
from that repo, not from this pipeline.
|
||||
|
||||
---
|
||||
|
||||
@@ -159,13 +190,9 @@ deploy/
|
||||
├─ compose.yml # Musify's own services: wait-for-postgres, keys-init,
|
||||
│ # migrate, seaweedfs-init, zitadel-init, api/worker/gateway/web-player
|
||||
├─ compose.dev.yml # dev overlay: host ports
|
||||
├─ compose.prod.yml # prod overlay: nginx edge, joins infra-net
|
||||
├─ compose.prod.yml # prod overlay: joins infra-net
|
||||
├─ .env.example / .env.prod.example
|
||||
├─ keys/ # RS256 stream-ticket key pair (generated)
|
||||
└─ nginx/
|
||||
├─ templates/default.conf.template # vhosts, rendered with the domain by envsubst
|
||||
├─ snippets/proxy.conf # proxy headers shared by every vhost
|
||||
└─ certs/ # origin.pem + origin.key (not versioned)
|
||||
└─ keys/ # RS256 stream-ticket key pair (generated)
|
||||
```
|
||||
|
||||
The application images are built from `backend/Musify.*.Dockerfile` (build
|
||||
|
||||
+5
-34
@@ -1,11 +1,10 @@
|
||||
name: musify-prod
|
||||
|
||||
# Production overlay: adds the nginx edge and joins Infrastructure's shared
|
||||
# `infra-net` network so this project's containers can reach Postgres,
|
||||
# Zitadel, SeaweedFS, RabbitMQ and Jaeger by container name. None of them
|
||||
# run as part of this compose project anymore (see
|
||||
# ../../../Infrastructure/README.md, which must already be up). Nothing but
|
||||
# nginx publishes a port; every other service is reachable only on infra-net.
|
||||
# Production overlay: joins Infrastructure's shared `infra-net` network so
|
||||
# this project's containers can reach Postgres, Zitadel, SeaweedFS, RabbitMQ
|
||||
# and Jaeger by container name, and so the shared edge nginx (Infrastructure's
|
||||
# `edge/`, which owns host ports 80/443 and terminates TLS for every domain)
|
||||
# can reach api, gateway and web-player. Nothing here publishes a port.
|
||||
#
|
||||
# docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml up -d
|
||||
# docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml --profile apps up -d --build
|
||||
@@ -20,31 +19,3 @@ services:
|
||||
zitadel-init:
|
||||
volumes:
|
||||
- ./.env.prod:/workspace/.env
|
||||
|
||||
# Every vhost proxies through `set $upstream ...; proxy_pass $upstream;`
|
||||
# with the embedded Docker DNS resolver (see nginx/templates), so nginx
|
||||
# does not need api/gateway/web-player to exist at its own startup, only
|
||||
# at request time. That is what lets it start in the FIRST command
|
||||
# (profile-gated services aren't part of that invocation yet) and still be
|
||||
# reachable at the auth domain for zitadel-init to provision through.
|
||||
nginx:
|
||||
image: nginx:1.27-alpine
|
||||
container_name: musify-nginx
|
||||
environment:
|
||||
# The entrypoint renders /etc/nginx/templates/*.template with envsubst.
|
||||
# The filter keeps it from eating nginx's own $host / $remote_addr.
|
||||
MUSIFY_ROOT_DOMAIN: ${ROOT_DOMAIN}
|
||||
MUSIFY_MAX_UPLOAD_SIZE: ${MAX_UPLOAD_SIZE:-1024m}
|
||||
NGINX_ENVSUBST_FILTER: ^MUSIFY_
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./nginx/templates:/etc/nginx/templates:ro
|
||||
- ./nginx/snippets:/etc/nginx/snippets:ro
|
||||
- ./nginx/certs:/etc/nginx/certs:ro
|
||||
- nginx_cache:/var/cache/nginx
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
nginx_cache:
|
||||
|
||||
@@ -381,6 +381,10 @@ services:
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
# adapter-node rejects request bodies over 512K by default; audio
|
||||
# uploads are posted to /upload. Keep in line with the edge's
|
||||
# client_max_body_size.
|
||||
BODY_SIZE_LIMIT: 1G
|
||||
ORIGIN: ${PUBLIC_WEB_URL}
|
||||
ZITADEL_ISSUER: ${PUBLIC_AUTH_URL}
|
||||
ZITADEL_CLIENT_ID: ${WEB_CLIENT_ID}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
# Shared proxy settings for every Musify vhost.
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
@@ -1,119 +0,0 @@
|
||||
# Musify edge. The nginx entrypoint renders this with envsubst into
|
||||
# /etc/nginx/conf.d/default.conf (replacing the image's stock file) using the
|
||||
# MUSIFY_* variables set in compose.prod.yml.
|
||||
#
|
||||
# Cloudflare (Full strict) terminates the public edge; this box only needs to
|
||||
# serve the Cloudflare Origin Certificate in nginx/certs/. Each vhost proxies to
|
||||
# a compose service by name through the embedded Docker DNS resolver, so nginx
|
||||
# re-resolves it instead of caching the IP of a container that may be recreated.
|
||||
|
||||
resolver 127.0.0.11 valid=10s;
|
||||
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name ${MUSIFY_ROOT_DOMAIN} www.${MUSIFY_ROOT_DOMAIN}
|
||||
api.${MUSIFY_ROOT_DOMAIN} auth.${MUSIFY_ROOT_DOMAIN}
|
||||
stream.${MUSIFY_ROOT_DOMAIN} s3.${MUSIFY_ROOT_DOMAIN};
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
# Web player (SvelteKit, adapter-node). Uploads are posted to its own form
|
||||
# actions, so it needs the large body size too.
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name ${MUSIFY_ROOT_DOMAIN};
|
||||
client_max_body_size ${MUSIFY_MAX_UPLOAD_SIZE};
|
||||
|
||||
ssl_certificate /etc/nginx/certs/origin.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/origin.key;
|
||||
|
||||
location / {
|
||||
set $upstream http://web-player:3000;
|
||||
proxy_pass $upstream;
|
||||
include /etc/nginx/snippets/proxy.conf;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name www.${MUSIFY_ROOT_DOMAIN};
|
||||
|
||||
ssl_certificate /etc/nginx/certs/origin.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/origin.key;
|
||||
|
||||
return 301 https://${MUSIFY_ROOT_DOMAIN}$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name api.${MUSIFY_ROOT_DOMAIN};
|
||||
|
||||
ssl_certificate /etc/nginx/certs/origin.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/origin.key;
|
||||
|
||||
location / {
|
||||
set $upstream http://api:5111;
|
||||
proxy_pass $upstream;
|
||||
include /etc/nginx/snippets/proxy.conf;
|
||||
}
|
||||
}
|
||||
|
||||
# Audio bytes. Buffering off keeps range requests (seeking) responsive.
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name stream.${MUSIFY_ROOT_DOMAIN};
|
||||
|
||||
ssl_certificate /etc/nginx/certs/origin.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/origin.key;
|
||||
|
||||
location / {
|
||||
set $upstream http://gateway:8081;
|
||||
proxy_pass $upstream;
|
||||
include /etc/nginx/snippets/proxy.conf;
|
||||
proxy_buffering off;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name auth.${MUSIFY_ROOT_DOMAIN};
|
||||
|
||||
ssl_certificate /etc/nginx/certs/origin.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/origin.key;
|
||||
|
||||
location / {
|
||||
set $upstream http://zitadel:8080;
|
||||
proxy_pass $upstream;
|
||||
include /etc/nginx/snippets/proxy.conf;
|
||||
grpc_set_header Host $host;
|
||||
}
|
||||
}
|
||||
|
||||
# Presigned S3 PUT/GET straight from the browser.
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name s3.${MUSIFY_ROOT_DOMAIN};
|
||||
client_max_body_size ${MUSIFY_MAX_UPLOAD_SIZE};
|
||||
|
||||
ssl_certificate /etc/nginx/certs/origin.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/origin.key;
|
||||
|
||||
location / {
|
||||
set $upstream http://seaweedfs:8333;
|
||||
proxy_pass $upstream;
|
||||
include /etc/nginx/snippets/proxy.conf;
|
||||
proxy_request_buffering off;
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,12 @@ Status legend: ✅ done · 🟡 partial / mockup · ⬜ pending.
|
||||
## Home (app) `/` 🟡
|
||||
|
||||
- **Hero**: a greeting plus "Your music. No limits." with a color wash taken from the current track's hue.
|
||||
- **Quick access, meaning recently played** (`player.recentlyPlayed`, client side for now). Empty state with an icon and an "Explore" CTA.
|
||||
- **Quick access, meaning recently played** (`GET /users/{id}/listening-history` merged with `player.recentlyPlayed` via `mergeRecentlyPlayed`). Empty state with an icon and an "Explore" CTA.
|
||||
- **Your playlists**: mosaic cards for the user's playlists (sample data for now). Has an empty state.
|
||||
- **Resume on load**: the root layout fetches `GET /users/{id}/last-listened-track` and hydrates the player (`player.hydrate`) with it, paused, so the player bar isn't empty on a fresh session. Only applies when nothing is already loaded (won't override an in-progress session).
|
||||
|
||||
### Pending backend work (ASP.NET) for Home
|
||||
|
||||
- **Recently played**: track plays per user (a history table with `userId`, `trackId`, `playedAt`) and expose `GET /me/recently-played?limit=` (or `/users/{id}/recently-played`), returning tracks ordered by `playedAt` descending, with no duplicates. The frontend would load this in a `load` function and pass it to the store instead of using `recentlyPlayed`.
|
||||
- **Playlists by last listen**: add `lastPlayedAt` to the playlist (the schema currently only has `createdAt`/`updatedAt`) and allow sorting `GET /playlists/users/{userId}` by that field (for example `?sort=lastPlayed`), to show "your most recently played" playlists.
|
||||
- Tracks will need an **artist** and a **color/hue** (or a real cover to extract one from) for the artwork and the dynamic accent. Right now `TrackApplicationResponse` carries neither artist nor color.
|
||||
|
||||
|
||||
Generated
+55
-14
@@ -39,6 +39,40 @@
|
||||
"vite": "^8.0.16"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.11.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz",
|
||||
"integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "1.2.3",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",
|
||||
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.11.3",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
|
||||
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/wasi-threads": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
|
||||
@@ -1118,7 +1152,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.69.1.tgz",
|
||||
"integrity": "sha512-+nz8Fx/cElzb2ZPHC+6Ll3y3NEVIe4Na75PeplLlyTmd1dBXAjz2KR14y1ZgNjb2ThfAYzulu+PFy1UE3RCUzA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"@sveltejs/acorn-typescript": "^1.0.9",
|
||||
@@ -1170,7 +1203,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-7.1.2.tgz",
|
||||
"integrity": "sha512-DrUBA2UXRfDmUX/ZTiEopd3X40yavsJF1FX2RygcuIScHL7o5YX1fMvoYnDhjeJQC4weCOklirpNWlcb2NiSeA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"deepmerge": "^4.3.1",
|
||||
"magic-string": "^0.30.21",
|
||||
@@ -1408,6 +1440,27 @@
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
|
||||
"version": "1.11.1",
|
||||
"dev": true,
|
||||
"inBundle": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "1.2.2",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
|
||||
"version": "1.11.1",
|
||||
"dev": true,
|
||||
"inBundle": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
|
||||
"version": "1.2.2",
|
||||
"dev": true,
|
||||
@@ -1544,7 +1597,6 @@
|
||||
"integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
@@ -1606,7 +1658,6 @@
|
||||
"integrity": "sha512-KA0OshtlcCCXmbfqyZkM5pV3/WNraJf7DkJRLpyrmwPtud57H5BDX7C3k0LPSPxpprfRL+cJDGabF10mvNCoCw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.64.0",
|
||||
"@typescript-eslint/types": "8.64.0",
|
||||
@@ -1714,7 +1765,6 @@
|
||||
"integrity": "sha512-qjhfuTfLXjA4IOzXvz0rTjT01BqEiIgPoUeMwiEjnaHKJMTNo8rH5pYW1a2L/0Dnux2fPC85AeyJoWaGa8WxTA==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
@@ -1798,7 +1848,6 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
|
||||
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -2033,7 +2082,6 @@
|
||||
"integrity": "sha512-GVTD7s1vdIl6UYvAfriOPeY1Df8LIZjfofLvHwde+erDHGGuHyuM6xoxRxmHiebhYuD2p1vN4wWh0XzPARSGDQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -3112,7 +3160,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.12",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -3246,7 +3293,6 @@
|
||||
"integrity": "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
@@ -3263,7 +3309,6 @@
|
||||
"integrity": "sha512-wXvbXMjSvb4C9ENWTHXyd+ihakKCsJ6rJhLP6/8HFNj4GkZr48jqL9PoKsl2sk7SyCZRTnJ7O2TTowUpOxP/KA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
@@ -3434,7 +3479,6 @@
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
|
||||
"integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.9"
|
||||
},
|
||||
@@ -3569,7 +3613,6 @@
|
||||
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.4.tgz",
|
||||
"integrity": "sha512-/d0QHehmRuJW8gVz395MTkPcPozxzdjBMBE8oEYGz8O3b9KTMzzQ9ZHJQLuFKOHOPQbU6kx/X4iid/EBBzH7iw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/remapping": "^2.3.4",
|
||||
"@jridgewell/sourcemap-codec": "^1.5.0",
|
||||
@@ -3781,7 +3824,6 @@
|
||||
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -3843,7 +3885,6 @@
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.3.tgz",
|
||||
"integrity": "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"lightningcss": "^1.32.0",
|
||||
"picomatch": "^4.0.4",
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { Handle } from '@sveltejs/kit';
|
||||
import {
|
||||
clearSessionCookie,
|
||||
decodeSession,
|
||||
encodeSession,
|
||||
readSessionCookie,
|
||||
refreshSession,
|
||||
sessionCookieOptions,
|
||||
SESSION_COOKIE
|
||||
writeSessionCookie
|
||||
} from '$lib/server/auth';
|
||||
import { authConfig } from '$lib/server/config';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
let session = await decodeSession(event.cookies.get(SESSION_COOKIE));
|
||||
let session = await decodeSession(readSessionCookie(event.cookies));
|
||||
|
||||
if (
|
||||
session &&
|
||||
@@ -17,13 +18,9 @@ export const handle: Handle = async ({ event, resolve }) => {
|
||||
) {
|
||||
session = await refreshSession(session);
|
||||
if (session) {
|
||||
event.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
await encodeSession(session),
|
||||
sessionCookieOptions(event.url)
|
||||
);
|
||||
writeSessionCookie(event.cookies, await encodeSession(session), event.url);
|
||||
} else {
|
||||
event.cookies.delete(SESSION_COOKIE, { path: '/' });
|
||||
clearSessionCookie(event.cookies);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+48
@@ -553,6 +553,23 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/users/{id}/last-listened-track": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
|
||||
get: operations["GetLastTrackListenedByUserId"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/users/{id}/listening-stats": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -697,7 +714,9 @@ export interface components {
|
||||
pictureIntentId: string;
|
||||
|
||||
audioIntentId: string;
|
||||
tags: components["schemas"]["Genre"][];
|
||||
};
|
||||
Genre: "Pop" | "Rock" | "HipHop" | "RnB" | "Jazz" | "Blues" | "Classical" | "Electronic" | "House" | "Techno" | "Trance" | "Dubstep" | "DrumAndBass" | "Metal" | "Punk" | "Reggae" | "Reggaeton" | "Country" | "Folk" | "Indie" | "KPop" | "Latin" | "Soul" | "Funk" | "Ambient" | "Lofi";
|
||||
CreateUserRequest: {
|
||||
|
||||
id: number | string;
|
||||
@@ -2375,6 +2394,35 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
GetLastTrackListenedByUserId: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: number | string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["TrackApplicationResponse"];
|
||||
};
|
||||
};
|
||||
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
};
|
||||
};
|
||||
GetUserProfile: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
</script>
|
||||
|
||||
<header
|
||||
class="sticky top-0 z-(--z-sticky) flex h-14 items-center justify-between border-b border-hairline bg-bg/85 page-x backdrop-blur-md sm:hidden"
|
||||
class="sticky top-0 z-(--z-sticky) flex h-14 items-center justify-between bg-transparent page-x backdrop-blur-md sm:hidden"
|
||||
>
|
||||
<a href="/">
|
||||
<Logo size="sm" />
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import ListRow from '../ui/media/ListRow.svelte';
|
||||
import IconButton from '../ui/primitives/IconButton.svelte';
|
||||
import Plus from '@lucide/svelte/icons/plus';
|
||||
import Logo from '../ui/primitives/Logo.svelte';
|
||||
|
||||
interface SidebarPlaylist {
|
||||
id: string;
|
||||
@@ -33,6 +34,10 @@
|
||||
class="hidden shrink-0 flex-col border-r border-hairline p-5 lg:flex"
|
||||
style="width:var(--mf-sidebar-w)"
|
||||
>
|
||||
<a href="/" class="mb-4">
|
||||
<Logo size="sm" />
|
||||
</a>
|
||||
|
||||
<nav class="flex flex-col gap-1">
|
||||
{#each navLinks as link (link.href)}
|
||||
{@const active = isActive(link.href)}
|
||||
|
||||
@@ -3,20 +3,21 @@
|
||||
|
||||
interface Props {
|
||||
selected?: boolean;
|
||||
disabled?: boolean;
|
||||
count?: number;
|
||||
href?: string;
|
||||
onclick?: () => void;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let { selected = false, count, href, onclick, children }: Props = $props();
|
||||
let { selected = false, disabled = false, count, href, onclick, children }: Props = $props();
|
||||
|
||||
const classes = $derived(
|
||||
href
|
||||
? 'rounded-full border border-line-strong px-3.5 py-2 text-xs text-fg-2 transition-colors hover:bg-hover hover:text-fg'
|
||||
: `flex items-center gap-2 rounded-full px-3.5 py-2 text-xs font-medium transition ${
|
||||
selected ? 'bg-cta-strong text-ink' : 'bg-btn text-fg-2 hover:bg-btn-hover hover:text-fg'
|
||||
}`
|
||||
} ${disabled ? 'cursor-not-allowed opacity-40' : ''}`
|
||||
);
|
||||
</script>
|
||||
|
||||
@@ -30,5 +31,5 @@
|
||||
{#if href}
|
||||
<a {href} class={classes}>{@render content()}</a>
|
||||
{:else}
|
||||
<button type="button" {onclick} class={classes}>{@render content()}</button>
|
||||
<button type="button" {onclick} {disabled} class={classes}>{@render content()}</button>
|
||||
{/if}
|
||||
|
||||
@@ -5,18 +5,10 @@
|
||||
|
||||
let { size = 'sm' }: Props = $props();
|
||||
|
||||
const MARK: Record<'sm' | 'lg', string> = {
|
||||
sm: 'size-5.5 rounded-thumb',
|
||||
lg: 'size-8 rounded-control'
|
||||
};
|
||||
|
||||
const TEXT: Record<'sm' | 'lg', string> = {
|
||||
sm: 'font-display text-lg font-semibold tracking-tight text-fg',
|
||||
lg: 'font-display text-[clamp(1.5rem,3vw,2.5rem)] font-semibold tracking-tight'
|
||||
};
|
||||
</script>
|
||||
|
||||
<span class="flex items-center gap-3">
|
||||
<span class="{MARK[size]} bg-(image:--mf-logo-grad)"></span>
|
||||
<span class={TEXT[size]}>Musify</span>
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
export const TRACK_GENRES = [
|
||||
{ value: 'Pop', label: 'Pop' },
|
||||
{ value: 'Rock', label: 'Rock' },
|
||||
{ value: 'HipHop', label: 'Hip-hop' },
|
||||
{ value: 'RnB', label: 'R&B' },
|
||||
{ value: 'Jazz', label: 'Jazz' },
|
||||
{ value: 'Blues', label: 'Blues' },
|
||||
{ value: 'Classical', label: 'Clásica' },
|
||||
{ value: 'Electronic', label: 'Electrónica' },
|
||||
{ value: 'House', label: 'House' },
|
||||
{ value: 'Techno', label: 'Techno' },
|
||||
{ value: 'Trance', label: 'Trance' },
|
||||
{ value: 'Dubstep', label: 'Dubstep' },
|
||||
{ value: 'DrumAndBass', label: 'Drum and bass' },
|
||||
{ value: 'Metal', label: 'Metal' },
|
||||
{ value: 'Punk', label: 'Punk' },
|
||||
{ value: 'Reggae', label: 'Reggae' },
|
||||
{ value: 'Reggaeton', label: 'Reggaetón' },
|
||||
{ value: 'Country', label: 'Country' },
|
||||
{ value: 'Folk', label: 'Folk' },
|
||||
{ value: 'Indie', label: 'Indie' },
|
||||
{ value: 'KPop', label: 'K-pop' },
|
||||
{ value: 'Latin', label: 'Latina' },
|
||||
{ value: 'Soul', label: 'Soul' },
|
||||
{ value: 'Funk', label: 'Funk' },
|
||||
{ value: 'Ambient', label: 'Ambient' },
|
||||
{ value: 'Lofi', label: 'Lo-fi' }
|
||||
] as const;
|
||||
|
||||
export type TrackGenre = (typeof TRACK_GENRES)[number]['value'];
|
||||
|
||||
const GENRE_VALUES: ReadonlySet<string> = new Set(TRACK_GENRES.map((genre) => genre.value));
|
||||
|
||||
const INTENSE: ReadonlySet<TrackGenre> = new Set(['Metal', 'Punk', 'Dubstep', 'DrumAndBass']);
|
||||
const MELLOW: ReadonlySet<TrackGenre> = new Set(['Classical', 'Ambient', 'Lofi']);
|
||||
|
||||
export function isTrackGenre(value: string): value is TrackGenre {
|
||||
return GENRE_VALUES.has(value);
|
||||
}
|
||||
|
||||
export function areCompatible(a: TrackGenre, b: TrackGenre): boolean {
|
||||
return !((INTENSE.has(a) && MELLOW.has(b)) || (INTENSE.has(b) && MELLOW.has(a)));
|
||||
}
|
||||
|
||||
export function genreLabel(value: TrackGenre): string {
|
||||
return TRACK_GENRES.find((genre) => genre.value === value)?.label ?? value;
|
||||
}
|
||||
|
||||
export function findConflict(tags: readonly TrackGenre[]): [TrackGenre, TrackGenre] | undefined {
|
||||
for (let i = 0; i < tags.length; i++) {
|
||||
for (let j = i + 1; j < tags.length; j++) {
|
||||
if (!areCompatible(tags[i], tags[j])) return [tags[i], tags[j]];
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -315,6 +315,15 @@ class PlayerState {
|
||||
return `${url}${sep}t=${encodeURIComponent(ticket)}`;
|
||||
}
|
||||
|
||||
hydrate(item: ApiTrackLike) {
|
||||
if (this.currentId !== null || this.tracks.length > 0) return;
|
||||
const track = toTrack(toQueueItem(item));
|
||||
this.tracks = [track];
|
||||
this.currentId = track.id;
|
||||
this.#applyAccent(track.id);
|
||||
this.#syncMediaSessionMetadata(track);
|
||||
}
|
||||
|
||||
playlistTracks(ids: (string | number)[]): PlayerTrack[] {
|
||||
return ids
|
||||
.map((id) => this.tracks.find((t) => t.id === id))
|
||||
@@ -384,6 +393,10 @@ class PlayerState {
|
||||
toggle() {
|
||||
const audio = this.#audioEl();
|
||||
if (!audio || this.currentId === null) return;
|
||||
if (!audio.src) {
|
||||
this.#loadCurrent();
|
||||
return;
|
||||
}
|
||||
if (audio.paused) audio.play().catch(() => {});
|
||||
else audio.pause();
|
||||
}
|
||||
|
||||
@@ -52,9 +52,27 @@ export function unwrapOrError<T>(
|
||||
return result.data;
|
||||
}
|
||||
|
||||
export function apiErrorDetail(error: unknown): string | undefined {
|
||||
if (typeof error !== 'object' || error === null) return undefined;
|
||||
const { errors, detail, title } = error as {
|
||||
errors?: Record<string, unknown>;
|
||||
detail?: unknown;
|
||||
title?: unknown;
|
||||
};
|
||||
if (errors && typeof errors === 'object') {
|
||||
const messages = Object.values(errors)
|
||||
.flat()
|
||||
.filter((entry): entry is string => typeof entry === 'string');
|
||||
if (messages.length > 0) return messages.join(' ');
|
||||
}
|
||||
if (typeof detail === 'string' && detail !== '') return detail;
|
||||
if (typeof title === 'string' && title !== '') return title;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function unwrapOrFail(
|
||||
result: { error?: unknown },
|
||||
message: string
|
||||
): ActionFailure<{ message: string }> | undefined {
|
||||
return result.error ? fail(502, { message }) : undefined;
|
||||
): ActionFailure<{ message: string; detail?: string }> | undefined {
|
||||
return result.error ? fail(502, { message, detail: apiErrorDetail(result.error) }) : undefined;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import * as client from 'openid-client';
|
||||
import { EncryptJWT, jwtDecrypt } from 'jose';
|
||||
import { dev } from '$app/environment';
|
||||
@@ -53,6 +54,44 @@ export function sessionCookieOptions(url: URL) {
|
||||
};
|
||||
}
|
||||
|
||||
const SESSION_CHUNK_SIZE = 3600;
|
||||
|
||||
function sessionChunkName(index: number): string {
|
||||
return index === 0 ? SESSION_COOKIE : `${SESSION_COOKIE}.${index}`;
|
||||
}
|
||||
|
||||
export function readSessionCookie(cookies: Cookies): string | undefined {
|
||||
const parts: string[] = [];
|
||||
for (let index = 0; ; index++) {
|
||||
const part = cookies.get(sessionChunkName(index));
|
||||
if (part === undefined) break;
|
||||
parts.push(part);
|
||||
}
|
||||
return parts.length > 0 ? parts.join('') : undefined;
|
||||
}
|
||||
|
||||
export function clearSessionCookie(cookies: Cookies, keep = 0): void {
|
||||
for (const { name } of cookies.getAll()) {
|
||||
const match =
|
||||
name === SESSION_COOKIE
|
||||
? 0
|
||||
: name.startsWith(`${SESSION_COOKIE}.`)
|
||||
? Number(name.slice(SESSION_COOKIE.length + 1))
|
||||
: -1;
|
||||
if (Number.isInteger(match) && match >= keep) cookies.delete(name, { path: '/' });
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSessionCookie(cookies: Cookies, token: string, url: URL): void {
|
||||
const options = sessionCookieOptions(url);
|
||||
const count = Math.ceil(token.length / SESSION_CHUNK_SIZE);
|
||||
for (let index = 0; index < count; index++) {
|
||||
const chunk = token.slice(index * SESSION_CHUNK_SIZE, (index + 1) * SESSION_CHUNK_SIZE);
|
||||
cookies.set(sessionChunkName(index), chunk, options);
|
||||
}
|
||||
clearSessionCookie(cookies, count);
|
||||
}
|
||||
|
||||
export async function encodeSession(session: Session): Promise<string> {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
return new EncryptJWT({ ...session })
|
||||
|
||||
@@ -9,12 +9,17 @@ function positiveInt(value: string | undefined, fallback: number): number {
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
function required(name: string, value: string | undefined): string {
|
||||
if (!value) throw new Error(`Missing required environment variable: ${name}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
export const authConfig = {
|
||||
get issuer() {
|
||||
return env.ZITADEL_ISSUER;
|
||||
return required('ZITADEL_ISSUER', env.ZITADEL_ISSUER);
|
||||
},
|
||||
get clientId() {
|
||||
return env.ZITADEL_CLIENT_ID;
|
||||
return required('ZITADEL_CLIENT_ID', env.ZITADEL_CLIENT_ID);
|
||||
},
|
||||
get clientSecret(): string | undefined {
|
||||
const secret = env.ZITADEL_CLIENT_SECRET;
|
||||
@@ -24,10 +29,10 @@ export const authConfig = {
|
||||
return env.OIDC_SCOPE || DEFAULT_OIDC_SCOPE;
|
||||
},
|
||||
get redirectUri() {
|
||||
return env.AUTH_REDIRECT_URI;
|
||||
return required('AUTH_REDIRECT_URI', env.AUTH_REDIRECT_URI);
|
||||
},
|
||||
get postLogoutUri() {
|
||||
return env.AUTH_POST_LOGOUT_URI;
|
||||
return required('AUTH_POST_LOGOUT_URI', env.AUTH_POST_LOGOUT_URI);
|
||||
},
|
||||
get sessionSecret() {
|
||||
return env.SESSION_SECRET;
|
||||
|
||||
@@ -63,7 +63,6 @@ export function buildThemeTokens(hue: number, mode: 'dark' | 'light' = 'dark'):
|
||||
'--mf-spotlight-bg': light
|
||||
? `linear-gradient(120deg, ${glow(0.9, 0.04, 0.55)}, ${glow(0.96, 0.02, 0.35)} 55%)`
|
||||
: `linear-gradient(120deg, ${glow(0.22, 0.04, 0.5)}, ${glow(0.13, 0.02, 0.3)} 55%, ${glow(0.11, 0.015, 0.2)})`,
|
||||
'--mf-logo-grad': `linear-gradient(${accent}, ${accent})`,
|
||||
'--mf-cover-grad': light
|
||||
? `linear-gradient(150deg, oklch(0.84 0.03 ${H}), oklch(0.74 0.02 ${H}))`
|
||||
: `linear-gradient(150deg, oklch(0.34 0.03 ${H}), oklch(0.18 0.015 ${H}))`
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
unwrapOrFail
|
||||
} from '$lib/server/api';
|
||||
import { putPresigned, extOf, contentTypeOf, AUDIO_TYPES, IMAGE_TYPES } from '$lib/server/upload';
|
||||
import { findConflict, genreLabel, isTrackGenre, type TrackGenre } from '$lib/data/trackGenres';
|
||||
|
||||
const MAX_TITLE = 100;
|
||||
|
||||
@@ -23,6 +24,7 @@ export const actions: Actions = {
|
||||
const title = String(form.get('title') ?? '').trim();
|
||||
const audio = form.get('audio');
|
||||
const cover = form.get('cover');
|
||||
const rawTags = form.getAll('tags').map(String);
|
||||
|
||||
if (title === '' || title.length > MAX_TITLE) {
|
||||
return fail(400, { message: 'El título es obligatorio (máx. 100 caracteres).' });
|
||||
@@ -34,6 +36,20 @@ export const actions: Actions = {
|
||||
return fail(400, { message: 'Selecciona una portada.' });
|
||||
}
|
||||
|
||||
if (rawTags.length === 0) {
|
||||
return fail(400, { message: 'Elige al menos un género.' });
|
||||
}
|
||||
if (!rawTags.every(isTrackGenre)) {
|
||||
return fail(400, { message: 'Alguno de los géneros no es válido.' });
|
||||
}
|
||||
const tags: TrackGenre[] = [...new Set(rawTags)];
|
||||
const conflict = findConflict(tags);
|
||||
if (conflict) {
|
||||
return fail(400, {
|
||||
message: `Los géneros ${genreLabel(conflict[0])} y ${genreLabel(conflict[1])} no se pueden combinar.`
|
||||
});
|
||||
}
|
||||
|
||||
const audioContentType = contentTypeOf(audio, AUDIO_TYPES);
|
||||
const pictureContentType = contentTypeOf(cover, IMAGE_TYPES);
|
||||
const api = createApiClient({ fetch, accessToken });
|
||||
@@ -73,7 +89,8 @@ export const actions: Actions = {
|
||||
body: {
|
||||
title,
|
||||
pictureIntentId: urls.pictureIntentId,
|
||||
audioIntentId: urls.audioIntentId
|
||||
audioIntentId: urls.audioIntentId,
|
||||
tags
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
import Input from '$lib/components/ui/primitives/Input.svelte';
|
||||
import Checkbox from '$lib/components/ui/primitives/Checkbox.svelte';
|
||||
import Button from '$lib/components/ui/primitives/Button.svelte';
|
||||
import Chip from '$lib/components/ui/primitives/Chip.svelte';
|
||||
import { TRACK_GENRES, areCompatible, type TrackGenre } from '$lib/data/trackGenres';
|
||||
|
||||
type Status = 'idle' | 'uploading' | 'done' | 'error';
|
||||
type StepState = 'idle' | 'active' | 'done';
|
||||
@@ -28,6 +30,8 @@
|
||||
let status = $state<Status>('idle');
|
||||
let acceptedTerms = $state(false);
|
||||
let errorMsg = $state('');
|
||||
let errorDetail = $state('');
|
||||
let tags = $state<TrackGenre[]>([]);
|
||||
let publishedTitle = $state('');
|
||||
let audioInput = $state<HTMLInputElement>();
|
||||
|
||||
@@ -40,7 +44,7 @@
|
||||
const busy = $derived(status === 'uploading');
|
||||
|
||||
const canPublish = $derived(
|
||||
title.trim() !== '' && audioName !== '' && hasCover && acceptedTerms && !busy
|
||||
title.trim() !== '' && audioName !== '' && hasCover && tags.length > 0 && acceptedTerms && !busy
|
||||
);
|
||||
|
||||
const stepStates = $derived.by<StepState[]>(() => {
|
||||
@@ -81,6 +85,14 @@
|
||||
pickAudio(file);
|
||||
}
|
||||
|
||||
function toggleTag(tag: TrackGenre) {
|
||||
tags = tags.includes(tag) ? tags.filter((current) => current !== tag) : [...tags, tag];
|
||||
}
|
||||
|
||||
function tagBlocked(tag: TrackGenre) {
|
||||
return !tags.includes(tag) && tags.some((current) => !areCompatible(current, tag));
|
||||
}
|
||||
|
||||
function reset() {
|
||||
title = '';
|
||||
audioName = '';
|
||||
@@ -90,6 +102,8 @@
|
||||
status = 'idle';
|
||||
acceptedTerms = false;
|
||||
errorMsg = '';
|
||||
errorDetail = '';
|
||||
tags = [];
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -153,6 +167,7 @@
|
||||
use:enhance={() => {
|
||||
status = 'uploading';
|
||||
errorMsg = '';
|
||||
errorDetail = '';
|
||||
return async ({ result }) => {
|
||||
if (result.type === 'success') {
|
||||
publishedTitle = title;
|
||||
@@ -160,6 +175,7 @@
|
||||
} else if (result.type === 'failure') {
|
||||
status = 'error';
|
||||
errorMsg = (result.data?.message as string) ?? 'No se pudo subir la canción.';
|
||||
errorDetail = (result.data?.detail as string | undefined) ?? '';
|
||||
} else {
|
||||
status = 'error';
|
||||
errorMsg = 'Error inesperado durante la subida.';
|
||||
@@ -236,6 +252,26 @@
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field label="Géneros">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each TRACK_GENRES as genre (genre.value)}
|
||||
<Chip
|
||||
selected={tags.includes(genre.value)}
|
||||
disabled={tagBlocked(genre.value)}
|
||||
onclick={() => toggleTag(genre.value)}
|
||||
>
|
||||
{genre.label}
|
||||
</Chip>
|
||||
{/each}
|
||||
</div>
|
||||
{#each tags as tag (tag)}
|
||||
<input type="hidden" name="tags" value={tag} />
|
||||
{/each}
|
||||
{#snippet hint()}
|
||||
<p>Elige al menos uno. Algunos géneros no se pueden combinar, como Metal con Ambient.</p>
|
||||
{/snippet}
|
||||
</Field>
|
||||
|
||||
<Checkbox bind:checked={acceptedTerms}>
|
||||
Acepto los
|
||||
<a
|
||||
@@ -260,7 +296,10 @@
|
||||
{/if}
|
||||
|
||||
{#if status === 'error'}
|
||||
<Alert tone="danger">{errorMsg}</Alert>
|
||||
<Alert tone="danger">
|
||||
{errorMsg}
|
||||
{#if errorDetail}<span class="mt-1 block text-xs opacity-80">{errorDetail}</span>{/if}
|
||||
</Alert>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-end sm:gap-4">
|
||||
|
||||
@@ -39,6 +39,22 @@ async function fetchLikedTracks(fetchFn: typeof fetch, accessToken: string | nul
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchLastPlayedTrack(
|
||||
fetchFn: typeof fetch,
|
||||
accessToken: string | null,
|
||||
userId: string
|
||||
) {
|
||||
try {
|
||||
const api = createApiClient({ fetch: fetchFn, accessToken: accessToken ?? undefined });
|
||||
const { data } = await api.GET('/users/{id}/last-listened-track', {
|
||||
params: { path: { id: userId } }
|
||||
});
|
||||
return data ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const load: LayoutServerLoad = async ({ locals, url, fetch }) => {
|
||||
const allowAnonymousListening = await getAllowAnonymousListening(fetch);
|
||||
|
||||
@@ -56,13 +72,15 @@ export const load: LayoutServerLoad = async ({ locals, url, fetch }) => {
|
||||
allowAnonymousListening,
|
||||
sidebarPlaylists: [],
|
||||
likedTracks: [],
|
||||
lastPlayedTrack: null,
|
||||
accountUrl
|
||||
};
|
||||
}
|
||||
|
||||
const [sidebarPlaylists, likedTracks] = await Promise.all([
|
||||
const [sidebarPlaylists, likedTracks, lastPlayedTrack] = await Promise.all([
|
||||
fetchSidebarPlaylists(fetch, locals.accessToken, locals.user.sub),
|
||||
fetchLikedTracks(fetch, locals.accessToken)
|
||||
fetchLikedTracks(fetch, locals.accessToken),
|
||||
fetchLastPlayedTrack(fetch, locals.accessToken, locals.user.sub)
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -70,6 +88,7 @@ export const load: LayoutServerLoad = async ({ locals, url, fetch }) => {
|
||||
allowAnonymousListening,
|
||||
sidebarPlaylists,
|
||||
likedTracks,
|
||||
lastPlayedTrack,
|
||||
accountUrl
|
||||
};
|
||||
};
|
||||
|
||||
@@ -30,15 +30,19 @@
|
||||
if (data.likedTracks?.length) liked.hydrate(data.likedTracks);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (data.lastPlayedTrack) player.hydrate(data.lastPlayedTrack);
|
||||
});
|
||||
|
||||
const isAuthPage = $derived(page.url.pathname === '/auth');
|
||||
const hasTrack = $derived(player.currentId !== null);
|
||||
|
||||
const initialThemeCss = `:root{${tokensToCss(buildThemeTokens(ACCENT_HUE, 'dark'))}}:root[data-theme='light']{${tokensToCss(buildThemeTokens(ACCENT_HUE, 'light'))}}`;
|
||||
|
||||
let hadTrack = false;
|
||||
let wasPlaying = false;
|
||||
$effect(() => {
|
||||
if (hasTrack && !hadTrack) queuePanel.show();
|
||||
hadTrack = hasTrack;
|
||||
if (player.playing && !wasPlaying) queuePanel.show();
|
||||
wasPlaying = player.playing;
|
||||
});
|
||||
|
||||
function isTypingTarget(target: EventTarget | null): boolean {
|
||||
|
||||
@@ -4,10 +4,9 @@ import type { RequestHandler } from './$types';
|
||||
import {
|
||||
getOidcConfig,
|
||||
encodeSession,
|
||||
sessionCookieOptions,
|
||||
toSessionUser,
|
||||
writeSessionCookie,
|
||||
type Session,
|
||||
SESSION_COOKIE,
|
||||
STATE_COOKIE,
|
||||
VERIFIER_COOKIE,
|
||||
NONCE_COOKIE,
|
||||
@@ -55,7 +54,7 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
|
||||
expiresAt: Math.floor(Date.now() / 1000) + (tokens.expires_in ?? 3600)
|
||||
};
|
||||
|
||||
cookies.set(SESSION_COOKIE, await encodeSession(session), sessionCookieOptions(url));
|
||||
writeSessionCookie(cookies, await encodeSession(session), url);
|
||||
|
||||
for (const name of [STATE_COOKIE, VERIFIER_COOKIE, NONCE_COOKIE, RETURN_COOKIE]) {
|
||||
cookies.delete(name, { path: '/' });
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import * as client from 'openid-client';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getOidcConfig, decodeSession, SESSION_COOKIE } from '$lib/server/auth';
|
||||
import {
|
||||
clearSessionCookie,
|
||||
decodeSession,
|
||||
getOidcConfig,
|
||||
readSessionCookie
|
||||
} from '$lib/server/auth';
|
||||
import { authConfig } from '$lib/server/config';
|
||||
|
||||
const handleLogout: RequestHandler = async ({ cookies }) => {
|
||||
const session = await decodeSession(cookies.get(SESSION_COOKIE));
|
||||
cookies.delete(SESSION_COOKIE, { path: '/' });
|
||||
const session = await decodeSession(readSessionCookie(cookies));
|
||||
clearSessionCookie(cookies);
|
||||
|
||||
const config = await getOidcConfig();
|
||||
const endSessionUrl = client.buildEndSessionUrl(config, {
|
||||
|
||||
Reference in New Issue
Block a user