btrtracks/common/async.js

76 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-10-06 12:30:02 +00:00
import {exec} from 'child_process'
2018-10-07 16:03:04 +00:00
import path from 'path'
2018-10-06 12:30:02 +00:00
import fs from 'fs-extra'
function filewalker (dir, done) {
let results = []
fs.readdir(dir, function (err, list) {
if (err) return done(err)
let pending = list.length
if (!pending) return done(null, results)
list.forEach(function (file) {
file = path.resolve(dir, file)
fs.stat(file, function (err, stat) {
if (err) return done(err)
// If directory, execute a recursive call
if (stat && stat.isDirectory()) {
filewalker(file, function (err, res) {
if (err) return done(err)
results = results.concat(res)
if (!--pending) done(null, results)
})
} else {
results.push(file)
if (!--pending) done(null, results)
}
})
})
})
}
2018-10-07 16:03:04 +00:00
async function insertDB (db, track) {
let ensure = await db.get('SELECT * FROM Track WHERE title=? AND artist=?', track.title, track.artist)
if (ensure) {
return null
}
await db.run('INSERT INTO Track VALUES (NULL,?,?,?,?,?,?,?,?)',
[track.title, track.artist, track.file, track.album || null, track.genre || null, track.track || null,
track.year || null, Math.floor(track.duration)])
return track
}
2018-10-06 12:30:02 +00:00
function getFiles (dir) {
return new Promise((resolve, reject) => {
filewalker(dir, (err, files) => {
if (err) return reject(err)
resolve(files)
})
})
}
function promiseExec (cmd, opts) {
return new Promise((resolve, reject) => {
exec(cmd, opts, function (err, stdout, stderr) {
if (err) return reject(err)
resolve({stdout, stderr})
})
})
}
function askAsync (rl, q) {
return new Promise((resolve, reject) => {
rl.question(q, resolve)
})
}
2018-10-07 16:03:04 +00:00
export default {getFiles, promiseExec, askAsync, insertDB}