2020-11-27 20:51:31 -09:00
|
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
|
|
|
import { useDataProvider, useNotify } from 'react-admin'
|
|
|
|
|
import subsonic from '../subsonic'
|
|
|
|
|
|
2021-03-26 19:56:19 -08:00
|
|
|
export const useToggleLove = (resource, record = {}) => {
|
2020-11-27 20:51:31 -09:00
|
|
|
const [loading, setLoading] = useState(false)
|
|
|
|
|
const notify = useNotify()
|
|
|
|
|
|
|
|
|
|
const mountedRef = useRef(false)
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
mountedRef.current = true
|
|
|
|
|
return () => {
|
|
|
|
|
mountedRef.current = false
|
|
|
|
|
}
|
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
const dataProvider = useDataProvider()
|
|
|
|
|
|
|
|
|
|
const refreshRecord = useCallback(() => {
|
2025-06-04 16:38:28 -08:00
|
|
|
const promises = []
|
|
|
|
|
|
|
|
|
|
// Always refresh the original resource
|
|
|
|
|
const params = { id: record.id }
|
|
|
|
|
if (record.playlistId) {
|
|
|
|
|
params.filter = { playlist_id: record.playlistId }
|
|
|
|
|
}
|
|
|
|
|
promises.push(dataProvider.getOne(resource, params))
|
|
|
|
|
|
|
|
|
|
// If we have a mediaFileId, also refresh the song
|
|
|
|
|
if (record.mediaFileId) {
|
|
|
|
|
promises.push(dataProvider.getOne('song', { id: record.mediaFileId }))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Promise.all(promises)
|
|
|
|
|
.catch((e) => {
|
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
|
console.log('Error encountered: ' + e)
|
|
|
|
|
})
|
|
|
|
|
.finally(() => {
|
|
|
|
|
if (mountedRef.current) {
|
|
|
|
|
setLoading(false)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}, [dataProvider, record.mediaFileId, record.id, record.playlistId, resource])
|
2020-11-27 20:51:31 -09:00
|
|
|
|
2021-03-26 19:56:19 -08:00
|
|
|
const toggleLove = () => {
|
2020-11-27 20:51:31 -09:00
|
|
|
const toggle = record.starred ? subsonic.unstar : subsonic.star
|
2025-06-04 16:38:28 -08:00
|
|
|
const id = record.mediaFileId || record.id
|
2020-11-27 20:51:31 -09:00
|
|
|
|
|
|
|
|
setLoading(true)
|
2025-06-04 16:38:28 -08:00
|
|
|
toggle(id)
|
2020-11-27 20:51:31 -09:00
|
|
|
.then(refreshRecord)
|
|
|
|
|
.catch((e) => {
|
2024-09-28 07:54:36 -08:00
|
|
|
// eslint-disable-next-line no-console
|
2021-03-26 19:56:19 -08:00
|
|
|
console.log('Error toggling love: ', e)
|
2020-11-27 20:51:31 -09:00
|
|
|
notify('ra.page.error', 'warning')
|
|
|
|
|
if (mountedRef.current) {
|
|
|
|
|
setLoading(false)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-26 19:56:19 -08:00
|
|
|
return [toggleLove, loading]
|
2020-11-27 20:51:31 -09:00
|
|
|
}
|