- Replace mobile placeholder with Expo Router app (tabs, playback, auth, library) - Move Convex backend to @otunes/convex for web and mobile reuse - Update web app imports and API routes to use shared package
396 lines
13 KiB
TypeScript
396 lines
13 KiB
TypeScript
import { useAction, useMutation, useQuery } from "convex/react"
|
|
import * as ImagePicker from "expo-image-picker"
|
|
import { useState } from "react"
|
|
import {
|
|
Pressable,
|
|
ScrollView,
|
|
StyleSheet,
|
|
Switch,
|
|
Text,
|
|
View,
|
|
} from "react-native"
|
|
import { SafeAreaView } from "react-native-safe-area-context"
|
|
|
|
import { ScreenHeader } from "@/components/screen-header"
|
|
import { Button, Input, LoadingView } from "@/components/ui/primitives"
|
|
import { contentBottomInset } from "@/components/player"
|
|
import { api } from "@otunes/convex/_generated/api"
|
|
import type { Doc, Id } from "@otunes/convex/_generated/dataModel"
|
|
import { initialsFromName } from "@/lib/format"
|
|
import { showError, showSuccess } from "@/lib/toast"
|
|
import type { PlaybackQuality } from "@/lib/urls"
|
|
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
|
|
|
type Section = "profile" | "quality" | "users" | "library"
|
|
|
|
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" },
|
|
]
|
|
|
|
export default function SettingsScreen() {
|
|
const colors = useThemeColors()
|
|
const user = useQuery(api.auth.currentUser)
|
|
const allUsers = useQuery(api.users.listUsers)
|
|
const [section, setSection] = useState<Section>("profile")
|
|
|
|
if (!user) {
|
|
return (
|
|
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]} edges={["top"]}>
|
|
<ScreenHeader title="Settings" />
|
|
<LoadingView />
|
|
</SafeAreaView>
|
|
)
|
|
}
|
|
|
|
const isAdmin = user.isAdmin === true
|
|
const sections: { id: Section; label: string; admin?: boolean }[] = [
|
|
{ id: "profile", label: "Profile" },
|
|
{ id: "quality", label: "Quality" },
|
|
{ id: "library", label: "Library", admin: true },
|
|
{ id: "users", label: "Users", admin: true },
|
|
]
|
|
|
|
return (
|
|
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]} edges={["top"]}>
|
|
<ScreenHeader title="Settings" />
|
|
<ScrollView contentContainerStyle={{ paddingBottom: contentBottomInset }}>
|
|
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.tabs}>
|
|
{sections
|
|
.filter((item) => !item.admin || isAdmin)
|
|
.map((item) => (
|
|
<Pressable
|
|
key={item.id}
|
|
onPress={() => setSection(item.id)}
|
|
style={[
|
|
styles.tab,
|
|
{
|
|
backgroundColor:
|
|
section === item.id ? colors.foreground : colors.muted,
|
|
},
|
|
]}
|
|
>
|
|
<Text
|
|
style={{
|
|
color: section === item.id ? colors.background : colors.foreground,
|
|
fontWeight: "600",
|
|
}}
|
|
>
|
|
{item.label}
|
|
</Text>
|
|
</Pressable>
|
|
))}
|
|
</ScrollView>
|
|
|
|
<View style={styles.content}>
|
|
{section === "profile" ? <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}
|
|
</View>
|
|
</ScrollView>
|
|
</SafeAreaView>
|
|
)
|
|
}
|
|
|
|
function ProfileSection({ user }: { user: Doc<"users"> }) {
|
|
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}` })
|
|
showSuccess("Profile photo updated")
|
|
} catch (error) {
|
|
showError(error instanceof Error ? error.message : "Failed to update photo")
|
|
}
|
|
}
|
|
|
|
async function handlePasswordChange() {
|
|
if (newPassword !== confirmPassword) {
|
|
showError("Passwords do not match")
|
|
return
|
|
}
|
|
setChangingPassword(true)
|
|
try {
|
|
await updatePassword({ newPassword })
|
|
setNewPassword("")
|
|
setConfirmPassword("")
|
|
showSuccess("Password updated")
|
|
} catch (error) {
|
|
showError(error instanceof Error ? error.message : "Failed to update password")
|
|
} finally {
|
|
setChangingPassword(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<View style={styles.sectionBlock}>
|
|
<View style={[styles.avatar, { backgroundColor: colors.muted }]}>
|
|
<Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 20 }}>
|
|
{initialsFromName(user.name)}
|
|
</Text>
|
|
</View>
|
|
<Button title="Upload profile photo" variant="secondary" onPress={() => void pickImage()} />
|
|
{user.image ? (
|
|
<Button title="Remove photo" variant="ghost" onPress={() => void updateImage({ image: null })} />
|
|
) : null}
|
|
<Input value={name} onChangeText={setName} placeholder="Name" />
|
|
<Button
|
|
title="Save name"
|
|
variant="secondary"
|
|
onPress={() =>
|
|
void updateName({ name }).catch((error: Error) => showError(error.message))
|
|
}
|
|
/>
|
|
<Input
|
|
value={email}
|
|
onChangeText={setEmail}
|
|
placeholder="Email"
|
|
autoCapitalize="none"
|
|
keyboardType="email-address"
|
|
/>
|
|
<Button
|
|
title="Save email"
|
|
variant="secondary"
|
|
onPress={() =>
|
|
void updateEmail({ email }).catch((error: Error) => showError(error.message))
|
|
}
|
|
/>
|
|
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>Password</Text>
|
|
<Input value={newPassword} onChangeText={setNewPassword} placeholder="New password" secureTextEntry />
|
|
<Input
|
|
value={confirmPassword}
|
|
onChangeText={setConfirmPassword}
|
|
placeholder="Confirm password"
|
|
secureTextEntry
|
|
/>
|
|
<Button
|
|
title="Update password"
|
|
loading={changingPassword}
|
|
disabled={!newPassword || newPassword !== confirmPassword}
|
|
onPress={() => void handlePasswordChange()}
|
|
/>
|
|
</View>
|
|
)
|
|
}
|
|
|
|
function QualitySection({ user }: { user: Doc<"users"> }) {
|
|
const colors = useThemeColors()
|
|
const updateQuality = useMutation(api.users.updatePlaybackQuality)
|
|
const updateAtmos = useMutation(api.users.updatePreferAtmos)
|
|
const quality = user.playbackQuality ?? "medium"
|
|
|
|
return (
|
|
<View style={styles.sectionBlock}>
|
|
{QUALITY_OPTIONS.map((option) => (
|
|
<Pressable
|
|
key={option.value}
|
|
style={[
|
|
styles.qualityRow,
|
|
{
|
|
borderColor: colors.border,
|
|
backgroundColor: quality === option.value ? colors.muted : colors.card,
|
|
},
|
|
]}
|
|
onPress={() =>
|
|
void updateQuality({ playbackQuality: option.value }).catch((error: Error) =>
|
|
showError(error.message)
|
|
)
|
|
}
|
|
>
|
|
<Text style={{ color: colors.foreground, fontWeight: "600" }}>{option.label}</Text>
|
|
<Text style={{ color: colors.mutedForeground }}>{option.description}</Text>
|
|
</Pressable>
|
|
))}
|
|
<View style={[styles.switchRow, { borderColor: colors.border }]}>
|
|
<Text style={{ color: colors.foreground, flex: 1 }}>
|
|
Prefer Dolby Atmos when available
|
|
</Text>
|
|
<Switch
|
|
value={user.preferAtmos ?? false}
|
|
onValueChange={(checked) =>
|
|
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
|
|
showError(error.message)
|
|
)
|
|
}
|
|
/>
|
|
</View>
|
|
</View>
|
|
)
|
|
}
|
|
|
|
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 (
|
|
<View style={styles.sectionBlock}>
|
|
<Button
|
|
title="Update library"
|
|
loading={updating}
|
|
onPress={async () => {
|
|
setUpdating(true)
|
|
try {
|
|
await updateLibrary({})
|
|
showSuccess("Library updated")
|
|
} catch (error) {
|
|
showError(error instanceof Error ? error.message : "Failed to update library")
|
|
} finally {
|
|
setUpdating(false)
|
|
}
|
|
}}
|
|
/>
|
|
<Button
|
|
title="Clean HLS streams"
|
|
variant="secondary"
|
|
loading={cleaningHls}
|
|
onPress={async () => {
|
|
setCleaningHls(true)
|
|
try {
|
|
const result = await cleanupHlsStreams({})
|
|
showSuccess(`Removed ${result.removed} idle HLS streams`)
|
|
} catch (error) {
|
|
showError(error instanceof Error ? error.message : "Failed to clean HLS streams")
|
|
} finally {
|
|
setCleaningHls(false)
|
|
}
|
|
}}
|
|
/>
|
|
</View>
|
|
)
|
|
}
|
|
|
|
function UsersSection({
|
|
users,
|
|
currentUserId,
|
|
}: {
|
|
users: Doc<"users">[]
|
|
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 (
|
|
<View style={styles.sectionBlock}>
|
|
<View style={[styles.switchRow, { borderColor: colors.border }]}>
|
|
<Text style={{ color: colors.foreground, flex: 1 }}>Disable account creation</Text>
|
|
<Switch
|
|
value={appSettings?.disableAccountCreation ?? false}
|
|
onValueChange={(checked) =>
|
|
void setDisableCreation({ disabled: checked }).catch((error: Error) =>
|
|
showError(error.message)
|
|
)
|
|
}
|
|
/>
|
|
</View>
|
|
{users.map((user) => (
|
|
<View key={user._id} style={[styles.userRow, { borderColor: colors.border }]}>
|
|
<View style={{ flex: 1 }}>
|
|
<Text style={{ color: colors.foreground, fontWeight: "600" }}>{user.name}</Text>
|
|
<Text style={{ color: colors.mutedForeground }}>{user.email}</Text>
|
|
{user.isAdmin ? (
|
|
<Text style={{ color: colors.mutedForeground }}>Admin</Text>
|
|
) : null}
|
|
</View>
|
|
{user._id !== currentUserId ? (
|
|
<View style={styles.userActions}>
|
|
<Button
|
|
title={user.isAdmin ? "Remove admin" : "Make admin"}
|
|
variant="secondary"
|
|
onPress={() =>
|
|
void setAdmin({ userId: user._id, isAdmin: !user.isAdmin }).then(() =>
|
|
showSuccess("Updated permissions")
|
|
)
|
|
}
|
|
/>
|
|
<Button
|
|
title="Delete"
|
|
variant="destructive"
|
|
onPress={() =>
|
|
void deleteUserMutation({ userId: user._id }).then(() =>
|
|
showSuccess("User deleted")
|
|
)
|
|
}
|
|
/>
|
|
</View>
|
|
) : null}
|
|
</View>
|
|
))}
|
|
</View>
|
|
)
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
safe: { flex: 1 },
|
|
tabs: {
|
|
paddingHorizontal: spacing.lg,
|
|
paddingVertical: spacing.md,
|
|
},
|
|
tab: {
|
|
paddingHorizontal: spacing.md,
|
|
paddingVertical: spacing.sm,
|
|
borderRadius: radius.full,
|
|
marginRight: spacing.sm,
|
|
},
|
|
content: { paddingHorizontal: spacing.lg },
|
|
sectionBlock: { gap: spacing.md, paddingBottom: spacing.xl },
|
|
sectionTitle: { fontSize: 16, fontWeight: "700", marginTop: spacing.md },
|
|
avatar: {
|
|
width: 72,
|
|
height: 72,
|
|
borderRadius: 36,
|
|
alignItems: "center",
|
|
justifyContent: "center",
|
|
},
|
|
qualityRow: {
|
|
borderWidth: 1,
|
|
borderRadius: radius.md,
|
|
padding: spacing.md,
|
|
gap: 4,
|
|
},
|
|
switchRow: {
|
|
flexDirection: "row",
|
|
alignItems: "center",
|
|
gap: spacing.md,
|
|
borderWidth: 1,
|
|
borderRadius: radius.md,
|
|
padding: spacing.md,
|
|
},
|
|
userRow: {
|
|
borderWidth: 1,
|
|
borderRadius: radius.md,
|
|
padding: spacing.md,
|
|
gap: spacing.sm,
|
|
},
|
|
userActions: { gap: spacing.sm },
|
|
})
|