-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathApp.tsx
More file actions
448 lines (417 loc) · 14 KB
/
Copy pathApp.tsx
File metadata and controls
448 lines (417 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import { useCallback, useEffect, useRef, useState } from 'react'
import { type User } from '@audius/sdk'
import * as DocumentPicker from 'expo-document-picker'
import * as ImagePicker from 'expo-image-picker'
import { StatusBar } from 'expo-status-bar'
import {
ActivityIndicator,
ScrollView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native'
import {
createSessionId,
formatErrorForDebug,
newOperationId
} from '../shared/exampleDebug'
import { config } from './src/config'
import { getSDK } from './src/sdk'
// Genre is a freeform string up to 100 chars at the API/SDK layer. See
// `Genre` from @audius/sdk for the canonical autocomplete suggestions if
// you want to show a picker; this example uses a plain text input.
const MAX_GENRE_LENGTH = 100
type Screen = 'home' | 'signed-in'
export default function App() {
const [screen, setScreen] = useState<Screen>('home')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [profile, setProfile] = useState<User | null>(null)
const [audioFile, setAudioFile] =
useState<DocumentPicker.DocumentPickerAsset | null>(null)
const [coverUri, setCoverUri] = useState<string | null>(null)
const [title, setTitle] = useState('')
const [genre, setGenre] = useState<string>('')
const [description, setDescription] = useState('')
const [uploading, setUploading] = useState(false)
const [result, setResult] = useState<string | null>(null)
const [debugLogs, setDebugLogs] = useState<string[]>([])
const sessionIdRef = useRef(createSessionId())
const opIdRef = useRef(`boot-${newOperationId()}`)
const sdk = getSDK()
const logDebug = useCallback((message: string, payload?: unknown) => {
const timestamp = new Date().toISOString().slice(11, 19)
const details =
payload === undefined
? ''
: ` ${JSON.stringify(
payload,
(_, value) => (value instanceof Error ? value.message : value),
2
)}`
const line = `[sess:${sessionIdRef.current}][op:${opIdRef.current}] [${timestamp}] ${message}${details}`
console.log(`[upload] ${line}`)
setDebugLogs((prev) => [...prev.slice(-79), line])
}, [])
// On mount: restore existing session.
useEffect(() => {
opIdRef.current = `restore-${newOperationId()}`
logDebug('Checking existing OAuth session')
sdk.oauth.isAuthenticated().then((authenticated) => {
logDebug('oauth.isAuthenticated resolved', { authenticated })
if (!authenticated) return
setLoading(true)
sdk.oauth
.getUser()
.then((user) => {
setProfile(user ?? null)
setScreen('signed-in')
logDebug('oauth.getUser succeeded (session restore)', {
handle: user.handle,
id: user.id
})
})
.catch(async (e) => {
console.error('Failed to get user', e)
const details = await formatErrorForDebug(e)
logDebug('Session restore failed', details)
})
.finally(() => setLoading(false))
})
}, [sdk.oauth, logDebug])
const handleSignIn = useCallback(async () => {
opIdRef.current = `signin-${newOperationId()}`
setError(null)
setLoading(true)
try {
logDebug('Starting oauth.login')
await sdk.oauth.login({
scope: 'write',
display: 'fullScreen'
})
logDebug('oauth.login succeeded')
const user = await sdk.oauth.getUser()
logDebug('oauth.getUser succeeded', { handle: user.handle, id: user.id })
setProfile(user)
setScreen('signed-in')
} catch (e: unknown) {
const details = await formatErrorForDebug(e)
logDebug('Sign-in flow failed', details)
setError(e instanceof Error ? e.message : 'Sign-in failed')
} finally {
setLoading(false)
}
}, [sdk.oauth, logDebug])
const handleSignOut = useCallback(async () => {
logDebug('Starting oauth.logout')
await sdk.oauth.logout().catch(() => {})
logDebug('oauth.logout completed')
setProfile(null)
setAudioFile(null)
setCoverUri(null)
setTitle('')
setGenre('')
setDescription('')
setResult(null)
setScreen('home')
setError(null)
}, [sdk.oauth, logDebug])
const pickAudio = useCallback(async () => {
try {
const res = await DocumentPicker.getDocumentAsync({
type: 'audio/*',
copyToCacheDirectory: true
})
if (res.canceled) return
setAudioFile(res.assets[0] ?? null)
setResult(null)
} catch (e) {
setResult(e instanceof Error ? e.message : 'Failed to pick audio')
}
}, [])
const pickCover = useCallback(async () => {
try {
const res = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: true,
aspect: [1, 1],
quality: 0.8
})
if (res.canceled) return
setCoverUri(res.assets[0]?.uri ?? null)
setResult(null)
} catch (e) {
setResult(e instanceof Error ? e.message : 'Failed to pick cover')
}
}, [])
const handleUpload = useCallback(async () => {
if (!profile) return
if (!audioFile) {
setResult('Please select an audio file')
return
}
if (!title.trim()) {
setResult('Please enter a title')
return
}
opIdRef.current = `upload-${newOperationId()}`
setUploading(true)
setResult(null)
try {
logDebug('Starting upload flow', { userId: profile.id, title: title.trim() })
setResult('Uploading audio...')
const audioUpload = sdk.uploads.createAudioUpload({
file: {
uri: audioFile.uri,
name: audioFile.name ?? 'audio',
type: audioFile.mimeType ?? 'audio/mpeg'
}
})
const imageUpload = coverUri
? sdk.uploads.createImageUpload({
file: { uri: coverUri, name: 'cover.jpg', type: 'image/jpeg' }
})
: undefined
if (coverUri) setResult('Uploading cover art...')
const [audioResult, coverArtSizes] = await Promise.all([
audioUpload.start(),
imageUpload?.start()
])
if (!audioResult.trackCid) {
logDebug('Audio upload missing trackCid')
setResult('Audio upload did not return a track CID')
return
}
setResult('Creating track...')
const userId = String(profile.id ?? '')
const res = await sdk.tracks.createTrack({
userId,
metadata: {
title: title.trim(),
genre,
...audioResult,
trackCid: audioResult.trackCid,
description: description.trim() || undefined,
coverArtSizes
}
})
logDebug('tracks.createTrack succeeded', { trackId: res?.trackId })
setResult(`Track created! ID: ${res?.trackId ?? '—'}`)
} catch (e: unknown) {
const details = await formatErrorForDebug(e)
logDebug('Upload / createTrack failed', details)
const rid =
typeof details.requestId === 'string' ? ` (requestId: ${details.requestId})` : ''
setResult(
`${details.message ?? (e instanceof Error ? e.message : 'Request failed')}${rid}`
)
} finally {
setUploading(false)
}
}, [profile, audioFile, coverUri, title, genre, description, sdk, logDebug])
if (!config.isConfigured) {
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.title}>OAuth Upload</Text>
<Text style={styles.body}>
Requires an Audius developer app API key.
</Text>
<Text style={styles.body}>Create a .env file with:</Text>
<Text style={styles.code}>
EXPO_PUBLIC_AUDIUS_API_KEY=your_api_key
</Text>
<Text style={styles.body}>
Get one at audius.co/settings → Developer Apps.
</Text>
</View>
<StatusBar style="auto" />
</View>
)
}
if (screen === 'signed-in' && profile) {
return (
<View style={styles.container}>
<ScrollView
style={styles.scroll}
contentContainerStyle={styles.scrollContent}
>
<View style={styles.profileRow}>
<Text style={styles.handle}>@{profile.handle ?? 'user'}</Text>
<TouchableOpacity style={styles.signOutBtn} onPress={handleSignOut}>
<Text style={styles.signOutBtnText}>Sign out</Text>
</TouchableOpacity>
</View>
<Text style={styles.title}>Upload track</Text>
<Text style={styles.subtitle}>
Pick an audio file and add metadata. The track is created directly
via the OAuth access token — no backend server needed.
</Text>
<TouchableOpacity style={styles.pickBtn} onPress={pickAudio}>
<Text style={styles.pickBtnText}>
{audioFile
? `Audio: ${audioFile.name ?? 'Selected'}`
: 'Pick audio file'}
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.pickBtn} onPress={pickCover}>
<Text style={styles.pickBtnText}>
{coverUri ? 'Cover art selected' : 'Pick cover art (optional)'}
</Text>
</TouchableOpacity>
<TextInput
style={styles.input}
placeholder="Track title"
placeholderTextColor="#888"
value={title}
onChangeText={setTitle}
/>
<Text style={styles.label}>Genre</Text>
<TextInput
style={styles.input}
placeholder="e.g. Electronic, Phonk, Lo-Fi…"
placeholderTextColor="#888"
value={genre}
onChangeText={setGenre}
maxLength={MAX_GENRE_LENGTH}
autoCapitalize="words"
autoCorrect={false}
/>
<TextInput
style={[styles.input, styles.textArea]}
placeholder="Description (optional)"
placeholderTextColor="#888"
value={description}
onChangeText={setDescription}
multiline
numberOfLines={3}
/>
<TouchableOpacity
style={[styles.button, uploading && styles.buttonDisabled]}
onPress={handleUpload}
disabled={uploading}
>
{uploading ? (
<ActivityIndicator size="small" color="#fff" />
) : (
<Text style={styles.buttonText}>Upload</Text>
)}
</TouchableOpacity>
{result ? <Text style={styles.result}>{result}</Text> : null}
<Text style={styles.debugTitle}>Debug Log</Text>
<Text style={styles.debugSession} selectable>
Session: {sessionIdRef.current} (share with support)
</Text>
<View style={styles.debugBox}>
{debugLogs.length === 0 ? (
<Text style={styles.debugLine}>No log entries yet</Text>
) : (
debugLogs.slice(-10).map((line, index) => (
<Text key={`${line}-${index}`} style={styles.debugLine}>
{line}
</Text>
))
)}
</View>
</ScrollView>
<StatusBar style="auto" />
</View>
)
}
return (
<View style={styles.container}>
<View style={styles.center}>
<Text style={styles.title}>Audius OAuth Upload</Text>
<Text style={styles.subtitle}>
Sign in with Audius (write scope) — uploads and track creation happen
entirely on-device using the OAuth access token.
</Text>
{loading ? (
<ActivityIndicator size="large" style={styles.loader} />
) : (
<TouchableOpacity
style={styles.button}
onPress={handleSignIn}
disabled={loading}
>
<Text style={styles.buttonText}>Sign in with Audius</Text>
</TouchableOpacity>
)}
{error ? <Text style={styles.error}>{error}</Text> : null}
</View>
<StatusBar style="auto" />
</View>
)
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#fff', paddingTop: 60 },
center: { flex: 1, padding: 24, justifyContent: 'center' },
card: {
margin: 24,
padding: 24,
backgroundColor: '#f5f5f5',
borderRadius: 12
},
title: { fontSize: 28, fontWeight: 'bold', marginBottom: 8 },
subtitle: { fontSize: 16, color: '#666', marginBottom: 24 },
body: { fontSize: 13, color: '#333', marginTop: 8 },
code: { fontFamily: 'monospace', fontSize: 12, color: '#555', marginTop: 6 },
button: {
backgroundColor: '#CC0FE0',
paddingVertical: 14,
paddingHorizontal: 24,
borderRadius: 8,
alignSelf: 'center'
},
buttonDisabled: { opacity: 0.7 },
buttonText: { color: '#fff', fontSize: 16, fontWeight: '600' },
loader: { marginVertical: 16 },
error: { color: '#d32f2f', marginTop: 12 },
scroll: { flex: 1 },
scrollContent: { padding: 24, paddingBottom: 48 },
profileRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16
},
handle: { fontSize: 16, color: '#333' },
signOutBtn: { paddingVertical: 8, paddingHorizontal: 16 },
signOutBtnText: { color: '#0066cc', fontSize: 16 },
pickBtn: {
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 8,
padding: 14,
marginBottom: 12
},
pickBtnText: { fontSize: 14, color: '#333' },
input: {
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 8,
padding: 12,
marginBottom: 12,
fontSize: 16
},
textArea: { minHeight: 80, textAlignVertical: 'top' },
label: { fontSize: 14, fontWeight: '500', marginBottom: 8, color: '#333' },
result: { marginTop: 16, fontSize: 13, color: '#555', lineHeight: 20 },
debugTitle: { marginTop: 16, fontSize: 13, fontWeight: '600', color: '#333' },
debugSession: {
fontSize: 11,
color: '#666',
fontFamily: 'monospace',
marginBottom: 6
},
debugBox: {
marginTop: 8,
padding: 8,
borderRadius: 8,
backgroundColor: '#111',
maxHeight: 180
},
debugLine: { fontSize: 11, color: '#ddd', marginBottom: 4 }
})