|
| 1 | +import { useCallback, useEffect, useRef, useState } from 'react' |
| 2 | +import { |
| 3 | + ActivityIndicator, |
| 4 | + StyleSheet, |
| 5 | + Text, |
| 6 | + TextInput, |
| 7 | + TouchableOpacity, |
| 8 | + View |
| 9 | +} from 'react-native' |
| 10 | +import { WebView } from 'react-native-webview' |
| 11 | +import { StatusBar } from 'expo-status-bar' |
| 12 | +import * as Linking from 'expo-linking' |
| 13 | +import { buildOAuthUrl, randomState } from './src/oauth/buildOAuthUrl' |
| 14 | +import { getSDK } from './src/sdk' |
| 15 | +import { config } from './src/config' |
| 16 | + |
| 17 | +const REDIRECT_URI = 'http://localhost/oauth/callback' |
| 18 | + |
| 19 | +type Screen = 'home' | 'webview' | 'signed-in' |
| 20 | + |
| 21 | +export default function App() { |
| 22 | + const [screen, setScreen] = useState<Screen>('home') |
| 23 | + const [loading, setLoading] = useState(false) |
| 24 | + const [error, setError] = useState<string | null>(null) |
| 25 | + const [userId, setUserId] = useState<string | null>(null) |
| 26 | + const [profile, setProfile] = useState<{ handle: string } | null>(null) |
| 27 | + const [description, setDescription] = useState('') |
| 28 | + const [updateLoading, setUpdateLoading] = useState(false) |
| 29 | + const [result, setResult] = useState<string | null>(null) |
| 30 | + const oauthStateRef = useRef<string | null>(null) |
| 31 | + |
| 32 | + const handleOpenAuth = useCallback(() => { |
| 33 | + setError(null) |
| 34 | + const state = randomState() |
| 35 | + oauthStateRef.current = state |
| 36 | + setScreen('webview') |
| 37 | + }, []) |
| 38 | + |
| 39 | + const handleRedirect = useCallback( |
| 40 | + async (url: string) => { |
| 41 | + if (!url.startsWith(REDIRECT_URI) && !url.startsWith('audiuswrites://oauth/callback')) return |
| 42 | + setScreen('home') |
| 43 | + setLoading(true) |
| 44 | + setError(null) |
| 45 | + try { |
| 46 | + const parsed = Linking.parse(url) |
| 47 | + const query = (parsed.queryParams ?? {}) as Record<string, string> |
| 48 | + const token = query.token ?? query.access_token ?? (parsed.fragment ?? '').split('token=')[1]?.split('&')[0] |
| 49 | + const state = query.state |
| 50 | + if (!token) { |
| 51 | + setError('No token in redirect') |
| 52 | + return |
| 53 | + } |
| 54 | + if (state !== oauthStateRef.current) { |
| 55 | + setError('State mismatch') |
| 56 | + return |
| 57 | + } |
| 58 | + const verifyRes = await getSDK().users.verifyIDToken({ token }) |
| 59 | + const data = verifyRes.data |
| 60 | + if (!data) { |
| 61 | + setError('Invalid token') |
| 62 | + return |
| 63 | + } |
| 64 | + const uid = data.userId ?? data.sub |
| 65 | + setProfile({ handle: data.handle ?? data.sub ?? 'Unknown' }) |
| 66 | + setUserId(uid) |
| 67 | + setScreen('signed-in') |
| 68 | + } catch (e: unknown) { |
| 69 | + if (e && typeof e === 'object' && 'response' in e && e.response && typeof (e.response as Response).text === 'function') { |
| 70 | + const res = e.response as Response |
| 71 | + try { |
| 72 | + const body = await res.text() |
| 73 | + setError(`API error ${res.status}: ${body || res.statusText || 'Unknown'}`) |
| 74 | + } catch { |
| 75 | + setError(`API error ${res.status}`) |
| 76 | + } |
| 77 | + } else { |
| 78 | + setError(e instanceof Error ? e.message : 'Sign-in failed') |
| 79 | + } |
| 80 | + } finally { |
| 81 | + setLoading(false) |
| 82 | + } |
| 83 | + }, |
| 84 | + [] |
| 85 | + ) |
| 86 | + |
| 87 | + useEffect(() => { |
| 88 | + const sub = Linking.addEventListener('url', (event) => handleRedirect(event.url)) |
| 89 | + Linking.getInitialURL().then((url) => { if (url) handleRedirect(url) }) |
| 90 | + return () => sub.remove() |
| 91 | + }, [handleRedirect]) |
| 92 | + |
| 93 | + const handleSignOut = useCallback(() => { |
| 94 | + setUserId(null) |
| 95 | + setProfile(null) |
| 96 | + setDescription('') |
| 97 | + setResult(null) |
| 98 | + setScreen('home') |
| 99 | + setError(null) |
| 100 | + }, []) |
| 101 | + |
| 102 | + const handleUpdate = useCallback(async () => { |
| 103 | + if (!config.writeServerUrl || !userId) return |
| 104 | + setUpdateLoading(true) |
| 105 | + setResult(null) |
| 106 | + try { |
| 107 | + const res = await fetch(`${config.writeServerUrl}/update-description`, { |
| 108 | + method: 'POST', |
| 109 | + headers: { 'Content-Type': 'application/json' }, |
| 110 | + body: JSON.stringify({ userId, description: description.trim() }) |
| 111 | + }) |
| 112 | + const data = await res.json().catch(() => ({})) |
| 113 | + if (res.ok) { |
| 114 | + setResult('Description updated.') |
| 115 | + } else { |
| 116 | + setResult(data?.error ?? `Error ${res.status}`) |
| 117 | + } |
| 118 | + } catch (e) { |
| 119 | + setResult(e instanceof Error ? e.message : 'Request failed') |
| 120 | + } finally { |
| 121 | + setUpdateLoading(false) |
| 122 | + } |
| 123 | + }, [userId, description]) |
| 124 | + |
| 125 | + if (screen === 'webview') { |
| 126 | + const state = oauthStateRef.current ?? randomState() |
| 127 | + oauthStateRef.current = state |
| 128 | + const oauthUrl = buildOAuthUrl({ |
| 129 | + scope: 'write', |
| 130 | + redirectUri: REDIRECT_URI, |
| 131 | + state, |
| 132 | + responseMode: 'query', |
| 133 | + display: 'fullScreen', |
| 134 | + ...(config.apiKey ? { apiKey: config.apiKey } : { appName: 'AudiusWritesExample' }) |
| 135 | + }) |
| 136 | + return ( |
| 137 | + <View style={styles.container}> |
| 138 | + <TouchableOpacity style={styles.backBtn} onPress={() => setScreen('home')}> |
| 139 | + <Text style={styles.backBtnText}>← Cancel</Text> |
| 140 | + </TouchableOpacity> |
| 141 | + <WebView |
| 142 | + source={{ uri: oauthUrl }} |
| 143 | + style={styles.webview} |
| 144 | + onShouldStartLoadWithRequest={(req) => { |
| 145 | + if (req.url.startsWith(REDIRECT_URI) || req.url.startsWith('audiuswrites://oauth/callback')) { |
| 146 | + handleRedirect(req.url) |
| 147 | + return false |
| 148 | + } |
| 149 | + return true |
| 150 | + }} |
| 151 | + /> |
| 152 | + <StatusBar style="auto" /> |
| 153 | + </View> |
| 154 | + ) |
| 155 | + } |
| 156 | + |
| 157 | + if (screen === 'signed-in' && userId && profile) { |
| 158 | + return ( |
| 159 | + <View style={styles.container}> |
| 160 | + <View style={styles.card}> |
| 161 | + <View style={styles.profileRow}> |
| 162 | + <Text style={styles.handle}>@{profile.handle}</Text> |
| 163 | + <TouchableOpacity style={styles.signOutBtn} onPress={handleSignOut}> |
| 164 | + <Text style={styles.signOutBtnText}>Sign out</Text> |
| 165 | + </TouchableOpacity> |
| 166 | + </View> |
| 167 | + <Text style={styles.title}>Update description</Text> |
| 168 | + <Text style={styles.subtitle}> |
| 169 | + Server uses your stored bearer to update your bio. |
| 170 | + </Text> |
| 171 | + <TextInput |
| 172 | + style={styles.input} |
| 173 | + placeholder="New description" |
| 174 | + placeholderTextColor="#888" |
| 175 | + value={description} |
| 176 | + onChangeText={setDescription} |
| 177 | + multiline |
| 178 | + numberOfLines={3} |
| 179 | + /> |
| 180 | + <TouchableOpacity |
| 181 | + style={[styles.button, updateLoading && styles.buttonDisabled]} |
| 182 | + onPress={handleUpdate} |
| 183 | + disabled={updateLoading} |
| 184 | + > |
| 185 | + {updateLoading ? ( |
| 186 | + <ActivityIndicator size="small" color="#fff" /> |
| 187 | + ) : ( |
| 188 | + <Text style={styles.buttonText}>Update description</Text> |
| 189 | + )} |
| 190 | + </TouchableOpacity> |
| 191 | + {result ? <Text style={styles.result}>{result}</Text> : null} |
| 192 | + </View> |
| 193 | + <StatusBar style="auto" /> |
| 194 | + </View> |
| 195 | + ) |
| 196 | + } |
| 197 | + |
| 198 | + if (!config.isConfigured) { |
| 199 | + return ( |
| 200 | + <View style={styles.container}> |
| 201 | + <View style={styles.card}> |
| 202 | + <Text style={styles.title}>Authenticated writes</Text> |
| 203 | + <Text style={styles.required}> |
| 204 | + Requires your server. Create a .env with: |
| 205 | + </Text> |
| 206 | + <Text style={styles.code}>EXPO_PUBLIC_AUDIUS_API_KEY=your_api_key</Text> |
| 207 | + <Text style={styles.code}>EXPO_PUBLIC_WRITE_SERVER_URL=http://localhost:3001</Text> |
| 208 | + <Text style={styles.required}> |
| 209 | + Run the server with AUDIUS_API_KEY. See README. |
| 210 | + </Text> |
| 211 | + </View> |
| 212 | + <StatusBar style="auto" /> |
| 213 | + </View> |
| 214 | + ) |
| 215 | + } |
| 216 | + |
| 217 | + return ( |
| 218 | + <View style={styles.container}> |
| 219 | + <View style={styles.center}> |
| 220 | + <Text style={styles.title}>Authenticated writes</Text> |
| 221 | + <Text style={styles.subtitle}> |
| 222 | + Sign in with Audius (write scope) to authorize the app, then update your description. |
| 223 | + </Text> |
| 224 | + {loading ? ( |
| 225 | + <ActivityIndicator size="large" style={styles.loader} /> |
| 226 | + ) : ( |
| 227 | + <TouchableOpacity style={styles.button} onPress={handleOpenAuth} disabled={loading}> |
| 228 | + <Text style={styles.buttonText}>Sign in with Audius (write)</Text> |
| 229 | + </TouchableOpacity> |
| 230 | + )} |
| 231 | + {error ? <Text style={styles.error}>{error}</Text> : null} |
| 232 | + </View> |
| 233 | + <StatusBar style="auto" /> |
| 234 | + </View> |
| 235 | + ) |
| 236 | +} |
| 237 | + |
| 238 | +const styles = StyleSheet.create({ |
| 239 | + container: { flex: 1, backgroundColor: '#fff', paddingTop: 60 }, |
| 240 | + center: { flex: 1, padding: 24, justifyContent: 'center' }, |
| 241 | + card: { margin: 24, padding: 24, backgroundColor: '#f5f5f5', borderRadius: 12 }, |
| 242 | + title: { fontSize: 20, fontWeight: '600', marginBottom: 8 }, |
| 243 | + subtitle: { fontSize: 14, color: '#666', marginBottom: 16 }, |
| 244 | + required: { fontSize: 13, color: '#333', marginTop: 12 }, |
| 245 | + code: { fontFamily: 'monospace', fontSize: 12, color: '#555', marginTop: 6 }, |
| 246 | + profileRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }, |
| 247 | + handle: { fontSize: 16, color: '#333' }, |
| 248 | + signOutBtn: { paddingVertical: 8, paddingHorizontal: 16 }, |
| 249 | + signOutBtnText: { color: '#0066cc', fontSize: 16 }, |
| 250 | + input: { |
| 251 | + borderWidth: 1, |
| 252 | + borderColor: '#ccc', |
| 253 | + borderRadius: 8, |
| 254 | + padding: 12, |
| 255 | + marginBottom: 12, |
| 256 | + fontSize: 14, |
| 257 | + minHeight: 80, |
| 258 | + textAlignVertical: 'top' |
| 259 | + }, |
| 260 | + button: { |
| 261 | + backgroundColor: '#CC0FE0', |
| 262 | + paddingVertical: 14, |
| 263 | + paddingHorizontal: 24, |
| 264 | + borderRadius: 8, |
| 265 | + alignSelf: 'flex-start' |
| 266 | + }, |
| 267 | + buttonDisabled: { opacity: 0.7 }, |
| 268 | + buttonText: { color: '#fff', fontSize: 16, fontWeight: '600' }, |
| 269 | + result: { fontSize: 13, color: '#333', marginTop: 12 }, |
| 270 | + loader: { marginVertical: 16 }, |
| 271 | + error: { color: '#d32f2f', marginTop: 12, fontSize: 13 }, |
| 272 | + backBtn: { padding: 16 }, |
| 273 | + backBtnText: { color: '#0066cc', fontSize: 16 }, |
| 274 | + webview: { flex: 1 } |
| 275 | +}) |
0 commit comments