-
Notifications
You must be signed in to change notification settings - Fork 72
/
index.ts
302 lines (260 loc) · 6.22 KB
/
index.ts
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
import path from 'path'
import _ from 'lodash'
import fs from 'fs-extra'
import symbols from 'log-symbols'
import debugFactory from 'debug'
import pretry from 'promise.retry'
import sanitize from 'filenamify'
import dl from 'dl-vampire'
import getPlayurl from './api/playurl'
import BaseAdapter, {Song, TransformSong} from './adapter/base'
const debug = debugFactory('yun:index')
/**
* page type
*/
export const types = [
{
type: 'playlist',
typeText: '列表',
},
{
type: 'album',
typeText: '专辑',
},
{
type: 'djradio',
typeText: '电台',
},
]
/**
* 下载一首歌曲
*/
export async function downloadSong(options: downloadSong.Options) {
const progress: boolean = options.progress
if (progress) {
return downloadSongWithProgress(options)
} else {
return downloadSongPlain(options)
}
}
export namespace downloadSong {
export interface Options {
progress?: boolean
url: string
file: string
song: TransformSong
totalLength: number
retryTimeout?: number
retryTimes?: number
skipExists?: boolean
}
}
async function downloadSongWithProgress(options: downloadSong.Options) {
const ProgressBar = require('@magicdawn/ascii-progress')
const {
url,
file,
song,
totalLength,
retryTimeout,
retryTimes,
skipExists,
} = options
let bar
const initBar = () => {
bar = new ProgressBar({
schema: `:symbol ${song.index}/${totalLength} [:bar] :postText`,
total: 100,
current: 0,
width: 10,
filled: '=',
blank: ' ',
})
}
// 成功
const success = () => {
bar.update(1, {symbol: symbols.success, postText: `下载成功 ${file}`})
}
// 失败
const fail = () => {
bar.update(0, {symbol: symbols.error, postText: `下载失败 ${file}`})
bar.terminate()
}
// 下载中
const downloading = percent =>
bar.update(percent, {symbol: symbols.info, postText: ` 下载中 ${file}`})
// 重试
const retry = i => {
bar.tick(0, {symbol: symbols.warning, postText: ` ${i + 1}次失败 ${file}`})
}
// init state
initBar()
downloading(0)
try {
await dl({
url,
file,
skipExists,
onprogress(p) {
const {percent} = p
if (percent === 1) {
success()
} else {
downloading(percent)
}
},
retry: {
timeout: retryTimeout,
times: retryTimes,
onerror: function(e, i) {
retry(i)
},
},
})
} catch (e) {
fail()
return
}
success()
}
export async function downloadSongPlain(options: downloadSong.Options) {
const {
url,
file,
song,
totalLength,
retryTimeout,
retryTimes,
skipExists,
} = options
try {
await dl({
url,
file,
skipExists,
retry: {
timeout: retryTimeout,
times: retryTimes,
onerror: function(e, i) {
console.log(
`${symbols.warning} ${song.index}/${totalLength} ${i +
1}次失败 ${file}`
)
},
},
})
} catch (e) {
console.log(
`${symbols.error} ${song.index}/${totalLength} 下载失败 ${file}`
)
console.error(e.stack || e)
return
}
console.log(
`${symbols.success} ${song.index}/${totalLength} 下载完成 ${file}`
)
}
/**
* check page type
*/
export function getType(url: string) {
const item = _.find(types, item => url.indexOf(item.type) > -1)
if (item) return item
const msg = 'unsupported type'
throw new Error(msg)
}
/**
* get a adapter via `url`
*
* an adapter should have {
* getTitle($) => string
* getDetail($, url, quality) => [song, ...]
* }
*/
export function getAdapter(url: string): BaseAdapter {
const type = getType(url)
const typeKey = type.type
const Adapter = require('./adapter/' + typeKey).default
return new Adapter()
}
/**
* 获取title
*/
export function getTitle($: CheerioStatic, url: string) {
const adapter = getAdapter(url)
return adapter.getTitle($)
}
/**
* 获取歌曲
*/
export async function getSongs($: CheerioStatic, url: string, quality: number) {
const adapter = getAdapter(url)
// 基本信息
let songs = await adapter.getDetail($, url, quality)
// 获取下载链接
const ids = songs.map(s => s.id)
let json = await getPlayurl(ids, quality) // 0-29有链接, max 30? 没有链接都是下线的
json = json.filter(s => s.url) // remove 版权保护没有链接的
// 移除版权限制在json中没有数据的歌曲
const removed = []
for (let song of songs) {
const id = song.id
const ajaxData = _.find(json, ['id', id])
if (!ajaxData) {
// 版权受限
removed.push(song)
} else {
// we are ok
song.ajaxData = ajaxData
}
}
const removedIds = _.map(removed, 'id')
songs = _.reject(songs, s => _.includes(removedIds, s.id))
// 根据详细信息获取歌曲
return adapter.getSongs(songs)
}
/**
* 获取歌曲文件表示
*/
export function getFileName(options: getFileName.Options) {
let {format, url, song, name} = options
const typesItem = getType(url)
// 从 type 中取值, 先替换 `长的`
;['typeText', 'type'].forEach(t => {
const val = sanitize(String(typesItem[t]))
format = format.replace(new RegExp(':' + t, 'ig'), val)
})
// 从 `song` 中取值
;['songName', 'singer', 'rawIndex', 'index', 'ext'].forEach(t => {
// t -> token
// rawIndex 为 number, sanitize(number) error
const val = sanitize(String(song[t]))
format = format.replace(new RegExp(':' + t, 'ig'), val)
})
// name
format = format.replace(new RegExp(':name', 'ig'), sanitize(name))
// djradio only
if (typesItem.type === 'djradio') {
const programDate = _.get(song, 'raw.programUi.date')
if (programDate) {
format = format.replace(new RegExp(':programDate'), sanitize(programDate))
}
const programOrder = _.get(song, 'raw.programUi.programOrder')
if (programOrder) {
format = format.replace(
new RegExp(':programOrder'),
sanitize(programOrder)
)
}
}
return format
}
export namespace getFileName {
export interface Options {
format: string
song: TransformSong
url: string
// 专辑 or playlist 名称
name: string
}
}