audiobookshelf/server/models/PlaybackSession.js

81 lines
2.4 KiB
JavaScript
Raw Normal View History

const { DataTypes, Model } = require('sequelize')
module.exports = (sequelize) => {
class PlaybackSession extends Model {
getMediaItem(options) {
if (!this.mediaItemType) return Promise.resolve(null)
2023-03-19 21:19:22 +01:00
const mixinMethodName = `get${sequelize.uppercaseFirst(this.mediaItemType)}`
return this[mixinMethodName](options)
}
}
PlaybackSession.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
2023-03-19 21:19:22 +01:00
mediaItemId: DataTypes.UUIDV4,
mediaItemType: DataTypes.STRING,
displayTitle: DataTypes.STRING,
displayAuthor: DataTypes.STRING,
2023-03-18 22:56:57 +01:00
duration: DataTypes.FLOAT,
playMethod: DataTypes.STRING,
mediaPlayer: DataTypes.STRING,
2023-03-18 22:56:57 +01:00
startTime: DataTypes.FLOAT,
currentTime: DataTypes.FLOAT,
serverVersion: DataTypes.STRING
}, {
sequelize,
2023-03-19 21:19:22 +01:00
modelName: 'playbackSession'
})
2023-03-19 21:19:22 +01:00
const { book, podcastEpisode, user, device } = sequelize.models
2023-03-19 21:19:22 +01:00
user.hasMany(PlaybackSession)
PlaybackSession.belongsTo(user)
2023-03-13 23:13:31 +01:00
2023-03-19 21:19:22 +01:00
device.hasMany(PlaybackSession)
PlaybackSession.belongsTo(device)
2023-03-13 23:13:31 +01:00
2023-03-19 21:19:22 +01:00
book.hasMany(PlaybackSession, {
foreignKey: 'mediaItemId',
constraints: false,
scope: {
2023-03-19 21:19:22 +01:00
mediaItemType: 'book'
}
})
2023-03-19 21:19:22 +01:00
PlaybackSession.belongsTo(book, { foreignKey: 'mediaItemId', constraints: false })
2023-03-19 21:19:22 +01:00
podcastEpisode.hasOne(PlaybackSession, {
foreignKey: 'mediaItemId',
constraints: false,
scope: {
2023-03-19 21:19:22 +01:00
mediaItemType: 'podcastEpisode'
}
})
2023-03-19 21:19:22 +01:00
PlaybackSession.belongsTo(podcastEpisode, { foreignKey: 'mediaItemId', constraints: false })
PlaybackSession.addHook('afterFind', findResult => {
2023-03-19 21:19:22 +01:00
if (!findResult) return
if (!Array.isArray(findResult)) findResult = [findResult]
2023-03-19 21:19:22 +01:00
for (const instance of findResult) {
2023-03-19 21:19:22 +01:00
if (instance.mediaItemType === 'book' && instance.book !== undefined) {
instance.mediaItem = instance.book
instance.dataValues.mediaItem = instance.dataValues.book
} else if (instance.mediaItemType === 'podcastEpisode' && instance.podcastEpisode !== undefined) {
instance.mediaItem = instance.podcastEpisode
instance.dataValues.mediaItem = instance.dataValues.podcastEpisode
}
// To prevent mistakes:
2023-03-19 21:19:22 +01:00
delete instance.book
delete instance.dataValues.book
delete instance.podcastEpisode
delete instance.dataValues.podcastEpisode
}
})
return PlaybackSession
}