-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJob.class.js
115 lines (102 loc) · 2.97 KB
/
Job.class.js
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
const fs = require('fs'),
axios = require('axios').default;
function Job(datas, force = false) {
this.datas = datas;
this.force = force;
this.inited = false;
this.queue = [];
this.lastQueueTime = 0;
this.debounce = 1000;
this.regexFormated = new RegExp("^([0-9]{4}) - (.*)$");
this.init = (callback) => {
fs.stat(this.datas.path, (err, pathStat) => {
if (err || !pathStat.isDirectory()) {
throw new exception(`'${this.datas.path}' is not a directory`);
}
else {
this.inited = true;
callback && callback(this);
}
});
};
this.start = () => {
if (!this.inited) {
throw new exception('Job not inited');
}
fs.readdir(`${this.datas.path}`, (err, artists) => {
if(!err && artists) {
artists.forEach(artist => {
fs.stat(`${this.datas.path}/${artist}`, (err, statsArtist) => {
if (statsArtist.isDirectory()) {
fs.readdir(`${this.datas.path}/${artist}`, (err, albums) => {
if(!err && albums) {
albums.forEach(album => {
fs.stat(`${this.datas.path}/${artist}/${album}`, (err, statsAlbum) => {
this.queue.push({
path: `${this.datas.path}/${artist}/${album}`,
artist,
album: statsAlbum.isDirectory()
? album
: album.split('.').slice(0, -1).join('.'),
isDirectory: statsAlbum.isDirectory()
});
this.doQueue();
});
});
}
});
}
});
});
}
});
}
this.doQueue = () => {
if (!this.doingQueue && this.queue.length > 0) {
this.doingQueue = true;
const now = new Date().getTime();
if (now < this.lastQueueTime + this.debounce) {
setTimeout(() => {
this.doingQueue = false;
this.doQueue();
}, this.debounce);
} else {
this.lastQueueTime = now;
const item = this.queue.pop();
// console.log(item);
if (this.regexFormated.exec(item.album) === null) {
console.log(`GET : ${item.artist} - ${item.album}`);
axios.get(`https://musicbrainz.org/ws/2/release?limit=1&fmt=json&query=artistname:${item.artist} release:${item.album}`)
.then((response) => {
if (response.data.releases.length) {
const year = new Date(response.data.releases[0].date).getFullYear();
let newPath = item.path.split(/[\\/]+/);
newPath[newPath.length-1] = isNaN(year)
? `${response.data.releases[0].title}`
: `${year} - ${response.data.releases[0].title}`;
if (!item.isDirectory) {
newPath[newPath.length-1] += '.' + item.path.split('.').pop();
}
fs.rename(item.path, newPath.join('/'), () => {
this.doingQueue = false;
this.doQueue();
});
} else {
this.doingQueue = false;
this.doQueue();
}
})
.catch((error) => {
this.doingQueue = false;
this.doQueue();
});
//
} else {
this.doingQueue = false;
this.doQueue();
}
}
}
}
}
module.exports = Job;