Skip to content

Instantly share code, notes, and snippets.

@lethak
Last active March 12, 2020 00:37
Show Gist options
  • Save lethak/e44300e5b85456ea08433c3790009a8b to your computer and use it in GitHub Desktop.
Save lethak/e44300e5b85456ea08433c3790009a8b to your computer and use it in GitHub Desktop.
DI.FM hook "onWebplayerTrackChange"
//----
// Educational gist based from my understanding working on https://github.com/lethak/LTKDIFMU-userscript
//----
// Defining our event listener
function onWebplayerTrackChange (e) {
// 'e' is a BackboneJS Model: @see https://cdnjs.com/libraries/backbone.js/tutorials/what-is-a-model
// creating a payload variable with track data
const payload = e ? {
id: e.get('id') ? e.get('id') : null,
src: e.get('src') ? e.get('src') : null,
display_artist: e.get('display_artist') ? e.get('display_artist') : null,
display_title: e.get('display_title') ? e.get('display_title') : null,
assets: e.get('content') ? (e.get('content').assets ? e.get('content').assets : null) : null
} : null;
/*
if 'payload' is null, no valid track was loaded.
'payload.id' and 'payload.src' can be used there for whatever purpose.
Since this event technically can be triggered multiple times with the same track,
the id can be used to dedupe whatever you are doing.
'src' is the track download url but without the full protocol (only //),
it is advised to use https whenever possible. This URL is only valid for 24h hours and query parameters should not be modified because of the oauth signature.
This also means this url is broadcasting your DI identity to the content server (DI user id and IP most likely)
if other arrtibutes are required, dig into 'e.attributes' and access them with 'e.get('something').somethingElse'.
Remember that any value could be non existant or null in e.attributes, always check what you are using is there or it will trigger exceptions.
'assets' will contains details about multiple url available, typically one asset for each available quality.
If you need the best quality, you can dig into 'di.app.options.stream_set_configs' to find out who is what.
*/
// For demo purpose:
console.warn('onWebplayerTrackChange just triggered with payload = ', payload)
}
// Registering our new event listener to one of DI's event bus. Obviously 'di.app.vent' must to be accessible, typically after DOM is ready.
di.app.vent.on('webplayer:track:change', onWebplayerTrackChange)
// If you want to print the list of available events:
console.log('Available events: ', Object.keys(di.app.vent._events))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment