62 lines
1.8 KiB
JavaScript
62 lines
1.8 KiB
JavaScript
const Router = require('@koa/router')
|
|
const r = new Router()
|
|
module.exports = r
|
|
|
|
const koaBody = require('koa-body')
|
|
const {
|
|
download: ytdl,
|
|
getTitle
|
|
} = require('@libs/youtube.js')
|
|
const qs = require('querystring')
|
|
const fs = require('fs')
|
|
const path = require('path')
|
|
const config = require('@config/index.js')
|
|
const store = require('@libs/memstore.js')
|
|
|
|
r.post('/download', koaBody(), async c => {
|
|
console.log(c.request)
|
|
const { url } = c.request.body
|
|
if (typeof url !== 'string' || url.trim().length === 0) c.throw(400, 'url is empty')
|
|
let id = ''
|
|
if (/:\/\/youtu\.be/i.test(url)) {
|
|
const arr = url.split('/')
|
|
id = arr[arr.length - 1]
|
|
} else {
|
|
const arr = url.split('?')
|
|
if (arr.length !== 2) c.throw(400, 'url format error')
|
|
const q = qs.parse(arr[1])
|
|
if (!('v' in q) || typeof q.v !== 'string' || q.v.length === 0) c.throw(400, 'url format error')
|
|
id = q.v
|
|
}
|
|
|
|
const title = await getTitle(url)
|
|
|
|
const result = await ytdl(url)
|
|
if (!result) c.throw(500, 'download fail')
|
|
|
|
store.set(`${id}.mp3`, { title })
|
|
|
|
c.body = {
|
|
url: `${c.protocol}://${c.host.replace(/\/$/, '')}/api/youtube/download?file=${id}.mp3`
|
|
}
|
|
c.status = 200
|
|
})
|
|
|
|
r.get('/download', async c => {
|
|
const { file } = c.query
|
|
if (typeof file !== 'string' || file.trim().length === 0) c.throw(400, 'file is empty')
|
|
|
|
const fp = path.resolve(config.download_location, file)
|
|
if (!fs.existsSync(fp)) c.throw(404, 'file not found')
|
|
|
|
const fileInfo = store.get(file)
|
|
let fn = file
|
|
if (fileInfo !== null && 'title' in fileInfo) fn = `${fileInfo.title}.mp3`
|
|
|
|
const rs = fs.createReadStream(fp)
|
|
c.set('Content-disposition', `attachment; filename="${encodeURIComponent(fn)}"; filename*="utf8''${encodeURIComponent(fn)}";`)
|
|
c.set('Content-Type', 'audio/mpeg')
|
|
c.body = rs
|
|
c.status = 200
|
|
})
|