-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmod.ts
More file actions
218 lines (192 loc) · 6.42 KB
/
mod.ts
File metadata and controls
218 lines (192 loc) · 6.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { musicbrainzApiBaseUrl } from '@/config.ts';
import type {
ArtistCreditName,
EntityId,
HarmonyRelease,
HarmonyTrack,
MediumFormat,
ReleaseGroupType,
ReleaseOptions,
ReleaseSpecifier,
} from '@/harmonizer/types.ts';
import {
type ApiQueryOptions,
type CacheEntry,
MetadataApiProvider,
type ProviderOptions,
ReleaseApiLookup,
} from '@/providers/base.ts';
import { DurationPrecision, FeatureQuality, FeatureQualityMap } from '@/providers/features.ts';
import { parseHyphenatedDate } from '@/utils/date.ts';
import { ResponseError } from '@/utils/errors.ts';
import { isDefined } from '@/utils/predicate.ts';
import { ArtistCredit, Release } from '@kellnerd/musicbrainz/api-types';
import { join } from 'std/url/join.ts';
export default class MusicBrainzProvider extends MetadataApiProvider {
constructor(options: ProviderOptions = {}) {
super({
rateLimitInterval: 5000,
concurrentRequests: 5,
...options,
});
if (options.appInfo) {
const { name, version, contact } = options.appInfo;
this.userAgent = `${name}/${version}`;
if (contact) {
this.userAgent += ` ( ${contact} )`;
}
} else {
this.userAgent = 'Harmony';
}
}
readonly name = 'MusicBrainz';
readonly supportedUrls = new URLPattern({
hostname: '{(beta|test).}?musicbrainz.(org|eu)',
pathname: '/:type(artist|release)/:id([0-9a-f-]{36})',
});
override readonly features: FeatureQualityMap = {
'duration precision': DurationPrecision.S_OR_MS,
'GTIN lookup': FeatureQuality.GOOD,
'MBID resolving': FeatureQuality.GOOD,
'release label': FeatureQuality.GOOD,
};
readonly entityTypeMap = {
artist: 'artist',
label: 'label',
release: 'release',
};
releaseLookup(specifier: ReleaseSpecifier, options: ReleaseOptions = {}) {
return new MusicBrainzReleaseLookup(this, specifier, options);
}
readonly apiBaseUrl = musicbrainzApiBaseUrl;
constructUrl(entity: EntityId): URL {
return join('https://musicbrainz.org', entity.type, entity.id);
}
async query<Data>(apiUrl: URL, options: ApiQueryOptions): Promise<CacheEntry<Data>> {
const cacheEntry = await this.fetchJSON<Data>(apiUrl, {
policy: { maxTimestamp: options.snapshotMaxTimestamp },
requestInit: {
headers: {
'Accept': 'application/json',
'User-Agent': this.userAgent,
},
},
});
const { error } = cacheEntry.content as { error?: string };
if (error) {
throw new ResponseError(this.name, error, apiUrl);
}
return cacheEntry;
}
private userAgent: string;
}
export class MusicBrainzReleaseLookup extends ReleaseApiLookup<MusicBrainzProvider, RawRelease> {
constructReleaseApiUrl(): URL {
let url: URL;
if (this.lookup.method === 'id') {
url = join(this.provider.apiBaseUrl, 'release', this.lookup.value);
url.searchParams.set('inc', ['artist-credits', 'labels', 'recordings', 'release-groups'].join('+'));
} else { // if (this.lookup.method === 'gtin')
url = join(this.provider.apiBaseUrl, 'release');
url.searchParams.set('query', `barcode:${this.lookup.value}`);
}
url.searchParams.set('fmt', 'json');
return url;
}
async getRawRelease(): Promise<RawRelease> {
if (this.lookup.method === 'gtin') {
const apiUrl = this.constructReleaseApiUrl();
const { content, timestamp } = await this.provider.query<ReleaseSearchResults>(apiUrl, {
snapshotMaxTimestamp: this.options.snapshotMaxTimestamp,
});
this.updateCacheTime(timestamp);
const { releases } = content;
if (releases.length) {
if (releases.length > 1) {
this.warnMultipleResults(
releases.slice(1).map((release) => this.provider.constructUrl({ id: release.id, type: 'release' })),
);
}
// Perform a regular ID lookup with the found release ID to retrieve complete data.
this.lookup.method = 'id';
this.lookup.value = releases[0].id;
} else {
throw new ResponseError(this.provider.name, 'API returned no results', apiUrl);
}
}
const { content: release, timestamp } = await this.provider.query<RawRelease>(this.constructReleaseApiUrl(), {
snapshotMaxTimestamp: this.options.snapshotMaxTimestamp,
});
this.updateCacheTime(timestamp);
return release;
}
convertRawRelease(rawRelease: RawRelease): HarmonyRelease {
this.entity = {
id: rawRelease.id,
type: 'release',
};
const releaseGroup = rawRelease['release-group'];
const releaseTypes: ReleaseGroupType[] = [...releaseGroup['secondary-types']];
if (releaseGroup['primary-type']) {
releaseTypes.unshift(releaseGroup['primary-type']);
}
const release: HarmonyRelease = {
title: rawRelease.title,
artists: rawRelease['artist-credit'].map(this.convertRawArtist),
gtin: rawRelease.barcode || undefined, // TODO: handle empty barcode
externalLinks: [],
media: rawRelease.media.map((medium) => ({
number: medium.position,
format: medium.format as MediumFormat ?? undefined,
title: medium.title || undefined,
tracklist: medium.tracks?.map<HarmonyTrack>((track) => ({
number: track.number,
title: track.title,
length: track.length ?? undefined,
artists: track['artist-credit'].map(this.convertRawArtist),
recording: { mbid: track.recording.id },
type: track.recording.video ? 'video' : 'audio',
})) ?? [],
})),
releaseDate: parseHyphenatedDate(rawRelease.date ?? ''),
labels: rawRelease['label-info'].map((info) => ({
name: info.label?.name,
catalogNumber: info['catalog-number'] ?? undefined,
mbid: info.label?.id,
})),
status: rawRelease.status ?? undefined,
packaging: rawRelease.packaging ?? undefined,
availableIn: rawRelease['release-events']
?.flatMap((event) => event.area?.['iso-3166-1-codes']).filter(isDefined) ?? [],
releaseGroup: { mbid: releaseGroup.id },
types: releaseTypes,
info: this.generateReleaseInfo(),
};
const { language } = rawRelease['text-representation'];
if (language) {
release.language = { code: language };
}
return release;
}
private convertRawArtist(artistCredit: ArtistCredit): ArtistCreditName {
return {
name: artistCredit.artist.name,
creditedName: artistCredit.name,
mbid: artistCredit.artist.id,
};
}
}
type RawRelease = Release<'artist-credits' | 'labels' | 'recordings' | 'release-groups'>;
interface ReleaseSearchResults {
created: string;
count: number;
offset: number;
releases: ReleaseResult[];
}
// Incomplete, will be replaced by types from @kellnerd/musicbrainz once those exist.
interface ReleaseResult {
/** MBID of the release. */
id: string;
title: string;
barcode: string;
}