forked from irgendwr/sinusbot-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcover.js
executable file
Β·321 lines (280 loc) Β· 11.7 KB
/
cover.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* Forum:
* GitHub: https://github.com/irgendwr/sinusbot-scripts
*/
registerPlugin({
name: 'Cover',
version: '1.0.0',
description: 'Automatically attempts to download a cover image.',
author: 'Jonas BΓΆgle (irgendwr)',
backends: ['ts3', 'discord'],
requiredModules: ['http'],
vars: [
{
name: 'provider',
title: 'Data Provider',
type: 'select',
options: [
'musicbrainz.org (free, no account required, BUT results are often wrong)',
'last.fm (free, better, BUT requires account)'
]
}, {
name: 'lastfm_apikey',
title: 'last.fm API Key (https://www.last.fm/api/account/create)',
type: 'string',
conditions: [{ field: 'provider', value: '1'}]
}
]
}, (_, config, meta) => {
const event = require('event')
const engine = require('engine')
const http = require('http')
const media = require('media')
const userAgent = `SinusBot${meta.name}Script/${meta.version} (https://github.com/irgendwr/sinusbot-scripts)`
engine.log(`Loaded ${meta.name} v${meta.version} by ${meta.author}.`)
var invalids = [];
event.on('track', (/** @type {Track} */ track) => {
if (track.thumbnail()) {
engine.log('skipping: track already has a thumbnail')
return;
}
if (invalids.includes(track.id())) {
engine.log('skipping: previously marked as invalid (reload scripts to clear)')
return;
}
if (track.type() !== '' && track.type() !== 'file') {
engine.log('skipping: invalid file type')
return;
}
switch (config.provider) {
case 1:
case "1":
queryLastFM(track)
break
default:
queryMB(track)
}
})
/**
* Queries last.fm for thumbnail
* @param {Track} track
*/
function queryLastFM(track) {
if (!config.lastfm_apikey) {
engine.log('Error: You need to set a last.fm API Key in the Script Settings.')
return;
}
let album = track.album()
let artist = track.artist()
let title = track.title()
if (album && artist) {
engine.log(`Searching last.fm for album thumbnail (${artist} - ${album})...`)
http.simpleRequest({
method: 'GET',
url: `http://ws.audioscrobbler.com/2.0/?method=album.getInfo&album=${encodeURIComponent(album)}&artist=${encodeURIComponent(artist)}&api_key=${encodeURIComponent(config.lastfm_apikey)}&format=json`,
timeout: 9000,
headers: {
'Accept': 'application/json',
'User-Agent': userAgent
}
}, (error, response) => {
if (error) return engine.log('Error: ' + error)
if (response.statusCode != 200) return engine.log('HTTP Error: ' + response.status)
// parse JSON response
let result = JSON.parse(response.data.toString())
if (result.album && result.album.image.length !== 0) {
// get highest quality image
const thumbnail = result.album.image[Math.min(result.album.image.length, 3)]['#text'] // 3 => "extralarge"
engine.log('success: '+thumbnail)
track.setThumbnailFromURL(thumbnail)
} else {
engine.log('no results found, marking as invalid')
invalid(track)
}
})
} else if (title && artist) {
engine.log(`Searching last.fm for track thumbnail (${artist} - ${title})...`)
http.simpleRequest({
method: 'GET',
url: `http://ws.audioscrobbler.com/2.0/?method=track.getInfo&track=${encodeURIComponent(title)}&artist=${encodeURIComponent(artist)}&api_key=${encodeURIComponent(config.lastfm_apikey)}&format=json`,
timeout: 9000,
headers: {
'Accept': 'application/json',
'User-Agent': userAgent
}
}, (error, response) => {
if (error) return engine.log('Error: ' + error)
if (response.statusCode != 200) return engine.log('HTTP Error: ' + response.status)
// parse JSON response
let result = JSON.parse(response.data.toString())
if (result.track && result.track.album && result.track.album.image.length !== 0) {
// get highest quality image
const thumbnail = result.track.album.image[Math.min(result.track.album.image.length, 3)]['#text'] // 3 => "extralarge"
engine.log('success: '+thumbnail)
track.setThumbnailFromURL(thumbnail)
} else {
engine.log('no results found, marking as invalid')
invalid(track)
}
})
} else {
engine.log('not enough info: you need to set artist and (title or album), marking as invalid')
invalid(track)
}
}
/**
* Queries musicbrainz.org for thumbnail
* @param {Track} track
*/
function queryMB(track) {
let album = track.album()
let artist = track.artist()
let title = track.title()
if (artist && album) {
engine.log(`Searching MB for release thumbnail (${artist} - ${album})...`)
http.simpleRequest({
method: 'GET',
url: `https://musicbrainz.org/ws/2/release/?query="${luceneEscape(album)}"%20AND%20artist:"${luceneEscape(artist)}`,
timeout: 9000,
headers: {
'Accept': 'application/json',
'User-Agent': userAgent
}
}, (error, response) => {
if (error) return engine.log('Error: ' + error)
if (response.statusCode != 200) return engine.log('HTTP Error: ' + response.status)
// parse JSON response
let {releases} = JSON.parse(response.data.toString())
if (releases.length !== 0) {
setThumbnailFromMBID(track, releases[0].id)
} else {
engine.log('no results found, marking as invalid')
invalid(track)
}
})
} else if (title && artist) {
engine.log(`Searching MB for recording thumbnail (${artist} - ${title})...`)
http.simpleRequest({
method: 'GET',
url: `https://musicbrainz.org/ws/2/recording/?query="${luceneEscape(title)}"%20AND%20artist:"${luceneEscape(artist)}"%20AND%20dur:[${track.duration()-10000}%20TO%20${track.duration()+10000}]`,
timeout: 9000,
headers: {
'Accept': 'application/json',
'User-Agent': userAgent
}
}, (error, response) => {
if (error) return engine.log('Error: ' + error)
if (response.statusCode != 200) return engine.log('HTTP Error: ' + response.status);
// parse JSON response
let {recordings} = JSON.parse(response.data.toString())
if (recordings.length !== 0 && recordings[0].releases.length !== 0) {
setThumbnailFromMBID(track, recordings[0].releases[0].id)
} else {
engine.log('no results found, marking as invalid')
invalid(track)
}
})
} else {
engine.log('not enough info: you need to set artist and (title or album), marking as invalid')
invalid(track)
}
}
/**
* Sets a tracks thumbnail.
* @param {Track} track
* @param {string} mbid
*/
function setThumbnailFromMBID(track, mbid) {
//engine.log('mbid: '+mbid)
http.simpleRequest({
method: 'GET',
url: `https://coverartarchive.org/release/${mbid}/`,
timeout: 6000,
headers: {
'Accept': 'application/json',
'User-Agent': userAgent
}
}, (err, response) => {
if (err) return engine.log('Error: ' + err)
if (response.statusCode != 200) return engine.log('HTTP Error (cover): ' + response.status)
let {images} = JSON.parse(response.data.toString())
if (images && images.length !== 0) {
engine.log('success: '+images[0].thumbnails.large)
track.setThumbnailFromURL(images[0].thumbnails.large)
} else {
engine.log('no image found, marking as invalid')
invalid(track)
}
});
}
/**
* Marks a track as invalid
* @param {Track} track
*/
function invalid(track) {
invalids.push(track.id())
}
/**
* Escape lucene string
* @see https://lucene.apache.org/core/4_3_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Escaping_Special_Characters
* @param {string} str
* @return {string}
*/
function luceneEscape(str) {
str = str.replace(/[+\-!(){}[\]^"~*?:\\/]|&&|\|\|/gm, "\\$&")
return encodeURIComponent(str)
}
event.on('load', () => {
const command = require('command')
if (!command) {
engine.log('command.js library not found! Please download command.js to your scripts folder and restart the SinusBot, otherwise this script will not work.');
engine.log('command.js can be found here: https://github.com/Multivit4min/Sinusbot-Command/blob/master/command.js');
return;
}
command.createCommand('setthumbnail')
.help('Set thumbnail of currently playing track')
.manual('Set thumbnail of currently playing track')
.checkPermission(hasEditFilePermission)
// @ts-ignore
.addArgument(command.createArgument('rest').setName('url').min(1))
.exec((client, args, reply) => {
let track = media.getCurrentTrack()
if (!track) {
reply('no track playing')
return;
}
track.setThumbnailFromURL(args.url)
})
command.createCommand('delthumbnail')
.help('Deletes thumbnail of currently playing track')
.manual('Deletes thumbnail of currently playing track')
.checkPermission(hasEditFilePermission)
.exec((client, args, reply) => {
let track = media.getCurrentTrack()
if (!track) {
reply('no track playing')
return;
}
track.removeThumbnail()
})
})
/**
* Checks if a client has the necessary permissons
* @param {Client} client
* @returns {boolean} true if client has permission
* @requires engine
*/
function hasEditFilePermission(client) {
// try to find a sinusbot user that matches
let matches = engine.getUsers().filter(user =>
// does the UID match?
user.tsUid() == client.uid() ||
// or does a group ID match?
client.getServerGroups().map(group => group.id()).includes(user.tsGroupId())
)
return matches.some(user => {
// edit file permissions?
return (user.privileges() & (1 << 4)) != 0
})
}
})