audiobookshelf/server/models/MediaProgress.js

73 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-03-12 20:51:45 +01:00
const { DataTypes, Model } = require('sequelize')
/*
* Polymorphic association: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations/
* Book has many MediaProgress. PodcastEpisode has many MediaProgress.
*/
module.exports = (sequelize) => {
class MediaProgress extends Model {
getMediaItem(options) {
if (!this.mediaItemType) return Promise.resolve(null)
2023-03-18 22:56:57 +01:00
const mixinMethodName = `get${this.mediaItemType}`
2023-03-12 20:51:45 +01:00
return this[mixinMethodName](options)
}
}
MediaProgress.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
2023-03-18 22:56:57 +01:00
MediaItemId: DataTypes.UUIDV4,
2023-03-12 20:51:45 +01:00
mediaItemType: DataTypes.STRING,
2023-03-18 22:56:57 +01:00
duration: DataTypes.FLOAT,
currentTime: DataTypes.FLOAT,
2023-03-12 20:51:45 +01:00
isFinished: DataTypes.BOOLEAN,
hideFromContinueListening: DataTypes.BOOLEAN,
finishedAt: DataTypes.DATE
}, {
sequelize,
modelName: 'MediaProgress'
})
const { Book, PodcastEpisode, User } = sequelize.models
Book.hasMany(MediaProgress, {
2023-03-18 22:56:57 +01:00
foreignKey: 'MediaItemId',
2023-03-12 20:51:45 +01:00
constraints: false,
scope: {
2023-03-18 22:56:57 +01:00
mediaItemType: 'Book'
2023-03-12 20:51:45 +01:00
}
})
2023-03-18 22:56:57 +01:00
MediaProgress.belongsTo(Book, { foreignKey: 'MediaItemId', constraints: false })
2023-03-12 20:51:45 +01:00
PodcastEpisode.hasMany(MediaProgress, {
2023-03-18 22:56:57 +01:00
foreignKey: 'MediaItemId',
2023-03-12 20:51:45 +01:00
constraints: false,
scope: {
2023-03-18 22:56:57 +01:00
mediaItemType: 'PodcastEpisode'
2023-03-12 20:51:45 +01:00
}
})
2023-03-18 22:56:57 +01:00
MediaProgress.belongsTo(PodcastEpisode, { foreignKey: 'MediaItemId', constraints: false })
2023-03-12 20:51:45 +01:00
MediaProgress.addHook('afterFind', findResult => {
if (!Array.isArray(findResult)) findResult = [findResult]
for (const instance of findResult) {
2023-03-18 22:56:57 +01:00
if (instance.mediaItemType === 'Book' && instance.Book !== undefined) {
instance.MediaItem = instance.Book
2023-03-18 22:56:57 +01:00
} else if (instance.mediaItemType === 'PodcastEpisode' && instance.PodcastEpisode !== undefined) {
instance.MediaItem = instance.PodcastEpisode
2023-03-12 20:51:45 +01:00
}
// To prevent mistakes:
delete instance.Book
delete instance.dataValues.Book
delete instance.PodcastEpisode
delete instance.dataValues.PodcastEpisode
2023-03-12 20:51:45 +01:00
}
})
User.hasMany(MediaProgress)
MediaProgress.belongsTo(User)
return MediaProgress
}