Add: User listening sessions and user listening stats #167

This commit is contained in:
advplyr 2021-11-12 19:43:16 -06:00
parent 663d02e9fe
commit 91e44bc2f9
16 changed files with 461 additions and 72 deletions

View file

@ -1,16 +1,22 @@
const Logger = require('../Logger')
const date = require('date-and-time')
class UserListeningSession {
constructor(session) {
this.id = null
this.sessionType = 'listeningSession'
this.userId = null
this.audiobookId = null
this.audiobookTitle = null
this.audiobookAuthor = null
this.audiobookGenres = []
this.date = null
this.dayOfWeek = null
this.timeListening = null
this.lastUpdate = null
this.startedAt = null
this.finishedAt = null
if (session) {
this.construct(session)
@ -19,39 +25,68 @@ class UserListeningSession {
toJSON() {
return {
id: this.id,
sessionType: this.sessionType,
userId: this.userId,
audiobookId: this.audiobookId,
audiobookTitle: this.audiobookTitle,
audiobookAuthor: this.audiobookAuthor,
audiobookGenres: [...this.audiobookGenres],
date: this.date,
dayOfWeek: this.dayOfWeek,
timeListening: this.timeListening,
lastUpdate: this.lastUpdate,
startedAt: this.startedAt,
finishedAt: this.finishedAt
startedAt: this.startedAt
}
}
construct(session) {
this.id = session.id
this.sessionType = session.sessionType
this.userId = session.userId
this.audiobookId = session.audiobookId
this.audiobookTitle = session.audiobookTitle
this.audiobookAuthor = session.audiobookAuthor
this.audiobookGenres = session.audiobookGenres
this.date = session.date
this.dayOfWeek = session.dayOfWeek
this.timeListening = session.timeListening || null
this.lastUpdate = session.lastUpdate || null
this.startedAt = session.startedAt
this.finishedAt = session.finishedAt || null
}
setData(audiobook, user) {
this.id = 'ls_' + (Math.trunc(Math.random() * 1000) + Date.now()).toString(36)
this.userId = user.id
this.audiobookId = audiobook.id
this.audiobookTitle = audiobook.title || ''
this.audiobookAuthor = audiobook.author || ''
this.audiobookAuthor = audiobook.authorFL || ''
this.audiobookGenres = [...audiobook.genres]
this.timeListening = 0
this.lastUpdate = Date.now()
this.startedAt = Date.now()
this.finishedAt = null
}
addListeningTime(timeListened) {
if (timeListened && !isNaN(timeListened)) {
if (!this.date) {
// Set date info on first listening update
this.date = date.format(new Date(), 'YYYY-MM-DD')
this.dayOfWeek = date.format(new Date(), 'dddd')
}
this.timeListening += timeListened
this.lastUpdate = Date.now()
}
}
// New date since start of listening session
checkDateRollover() {
if (!this.date) return false
return date.format(new Date(), 'YYYY-MM-DD') !== this.date
}
}
module.exports = UserListeningSession