music-very-player/src/track.js

119 lines
2.9 KiB
JavaScript

const { from_string_to_seconds, from_seconds_to_string } = require('./helpers/duration')
/**
* @class
*/
class Track {
#url
#title
#length
#source
#last_played
#play_count
/**
* @constructor
* @param {Object} parameters={}
* @param {string} parameters.url The url of the track
* @param {string} parameters.title The title of the track
* @param {number|durationString} parameters.length The length of the track, either in seconds or following the [[HH:]mm:]ss format.
* @param {string} parameters.source The source where the track comes from. Note that as of now, only <code>'youtube'</code> is supported.
* @param {number|Date} [parameters.last_played=0] The timestamp when this track has been played for the last time
* @param {number} [parameters.play_count=0] The number of times this track has been played
*/
constructor({url, title, full_title, length, source, last_played = 0, play_count = 0} = {}) {
if (typeof length === 'string') {
this.#length = from_string_to_seconds(length)
} else {
this.#length = length
}
this.#url = url
this.#title = title || full_title
this.#source = source
this.#last_played = new Date(last_played)
this.#play_count = play_count
}
/**
* @returns {Track} A copy of the current track
*/
clone() {
return new Track(this.toJSON())
}
/**
* @returns {Object} A JSON object that describe the track<br />
* This object can be sent back to the {@link Track} constructor if needed
*/
toJSON() {
return {
url: this.#url,
title: this.#title,
length: this.#length,
source: this.#source,
last_played: this.#last_played.getTime(),
play_count: this.#play_count
}
}
/**
* @returns {string} A string representation of the track
*/
toString() {
return this.#title + ' (' + this.get_length_as_string() + ')'
}
/**
* @returns {string} The url of the track
*/
get_url() {
return this.#url
}
/**
* @returns {string} The title of the track
*/
get_title() {
return this.#title
}
/**
* @returns {string} The full title of the track
*/
get_full_title() {
return this.#title
}
/**
* @returns {number} The length of the track, in seconds
*/
get_length() {
return this.#length
}
/**
* @returns {string} The source where the track comes from, mostly <code>'youtube'</code>
*/
get_source() {
return this.#source
}
/**
* Update the play count and the last played date of the track. This method is meant to be used by the {@link Player} class<br />
* Note that this will be updated in the database file only after a !register
*/
update_play_count() {
this.#play_count += 1
this.#last_played = new Date()
}
/**
* @returns {durationString} A string representation of the track length
*/
get_length_as_string() {
return from_seconds_to_string(this.#length)
}
}
module.exports = { Track }