refactor(metadata): consolidate metadata providers on the frontend (#2719)
This commit is contained in:
+14
-320
@@ -664,327 +664,21 @@
|
||||
@if (providerSectionExpanded) {
|
||||
<div class="collapsible-content">
|
||||
<div class="field-row metadata-ids-row">
|
||||
@if (isFieldVisible('openlibraryId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="openlibraryId">{{ t('openlibraryId') }} @if (isEmbeddable('openlibraryId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="openlibraryId" formControlName="openlibraryId"/>
|
||||
@if (!book.metadata!['openlibraryIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('openlibraryId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['openlibraryIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('openlibraryId')" severity="warn"></p-button>
|
||||
}
|
||||
@for (field of providerFields.fields(); track field.name) {
|
||||
@if (isFieldVisible(field.name)) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label [for]="field.name">{{ providerFields.label(field.name) }} @if (isEmbeddable(field.name, book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText [id]="field.name" [formControlName]="field.name"/>
|
||||
@if (!book.metadata![field.lockName]) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.name)" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata![field.lockName]) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.name)" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('asin')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="asin">{{ t('amazonAsin') }} @if (isEmbeddable('asin', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="asin" formControlName="asin"/>
|
||||
@if (!book.metadata!['asinLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['asinLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('amazonRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="amazonRating">{{ t('amazonRating') }} @if (isEmbeddable('amazonRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="amazonRating" formControlName="amazonRating"/>
|
||||
@if (!book.metadata!['amazonRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('amazonRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['amazonRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('amazonRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('amazonReviewCount')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="amazonRatingCount">{{ t('amazonReviewCount') }} @if (isEmbeddable('amazonReviewCount', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="amazonRatingCount" formControlName="amazonReviewCount"/>
|
||||
@if (!book.metadata!['amazonReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('amazonReviewCount')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['amazonReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('amazonReviewCount')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('googleId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="googleId">{{ t('googleBooksId') }} @if (isEmbeddable('googleId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="googleId" formControlName="googleId"/>
|
||||
@if (!book.metadata!['googleIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('googleId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['googleIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('googleId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('goodreadsId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="goodreadsId">{{ t('goodreadsId') }} @if (isEmbeddable('goodreadsId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="goodreadsId" formControlName="goodreadsId"/>
|
||||
@if (!book.metadata!['goodreadsIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['goodreadsIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('goodreadsRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="goodreadsRating">{{ t('goodreadsRating') }} @if (isEmbeddable('goodreadsRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="goodreadsRating" formControlName="goodreadsRating"/>
|
||||
@if (!book.metadata!['goodreadsRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['goodreadsRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('goodreadsReviewCount')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="goodreadsReviewCount">{{ t('goodreadsReviewCount') }} @if (isEmbeddable('goodreadsReviewCount', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="goodreadsReviewCount" formControlName="goodreadsReviewCount"/>
|
||||
@if (!book.metadata!['goodreadsReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('goodreadsReviewCount')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['goodreadsReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('goodreadsReviewCount')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('hardcoverId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="hardcoverId">{{ t('hardcoverId') }} @if (isEmbeddable('hardcoverId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="hardcoverId" formControlName="hardcoverId"/>
|
||||
@if (!book.metadata!['hardcoverIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['hardcoverIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('hardcoverBookId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="hardcoverBookId">{{ t('hardcoverBookId') }} @if (isEmbeddable('hardcoverBookId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="hardcoverBookId" formControlName="hardcoverBookId"/>
|
||||
@if (!book.metadata!['hardcoverBookIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverBookId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['hardcoverBookIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverBookId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('hardcoverRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="hardcoverRating">{{ t('hardcoverRating') }} @if (isEmbeddable('hardcoverRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="hardcoverRating" formControlName="hardcoverRating"/>
|
||||
@if (!book.metadata!['hardcoverRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['hardcoverRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('hardcoverReviewCount')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="hardcoverReviewCount">{{ t('hardcoverReviewCount') }} @if (isEmbeddable('hardcoverReviewCount', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="hardcoverReviewCount" formControlName="hardcoverReviewCount"/>
|
||||
@if (!book.metadata!['hardcoverReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('hardcoverReviewCount')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['hardcoverReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('hardcoverReviewCount')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('lubimyczytacId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="lubimyczytacId">{{ t('lubimyczytacId') }} @if (isEmbeddable('lubimyczytacId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="lubimyczytacId" formControlName="lubimyczytacId"/>
|
||||
@if (!book.metadata!['lubimyczytacIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('lubimyczytacId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['lubimyczytacIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('lubimyczytacId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('lubimyczytacRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="lubimyczytacRating">{{ t('lubimyczytacRating') }} @if (isEmbeddable('lubimyczytacRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="lubimyczytacRating" formControlName="lubimyczytacRating"/>
|
||||
@if (!book.metadata!['lubimyczytacRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('lubimyczytacRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['lubimyczytacRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('lubimyczytacRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('comicvineId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="comicvineId">{{ t('comicvineId') }} @if (isEmbeddable('comicvineId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="comicvineId" formControlName="comicvineId"/>
|
||||
@if (!book.metadata!['comicvineIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('comicvineId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['comicvineIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('comicvineId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('ranobedbId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="ranobedbId">{{ t('ranobedbId') }} @if (isEmbeddable('ranobedbId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="ranobedbId" formControlName="ranobedbId"/>
|
||||
@if (!book.metadata!['ranobedbIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('ranobedbId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['ranobedbIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('ranobedbId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('ranobedbRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="ranobedbRating">{{ t('ranobedbRating') }} @if (isEmbeddable('ranobedbRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="ranobedbRating" formControlName="ranobedbRating"/>
|
||||
@if (!book.metadata!['ranobedbRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('ranobedbRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['ranobedbRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('ranobedbRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('audibleId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="audibleId">{{ t('audibleId') }} @if (isEmbeddable('audibleId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="audibleId" formControlName="audibleId"/>
|
||||
@if (!book.metadata!['audibleIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['audibleIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('audibleRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="audibleRating">{{ t('audibleRating') }} @if (isEmbeddable('audibleRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="audibleRating" formControlName="audibleRating"/>
|
||||
@if (!book.metadata!['audibleRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['audibleRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('audibleReviewCount')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="audibleReviewCount">{{ t('audibleReviewCount') }} @if (isEmbeddable('audibleReviewCount', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="audibleReviewCount" formControlName="audibleReviewCount"/>
|
||||
@if (!book.metadata!['audibleReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleReviewCount')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['audibleReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleReviewCount')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('applebooksId')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="applebooksId">{{ t('applebooksId') }} @if (isEmbeddable('applebooksId', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="applebooksId" formControlName="applebooksId"/>
|
||||
@if (!book.metadata!['applebooksIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('applebooksId')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['applebooksIdLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('applebooksId')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('applebooksRating')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="applebooksRating">{{ t('applebooksRating') }} @if (isEmbeddable('applebooksRating', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="applebooksRating" formControlName="applebooksRating"/>
|
||||
@if (!book.metadata!['applebooksRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('applebooksRating')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['applebooksRatingLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('applebooksRating')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (isFieldVisible('applebooksReviewCount')) {
|
||||
<div class="field-group metadata-id-field">
|
||||
<label for="applebooksReviewCount">{{ t('applebooksReviewCount') }} @if (isEmbeddable('applebooksReviewCount', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
|
||||
<div class="field-with-lock">
|
||||
<input pSize="small" pInputText id="applebooksReviewCount" formControlName="applebooksReviewCount"/>
|
||||
@if (!book.metadata!['applebooksReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('applebooksReviewCount')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['applebooksReviewCountLocked']) {
|
||||
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('applebooksReviewCount')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+58
-244
@@ -1,4 +1,5 @@
|
||||
import {Component, computed, DestroyRef, effect, EffectRef, EventEmitter, inject, Input, OnInit, Output} from "@angular/core";
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {Component, computed, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from "@angular/core";
|
||||
import {InputText} from "@openng/optimus-ui/inputtext";
|
||||
import {Button} from "@openng/optimus-ui/button";
|
||||
import {Divider} from "@openng/optimus-ui/divider";
|
||||
@@ -8,7 +9,7 @@ import {MessageService} from "@openng/optimus-ui/api";
|
||||
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper,} from "../../../../book/model/book.model";
|
||||
import {UrlHelperService} from "../../../../../shared/service/url-helper.service";
|
||||
import {CoverComponent} from "../../../../../shared/components/cover/cover.component";
|
||||
import {ALL_COMIC_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, COMIC_FORM_TO_MODEL_LOCK, COMIC_TEXT_METADATA_FIELDS, COMIC_ARRAY_METADATA_FIELDS, COMIC_TEXTAREA_METADATA_FIELDS, isFieldEmbeddable, hasMetadataWriter} from '../../../../../shared/metadata';
|
||||
import {ALL_COMIC_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, COMIC_FORM_TO_MODEL_LOCK, COMIC_TEXT_METADATA_FIELDS, COMIC_ARRAY_METADATA_FIELDS, COMIC_TEXTAREA_METADATA_FIELDS, isFieldEmbeddable, hasMetadataWriter, MetadataProviderFieldsService, providerFieldRecord} from '../../../../../shared/metadata';
|
||||
import {FileUpload, FileUploadErrorEvent, FileUploadEvent,} from "@openng/optimus-ui/fileupload";
|
||||
import {HttpResponse} from "@angular/common/http";
|
||||
import {BookService} from "../../../../book/service/book.service";
|
||||
@@ -33,6 +34,9 @@ import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-se
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {MetadataSourceQueryService} from '../../../sources/metadata-source-query.service';
|
||||
|
||||
@Component({
|
||||
selector: "app-metadata-editor",
|
||||
standalone: true,
|
||||
@@ -102,6 +106,9 @@ export class MetadataEditorComponent implements OnInit {
|
||||
private destroyRef = inject(DestroyRef);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly sources = inject(MetadataSourceQueryService);
|
||||
protected readonly providerFields = inject(MetadataProviderFieldsService);
|
||||
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
|
||||
|
||||
metadataForm: FormGroup;
|
||||
@@ -147,33 +154,13 @@ export class MetadataEditorComponent implements OnInit {
|
||||
comicTextareaFields = COMIC_TEXTAREA_METADATA_FIELDS;
|
||||
audiobookMetadataFields = AUDIOBOOK_METADATA_FIELDS;
|
||||
|
||||
providerSpecificFields: MetadataProviderSpecificFields = {
|
||||
openlibraryId: true,
|
||||
asin: true,
|
||||
amazonRating: true,
|
||||
amazonReviewCount: true,
|
||||
googleId: true,
|
||||
goodreadsId: true,
|
||||
goodreadsRating: true,
|
||||
goodreadsReviewCount: true,
|
||||
hardcoverId: true,
|
||||
hardcoverBookId: true,
|
||||
hardcoverRating: true,
|
||||
hardcoverReviewCount: true,
|
||||
comicvineId: true,
|
||||
lubimyczytacId: true,
|
||||
lubimyczytacRating: true,
|
||||
ranobedbId: true,
|
||||
ranobedbRating: true,
|
||||
audibleId: true,
|
||||
audibleRating: true,
|
||||
audibleReviewCount: true,
|
||||
applebooksId: true,
|
||||
applebooksRating: true,
|
||||
applebooksReviewCount: true,
|
||||
};
|
||||
private readonly providerSpecificFields = computed<MetadataProviderSpecificFields>(
|
||||
() => this.appSettingsService.appSettings()?.metadataProviderSpecificFields
|
||||
?? providerFieldRecord(this.providerFields.fields(), () => true),
|
||||
);
|
||||
|
||||
private readonly providerFieldNames = computed(() => new Set(this.providerFields.fields().map(field => field.name)));
|
||||
|
||||
private syncProviderFieldsEffect!: EffectRef;
|
||||
readonly navigationState = this.bookNavigationService.navigationState;
|
||||
readonly canNavigatePrevious = this.bookNavigationService.canNavigatePrevious;
|
||||
readonly canNavigateNext = this.bookNavigationService.canNavigateNext;
|
||||
@@ -279,29 +266,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
description: new FormControl(""),
|
||||
pageCount: new FormControl(""),
|
||||
language: new FormControl(""),
|
||||
openlibraryId: new FormControl(""),
|
||||
asin: new FormControl(""),
|
||||
amazonRating: new FormControl(""),
|
||||
amazonReviewCount: new FormControl(""),
|
||||
goodreadsId: new FormControl(""),
|
||||
comicvineId: new FormControl(""),
|
||||
goodreadsRating: new FormControl(""),
|
||||
goodreadsReviewCount: new FormControl(""),
|
||||
hardcoverId: new FormControl(""),
|
||||
hardcoverBookId: new FormControl(""),
|
||||
hardcoverRating: new FormControl(""),
|
||||
hardcoverReviewCount: new FormControl(""),
|
||||
lubimyczytacId: new FormControl(""),
|
||||
lubimyczytacRating: new FormControl(""),
|
||||
ranobedbId: new FormControl(""),
|
||||
ranobedbRating: new FormControl(""),
|
||||
googleId: new FormControl(""),
|
||||
audibleId: new FormControl(""),
|
||||
audibleRating: new FormControl(""),
|
||||
audibleReviewCount: new FormControl(""),
|
||||
applebooksId: new FormControl(""),
|
||||
applebooksRating: new FormControl(""),
|
||||
applebooksReviewCount: new FormControl(""),
|
||||
seriesName: new FormControl(""),
|
||||
seriesNumber: new FormControl(""),
|
||||
seriesTotal: new FormControl(""),
|
||||
@@ -321,29 +285,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
descriptionLocked: new FormControl(false),
|
||||
pageCountLocked: new FormControl(false),
|
||||
languageLocked: new FormControl(false),
|
||||
openlibraryIdLocked: new FormControl(false),
|
||||
asinLocked: new FormControl(false),
|
||||
amazonRatingLocked: new FormControl(false),
|
||||
amazonReviewCountLocked: new FormControl(false),
|
||||
goodreadsIdLocked: new FormControl(""),
|
||||
comicvineIdLocked: new FormControl(false),
|
||||
goodreadsRatingLocked: new FormControl(false),
|
||||
goodreadsReviewCountLocked: new FormControl(false),
|
||||
hardcoverIdLocked: new FormControl(false),
|
||||
hardcoverBookIdLocked: new FormControl(false),
|
||||
hardcoverRatingLocked: new FormControl(false),
|
||||
hardcoverReviewCountLocked: new FormControl(false),
|
||||
lubimyczytacIdLocked: new FormControl(false),
|
||||
lubimyczytacRatingLocked: new FormControl(false),
|
||||
ranobedbIdLocked: new FormControl(""),
|
||||
ranobedbRatingLocked: new FormControl(false),
|
||||
googleIdLocked: new FormControl(false),
|
||||
audibleIdLocked: new FormControl(false),
|
||||
audibleRatingLocked: new FormControl(false),
|
||||
audibleReviewCountLocked: new FormControl(false),
|
||||
applebooksIdLocked: new FormControl(false),
|
||||
applebooksRatingLocked: new FormControl(false),
|
||||
applebooksReviewCountLocked: new FormControl(false),
|
||||
seriesNameLocked: new FormControl(false),
|
||||
seriesNumberLocked: new FormControl(false),
|
||||
seriesTotalLocked: new FormControl(false),
|
||||
@@ -380,6 +321,11 @@ export class MetadataEditorComponent implements OnInit {
|
||||
{label: '21+', value: 21}
|
||||
];
|
||||
|
||||
for (const field of this.providerFields.fields()) {
|
||||
this.metadataForm.addControl(field.name, new FormControl(''));
|
||||
this.metadataForm.addControl(field.lockName, new FormControl(false));
|
||||
}
|
||||
|
||||
// Add audiobook metadata form controls
|
||||
for (const field of AUDIOBOOK_METADATA_FIELDS) {
|
||||
const defaultValue = field.type === 'boolean' ? null : '';
|
||||
@@ -393,13 +339,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
this.metadataForm.addControl(field.controlName, new FormControl(defaultValue));
|
||||
this.metadataForm.addControl(field.lockedKey, new FormControl(false));
|
||||
}
|
||||
|
||||
this.syncProviderFieldsEffect = effect(() => {
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
if (settings?.metadataProviderSpecificFields) {
|
||||
this.providerSpecificFields = settings.metadataProviderSpecificFields;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -427,29 +366,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
language: metadata.language ?? null,
|
||||
rating: metadata.rating ?? null,
|
||||
reviewCount: metadata.reviewCount ?? null,
|
||||
openlibraryId: metadata.openlibraryId ?? null,
|
||||
asin: metadata.asin ?? null,
|
||||
amazonRating: metadata.amazonRating ?? null,
|
||||
amazonReviewCount: metadata.amazonReviewCount ?? null,
|
||||
goodreadsId: metadata.goodreadsId ?? null,
|
||||
comicvineId: metadata.comicvineId ?? null,
|
||||
goodreadsRating: metadata.goodreadsRating ?? null,
|
||||
goodreadsReviewCount: metadata.goodreadsReviewCount ?? null,
|
||||
hardcoverId: metadata.hardcoverId ?? null,
|
||||
hardcoverBookId: metadata.hardcoverBookId ?? null,
|
||||
hardcoverRating: metadata.hardcoverRating ?? null,
|
||||
hardcoverReviewCount: metadata.hardcoverReviewCount ?? null,
|
||||
lubimyczytacId: metadata.lubimyczytacId ?? null,
|
||||
lubimyczytacRating: metadata.lubimyczytacRating ?? null,
|
||||
ranobedbId: metadata.ranobedbId ?? null,
|
||||
ranobedbRating: metadata.ranobedbRating ?? null,
|
||||
googleId: metadata.googleId ?? null,
|
||||
audibleId: metadata.audibleId ?? null,
|
||||
audibleRating: metadata.audibleRating ?? null,
|
||||
audibleReviewCount: metadata.audibleReviewCount ?? null,
|
||||
applebooksId: metadata.applebooksId ?? null,
|
||||
applebooksRating: metadata.applebooksRating ?? null,
|
||||
applebooksReviewCount: metadata.applebooksReviewCount ?? null,
|
||||
seriesName: metadata.seriesName ?? null,
|
||||
seriesNumber: metadata.seriesNumber ?? null,
|
||||
seriesTotal: metadata.seriesTotal ?? null,
|
||||
@@ -466,29 +382,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
descriptionLocked: metadata.descriptionLocked ?? false,
|
||||
pageCountLocked: metadata.pageCountLocked ?? false,
|
||||
languageLocked: metadata.languageLocked ?? false,
|
||||
openlibraryIdLocked: metadata.openlibraryIdLocked ?? false,
|
||||
asinLocked: metadata.asinLocked ?? false,
|
||||
amazonRatingLocked: metadata.amazonRatingLocked ?? false,
|
||||
amazonReviewCountLocked: metadata.amazonReviewCountLocked ?? false,
|
||||
goodreadsIdLocked: metadata.goodreadsIdLocked ?? false,
|
||||
comicvineIdLocked: metadata.comicvineIdLocked ?? false,
|
||||
goodreadsRatingLocked: metadata.goodreadsRatingLocked ?? false,
|
||||
goodreadsReviewCountLocked: metadata.goodreadsReviewCountLocked ?? false,
|
||||
hardcoverIdLocked: metadata.hardcoverIdLocked ?? false,
|
||||
hardcoverBookIdLocked: metadata.hardcoverBookIdLocked ?? false,
|
||||
hardcoverRatingLocked: metadata.hardcoverRatingLocked ?? false,
|
||||
hardcoverReviewCountLocked: metadata.hardcoverReviewCountLocked ?? false,
|
||||
lubimyczytacIdLocked: metadata.lubimyczytacIdLocked ?? false,
|
||||
lubimyczytacRatingLocked: metadata.lubimyczytacRatingLocked ?? false,
|
||||
ranobedbIdLocked: metadata.ranobedbIdLocked ?? false,
|
||||
ranobedbRatingLocked: metadata.ranobedbRatingLocked ?? false,
|
||||
googleIdLocked: metadata.googleIdLocked ?? false,
|
||||
audibleIdLocked: metadata.audibleIdLocked ?? false,
|
||||
audibleRatingLocked: metadata.audibleRatingLocked ?? false,
|
||||
audibleReviewCountLocked: metadata.audibleReviewCountLocked ?? false,
|
||||
applebooksIdLocked: metadata.applebooksIdLocked ?? false,
|
||||
applebooksRatingLocked: metadata.applebooksRatingLocked ?? false,
|
||||
applebooksReviewCountLocked: metadata.applebooksReviewCountLocked ?? false,
|
||||
seriesNameLocked: metadata.seriesNameLocked ?? false,
|
||||
seriesNumberLocked: metadata.seriesNumberLocked ?? false,
|
||||
seriesTotalLocked: metadata.seriesTotalLocked ?? false,
|
||||
@@ -501,6 +394,13 @@ export class MetadataEditorComponent implements OnInit {
|
||||
contentRatingLocked: metadata.contentRatingLocked ?? false,
|
||||
});
|
||||
|
||||
const providerPatch: Record<string, string | number | boolean | null> = {};
|
||||
for (const field of this.providerFields.fields()) {
|
||||
providerPatch[field.name] = metadata[field.name] ?? null;
|
||||
providerPatch[field.lockName] = metadata[field.lockName] ?? false;
|
||||
}
|
||||
this.metadataForm.patchValue(providerPatch);
|
||||
|
||||
// Patch audiobook metadata
|
||||
const audiobookPatch: Record<string, unknown> = {};
|
||||
for (const field of AUDIOBOOK_METADATA_FIELDS) {
|
||||
@@ -540,30 +440,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
{key: "languageLocked", control: "language"},
|
||||
{key: "isbn10Locked", control: "isbn10"},
|
||||
{key: "isbn13Locked", control: "isbn13"},
|
||||
{key: "openlibraryIdLocked", control: "openlibraryId"},
|
||||
{key: "asinLocked", control: "asin"},
|
||||
{key: "amazonReviewCountLocked", control: "amazonReviewCount"},
|
||||
{key: "amazonRatingLocked", control: "amazonRating"},
|
||||
{key: "goodreadsIdLocked", control: "goodreadsId"},
|
||||
{key: "comicvineIdLocked", control: "comicvineId"},
|
||||
{key: "goodreadsReviewCountLocked", control: "goodreadsReviewCount"},
|
||||
{key: "goodreadsRatingLocked", control: "goodreadsRating"},
|
||||
{key: "hardcoverIdLocked", control: "hardcoverId"},
|
||||
{key: "hardcoverBookIdLocked", control: "hardcoverBookId"},
|
||||
{key: "hardcoverReviewCountLocked", control: "hardcoverReviewCount"},
|
||||
{key: "hardcoverRatingLocked", control: "hardcoverRating"},
|
||||
{key: "lubimyczytacIdLocked", control: "lubimyczytacId"},
|
||||
{key: "lubimyczytacRatingLocked", control: "lubimyczytacRating"},
|
||||
{key: "ranobedbReviewCountLocked", control: "ranobedbReviewCount"},
|
||||
{key: "ranobedbIdLocked", control: "ranobedbId"},
|
||||
{key: "ranobedbRatingLocked", control: "ranobedbRating"},
|
||||
{key: "googleIdLocked", control: "googleId"},
|
||||
{key: "audibleIdLocked", control: "audibleId"},
|
||||
{key: "audibleRatingLocked", control: "audibleRating"},
|
||||
{key: "audibleReviewCountLocked", control: "audibleReviewCount"},
|
||||
{key: "applebooksIdLocked", control: "applebooksId"},
|
||||
{key: "applebooksRatingLocked", control: "applebooksRating"},
|
||||
{key: "applebooksReviewCountLocked", control: "applebooksReviewCount"},
|
||||
...this.providerFields.fields().map(field => ({key: field.lockName, control: field.name})),
|
||||
{key: "pageCountLocked", control: "pageCount"},
|
||||
{key: "descriptionLocked", control: "description"},
|
||||
{key: "seriesNameLocked", control: "seriesName"},
|
||||
@@ -735,29 +612,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
pageCount: form.get("pageCount")?.value,
|
||||
rating: form.get("rating")?.value,
|
||||
reviewCount: form.get("reviewCount")?.value,
|
||||
openlibraryId: form.get("openlibraryId")?.value,
|
||||
asin: form.get("asin")?.value,
|
||||
amazonRating: form.get("amazonRating")?.value,
|
||||
amazonReviewCount: form.get("amazonReviewCount")?.value,
|
||||
goodreadsId: form.get("goodreadsId")?.value,
|
||||
comicvineId: form.get("comicvineId")?.value,
|
||||
goodreadsRating: form.get("goodreadsRating")?.value,
|
||||
goodreadsReviewCount: form.get("goodreadsReviewCount")?.value,
|
||||
hardcoverId: form.get("hardcoverId")?.value,
|
||||
hardcoverBookId: form.get("hardcoverBookId")?.value,
|
||||
hardcoverRating: form.get("hardcoverRating")?.value,
|
||||
hardcoverReviewCount: form.get("hardcoverReviewCount")?.value,
|
||||
lubimyczytacId: form.get("lubimyczytacId")?.value,
|
||||
lubimyczytacRating: form.get("lubimyczytacRating")?.value,
|
||||
ranobedbId: form.get("ranobedbId")?.value,
|
||||
ranobedbRating: form.get("ranobedbRating")?.value,
|
||||
googleId: form.get("googleId")?.value,
|
||||
audibleId: form.get("audibleId")?.value,
|
||||
audibleRating: form.get("audibleRating")?.value,
|
||||
audibleReviewCount: form.get("audibleReviewCount")?.value,
|
||||
applebooksId: form.get("applebooksId")?.value,
|
||||
applebooksRating: form.get("applebooksRating")?.value,
|
||||
applebooksReviewCount: form.get("applebooksReviewCount")?.value,
|
||||
language: form.get("language")?.value,
|
||||
seriesName: form.get("seriesName")?.value,
|
||||
seriesNumber: form.get("seriesNumber")?.value,
|
||||
@@ -785,29 +639,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
descriptionLocked: form.get("descriptionLocked")?.value,
|
||||
pageCountLocked: form.get("pageCountLocked")?.value,
|
||||
languageLocked: form.get("languageLocked")?.value,
|
||||
openlibraryIdLocked: form.get("openlibraryIdLocked")?.value,
|
||||
asinLocked: form.get("asinLocked")?.value,
|
||||
amazonRatingLocked: form.get("amazonRatingLocked")?.value,
|
||||
amazonReviewCountLocked: form.get("amazonReviewCountLocked")?.value,
|
||||
goodreadsIdLocked: form.get("goodreadsIdLocked")?.value,
|
||||
comicvineIdLocked: form.get("comicvineIdLocked")?.value,
|
||||
goodreadsRatingLocked: form.get("goodreadsRatingLocked")?.value,
|
||||
goodreadsReviewCountLocked: form.get("goodreadsReviewCountLocked")?.value,
|
||||
hardcoverIdLocked: form.get("hardcoverIdLocked")?.value,
|
||||
hardcoverBookIdLocked: form.get("hardcoverBookIdLocked")?.value,
|
||||
hardcoverRatingLocked: form.get("hardcoverRatingLocked")?.value,
|
||||
hardcoverReviewCountLocked: form.get("hardcoverReviewCountLocked")?.value,
|
||||
lubimyczytacIdLocked: form.get("lubimyczytacIdLocked")?.value,
|
||||
lubimyczytacRatingLocked: form.get("lubimyczytacRatingLocked")?.value,
|
||||
ranobedbIdLocked: form.get("ranobedbIdLocked")?.value,
|
||||
ranobedbRatingLocked: form.get("ranobedbRatingLocked")?.value,
|
||||
googleIdLocked: form.get("googleIdLocked")?.value,
|
||||
audibleIdLocked: form.get("audibleIdLocked")?.value,
|
||||
audibleRatingLocked: form.get("audibleRatingLocked")?.value,
|
||||
audibleReviewCountLocked: form.get("audibleReviewCountLocked")?.value,
|
||||
applebooksIdLocked: form.get("applebooksIdLocked")?.value,
|
||||
applebooksRatingLocked: form.get("applebooksRatingLocked")?.value,
|
||||
applebooksReviewCountLocked: form.get("applebooksReviewCountLocked")?.value,
|
||||
seriesNameLocked: form.get("seriesNameLocked")?.value,
|
||||
seriesNumberLocked: form.get("seriesNumberLocked")?.value,
|
||||
seriesTotalLocked: form.get("seriesTotalLocked")?.value,
|
||||
@@ -824,6 +655,11 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}),
|
||||
};
|
||||
|
||||
for (const field of this.providerFields.fields()) {
|
||||
metadata[field.name] = form.get(field.name)?.value;
|
||||
metadata[field.lockName] = form.get(field.lockName)?.value;
|
||||
}
|
||||
|
||||
// Build comic metadata from form controls
|
||||
const comicMetadata: Record<string, unknown> = {};
|
||||
for (const field of ALL_COMIC_METADATA_FIELDS) {
|
||||
@@ -879,29 +715,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
description: wasCleared("description"),
|
||||
pageCount: wasCleared("pageCount"),
|
||||
language: wasCleared("language"),
|
||||
openlibraryId: wasCleared("openlibraryId"),
|
||||
asin: wasCleared("asin"),
|
||||
amazonRating: wasCleared("amazonRating"),
|
||||
amazonReviewCount: wasCleared("amazonReviewCount"),
|
||||
goodreadsId: wasCleared("goodreadsId"),
|
||||
comicvineId: wasCleared("comicvineId"),
|
||||
goodreadsRating: wasCleared("goodreadsRating"),
|
||||
goodreadsReviewCount: wasCleared("goodreadsReviewCount"),
|
||||
hardcoverId: wasCleared("hardcoverId"),
|
||||
hardcoverRating: wasCleared("hardcoverRating"),
|
||||
hardcoverReviewCount: wasCleared("hardcoverReviewCount"),
|
||||
hardcoverBookId: wasCleared("hardcoverBookId"),
|
||||
lubimyczytacId: wasCleared("lubimyczytacId"),
|
||||
lubimyczytacRating: wasCleared("lubimyczytacRating"),
|
||||
ranobedbId: wasCleared("ranobedbId"),
|
||||
ranobedbRating: wasCleared("ranobedbRating"),
|
||||
googleId: wasCleared("googleId"),
|
||||
audibleId: wasCleared("audibleId"),
|
||||
audibleRating: wasCleared("audibleRating"),
|
||||
audibleReviewCount: wasCleared("audibleReviewCount"),
|
||||
applebooksId: wasCleared("applebooksId"),
|
||||
applebooksRating: wasCleared("applebooksRating"),
|
||||
applebooksReviewCount: wasCleared("applebooksReviewCount"),
|
||||
seriesName: wasCleared("seriesName"),
|
||||
seriesNumber: wasCleared("seriesNumber"),
|
||||
seriesTotal: wasCleared("seriesTotal"),
|
||||
@@ -913,6 +726,10 @@ export class MetadataEditorComponent implements OnInit {
|
||||
contentRating: wasCleared("contentRating"),
|
||||
};
|
||||
|
||||
for (const field of this.providerFields.fields()) {
|
||||
clearFlags[field.name] = wasCleared(field.name);
|
||||
}
|
||||
|
||||
return {metadata, clearFlags};
|
||||
}
|
||||
|
||||
@@ -1101,29 +918,26 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}, 15000);
|
||||
}
|
||||
|
||||
fetchFromFile(bookId: number) {
|
||||
async fetchFromFile(bookId: number): Promise<void> {
|
||||
this.isFetchingFromFile = true;
|
||||
this.bookMetadataManageService.getFileMetadata(bookId).pipe(
|
||||
finalize(() => this.isFetchingFromFile = false),
|
||||
takeUntilDestroyed(this.destroyRef)
|
||||
).subscribe({
|
||||
next: (metadata) => {
|
||||
this.populateFormFromMetadata(metadata);
|
||||
this.metadataForm.markAsDirty();
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||
detail: this.t.translate('metadata.editor.toast.fileMetadataLoaded'),
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('metadata.editor.toast.errorSummary'),
|
||||
detail: err?.error?.message || this.t.translate('metadata.editor.toast.fileMetadataFailed'),
|
||||
});
|
||||
}
|
||||
});
|
||||
try {
|
||||
this.populateFormFromMetadata(await this.queryClient.query(this.sources.fileMetadata(bookId)));
|
||||
this.metadataForm.markAsDirty();
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('metadata.editor.toast.successSummary'),
|
||||
detail: this.t.translate('metadata.editor.toast.fileMetadataLoaded'),
|
||||
});
|
||||
} catch (err) {
|
||||
const message: unknown = err instanceof HttpErrorResponse ? err.error?.message : null;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('metadata.editor.toast.errorSummary'),
|
||||
detail: typeof message === 'string' ? message : this.t.translate('metadata.editor.toast.fileMetadataFailed'),
|
||||
});
|
||||
} finally {
|
||||
this.isFetchingFromFile = false;
|
||||
}
|
||||
}
|
||||
|
||||
onNext() {
|
||||
@@ -1189,7 +1003,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}
|
||||
|
||||
isFieldVisible(field: keyof MetadataProviderSpecificFields): boolean {
|
||||
return this.providerSpecificFields[field] ?? false;
|
||||
return this.providerSpecificFields()[field];
|
||||
}
|
||||
|
||||
protected readonly sample = sample;
|
||||
@@ -1225,7 +1039,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}
|
||||
|
||||
isEmbeddable(controlName: string, book: Book): boolean {
|
||||
return isFieldEmbeddable(book.primaryFile?.bookType, controlName);
|
||||
return isFieldEmbeddable(book.primaryFile?.bookType, controlName, this.providerFieldNames());
|
||||
}
|
||||
|
||||
hasWriter(book: Book): boolean {
|
||||
|
||||
+3
-10
@@ -1,13 +1,6 @@
|
||||
@if (book; as book) {
|
||||
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="metadata-picker" *transloco="let t; prefix: 'metadata.picker'">
|
||||
<div class="dialog-body">
|
||||
@if (detailLoading) {
|
||||
<div class="detail-loading-banner">
|
||||
<i class="pi pi-spin pi-spinner"></i>
|
||||
<span>{{ t('loadingMetadata') }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Column Headers -->
|
||||
<div class="column-headers">
|
||||
<div class="column-label current">
|
||||
@@ -716,7 +709,7 @@
|
||||
}
|
||||
|
||||
<!-- Provider Metadata Section -->
|
||||
@if (metadataProviderFields.length > 0) {
|
||||
@if (metadataProviderFields().length > 0) {
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-cloud"></i>
|
||||
@@ -724,9 +717,9 @@
|
||||
</div>
|
||||
|
||||
<div class="section-content">
|
||||
@for (field of metadataProviderFields; track field) {
|
||||
@for (field of metadataProviderFields(); track field) {
|
||||
<div class="field-row">
|
||||
<span class="field-label">{{ field.label }}</span>
|
||||
<span class="field-label">{{ providerFields.label(field.providerKey!) }}</span>
|
||||
<div class="field-content">
|
||||
<div class="field-side current">
|
||||
<button
|
||||
|
||||
+1
-21
@@ -25,26 +25,6 @@
|
||||
}
|
||||
|
||||
|
||||
// Detail loading banner
|
||||
.detail-loading-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4375rem;
|
||||
padding: 0.5469rem 0.875rem;
|
||||
background: rgb(34 197 94 / 10%);
|
||||
border: 1px solid rgb(34 197 94 / 30%);
|
||||
border-radius: 8px;
|
||||
color: var(--p-green-400);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 600;
|
||||
animation: fade-in 0.3s ease-in;
|
||||
|
||||
i {
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
}
|
||||
|
||||
// Body
|
||||
.dialog-body {
|
||||
flex: 1;
|
||||
@@ -374,7 +354,7 @@
|
||||
min-width: 100px;
|
||||
|
||||
@media (width >= 768px) {
|
||||
min-width: 120px;
|
||||
width: 120px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
+72
-46
@@ -3,7 +3,6 @@ import {TestBed} from '@angular/core/testing';
|
||||
import {of} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {CdkDragDrop} from '@angular/cdk/drag-drop';
|
||||
import {AutoCompleteSelectEvent} from '@openng/optimus-ui/autocomplete';
|
||||
|
||||
@@ -15,6 +14,7 @@ import {AppSettingsService} from '../../../../../shared/service/app-settings.ser
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {MetadataFormBuilder} from '../../../../../shared/metadata';
|
||||
import {MetadataUtilsService} from '../../../../../shared/metadata/metadata-utils.service';
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {MetadataPickerComponent} from './metadata-picker.component';
|
||||
|
||||
describe('MetadataPickerComponent', () => {
|
||||
@@ -31,7 +31,6 @@ describe('MetadataPickerComponent', () => {
|
||||
const uploadAudiobookCoverFromUrl = vi.fn(() => of(void 0));
|
||||
const supportsDualCovers = vi.fn(() => true);
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string, params?: Record<string, unknown>) => params?.['field'] ? `${key}:${params['field']}` : key);
|
||||
const getThumbnailUrl = vi.fn((bookId: number, updatedOn?: string) => `thumb:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `cover:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getAudiobookCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `audio-cover:${bookId}:${updatedOn ?? 'none'}`);
|
||||
@@ -44,7 +43,7 @@ describe('MetadataPickerComponent', () => {
|
||||
authors: ['Alice'],
|
||||
categories: ['Fantasy'],
|
||||
description: 'Original description',
|
||||
provider: 'googleBooks',
|
||||
provider: 'Google',
|
||||
coverUpdatedOn: '2026-03-26',
|
||||
titleLocked: true,
|
||||
comicMetadata: {
|
||||
@@ -68,7 +67,7 @@ describe('MetadataPickerComponent', () => {
|
||||
} as Book;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
uniqueMetadata.set({
|
||||
authors: ['Alice', 'Bob'],
|
||||
categories: ['Fantasy', 'History'],
|
||||
@@ -82,12 +81,12 @@ describe('MetadataPickerComponent', () => {
|
||||
uploadAudiobookCoverFromUrl.mockClear();
|
||||
supportsDualCovers.mockClear();
|
||||
messageAdd.mockClear();
|
||||
translate.mockClear();
|
||||
getThumbnailUrl.mockClear();
|
||||
getCoverUrl.mockClear();
|
||||
getAudiobookCoverUrl.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [getTranslocoModule({preloadLangs: true})],
|
||||
providers: [
|
||||
MetadataFormBuilder,
|
||||
MetadataUtilsService,
|
||||
@@ -102,9 +101,8 @@ describe('MetadataPickerComponent', () => {
|
||||
useValue: {getThumbnailUrl, getCoverUrl, getAudiobookCoverUrl},
|
||||
},
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
});
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
it('syncs provider field visibility from app settings and filters metadata suggestions', () => {
|
||||
@@ -119,9 +117,9 @@ describe('MetadataPickerComponent', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.metadataProviderFields.map(field => field.controlName)).toContain('googleId');
|
||||
expect(component.metadataProviderFields.map(field => field.controlName)).toContain('audibleId');
|
||||
expect(component.metadataProviderFields.map(field => field.controlName)).not.toContain('amazonRating');
|
||||
expect(component.metadataProviderFields().map(field => field.controlName)).toContain('googleId');
|
||||
expect(component.metadataProviderFields().map(field => field.controlName)).toContain('audibleId');
|
||||
expect(component.metadataProviderFields().map(field => field.controlName)).not.toContain('amazonRating');
|
||||
|
||||
component.filterItems({query: 'fan'}, 'categories');
|
||||
expect(component.getFiltered('categories')).toEqual(['Fantasy']);
|
||||
@@ -134,7 +132,7 @@ describe('MetadataPickerComponent', () => {
|
||||
component.copiedFields = {title: true};
|
||||
component.savedFields = {title: true};
|
||||
component.hoveredFields = {title: true};
|
||||
component.fetchedMetadata = createMetadata({provider: 'comicvine'});
|
||||
component.fetchedMetadata = createMetadata({provider: 'Comicvine'});
|
||||
|
||||
component.book = createBook();
|
||||
|
||||
@@ -151,6 +149,7 @@ describe('MetadataPickerComponent', () => {
|
||||
|
||||
it('handles author and array autocomplete helpers without duplicating values', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.fetchedMetadata = createMetadata();
|
||||
component.book = createBook();
|
||||
component.metadataForm.get('authors')?.setValue(['Alice', 'Bob']);
|
||||
|
||||
@@ -179,19 +178,19 @@ describe('MetadataPickerComponent', () => {
|
||||
|
||||
it('copies fetched values, respects locked fields, and resets fields back to the original metadata', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.book = createBook();
|
||||
component.fetchedMetadata = createMetadata({
|
||||
title: 'Fetched Title',
|
||||
provider: 'Audible',
|
||||
thumbnailUrl: 'https://covers.example/audiobook.jpg',
|
||||
comicMetadata: {issueNumber: '7'},
|
||||
});
|
||||
component.book = createBook();
|
||||
|
||||
component.copyFetchedToCurrent('title');
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'metadata.picker.toast.actionBlockedSummary',
|
||||
detail: 'metadata.picker.toast.fieldLockedDetail:title',
|
||||
summary: 'Action Blocked',
|
||||
detail: 'title is locked and cannot be updated.',
|
||||
});
|
||||
|
||||
component.metadataForm.get('titleLocked')?.setValue(false);
|
||||
@@ -208,8 +207,8 @@ describe('MetadataPickerComponent', () => {
|
||||
component.copyFetchedToCurrent('comicIssueNumber');
|
||||
expect(messageAdd).toHaveBeenLastCalledWith({
|
||||
severity: 'warn',
|
||||
summary: 'metadata.picker.toast.actionBlockedSummary',
|
||||
detail: 'metadata.picker.toast.fieldLockedDetail:Issue #',
|
||||
summary: 'Action Blocked',
|
||||
detail: 'Issue # is locked and cannot be updated.',
|
||||
});
|
||||
|
||||
component.resetField('title');
|
||||
@@ -217,14 +216,11 @@ describe('MetadataPickerComponent', () => {
|
||||
expect(component.isValueCopied('title')).toBe(false);
|
||||
});
|
||||
|
||||
it('saves metadata, uploads audible covers when needed, and toggles lock states', () => {
|
||||
it('saves metadata and marks copied fields as saved', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.fetchedMetadata = createMetadata({
|
||||
provider: 'Audible',
|
||||
thumbnailUrl: 'https://covers.example/audiobook.jpg',
|
||||
});
|
||||
component.fetchedMetadata = createMetadata();
|
||||
component.book = createBook();
|
||||
component.copiedFields = {title: true, audiobookThumbnailUrl: true};
|
||||
component.copiedFields = {title: true};
|
||||
component.metadataForm.get('titleLocked')?.setValue(false);
|
||||
component.metadataForm.get('title')?.enable();
|
||||
component.metadataForm.get('title')?.setValue('Updated Title');
|
||||
@@ -235,15 +231,34 @@ describe('MetadataPickerComponent', () => {
|
||||
metadata: expect.objectContaining({title: 'Updated Title'}),
|
||||
clearFlags: expect.any(Object),
|
||||
}), false, 'REPLACE_WHEN_PROVIDED');
|
||||
expect(uploadAudiobookCoverFromUrl).toHaveBeenCalledWith(21, 'https://covers.example/audiobook.jpg');
|
||||
expect(component.isSaving).toBe(false);
|
||||
expect(component.isValueSaved('title')).toBe(true);
|
||||
expect(component.isValueSaved('audiobookThumbnailUrl')).toBe(true);
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'metadata.picker.toast.successSummary',
|
||||
detail: 'metadata.picker.toast.metadataUpdated',
|
||||
summary: 'Success',
|
||||
detail: 'Book metadata updated',
|
||||
});
|
||||
});
|
||||
|
||||
it('uploads an Audible cover when its fetched cover was copied', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.fetchedMetadata = createMetadata({
|
||||
provider: 'Audible',
|
||||
thumbnailUrl: 'https://covers.example/audiobook.jpg',
|
||||
});
|
||||
component.book = createBook();
|
||||
component.copiedFields = {audiobookThumbnailUrl: true};
|
||||
|
||||
component.onSave();
|
||||
|
||||
expect(uploadAudiobookCoverFromUrl).toHaveBeenCalledWith(21, 'https://covers.example/audiobook.jpg');
|
||||
expect(component.isValueSaved('audiobookThumbnailUrl')).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles individual and all lock states', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.fetchedMetadata = createMetadata();
|
||||
component.book = createBook();
|
||||
|
||||
component.toggleLock('thumbnailUrl');
|
||||
expect(component.metadataForm.get('coverLocked')?.value).toBe(true);
|
||||
@@ -252,24 +267,11 @@ describe('MetadataPickerComponent', () => {
|
||||
component.lockAll();
|
||||
component.unlockAll();
|
||||
|
||||
expect(updateBookMetadata).toHaveBeenCalledTimes(4);
|
||||
expect(updateBookMetadata).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('covers hover state, back navigation, dual-cover helpers, and comic visibility helpers', () => {
|
||||
it('tracks hover state for copied fields that are not saved', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
const goBackEmit = vi.spyOn(component.goBack, 'emit');
|
||||
const book = createBook({}, {
|
||||
isPhysical: true,
|
||||
primaryFile: undefined,
|
||||
alternativeFormats: [{id: 2, bookId: 21, bookType: 'AUDIOBOOK'}],
|
||||
});
|
||||
|
||||
component.fetchedMetadata = createMetadata({
|
||||
provider: 'comicvine',
|
||||
narrator: 'Narrator',
|
||||
comicMetadata: {issueNumber: '7'},
|
||||
});
|
||||
component.book = book;
|
||||
component.copiedFields = {title: true};
|
||||
component.savedFields = {title: false};
|
||||
|
||||
@@ -278,19 +280,43 @@ describe('MetadataPickerComponent', () => {
|
||||
|
||||
component.onMouseLeave('title');
|
||||
expect(component.hoveredFields['title']).toBe(false);
|
||||
});
|
||||
|
||||
it('emits when navigating back', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
const goBackEmit = vi.spyOn(component.goBack, 'emit');
|
||||
|
||||
component.goBackClick();
|
||||
|
||||
expect(goBackEmit).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('reports audiobook provider values and dual-cover support', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
const book = createBook({}, {
|
||||
isPhysical: true,
|
||||
primaryFile: undefined,
|
||||
alternativeFormats: [{id: 2, bookId: 21, bookType: 'AUDIOBOOK'}],
|
||||
});
|
||||
component.fetchedMetadata = createMetadata({provider: 'Comicvine'});
|
||||
|
||||
expect(component.isAudibleProvider()).toBe(false);
|
||||
component.fetchedMetadata = createMetadata({provider: 'Audible', narrator: 'Narrator', comicMetadata: {issueNumber: '7'}});
|
||||
component.fetchedMetadata = createMetadata({provider: 'Audible', narrator: 'Narrator'});
|
||||
expect(component.isAudibleProvider()).toBe(true);
|
||||
expect(component.getFetchedAudiobookValue('narrator')).toBe('Narrator');
|
||||
expect(component.getFetchedComicValue('issueNumber')).toBe('7');
|
||||
|
||||
expect(component.hasEbookFormat(book)).toBe(true);
|
||||
expect(component.hasAudiobookFormat(book)).toBe(true);
|
||||
expect(component.supportsDualCovers(book)).toBe(true);
|
||||
});
|
||||
|
||||
it('reports fetched and current comic data and section visibility', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new MetadataPickerComponent());
|
||||
component.fetchedMetadata = createMetadata({
|
||||
provider: 'Comicvine',
|
||||
comicMetadata: {issueNumber: '7'},
|
||||
});
|
||||
component.book = createBook();
|
||||
|
||||
expect(component.getFetchedComicValue('issueNumber')).toBe('7');
|
||||
expect(component.hasAnyFetchedComicData()).toBe(true);
|
||||
expect(component.hasAnyCurrentComicData()).toBe(true);
|
||||
expect(component.shouldShowComicSection()).toBe(true);
|
||||
|
||||
+13
-25
@@ -1,4 +1,4 @@
|
||||
import {Component, computed, DestroyRef, effect, EventEmitter, inject, Input, Output} from '@angular/core';
|
||||
import {Component, computed, DestroyRef, effect, EventEmitter, inject, Input, Output, signal} from '@angular/core';
|
||||
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../../book/model/book.model';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
@@ -18,7 +18,7 @@ import {Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import {LazyLoadImageModule} from 'ng-lazyload-image';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-settings.model';
|
||||
import {ALL_COMIC_METADATA_FIELDS, ALL_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, COMIC_ARRAY_METADATA_FIELDS, COMIC_FORM_TO_MODEL_LOCK, COMIC_TEXT_METADATA_FIELDS, COMIC_TEXTAREA_METADATA_FIELDS, getArrayFields, getBookDetailsFields, getBottomFields, getProviderFields, getSeriesFields, getTextareaFields, getTopFields, MetadataFieldConfig, MetadataFormBuilder, MetadataUtilsService} from '../../../../../shared/metadata';
|
||||
import {ALL_COMIC_METADATA_FIELDS, allMetadataFields, AUDIOBOOK_METADATA_FIELDS, COMIC_ARRAY_METADATA_FIELDS, COMIC_FORM_TO_MODEL_LOCK, COMIC_TEXT_METADATA_FIELDS, COMIC_TEXTAREA_METADATA_FIELDS, getArrayFields, getBookDetailsFields, getProviderFields, getSeriesFields, getTextareaFields, getTopFields, MetadataFieldConfig, MetadataProviderFieldsService, MetadataFormBuilder, MetadataUtilsService} from '../../../../../shared/metadata';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
@@ -50,8 +50,6 @@ export class MetadataPickerComponent {
|
||||
metadataDescription: MetadataFieldConfig[] = [];
|
||||
metadataSeriesFields: MetadataFieldConfig[] = [];
|
||||
metadataBookDetailsFields: MetadataFieldConfig[] = [];
|
||||
metadataProviderFields: MetadataFieldConfig[] = [];
|
||||
metadataFieldsBottom: MetadataFieldConfig[] = [];
|
||||
audiobookMetadataFields: MetadataFieldConfig[] = [];
|
||||
comicTextFields: MetadataFieldConfig[] = [];
|
||||
comicArrayFields: MetadataFieldConfig[] = [];
|
||||
@@ -84,7 +82,6 @@ export class MetadataPickerComponent {
|
||||
return this.currentBook;
|
||||
}
|
||||
|
||||
@Input() detailLoading = false;
|
||||
@Output() goBack = new EventEmitter<boolean>();
|
||||
|
||||
currentBook: Book | null = null;
|
||||
@@ -110,13 +107,16 @@ export class MetadataPickerComponent {
|
||||
private formBuilder = inject(MetadataFormBuilder);
|
||||
private metadataUtils = inject(MetadataUtilsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
protected readonly providerFields = inject(MetadataProviderFieldsService);
|
||||
private readonly uniqueMetadata = computed(() => this.bookService.uniqueMetadata());
|
||||
|
||||
|
||||
private enabledProviderFields: MetadataProviderSpecificFields | null = null;
|
||||
private readonly enabledProviderFields = signal<MetadataProviderSpecificFields | null>(null);
|
||||
private readonly allFields = computed(() => allMetadataFields(this.providerFields.fields()));
|
||||
readonly metadataProviderFields = computed(() => getProviderFields(this.allFields(), this.enabledProviderFields()));
|
||||
|
||||
constructor() {
|
||||
this.metadataForm = this.formBuilder.buildForm(true);
|
||||
this.metadataForm = this.formBuilder.buildForm(true, this.allFields());
|
||||
this.initFieldArrays();
|
||||
}
|
||||
|
||||
@@ -126,22 +126,12 @@ export class MetadataPickerComponent {
|
||||
this.metadataDescription = getTextareaFields();
|
||||
this.metadataSeriesFields = getSeriesFields();
|
||||
this.metadataBookDetailsFields = getBookDetailsFields();
|
||||
this.updateProviderFields();
|
||||
this.updateBottomFields();
|
||||
this.audiobookMetadataFields = AUDIOBOOK_METADATA_FIELDS;
|
||||
this.comicTextFields = COMIC_TEXT_METADATA_FIELDS;
|
||||
this.comicArrayFields = COMIC_ARRAY_METADATA_FIELDS;
|
||||
this.comicTextareaFields = COMIC_TEXTAREA_METADATA_FIELDS;
|
||||
}
|
||||
|
||||
private updateProviderFields(): void {
|
||||
this.metadataProviderFields = getProviderFields(this.enabledProviderFields);
|
||||
}
|
||||
|
||||
private updateBottomFields(): void {
|
||||
this.metadataFieldsBottom = getBottomFields(this.enabledProviderFields);
|
||||
}
|
||||
|
||||
getFiltered(controlName: string): string[] {
|
||||
return this.filteredItems[controlName] ?? [];
|
||||
}
|
||||
@@ -155,9 +145,7 @@ export class MetadataPickerComponent {
|
||||
private readonly syncProviderFieldsEffect = effect(() => {
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
if (settings?.metadataProviderSpecificFields) {
|
||||
this.enabledProviderFields = settings.metadataProviderSpecificFields;
|
||||
this.updateProviderFields();
|
||||
this.updateBottomFields();
|
||||
this.enabledProviderFields.set(settings.metadataProviderSpecificFields);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -165,7 +153,7 @@ export class MetadataPickerComponent {
|
||||
void book;
|
||||
const patchData: Record<string, unknown> = {};
|
||||
|
||||
for (const field of ALL_METADATA_FIELDS) {
|
||||
for (const field of this.allFields()) {
|
||||
const key = field.controlName as keyof BookMetadata;
|
||||
const lockedKey = field.lockedKey as keyof BookMetadata;
|
||||
const value = metadata[key];
|
||||
@@ -222,7 +210,7 @@ export class MetadataPickerComponent {
|
||||
|
||||
private applyLockStates(metadata: BookMetadata): void {
|
||||
const lockedFields: Record<string, boolean> = {};
|
||||
for (const field of ALL_METADATA_FIELDS) {
|
||||
for (const field of this.allFields()) {
|
||||
lockedFields[field.lockedKey] = !!metadata[field.lockedKey as keyof BookMetadata];
|
||||
}
|
||||
// Also handle audiobook metadata lock states (now at top-level of BookMetadata)
|
||||
@@ -235,7 +223,7 @@ export class MetadataPickerComponent {
|
||||
const modelLockKey = COMIC_FORM_TO_MODEL_LOCK[field.lockedKey];
|
||||
lockedFields[field.lockedKey] = !!comicMeta?.[modelLockKey as keyof ComicMetadata];
|
||||
}
|
||||
this.formBuilder.applyLockStates(this.metadataForm, lockedFields);
|
||||
this.formBuilder.applyLockStates(this.metadataForm, lockedFields, this.allFields());
|
||||
}
|
||||
|
||||
onAutoCompleteSelect(fieldName: string, event: AutoCompleteSelectEvent) {
|
||||
@@ -349,7 +337,7 @@ export class MetadataPickerComponent {
|
||||
private buildMetadataFromForm(): BookMetadata {
|
||||
const metadata: Record<string, unknown> = {bookId: this.currentBookId};
|
||||
|
||||
for (const field of ALL_METADATA_FIELDS) {
|
||||
for (const field of this.allFields()) {
|
||||
if (field.type === 'array') {
|
||||
metadata[field.controlName] = this.getArrayValue(field.controlName);
|
||||
} else if (field.type === 'number') {
|
||||
@@ -460,7 +448,7 @@ export class MetadataPickerComponent {
|
||||
private inferClearFlags(current: BookMetadata, original: BookMetadata): MetadataClearFlags {
|
||||
const flags: Record<string, boolean> = {};
|
||||
|
||||
for (const field of ALL_METADATA_FIELDS) {
|
||||
for (const field of this.allFields()) {
|
||||
const key = field.controlName as keyof BookMetadata;
|
||||
const curr = current[key];
|
||||
const orig = original[key];
|
||||
|
||||
+33
-35
@@ -3,7 +3,6 @@
|
||||
<app-metadata-picker
|
||||
[fetchedMetadata]="selectedMetadata"
|
||||
[book]="book()"
|
||||
[detailLoading]="detailLoading()"
|
||||
(goBack)="onGoBack()">
|
||||
</app-metadata-picker>
|
||||
</div>
|
||||
@@ -20,8 +19,10 @@
|
||||
inputId="metadata-search-providers"
|
||||
[filter]="false"
|
||||
showToggleAll="false"
|
||||
[options]="providers()"
|
||||
formControlName="provider"
|
||||
[options]="providerOptions()"
|
||||
optionLabel="label"
|
||||
optionValue="id"
|
||||
formControlName="providers"
|
||||
[placeholder]="t('selectProviders')"
|
||||
class="'custom-multiselect'">
|
||||
</p-multiselect>
|
||||
@@ -84,7 +85,7 @@
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@if (loading() || searchTriggered()) {
|
||||
@if (hasSearched()) {
|
||||
<div class="provider-status">
|
||||
<div class="status-header">
|
||||
<div class="results-info">
|
||||
@@ -104,19 +105,20 @@
|
||||
<div class="provider-pills">
|
||||
@for (tab of providerTabs(); track tab.provider) {
|
||||
<div class="provider-pill"
|
||||
[class]="'provider-' + providerClass(tab.provider)"
|
||||
[class.has-results]="tab.count > 0"
|
||||
[class.active]="isProviderPillActive(tab.provider)"
|
||||
[class]="'provider-pill provider-' + tab.provider.toLowerCase() + (tab.count > 0 ? ' has-results' : '') + (isProviderPillActive(tab.provider) ? ' active' : '')"
|
||||
[attr.role]="tab.count > 0 ? 'button' : null"
|
||||
[attr.tabindex]="tab.count > 0 ? '0' : null"
|
||||
(click)="tab.count > 0 && onProviderPillClick(tab.provider, $event)"
|
||||
(keydown.enter)="tab.count > 0 && onProviderPillClick(tab.provider, $event)"
|
||||
[style.cursor]="tab.count > 0 ? 'pointer' : 'default'">
|
||||
(keydown.enter)="tab.count > 0 && onProviderPillClick(tab.provider, $event)">
|
||||
<div class="pill-icon">
|
||||
<i class="pi pi-database"></i>
|
||||
</div>
|
||||
<div class="pill-content">
|
||||
<span class="pill-name">{{ tab.provider }}</span>
|
||||
<span class="pill-name">
|
||||
{{ providerLabelKey(tab.provider) | transloco }}
|
||||
</span>
|
||||
@if (loading() && tab.count === 0) {
|
||||
<i class="pi pi-spin pi-spinner pill-spinner"></i>
|
||||
} @else {
|
||||
@@ -129,23 +131,31 @@
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!searchTriggered() && results().length === 0) {
|
||||
@if (!hasSearched()) {
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">
|
||||
<i class="pi pi-search"></i>
|
||||
</div>
|
||||
<h3>{{ t('readyToSearch') }}</h3>
|
||||
<p>{{ t('readyToSearchHint') }}</p>
|
||||
@if (noProviders()) {
|
||||
<h3>{{ t('noProviders') }}</h3>
|
||||
} @else {
|
||||
<h3>{{ t('readyToSearch') }}</h3>
|
||||
<p>{{ t('readyToSearchHint') }}</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (searchTriggered() && results().length === 0 && !loading()) {
|
||||
@if (hasSearched() && !loading() && (results().length === 0 || failed())) {
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon no-results">
|
||||
<i class="pi pi-inbox"></i>
|
||||
</div>
|
||||
<h3>{{ t('noResultsFound') }}</h3>
|
||||
<p>{{ t('noResultsHint') }}</p>
|
||||
@if (failed()) {
|
||||
<h3>{{ t('searchFailed') }}</h3>
|
||||
} @else {
|
||||
<h3>{{ t('noResultsFound') }}</h3>
|
||||
<p>{{ t('noResultsHint') }}</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -164,7 +174,7 @@
|
||||
class="book-cover"
|
||||
[src]="metadata.thumbnailUrl"
|
||||
[title]="metadata.title"
|
||||
[authors]="metadata.authors ?? []"
|
||||
[authors]="metadata.authors"
|
||||
[alt]="metadata.title ?? ''"/>
|
||||
<div class="card-overlay">
|
||||
<i class="pi pi-eye"></i>
|
||||
@@ -174,32 +184,20 @@
|
||||
|
||||
<div class="card-content">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title">{{ truncateText(metadata.title!, 60) }}</h4>
|
||||
<div
|
||||
class="card-provider"
|
||||
[class]="'card-provider provider-' + providerClass(metadata)"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
(click)="onProviderClick($event)"
|
||||
(keydown.enter)="onProviderClick($event)"
|
||||
>
|
||||
@if (providerHref(metadata); as href) {
|
||||
<a [href]="href" target="_blank" rel="noopener">
|
||||
@if (providerName(metadata); as name) {
|
||||
{{ name }}
|
||||
} @else {
|
||||
{{ t('unknownProvider') }}
|
||||
}
|
||||
<h4 class="card-title">{{ truncateText(metadata.title, 60) }}</h4>
|
||||
<div class="card-provider" [class]="'provider-' + providerClass(metadata.provider)">
|
||||
@let providerLabel = providerLabelKey(metadata.provider) | transloco;
|
||||
@if (metadata.externalUrl; as href) {
|
||||
<a [href]="href" target="_blank" rel="noopener" (click)="$event.stopPropagation()">
|
||||
{{ providerLabel }}
|
||||
</a>
|
||||
} @else if (providerName(metadata); as name) {
|
||||
{{ name }}
|
||||
} @else {
|
||||
{{ t('unknownProvider') }}
|
||||
{{ providerLabel }}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (metadata.authors && metadata.authors.length > 0) {
|
||||
@if (metadata.authors?.length) {
|
||||
<p class="card-authors">
|
||||
<i class="pi pi-user"></i>
|
||||
{{ truncateText(metadata.authors.join(', '), 50) }}
|
||||
|
||||
+83
-52
@@ -1,24 +1,23 @@
|
||||
import {Component, input, output, provideZonelessChangeDetection, signal} from '@angular/core';
|
||||
import {MetadataCatalogService} from '../../../../../shared/metadata/metadata-catalog.service';
|
||||
import {METADATA_PROVIDER_LIST, type MetadataProviderId} from '../../../../../shared/metadata/metadata-providers';
|
||||
import {Component, computed, input, output, provideZonelessChangeDetection, signal} from '@angular/core';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {Subject} from 'rxjs';
|
||||
import {experimental_streamedQuery, provideTanStackQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Book, BookMetadata} from '../../../../book/model/book.model';
|
||||
import {BookMetadataService} from '../../../../book/service/book-metadata.service';
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {AppSettings} from '../../../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {Book, BookMetadata} from '../../../../book/model/book.model';
|
||||
import {MetadataSourceQueryService, type MetadataSearchParams, type MetadataSearchResult} from '../../../sources/metadata-source-query.service';
|
||||
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
|
||||
import {MetadataSearcherComponent} from './metadata-searcher.component';
|
||||
import {MetadataProviderService} from '../../../service/metadata-provider.service';
|
||||
import {MetadataProvider} from '../../../model/metadata-provider.model';
|
||||
|
||||
@Component({selector: 'app-metadata-picker', template: '', standalone: true})
|
||||
class PickerStub {
|
||||
readonly fetchedMetadata = input<BookMetadata>();
|
||||
readonly book = input<Book | null>();
|
||||
readonly detailLoading = input(false);
|
||||
readonly goBack = output<boolean>();
|
||||
}
|
||||
|
||||
@@ -31,55 +30,73 @@ class CoverStub {
|
||||
}
|
||||
|
||||
describe('MetadataSearcherComponent', () => {
|
||||
const providers = signal(METADATA_PROVIDER_LIST);
|
||||
const providersLoading = signal(false);
|
||||
let fixture: ComponentFixture<MetadataSearcherComponent>;
|
||||
let component: MetadataSearcherComponent;
|
||||
let search$: Subject<BookMetadata>;
|
||||
let detail$: Subject<BookMetadata>;
|
||||
let providers$: Subject<MetadataProvider[]>;
|
||||
let results: MetadataSearchResult[];
|
||||
let streamError: Error | null;
|
||||
let queryResult: Promise<MetadataSearchResult[]>;
|
||||
let queryClient: QueryClient;
|
||||
const appSettings = signal<Pick<AppSettings, 'autoBookSearch' | 'metadataProviderSettings'> | null>(null);
|
||||
const prospective = vi.fn((params: MetadataSearchParams) => queryOptions({
|
||||
queryKey: ['prospective', params],
|
||||
queryFn: experimental_streamedQuery({
|
||||
streamFn: async function* () {
|
||||
yield* await queryResult;
|
||||
if (streamError) throw streamError;
|
||||
},
|
||||
}),
|
||||
retry: false,
|
||||
}));
|
||||
|
||||
const appSettings = signal<AppSettings | null>(null);
|
||||
const fetchBookMetadata = vi.fn();
|
||||
const fetchMetadataDetail = vi.fn();
|
||||
const fetchMetadataProviders = vi.fn();
|
||||
|
||||
const settings = (): AppSettings => ({
|
||||
autoBookSearch: false,
|
||||
const settings = (autoBookSearch = false): Pick<AppSettings, 'autoBookSearch' | 'metadataProviderSettings'> => ({
|
||||
autoBookSearch,
|
||||
metadataProviderSettings: {
|
||||
openLibrary: {enabled: true},
|
||||
amazon: {enabled: false, cookie: '', domain: 'com'},
|
||||
google: {enabled: false, language: '', apiKey: ''},
|
||||
goodReads: {enabled: true},
|
||||
ranobedb: {enabled: false, preferRomaji: false},
|
||||
hardcover: {enabled: false, apiKey: ''},
|
||||
comicvine: {enabled: false, apiKey: ''},
|
||||
douban: {enabled: false},
|
||||
lubimyczytac: {enabled: false},
|
||||
audible: {enabled: false, domain: 'com'},
|
||||
appleBooks: {enabled: false, country: ''},
|
||||
},
|
||||
} as unknown as AppSettings);
|
||||
});
|
||||
|
||||
const book = (): Book => ({
|
||||
id: 1,
|
||||
const book = (id = 1) => ({
|
||||
id,
|
||||
libraryId: 1,
|
||||
metadata: {bookId: 1, title: 'Dune', authors: ['Frank Herbert'], isbn13: '9780441013593'},
|
||||
} as Book);
|
||||
|
||||
const openLibraryResult = (): BookMetadata => ({
|
||||
bookId: 1,
|
||||
provider: 'OpenLibrary',
|
||||
title: 'Dune',
|
||||
openlibraryId: '/books/OL30014174M',
|
||||
goodreadsId: '53403754',
|
||||
metadata: {bookId: id, title: 'Dune', authors: ['Frank Herbert'], isbn13: '9780441013593'},
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
search$ = new Subject<BookMetadata>();
|
||||
detail$ = new Subject<BookMetadata>();
|
||||
providers$ = new Subject<MetadataProvider[]>();
|
||||
providers.set(METADATA_PROVIDER_LIST);
|
||||
providersLoading.set(false);
|
||||
results = [];
|
||||
streamError = null;
|
||||
queryResult = Promise.resolve(results);
|
||||
prospective.mockClear();
|
||||
appSettings.set(null);
|
||||
fetchBookMetadata.mockReset().mockReturnValue(search$.asObservable());
|
||||
fetchMetadataDetail.mockReset().mockReturnValue(detail$.asObservable());
|
||||
fetchMetadataProviders.mockReset().mockReturnValue(providers$.asObservable());
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [MetadataSearcherComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideTanStackQuery(queryClient = new QueryClient()),
|
||||
{provide: AppSettingsService, useValue: {appSettings}},
|
||||
{provide: BookMetadataService, useValue: {fetchBookMetadata, fetchMetadataDetail}},
|
||||
{provide: MetadataProviderService, useValue: {fetchMetadataProviders, fetchMetadataDetail}},
|
||||
{provide: MetadataSourceQueryService, useValue: {
|
||||
prospective,
|
||||
providersLoading: providersLoading.asReadonly(),
|
||||
enabledProviders: computed(() => providers().filter(provider => appSettings()?.metadataProviderSettings[provider.settingsKey]?.enabled)),
|
||||
}},
|
||||
{provide: MetadataCatalogService, useValue: {
|
||||
providers: providers.asReadonly(),
|
||||
provider: (id: MetadataProviderId) => providers().find(provider => provider.id === id),
|
||||
}},
|
||||
],
|
||||
})
|
||||
.overrideComponent(MetadataSearcherComponent, {
|
||||
@@ -92,27 +109,41 @@ describe('MetadataSearcherComponent', () => {
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
function setUp(isActiveTab = false): void {
|
||||
appSettings.set(settings());
|
||||
fixture.componentRef.setInput('book', book());
|
||||
function setUp(isActiveTab = false, autoBookSearch = false, id = 1): void {
|
||||
appSettings.set(settings(autoBookSearch));
|
||||
fixture.componentRef.setInput('book', book(id));
|
||||
fixture.componentRef.setInput('isActiveTab', isActiveTab);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
it('keeps an OpenLibrary result even when it carries a Goodreads ID', () => {
|
||||
setUp();
|
||||
const result = openLibraryResult();
|
||||
function latestQuery() {
|
||||
const query = prospective.mock.results.at(-1);
|
||||
if (!query || query.type !== 'return') throw new Error('Expected a prospective query');
|
||||
return query.value;
|
||||
}
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
component.onSubmit();
|
||||
search$.next(result);
|
||||
TestBed.flushEffects();
|
||||
await queryClient.fetchQuery(latestQuery()).catch(() => undefined);
|
||||
await fixture.whenStable();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
TestBed.flushEffects();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
component.onBookClick(result);
|
||||
it('keeps the selected result provider', async () => {
|
||||
results = [{bookId: 1, provider: 'OpenLibrary', title: 'Dune'}];
|
||||
queryResult = Promise.resolve(results);
|
||||
setUp();
|
||||
|
||||
expect(fetchMetadataDetail).not.toHaveBeenCalled();
|
||||
expect(component.selected()).toBe(result);
|
||||
expect(component.detailLoading()).toBe(false);
|
||||
await submit();
|
||||
component.onBookClick(component.results()[0]);
|
||||
|
||||
expect(component.selected()?.provider).toBe('OpenLibrary');
|
||||
});
|
||||
|
||||
it('keeps user-edited search terms when the tab is switched away and back', () => {
|
||||
it('keeps typed terms through a tab switch', () => {
|
||||
setUp(true);
|
||||
component.form.patchValue({title: 'Dune Messiah', isbn: ''});
|
||||
|
||||
@@ -121,7 +152,7 @@ describe('MetadataSearcherComponent', () => {
|
||||
fixture.componentRef.setInput('isActiveTab', true);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(component.form.value.title).toBe('Dune Messiah');
|
||||
expect(component.form.value.isbn).toBe('');
|
||||
expect(component.form.value).toMatchObject({title: 'Dune Messiah', isbn: ''});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
+97
-192
@@ -1,57 +1,26 @@
|
||||
import {Component, computed, effect, inject, input, OnDestroy, signal} from '@angular/core';
|
||||
import {Component, computed, effect, inject, input, linkedSignal, signal} from '@angular/core';
|
||||
import {toSignal} from '@angular/core/rxjs-interop';
|
||||
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {FormBuilder, ReactiveFormsModule} from '@angular/forms';
|
||||
import {Button} from '@openng/optimus-ui/button';
|
||||
import {InputText} from '@openng/optimus-ui/inputtext';
|
||||
import {MultiSelect} from '@openng/optimus-ui/multiselect';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {TranslocoDirective} from '@jsverse/transloco';
|
||||
import {catchError, Subject, takeUntil} from 'rxjs';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {injectQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {FetchMetadataRequest} from '../../../model/request/fetch-metadata-request.model';
|
||||
import {Book, BookMetadata} from '../../../../book/model/book.model';
|
||||
import {Book} from '../../../../book/model/book.model';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {BookMetadataService} from '../../../../book/service/book-metadata.service';
|
||||
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
|
||||
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
|
||||
import {MetadataProviderService} from '../../../service/metadata-provider.service';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {MetadataCatalogService} from '../../../../../shared/metadata/metadata-catalog.service';
|
||||
import type {MetadataProviderId} from '../../../../../shared/metadata/metadata-providers';
|
||||
import {
|
||||
MetadataSourceQueryService,
|
||||
type MetadataSearchParams,
|
||||
type MetadataSearchResult,
|
||||
} from '../../../sources/metadata-source-query.service';
|
||||
|
||||
const DETAIL_ID_FIELD: Record<string, keyof BookMetadata> = {
|
||||
GoodReads: 'goodreadsId',
|
||||
Amazon: 'asin',
|
||||
Audible: 'audibleId',
|
||||
Comicvine: 'comicvineId',
|
||||
};
|
||||
|
||||
function providerKey(result: BookMetadata): string {
|
||||
return result.provider?.toLowerCase() ?? 'unknown';
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||||
}
|
||||
|
||||
function needsDetail(result: BookMetadata): boolean {
|
||||
if (result.provider === 'Comicvine') {
|
||||
const comic = result.comicMetadata;
|
||||
return !comic || !(
|
||||
comic.pencillers?.length || comic.inkers?.length || comic.colorists?.length ||
|
||||
comic.letterers?.length || comic.editors?.length || comic.characters?.length
|
||||
);
|
||||
}
|
||||
return !result.description;
|
||||
}
|
||||
|
||||
export function detailRequestFor(result: BookMetadata): { provider: string; id: string } | null {
|
||||
const provider = result.provider;
|
||||
const idField = provider ? DETAIL_ID_FIELD[provider] : undefined;
|
||||
const id = idField ? result[idField] : undefined;
|
||||
if (!provider || typeof id !== 'string' || !id || !needsDetail(result)) {
|
||||
return null;
|
||||
}
|
||||
return {provider, id};
|
||||
}
|
||||
const NO_SEARCH: MetadataSearchParams = {bookId: 0, providers: []};
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-searcher',
|
||||
@@ -59,70 +28,81 @@ export function detailRequestFor(result: BookMetadata): { provider: string; id:
|
||||
styleUrls: ['./metadata-searcher.component.scss'],
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
FormsModule,
|
||||
Button,
|
||||
InputText,
|
||||
MetadataPickerComponent,
|
||||
MultiSelect,
|
||||
Tooltip,
|
||||
TranslocoDirective,
|
||||
TranslocoPipe,
|
||||
CoverComponent
|
||||
],
|
||||
standalone: true
|
||||
})
|
||||
export class MetadataSearcherComponent implements OnDestroy {
|
||||
export class MetadataSearcherComponent {
|
||||
readonly book = input<Book | null>(null);
|
||||
readonly isActiveTab = input(false);
|
||||
|
||||
private readonly formBuilder = inject(FormBuilder);
|
||||
private readonly bookMetadataService = inject(BookMetadataService);
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
private readonly metadataProviderService = inject(MetadataProviderService);
|
||||
private readonly sources = inject(MetadataSourceQueryService);
|
||||
private readonly catalog = inject(MetadataCatalogService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
|
||||
private readonly search = signal<MetadataSearchParams | null>(null);
|
||||
private resetForBookId: number | null = null;
|
||||
private readonly autoSearchPending = linkedSignal<number | undefined, boolean>({
|
||||
source: () => this.book()?.id,
|
||||
computation: bookId => bookId !== undefined
|
||||
&& !!this.appSettingsService.appSettings()?.autoBookSearch,
|
||||
});
|
||||
private providersInitialised = false;
|
||||
private readonly query = injectQuery(() => ({
|
||||
...this.sources.prospective(this.search() ?? NO_SEARCH),
|
||||
enabled: this.search() !== null,
|
||||
}));
|
||||
|
||||
readonly form: FormGroup = this.formBuilder.group({
|
||||
provider: null,
|
||||
title: [''],
|
||||
author: [''],
|
||||
isbn: ['']
|
||||
readonly form = this.formBuilder.group({
|
||||
providers: this.formBuilder.control<MetadataProviderId[] | null>(null),
|
||||
title: this.formBuilder.nonNullable.control(''),
|
||||
author: this.formBuilder.nonNullable.control(''),
|
||||
isbn: this.formBuilder.nonNullable.control('')
|
||||
});
|
||||
|
||||
readonly results = signal<BookMetadata[]>([]);
|
||||
readonly searchedProviders = signal<string[]>([]);
|
||||
readonly loading = signal(false);
|
||||
readonly searchTriggered = signal(false);
|
||||
readonly selectedFilters = signal<Set<string>>(new Set(['all']));
|
||||
readonly selected = signal<BookMetadata | null>(null);
|
||||
readonly detailLoading = signal(false);
|
||||
readonly results = computed(() => this.query.data() ?? []);
|
||||
readonly loading = this.query.isFetching;
|
||||
readonly failed = computed(() => this.query.isError());
|
||||
readonly hasSearched = computed(() => this.search() !== null);
|
||||
readonly selectedFilters = signal<Set<MetadataProviderId | 'all'>>(new Set(['all']));
|
||||
readonly selected = signal<MetadataSearchResult | null>(null);
|
||||
|
||||
readonly providers = toSignal(
|
||||
this.metadataProviderService.fetchMetadataProviders()
|
||||
.pipe(map(
|
||||
providers => providers.filter(p => p.enabled).map(p => capitalize(p.name))
|
||||
))
|
||||
.pipe(catchError(() => []))
|
||||
);
|
||||
readonly providers = computed(() => this.sources.enabledProviders().map(provider => provider.id));
|
||||
readonly noProviders = computed(() => !this.sources.providersLoading() && this.providers().length === 0);
|
||||
|
||||
readonly providerOptions = computed(() => this.sources.enabledProviders().map(provider => ({
|
||||
id: provider.id,
|
||||
label: this.t.translate(provider.labelKey, {}, this.activeLang()),
|
||||
})));
|
||||
|
||||
readonly resultsByProvider = computed(() => {
|
||||
const groups = new Map<string, BookMetadata[]>();
|
||||
this.searchedProviders().forEach(provider => groups.set(provider.toLowerCase(), []));
|
||||
const groups = new Map<MetadataProviderId, MetadataSearchResult[]>();
|
||||
this.search()?.providers.forEach(provider => groups.set(provider, []));
|
||||
for (const result of this.results()) {
|
||||
const key = providerKey(result);
|
||||
groups.set(key, [...(groups.get(key) ?? []), result]);
|
||||
groups.get(result.provider)?.push(result);
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
|
||||
readonly providerTabs = computed(() =>
|
||||
this.searchedProviders().map(provider => ({
|
||||
provider,
|
||||
count: this.resultsByProvider().get(provider.toLowerCase())?.length ?? 0
|
||||
}))
|
||||
);
|
||||
readonly providerTabs = computed(() => Array.from(
|
||||
this.resultsByProvider(),
|
||||
([provider, results]) => ({provider, count: results.length})
|
||||
));
|
||||
|
||||
readonly interleavedResults = computed(() => {
|
||||
private readonly interleavedResults = computed(() => {
|
||||
const lists = Array.from(this.resultsByProvider().values());
|
||||
const maxLength = Math.max(0, ...lists.map(list => list.length));
|
||||
const interleaved: BookMetadata[] = [];
|
||||
const interleaved: MetadataSearchResult[] = [];
|
||||
for (let i = 0; i < maxLength; i++) {
|
||||
for (const list of lists) {
|
||||
if (i < list.length) interleaved.push(list[i]);
|
||||
@@ -134,19 +114,14 @@ export class MetadataSearcherComponent implements OnDestroy {
|
||||
readonly filteredResults = computed(() => {
|
||||
const filters = this.selectedFilters();
|
||||
const all = this.interleavedResults();
|
||||
return filters.has('all') ? all : all.filter(result => filters.has(providerKey(result)));
|
||||
return filters.has('all') ? all : all.filter(result => filters.has(result.provider));
|
||||
});
|
||||
|
||||
private bookId: number | null = null;
|
||||
private readonly autoSearchPending = signal(false);
|
||||
private providersInitialised = false;
|
||||
private readonly cancel$ = new Subject<void>();
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (!this.appSettingsService.appSettings() || this.sources.providersLoading()) return;
|
||||
const providers = this.providers();
|
||||
if (!this.appSettingsService.appSettings() || !providers) return;
|
||||
const control = this.form.get('provider')!;
|
||||
const control = this.form.controls.providers;
|
||||
|
||||
if (!this.providersInitialised) {
|
||||
this.providersInitialised = true;
|
||||
@@ -154,7 +129,7 @@ export class MetadataSearcherComponent implements OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
const current: string[] = control.value ?? [];
|
||||
const current = control.value ?? [];
|
||||
const valid = current.filter(provider => providers.includes(provider));
|
||||
if (valid.length !== current.length) {
|
||||
control.setValue(valid.length > 0 ? valid : null);
|
||||
@@ -169,173 +144,107 @@ export class MetadataSearcherComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
const providers = this.providers();
|
||||
if (!settings || !providers || book.id === this.bookId) return;
|
||||
if (!settings || book.id === this.resetForBookId) return;
|
||||
|
||||
this.bookId = book.id;
|
||||
this.resetForBookId = book.id;
|
||||
this.resetForBook(book);
|
||||
if (providers.length > 0) {
|
||||
this.autoSearchPending.set(!!settings.autoBookSearch);
|
||||
}
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
if (this.autoSearchPending() && this.isActiveTab()) {
|
||||
if (this.autoSearchPending() && this.isActiveTab() && !this.sources.providersLoading()) {
|
||||
this.autoSearchPending.set(false);
|
||||
this.onSubmit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.cancel$.next();
|
||||
this.cancel$.complete();
|
||||
}
|
||||
|
||||
get isSearchEnabled(): boolean {
|
||||
const providerSelected = !!this.form.get('provider')?.value;
|
||||
const title = this.form.get('title')?.value;
|
||||
const isbn = this.form.get('isbn')?.value;
|
||||
return providerSelected && (title || isbn);
|
||||
const providerSelected = !!this.form.controls.providers.value?.length;
|
||||
const title = this.form.controls.title.value;
|
||||
const isbn = this.form.controls.isbn.value;
|
||||
return providerSelected && (title.length > 0 || isbn.length > 0);
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
this.searchTriggered.set(true);
|
||||
const selectedProviders: string[] | null = this.form.get('provider')?.value;
|
||||
if (!selectedProviders?.length || this.bookId === null) return;
|
||||
const selectedProviders = this.form.controls.providers.value;
|
||||
const bookId = this.book()?.id;
|
||||
if (!selectedProviders?.length || bookId === undefined) return;
|
||||
|
||||
const request: FetchMetadataRequest = {
|
||||
bookId: this.bookId,
|
||||
const params: MetadataSearchParams = {
|
||||
bookId,
|
||||
providers: selectedProviders,
|
||||
title: this.form.get('title')?.value,
|
||||
author: this.form.get('author')?.value,
|
||||
isbn: this.form.get('isbn')?.value
|
||||
title: this.form.controls.title.value,
|
||||
author: this.form.controls.author.value,
|
||||
isbn: this.form.controls.isbn.value
|
||||
};
|
||||
|
||||
this.cancel$.next();
|
||||
this.results.set([]);
|
||||
this.searchedProviders.set(selectedProviders);
|
||||
this.selectedFilters.set(new Set(['all']));
|
||||
this.loading.set(true);
|
||||
|
||||
this.bookMetadataService.fetchBookMetadata(request.bookId, request)
|
||||
.pipe(takeUntil(this.cancel$))
|
||||
.subscribe({
|
||||
next: result => this.results.update(all => [...all, result]),
|
||||
error: error => {
|
||||
console.error('Error fetching metadata:', error);
|
||||
this.loading.set(false);
|
||||
},
|
||||
complete: () => this.loading.set(false)
|
||||
});
|
||||
void this.queryClient.resetQueries({queryKey: this.sources.prospective(params).queryKey, exact: true});
|
||||
this.search.set(params);
|
||||
}
|
||||
|
||||
onBookClick(result: BookMetadata): void {
|
||||
onBookClick(result: MetadataSearchResult): void {
|
||||
this.selected.set(result);
|
||||
|
||||
const detail = detailRequestFor(result);
|
||||
this.detailLoading.set(!!detail);
|
||||
if (!detail) return;
|
||||
|
||||
this.bookMetadataService.fetchMetadataDetail(detail.provider, detail.id)
|
||||
.pipe(takeUntil(this.cancel$))
|
||||
.subscribe({
|
||||
next: enriched => {
|
||||
if (this.selected() !== result) return;
|
||||
this.selected.set(enriched);
|
||||
this.detailLoading.set(false);
|
||||
},
|
||||
error: error => {
|
||||
console.error('Error fetching detailed metadata:', error);
|
||||
if (this.selected() === result) this.detailLoading.set(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onGoBack(): void {
|
||||
this.detailLoading.set(false);
|
||||
this.selected.set(null);
|
||||
}
|
||||
|
||||
onProviderPillClick(provider: string, event: Event): void {
|
||||
const key = provider.toLowerCase();
|
||||
onProviderPillClick(provider: MetadataProviderId, event: Event): void {
|
||||
const isModifierClick = (event instanceof MouseEvent || event instanceof KeyboardEvent) && (event.ctrlKey || event.metaKey);
|
||||
|
||||
this.selectedFilters.update(filters => {
|
||||
const next = new Set(filters);
|
||||
if (isModifierClick) {
|
||||
if (next.has(key)) {
|
||||
next.delete(key);
|
||||
if (next.has(provider)) {
|
||||
next.delete(provider);
|
||||
} else {
|
||||
next.add(key);
|
||||
next.add(provider);
|
||||
next.delete('all');
|
||||
}
|
||||
if (next.size === 0) next.add('all');
|
||||
} else if (next.has(key) && next.size === 1) {
|
||||
} else if (next.has(provider) && next.size === 1) {
|
||||
next.clear();
|
||||
next.add('all');
|
||||
} else {
|
||||
next.clear();
|
||||
next.add(key);
|
||||
next.add(provider);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
isProviderPillActive(provider: string): boolean {
|
||||
return this.selectedFilters().has(provider.toLowerCase());
|
||||
isProviderPillActive(provider: MetadataProviderId): boolean {
|
||||
return this.selectedFilters().has(provider);
|
||||
}
|
||||
|
||||
providerClass(result: BookMetadata): string {
|
||||
return providerKey(result);
|
||||
providerClass(id: MetadataProviderId): string {
|
||||
return id.toLowerCase();
|
||||
}
|
||||
|
||||
providerName(result: BookMetadata): string | null {
|
||||
return result.provider ?? null;
|
||||
providerLabelKey(id: MetadataProviderId): string {
|
||||
return this.catalog.provider(id)?.labelKey ?? id;
|
||||
}
|
||||
|
||||
providerHref(result: BookMetadata): string | null {
|
||||
if (!result.externalUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return result.externalUrl;
|
||||
}
|
||||
|
||||
onProviderClick(event: Event): void {
|
||||
const target = event.target as HTMLElement;
|
||||
if (target.tagName === 'A' || target.closest('a')) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
}
|
||||
|
||||
sanitizeHtml(htmlString: string | null | undefined): string {
|
||||
if (!htmlString) return '';
|
||||
sanitizeHtml(htmlString: string): string {
|
||||
return htmlString.replace(/<\/?[^>]+(>|$)/g, '').trim();
|
||||
}
|
||||
|
||||
truncateText(text: string | null, length: number): string {
|
||||
truncateText(text: string | undefined, length: number): string {
|
||||
const safeText = text ?? '';
|
||||
return safeText.length > length ? safeText.substring(0, length) + '...' : safeText;
|
||||
}
|
||||
|
||||
private isEnabledProviderSetting(value: unknown): value is { enabled: boolean } {
|
||||
return !!value && typeof value === 'object' && 'enabled' in value && typeof value.enabled == 'boolean';
|
||||
}
|
||||
|
||||
private resetSearchState(): void {
|
||||
this.cancel$.next();
|
||||
this.loading.set(false);
|
||||
this.detailLoading.set(false);
|
||||
this.searchTriggered.set(false);
|
||||
this.search.set(null);
|
||||
this.selected.set(null);
|
||||
this.results.set([]);
|
||||
this.searchedProviders.set([]);
|
||||
this.selectedFilters.set(new Set(['all']));
|
||||
}
|
||||
|
||||
private clearForNoBook(): void {
|
||||
this.bookId = null;
|
||||
this.resetForBookId = null;
|
||||
this.autoSearchPending.set(false);
|
||||
this.resetSearchState();
|
||||
this.form.patchValue({title: '', author: '', isbn: ''});
|
||||
@@ -343,10 +252,6 @@ export class MetadataSearcherComponent implements OnDestroy {
|
||||
|
||||
private resetForBook(book: Book): void {
|
||||
this.resetSearchState();
|
||||
this.patchFormFromBook(book);
|
||||
}
|
||||
|
||||
private patchFormFromBook(book: Book): void {
|
||||
this.form.patchValue({
|
||||
title: book.metadata?.title ?? '',
|
||||
author: book.metadata?.authors?.[0] ?? '',
|
||||
|
||||
+8
-115
@@ -184,127 +184,20 @@
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
@if (book?.metadata?.amazonRating || book?.metadata?.asin || book?.metadata?.goodreadsRating || book?.metadata?.goodreadsId || book?.metadata?.hardcoverRating || book?.metadata?.hardcoverId || book?.metadata?.lubimyczytacRating || book?.metadata?.lubimyczytacId || book?.metadata?.ranobedbRating || book?.metadata?.ranobedbId || book?.metadata?.audibleRating || book?.metadata?.audibleId || book?.metadata?.googleId) {
|
||||
@if (providerBadges().length > 0) {
|
||||
<div class="gradient-divider"></div>
|
||||
}
|
||||
|
||||
<div class="external-ratings">
|
||||
@if (book?.metadata?.amazonRating || book?.metadata?.asin) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="'https://www.amazon.com/dp/' + (book.metadata?.asin ?? '')"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
[pTooltip]="book?.metadata?.amazonRating ? getRatingTooltip(book, 'amazon') : undefined"
|
||||
@for (provider of providerBadges(); track provider.id) {
|
||||
<span
|
||||
class="rating-badge"
|
||||
[pTooltip]="provider.tooltip"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<img src="https://www.amazon.com/favicon.ico" alt="Amazon" class="rating-favicon"/>
|
||||
@if (book?.metadata?.amazonRating) {
|
||||
<span class="rating-value">{{ getRatingPercent(book.metadata!.amazonRating) }}%</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.goodreadsRating || book?.metadata?.goodreadsId) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="'https://www.goodreads.com/book/show/' + (book.metadata?.goodreadsId ?? '')"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
[pTooltip]="book?.metadata?.goodreadsRating ? getRatingTooltip(book, 'goodreads') : undefined"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<img src="https://www.goodreads.com/favicon.ico" alt="Goodreads" class="rating-favicon"/>
|
||||
@if (book?.metadata?.goodreadsRating) {
|
||||
<span class="rating-value">{{ getRatingPercent(book.metadata!.goodreadsRating) }}%</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.hardcoverRating || book?.metadata?.hardcoverId) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="'https://hardcover.app/books/' + (book.metadata?.hardcoverId ?? '')"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
[pTooltip]="book?.metadata?.hardcoverRating ? getRatingTooltip(book, 'hardcover') : undefined"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<img src="https://assets.hardcover.app/static/favicon.ico" alt="Hardcover" class="rating-favicon"/>
|
||||
@if (book?.metadata?.hardcoverRating) {
|
||||
<span class="rating-value">{{ getRatingPercent(book.metadata!.hardcoverRating) }}%</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.lubimyczytacRating || book?.metadata?.lubimyczytacId) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="book.metadata?.lubimyczytacId ? 'https://lubimyczytac.pl/ksiazka/' + book.metadata?.lubimyczytacId + '/ksiazka' : ''"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
[pTooltip]="book?.metadata?.lubimyczytacRating ? getRatingTooltip(book, 'lubimyczytac') : undefined"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<img src="https://lubimyczytac.pl/favicon.ico" alt="Lubimyczytac" class="rating-favicon"/>
|
||||
@if (book?.metadata?.lubimyczytacRating) {
|
||||
<span class="rating-value">{{ getRatingPercent(book.metadata!.lubimyczytacRating) }}%</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.ranobedbRating || book?.metadata?.ranobedbId) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="'https://ranobedb.org/book/' + (book.metadata?.ranobedbId ?? '')"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
[pTooltip]="book?.metadata?.ranobedbRating ? getRatingTooltip(book, 'ranobedb') : undefined"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<img src="https://www.ranobedb.org/favicon.png" alt="Ranobedb" class="rating-favicon"/>
|
||||
@if (book?.metadata?.ranobedbRating) {
|
||||
<span class="rating-value">{{ getRatingPercent(book.metadata!.ranobedbRating) }}%</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.audibleRating || book?.metadata?.audibleId) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="'https://www.audible.com/pd/' + (book.metadata?.audibleId ?? '')"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
[pTooltip]="book?.metadata?.audibleRating ? getRatingTooltip(book, 'audible') : undefined"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<img src="https://www.audible.com/favicon.ico" alt="Audible" class="rating-favicon"/>
|
||||
@if (book?.metadata?.audibleRating) {
|
||||
<span class="rating-value">{{ getRatingPercent(book.metadata!.audibleRating) }}%</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.googleId) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="'https://books.google.com/books?id=' + book.metadata!.googleId"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<img src="https://books.google.com/favicon.ico" alt="Google Books" class="rating-favicon"/>
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (book?.metadata?.comicMetadata?.webLink) {
|
||||
<a
|
||||
class="rating-link"
|
||||
[href]="book.metadata!.comicMetadata!.webLink"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<img src="https://www.comicvine.com/favicon.ico" alt="Comic Vine" class="rating-favicon"/>
|
||||
</a>
|
||||
<span class="rating-provider">{{ provider.labelKey | transloco }}</span>
|
||||
<span class="rating-value">{{ getRatingPercent(provider.rating) }}%</span>
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+4
-17
@@ -317,29 +317,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
.rating-link {
|
||||
.rating-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3281rem;
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.rating-link:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.rating-link:hover .rating-favicon {
|
||||
transform: scale(1.2);
|
||||
filter: drop-shadow(0 2px 4px rgb(0 0 0 / 30%));
|
||||
}
|
||||
|
||||
.rating-favicon {
|
||||
width: 1.0938rem;
|
||||
height: 1.0938rem;
|
||||
object-fit: contain;
|
||||
transition: transform 0.2s ease, filter 0.2s ease;
|
||||
.rating-provider {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.rating-value {
|
||||
|
||||
+13
-5
@@ -1,6 +1,8 @@
|
||||
import {MetadataCatalogService} from '../../../../../shared/metadata/metadata-catalog.service';
|
||||
import {METADATA_PROVIDER_LIST} from '../../../../../shared/metadata/metadata-providers';
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {BehaviorSubject, of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService, MenuItem} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
@@ -42,6 +44,8 @@ interface ConfirmationLike {
|
||||
}
|
||||
|
||||
describe('MetadataViewerComponent', () => {
|
||||
let langChanges: BehaviorSubject<string>;
|
||||
const providers = signal(METADATA_PROVIDER_LIST);
|
||||
const currentUser = signal<CurrentUser | null>(null);
|
||||
const appSettings = signal<AppSettings | null>(null);
|
||||
const navigationState = signal(false);
|
||||
@@ -90,10 +94,11 @@ describe('MetadataViewerComponent', () => {
|
||||
});
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string, params?: Record<string, unknown>) => {
|
||||
const translatedKey = langChanges.value === 'en' ? key : `${langChanges.value}:${key}`;
|
||||
if (!params) {
|
||||
return key;
|
||||
return translatedKey;
|
||||
}
|
||||
return `${key}:${Object.entries(params).map(([paramKey, value]) => `${paramKey}=${value}`).join(',')}`;
|
||||
return `${translatedKey}:${Object.entries(params).map(([paramKey, value]) => `${paramKey}=${String(value)}`).join(',')}`;
|
||||
});
|
||||
const getCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `cover:${bookId}:${updatedOn ?? 'none'}`);
|
||||
const getAudiobookCoverUrl = vi.fn((bookId: number, updatedOn?: string) => `audio:${bookId}:${updatedOn ?? 'none'}`);
|
||||
@@ -150,6 +155,8 @@ describe('MetadataViewerComponent', () => {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
langChanges = new BehaviorSubject('en');
|
||||
providers.set(METADATA_PROVIDER_LIST);
|
||||
currentUser.set(null);
|
||||
appSettings.set(null);
|
||||
navigationState.set(false);
|
||||
@@ -202,7 +209,8 @@ describe('MetadataViewerComponent', () => {
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: TranslocoService, useValue: {translate, getActiveLang: () => 'en', langChanges$: of('en')}},
|
||||
{provide: MetadataCatalogService, useValue: {providers: providers.asReadonly()}},
|
||||
{provide: TranslocoService, useValue: {translate, getActiveLang: () => langChanges.value, langChanges$: langChanges}},
|
||||
{provide: LibraryService, useValue: {findLibraryById}},
|
||||
{
|
||||
provide: BookDialogHelperService,
|
||||
@@ -482,7 +490,6 @@ describe('MetadataViewerComponent', () => {
|
||||
expect(component.getStarColorScaled(null)).toBe('rgb(203, 213, 225)');
|
||||
expect(component.getStarColorScaled(5)).toBe('rgb(34, 197, 94)');
|
||||
expect(component.getRatingPercent(4.5)).toBe(90);
|
||||
expect(component.getRatingTooltip(createBook({metadata: createMetadata({amazonRating: 4.2, amazonReviewCount: 1234})}), 'amazon')).toBe('★ 4.2 | 1,234 reviews');
|
||||
expect(component.getStatusLabel(ReadStatus.READING)).toBe('metadata.viewer.readStatusReading'.toUpperCase());
|
||||
expect(component.getStatusLabel('missing')).toBe('UNSET');
|
||||
expect(component.getBookCoverUrl(createBook())).toBe('cover:21:2026-03-26');
|
||||
@@ -498,4 +505,5 @@ describe('MetadataViewerComponent', () => {
|
||||
expect(component.getChannelLabel(2)).toBe('metadata.viewer.channelStereo');
|
||||
expect(component.getChannelLabel(6)).toBe('metadata.viewer.channelMultiple:count=6');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
+37
-35
@@ -40,7 +40,15 @@ import {AuthorService} from '../../../../author-browser/service/author.service';
|
||||
import {Dialog} from '@openng/optimus-ui/dialog';
|
||||
import {Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import DOMPurify from 'dompurify';
|
||||
import {MetadataCatalogService} from '../../../../../shared/metadata/metadata-catalog.service';
|
||||
import type {MetadataProviderId} from '../../../../../shared/metadata/metadata-providers';
|
||||
|
||||
interface ProviderBadge {
|
||||
id: MetadataProviderId;
|
||||
labelKey: string;
|
||||
rating: number | null;
|
||||
tooltip: string | undefined;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-viewer',
|
||||
@@ -100,6 +108,7 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked {
|
||||
}
|
||||
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
|
||||
private libraryService = inject(LibraryService);
|
||||
private bookDialogHelperService = inject(BookDialogHelperService)
|
||||
private emailService = inject(EmailService);
|
||||
@@ -118,6 +127,34 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked {
|
||||
private dialogRef = inject(DynamicDialogRef, { optional: true });
|
||||
private userState = this.userService.currentUser;
|
||||
private appSettings = this.appSettingsService.appSettings;
|
||||
private readonly catalog = inject(MetadataCatalogService);
|
||||
|
||||
readonly providerBadges = computed((): ProviderBadge[] => {
|
||||
const metadata = this.currentBook()?.metadata;
|
||||
if (!metadata) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.catalog.providers().map(provider => {
|
||||
const book = provider.book;
|
||||
const rating = (book?.rating ? metadata[book.rating] : null) ?? null;
|
||||
const reviewCount = (book?.reviewCount ? metadata[book.reviewCount] : null) ?? null;
|
||||
|
||||
return {
|
||||
id: provider.id,
|
||||
labelKey: provider.labelKey,
|
||||
rating,
|
||||
tooltip: this.ratingTooltip(rating, reviewCount),
|
||||
};
|
||||
}).filter(provider => provider.rating !== null);
|
||||
});
|
||||
|
||||
private ratingTooltip(rating: number | null, reviewCount: number | null): string | undefined {
|
||||
if (rating === null) return undefined;
|
||||
return reviewCount === null
|
||||
? this.t.translate('metadata.viewer.ratingTooltipNoReviews', {rating}, this.activeLang())
|
||||
: this.t.translate('metadata.viewer.ratingTooltip', {rating, reviews: reviewCount.toLocaleString()}, this.activeLang());
|
||||
}
|
||||
|
||||
private navigateAfterDialogClose(navigate: () => void): void {
|
||||
if (this.metadataCenterViewMode !== 'dialog') {
|
||||
@@ -475,7 +512,6 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked {
|
||||
if (user) {
|
||||
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ngAfterViewChecked(): void {
|
||||
@@ -1139,40 +1175,6 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked {
|
||||
return p != null ? Math.round(p * 10) / 10 : null;
|
||||
}
|
||||
|
||||
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover' | 'lubimyczytac' | 'ranobedb' | 'audible'): string {
|
||||
const meta = book?.metadata;
|
||||
if (!meta) return '';
|
||||
|
||||
switch (source) {
|
||||
case 'amazon':
|
||||
return meta.amazonRating != null
|
||||
? `★ ${meta.amazonRating} | ${meta.amazonReviewCount?.toLocaleString() ?? '0'} reviews`
|
||||
: '';
|
||||
case 'goodreads':
|
||||
return meta.goodreadsRating != null
|
||||
? `★ ${meta.goodreadsRating} | ${meta.goodreadsReviewCount?.toLocaleString() ?? '0'} reviews`
|
||||
: '';
|
||||
case 'hardcover':
|
||||
return meta.hardcoverRating != null
|
||||
? `★ ${meta.hardcoverRating} | ${meta.hardcoverReviewCount?.toLocaleString() ?? '0'} reviews`
|
||||
: '';
|
||||
case 'lubimyczytac':
|
||||
return meta.lubimyczytacRating != null
|
||||
? `★ ${meta.lubimyczytacRating}`
|
||||
: '';
|
||||
case 'ranobedb':
|
||||
return meta.ranobedbRating != null
|
||||
? `★ ${meta.ranobedbRating}`
|
||||
: '';
|
||||
case 'audible':
|
||||
return meta.audibleRating != null
|
||||
? `★ ${meta.audibleRating} | ${meta.audibleReviewCount?.toLocaleString() ?? '0'} reviews`
|
||||
: '';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
getRatingPercent(rating: number | null | undefined): number {
|
||||
if (rating == null) return 0;
|
||||
return Math.round((rating / 5) * 100);
|
||||
|
||||
+22
-14
@@ -8,11 +8,13 @@
|
||||
</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<p-tag
|
||||
[value]="getSyncStatusLabel()"
|
||||
[severity]="getSyncStatusSeverity()"
|
||||
class="sync-status-tag"
|
||||
/>
|
||||
@if (syncStatus() !== null) {
|
||||
<p-tag
|
||||
[value]="syncStatusLabel()"
|
||||
[severity]="syncStatusSeverity()"
|
||||
class="sync-status-tag"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -21,6 +23,12 @@
|
||||
<i class="pi pi-spin pi-spinner"></i>
|
||||
<span>{{ t('loading') }}</span>
|
||||
</div>
|
||||
} @else if (failed()) {
|
||||
<div class="empty-state" role="alert">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<p>{{ t('readFailed') }}</p>
|
||||
<p-button [label]="'common.retry' | transloco" (onClick)="retryRead()" size="small" />
|
||||
</div>
|
||||
} @else {
|
||||
<div class="sidecar-actions">
|
||||
<p-button
|
||||
@@ -37,7 +45,7 @@
|
||||
[label]="t('importBtn')"
|
||||
icon="pi pi-download"
|
||||
[loading]="importing()"
|
||||
[disabled]="syncStatus === 'MISSING'"
|
||||
[disabled]="syncStatus() === 'MISSING'"
|
||||
(onClick)="importFromSidecar()"
|
||||
severity="secondary"
|
||||
size="small"
|
||||
@@ -46,7 +54,7 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
@if (syncStatus === 'MISSING') {
|
||||
@if (syncStatus() === 'MISSING') {
|
||||
<div class="empty-state">
|
||||
<i class="pi pi-file"></i>
|
||||
<h4>{{ t('noSidecarTitle') }}</h4>
|
||||
@@ -54,33 +62,33 @@
|
||||
{{ t('noSidecarDescription') }}
|
||||
</p>
|
||||
</div>
|
||||
} @else if (sidecarContent) {
|
||||
} @else if (sidecarContent(); as sidecar) {
|
||||
<div class="sidecar-content">
|
||||
<div class="content-header">
|
||||
<div class="content-meta">
|
||||
<span class="meta-item">
|
||||
<i class="pi pi-clock"></i>
|
||||
{{ t('generatedLabel') }} {{ sidecarContent.generatedAt | date:'medium' }}
|
||||
{{ t('generatedLabel') }} {{ sidecar.generatedAt | date:'medium' }}
|
||||
</span>
|
||||
<span class="meta-item">
|
||||
<i class="pi pi-tag"></i>
|
||||
{{ t('versionLabel') }} {{ sidecarContent.version }}
|
||||
{{ t('versionLabel') }} {{ sidecar.version }}
|
||||
</span>
|
||||
<span class="meta-item">
|
||||
<i class="pi pi-cog"></i>
|
||||
{{ t('byLabel') }} {{ sidecarContent.generatedBy }}
|
||||
{{ t('byLabel') }} {{ sidecar.generatedBy }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="json-viewer">
|
||||
<pre class="json-content">{{ sidecarContent | json }}</pre>
|
||||
<pre class="json-content">{{ sidecar | json }}</pre>
|
||||
</div>
|
||||
|
||||
@if (sidecarContent.cover) {
|
||||
@if (sidecar.cover; as cover) {
|
||||
<div class="cover-info">
|
||||
<i class="pi pi-image"></i>
|
||||
<span>{{ t('coverFileLabel') }} {{ sidecarContent.cover.path }}</span>
|
||||
<span>{{ t('coverFileLabel') }} {{ cover.path }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
+173
-187
@@ -1,58 +1,88 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {provideTanStackQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {BehaviorSubject, of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {Book} from '../../../../book/model/book.model';
|
||||
import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service';
|
||||
import {SidecarService} from '../../../service/sidecar.service';
|
||||
import {SidecarMetadata, SidecarSyncStatus} from '../../../sources/sidecar.models';
|
||||
import {metadataSourceKeys, MetadataSourceQueryService} from '../../../sources/metadata-source-query.service';
|
||||
import {SidecarViewerComponent} from './sidecar-viewer.component';
|
||||
|
||||
describe('SidecarViewerComponent', () => {
|
||||
const getSyncStatus = vi.fn();
|
||||
const getSidecarContent = vi.fn();
|
||||
const exportToSidecar = vi.fn();
|
||||
const importFromSidecar = vi.fn();
|
||||
let status: SidecarSyncStatus;
|
||||
let statusError: Error | null;
|
||||
let contentError: Error | null;
|
||||
let content: SidecarMetadata;
|
||||
let queryClient: QueryClient;
|
||||
let fixture: ComponentFixture<SidecarViewerComponent>;
|
||||
let langChanges: BehaviorSubject<string>;
|
||||
const messageAdd = vi.fn();
|
||||
const translate = vi.fn((key: string) => `translated:${key}`);
|
||||
const exportToSidecar = vi.fn(() => of({message: 'ok'}));
|
||||
const importFromSidecar = vi.fn(() => of({message: 'ok'}));
|
||||
const contentQuery = vi.fn(async () => {
|
||||
if (contentError) throw contentError;
|
||||
return content;
|
||||
});
|
||||
const sidecarStatus = vi.fn((bookId: number) => queryOptions({
|
||||
queryKey: metadataSourceKeys.sidecarStatus(bookId),
|
||||
queryFn: async () => {
|
||||
if (statusError) throw statusError;
|
||||
return {status};
|
||||
},
|
||||
retry: false,
|
||||
}));
|
||||
const sidecar = vi.fn((bookId: number) => queryOptions({
|
||||
queryKey: metadataSourceKeys.sidecar(bookId),
|
||||
queryFn: contentQuery,
|
||||
retry: false,
|
||||
}));
|
||||
const translate = vi.fn((key: string) => `${langChanges.value === 'en' ? 'translated' : langChanges.value}:${key}`);
|
||||
|
||||
function createBook(id: number): Book {
|
||||
return {
|
||||
id,
|
||||
title: `Book ${id}`,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
} as Book;
|
||||
}
|
||||
const book = (id: number): Book => ({id, libraryId: 1, libraryName: 'Library'});
|
||||
|
||||
function createMetadata(): SidecarMetadata {
|
||||
return {
|
||||
beforeEach(() => {
|
||||
langChanges = new BehaviorSubject('en');
|
||||
status = 'IN_SYNC';
|
||||
statusError = null;
|
||||
contentError = null;
|
||||
content = {
|
||||
version: '1',
|
||||
generatedAt: '2026-03-26T00:00:00Z',
|
||||
generatedBy: 'test',
|
||||
metadata: {title: 'Example'},
|
||||
cover: {source: 'embedded', path: '/covers/example.jpg'},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
getSyncStatus.mockReset();
|
||||
getSidecarContent.mockReset();
|
||||
exportToSidecar.mockReset();
|
||||
importFromSidecar.mockReset();
|
||||
messageAdd.mockReset();
|
||||
translate.mockClear();
|
||||
sidecarStatus.mockClear();
|
||||
sidecar.mockClear();
|
||||
contentQuery.mockClear();
|
||||
exportToSidecar.mockReset();
|
||||
exportToSidecar.mockReturnValue(of({message: 'ok'}));
|
||||
importFromSidecar.mockReset();
|
||||
importFromSidecar.mockReturnValue(of({message: 'ok'}));
|
||||
queryClient = new QueryClient();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: SidecarService,
|
||||
useValue: {getSyncStatus, getSidecarContent, exportToSidecar, importFromSidecar},
|
||||
},
|
||||
provideTanStackQuery(queryClient),
|
||||
{provide: MessageService, useValue: {add: messageAdd}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
]
|
||||
{provide: SidecarService, useValue: {exportToSidecar, importFromSidecar}},
|
||||
{provide: MetadataSourceQueryService, useValue: {sidecarStatus, sidecar}},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
config: {reRenderOnLangChange: false},
|
||||
langChanges$: langChanges,
|
||||
getActiveLang: () => langChanges.value,
|
||||
selectTranslate: (key: string) => of(translate(key)),
|
||||
_loadDependencies: () => of(undefined),
|
||||
translate,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -60,173 +90,129 @@ describe('SidecarViewerComponent', () => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('resets its state when the selected book is cleared', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.currentBookId = 7;
|
||||
component.sidecarContent = createMetadata();
|
||||
component.syncStatus = 'IN_SYNC';
|
||||
component.loading.set(true);
|
||||
component.error = 'failed';
|
||||
async function createComponent(bookId = 7): Promise<SidecarViewerComponent> {
|
||||
fixture = TestBed.createComponent(SidecarViewerComponent);
|
||||
fixture.componentRef.setInput('book', book(bookId));
|
||||
await fixture.whenStable();
|
||||
await queryClient.fetchQuery(sidecarStatus(bookId)).catch(() => undefined);
|
||||
await fixture.whenStable();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
await fixture.whenStable();
|
||||
if (status !== 'MISSING' && status !== 'NOT_APPLICABLE' && statusError === null) {
|
||||
await queryClient.fetchQuery(sidecar(bookId)).catch(() => undefined);
|
||||
await fixture.whenStable();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
await fixture.whenStable();
|
||||
}
|
||||
return fixture.componentInstance;
|
||||
}
|
||||
|
||||
component.book = null;
|
||||
it('shows sidecar status and content and updates the label when the language changes', async () => {
|
||||
const component = await createComponent();
|
||||
|
||||
expect(component.currentBookId).toBeNull();
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.syncStatus).toBe('NOT_APPLICABLE');
|
||||
expect(component.loading()).toBe(false);
|
||||
expect(component.error).toBeNull();
|
||||
expect(component.syncStatus()).toBe('IN_SYNC');
|
||||
expect(component.sidecarContent()).toEqual(content);
|
||||
expect(component.syncStatusLabel()).toBe('translated:metadata.sidecar.syncStatusInSync');
|
||||
|
||||
langChanges.next('de');
|
||||
await fixture.whenStable();
|
||||
|
||||
expect(component.syncStatusLabel()).toBe('de:metadata.sidecar.syncStatusInSync');
|
||||
expect(component.syncStatus()).toBe('IN_SYNC');
|
||||
});
|
||||
|
||||
it('loads sync status and content when a sidecar exists for the selected book', () => {
|
||||
const metadata = createMetadata();
|
||||
getSyncStatus.mockReturnValue(of({status: 'IN_SYNC'}));
|
||||
getSidecarContent.mockReturnValue(of(metadata));
|
||||
it('skips sidecar content for missing and not-applicable statuses', async () => {
|
||||
status = 'MISSING';
|
||||
const missing = await createComponent(3);
|
||||
expect(missing.sidecarContent()).toBeNull();
|
||||
expect(contentQuery).not.toHaveBeenCalled();
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.book = createBook(7);
|
||||
|
||||
expect(getSyncStatus).toHaveBeenCalledWith(7);
|
||||
expect(getSidecarContent).toHaveBeenCalledWith(7);
|
||||
expect(component.currentBookId).toBe(7);
|
||||
expect(component.syncStatus).toBe('IN_SYNC');
|
||||
expect(component.sidecarContent).toEqual(metadata);
|
||||
expect(component.loading()).toBe(false);
|
||||
status = 'NOT_APPLICABLE';
|
||||
const notApplicable = await createComponent(4);
|
||||
expect(notApplicable.sidecarContent()).toBeNull();
|
||||
expect(contentQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips content loading when the sidecar is missing or not applicable', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
getSyncStatus.mockReturnValue(of({status: 'MISSING'}));
|
||||
|
||||
component.book = createBook(3);
|
||||
|
||||
expect(getSidecarContent).not.toHaveBeenCalled();
|
||||
expect(component.syncStatus).toBe('MISSING');
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.loading()).toBe(false);
|
||||
|
||||
getSyncStatus.mockReturnValue(of({status: 'NOT_APPLICABLE'}));
|
||||
component.book = createBook(4);
|
||||
|
||||
expect(getSidecarContent).not.toHaveBeenCalled();
|
||||
expect(component.syncStatus).toBe('NOT_APPLICABLE');
|
||||
expect(component.loading()).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to NOT_APPLICABLE when sync status lookup fails', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
getSyncStatus.mockReturnValue(throwError(() => new Error('boom')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.book = createBook(5);
|
||||
|
||||
expect(component.syncStatus).toBe('NOT_APPLICABLE');
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.loading()).toBe(false);
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('suppresses console noise for missing sidecar content but logs other load failures', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
|
||||
getSyncStatus.mockReturnValue(of({status: 'OUTDATED'}));
|
||||
getSidecarContent.mockReturnValue(throwError(() => ({status: 404})));
|
||||
component.book = createBook(6);
|
||||
|
||||
expect(component.sidecarContent).toBeNull();
|
||||
expect(component.loading()).toBe(false);
|
||||
expect(consoleError).not.toHaveBeenCalled();
|
||||
|
||||
getSidecarContent.mockReturnValue(throwError(() => ({status: 500})));
|
||||
component.loadSidecarData(6);
|
||||
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('exports to sidecar, shows a success toast, and reloads the current book data', () => {
|
||||
exportToSidecar.mockReturnValue(of({message: 'ok'}));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
const reload = vi.spyOn(component, 'loadSidecarData').mockImplementation(() => undefined);
|
||||
component.currentBookId = 9;
|
||||
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(exportToSidecar).toHaveBeenCalledWith(9);
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:metadata.sidecar.toast.exportSuccessSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.exportSuccessDetail',
|
||||
});
|
||||
expect(reload).toHaveBeenCalledWith(9);
|
||||
expect(component.exporting()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows an error toast when export fails and ignores export without a selected book', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
exportToSidecar.mockReturnValue(throwError(() => new Error('export failed')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(exportToSidecar).not.toHaveBeenCalled();
|
||||
|
||||
component.currentBookId = 11;
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:metadata.sidecar.toast.exportFailedSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.exportFailedDetail',
|
||||
});
|
||||
expect(component.exporting()).toBe(false);
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('imports from sidecar, shows success or error toasts, and reloads when needed', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
importFromSidecar.mockReturnValueOnce(of({message: 'ok'})).mockReturnValueOnce(throwError(() => new Error('import failed')));
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
const reload = vi.spyOn(component, 'loadSidecarData').mockImplementation(() => undefined);
|
||||
|
||||
component.currentBookId = 12;
|
||||
component.importFromSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'translated:metadata.sidecar.toast.importSuccessSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.importSuccessDetail',
|
||||
});
|
||||
expect(reload).toHaveBeenCalledWith(12);
|
||||
expect(component.importing()).toBe(false);
|
||||
|
||||
component.importFromSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenLastCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'translated:metadata.sidecar.toast.importFailedSummary',
|
||||
detail: 'translated:metadata.sidecar.toast.importFailedDetail',
|
||||
});
|
||||
expect(component.importing()).toBe(false);
|
||||
expect(consoleError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('maps sync status severities and labels across all branches', () => {
|
||||
const component = TestBed.runInInjectionContext(() => new SidecarViewerComponent());
|
||||
const cases: [SidecarSyncStatus | 'UNKNOWN', string, string][] = [
|
||||
it('maps every status to its severity and label', async () => {
|
||||
const cases: [SidecarSyncStatus, ReturnType<SidecarViewerComponent['syncStatusSeverity']>, string][] = [
|
||||
['IN_SYNC', 'success', 'translated:metadata.sidecar.syncStatusInSync'],
|
||||
['OUTDATED', 'warn', 'translated:metadata.sidecar.syncStatusOutdated'],
|
||||
['CONFLICT', 'danger', 'translated:metadata.sidecar.syncStatusConflict'],
|
||||
['MISSING', 'secondary', 'translated:metadata.sidecar.syncStatusMissing'],
|
||||
['NOT_APPLICABLE', 'info', 'translated:metadata.sidecar.syncStatusNA'],
|
||||
['UNKNOWN', 'info', 'translated:metadata.sidecar.syncStatusUnknown'],
|
||||
];
|
||||
|
||||
for (const [status, severity, label] of cases) {
|
||||
component.syncStatus = status as SidecarSyncStatus;
|
||||
expect(component.getSyncStatusSeverity()).toBe(severity);
|
||||
expect(component.getSyncStatusLabel()).toBe(label);
|
||||
for (const [index, [nextStatus, severity, label]] of cases.entries()) {
|
||||
status = nextStatus;
|
||||
const component = await createComponent(index + 20);
|
||||
expect(component.syncStatusSeverity()).toBe(severity);
|
||||
expect(component.syncStatusLabel()).toBe(label);
|
||||
}
|
||||
});
|
||||
|
||||
it('shows a status read failure and retries it without claiming the sidecar is inapplicable', async () => {
|
||||
statusError = new Error('Status unavailable');
|
||||
const component = await createComponent();
|
||||
|
||||
expect(component.syncStatus()).toBeNull();
|
||||
expect(component.failed()).toBe(true);
|
||||
expect(contentQuery).not.toHaveBeenCalled();
|
||||
expect(fixture.nativeElement.querySelector('[role="alert"]')?.textContent).toContain('metadata.sidecar.readFailed');
|
||||
|
||||
statusError = null;
|
||||
component.retryRead();
|
||||
await vi.waitFor(() => expect(component.sidecarContent()).toEqual(content));
|
||||
await fixture.whenStable();
|
||||
expect(component.failed()).toBe(false);
|
||||
expect(component.syncStatus()).toBe('IN_SYNC');
|
||||
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a content read failure separately from missing sidecar data', async () => {
|
||||
contentError = new Error('Content unavailable');
|
||||
const component = await createComponent();
|
||||
|
||||
expect(component.syncStatus()).toBe('IN_SYNC');
|
||||
expect(component.failed()).toBe(true);
|
||||
expect(component.sidecarContent()).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('[role="alert"]')?.textContent).toContain('metadata.sidecar.readFailed');
|
||||
});
|
||||
|
||||
it('exports with a success toast and invalidates the book sidecar key', async () => {
|
||||
const component = await createComponent(12);
|
||||
const invalidate = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
expect(invalidate).toHaveBeenCalledWith({queryKey: metadataSourceKeys.sidecar(12)});
|
||||
});
|
||||
|
||||
it('reports an export error', async () => {
|
||||
exportToSidecar.mockReturnValue(throwError(() => new Error('export failed')));
|
||||
const component = await createComponent(12);
|
||||
|
||||
component.exportToSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('imports with a success toast and invalidates the book sidecar key', async () => {
|
||||
const component = await createComponent(12);
|
||||
const invalidate = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
component.importFromSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
expect(invalidate).toHaveBeenCalledWith({queryKey: metadataSourceKeys.sidecar(12)});
|
||||
});
|
||||
|
||||
it('reports an import error', async () => {
|
||||
importFromSidecar.mockReturnValue(throwError(() => new Error('import failed')));
|
||||
const component = await createComponent(12);
|
||||
|
||||
component.importFromSidecar();
|
||||
|
||||
expect(messageAdd).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
});
|
||||
|
||||
+81
-104
@@ -1,100 +1,108 @@
|
||||
import {Component, inject, Input, OnDestroy, signal} from '@angular/core';
|
||||
import {Component, computed, inject, input, OnDestroy, signal} from '@angular/core';
|
||||
import {toSignal} from '@angular/core/rxjs-interop';
|
||||
import {Subject} from 'rxjs';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
import {injectQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {Book} from '../../../../book/model/book.model';
|
||||
import {SidecarMetadata, SidecarService, SidecarSyncStatus} from '../../../service/sidecar.service';
|
||||
import {SidecarService} from '../../../service/sidecar.service';
|
||||
import {SidecarMetadata, SidecarSyncStatus} from '../../../sources/sidecar.models';
|
||||
import {metadataSourceKeys, MetadataSourceQueryService} from '../../../sources/metadata-source-query.service';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {Button} from '@openng/optimus-ui/button';
|
||||
import {Tag} from '@openng/optimus-ui/tag';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {DatePipe, JsonPipe} from '@angular/common';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-sidecar-viewer',
|
||||
standalone: true,
|
||||
templateUrl: './sidecar-viewer.component.html',
|
||||
styleUrls: ['./sidecar-viewer.component.scss'],
|
||||
imports: [Button, Tag, Tooltip, JsonPipe, DatePipe, TranslocoDirective]
|
||||
imports: [Button, Tag, Tooltip, JsonPipe, DatePipe, TranslocoDirective, TranslocoPipe]
|
||||
})
|
||||
export class SidecarViewerComponent implements OnDestroy {
|
||||
@Input()
|
||||
set book(value: Book | null) {
|
||||
if (!value) {
|
||||
this.currentBookId = null;
|
||||
this.sidecarContent = null;
|
||||
this.syncStatus = 'NOT_APPLICABLE';
|
||||
this.loading.set(false);
|
||||
this.error = null;
|
||||
return;
|
||||
}
|
||||
readonly book = input<Book | null>(null);
|
||||
readonly currentBookId = computed(() => this.book()?.id ?? null);
|
||||
|
||||
this.currentBookId = value.id;
|
||||
this.loadSidecarData(value.id);
|
||||
}
|
||||
|
||||
private sidecarService = inject(SidecarService);
|
||||
private messageService = inject(MessageService);
|
||||
private readonly sidecarService = inject(SidecarService);
|
||||
private readonly sources = inject(MetadataSourceQueryService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
sidecarContent: SidecarMetadata | null = null;
|
||||
syncStatus: SidecarSyncStatus = 'NOT_APPLICABLE';
|
||||
loading = signal(false);
|
||||
exporting = signal(false);
|
||||
importing = signal(false);
|
||||
currentBookId: number | null = null;
|
||||
error: string | null = null;
|
||||
private readonly statusQuery = injectQuery(() => ({
|
||||
...this.sources.sidecarStatus(this.currentBookId() ?? 0),
|
||||
enabled: this.currentBookId() !== null,
|
||||
}));
|
||||
|
||||
loadSidecarData(bookId: number): void {
|
||||
this.loading.set(true);
|
||||
this.error = null;
|
||||
readonly syncStatus = computed<SidecarSyncStatus | null>(() =>
|
||||
this.statusQuery.isError() ? null : this.statusQuery.data()?.status ?? null
|
||||
);
|
||||
readonly syncStatusSeverity = computed(() => {
|
||||
switch (this.syncStatus()) {
|
||||
case 'IN_SYNC':
|
||||
return 'success';
|
||||
case 'OUTDATED':
|
||||
return 'warn';
|
||||
case 'CONFLICT':
|
||||
return 'danger';
|
||||
case 'MISSING':
|
||||
return 'secondary';
|
||||
default:
|
||||
return 'info';
|
||||
}
|
||||
});
|
||||
readonly syncStatusLabel = computed(() => {
|
||||
const lang = this.activeLang();
|
||||
switch (this.syncStatus()) {
|
||||
case 'IN_SYNC':
|
||||
return this.t.translate('metadata.sidecar.syncStatusInSync', {}, lang);
|
||||
case 'OUTDATED':
|
||||
return this.t.translate('metadata.sidecar.syncStatusOutdated', {}, lang);
|
||||
case 'CONFLICT':
|
||||
return this.t.translate('metadata.sidecar.syncStatusConflict', {}, lang);
|
||||
case 'MISSING':
|
||||
return this.t.translate('metadata.sidecar.syncStatusMissing', {}, lang);
|
||||
case 'NOT_APPLICABLE':
|
||||
return this.t.translate('metadata.sidecar.syncStatusNA', {}, lang);
|
||||
default:
|
||||
return this.t.translate('metadata.sidecar.syncStatusUnknown', {}, lang);
|
||||
}
|
||||
});
|
||||
private readonly hasSidecar = computed(() => {
|
||||
const status = this.syncStatus();
|
||||
return status !== null && status !== 'MISSING' && status !== 'NOT_APPLICABLE';
|
||||
});
|
||||
|
||||
this.sidecarService.getSyncStatus(bookId).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: (response) => {
|
||||
this.syncStatus = response.status;
|
||||
private readonly contentQuery = injectQuery(() => ({
|
||||
...this.sources.sidecar(this.currentBookId() ?? 0),
|
||||
enabled: this.currentBookId() !== null && this.hasSidecar(),
|
||||
}));
|
||||
|
||||
if (response.status !== 'MISSING' && response.status !== 'NOT_APPLICABLE') {
|
||||
this.loadSidecarContent(bookId);
|
||||
} else {
|
||||
this.sidecarContent = null;
|
||||
this.loading.set(false);
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
this.syncStatus = 'NOT_APPLICABLE';
|
||||
this.sidecarContent = null;
|
||||
this.loading.set(false);
|
||||
console.error('Failed to get sync status:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
readonly sidecarContent = computed<SidecarMetadata | null>(() =>
|
||||
this.hasSidecar() && !this.contentQuery.isError() ? this.contentQuery.data() ?? null : null
|
||||
);
|
||||
readonly loading = computed(() => this.statusQuery.isLoading() || this.contentQuery.isLoading());
|
||||
readonly failed = computed(() => this.statusQuery.isError() || (this.hasSidecar() && this.contentQuery.isError()));
|
||||
readonly exporting = signal(false);
|
||||
readonly importing = signal(false);
|
||||
|
||||
private loadSidecarContent(bookId: number): void {
|
||||
this.sidecarService.getSidecarContent(bookId).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: (content) => {
|
||||
this.sidecarContent = content;
|
||||
this.loading.set(false);
|
||||
},
|
||||
error: (err) => {
|
||||
this.sidecarContent = null;
|
||||
this.loading.set(false);
|
||||
if (err.status !== 404) {
|
||||
console.error('Failed to load sidecar content:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
retryRead(): void {
|
||||
const bookId = this.currentBookId();
|
||||
if (bookId !== null) {
|
||||
void this.queryClient.invalidateQueries({queryKey: metadataSourceKeys.sidecar(bookId)});
|
||||
}
|
||||
}
|
||||
|
||||
exportToSidecar(): void {
|
||||
if (!this.currentBookId) return;
|
||||
const bookId = this.currentBookId();
|
||||
if (!bookId) return;
|
||||
|
||||
this.exporting.set(true);
|
||||
this.sidecarService.exportToSidecar(this.currentBookId).pipe(
|
||||
this.sidecarService.exportToSidecar(bookId).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: () => {
|
||||
@@ -103,7 +111,7 @@ export class SidecarViewerComponent implements OnDestroy {
|
||||
summary: this.t.translate('metadata.sidecar.toast.exportSuccessSummary'),
|
||||
detail: this.t.translate('metadata.sidecar.toast.exportSuccessDetail')
|
||||
});
|
||||
this.loadSidecarData(this.currentBookId!);
|
||||
void this.queryClient.invalidateQueries({queryKey: metadataSourceKeys.sidecar(bookId)});
|
||||
this.exporting.set(false);
|
||||
},
|
||||
error: (err) => {
|
||||
@@ -119,10 +127,11 @@ export class SidecarViewerComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
importFromSidecar(): void {
|
||||
if (!this.currentBookId) return;
|
||||
const bookId = this.currentBookId();
|
||||
if (!bookId) return;
|
||||
|
||||
this.importing.set(true);
|
||||
this.sidecarService.importFromSidecar(this.currentBookId).pipe(
|
||||
this.sidecarService.importFromSidecar(bookId).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: () => {
|
||||
@@ -131,7 +140,7 @@ export class SidecarViewerComponent implements OnDestroy {
|
||||
summary: this.t.translate('metadata.sidecar.toast.importSuccessSummary'),
|
||||
detail: this.t.translate('metadata.sidecar.toast.importSuccessDetail')
|
||||
});
|
||||
this.loadSidecarData(this.currentBookId!);
|
||||
void this.queryClient.invalidateQueries({queryKey: metadataSourceKeys.sidecar(bookId)});
|
||||
this.importing.set(false);
|
||||
},
|
||||
error: (err) => {
|
||||
@@ -146,38 +155,6 @@ export class SidecarViewerComponent implements OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
getSyncStatusSeverity(): 'success' | 'info' | 'warn' | 'danger' | 'secondary' | 'contrast' {
|
||||
switch (this.syncStatus) {
|
||||
case 'IN_SYNC':
|
||||
return 'success';
|
||||
case 'OUTDATED':
|
||||
return 'warn';
|
||||
case 'CONFLICT':
|
||||
return 'danger';
|
||||
case 'MISSING':
|
||||
return 'secondary';
|
||||
default:
|
||||
return 'info';
|
||||
}
|
||||
}
|
||||
|
||||
getSyncStatusLabel(): string {
|
||||
switch (this.syncStatus) {
|
||||
case 'IN_SYNC':
|
||||
return this.t.translate('metadata.sidecar.syncStatusInSync');
|
||||
case 'OUTDATED':
|
||||
return this.t.translate('metadata.sidecar.syncStatusOutdated');
|
||||
case 'CONFLICT':
|
||||
return this.t.translate('metadata.sidecar.syncStatusConflict');
|
||||
case 'MISSING':
|
||||
return this.t.translate('metadata.sidecar.syncStatusMissing');
|
||||
case 'NOT_APPLICABLE':
|
||||
return this.t.translate('metadata.sidecar.syncStatusNA');
|
||||
default:
|
||||
return this.t.translate('metadata.sidecar.syncStatusUnknown');
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
|
||||
+12
-6
@@ -96,21 +96,27 @@
|
||||
<p-progressSpinner strokeWidth="3" animationDuration="1s"></p-progressSpinner>
|
||||
<p>{{ t('searchingForCovers') }}</p>
|
||||
</div>
|
||||
} @else if (coverImages.length === 0) {
|
||||
} @else if (coverImages().length === 0 || failed()) {
|
||||
<!-- No Results State -->
|
||||
<div class="empty-state no-results">
|
||||
<div class="empty-state-icon warning">
|
||||
<i class="pi pi-search"></i>
|
||||
</div>
|
||||
<h3>{{ t('noCoversFound') }}</h3>
|
||||
<p>{{ t('noCoversFoundDescription') }}</p>
|
||||
@if (failed()) {
|
||||
<h3>{{ t('searchFailed') }}</h3>
|
||||
} @else {
|
||||
<h3>{{ t('noCoversFound') }}</h3>
|
||||
<p>{{ t('noCoversFoundDescription') }}</p>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
}
|
||||
|
||||
@if (!loading() && coverImages().length > 0) {
|
||||
<!-- Results Grid -->
|
||||
<div class="results-header">
|
||||
<span class="results-count">
|
||||
<i class="pi pi-images"></i>
|
||||
{{ coverImages.length === 1 ? t('coversFoundSingular', { count: coverImages.length }) : t('coversFoundPlural', { count: coverImages.length }) }}
|
||||
{{ coverImages().length === 1 ? t('coversFoundSingular', { count: coverImages().length }) : t('coversFoundPlural', { count: coverImages().length }) }}
|
||||
</span>
|
||||
<span class="results-hint">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
@@ -119,7 +125,7 @@
|
||||
</div>
|
||||
|
||||
<div class="covers-grid">
|
||||
@for (cover of coverImages; track cover.url; let i = $index) {
|
||||
@for (cover of coverImages(); track cover.url; let i = $index) {
|
||||
<div class="cover-card">
|
||||
<div class="cover-image-wrapper">
|
||||
<p-image
|
||||
|
||||
+47
-73
@@ -1,25 +1,26 @@
|
||||
import {Component, inject, Input, OnInit, signal} from '@angular/core';
|
||||
import {Component, computed, inject, signal} from '@angular/core';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {BookCoverService, CoverFetchRequest, CoverImage} from '../../../../shared/services/book-cover.service';
|
||||
import {finalize} from 'rxjs/operators';
|
||||
import {FormBuilder, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {injectQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {Button} from '@openng/optimus-ui/button';
|
||||
import {InputText} from '@openng/optimus-ui/inputtext';
|
||||
import {ProgressSpinner} from '@openng/optimus-ui/progressspinner';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookMetadataManageService} from '../../../book/service/book-metadata-manage.service';
|
||||
import {CoverImage, CoverSearchParams, MetadataSourceQueryService} from '../../sources/metadata-source-query.service';
|
||||
import {Image} from '@openng/optimus-ui/image';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
const NO_SEARCH: CoverSearchParams = {bookId: 0, coverType: 'ebook'};
|
||||
|
||||
@Component({
|
||||
selector: 'app-cover-search',
|
||||
templateUrl: './cover-search.component.html',
|
||||
imports: [
|
||||
Button,
|
||||
ReactiveFormsModule,
|
||||
FormsModule,
|
||||
InputText,
|
||||
ProgressSpinner,
|
||||
Image,
|
||||
@@ -28,47 +29,41 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
],
|
||||
styleUrls: ['./cover-search.component.scss']
|
||||
})
|
||||
export class CoverSearchComponent implements OnInit {
|
||||
@Input() bookId!: number;
|
||||
searchForm: FormGroup;
|
||||
coverImages: CoverImage[] = [];
|
||||
loading = signal(false);
|
||||
hasSearched = signal(false);
|
||||
coverType: 'ebook' | 'audiobook' = 'ebook';
|
||||
|
||||
private fb = inject(FormBuilder);
|
||||
private bookCoverService = inject(BookCoverService);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
protected dynamicDialogRef = inject(DynamicDialogRef);
|
||||
protected bookService = inject(BookService);
|
||||
private bookMetadataManageService = inject(BookMetadataManageService);
|
||||
private messageService = inject(MessageService);
|
||||
export class CoverSearchComponent {
|
||||
private readonly fb = inject(FormBuilder);
|
||||
private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
protected readonly dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly bookMetadataManageService = inject(BookMetadataManageService);
|
||||
private readonly sources = inject(MetadataSourceQueryService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private readonly bookId: number = this.dynamicDialogConfig.data.bookId;
|
||||
private readonly book = this.bookService.findBookById(this.bookId);
|
||||
readonly searchForm = this.fb.nonNullable.group({
|
||||
title: ['', Validators.required],
|
||||
author: ['']
|
||||
});
|
||||
readonly coverType: 'ebook' | 'audiobook' = this.dynamicDialogConfig.data.coverType ??
|
||||
(this.book?.primaryFile?.bookType === 'AUDIOBOOK' ? 'audiobook' : 'ebook');
|
||||
private readonly search = signal<CoverSearchParams | null>(null);
|
||||
private readonly query = injectQuery(() => ({
|
||||
...this.sources.coverSearch(this.search() ?? NO_SEARCH),
|
||||
enabled: this.search() !== null,
|
||||
}));
|
||||
|
||||
readonly coverImages = computed(() => [...(this.query.data() ?? [])].sort((a, b) => a.index - b.index));
|
||||
readonly loading = this.query.isFetching;
|
||||
readonly failed = computed(() => this.query.isError());
|
||||
readonly hasSearched = computed(() => this.search() !== null);
|
||||
|
||||
constructor() {
|
||||
this.searchForm = this.fb.group({
|
||||
title: ['', Validators.required],
|
||||
author: ['']
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.bookId = this.dynamicDialogConfig.data.bookId;
|
||||
const book = this.bookService.findBookById(this.bookId);
|
||||
|
||||
// Use explicitly provided coverType, or auto-detect based on primary file
|
||||
if (this.dynamicDialogConfig.data.coverType) {
|
||||
this.coverType = this.dynamicDialogConfig.data.coverType;
|
||||
} else if (book?.primaryFile?.bookType === 'AUDIOBOOK') {
|
||||
this.coverType = 'audiobook';
|
||||
} else {
|
||||
this.coverType = 'ebook';
|
||||
}
|
||||
|
||||
if (book) {
|
||||
if (this.book) {
|
||||
this.searchForm.patchValue({
|
||||
title: book.metadata?.title || '',
|
||||
author: book.metadata?.authors && book.metadata?.authors.length > 0 ? book.metadata?.authors[0] : ''
|
||||
title: this.book.metadata?.title || '',
|
||||
author: this.book.metadata?.authors?.[0] ?? ''
|
||||
});
|
||||
|
||||
if (this.searchForm.valid) {
|
||||
@@ -78,36 +73,16 @@ export class CoverSearchComponent implements OnInit {
|
||||
}
|
||||
|
||||
onSearch() {
|
||||
if (this.searchForm.valid) {
|
||||
this.loading.set(true);
|
||||
this.coverImages = [];
|
||||
const request: CoverFetchRequest = {
|
||||
bookId: this.bookId,
|
||||
title: this.searchForm.value.title,
|
||||
author: this.searchForm.value.author,
|
||||
coverType: this.coverType
|
||||
};
|
||||
if (!this.searchForm.valid) return;
|
||||
|
||||
this.bookCoverService.fetchBookCovers(request)
|
||||
.pipe(finalize(() => {
|
||||
this.loading.set(false);
|
||||
this.hasSearched.set(true);
|
||||
}))
|
||||
.subscribe({
|
||||
next: (image) => {
|
||||
this.coverImages.push(image);
|
||||
this.coverImages.sort((a, b) => a.index - b.index);
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Error fetching covers:', error);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log('Form invalid', {
|
||||
formErrors: this.searchForm.errors,
|
||||
titleErrors: this.searchForm.get('title')?.errors
|
||||
});
|
||||
}
|
||||
const params: CoverSearchParams = {
|
||||
bookId: this.bookId,
|
||||
title: this.searchForm.value.title,
|
||||
author: this.searchForm.value.author,
|
||||
coverType: this.coverType,
|
||||
};
|
||||
void this.queryClient.resetQueries({queryKey: this.sources.coverSearch(params).queryKey, exact: true});
|
||||
this.search.set(params);
|
||||
}
|
||||
|
||||
selectAndSave(image: CoverImage) {
|
||||
@@ -138,7 +113,6 @@ export class CoverSearchComponent implements OnInit {
|
||||
|
||||
onClear() {
|
||||
this.searchForm.reset();
|
||||
this.coverImages = [];
|
||||
this.hasSearched.set(false);
|
||||
this.search.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
+21
-9
@@ -34,29 +34,33 @@
|
||||
<td class="metadata-table-cell" style="max-width: 70px; width: 70px;"></td>
|
||||
<td class="metadata-table-cell set-all-label" style="max-width: 127px; width: 127px;">{{ t('setAll') }}</td>
|
||||
<td class="metadata-table-cell">
|
||||
<p-select [options]="providersWithClear" [(ngModel)]="bulkP1"
|
||||
<p-select [options]="providerOptionsWithClear()" [(ngModel)]="bulkP1"
|
||||
(ngModelChange)="setBulkProvider('p1', $event)"
|
||||
optionLabel="label" optionValue="value"
|
||||
[placeholder]="t('setAllP1')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
</td>
|
||||
<td class="metadata-table-cell">
|
||||
<p-select [options]="providersWithClear" [(ngModel)]="bulkP2"
|
||||
<p-select [options]="providerOptionsWithClear()" [(ngModel)]="bulkP2"
|
||||
(ngModelChange)="setBulkProvider('p2', $event)"
|
||||
optionLabel="label" optionValue="value"
|
||||
[placeholder]="t('setAllP2')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
</td>
|
||||
<td class="metadata-table-cell">
|
||||
<p-select [options]="providersWithClear" [(ngModel)]="bulkP3"
|
||||
<p-select [options]="providerOptionsWithClear()" [(ngModel)]="bulkP3"
|
||||
(ngModelChange)="setBulkProvider('p3', $event)"
|
||||
optionLabel="label" optionValue="value"
|
||||
[placeholder]="t('setAllP3')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
</td>
|
||||
<td class="metadata-table-cell">
|
||||
<p-select [options]="providersWithClear" [(ngModel)]="bulkP4"
|
||||
<p-select [options]="providerOptionsWithClear()" [(ngModel)]="bulkP4"
|
||||
(ngModelChange)="setBulkProvider('p4', $event)"
|
||||
optionLabel="label" optionValue="value"
|
||||
[placeholder]="t('setAllP4')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
@@ -73,28 +77,36 @@
|
||||
</td>
|
||||
<td class="metadata-table-cell-sm field-label" style="max-width: 127px; width: 127px;">{{ formatLabel(field) }}</td>
|
||||
<td class="metadata-table-cell-sm">
|
||||
<p-select [options]="providers" [(ngModel)]="fieldOptions[field].p1"
|
||||
<p-select [options]="providerOptionsFor(fieldOptions[field].p1)" [(ngModel)]="fieldOptions[field].p1"
|
||||
optionDisabled="disabled"
|
||||
optionLabel="label" optionValue="value"
|
||||
[disabled]="!enabledFields[field]"
|
||||
[placeholder]="t('unset')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
</td>
|
||||
<td class="metadata-table-cell-sm">
|
||||
<p-select [options]="providers" [(ngModel)]="fieldOptions[field].p2"
|
||||
<p-select [options]="providerOptionsFor(fieldOptions[field].p2)" [(ngModel)]="fieldOptions[field].p2"
|
||||
optionDisabled="disabled"
|
||||
optionLabel="label" optionValue="value"
|
||||
[disabled]="!enabledFields[field]"
|
||||
[placeholder]="t('unset')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
</td>
|
||||
<td class="metadata-table-cell-sm">
|
||||
<p-select [options]="providers" [(ngModel)]="fieldOptions[field].p3"
|
||||
<p-select [options]="providerOptionsFor(fieldOptions[field].p3)" [(ngModel)]="fieldOptions[field].p3"
|
||||
optionDisabled="disabled"
|
||||
optionLabel="label" optionValue="value"
|
||||
[disabled]="!enabledFields[field]"
|
||||
[placeholder]="t('unset')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
</p-select>
|
||||
</td>
|
||||
<td class="metadata-table-cell-sm">
|
||||
<p-select [options]="providers" [(ngModel)]="fieldOptions[field].p4"
|
||||
<p-select [options]="providerOptionsFor(fieldOptions[field].p4)" [(ngModel)]="fieldOptions[field].p4"
|
||||
optionDisabled="disabled"
|
||||
optionLabel="label" optionValue="value"
|
||||
[disabled]="!enabledFields[field]"
|
||||
[placeholder]="t('unset')" appendTo="body"
|
||||
class="select-full-width" size="small">
|
||||
@@ -109,7 +121,7 @@
|
||||
<h3 class="section-title">{{ t('providerSpecificFields') }}</h3>
|
||||
<p class="section-description">{{ t('providerSpecificDescription') }}</p>
|
||||
<div class="fields-grid">
|
||||
@for (field of providerSpecificFields; track field) {
|
||||
@for (field of providerSpecificFields(); track field) {
|
||||
<div class="field-card">
|
||||
<p-checkbox [(ngModel)]="enabledFields[field]" [binary]="true"
|
||||
[pTooltip]="t('enableFieldTooltip')"
|
||||
|
||||
+21
-3
@@ -1,4 +1,7 @@
|
||||
import {SimpleChange} from '@angular/core';
|
||||
import {of} from 'rxjs';
|
||||
import {METADATA_PROVIDER_LIST, type MetadataProviderId} from '../../../../../shared/metadata/metadata-providers';
|
||||
import {MetadataSourceQueryService} from '../../../sources/metadata-source-query.service';
|
||||
import {computed, signal, SimpleChange} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
@@ -7,18 +10,28 @@ import {TranslocoService} from '@jsverse/transloco';
|
||||
import {FieldOptions, MetadataRefreshOptions} from '../../../model/request/metadata-refresh-options.model';
|
||||
import {MetadataAdvancedFetchOptionsComponent} from './metadata-advanced-fetch-options.component';
|
||||
|
||||
function providersWhereEnabled(isEnabled: (id: MetadataProviderId) => boolean) {
|
||||
return METADATA_PROVIDER_LIST.map(provider => ({...provider, enabled: isEnabled(provider.id)}));
|
||||
}
|
||||
|
||||
describe('MetadataAdvancedFetchOptionsComponent', () => {
|
||||
const providers = signal(providersWhereEnabled(() => true));
|
||||
const add = vi.fn();
|
||||
const translate = vi.fn((key: string) => `translated:${key}`);
|
||||
|
||||
beforeEach(() => {
|
||||
providers.set(providersWhereEnabled(() => true));
|
||||
add.mockClear();
|
||||
translate.mockClear();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: MetadataSourceQueryService, useValue: {
|
||||
providers: providers.asReadonly(),
|
||||
enabledProviders: computed(() => providers().filter(provider => provider.enabled)),
|
||||
}},
|
||||
{provide: MessageService, useValue: {add}},
|
||||
{provide: TranslocoService, useValue: {translate}},
|
||||
{provide: TranslocoService, useValue: {translate, langChanges$: of('en'), getActiveLang: () => 'en'}},
|
||||
]
|
||||
});
|
||||
});
|
||||
@@ -66,8 +79,13 @@ describe('MetadataAdvancedFetchOptionsComponent', () => {
|
||||
it('emits metadata options when all enabled non-provider fields have a provider', () => {
|
||||
const component = createComponent();
|
||||
const emit = vi.spyOn(component.metadataOptionsSubmitted, 'emit');
|
||||
providers.set(providersWhereEnabled(id => id === 'GoodReads'));
|
||||
expect(component.providerOptionsFor('Google')).toEqual([
|
||||
{value: 'GoodReads', label: 'translated:metadata.providers.goodReads'},
|
||||
{value: 'Google', label: 'translated:metadata.advancedFetchOptions.inactiveProvider', disabled: true},
|
||||
]);
|
||||
|
||||
for (const field of component.fields) {
|
||||
for (const field of component.fields()) {
|
||||
component.enabledFields[field] = false;
|
||||
}
|
||||
component.fieldOptions.title.p1 = 'Google';
|
||||
|
||||
+52
-125
@@ -1,4 +1,5 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
|
||||
import {Component, computed, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
|
||||
import {toSignal} from '@angular/core/rxjs-interop';
|
||||
import {Select} from '@openng/optimus-ui/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
|
||||
@@ -13,6 +14,10 @@ import {
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
import {MetadataProviderFieldsService} from '../../../../../shared/metadata';
|
||||
import type {MetadataProviderId} from '../../../../../shared/metadata/metadata-providers';
|
||||
import {MetadataSourceQueryService} from '../../../sources/metadata-source-query.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-advanced-fetch-options',
|
||||
templateUrl: './metadata-advanced-fetch-options.component.html',
|
||||
@@ -22,72 +27,50 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
})
|
||||
export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
|
||||
|
||||
private messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly sources = inject(MetadataSourceQueryService);
|
||||
private readonly providerFields = inject(MetadataProviderFieldsService);
|
||||
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
|
||||
|
||||
@Output() metadataOptionsSubmitted = new EventEmitter<MetadataRefreshOptions>();
|
||||
@Input() currentMetadataOptions!: MetadataRefreshOptions;
|
||||
@Input() submitButtonLabel!: string;
|
||||
|
||||
fields: (keyof FieldOptions)[] = [
|
||||
'title', 'subtitle', 'description', 'authors', 'publisher', 'publishedDate',
|
||||
'seriesName', 'seriesNumber', 'seriesTotal', 'isbn13', 'isbn10',
|
||||
'language', 'categories', 'cover', 'pageCount',
|
||||
'openlibraryId',
|
||||
'asin', 'amazonRating', 'amazonReviewCount',
|
||||
'googleId',
|
||||
'goodreadsId', 'goodreadsRating', 'goodreadsReviewCount',
|
||||
'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount', 'moods', 'tags',
|
||||
'comicvineId',
|
||||
'lubimyczytacId', 'lubimyczytacRating',
|
||||
'ranobedbId', 'ranobedbRating',
|
||||
'audibleId', 'audibleRating', 'audibleReviewCount',
|
||||
'applebooksId', 'applebooksRating', 'applebooksReviewCount',
|
||||
];
|
||||
|
||||
providerSpecificFields: (keyof FieldOptions)[] = [
|
||||
'openlibraryId',
|
||||
'asin', 'amazonRating', 'amazonReviewCount',
|
||||
'googleId',
|
||||
'goodreadsId', 'goodreadsRating', 'goodreadsReviewCount',
|
||||
'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount', 'moods', 'tags',
|
||||
'comicvineId',
|
||||
'lubimyczytacId', 'lubimyczytacRating',
|
||||
'ranobedbId', 'ranobedbRating',
|
||||
'audibleId', 'audibleRating', 'audibleReviewCount',
|
||||
'applebooksId', 'applebooksRating', 'applebooksReviewCount',
|
||||
];
|
||||
|
||||
nonProviderSpecificFields: (keyof FieldOptions)[] = [
|
||||
'title', 'subtitle', 'description', 'authors', 'publisher', 'publishedDate',
|
||||
'seriesName', 'seriesNumber', 'seriesTotal', 'isbn13', 'isbn10',
|
||||
'language', 'categories', 'cover', 'pageCount',
|
||||
];
|
||||
|
||||
providers: string[] = [
|
||||
'OpenLibrary',
|
||||
'Amazon',
|
||||
'Google',
|
||||
'GoodReads',
|
||||
'Hardcover',
|
||||
'Comicvine',
|
||||
'Douban',
|
||||
'Lubimyczytac',
|
||||
'Ranobedb',
|
||||
'Audible',
|
||||
'AppleBooks'
|
||||
];
|
||||
providersWithClear: string[] = [
|
||||
'Clear All',
|
||||
'OpenLibrary',
|
||||
'Amazon',
|
||||
'Google',
|
||||
'GoodReads',
|
||||
'Hardcover',
|
||||
'Comicvine',
|
||||
'Douban',
|
||||
'Lubimyczytac',
|
||||
'Ranobedb',
|
||||
'Audible',
|
||||
'AppleBooks'
|
||||
];
|
||||
readonly providerSpecificFields = computed<(keyof FieldOptions)[]>(() => [
|
||||
...this.providerFields.fields().map(field => field.name),
|
||||
'moods', 'tags',
|
||||
]);
|
||||
|
||||
readonly fields = computed<(keyof FieldOptions)[]>(() => [...this.nonProviderSpecificFields, ...this.providerSpecificFields()]);
|
||||
|
||||
readonly providerOptions = computed(() => this.sources.enabledProviders().map(provider => ({
|
||||
value: provider.id,
|
||||
label: this.t.translate(provider.labelKey, {}, this.activeLang()),
|
||||
})));
|
||||
readonly providerOptionsWithClear = computed(() => [
|
||||
{value: 'Clear All', label: 'Clear All'},
|
||||
...this.providerOptions(),
|
||||
]);
|
||||
|
||||
providerOptionsFor(selected: string | null) {
|
||||
const enabled = this.providerOptions();
|
||||
if (!selected || enabled.some(option => option.value === selected)) return enabled;
|
||||
|
||||
const provider = this.sources.providers().find(provider => provider.id === selected);
|
||||
const label = provider ? this.t.translate(provider.labelKey, {}, this.activeLang()) : selected;
|
||||
return [...enabled, {
|
||||
value: selected,
|
||||
label: this.t.translate('metadata.advancedFetchOptions.inactiveProvider', {provider: label}, this.activeLang()),
|
||||
disabled: true,
|
||||
}];
|
||||
}
|
||||
|
||||
refreshCovers: boolean = false;
|
||||
mergeCategories: boolean = false;
|
||||
@@ -110,55 +93,17 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
|
||||
bulkP3: string | null = null;
|
||||
bulkP4: string | null = null;
|
||||
|
||||
private messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private justSubmitted = false;
|
||||
|
||||
private providerSpecificFieldsList = [
|
||||
// OpenLibrary
|
||||
'openlibraryId',
|
||||
|
||||
// Amazon
|
||||
'asin', 'amazonRating', 'amazonReviewCount',
|
||||
|
||||
// Google
|
||||
'googleId',
|
||||
|
||||
// Goodreads
|
||||
'goodreadsId', 'goodreadsRating', 'goodreadsReviewCount',
|
||||
|
||||
// Hardcover
|
||||
'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount',
|
||||
|
||||
// Comicvine
|
||||
'comicvineId',
|
||||
|
||||
// Lubimyczytac
|
||||
'lubimyczytacId', 'lubimyczytacRating',
|
||||
|
||||
// Ranobedb
|
||||
'ranobedbId', 'ranobedbRating',
|
||||
|
||||
// Audible
|
||||
'audibleId', 'audibleRating', 'audibleReviewCount',
|
||||
|
||||
// Apple Books
|
||||
'applebooksId', 'applebooksRating', 'applebooksReviewCount',
|
||||
|
||||
// Generic provider-specific
|
||||
'moods', 'tags'
|
||||
];
|
||||
|
||||
private initializeFieldOptions(): FieldOptions {
|
||||
return this.fields.reduce((acc, field) => {
|
||||
return this.fields().reduce((acc, field) => {
|
||||
acc[field] = {p1: null, p2: null, p3: null, p4: null};
|
||||
return acc;
|
||||
}, {} as FieldOptions);
|
||||
}
|
||||
|
||||
private initializeEnabledFields(): Record<keyof FieldOptions, boolean> {
|
||||
return this.fields.reduce((acc, field) => {
|
||||
return this.fields().reduce((acc, field) => {
|
||||
acc[field] = true;
|
||||
return acc;
|
||||
}, {} as Record<keyof FieldOptions, boolean>);
|
||||
@@ -172,7 +117,7 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
|
||||
this.replaceMode = this.currentMetadataOptions.replaceMode || 'REPLACE_MISSING';
|
||||
|
||||
const backendFieldOptions = this.deepCloneFieldOptions(this.currentMetadataOptions.fieldOptions as FieldOptions || {});
|
||||
for (const field of this.fields) {
|
||||
for (const field of this.fields()) {
|
||||
if (!backendFieldOptions[field]) {
|
||||
backendFieldOptions[field] = {p1: null, p2: null, p3: null, p4: null};
|
||||
} else {
|
||||
@@ -191,7 +136,7 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
|
||||
|
||||
private deepCloneFieldOptions(fieldOptions: FieldOptions): FieldOptions {
|
||||
const cloned = {} as FieldOptions;
|
||||
for (const field of this.fields) {
|
||||
for (const field of this.fields()) {
|
||||
cloned[field] = {
|
||||
p1: fieldOptions[field]?.p1 || null,
|
||||
p2: fieldOptions[field]?.p2 || null,
|
||||
@@ -237,7 +182,7 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
|
||||
}
|
||||
}
|
||||
|
||||
setBulkProvider(priority: 'p1' | 'p2' | 'p3' | 'p4', provider: string | null): void {
|
||||
setBulkProvider(priority: 'p1' | 'p2' | 'p3' | 'p4', provider: MetadataProviderId | 'Clear All' | null): void {
|
||||
if (!provider) return;
|
||||
|
||||
const value = provider === 'Clear All' ? null : provider;
|
||||
@@ -303,37 +248,19 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
|
||||
'pageCount': 'Page Count',
|
||||
'rating': 'Rating',
|
||||
'reviewCount': 'Review Count',
|
||||
'openlibraryId': 'OpenLibrary ID',
|
||||
'asin': 'Amazon ASIN',
|
||||
'goodreadsId': 'Goodreads ID',
|
||||
'comicvineId': 'Comicvine ID',
|
||||
'hardcoverId': 'Hardcover ID',
|
||||
'hardcoverBookId': 'Hardcover Book ID',
|
||||
'googleId': 'Google Books ID',
|
||||
'amazonRating': 'Amazon Rating',
|
||||
'amazonReviewCount': 'Amazon Review Count',
|
||||
'goodreadsRating': 'Goodreads Rating',
|
||||
'goodreadsReviewCount': 'Goodreads Review Count',
|
||||
'hardcoverRating': 'Hardcover Rating',
|
||||
'hardcoverReviewCount': 'Hardcover Review Count',
|
||||
'lubimyczytacId': 'Lubimyczytac ID',
|
||||
'lubimyczytacRating': 'Lubimyczytac Rating',
|
||||
'ranobedbId': 'Ranobedb ID',
|
||||
'ranobedbRating': 'Ranobedb Rating',
|
||||
'audibleId': 'Audible ID',
|
||||
'audibleRating': 'Audible Rating',
|
||||
'audibleReviewCount': 'Audible Review Count',
|
||||
'applebooksId': 'Apple Books ID',
|
||||
'applebooksRating': 'Apple Books Rating',
|
||||
'applebooksReviewCount': 'Apple Books Review Count',
|
||||
'moods': 'Moods (Hardcover)',
|
||||
'tags': 'Tags (Hardcover)'
|
||||
};
|
||||
|
||||
return fieldLabels[field] || field.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()).trim();
|
||||
if (fieldLabels[field]) return fieldLabels[field];
|
||||
|
||||
const providerField = this.providerFields.fields().find(providerField => providerField.name === field);
|
||||
return providerField
|
||||
? this.providerFields.label(providerField.name)
|
||||
: field.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()).trim();
|
||||
}
|
||||
|
||||
isProviderSpecificField(field: keyof FieldOptions): boolean {
|
||||
return this.providerSpecificFieldsList.includes(field as string);
|
||||
return this.providerSpecificFields().includes(field);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-7
@@ -12,21 +12,21 @@
|
||||
|
||||
<div class="section-body">
|
||||
<div class="provider-groups-container">
|
||||
@for (group of providerGroups; track group.labelKey) {
|
||||
@for (group of providerGroups(); track group.label) {
|
||||
<div class="provider-group">
|
||||
<div class="group-header">
|
||||
<span class="group-icon pi pi-database"></span>
|
||||
<h4 class="group-label">{{ getProviderLabel(group.labelKey) }}</h4>
|
||||
<h4 class="group-label">{{ group.label }}</h4>
|
||||
</div>
|
||||
<div class="field-list">
|
||||
@for (field of group.fields; track field) {
|
||||
@for (field of group.fields; track field.name) {
|
||||
<div class="field-item">
|
||||
<p-toggleswitch
|
||||
[inputId]="field"
|
||||
[ngModel]="selectedFields.includes(field)"
|
||||
(ngModelChange)="toggleField(field, $event)">
|
||||
[inputId]="field.name"
|
||||
[ngModel]="selectedFields.includes(field.name)"
|
||||
(ngModelChange)="toggleField(field.name, $event)">
|
||||
</p-toggleswitch>
|
||||
<label [for]="field">{{ getFieldLabel(field) }}</label>
|
||||
<label [for]="field.name">{{ field.label }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
+8
-3
@@ -64,12 +64,17 @@ describe('MetadataProviderFieldSelectorComponent', () => {
|
||||
}]);
|
||||
});
|
||||
|
||||
it('translates provider and field labels through Transloco', () => {
|
||||
it('groups the provider fields by provider, with translated labels', () => {
|
||||
const fixture = TestBed.createComponent(MetadataProviderFieldSelectorComponent);
|
||||
const component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(component.getProviderLabel('amazon')).toBe('Amazon');
|
||||
expect(component.getFieldLabel('asin')).toBeDefined();
|
||||
const amazon = component.providerGroups().find(group => group.label === 'Amazon');
|
||||
|
||||
expect(amazon?.fields).toEqual([
|
||||
{name: 'asin', label: 'Amazon ASIN'},
|
||||
{name: 'amazonRating', label: 'Amazon Rating'},
|
||||
{name: 'amazonReviewCount', label: 'Amazon Review Count'},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
+22
-38
@@ -1,8 +1,11 @@
|
||||
import {Component, effect, inject, Input} from '@angular/core';
|
||||
import {Component, computed, effect, inject, Input} from '@angular/core';
|
||||
import {toSignal} from '@angular/core/rxjs-interop';
|
||||
import {ToggleSwitch} from '@openng/optimus-ui/toggleswitch';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {AppSettingKey, MetadataProviderSpecificFields} from '../../../../shared/model/app-settings.model';
|
||||
import {MetadataProviderFieldsService, providerFieldRecord} from '../../../../shared/metadata';
|
||||
import {MetadataCatalogService} from '../../../../shared/metadata/metadata-catalog.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
@@ -17,40 +20,25 @@ export class MetadataProviderFieldSelectorComponent {
|
||||
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private t = inject(TranslocoService);
|
||||
private catalog = inject(MetadataCatalogService);
|
||||
private providerFields = inject(MetadataProviderFieldsService);
|
||||
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
|
||||
|
||||
providerGroups: { labelKey: string, fields: string[] }[] = [
|
||||
{labelKey: 'openlibrary', fields: ['openlibraryId']},
|
||||
{labelKey: 'amazon', fields: ['asin', 'amazonRating', 'amazonReviewCount']},
|
||||
{labelKey: 'googleBooks', fields: ['googleId']},
|
||||
{labelKey: 'goodreads', fields: ['goodreadsId', 'goodreadsRating', 'goodreadsReviewCount']},
|
||||
{labelKey: 'hardcover', fields: ['hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount']},
|
||||
{labelKey: 'audible', fields: ['audibleId', 'audibleRating', 'audibleReviewCount']},
|
||||
{labelKey: 'applebooks', fields: ['applebooksId', 'applebooksRating', 'applebooksReviewCount']},
|
||||
{labelKey: 'comicvine', fields: ['comicvineId']},
|
||||
{labelKey: 'lubimyczytac', fields: ['lubimyczytacId', 'lubimyczytacRating']},
|
||||
{labelKey: 'ranobedb', fields: ['ranobedbId', 'ranobedbRating']}
|
||||
];
|
||||
readonly providerGroups = computed(() => {
|
||||
const lang = this.activeLang();
|
||||
return this.catalog.providers()
|
||||
.filter(provider => provider.book)
|
||||
.map(provider => ({
|
||||
label: this.t.translate(provider.labelKey, {}, lang),
|
||||
fields: this.providerFields.fields()
|
||||
.filter(field => field.provider === provider.id)
|
||||
.map(field => ({name: field.name, label: this.providerFields.label(field.name)})),
|
||||
}));
|
||||
});
|
||||
|
||||
getProviderLabel(key: string): string {
|
||||
return this.t.translate('settingsMeta.fieldSelector.providers.' + key);
|
||||
}
|
||||
|
||||
getFieldLabel(field: string): string {
|
||||
return this.t.translate('settingsMeta.fieldSelector.fields.' + field);
|
||||
}
|
||||
|
||||
private readonly allFieldNames: (keyof MetadataProviderSpecificFields)[] = [
|
||||
'openlibraryId',
|
||||
'asin', 'amazonRating', 'amazonReviewCount',
|
||||
'googleId',
|
||||
'goodreadsId', 'goodreadsRating', 'goodreadsReviewCount',
|
||||
'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount',
|
||||
'comicvineId',
|
||||
'lubimyczytacId', 'lubimyczytacRating',
|
||||
'ranobedbId', 'ranobedbRating',
|
||||
'audibleId', 'audibleRating', 'audibleReviewCount',
|
||||
'applebooksId', 'applebooksRating', 'applebooksReviewCount',
|
||||
];
|
||||
private readonly allFieldNames = computed<(keyof MetadataProviderSpecificFields)[]>(
|
||||
() => this.providerFields.fields().map(field => field.name),
|
||||
);
|
||||
|
||||
private readonly syncSettingsEffect = effect(() => {
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
@@ -81,10 +69,6 @@ export class MetadataProviderFieldSelectorComponent {
|
||||
}
|
||||
|
||||
private toFieldState(selectedFields: string[]): MetadataProviderSpecificFields {
|
||||
const fieldState = {} as MetadataProviderSpecificFields;
|
||||
for (const field of this.allFieldNames) {
|
||||
fieldState[field] = selectedFields.includes(field);
|
||||
}
|
||||
return fieldState;
|
||||
return providerFieldRecord(this.providerFields.fields(), field => selectedFields.includes(field.name));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
export interface MetadataProvider {
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
|
||||
import {FetchMetadataRequest} from './fetch-metadata-request.model';
|
||||
|
||||
describe('fetch-metadata-request.model', () => {
|
||||
it('captures the metadata fetch payload shape', () => {
|
||||
const request: FetchMetadataRequest = {
|
||||
bookId: 12,
|
||||
providers: ['google', 'hardcover'],
|
||||
title: 'A Wizard of Earthsea',
|
||||
author: 'Ursula K. Le Guin',
|
||||
isbn: '9780547773742'
|
||||
};
|
||||
|
||||
expect(request.providers).toContain('google');
|
||||
expect(request.bookId).toBe(12);
|
||||
expectTypeOf(request.providers).toEqualTypeOf<string[]>();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
export interface FetchMetadataRequest {
|
||||
bookId: number,
|
||||
providers: string[],
|
||||
title: string,
|
||||
author: string,
|
||||
isbn: string
|
||||
}
|
||||
+38
-37
@@ -1,4 +1,5 @@
|
||||
import {describe, expect, expectTypeOf, it} from 'vitest';
|
||||
import type {MetadataProviderId} from '../../../../shared/metadata/metadata-providers';
|
||||
|
||||
import {
|
||||
FieldOptions,
|
||||
@@ -7,7 +8,7 @@ import {
|
||||
MetadataReplaceMode
|
||||
} from './metadata-refresh-options.model';
|
||||
|
||||
const provider = (value: string | null): FieldProvider => ({
|
||||
const provider = (value: MetadataProviderId | null): FieldProvider => ({
|
||||
p4: value,
|
||||
p3: value,
|
||||
p2: value,
|
||||
@@ -17,46 +18,46 @@ const provider = (value: string | null): FieldProvider => ({
|
||||
describe('metadata-refresh-options.model', () => {
|
||||
it('supports replace-mode driven refresh settings', () => {
|
||||
const fieldOptions: FieldOptions = {
|
||||
openlibraryId: provider('openlibrary'),
|
||||
title: provider('google'),
|
||||
description: provider('google'),
|
||||
authors: provider('google'),
|
||||
categories: provider('google'),
|
||||
cover: provider('google'),
|
||||
subtitle: provider('google'),
|
||||
publisher: provider('google'),
|
||||
publishedDate: provider('google'),
|
||||
seriesName: provider('google'),
|
||||
seriesNumber: provider('google'),
|
||||
seriesTotal: provider('google'),
|
||||
isbn13: provider('google'),
|
||||
isbn10: provider('google'),
|
||||
language: provider('google'),
|
||||
pageCount: provider('google'),
|
||||
asin: provider('google'),
|
||||
goodreadsId: provider('goodreads'),
|
||||
openlibraryId: provider('OpenLibrary'),
|
||||
title: provider('Google'),
|
||||
description: provider('Google'),
|
||||
authors: provider('Google'),
|
||||
categories: provider('Google'),
|
||||
cover: provider('Google'),
|
||||
subtitle: provider('Google'),
|
||||
publisher: provider('Google'),
|
||||
publishedDate: provider('Google'),
|
||||
seriesName: provider('Google'),
|
||||
seriesNumber: provider('Google'),
|
||||
seriesTotal: provider('Google'),
|
||||
isbn13: provider('Google'),
|
||||
isbn10: provider('Google'),
|
||||
language: provider('Google'),
|
||||
pageCount: provider('Google'),
|
||||
asin: provider('Google'),
|
||||
goodreadsId: provider('GoodReads'),
|
||||
comicvineId: provider(null),
|
||||
hardcoverId: provider('hardcover'),
|
||||
hardcoverBookId: provider('hardcover'),
|
||||
googleId: provider('google'),
|
||||
hardcoverId: provider('Hardcover'),
|
||||
hardcoverBookId: provider('Hardcover'),
|
||||
googleId: provider('Google'),
|
||||
lubimyczytacId: provider(null),
|
||||
amazonRating: provider('amazon'),
|
||||
amazonReviewCount: provider('amazon'),
|
||||
goodreadsRating: provider('goodreads'),
|
||||
goodreadsReviewCount: provider('goodreads'),
|
||||
hardcoverRating: provider('hardcover'),
|
||||
hardcoverReviewCount: provider('hardcover'),
|
||||
amazonRating: provider('Amazon'),
|
||||
amazonReviewCount: provider('Amazon'),
|
||||
goodreadsRating: provider('GoodReads'),
|
||||
goodreadsReviewCount: provider('GoodReads'),
|
||||
hardcoverRating: provider('Hardcover'),
|
||||
hardcoverReviewCount: provider('Hardcover'),
|
||||
lubimyczytacRating: provider(null),
|
||||
ranobedbId: provider(null),
|
||||
ranobedbRating: provider(null),
|
||||
audibleId: provider('audible'),
|
||||
audibleRating: provider('audible'),
|
||||
audibleReviewCount: provider('audible'),
|
||||
applebooksId: provider('applebooks'),
|
||||
applebooksRating: provider('applebooks'),
|
||||
applebooksReviewCount: provider('applebooks'),
|
||||
moods: provider('google'),
|
||||
tags: provider('google')
|
||||
audibleId: provider('Audible'),
|
||||
audibleRating: provider('Audible'),
|
||||
audibleReviewCount: provider('Audible'),
|
||||
applebooksId: provider('AppleBooks'),
|
||||
applebooksRating: provider('AppleBooks'),
|
||||
applebooksReviewCount: provider('AppleBooks'),
|
||||
moods: provider('Google'),
|
||||
tags: provider('Google')
|
||||
};
|
||||
|
||||
const options: MetadataRefreshOptions = {
|
||||
@@ -110,7 +111,7 @@ describe('metadata-refresh-options.model', () => {
|
||||
}
|
||||
};
|
||||
|
||||
expect(options.fieldOptions?.title.p4).toBe('google');
|
||||
expect(options.fieldOptions?.title.p4).toBe('Google');
|
||||
expect(options.enabledFields?.subtitle).toBe(false);
|
||||
expectTypeOf(options.replaceMode).toEqualTypeOf<MetadataReplaceMode | undefined>();
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type {MetadataProviderFieldRecord} from '../../../../shared/metadata/metadata-provider-fields';
|
||||
|
||||
export type MetadataReplaceMode = 'REPLACE_ALL' | 'REPLACE_MISSING' | 'REPLACE_WHEN_PROVIDED';
|
||||
|
||||
export interface MetadataRefreshOptions {
|
||||
@@ -22,7 +24,7 @@ export interface FieldProvider {
|
||||
p1: string | null;
|
||||
}
|
||||
|
||||
export interface FieldOptions {
|
||||
interface GenericFieldOptions {
|
||||
title: FieldProvider;
|
||||
description: FieldProvider;
|
||||
authors: FieldProvider;
|
||||
@@ -38,29 +40,8 @@ export interface FieldOptions {
|
||||
isbn10: FieldProvider;
|
||||
language: FieldProvider;
|
||||
pageCount: FieldProvider;
|
||||
openlibraryId: FieldProvider;
|
||||
asin: FieldProvider;
|
||||
goodreadsId: FieldProvider;
|
||||
comicvineId: FieldProvider;
|
||||
hardcoverId: FieldProvider;
|
||||
hardcoverBookId: FieldProvider;
|
||||
googleId: FieldProvider;
|
||||
lubimyczytacId: FieldProvider;
|
||||
amazonRating: FieldProvider;
|
||||
amazonReviewCount: FieldProvider;
|
||||
goodreadsRating: FieldProvider;
|
||||
goodreadsReviewCount: FieldProvider;
|
||||
hardcoverRating: FieldProvider;
|
||||
hardcoverReviewCount: FieldProvider;
|
||||
lubimyczytacRating: FieldProvider;
|
||||
ranobedbId: FieldProvider;
|
||||
ranobedbRating: FieldProvider;
|
||||
audibleId: FieldProvider;
|
||||
audibleRating: FieldProvider;
|
||||
audibleReviewCount: FieldProvider;
|
||||
applebooksId: FieldProvider;
|
||||
applebooksRating: FieldProvider;
|
||||
applebooksReviewCount: FieldProvider;
|
||||
moods: FieldProvider;
|
||||
tags: FieldProvider;
|
||||
}
|
||||
|
||||
export type FieldOptions = GenericFieldOptions & MetadataProviderFieldRecord<FieldProvider>;
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {MetadataProviderService} from './metadata-provider.service';
|
||||
|
||||
describe('MetadataProviderService', () => {
|
||||
let service: MetadataProviderService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
let authService: {getInternalAccessToken: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(() => {
|
||||
authService = {
|
||||
getInternalAccessToken: vi.fn(() => 'token-123'),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
MetadataProviderService,
|
||||
{provide: AuthService, useValue: authService},
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(MetadataProviderService);
|
||||
httpTestingController = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpTestingController.verify();
|
||||
TestBed.resetTestingModule();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('requests provider detail through HTTP endpoints', () => {
|
||||
service.fetchMetadataDetail('google', 'abc123').subscribe();
|
||||
|
||||
const detailRequest = httpTestingController.expectOne(req =>
|
||||
req.url.endsWith('v1/metadata/providers/google/fetch/abc123')
|
||||
);
|
||||
expect(detailRequest.request.method).toBe('GET');
|
||||
detailRequest.flush({});
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {BookMetadata} from '../../book/model/book.model';
|
||||
import {MetadataProvider} from '../model/metadata-provider.model';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class MetadataProviderService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/metadata/providers`;
|
||||
private http = inject(HttpClient);
|
||||
|
||||
fetchMetadataProviders(): Observable<MetadataProvider[]> {
|
||||
return this.http.get<MetadataProvider[]>(`${this.url}`);
|
||||
}
|
||||
|
||||
fetchMetadataDetail(provider: string, providerItemId: string): Observable<BookMetadata> {
|
||||
return this.http.get<BookMetadata>(`${this.url}/${provider}/fetch/${providerItemId}`);
|
||||
}
|
||||
}
|
||||
@@ -35,31 +35,6 @@ describe('SidecarService', () => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('fetches sidecar content for a book', () => {
|
||||
service.getSidecarContent(42).subscribe(response => {
|
||||
expect(response.metadata.title).toBe('Book');
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/sidecar`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({
|
||||
version: '1',
|
||||
generatedAt: '2026-03-26T00:00:00Z',
|
||||
generatedBy: 'test',
|
||||
metadata: {title: 'Book'},
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches the sidecar sync status', () => {
|
||||
service.getSyncStatus(42).subscribe(response => {
|
||||
expect(response).toEqual({status: 'CONFLICT'});
|
||||
});
|
||||
|
||||
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/sidecar/status`);
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({status: 'CONFLICT'});
|
||||
});
|
||||
|
||||
it('exports a sidecar for a book', () => {
|
||||
service.exportToSidecar(42).subscribe(response => {
|
||||
expect(response).toEqual({message: 'ok'});
|
||||
|
||||
@@ -7,78 +7,6 @@ import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {invalidateAllBookCaches, invalidateBooksById} from '../../book/service/legacy-book-cache';
|
||||
import {invalidateAuthorsQuery} from '../../author-browser/service/author-query-cache';
|
||||
|
||||
export interface SidecarCoverInfo {
|
||||
source: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface SidecarSeries {
|
||||
name?: string;
|
||||
number?: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export interface SidecarIdentifiers {
|
||||
asin?: string;
|
||||
goodreadsId?: string;
|
||||
googleId?: string;
|
||||
hardcoverId?: string;
|
||||
comicvineId?: string;
|
||||
lubimyczytacId?: string;
|
||||
ranobedbId?: string;
|
||||
audibleId?: string;
|
||||
applebooksId?: string;
|
||||
openlibraryId?: string;
|
||||
}
|
||||
|
||||
export interface SidecarRating {
|
||||
average?: number;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export interface SidecarRatings {
|
||||
amazon?: SidecarRating;
|
||||
goodreads?: SidecarRating;
|
||||
hardcover?: SidecarRating;
|
||||
lubimyczytac?: SidecarRating;
|
||||
ranobedb?: SidecarRating;
|
||||
audible?: SidecarRating;
|
||||
applebooks?: SidecarRating;
|
||||
}
|
||||
|
||||
export interface SidecarBookMetadata {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
authors?: string[];
|
||||
publisher?: string;
|
||||
publishedDate?: string;
|
||||
description?: string;
|
||||
isbn10?: string;
|
||||
isbn13?: string;
|
||||
language?: string;
|
||||
pageCount?: number;
|
||||
categories?: string[];
|
||||
moods?: string[];
|
||||
tags?: string[];
|
||||
series?: SidecarSeries;
|
||||
identifiers?: SidecarIdentifiers;
|
||||
ratings?: SidecarRatings;
|
||||
ageRating?: number;
|
||||
contentRating?: string;
|
||||
narrator?: string;
|
||||
abridged?: boolean;
|
||||
}
|
||||
|
||||
export interface SidecarMetadata {
|
||||
version: string;
|
||||
generatedAt: string;
|
||||
generatedBy: string;
|
||||
metadata: SidecarBookMetadata;
|
||||
cover?: SidecarCoverInfo;
|
||||
}
|
||||
|
||||
export type SidecarSyncStatus = 'IN_SYNC' | 'OUTDATED' | 'MISSING' | 'CONFLICT' | 'NOT_APPLICABLE';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@@ -87,14 +15,6 @@ export class SidecarService {
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1`;
|
||||
|
||||
getSidecarContent(bookId: number): Observable<SidecarMetadata> {
|
||||
return this.http.get<SidecarMetadata>(`${this.apiUrl}/books/${bookId}/sidecar`);
|
||||
}
|
||||
|
||||
getSyncStatus(bookId: number): Observable<{status: SidecarSyncStatus}> {
|
||||
return this.http.get<{status: SidecarSyncStatus}>(`${this.apiUrl}/books/${bookId}/sidecar/status`);
|
||||
}
|
||||
|
||||
exportToSidecar(bookId: number): Observable<{message: string}> {
|
||||
return this.http.post<{message: string}>(`${this.apiUrl}/books/${bookId}/sidecar/export`, {});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user