audiobookshelf/client/components/readers/EpubReader.vue

270 lines
8.4 KiB
Vue
Raw Normal View History

<template>
<div class="h-full w-full">
2023-03-26 21:44:59 +02:00
<div class="h-full flex items-center justify-center">
<div style="width: 100px; max-width: 100px" class="h-full hidden sm:flex items-center overflow-x-hidden justify-center">
<span v-if="hasPrev" class="material-icons text-white text-opacity-50 hover:text-opacity-80 cursor-pointer text-6xl" @mousedown.prevent @click="prev">chevron_left</span>
</div>
2023-03-21 13:36:06 +01:00
<div id="frame" class="w-full" style="height: 80%">
<div id="viewer"></div>
</div>
2023-03-26 21:44:59 +02:00
<div style="width: 100px; max-width: 100px" class="h-full hidden sm:flex items-center justify-center overflow-x-hidden">
<span v-if="hasNext" class="material-icons text-white text-opacity-50 hover:text-opacity-80 cursor-pointer text-6xl" @mousedown.prevent @click="next">chevron_right</span>
</div>
</div>
</div>
</template>
<script>
import ePub from 'epubjs'
/**
* @typedef {object} EpubReader
2023-03-21 13:27:21 +01:00
* @property {ePub.Book} book
* @property {ePub.Rendition} rendition
*/
export default {
props: {
2023-03-21 13:27:21 +01:00
url: String,
libraryItem: {
type: Object,
default: () => {}
2023-03-21 13:27:21 +01:00
}
},
data() {
return {
2023-03-26 21:44:59 +02:00
windowWidth: 0,
2023-03-21 13:27:21 +01:00
/** @type {ePub.Book} */
book: null,
2023-03-21 13:27:21 +01:00
/** @type {ePub.Rendition} */
rendition: null
}
},
2023-03-21 13:27:21 +01:00
computed: {
/** @returns {string} */
libraryItemId() {
return this.libraryItem?.id
},
hasPrev() {
return !this.rendition?.location?.atStart
},
hasNext() {
return !this.rendition?.location?.atEnd
},
/** @returns {Array<ePub.NavItem>} */
chapters() {
return this.book ? this.book.navigation.toc : []
},
2023-03-21 13:27:21 +01:00
userMediaProgress() {
if (!this.libraryItemId) return
return this.$store.getters['user/getUserMediaProgress'](this.libraryItemId)
},
localStorageLocationsKey() {
return `ebookLocations-${this.libraryItemId}`
2023-03-26 21:44:59 +02:00
},
readerWidth() {
if (this.windowWidth < 640) return this.windowWidth
return this.windowWidth - 200
}
2023-03-21 13:27:21 +01:00
},
methods: {
prev() {
return this.rendition?.prev()
},
next() {
return this.rendition?.next()
},
goToChapter(href) {
return this.rendition?.display(href)
},
2023-03-21 13:27:21 +01:00
keyUp(e) {
const rtl = this.book.package.metadata.direction === 'rtl'
if ((e.keyCode || e.which) == 37) {
return rtl ? this.next() : this.prev()
} else if ((e.keyCode || e.which) == 39) {
return rtl ? this.prev() : this.next()
}
},
/**
* @param {object} payload
* @param {string} payload.ebookLocation - CFI of the current location
* @param {string} payload.ebookProgress - eBook Progress Percentage
*/
updateProgress(payload) {
this.$axios.$patch(`/api/me/progress/${this.libraryItemId}`, payload).catch((error) => {
console.error('EpubReader.updateProgress failed:', error)
})
},
getAllEbookLocationData() {
const locations = []
let totalSize = 0 // Total in bytes
for (const key in localStorage) {
if (!localStorage.hasOwnProperty(key) || !key.startsWith('ebookLocations-')) {
continue
}
try {
const ebookLocations = JSON.parse(localStorage[key])
if (!ebookLocations.locations) throw new Error('Invalid locations object')
ebookLocations.key = key
ebookLocations.size = (localStorage[key].length + key.length) * 2
locations.push(ebookLocations)
totalSize += ebookLocations.size
} catch (error) {
console.error('Failed to parse ebook locations', key, error)
localStorage.removeItem(key)
}
}
// Sort by oldest lastAccessed first
locations.sort((a, b) => a.lastAccessed - b.lastAccessed)
return {
locations,
totalSize
}
},
/** @param {string} locationString */
checkSaveLocations(locationString) {
const maxSizeInBytes = 3000000 // Allow epub locations to take up to 3MB of space
const newLocationsSize = JSON.stringify({ lastAccessed: Date.now(), locations: locationString }).length * 2
// Too large overall
if (newLocationsSize > maxSizeInBytes) {
console.error('Epub locations are too large to store. Size =', newLocationsSize)
return
}
const ebookLocationsData = this.getAllEbookLocationData()
let availableSpace = maxSizeInBytes - ebookLocationsData.totalSize
// Remove epub locations until there is room for locations
while (availableSpace < newLocationsSize && ebookLocationsData.locations.length) {
const oldestLocation = ebookLocationsData.locations.shift()
console.log(`Removing cached locations for epub "${oldestLocation.key}" taking up ${oldestLocation.size} bytes`)
availableSpace += oldestLocation.size
localStorage.removeItem(oldestLocation.key)
}
console.log(`Cacheing epub locations with key "${this.localStorageLocationsKey}" taking up ${newLocationsSize} bytes`)
this.saveLocations(locationString)
},
/** @param {string} locationString */
saveLocations(locationString) {
localStorage.setItem(
this.localStorageLocationsKey,
JSON.stringify({
lastAccessed: Date.now(),
locations: locationString
})
)
},
loadLocations() {
const locationsObjString = localStorage.getItem(this.localStorageLocationsKey)
if (!locationsObjString) return null
const locationsObject = JSON.parse(locationsObjString)
// Remove invalid location objects
if (!locationsObject.locations) {
console.error('Invalid epub locations stored', this.localStorageLocationsKey)
localStorage.removeItem(this.localStorageLocationsKey)
return null
}
// Update lastAccessed
this.saveLocations(locationsObject.locations)
return locationsObject.locations
},
/** @param {string} location - CFI of the new location */
2023-03-21 13:27:21 +01:00
relocated(location) {
2023-03-26 20:50:44 +02:00
if (this.userMediaProgress?.ebookLocation === location.start.cfi) {
return
}
if (location.end.percentage) {
this.updateProgress({
ebookLocation: location.start.cfi,
ebookProgress: location.end.percentage
})
} else {
this.updateProgress({
ebookLocation: location.start.cfi
})
2023-03-21 13:27:21 +01:00
}
},
initEpub() {
/** @type {EpubReader} */
const reader = this
2023-03-21 13:27:21 +01:00
/** @type {ePub.Book} */
reader.book = new ePub(reader.url, {
2023-03-26 21:44:59 +02:00
width: this.readerWidth,
height: window.innerHeight - 50
})
2023-03-21 13:27:21 +01:00
/** @type {ePub.Rendition} */
reader.rendition = reader.book.renderTo('viewer', {
2023-03-26 21:44:59 +02:00
width: this.readerWidth,
2023-03-21 13:36:06 +01:00
height: window.innerHeight * 0.8
})
// load saved progress
reader.rendition.display(this.userMediaProgress?.ebookLocation || reader.book.locations.start)
// load style
reader.rendition.themes.default({ '*': { color: '#fff!important' } })
2023-03-21 13:27:21 +01:00
reader.book.ready.then(() => {
// set up event listeners
reader.rendition.on('relocated', reader.relocated)
2023-03-21 13:27:21 +01:00
reader.rendition.on('keydown', reader.keyUp)
2023-03-26 21:44:59 +02:00
let touchStart = 0
let touchEnd = 0
reader.rendition.on('touchstart', (event) => {
touchStart = event.changedTouches[0].screenX
})
reader.rendition.on('touchend', (event) => {
touchEnd = event.changedTouches[0].screenX
const touchDistanceX = Math.abs(touchEnd - touchStart)
if (touchStart < touchEnd && touchDistanceX > 120) {
this.next()
}
if (touchStart > touchEnd && touchDistanceX > 120) {
this.prev()
}
})
// load ebook cfi locations
const savedLocations = this.loadLocations()
if (savedLocations) {
reader.book.locations.load(savedLocations)
2023-03-21 13:34:21 +01:00
} else {
reader.book.locations.generate().then(() => {
this.checkSaveLocations(reader.book.locations.save())
})
2023-03-21 13:34:21 +01:00
}
})
2023-03-26 21:44:59 +02:00
},
resize() {
this.windowWidth = window.innerWidth
this.rendition?.resize(this.readerWidth, window.innerHeight * 0.8)
}
},
2023-03-26 21:44:59 +02:00
beforeDestroy() {
window.removeEventListener('resize', this.resize)
this.book?.destroy()
},
mounted() {
2023-03-26 21:44:59 +02:00
this.windowWidth = window.innerWidth
window.addEventListener('resize', this.resize)
this.initEpub()
}
}
</script>