This repository has been archived by the owner on Jun 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify-dbus.js
61 lines (45 loc) · 1.6 KB
/
spotify-dbus.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
const DBus = require('dbus-next')
const getMetadataArtist = (metadata) => metadata.value['xesam:artist'].value[0]
const getMetadataTitle = (metadata) => metadata.value['xesam:title'].value
const getMetadataTrackID = (metadata) => metadata.value['mpris:trackid'].value
const getProperties = async () => {
const sessionBus = DBus.sessionBus()
const proxyObject = await sessionBus.getProxyObject(
'org.mpris.MediaPlayer2.spotify',
'/org/mpris/MediaPlayer2'
)
return proxyObject.getInterface('org.freedesktop.DBus.Properties')
}
const getMetadata = async () => {
const properties = await getProperties()
return properties.Get(
'org.mpris.MediaPlayer2.Player',
'Metadata'
)
}
const getTrack = async () => {
try {
const metadata = await getMetadata()
const trackID = getMetadataTrackID(metadata)
const artist = getMetadataArtist(metadata)
const title = getMetadataTitle(metadata)
return { trackID, artist, title }
} catch (exception) {
throw new Error('Something went wrong. Is Spotify Running?')
}
}
let metadataChangeTimer
const metadataChangeListener = async (callback) => {
const properties = await getProperties()
properties.on('PropertiesChanged', (_, changed) => {
clearTimeout(metadataChangeTimer)
metadataChangeTimer = setTimeout(() => {
let metadata = changed['Metadata']
let trackID = getMetadataTrackID(metadata)
let artist = getMetadataArtist(metadata)
let title = getMetadataTitle(metadata)
callback(null, { trackID, artist, title })
}, 1000)
})
}
module.exports = { getTrack, metadataChangeListener }