Compare commits

..

8 Commits

Author SHA1 Message Date
advplyr
73c1ea92f3 Add admin middleware for StatsController 2025-03-29 17:37:13 -05:00
advplyr
4fb5330308 Create new StatsController and move year in review stats endpoint 2025-03-29 17:34:17 -05:00
advplyr
f853cff920 Fix LazyBookCard test with new globals getter for placeholder url 2025-03-28 17:42:41 -05:00
advplyr
e87825f8df Merge pull request #4151 from mikiher/fix-component-tests
Fix broken component tests
2025-03-27 17:38:22 -05:00
advplyr
718433183b Fix Cover modal showing error image for items with no cover, update placeholder cover url to all come from global store 2025-03-27 17:37:25 -05:00
advplyr
7f3421f78a Merge pull request #4164 from advplyr/count_cache_for_userpermissions
Fix items count for users with item restricting permissions
2025-03-26 17:41:43 -05:00
mikiher
59e099f950 Add GitHub Actions workflow for running component tests 2025-03-24 07:42:26 +02:00
mikiher
b18da959db Fix broken component tests 2025-03-23 20:40:58 +02:00
14 changed files with 214 additions and 22 deletions

48
.github/workflows/component-tests.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: Run Component Tests
on:
workflow_dispatch:
inputs:
ref:
description: 'Branch/Tag/SHA to test'
required: true
pull_request:
paths:
- 'client/**'
- '.github/workflows/component-tests.yml'
push:
paths:
- 'client/**'
- '.github/workflows/component-tests.yml'
jobs:
run-component-tests:
name: Run Component Tests
runs-on: ubuntu-latest
steps:
- name: Checkout (push/pull request)
uses: actions/checkout@v4
if: github.event_name != 'workflow_dispatch'
- name: Checkout (workflow_dispatch)
uses: actions/checkout@v4
with:
ref: ${{ inputs.ref }}
if: github.event_name == 'workflow_dispatch'
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install dependencies
run: |
cd client
npm ci
- name: Run tests
run: |
cd client
npm test

View File

@@ -223,8 +223,7 @@ export default {
return this.mediaMetadata.explicit || false
},
placeholderUrl() {
const config = this.$config || this.$nuxt.$config
return `${config.routerBasePath}/book_placeholder.jpg`
return this.store.getters['globals/getPlaceholderCoverSrc']
},
bookCoverSrc() {
return this.store.getters['globals/getLibraryItemCoverSrc'](this._libraryItem, this.placeholderUrl)

View File

@@ -96,8 +96,8 @@ export default {
return this.author
},
placeholderUrl() {
const config = this.$config || this.$nuxt.$config
return `${config.routerBasePath}/book_placeholder.jpg`
const store = this.$store || this.$nuxt.$store
return store.getters['globals/getPlaceholderCoverSrc']
},
fullCoverUrl() {
if (!this.libraryItem) return null

View File

@@ -18,7 +18,7 @@
</div>
</div>
<p v-if="!imageFailed && showResolution" class="absolute -bottom-5 left-0 right-0 mx-auto text-xs text-gray-300 text-center">{{ resolution }}</p>
<p v-if="!imageFailed && showResolution && resolution" class="absolute -bottom-5 left-0 right-0 mx-auto text-xs text-gray-300 text-center">{{ resolution }}</p>
</div>
</template>
@@ -65,11 +65,12 @@ export default {
return 0.8 * this.sizeMultiplier
},
resolution() {
if (!this.naturalWidth || !this.naturalHeight) return null
return `${this.naturalWidth}×${this.naturalHeight}px`
},
placeholderUrl() {
const config = this.$config || this.$nuxt.$config
return `${config.routerBasePath}/book_placeholder.jpg`
const store = this.$store || this.$nuxt.$store
return store.getters['globals/getPlaceholderCoverSrc']
}
},
methods: {

View File

@@ -2,7 +2,7 @@
<div class="w-full h-full overflow-hidden overflow-y-auto px-2 sm:px-4 py-6 relative">
<div class="flex flex-col sm:flex-row mb-4">
<div class="relative self-center md:self-start">
<covers-preview-cover :src="$store.getters['globals/getLibraryItemCoverSrcById'](libraryItemId, libraryItemUpdatedAt, true)" :width="120" :book-cover-aspect-ratio="bookCoverAspectRatio" />
<covers-preview-cover :src="coverUrl" :width="120" :book-cover-aspect-ratio="bookCoverAspectRatio" />
<!-- book cover overlay -->
<div v-if="media.coverPath" class="absolute top-0 left-0 w-full h-full z-10 opacity-0 hover:opacity-100 transition-opacity duration-100">
@@ -157,6 +157,12 @@ export default {
coverPath() {
return this.media.coverPath
},
coverUrl() {
if (!this.coverPath) {
return this.$store.getters['globals/getPlaceholderCoverSrc']
}
return this.$store.getters['globals/getLibraryItemCoverSrcById'](this.libraryItemId, this.libraryItemUpdatedAt, true)
},
mediaMetadata() {
return this.media.metadata || {}
},

View File

@@ -55,7 +55,7 @@ export default {
return this.item.coverPath
},
coverUrl() {
if (!this.coverPath) return `${this.$config.routerBasePath}/book_placeholder.jpg`
if (!this.coverPath) return this.$store.getters['globals/getPlaceholderCoverSrc']
return this.$store.getters['globals/getLibraryItemCoverSrcById'](this.libraryItemId)
},
bookCoverAspectRatio() {

View File

@@ -19,7 +19,9 @@ describe('AuthorCard', () => {
const mocks = {
$strings: {
LabelBooks: 'Books',
ButtonQuickMatch: 'Quick Match'
ButtonQuickMatch: 'Quick Match',
ToastAuthorUpdateSuccess: 'Author updated',
ToastAuthorUpdateSuccessNoImageFound: 'Author updated (no image found)'
},
$store: {
getters: {
@@ -167,7 +169,7 @@ describe('AuthorCard', () => {
cy.get('&match').click()
cy.get('&spinner').should('be.hidden')
cy.get('@success').should('have.been.calledOnceWithExactly', 'Author John Doe was updated (no image found)')
cy.get('@success').should('have.been.calledOnceWithExactly', 'Author updated (no image found)')
cy.get('@error').should('not.have.been.called')
cy.get('@info').should('not.have.been.called')
})
@@ -189,7 +191,7 @@ describe('AuthorCard', () => {
cy.get('&match').click()
cy.get('&spinner').should('be.hidden')
cy.get('@success').should('have.been.calledOnceWithExactly', 'Author John Doe was updated')
cy.get('@success').should('have.been.calledOnceWithExactly', 'Author updated')
cy.get('@error').should('not.have.been.called')
cy.get('@info').should('not.have.been.called')
})

View File

@@ -49,6 +49,7 @@ function createMountOptions() {
'libraries/getLibraryProvider': () => 'audible.us',
'libraries/getBookCoverAspectRatio': 1,
'globals/getLibraryItemCoverSrc': () => 'https://my.server.com/book_placeholder.jpg',
'globals/getPlaceholderCoverSrc': 'https://my.server.com/book_placeholder.jpg',
getLibraryItemsStreaming: () => null,
getIsMediaQueued: () => false,
getIsStreamingFromDifferentLibrary: () => false
@@ -172,6 +173,7 @@ describe('LazyBookCard', () => {
})
it('shows titleImageNotReady and sets opacity 0 on coverImage when image not ready', () => {
mountOptions.mocks.$store.getters['globals/getLibraryItemCoverSrc'] = () => 'https://my.server.com/notfound.jpg'
cy.mount(LazyBookCard, mountOptions)
cy.get('&titleImageNotReady').should('be.visible')
@@ -257,7 +259,7 @@ describe('LazyBookCard', () => {
cy.get('#book-card-0').trigger('mouseover')
cy.get('&titleImageNotReady').should('be.hidden')
cy.get('&seriesNameOverlay').should('be.visible').and('have.text', 'Middle Earth Chronicles')
cy.get('&seriesNameOverlay').should('be.visible').and('have.text', 'The Lord of the Rings')
})
it('shows the seriesSequenceList when collapsed series has a sequence list', () => {

View File

@@ -30,6 +30,14 @@ describe('LazySeriesCard', () => {
}
const mocks = {
$getString: (id, args) => {
switch (id) {
case 'LabelAddedDate':
return `Added ${args[0]}`
default:
return null
}
},
$store: {
getters: {
'user/getUserCanUpdate': true,

View File

@@ -64,7 +64,7 @@ export default {
return this.mediaItemShare.playbackSession
},
coverUrl() {
if (!this.playbackSession.coverPath) return `${this.$config.routerBasePath}/book_placeholder.jpg`
if (!this.playbackSession.coverPath) return this.$store.getters['globals/getPlaceholderCoverSrc']
return `${this.$config.routerBasePath}/public/share/${this.mediaItemShare.slug}/cover`
},
downloadUrl() {

View File

@@ -87,7 +87,7 @@ export const getters = {
getLibraryItemCoverSrc:
(state, getters, rootState, rootGetters) =>
(libraryItem, placeholder = null, raw = false) => {
if (!placeholder) placeholder = `${rootState.routerBasePath}/book_placeholder.jpg`
if (!placeholder) placeholder = getters.getPlaceholderCoverSrc
if (!libraryItem) return placeholder
const media = libraryItem.media
if (!media?.coverPath || media.coverPath === placeholder) return placeholder
@@ -95,7 +95,6 @@ export const getters = {
// Absolute URL covers (should no longer be used)
if (media.coverPath.startsWith('http:') || media.coverPath.startsWith('https:')) return media.coverPath
const userToken = rootGetters['user/getToken']
const lastUpdate = libraryItem.updatedAt || Date.now()
const libraryItemId = libraryItem.libraryItemId || libraryItem.id // Workaround for /users/:id page showing media progress covers
return `${rootState.routerBasePath}/api/items/${libraryItemId}/cover?ts=${lastUpdate}${raw ? '&raw=1' : ''}`
@@ -103,11 +102,13 @@ export const getters = {
getLibraryItemCoverSrcById:
(state, getters, rootState, rootGetters) =>
(libraryItemId, timestamp = null, raw = false) => {
const placeholder = `${rootState.routerBasePath}/book_placeholder.jpg`
if (!libraryItemId) return placeholder
const userToken = rootGetters['user/getToken']
if (!libraryItemId) return getters.getPlaceholderCoverSrc
return `${rootState.routerBasePath}/api/items/${libraryItemId}/cover?${raw ? '&raw=1' : ''}${timestamp ? `&ts=${timestamp}` : ''}`
},
getPlaceholderCoverSrc: (state, getters, rootState, rootGetters) => {
return `${rootState.routerBasePath}/book_placeholder.jpg`
},
getIsBatchSelectingMediaItems: (state) => {
return state.selectedMediaItems.length
}

View File

@@ -0,0 +1,75 @@
const { Request, Response, NextFunction } = require('express')
const Logger = require('../Logger')
const adminStats = require('../utils/queries/adminStats')
/**
* @typedef RequestUserObject
* @property {import('../models/User')} user
*
* @typedef {Request & RequestUserObject} RequestWithUser
*/
class StatsController {
constructor() {}
/**
* GET: /api/stats/server
* Currently not in use
*
* @param {RequestWithUser} req
* @param {Response} res
*/
async getServerStats(req, res) {
Logger.debug('[StatsController] getServerStats')
const totalSize = await adminStats.getTotalSize()
const numAudioFiles = await adminStats.getNumAudioFiles()
res.json({
books: {
...totalSize.books,
numAudioFiles: numAudioFiles.numBookAudioFiles
},
podcasts: {
...totalSize.podcasts,
numAudioFiles: numAudioFiles.numPodcastAudioFiles
},
total: {
...totalSize.total,
numAudioFiles: numAudioFiles.numAudioFiles
}
})
}
/**
* GET: /api/stats/year/:year
*
* @param {RequestWithUser} req
* @param {Response} res
*/
async getAdminStatsForYear(req, res) {
const year = Number(req.params.year)
if (isNaN(year) || year < 2000 || year > 9999) {
Logger.error(`[StatsController] Invalid year "${year}"`)
return res.status(400).send('Invalid year')
}
const stats = await adminStats.getStatsForYear(year)
res.json(stats)
}
/**
*
* @param {RequestWithUser} req
* @param {Response} res
* @param {NextFunction} next
*/
async middleware(req, res, next) {
if (!req.user.isAdminOrUp) {
Logger.error(`[StatsController] Non-admin user "${req.user.username}" attempted to access stats route`)
return res.sendStatus(403)
}
next()
}
}
module.exports = new StatsController()

View File

@@ -33,8 +33,7 @@ const RSSFeedController = require('../controllers/RSSFeedController')
const CustomMetadataProviderController = require('../controllers/CustomMetadataProviderController')
const MiscController = require('../controllers/MiscController')
const ShareController = require('../controllers/ShareController')
const { getTitleIgnorePrefix } = require('../utils/index')
const StatsController = require('../controllers/StatsController')
class ApiRouter {
constructor(Server) {
@@ -320,6 +319,12 @@ class ApiRouter {
this.router.post('/share/mediaitem', ShareController.createMediaItemShare.bind(this))
this.router.delete('/share/mediaitem/:id', ShareController.deleteMediaItemShare.bind(this))
//
// Stats Routes
//
this.router.get('/stats/year/:year', StatsController.middleware.bind(this), StatsController.getAdminStatsForYear.bind(this))
this.router.get('/stats/server', StatsController.middleware.bind(this), StatsController.getServerStats.bind(this))
//
// Misc Routes
//
@@ -338,7 +343,6 @@ class ApiRouter {
this.router.get('/auth-settings', MiscController.getAuthSettings.bind(this))
this.router.patch('/auth-settings', MiscController.updateAuthSettings.bind(this))
this.router.post('/watcher/update', MiscController.updateWatchedPath.bind(this))
this.router.get('/stats/year/:year', MiscController.getAdminStatsForYear.bind(this))
this.router.get('/logger-data', MiscController.getLoggerData.bind(this))
}

View File

@@ -167,5 +167,51 @@ module.exports = {
topNarrators,
topGenres
}
},
/**
* Get total file size and number of items for books and podcasts
*
* @typedef {Object} SizeObject
* @property {number} totalSize
* @property {number} numItems
*
* @returns {Promise<{books: SizeObject, podcasts: SizeObject, total: SizeObject}}>}
*/
async getTotalSize() {
const [mediaTypeStats] = await Database.sequelize.query(`SELECT li.mediaType, SUM(li.size) AS totalSize, COUNT(*) AS numItems FROM libraryItems li group by li.mediaType;`)
const bookStats = mediaTypeStats.find((m) => m.mediaType === 'book')
const podcastStats = mediaTypeStats.find((m) => m.mediaType === 'podcast')
return {
books: {
totalSize: bookStats?.totalSize || 0,
numItems: bookStats?.numItems || 0
},
podcasts: {
totalSize: podcastStats?.totalSize || 0,
numItems: podcastStats?.numItems || 0
},
total: {
totalSize: (bookStats?.totalSize || 0) + (podcastStats?.totalSize || 0),
numItems: (bookStats?.numItems || 0) + (podcastStats?.numItems || 0)
}
}
},
/**
* Get total number of audio files for books and podcasts
*
* @returns {Promise<{numBookAudioFiles: number, numPodcastAudioFiles: number, numAudioFiles: number}>}
*/
async getNumAudioFiles() {
const [numBookAudioFilesRow] = await Database.sequelize.query(`SELECT SUM(json_array_length(b.audioFiles)) AS numAudioFiles FROM books b;`)
const numBookAudioFiles = numBookAudioFilesRow[0]?.numAudioFiles || 0
const numPodcastAudioFiles = await Database.podcastEpisodeModel.count()
return {
numBookAudioFiles,
numPodcastAudioFiles,
numAudioFiles: numBookAudioFiles + numPodcastAudioFiles
}
}
}