'use client';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useRef, useState } from 'react';
import useSWR from 'swr';
import {
SERVICE_LABELS,
SPOTIFY_LINK_PAGES,
STREAMING_SERVICES,
isQuietScrobbler,
type ConnectionDTO,
type MeDTO,
type NowPlayingProvider,
type TrackSearchResultDTO,
type UserSummaryDTO,
} from '@musicshare/shared';
import { Avatar } from '@/components/Avatar';
import { ServiceName } from '@/components/ServiceName';
import { SharingControls } from '@/components/SharingControls';
import { SupportCard } from '@/components/SupportLink';
import { api, client, fetcher, uploadFile, useMe } from '@/lib/api';
import { timeAgo } from '@musicshare/shared';
import { useDebounced } from '@/lib/useDebounced';
export default function SettingsPage() {
return (
);
}
function Settings() {
const { me, loggedOut } = useMe();
const router = useRouter();
if (loggedOut) router.replace('/login');
if (!me) return null;
return (
);
}
function ProfileForm({ me }: { me: MeDTO }) {
const { mutate } = useMe();
const [saved, setSaved] = useState(false);
const [error, setError] = useState(null);
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const str = (k: string) => (f.get(k) as string).trim() || null;
try {
const updated = await api('/me', {
method: 'PATCH',
body: { displayName: str('displayName'), bio: str('bio'), preferredService: str('preferredService') },
});
await mutate(updated, { revalidate: false });
setError(null);
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} catch (err) {
setError((err as Error).message);
}
};
return (
);
}
function AvatarPicker({ me }: { me: MeDTO }) {
const { mutate } = useMe();
const input = useRef(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const run = async (fn: () => Promise) => {
setBusy(true);
setError(null);
try {
await mutate(await fn(), { revalidate: false });
} catch (err) {
setError((err as Error).message);
}
setBusy(false);
};
const onPick = (e: React.ChangeEvent) => {
const file = e.target.files?.[0];
e.target.value = ''; // picking the same file again should still upload
if (!file) return;
if (file.size > 10 * 1024 * 1024) return setError('That picture is too big (10 MB max)');
run(() => uploadFile('/me/avatar', file));
};
return (
input.current?.click()}>
{busy ? 'Uploading…' : me.avatarUrl ? 'Change picture' : 'Add a picture'}
{me.avatarUrl && (
run(() => api('/me/avatar', { method: 'DELETE' }))}>
Remove
)}
{error &&
{error}
}
);
}
function AccountSettings({ me }: { me: MeDTO }) {
const { mutate } = useMe();
const [editing, setEditing] = useState<'email' | 'password' | null>(null);
const [message, setMessage] = useState(null);
const [error, setError] = useState(null);
const [show, setShow] = useState(false);
const run = async (fn: () => Promise, done: string) => {
setError(null);
try {
await fn();
await mutate();
setEditing(null);
setMessage(done);
} catch (err) {
setError((err as Error).message);
}
};
const field = (f: FormData, k: string) => String(f.get(k) ?? '');
return (
Account
Email
{me.email}{' '}
{me.emailVerified ? Confirmed : Not confirmed }
{me.pendingEmail && (
Changing to {me.pendingEmail} : open the link we sent there.{' '}
run(() => client.cancelEmailChange(), 'Email change cancelled.')}>
Cancel
)}
{!me.emailVerified && !me.pendingEmail && (
run(() => client.resendVerification(), `Sent a new link to ${me.email}.`)}>
Send the confirmation link again
)}
{editing === 'email' ? (
{
e.preventDefault();
const f = new FormData(e.currentTarget);
const email = field(f, 'email');
run(() => client.changeEmail({ email, password: field(f, 'password') }), `Check ${email} for a confirmation link.`);
}}
>
New email
Your password
setEditing(null)} />
) : editing === 'password' ? (
{
e.preventDefault();
const f = new FormData(e.currentTarget);
run(
() => client.changePassword({ currentPassword: field(f, 'current'), newPassword: field(f, 'new') }),
'Password changed. Your other devices were signed out.',
);
}}
>
Current password
New password
setEditing(null)} />
) : (
(setMessage(null), setEditing('email'))}>
Change email
(setMessage(null), setEditing('password'))}>
Change password
)}
{message && {message}
}
{error && {error}
}
);
}
function ShowPassword({ show, setShow }: { show: boolean; setShow: (v: boolean) => void }) {
return (
setShow(e.target.checked)} /> Show passwords
);
}
function FormButtons({ label, onCancel }: { label: string; onCancel: () => void }) {
return (
{label}
Cancel
);
}
function BlockedAccounts() {
const { data: blocked = [], mutate } = useSWR('/me/blocks', fetcher);
return (
Blocked accounts
{blocked.length === 0 ? (
You haven't blocked anyone. Block someone from the ⋯ menu on their profile.
) : (
{blocked.map((u) => (
{u.displayName ?? u.username}
(await client.unblock(u.username), mutate())}>
Unblock
))}
)}
);
}
function Connections() {
const params = useSearchParams();
const { data: connections = [], mutate } = useSWR('/connections', fetcher);
const [error, setError] = useState(params.get('error'));
const byProvider = new Map(connections.map((c) => [c.provider, c]));
const run = async (fn: () => Promise) => {
setError(null);
try {
await fn();
await mutate();
} catch (err) {
setError((err as Error).message);
}
};
const connectOAuth = (provider: 'plex' | 'lastfm') =>
run(async () => {
const { url } = await api<{ url: string }>(`/connections/${provider}/authorize`, { body: { client: 'web' } });
window.location.href = url;
});
const connectJellyfin = (e: React.FormEvent) => {
e.preventDefault();
const body = Object.fromEntries(new FormData(e.currentTarget));
run(() => api('/connections/jellyfin', { body }));
};
const connectUsername = (provider: 'lastfm' | 'listenbrainz') => (e: React.FormEvent) => {
e.preventDefault();
const username = new FormData(e.currentTarget).get('username');
run(() => api(`/connections/${provider}`, { body: { username } }));
};
const disconnect = (provider: NowPlayingProvider) =>
run(() => api(`/connections/${provider}`, { method: 'DELETE' }));
const status = (p: NowPlayingProvider) => {
const c = byProvider.get(p);
if (!c) return null;
return (
{c.status === 'error'
? `Needs reconnecting: ${c.lastError}`
: `Connected as ${c.displayName ?? c.externalUserId}${c.lastPolledAt ? ` · checked ${timeAgo(c.lastPolledAt)}` : ''}`}
);
};
return (
Music services
Connect where you listen. Your friends see what you're playing in real time.
{error && {error}
}
{/* Spotify caps new apps at a handful of accounts; Spotify's own Last.fm/ListenBrainz link works for everyone. */}
Spotify sends everything you play to Last.fm or ListenBrainz , and we share it from
there. Connect one of them below, then link Spotify on their site:
Last.fm (most popular): sign in below, then{' '}
connect “Spotify Scrobbling” on Last.fm
.
ListenBrainz (open source): add your username below, then{' '}
connect Spotify on ListenBrainz
.
On Android, the musicshare app shares Spotify automatically.
{status('plex') ?? Music you play from your Plex servers }
{byProvider.get('plex')?.status === 'active' ? (
disconnect('plex')}>
Disconnect
) : (
connectOAuth('plex')}>
{byProvider.has('plex') ? 'Reconnect' : 'Connect'}
)}
{byProvider.get('jellyfin')?.status === 'active' && (
disconnect('jellyfin')}>
Disconnect
)}
{connections.filter((c) => isQuietScrobbler(c)).map((c) => (
Nothing new from {SERVICE_LABELS[c.provider]} in over a week. If you listen on Spotify, its link to{' '}
{SERVICE_LABELS[c.provider]} expires every 6 months.{' '}
Re-link Spotify
.
))}
{(['lastfm', 'listenbrainz'] as const).map((p) => (
{status(p) ?? (
{p === 'lastfm'
? 'Works with anything that scrobbles: YouTube Music, Tidal, Deezer, SoundCloud…'
: 'Open-source scrobbling'}
)}
{byProvider.has(p) ? (
{p === 'lastfm' && (
Link Spotify
)}
disconnect(p)}>
Disconnect
) : p === 'lastfm' ? (
connectOAuth('lastfm')}>
Sign in with Last.fm
) : (
Connect
)}
))}
{byProvider.has('apple_music') ? status('apple_music') : 'Connect from the musicshare iPhone app (one tap)'}
);
}
const WEBHOOK_HELP: Partial> = {
plex: 'Plex Pass: add this under Plex → Settings → Webhooks for instant updates.',
jellyfin: 'Optional: add this URL in the Jellyfin Webhook plugin (Playback Start/Stop) for instant updates.',
};
function WebhookHint({ connection }: { connection: ConnectionDTO | undefined }) {
const [copied, setCopied] = useState(false);
if (!connection?.webhookUrl || connection.status !== 'active') return null;
const copy = async () => {
await navigator.clipboard.writeText(connection.webhookUrl!);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
};
return (
Instant updates
{WEBHOOK_HELP[connection.provider]}
{connection.webhookUrl}
{copied ? 'Copied' : 'Copy'}
);
}
function FeaturedPicker() {
const { me } = useMe();
const [q, setQ] = useState('');
const [selected, setSelected] = useState(null);
const [comment, setComment] = useState('');
const [saved, setSaved] = useState(false);
const debounced = useDebounced(q.trim(), 300);
const { data: results } = useSWR(
debounced.length >= 2 && !selected ? `/tracks/search?q=${encodeURIComponent(debounced)}` : null,
fetcher,
);
const save = async () => {
if (!selected) return;
await api('/me/featured', { method: 'PUT', body: { deezerId: selected.deezerId, comment: comment || null } });
setSaved(true);
};
return (
Featured song
Pin a song to your profile, with an optional note about why.
{selected ? (
{selected.artworkUrl &&
}
{selected.title}
{selected.artist}
{
setSelected(null);
setSaved(false);
}}
>
Change
) : (
<>
setQ(e.target.value)} />
{results && (
{results.map((r) => (
setSelected(r)}>
{r.artworkUrl && }
{r.title} · {r.artist}
))}
)}
>
)}
{selected && (
<>
setComment(e.target.value)}
/>
{saved ? 'Featured ✓' : 'Feature this song'}
{saved && me && (
View profile →
)}
>
)}
);
}
function DangerZone() {
const [confirming, setConfirming] = useState(false);
const router = useRouter();
const { mutate } = useMe();
const remove = async () => {
await api('/me', { method: 'DELETE' });
await mutate(undefined, { revalidate: true });
router.push('/');
};
return (
Delete account
Permanently removes your profile, follows and connected services.
{confirming ? (
Yes, delete my account
setConfirming(false)}>
Cancel
) : (
setConfirming(true)}>
Delete account…
)}
);
}