Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/FoxxMD/multi-scrobbler. Scrobble plays from multiple sources to multiple clients docs.multi-scrobbler.app
deezer docker jellyfin koito lastfm listenbrainz maloja mopidy mpris music music-assistant plex scrobble self-hosted spotify subsonic tautulli youtube-music
Something went wrong. Try again.
42 kB · 889 lines
TypeScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889import { type ArtistCredit, DEFAULT_MISSING_TYPES, type LifecycleInput, type MissingMbidType, type OptionalCacheUsage, type PlayObject, type TrackMetaIsrc } from "../../../core/Atomic.ts";import { MB_RELEASE_GROUP_SECONDARY_TYPES, mBReleaseSecondaryGroupTypesSchema } from "../vendor/musicbrainz/MusicbrainzTypes.ts";import { type MBReleaseGroupSecondaryType } from "../vendor/musicbrainz/MusicbrainzTypes.ts";import { type MBReleaseGroupPrimaryType } from "../vendor/musicbrainz/MusicbrainzTypes.ts";import { mBReleasePrimaryGroupTypesSchema } from "../vendor/musicbrainz/MusicbrainzTypes.ts";import { type MBReleaseStatus } from "../vendor/musicbrainz/MusicbrainzTypes.ts";import { mBReleaseStatusesSchema } from "../vendor/musicbrainz/MusicbrainzTypes.ts";import { isWhenCondition, testWhenConditions } from "../../utils/PlayTransformUtils.ts";import type {WebhookPayload} from "../infrastructure/config/health/webhooks.ts";import type {ExternalMetadataTerm, PlayTransformMetadataStage} from "../../../core/Transform.ts";import AtomicPartsTransformer from "./AtomicPartsTransformer.ts";import type {TransformerOptions} from "./AbstractTransformer.ts";import { ARTIST_WEIGHT, TITLE_WEIGHT } from "../infrastructure/Atomic.ts";import { DELIMITERS } from '../../../core/Atomic.ts';import { MaybeLogger } from '../MaybeLogger.ts';import { childLogger } from "@foxxmd/logging";import { MusicbrainzApiClientPool, recordingToPlay, type UsingTypes } from "../vendor/musicbrainz/MusicbrainzApiClientPool.ts";import type {IRecordingList, IRecordingMatch} from "musicbrainz-api";import { intersect, missingMbidTypes } from "../../utils.ts";import { removeUndefinedKeys } from '../../../core/DataUtils.ts';import { SimpleError, SkipTransformStageError, StagePrerequisiteError, StageTransformError } from "../errors/MSErrors.ts";import { scoreNormalizedStringsWeighted } from "../../utils/StringUtils.ts";import clone from "clone";import type { Cacheable } from "cacheable";import { splitByFirstRegexFound } from "../../../core/StringUtils.ts";import { nativeParse } from "./NativeTransformer.ts";import { comparePlayArtistsNormalized, scoreTrackWeightedAndNormalized } from "../../utils/PlayComparisonUtils.ts";import type { MusicbrainzTransformerConfig, MusicbrainzTransformerData, SearchType } from "./musicbrainz/MusicbrainzTransformerUtil.ts";import { maybeStringLowerArrayFromString } from "../../utils/ZodUtils.ts";
export const asMissingMbid = (str: string): MissingMbidType => { const clean = str.trim().toLocaleLowerCase(); switch(clean) { case 'track': case 'title': return 'title'; case 'artist': case 'artists': return 'artists'; case 'album': return 'album'; case 'duration': return 'duration' } throw new Error(`MissingMbidType must be one of 'artist' or 'title' or 'album' or 'duration', given: ${clean}`);}
export const asSearchType = (str: string): SearchType => { const clean = str.trim().toLocaleLowerCase(); switch(clean) { case 'artist': case 'artists': return 'artist'; case 'album': return 'album'; case 'freetext': return 'freetext'; case 'basic': return 'basic'; case 'isrc': return 'isrc'; case 'mbidrecording': return 'mbidrecording'; case 'basicorid': case 'basicorids': return 'basicorids'; } throw new Error(`SearchType must be one of 'freetext' | 'album' | 'artist' | 'basic' | 'basicOrids' | 'isrc' | 'mbidRecording' -- given: ${clean}`);}
export interface MusicbrainzTransformerDataStrong extends MusicbrainzTransformerData { searchWhenMissing: MissingMbidType[]
releaseGroupPrimaryTypeAllow?: MBReleaseGroupPrimaryType[] releaseGroupPrimaryTypeDeny?: MBReleaseGroupPrimaryType[] releaseGroupPrimaryTypePriority?: MBReleaseGroupPrimaryType[]
releaseGroupSecondaryTypeAllow?: MBReleaseGroupSecondaryType[] releaseGroupSecondaryTypeDeny?: MBReleaseGroupSecondaryType[] releaseGroupSecondaryTypePriority?: MBReleaseGroupSecondaryType[]
releaseStatusAllow?: MBReleaseStatus[] releaseStatusDeny?: MBReleaseStatus[] releaseStatusPriority?: MBReleaseStatus[]
titleWeight?: number artistWeight?: number albumWeight?: number}
export interface MusicbrainzTransformerDataStage extends MusicbrainzTransformerDataStrong,PlayTransformMetadataStage {}
export type MusicbrainzBestMatch = {play: PlayObject, score: number};
export type RecordingRankedMatched = IRecordingMatch & {rankScore?: number, artistScore?: number, titleScore?: number, albumScore?: number}
export interface IRecordingMSList extends IRecordingList { recordings: RecordingRankedMatched[] freeText?: boolean requestQuery: string requestQueries?: LifecycleInput[]}
export const parseStageConfig = (data: MusicbrainzTransformerData | undefined = {}, logger: MaybeLogger = new MaybeLogger()): MusicbrainzTransformerDataStrong => {
if (data === null || typeof data !== 'object') { throw new Error('Musicbrainz Transformer data should be an object or not defined.'); }
const { releaseGroupPrimaryTypeAllow, releaseGroupPrimaryTypeDeny, releaseGroupPrimaryTypePriority, releaseGroupSecondaryTypeAllow, releaseGroupSecondaryTypeDeny = [MB_RELEASE_GROUP_SECONDARY_TYPES.enum.audiobook], releaseGroupSecondaryTypePriority, releaseStatusAllow, releaseStatusDeny, releaseStatusPriority, releaseCountryAllow, releaseCountryDeny, releaseCountryPriority,
searchWhenMissing, fallbackArtistSearch, searchArtistMethod, fallbackFreeText, fallbackAlbumSearch, searchOrder = [], titleWeight, albumWeight, artistWeight, allowMusicVideo = false, ...rest } = data;
const config: MusicbrainzTransformerDataStrong = { searchWhenMissing: DEFAULT_MISSING_TYPES, score: 90,
releaseGroupPrimaryTypeAllow: mBReleasePrimaryGroupTypesSchema.parse(releaseGroupPrimaryTypeAllow), releaseGroupPrimaryTypeDeny: mBReleasePrimaryGroupTypesSchema.parse(releaseGroupPrimaryTypeDeny), releaseGroupPrimaryTypePriority: mBReleasePrimaryGroupTypesSchema.parse(releaseGroupPrimaryTypePriority),
releaseGroupSecondaryTypeAllow: mBReleaseSecondaryGroupTypesSchema.parse(releaseGroupSecondaryTypeAllow), releaseGroupSecondaryTypeDeny: mBReleaseSecondaryGroupTypesSchema.parse(releaseGroupSecondaryTypeDeny), releaseGroupSecondaryTypePriority: mBReleaseSecondaryGroupTypesSchema.parse(releaseGroupSecondaryTypePriority),
releaseStatusAllow: mBReleaseStatusesSchema.parse(releaseStatusAllow), releaseStatusDeny: mBReleaseStatusesSchema.parse(releaseStatusDeny), releaseStatusPriority: mBReleaseStatusesSchema.parse(releaseStatusPriority),
releaseCountryAllow: maybeStringLowerArrayFromString.parse(releaseCountryAllow), releaseCountryDeny: maybeStringLowerArrayFromString.parse(releaseCountryDeny), releaseCountryPriority: maybeStringLowerArrayFromString.parse(releaseCountryPriority), allowMusicVideo, ...rest, };
if(searchWhenMissing !== undefined) { config.searchWhenMissing = searchWhenMissing.map(asMissingMbid); }
logger.debug(`Will search if missing: ${config.searchWhenMissing.join(', ')} | Match if (default) score is >= ${config.score}`);
if(allowMusicVideo === false) { logger.debug('Disallowing music videos in results'); }
let soSet = searchOrder.length > 0 ? new Set<SearchType>(searchOrder.map(asSearchType)) : new Set<SearchType>(); const depSearch = [];
// preserve order of search from before searchOrder // by adding fallback properties in same order they were in getTransformerData if(fallbackAlbumSearch === true) { soSet.add('album'); depSearch.push('fallbackAlbumSearch'); }
if(fallbackArtistSearch !== undefined) { const cleanFallback = fallbackArtistSearch; if(!['native','naive'].includes(cleanFallback)) { throw new Error(`fallbackArtistSearch must be one of 'native' or 'naive', given: ${cleanFallback}`); } config.searchArtistMethod = cleanFallback; depSearch.push('fallbackArtistSearch'); soSet.add('artist'); }
if(fallbackFreeText === true) { soSet.add('freetext'); depSearch.push('fallbackFreeText'); }
if(depSearch.length > 0) { logger.warn(`fallback search options are DEPRECATED and will be removed in a future release. Please switch to 'searchOrder'. See Release 0.11.0 for migrating. Deprecated options used: ${depSearch.join(',')}`); if(depSearch.includes('fallbackArtistSearch')){ logger.warn(`'fallbackArtistSearch' is DEPRECATED and will removed in a future release. Please switch to 'searchOrder' with 'artist', and 'searchArtistMethod' for naive/native. See Release 0.11.0 for migrating.`); } // preserve order of search from before searchOrder // where isrc/basic ran before fallbacks // -- only add here if we know any fallbacks were used soSet = new Set<SearchType>(['isrc','basic', ...soSet]); }
if(soSet.has('artist') && config.searchArtistMethod === undefined) { const cleanFallback = (searchArtistMethod ?? 'native'); if(!['native','naive'].includes(cleanFallback)) { throw new Error(`searchArtistMethod must be one of 'native' or 'naive', given: ${cleanFallback}`); } config.searchArtistMethod = cleanFallback; logger.debug(`Artist search using${searchArtistMethod === undefined ? ' default' : ''} '${config.searchArtistMethod}' method`); }
const so = Array.from(soSet); const soHint: string[] = []; for(const s of so) { if(s === 'artist') { soHint.push(`artist (${config.searchArtistMethod})`); } else { soHint.push(s); } } if(so.length > 0) { logger.debug(`Search Order => ${soHint.join(' | ')}`); config.searchOrder = so; } else { logger.debug(`Search Order => default (isrc, basic) or stage default`); }
for(const [k,v] of Object.entries(config)) { if(k.includes('release') && v !== undefined) { logger.debug(`${k}: ${Array.isArray(v) ? v.join(' | ') : v}`); } }
if(titleWeight !== undefined) { config.titleWeight = titleWeight === true ? TITLE_WEIGHT : titleWeight; } if(artistWeight !== undefined) { config.artistWeight = artistWeight === true ? ARTIST_WEIGHT : artistWeight; } if(albumWeight !== undefined) { config.albumWeight = albumWeight === true ? 0.3 : albumWeight; }
if(albumWeight !== undefined || titleWeight !== undefined || artistWeight !== undefined) { logger.debug(`Ranking matches based on scrobble text. Weights => Title ${config.titleWeight} | Artist ${config.artistWeight} | Album ${config.albumWeight}`); }
return config;}
export default class MusicbrainzTransformer extends AtomicPartsTransformer<ExternalMetadataTerm, PlayObject, MusicbrainzTransformerDataStage> {
declare config: MusicbrainzTransformerConfig;
protected defaults!: MusicbrainzTransformerDataStrong;
protected api!: MusicbrainzApiClientPool; protected clientCache?: Cacheable;
public constructor(config: MusicbrainzTransformerConfig, options: TransformerOptions & {clientCache?: Cacheable}) { super(config, options); this.clientCache = options.clientCache; this.staggerOpts = { initialInterval: 0, maxRandomStagger: 100 } }
protected async doBuildInitData(): Promise<true | string | undefined> { this.defaults = parseStageConfig(this.config.defaults, childLogger(this.logger, 'Defaults'));
this.api = new MusicbrainzApiClientPool(this.config.name, {apis: this.config.data?.apis ?? [{enable: true}]}, { logger: this.logger, cache: this.clientCache, logUrl: this.config.options?.logUrl });
return true; }
protected doParseConfig(data: MusicbrainzTransformerDataStage) { if (data.type.toLocaleLowerCase().trim() !== 'musicbrainz') { throw new Error(`Musicbrainz Transformer is only usable with 'musicbrinz' type stages`); }
const stage: MusicbrainzTransformerDataStage = { ...data, ...parseStageConfig(data), type: 'musicbrainz' }
for (const k of ['artists', 'albumArtists', 'title', 'album', 'meta', 'duration'] as const) { if (!(k in stage)) { stage[k] = true; continue; } if (Array.isArray(stage[k])) { throw new Error(`${k} must be a boolean or when object`); } if (typeof stage[k] === 'boolean') { continue; } if (typeof stage[k] === 'object' && !isWhenCondition(stage[k])) { throw new Error(`${k} is not a valid when object`); } } return stage; }
public async handlePreFetch(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage): Promise<void> { const { searchWhenMissing = this.defaults.searchWhenMissing, forceSearch = this.defaults.forceSearch ?? false, logPreMbid = this.defaults.logPreMbid ?? false } = stageConfig;
if(logPreMbid) { const a = play.data.meta?.brainz?.artist; const parts: string[] = [ `Recording ${play.data.meta?.brainz?.recording ?? '(None)'}`, `Release ${play.data.meta?.brainz?.album ?? '(None)'}`, `Artists ${a === undefined || a.length === 0 ? '(None)' : a.join(', ')}`, `ISRC ${play.data.isrc ?? '(None)'}` ]; this.logger.debug(`Original MBIDS => ${parts.join(' | ')}`); }
const missing = missingMbidTypes(play); if(intersect(searchWhenMissing, missing).length > 0) { this.logger.debug(`Desired MBIDs for ${searchWhenMissing.join(',')} and Play is missing: ${missing.join(', ')}`); } else if(forceSearch) { this.logger.debug(`All desired MBIDs (${searchWhenMissing.join(',')}) exist but forceSearch = true`); } else { throw new SkipTransformStageError(`No desired MBIDs (${searchWhenMissing.join(',')}) are missing`, {shortStack: true}); } }
public async getTransformerData(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts?: OptionalCacheUsage): Promise<IRecordingMSList> { const { // preserve order of search from before searchOrder searchOrder = this.defaults.searchOrder ?? ['isrc', 'basic'] } = stageConfig; let results!: IRecordingMSList; const queries: LifecycleInput[] = [];
for(const searchType of searchOrder) { try { switch(searchType) { case 'isrc': results = (await this.searchByIsrc(play, stageConfig, opts)); break; case 'album': results = (await this.searchByAlbum(play, stageConfig, opts)); break; case 'artist': results = (await this.searchByArtist(play, stageConfig, opts)); break; case 'basic': results = (await this.searchByBasicFields(play, stageConfig, opts)); break; case 'freetext': results = (await this.searchByFreeText(play, stageConfig, opts)); break; case 'basicorids': results = (await this.searchByBasicFieldsOrMBIDs(play, stageConfig, opts)); break; case 'mbidrecording': results = (await this.searchByRecordingMbid(play, stageConfig, opts)); break; } queries.push({type: `mbQuery-${searchType}${results.recordings.length === 0 ? '-empty' : ''}`, input: results.requestQuery}); if(results.recordings.length === 0) { this.logger.debug(`'${searchType}' search type returned no matches`); } else { break; } } catch (e) { if(e instanceof SearchPrerequisiteError) { queries.push({type: `mbQuery-${searchType}-prereqFailure`, input: `Search type ${searchType} did not meet prerequesites: ${e.message}`}); this.logger.debug(`Search type ${searchType} did not meet prerequesites: ${e.message}`); } else { // we should be catching any unrecoverable errors in api calls // so we should only get here if something truly bad has happened // and we probably don't want to try additional api calls throw new StageTransformError('Search Error', 'Unexpected error occurred while getting musicbrainz recordings', {cause: e, inputs: queries}); } } }
return {...results, requestQueries: queries}; }
public async searchByBasicFields(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { this.logger.debug({labels: ['Basic Search']}, 'Searching by artist/album/track'); return await this.api.searchByRecording(play, opts); }
public async searchByBasicFieldsOrMBIDs(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { const using: UsingTypes[] = []; const { data: { meta: { brainz = {} } = {} } = {} } = play;
if(brainz.recording !== undefined) { using.push('mbidrecording'); } else if(brainz.track !== undefined) { using.push('mbidtrack'); } else { using.push('title'); } using.push(brainz.album !== undefined ? 'mbidrelease' : 'album'); using.push((brainz.artist ?? []).length > 0 ? 'mbidartist' : 'artist');
this.logger.debug({labels: ['Basic Or MBID Search']}, `Searching using ${using.join(', ')}}`); return await this.api.searchByRecording(play, {using, ...opts}); }
public async searchByIsrc(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { if(play.data.isrc !== undefined) { this.logger.debug({labels: ['ISRC Search']},'Searching with ISRC'); return await this.api.searchByRecording(play, {using: ['isrc'], ...opts}); } throw new SearchPrerequisiteError('Play does not have ISRC'); }
public async searchByRecordingMbid(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { if(play.data.meta?.brainz?.recording !== undefined) { this.logger.debug({labels: ['MBID Search']},'Searching with Recording MBID'); return await this.api.searchByRecording(play, {using: ['mbidrecording'], ...opts}); } throw new SearchPrerequisiteError('Play does not have recording MBID'); }
public async searchByAlbum(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { // possibly the artist is incorrect (may be combined as one string) // if we have an album we can likely still get a decent hit w/o using artist if(play.data.album !== undefined && play.data.artists !== undefined && play.data.artists.length > 0) { this.logger.debug({labels: ['Album Search']},'Searching with only track+album'); return await this.api.searchByRecording(play, {using: ['title','album'], ...opts}); } if(play.data.album === undefined) { throw new SearchPrerequisiteError('Play does not have an album'); } if(play.data.artists === undefined) { throw new SearchPrerequisiteError('Play does not have any artists'); } // only other possibility is artists is empty throw new SearchPrerequisiteError('Play does not have any artists'); }
public async searchByArtist(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { const { searchArtistMethod = this.defaults.searchArtistMethod, } = stageConfig; if(play.data.artists === undefined) { throw new SearchPrerequisiteError('Play does not have any artists'); } if(play.data.artists.length > 1) { throw new SearchPrerequisiteError('Play has more than one artist already'); } if(play.data.artists.length === 0) { throw new SearchPrerequisiteError('Play does not have any artists'); } // if only one artist // then its likely artist string is combined if(searchArtistMethod === 'naive') { // try a naive split using any common delimiter found and use the first value as artist // -- this will likely result in a less accurate match but at least it might find something // -- usually the "primary artist" is listed first in a combined artist string so cross your fingers this works const naiveSplit = splitByFirstRegexFound(play.data.artists[0].name, [play.data.artists[0].name]).map(x => x.trim()); if(naiveSplit.length > 1) { this.logger.debug({labels: ['Parsed Artist Search']},'Searching with track + first value from artist string split'); return await this.api.searchByRecording({...play, data: { ...play.data, artists: [{name: naiveSplit[0]}] }}, {using: ['title','artist']}); } throw new SearchPrerequisiteError('Naive parsing did not produce multiple artists'); } if(searchArtistMethod === 'native') { // use MS native parsing to extract artists from artist string and title // -- cleaning title is aggressive but at this point MB has not found anything which means its likely not "proper" // IE "My Track (Cool Remix)" is a proper recording name but "My Track (feat. Someone)" is not bc MB would have removed the joiner from the name // so we do the same to hopefully get a match // // ...additionally, since MB hasn't found anything with single artist string its likely the artist name does not have a common delimiter as part of their proper name // IE "Crosby, Stills, Nash & Young" is a proper artist name with delimiters included but "My Artist & My Feat Artists" is not // so we split out all artists by all found delimiters const nativePlay = nativeParse(play, {titleClean: true, delimiters: DELIMITERS}); this.logger.debug({labels: ['Parsed Artist Search']},'Searching with aggressive native parsing'); return await this.api.searchByRecording(nativePlay, {using: ['title','artist'], ...opts}); } throw new SearchPrerequisiteError(`Unknown searchArtistMethod '${searchArtistMethod}'`); }
public async searchByFreeText(play: PlayObject, stageConfig: MusicbrainzTransformerDataStage, opts: OptionalCacheUsage = {}): Promise<IRecordingMSList> { this.logger.debug({labels: ['Freetext Search']},'Trying freetext search'); const results = await this.api.searchByRecording(play, {freetext: true, ...opts}) as IRecordingMSList; results.freeText = true; return results; }
public async handlePostFetch(play: PlayObject, transformData: IRecordingMSList, stageConfig: MusicbrainzTransformerDataStage): Promise<PlayObject> { // if all searches fail prereqs then no recording lists are assigned to results if(transformData.recordings === undefined) { throw new StagePrerequisiteError('All search prerequisites failed, Musicbrainz API could not be searched with the given searchOrder options', { shortStack: true, inputs: transformData.requestQueries }); } if(transformData.recordings.length === 0) { throw new StagePrerequisiteError('No matches returned from Musicbrainz API', {shortStack: true, inputs: transformData.requestQueries}); }
const { score = this.defaults.score ?? 90, allowMusicVideo = this.defaults.allowMusicVideo ?? false } = stageConfig;
// if brainz meta contains track MBID then we should be able to get the exact release let explicitList: IRecordingMatch[]; let filtered: boolean; [explicitList, filtered] = filterByExplicitTrackMbid(transformData.recordings, play); if(filtered) { this.logger.debug(`Found exact release using track MBID`); return recordingToPlay(explicitList[0], {ignoreVA: stageConfig.ignoreVA}); } [explicitList, filtered] = filterByExplicitReleaseMbid(transformData.recordings, play); if(filtered) { this.logger.debug(`Found exact release using release MBID`); return recordingToPlay(explicitList[0], {ignoreVA: stageConfig.ignoreVA}); }
let filteredList: RecordingRankedMatched[] = transformData.recordings.filter(x => x.score >= score); if(filteredList.length === 0) { throw new StagePrerequisiteError(`All ${transformData.count} fetched matches had a score < ${score}, best match was ${transformData.recordings[0].score}`, {shortStack: true}); } let hadMusicVideo = false; if(allowMusicVideo === false && filteredList.some(x => x.video === true)) { hadMusicVideo = true; filteredList = filteredList.filter(x => x.video !== true); }
const mergedConfig = Object.assign({}, removeUndefinedKeys({...this.defaults}), removeUndefinedKeys({...stageConfig})); filteredList = filterByValidReleaseStatus(filteredList, mergedConfig); filteredList = filterByValidReleaseGroupPrimary(filteredList, mergedConfig); filteredList = filterByValidReleaseGroupSecondary(filteredList, mergedConfig); filteredList = filterByValidReleaseCountry(filteredList, mergedConfig);
if(filteredList.length === 0) { throw new StagePrerequisiteError(`All ${transformData.count} recordings were filtered out by allow/deny release config${hadMusicVideo ? ' and music video filter' : ''}`, {shortStack: true}); }
filteredList = rankReleasesByPriority(filteredList, mergedConfig, play);
this.logger.debug(`${filteredList.length} of ${transformData.count} were valid, filtered matches. Using match with best score of ${filteredList[0].score}`);
const recordingPlay = recordingToPlay(filteredList[0], {ignoreVA: stageConfig.ignoreVA}); recordingPlay.meta.lifecycleInputs = [...(recordingPlay.meta.lifecycleInputs ?? []), ...(transformData.requestQueries ?? []), {type: 'mbRecording', input: filteredList[0]}]; return recordingPlay; }
protected async handleTitle(play: PlayObject, parts: ExternalMetadataTerm, transformData: PlayObject): Promise<string | undefined> { if (parts === false) { return play.data.track; } if (typeof parts === 'object') { if (parts.when !== undefined) { if (!testWhenConditions(parts.when, play, { testMaybeRegex: this.regex.testMaybeRegex })) { this.logger.debug('When condition for track not met, returning original track'); return play.data.track; } } }
return transformData.data.track; } protected async handleArtists(play: PlayObject, parts: ExternalMetadataTerm, transformData: PlayObject): Promise<ArtistCredit[] | undefined> { if (parts === false) { return play.data.artists; } if (typeof parts === 'object') { if (parts.when !== undefined) { if (!testWhenConditions(parts.when, play, { testMaybeRegex: this.regex.testMaybeRegex })) { this.logger.debug('When condition for artists not met, returning original artists'); return play.data.artists; } } }
return transformData.data.artists; } protected async handleAlbumArtists(play: PlayObject, parts: ExternalMetadataTerm, transformData: PlayObject): Promise<ArtistCredit[] | undefined> { if (parts === false) { return play.data.albumArtists; } if (typeof parts === 'object') { if (parts.when !== undefined) { if (!testWhenConditions(parts.when, play, { testMaybeRegex: this.regex.testMaybeRegex })) { this.logger.debug('When condition for albumArtists not met, returning original artists'); return play.data.albumArtists; } } } return transformData.data.albumArtists; } protected async handleAlbum(play: PlayObject, parts: ExternalMetadataTerm, transformData: PlayObject): Promise<string | undefined> { if (parts === false) { return play.data.album; } if (typeof parts === 'object') { if (parts.when !== undefined) { if (!testWhenConditions(parts.when, play, { testMaybeRegex: this.regex.testMaybeRegex })) { this.logger.debug('When condition for album not met, returning original album'); return play.data.album; } } }
return transformData.data.album; } protected async handleDuration(play: PlayObject, parts: ExternalMetadataTerm, transformData: PlayObject): Promise<number | undefined> { if (parts === false || transformData.data.duration === undefined) { return play.data.duration; } if (typeof parts === 'object') { if (parts.when !== undefined) { if (!testWhenConditions(parts.when, play, { testMaybeRegex: this.regex.testMaybeRegex })) { this.logger.debug('When condition for duration not met, returning original duration'); return play.data.duration; } } }
return transformData.data.duration; }
protected async handleMeta(play: PlayObject, parts: ExternalMetadataTerm, transformData: PlayObject): Promise<TrackMetaIsrc | undefined> { if (parts === false) { return play.data.meta; } if (typeof parts === 'object') { if (parts.when !== undefined) { if (!testWhenConditions(parts.when, play, { testMaybeRegex: this.regex.testMaybeRegex })) { this.logger.debug('When condition for duration not met, returning original duration'); return play.data.meta; } } } return removeUndefinedKeys<TrackMetaIsrc>({...transformData.data.meta, isrc: transformData.data.isrc}); }
public async notify(payload: WebhookPayload): Promise<void> { }
}
export const filterByValidReleaseStatus = <T extends IRecordingMatch[]>(list: T, stageConfig: MusicbrainzTransformerDataStage, logger: MaybeLogger = new MaybeLogger()) => { const { releaseStatusAllow = [], releaseStatusDeny = [], releaseAllowEmpty } = stageConfig; if(releaseStatusAllow.length === 0 && releaseStatusDeny.length === 0) { return list; } const releaseFiltered = list.map(x => ({ ...x, releases: x.releases === undefined ? [] : x.releases.filter(y => { if(releaseStatusAllow.length > 0) { return releaseStatusAllow.includes(y.status?.toLocaleLowerCase() as MBReleaseStatus) } return !releaseStatusDeny.includes(y.status?.toLocaleLowerCase() as MBReleaseStatus) }) })); return releaseFiltered.filter(x => ( (list.find(y => y.id === x.id)?.releases ?? []).length === 0 && releaseAllowEmpty ) || x.releases.length > 0);}
export const filterByValidReleaseGroupPrimary = <T extends IRecordingMatch[]>(list: T, stageConfig: MusicbrainzTransformerDataStage, logger: MaybeLogger = new MaybeLogger()) => { const { releaseGroupPrimaryTypeAllow = [], releaseGroupPrimaryTypeDeny = [], releaseAllowEmpty } = stageConfig; if(releaseGroupPrimaryTypeAllow.length === 0 && releaseGroupPrimaryTypeAllow.length === 0) { return list; } const releaseFiltered = list.map(x => ({ ...x, releases: x.releases === undefined ? [] : x.releases.filter(y => { if(releaseGroupPrimaryTypeAllow.length > 0) { return releaseGroupPrimaryTypeAllow.includes(y["release-group"]?.["primary-type"]?.toLocaleLowerCase() as MBReleaseGroupPrimaryType) } return !releaseGroupPrimaryTypeDeny.includes(y["release-group"]?.["primary-type"]?.toLocaleLowerCase() as MBReleaseGroupPrimaryType) }) })); return releaseFiltered.filter(x => ( (list.find(y => y.id === x.id)?.releases ?? []).length === 0 && releaseAllowEmpty ) || x.releases.length > 0);}
export const filterByValidReleaseGroupSecondary = (list: IRecordingMatch[], stageConfig: MusicbrainzTransformerDataStage, logger: MaybeLogger = new MaybeLogger()) => { const { releaseGroupSecondaryTypeAllow = [], releaseGroupSecondaryTypeDeny = [], releaseAllowEmpty } = stageConfig; if(releaseGroupSecondaryTypeAllow.length === 0 && releaseGroupSecondaryTypeDeny.length === 0) { return list; } const releaseFiltered = list.map(x => ({ ...x, releases: x.releases === undefined ? [] : x.releases.filter(y => { if(releaseGroupSecondaryTypeAllow.length > 0) { return intersect(releaseGroupSecondaryTypeAllow, (y["release-group"]?.["secondary-types"] ?? []).map(x => x.toLocaleLowerCase()) as MBReleaseGroupSecondaryType[]).length > 0; } return intersect(releaseGroupSecondaryTypeDeny, (y["release-group"]?.["secondary-types"] ?? []).map(x => x.toLocaleLowerCase()) as MBReleaseGroupSecondaryType[]).length === 0; }) })); return releaseFiltered.filter(x => ( (list.find(y => y.id === x.id)?.releases ?? []).length === 0 && releaseAllowEmpty ) || x.releases.length > 0);}
export const filterByValidReleaseCountry = (list: IRecordingMatch[], stageConfig: MusicbrainzTransformerDataStage, logger: MaybeLogger = new MaybeLogger()) => { const { releaseCountryAllow = [], releaseCountryDeny = [], releaseAllowEmpty } = stageConfig; if(releaseCountryAllow.length === 0 && releaseCountryDeny.length === 0) { return list; } const releaseFiltered = list.map(x => ({ ...x, releases: x.releases === undefined ? [] : x.releases.filter(y => { if(releaseCountryAllow.length > 0) { return releaseCountryAllow.includes(y.country?.toLocaleLowerCase()) } return !releaseCountryDeny.includes(y.country?.toLocaleLowerCase()) }) })); return releaseFiltered.filter(x => ( (list.find(y => y.id === x.id)?.releases ?? []).length === 0 && releaseAllowEmpty ) || x.releases.length > 0);}
export const filterByExplicitTrackMbid = (list: IRecordingMatch[], play: PlayObject): [IRecordingMatch[], boolean] => { const trackMbid = play.data.meta?.brainz?.track; if (trackMbid === undefined) { return [list, false]; } let recMatch: IRecordingMatch | undefined, releaseMatchId: string; for (const rec of list) { if (recMatch !== undefined) { break; } for (const rel of rec.releases ?? []) { if (rel.media.some(x => { if(x.tracks !== undefined) { return x.tracks.some(y => y.id === trackMbid); } if(x.track !== undefined) { return x.track.some(y => y.id === trackMbid); } return false; })) { releaseMatchId = rel.id; recMatch = rec; break; } } } if (recMatch !== undefined) { const r = structuredClone(recMatch); r.releases = (r.releases ?? []).filter(x => x.id === releaseMatchId); return [[r], true]; } return [list, false];}
export const filterByExplicitReleaseMbid = (list: IRecordingMatch[], play: PlayObject): [IRecordingMatch[], boolean] => { const albumMbid = play.data.meta?.brainz?.album; if (albumMbid === undefined) { return [list, false]; } let recMatch: IRecordingMatch | undefined, releaseMatchId: string; for (const rec of list) { if (recMatch !== undefined) { break; } for (const rel of rec.releases ?? []) { if(rel.id === albumMbid) { releaseMatchId = rel.id; recMatch = rec; } } } if (recMatch !== undefined) { const r = structuredClone(recMatch); r.releases = (r.releases ?? []).filter(x => x.id === releaseMatchId); return [[r], true]; } return [list, false];}
export const rankReleasesByPriority = (list: IRecordingMatch[], stageConfig: MusicbrainzTransformerDataStage, play: PlayObject, logger: MaybeLogger = new MaybeLogger()): RecordingRankedMatched[] => { const { releaseStatusPriority = [], releaseGroupPrimaryTypePriority = [], releaseGroupSecondaryTypePriority = [], releaseCountryPriority = [], albumWeight = 0, titleWeight = 0, artistWeight = 0 } = stageConfig;
// reverse order so that "highest" priority (first in user list) ends up with the highest index, that we use as score const groupPrimaryPriority = [...releaseGroupPrimaryTypePriority].reverse(), groupSecPriority = [...releaseGroupSecondaryTypePriority].reverse(), countryPriority = [...releaseCountryPriority].reverse(), statusPriority = [...releaseStatusPriority].reverse();
const cList = clone(list) as RecordingRankedMatched[]; const rankedList = cList.map((x) => { let artistScore = 0; if(artistWeight !== 0) { const artistRes = comparePlayArtistsNormalized(play, recordingToPlay(x)); artistScore = artistRes[0] * (artistWeight + (artistRes[1] > 0 ? 0.05 : 0)); } const releases = (x.releases ?? []).map((a) => { const statAScore = statusPriority.findIndex(x => a.status !== undefined && x === a.status.toLocaleLowerCase()) + 1; const grpPAScore = groupPrimaryPriority.findIndex(x => x === a["release-group"]?.["primary-type"]?.toLocaleLowerCase()) + 1; const grpSAScore = (a["release-group"]?.["secondary-types"] ?? []).reduce((acc: number, curr: string) => acc + groupSecPriority.findIndex(x => x === (curr as MBReleaseGroupSecondaryType).toLocaleLowerCase()) + 1,0); const countryAScore = countryPriority.findIndex(x => a.country === undefined ? false : x === a.country.toLocaleLowerCase()) + 1; const compareScore = scoreNormalizedStringsWeighted(play.data.album, a.title, albumWeight, albumWeight !== 0 ? 0.05 : 0); return { ...a, albumScore: statAScore + grpPAScore + grpSAScore + countryAScore + compareScore, albumCompareScore: compareScore }; }); releases.sort((a, b) => b.albumScore - a.albumScore); let albumScore = 0; if(releases.length > 0) { albumScore = releases[0].albumCompareScore; } const titleScore = titleWeight === 0 ? 0 : scoreTrackWeightedAndNormalized(play.data.track ?? '', x.title, titleWeight, {exact: 0.05, naive: 0.03})[0];
return { ...x, titleScore, artistScore, albumScore, rankScore: titleScore + artistScore + albumScore, releases } }); rankedList.sort((a, b) => b.rankScore - a.rankScore) return rankedList;};
export class SearchPrerequisiteError extends SimpleError { name = 'Search Prerequistie Failure';}