-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathtrack-download.ts
More file actions
382 lines (354 loc) · 10.8 KB
/
Copy pathtrack-download.ts
File metadata and controls
382 lines (354 loc) · 10.8 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
import type {
DownloadFileArgs,
DownloadTrackArgs
} from '@audius/common/services'
import { TrackDownload as TrackDownloadBase } from '@audius/common/services'
import { tracksSocialActions, downloadsActions } from '@audius/common/store'
import { Platform, Share } from 'react-native'
import type {
FetchBlobResponse,
ReactNativeBlobUtilConfig,
StatefulPromise
} from 'react-native-blob-util'
import ReactNativeBlobUtil from 'react-native-blob-util'
import { zip } from 'react-native-zip-archive'
import { dedupFilenames } from '~/utils'
import { make, track as trackEvent } from 'app/services/analytics'
import { dispatch } from 'app/store'
import { EventNames } from 'app/types/analytics'
const { downloadFinished } = tracksSocialActions
const { beginDownload, setDownloadError, setFetchCancel, setFileInfo } =
downloadsActions
let fetchTasks: StatefulPromise<FetchBlobResponse>[] = []
const audiusDownloadsDirectory = 'AudiusDownloads'
const cancelDownloadTask = () => {
fetchTasks.forEach((task) => {
task.cancel()
})
}
const removePathIfExists = async (path: string) => {
try {
const exists = await ReactNativeBlobUtil.fs.exists(path)
if (!exists) return
await ReactNativeBlobUtil.fs.unlink(path)
} catch (err) {
console.error(err)
}
}
/**
* Download a file via ReactNativeBlobUtil
*/
const downloadOne = async ({
fileUrl,
filename,
directory,
getFetchConfig,
onFetchComplete
}: {
fileUrl: string
filename: string
directory: string
getFetchConfig: (filePath: string) => ReactNativeBlobUtilConfig
onFetchComplete?: (path: string) => Promise<void>
}) => {
const filePath = directory + '/' + filename
try {
const fetchTask = ReactNativeBlobUtil.config(
getFetchConfig(filePath)
).fetch('GET', fileUrl)
fetchTasks = [fetchTask]
const fetchRes = await fetchTask
await onFetchComplete?.(fetchRes.path())
// Track download success event
trackEvent(
make({
eventName: EventNames.TRACK_DOWNLOAD_SUCCESSFUL_DOWNLOAD_SINGLE,
device: 'native'
})
)
} catch (err) {
console.error(err)
dispatch(
setDownloadError(
err instanceof Error ? err : new Error(`Download failed: ${err}`)
)
)
// On failure attempt to delete the file
removePathIfExists(filePath)
// Track download failure event
trackEvent(
make({
eventName: EventNames.TRACK_DOWNLOAD_FAILED_DOWNLOAD_SINGLE,
device: 'native'
})
)
}
}
/**
* Download multiple files via ReactNativeBlobUtil
*/
const downloadMany = async ({
files,
directory,
getFetchConfig,
onFetchComplete
}: {
files: { url: string; filename: string }[]
directory: string
getFetchConfig: (filePath: string) => ReactNativeBlobUtilConfig
onFetchComplete?: (path: string) => Promise<void>
}) => {
dedupFilenames(files)
let responses
const tempDir =
ReactNativeBlobUtil.fs.dirs.DownloadDir + '/' + `AudiusTemp_${Date.now()}`
try {
const responsePromises = files.map(({ url, filename }) =>
ReactNativeBlobUtil.config(
getFetchConfig(tempDir + '/' + filename)
).fetch('GET', url)
)
fetchTasks = responsePromises
responses = await Promise.all(responsePromises)
if (!responses.every((response) => response.info().status === 200)) {
throw new Error('Download unsuccessful')
}
await zip(tempDir, directory + '.zip')
await onFetchComplete?.(directory + '.zip')
// Track download success event
trackEvent(
make({
eventName: EventNames.TRACK_DOWNLOAD_SUCCESSFUL_DOWNLOAD_ALL,
device: 'native'
})
)
} catch (err) {
console.error(err)
dispatch(
setDownloadError(
err instanceof Error ? err : new Error(`Download failed: ${err}`)
)
)
// Track download failure event
trackEvent(
make({
eventName: EventNames.TRACK_DOWNLOAD_FAILED_DOWNLOAD_ALL,
device: 'native'
})
)
} finally {
// Remove source directory at the end of the process regardless of what happens
removePathIfExists(tempDir)
try {
responses.forEach((response) => response.flush())
} catch (err) {
console.error(err)
}
}
}
const download = async ({
files,
rootDirectoryName,
abortSignal
}: DownloadTrackArgs) => {
if (files.length === 0) {
dispatch(setDownloadError(new Error('No downloadable files found')))
return
}
dispatch(beginDownload())
dispatch(
setFileInfo({
trackName: rootDirectoryName ?? '',
fileName: files[0].filename
})
)
if (abortSignal) {
abortSignal.onabort = () => {
cancelDownloadTask()
}
}
// TODO: Remove this method of canceling after the lossless
// feature set launches. The abort signal should be the way to do
// this task cancellation going forward.
dispatch(setFetchCancel(cancelDownloadTask))
const audiusDirectory =
ReactNativeBlobUtil.fs.dirs.DocumentDir + '/' + audiusDownloadsDirectory
if (Platform.OS === 'ios') {
const onFetchComplete = async (path: string) => {
try {
dispatch(downloadFinished())
await Share.share({
url: path
})
} finally {
// The fetched file is temporary on iOS and we always want to be sure to
// remove it.
removePathIfExists(path)
}
}
if (files.length === 1) {
const { url, filename } = files[0]
downloadOne({
fileUrl: url,
filename,
directory: audiusDirectory,
getFetchConfig: (filePath) => ({
/* iOS single file download will stage a file into a temporary location, then use the
* share sheet to let the user decide where to put it. Afterwards we delete the temp file.
*/
fileCache: true,
path: filePath
}),
onFetchComplete
})
} else {
downloadMany({
files,
directory: audiusDirectory + '/' + rootDirectoryName,
getFetchConfig: (filePath) => ({
/* iOS multi-file download will download all files to a temp location and then create a ZIP and
* let the user decide where to put it with the Share sheet. The temp files are deleted after the ZIP is created.
*/
fileCache: true,
path: filePath
}),
onFetchComplete
})
}
} else {
if (files.length === 1) {
const { url, filename } = files[0]
downloadOne({
fileUrl: url,
filename,
/* Single file download on Android will use the Download Manager and go
* straight to the Downloads directory.
*/
directory: ReactNativeBlobUtil.fs.dirs.DownloadDir,
getFetchConfig: () => ({
addAndroidDownloads: {
description: filename,
mediaScannable: true,
notification: true,
storeInDownloads: true,
title: filename,
useDownloadManager: true
}
}),
onFetchComplete: async () => {
dispatch(downloadFinished())
}
})
} else {
if (!rootDirectoryName)
throw new Error(
'rootDirectory must be supplied when downloading multiple files'
)
downloadMany({
files,
/* Multi-file download on Android will stage the files in a temporary directory
* under the downloads folder and then zip them. We don't use Download Manager for
* the initial downloads to avoid showing notifications, then manually add a
* notification for the zip file.
*/
directory:
ReactNativeBlobUtil.fs.dirs.DownloadDir + '/' + rootDirectoryName,
getFetchConfig: (filePath) => ({
fileCache: true,
path: filePath
}),
onFetchComplete: async (path: string) => {
let mediaStoragePath
// On android 13+, we need to manually copy to media storage
try {
mediaStoragePath =
await ReactNativeBlobUtil.MediaCollection.copyToMediaStore(
{
// The name of the file that should show up in Downloads as a .zip
name: rootDirectoryName,
// Can be left empty as we're putting the file into downloads
parentFolder: '',
mimeType: 'application/zip'
},
'Download',
path
)
} catch (e) {
console.error(e)
// Continue on because on android <13+ the media storage copy will
// not work, but we can deliver the file to the old download system
// by calling android.addCompleteDownload.
}
// We still need to add the complete download notification here anyway
// even if on android 13+
ReactNativeBlobUtil.android.addCompleteDownload({
title: rootDirectoryName,
description: rootDirectoryName,
mime: 'application/zip',
path: mediaStoragePath ?? path,
showNotification: true
})
dispatch(downloadFinished())
}
})
}
}
}
/** Generic file download that doesn't use sagas. */
const downloadFile = async ({
file: { url, filename },
mimeType,
abortSignal
}: DownloadFileArgs) => {
if (Platform.OS === 'ios') {
const audiusDirectory =
ReactNativeBlobUtil.fs.dirs.DocumentDir + '/' + audiusDownloadsDirectory
const filePath = audiusDirectory + '/' + filename
try {
const fetchPromise = ReactNativeBlobUtil.config({
/* on iOS we stage the file into a temporary location, then use the
* share sheet to let the user decide where to put it.
* Afterwards we delete the temp file.
*/
fileCache: true,
path: filePath
}).fetch('GET', url)
abortSignal?.addEventListener('abort', () => {
fetchPromise.cancel()
})
await fetchPromise
await Share.share({
url: filePath
})
} finally {
// The fetched file is temporary on iOS and we always want to be sure to remove it.
removePathIfExists(filePath)
}
} else {
// On Android we use the Download Manager to download the file.
const fetchPromise = ReactNativeBlobUtil.config({
addAndroidDownloads: {
description: filename,
mediaScannable: true,
notification: true,
storeInDownloads: true,
title: filename,
mime: mimeType,
useDownloadManager: true
}
}).fetch('GET', url)
abortSignal?.addEventListener('abort', () => {
fetchPromise.cancel()
})
await fetchPromise
}
}
class TrackDownload extends TrackDownloadBase {
async downloadTracks(args: DownloadTrackArgs) {
await download(args)
}
async downloadFile(args: DownloadFileArgs) {
await downloadFile(args)
}
}
export const trackDownload = new TrackDownload()