2018-08-14 18:26:02 +02:00
|
|
|
const fs = require('fs-extra');
|
|
|
|
const path = require('path');
|
|
|
|
const _ = require('lodash');
|
|
|
|
const sanitize = require('sanitize-filename');
|
|
|
|
const debug = require('debug')('publikator:organise');
|
2018-08-17 15:48:56 +02:00
|
|
|
const tags = require('./tags');
|
2018-08-14 18:26:02 +02:00
|
|
|
|
2018-08-17 18:53:14 +02:00
|
|
|
const getArtists = file => file.common.artist || file.common.artists.join(', ');
|
|
|
|
const getFolderName = file => `${getArtists(file)} - ${file.common.album}`;
|
2018-08-14 18:26:02 +02:00
|
|
|
const getFileName = file =>
|
2018-08-17 18:53:14 +02:00
|
|
|
`${file.common.track.no} - ${file.common.title}${path.extname(file.path)}`;
|
2018-08-14 18:26:02 +02:00
|
|
|
|
|
|
|
module.exports = {
|
2018-08-17 15:48:56 +02:00
|
|
|
/**
|
|
|
|
* Organises tracks into a new folder structure in `root`, as follows:
|
|
|
|
*
|
|
|
|
* {artist} - {album}/
|
|
|
|
* {track} - {title}.{ext}
|
|
|
|
* {track} - {title}.{ext}
|
|
|
|
* ...
|
|
|
|
*
|
|
|
|
* Returns `taggedFiles` with the paths changed to the new paths.
|
|
|
|
*/
|
|
|
|
byAlbum: async (root, taggedFiles) => {
|
|
|
|
const files = taggedFiles.filter(file =>
|
2018-08-17 18:53:14 +02:00
|
|
|
tags.hasTags(file, [
|
|
|
|
'common.artists',
|
|
|
|
'common.album',
|
|
|
|
'common.track',
|
|
|
|
'common.title',
|
|
|
|
])
|
2018-08-17 15:48:56 +02:00
|
|
|
);
|
2018-08-14 18:26:02 +02:00
|
|
|
|
|
|
|
debug(`grouping tracks by album`);
|
|
|
|
const folders = _.uniq(files.map(file => getFolderName(file)));
|
|
|
|
debug(`found ${folders.length} album(s)`);
|
|
|
|
debug(folders);
|
|
|
|
|
|
|
|
debug(`creating album directories`);
|
|
|
|
await Promise.all(
|
|
|
|
folders.map(album => fs.ensureDir(path.resolve(root, sanitize(album))))
|
|
|
|
);
|
|
|
|
|
|
|
|
debug(`copying tracks`);
|
|
|
|
return Promise.all(
|
2018-08-17 15:48:56 +02:00
|
|
|
files.map(async file => {
|
2018-08-14 18:26:02 +02:00
|
|
|
const newPath = path.resolve(
|
|
|
|
root,
|
|
|
|
getFolderName(file),
|
|
|
|
getFileName(file)
|
|
|
|
);
|
2018-08-17 15:48:56 +02:00
|
|
|
await fs.copyFile(file.path, newPath);
|
2018-08-14 18:26:02 +02:00
|
|
|
return _.assign({}, file, { path: newPath });
|
|
|
|
})
|
|
|
|
);
|
|
|
|
},
|
|
|
|
};
|