-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
212 lines (185 loc) · 5.66 KB
/
index.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"use strict";
const fs = require("fs");
const Jimp = require("jimp");
const axios = require("axios");
const Ajv = require("ajv");
const INVALID_COVERS = ["", "https://music.youtube.com/"];
const schema = require("./config.schema");
const config = require("./config");
const validate = new Ajv().compile(schema);
const isConfigValid = validate(config);
if (!isConfigValid) {
console.error("config.json is not valid. The errors below need to be fixed.");
console.error(validate.errors);
process.exit(1);
}
const {
ytmdRemoteUrl,
outputPattern,
albumArtWidth,
albumArtHeight,
trackFilePath,
albumArtFilePath,
pollIntervalMs,
removeTrackAfterPausedForMs,
} = config;
const albumArtTmpFilePath = `${albumArtFilePath}.tmp`;
// Compute multiple outputs safely; limit to the min number of specified files between outputPattern and trackFilePath
const getFilePatterns = () => {
const effectiveTrackFilePaths = Array.isArray(trackFilePath)
? trackFilePath
: [trackFilePath];
const effectiveOutputPatterns = Array.isArray(outputPattern)
? outputPattern
: [outputPattern];
const filePatterns = [];
for (
let i = 0;
i <
Math.min(effectiveTrackFilePaths.length, effectiveOutputPatterns.length);
i++
) {
filePatterns.push({
path: effectiveTrackFilePaths[i],
pattern: effectiveOutputPatterns[i],
});
}
return filePatterns;
};
const filePatterns = getFilePatterns();
console.log(
`ytmd-obs-output started. Polling interval is ${pollIntervalMs}ms.`
);
let currentTrack = {};
let currentTimeoutAfterPauseMs = 0;
const hasCurrentTrack = () => currentTrack.hasOwnProperty("title");
const hasTrackChanged = ({ author, title, album, cover }) =>
currentTrack.author !== author ||
currentTrack.title !== title ||
currentTrack.album !== album ||
currentTrack.cover !== cover;
const isTrackNonEmpty = ({ author, title, album }) =>
author !== "" || title !== "" || album !== "";
const removeFile = (filePath) => {
if (fs.existsSync(filePath)) {
fs.unlink(filePath, (error) => {
if (error) {
console.error(
`Error: Could not delete ${filePath}. Check permissions and disk space.`,
error
);
}
});
}
};
const writeTrackFile = ({ author, title, album }) => {
filePatterns.forEach(({ path, pattern }) => {
const outputText = pattern
.replace(/%author%/gi, author)
.replace(/%title%/gi, title)
.replace(/%album%/gi, album);
fs.writeFile(path, outputText, (error) => {
if (error) {
console.error(
`Error: Could not write ${path}. Check permissions and disk space.`,
error
);
} else {
console.log(`- Track written to ${path}.`);
}
});
});
};
const resizeAlbumCover = () => {
Jimp.read(albumArtTmpFilePath, (error, image) => {
if (error) {
console.error(
`- Error: Could not read ${albumArtTmpFilePath} when resizing. Removing cover file.`,
error
);
removeFile(albumArtTmpFilePath);
removeFile(albumArtFilePath);
} else if (image) {
image.contain(albumArtWidth, albumArtHeight).write(albumArtFilePath);
console.log(`- Cover resized to ${albumArtFilePath}.`);
}
});
};
const downloadAlbumCover = async ({ cover }) => {
try {
const response = await axios.get(cover, { responseType: "stream" });
// Non-null album art: download and convert to png
response.data
.pipe(fs.createWriteStream(albumArtTmpFilePath))
.on("error", (error) => {
if (error) {
console.error(
`Error: Could not write ${albumArtTmpFilePath} when downloading.`,
error
);
}
})
.on("finish", () => {
console.log(`- Cover downloaded to ${albumArtTmpFilePath}.`);
resizeAlbumCover();
});
} catch (error) {
console.error(`Error: Could not download ${cover}.`, error);
}
};
const removeTrackInfo = () => {
currentTrack = {};
console.log("- Removing track files...");
filePatterns.forEach(({ path }) => removeFile(path));
removeFile(albumArtTmpFilePath);
removeFile(albumArtFilePath);
};
const outputTrackInfo = ({ author, title, album, cover }) => {
console.log("New track detected. Changing track information.");
currentTrack = { author, title, album, cover };
console.log(currentTrack);
if (isTrackNonEmpty(currentTrack)) {
writeTrackFile(currentTrack);
} else {
removeTrackInfo();
}
if (!INVALID_COVERS.includes(currentTrack.cover)) {
console.log("- Downloading cover...");
downloadAlbumCover(currentTrack);
} else {
console.log("- Invalid cover. Removing cover file.");
removeFile(albumArtTmpFilePath);
removeFile(albumArtFilePath);
}
};
setInterval(async () => {
try {
const {
data: { player, track },
} = await axios.get(ytmdRemoteUrl);
if (removeTrackAfterPausedForMs) {
if (!player.hasSong || player.isPaused) {
if (hasCurrentTrack()) {
currentTimeoutAfterPauseMs += pollIntervalMs;
if (currentTimeoutAfterPauseMs >= removeTrackAfterPausedForMs) {
console.log(
`Track was paused for at least ${removeTrackAfterPausedForMs}ms. Removing track information.`
);
removeTrackInfo();
}
}
} else {
currentTimeoutAfterPauseMs = 0;
if (hasTrackChanged(track)) {
outputTrackInfo(track);
}
}
} else if (hasTrackChanged(track)) {
outputTrackInfo(track);
}
} catch (error) {
console.error(
`Error ${error.code}: ${error.message}. Check that YTMDesktop Remote API is running and your firewall is configured properly.`
);
}
}, pollIntervalMs);