Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async refresh ({ state, commit, dispatch, rootState }, selectedFolders) {
let folders = selectedFolders && selectedFolders.length ? selectedFolders : state.exportFolders
let songs = []
for (let folder of folders) {
try {
const dirs = fs.readdirSync(folder)
for (let item of dirs) {
const pathname = path.join(folder, item)
const stat = fs.statSync(pathname)
if (stat.isFile()) {
if (item.endsWith('.mp3')) {
const metadata = await mm.parseFile(pathname, {
duration: true
})
let songname = item.substring(0, item.lastIndexOf('.')).trim()
let artist = [], name = songname, matched = false
if (songname.split('-')[0] && songname.split('-')[1]) {
artist = songname.split('-')[0].split(',').map(item => { return {name: item} })
name = songname.split('-')[1].trim()
matched = false
}
let extraItem = {
artist, name, matched
}
// console.log(name, artist, metadata)
const songItem = {
function _parseCommon(filename) {
return musicMetadata.parseFile(filename, {native: false})
.then(function(metadata) {
// console.log('metadata._parseCommon', JSON.stringify(metadata));
// console.log('%s - %s\n\tat %s', metadata.common.album, metadata.common.title, filename);
return mm2custom(filename, metadata);
});
}
fs.readdir(this.dir, (err, dir) => {
// loop through results
for (let filePath of dir) {
// ensure that we're only working with files
if (fs.statSync(this.dir + filePath).isFile()) {
let buffer = readChunk.sync(this.dir + filePath, 0, fileType.minimumBytes)
let fileTypeInfo = fileType(buffer)
// only interestedin MP3 files at the moment, ignore all others
if (fileTypeInfo != null) {
if (fileTypeInfo.ext === 'mp3' || fileTypeInfo.ext === 'wav' || fileTypeInfo.ext === 'flac') {
// read metadata
mm.parseFile(this.dir + filePath, {native: true})
.then(metadata => {
console.log(metadata)
// Get data for file object
let artist = metadata.common.artist
let title = metadata.common.title
let album = metadata.common.album
let bitrate = metadata.format.bitrate
let codec = metadata.format.codec
let trackNo = metadata.common.track.no
// write the relevent data to the files array
this.files.push({
fileName: filePath,
artist: (artist !== null) ? artist.substring(0, 50).replace('/', '_') : '',
title: (title !== null) ? title.substring(0, 50).replace('/', '_') : '',
album: (album !== null) ? album : '',
trackNo: (trackNo !== null) ? trackNo : 0,
const metadata = { title: file.name }
ipc.send('wt-audio-metadata', infoHash, index, metadata)
const options = {
native: false,
skipCovers: true,
fileSize: file.length,
observer: event => {
ipc.send('wt-audio-metadata', infoHash, index, event.metadata)
}
}
const onMetaData = file.done
// If completed; use direct file access
? mm.parseFile(path.join(torrent.path, file.path), options)
// otherwise stream
: mm.parseStream(file.createReadStream(), file.name, options)
onMetaData
.then(() => {
console.log(`metadata for file='${file.name}' completed.`)
}).catch(function (err) {
return console.log('error getting audio metadata for ' + infoHash + ':' + index, err)
})
}
export const getMetadata = async (trackPath: string): Promise<track> => {
const defaultMetadata = getDefaultMetadata();
const basicMetadata: Track = {
...defaultMetadata,
path: trackPath
};
try {
const stats = await stat(trackPath);
const data = await mmd.parseFile(trackPath, {
native: true, skipCovers: true, fileSize: stats.size, duration: true
});
// Let's try to define something with what we got so far...
const parsedData = parseMusicMetadata(data, trackPath);
const metadata: Track = {
...defaultMetadata,
...parsedData,
path: trackPath
};
metadata.loweredMetas = getLoweredMeta(metadata);
// Let's try another wat to retrieve a track duration
if (!metadata.duration) {
async process (item, pathId) {
const pathInfo = path.parse(item.file)
const tags = await musicMeta.parseFile(item.file, {
duration: true,
skipCovers: true,
})
if (!tags.format.duration) {
throw new Error(' => could not determine duration')
}
log.info(' => duration: %s:%s',
Math.floor(tags.format.duration / 60),
Math.round(tags.format.duration % 60, 10).toString().padStart(2, '0')
)
// run parser
const parsed = this.parser({
dir: pathInfo.dir,
function metadata (path, cb) {
var audioStream = fs.createReadStream(path)
var returned = false // TODO clean up racy code
audioStream.on('error', (err) => {
if (!returned) {
returned = true
return cb(err)
}
})
mm.parseStream(audioStream, {native: true}, function (err, metadata) {
// important note, the stream is not closed by default. To prevent leaks, you must close it yourself
audioStream.destroy()
if (!returned) {
returned = true
return cb(err, err ? null : metadata)
}
})
}
this.fileExtension = supportedImageTypes[this.mimeType];
this.noThumbnail = '1'; // this may be overriden below
await this.handleImage(tmpAttachmentFile);
} else if (supportedAudioTypes[this.mimeType]) {
// Set media properties for 'audio' type
this.mediaType = 'audio';
this.fileExtension = supportedAudioTypes[this.mimeType];
this.noThumbnail = '1';
if (this.fileExtension === 'm4a') {
this.mimeType = 'audio/mp4'; // mime-type compatible with music-metadata
}
// Analyze metadata to get Artist & Title
const readStream = createReadStream(tmpAttachmentFile);
const { common: metadata } = await mmParseStream(
readStream,
this.mimeType,
{ mergeTagHeaders: true }
);
debug(`Metadata of ${tmpAttachmentFileName}`, metadata);
this.title = metadata.title;
if (_.isArray(metadata.artist)) {
[this.artist] = metadata.artist;
} else {
this.artist = metadata.artist;
}
} else {
// Set media properties for 'general' type
let type = "FILE";
if (IMAGE_TYPES.indexOf(file.type) !== -1) {
type = "IMAGE";
} else if (AUDIO_TYPES.indexOf(file.type) !== -1) {
type = "AUDIO";
} else if (VIDEO_TYPES.indexOf(file.type) !== -1) {
type = "VIDEO";
} else if (PDF_TYPES.indexOf(file.type) !== -1) {
type = "PDF";
}
const t = this;
// this is ridiculous
if (type === "AUDIO") {
musicmetadata(file, function(err, metadata) {
const { title, artist, album, picture, date } = metadata.common;
let pictureBlob;
if (picture && picture.length > 0 && picture[0]) {
pictureBlob = URL.createObjectURL(
new Blob([picture[0].data], {
type: "image/" + picture[0].format
})
);
}
const contentStateWithEntity = editorState
.getCurrentContent()
.createEntity(type, "IMMUTABLE", {
file: file,
name: file.name,
type: file.type,
size: file.size,
// Fall back on Blob
return this.parseBlob(await response.blob(), options);
}
} else {
throw new Error(`HTTP error status=${response.status}: ${response.statusText}`);
}
}
/**
* Parse audio from ITokenizer source
* @param {strtok3.ITokenizer} Audio source implementing the tokenizer interface
* @param {string} mimeType Content specification MIME-type, e.g.: 'audio/mpeg'
* @param {IOptions} options Parsing options
* @returns {Promise}
*/
export const parseFromTokenizer = mm.parseFromTokenizer;
/**
* Convert Web API File to Node Buffer
* @param {Blob} blob Web API Blob
* @returns {Promise}
*/
function convertBlobToBuffer(blob: Blob): Promise {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onloadend = event => {
let data = (event.target as any).result;
if (data instanceof ArrayBuffer) {
data = toBuffer(new Uint8Array((event.target as any).result));
}
resolve(data);