-
Notifications
You must be signed in to change notification settings - Fork 7
/
mod.ts
212 lines (180 loc) · 6.47 KB
/
mod.ts
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
import type { Artist, BeatportNextData, BeatportRelease, Release, Track } from './json_types.ts';
import type { ArtistCreditName, EntityId, HarmonyRelease, HarmonyTrack, LinkType } from '@/harmonizer/types.ts';
import { CacheEntry, MetadataProvider, ReleaseLookup } from '@/providers/base.ts';
import { DurationPrecision, FeatureQuality, FeatureQualityMap } from '@/providers/features.ts';
import { parseHyphenatedDate, PartialDate } from '@/utils/date.ts';
import { ProviderError, ResponseError } from '@/utils/errors.ts';
import { extractTextFromHtml } from '@/utils/html.ts';
export default class BeatportProvider extends MetadataProvider {
readonly name = 'Beatport';
readonly supportedUrls = new URLPattern({
hostname: 'www.beatport.com',
pathname: '/:type(artist|label|release)/:slug/:id',
});
readonly features: FeatureQualityMap = {
'cover size': 1400,
'duration precision': DurationPrecision.MS,
'GTIN lookup': FeatureQuality.EXPENSIVE,
'MBID resolving': FeatureQuality.PRESENT,
'release label': FeatureQuality.GOOD,
};
readonly entityTypeMap = {
artist: 'artist',
label: 'label',
release: 'release',
};
readonly releaseLookup = BeatportReleaseLookup;
readonly launchDate: PartialDate = {
year: 2005,
month: 1,
day: 7,
};
readonly baseUrl = 'https://www.beatport.com';
constructUrl(entity: EntityId): URL {
return new URL([entity.type, entity.slug ?? '-', entity.id].join('/'), this.baseUrl);
}
extractEmbeddedJson<Data>(webUrl: URL, maxTimestamp?: number): Promise<CacheEntry<Data>> {
return this.fetchJSON<Data>(webUrl, {
policy: { maxTimestamp },
responseMutator: async (response) => {
const html = await response.text();
const nextData = extractTextFromHtml(
html,
/<script(?=[^>]+?id=["']__NEXT_DATA__["'])(?=[^>]+?type=["']application\/json["'])[^>]+?>(.+?)<\/script>/i,
);
if (nextData) {
return new Response(nextData, response);
}
throw new ResponseError(this.name, 'Failed to extract embedded JSON', webUrl);
},
});
}
}
export class BeatportReleaseLookup extends ReleaseLookup<BeatportProvider, Release> {
constructReleaseApiUrl(): URL | undefined {
return undefined;
}
async getRawRelease(): Promise<BeatportRelease> {
let releaseId = this.lookup.value;
if (this.lookup.method === 'gtin') {
const id = await this.searchReleaseByGtin(this.lookup.value);
if (!id) {
throw new ProviderError(this.provider.name, 'Search returned no matching results');
}
releaseId = id;
}
const webUrl = this.provider.constructUrl({ id: releaseId, type: 'release' });
const { content: data, timestamp } = await this.provider.extractEmbeddedJson<BeatportNextData>(
webUrl,
this.options.snapshotMaxTimestamp,
);
this.updateCacheTime(timestamp);
return this.extractRawRelease(data);
}
async searchReleaseByGtin(gtin: string): Promise<string | undefined> {
const webUrl = new URL('search', this.provider.baseUrl);
webUrl.searchParams.set('q', gtin);
const { content: data, timestamp } = await this.provider.extractEmbeddedJson<BeatportNextData>(
webUrl,
this.options.snapshotMaxTimestamp,
);
this.updateCacheTime(timestamp);
const result = data.props.pageProps.dehydratedState.queries[0];
if (!('releases' in result.state.data)) {
throw new ProviderError(this.provider.name, 'Failed to extract results from embedded JSON');
}
const release = result.state.data.releases.data.find((r) => r.upc === gtin);
return release?.release_id.toString();
}
convertRawRelease(rawRelease: BeatportRelease): HarmonyRelease {
this.id = rawRelease.id.toString();
const releaseUrl = this.provider.constructUrl({
id: this.id,
type: 'release',
slug: rawRelease.slug,
});
const linkTypes: LinkType[] = ['paid download'];
// @todo paid streaming is not currently permitted for Beatport links
// see https://tickets.metabrainz.org/browse/STYLE-2141
// if (rawRelease.is_available_for_streaming) {
// linkTypes.push('paid streaming');
//}
return {
title: rawRelease.name,
artists: rawRelease.artists.map(this.makeArtistCreditName.bind(this)),
labels: [{
name: rawRelease.label.name,
catalogNumber: rawRelease.catalog_number,
externalIds: this.provider.makeExternalIds({
type: 'label',
id: rawRelease.label.id.toString(),
slug: rawRelease.label.slug,
}),
}],
gtin: rawRelease.upc ?? undefined,
releaseDate: parseHyphenatedDate(rawRelease.new_release_date),
media: [{
format: 'Digital Media',
tracklist: rawRelease.track_objects.map(this.convertRawTrack.bind(this)),
}],
externalLinks: [{
url: releaseUrl,
types: linkTypes,
}],
status: 'Official',
packaging: 'None',
images: [{
url: new URL(rawRelease.image.uri),
thumbUrl: new URL(rawRelease.image.dynamic_uri.replace('{w}x{h}', '250x250')),
types: ['front'],
}],
info: this.generateReleaseInfo(),
};
}
convertRawTrack(rawTrack: Track, index: number): HarmonyTrack {
let title = rawTrack.name;
if (rawTrack.mix_name !== 'Original Mix') {
title += ` (${rawTrack.mix_name})`;
}
return {
number: index + 1,
title: title,
artists: rawTrack.artists.map(this.makeArtistCreditName.bind(this)),
length: rawTrack.length_ms,
isrc: rawTrack.isrc,
};
}
makeArtistCreditName(artist: Artist): ArtistCreditName {
return {
name: artist.name,
creditedName: artist.name,
externalIds: this.provider.makeExternalIds({
type: 'artist',
id: artist.id.toString(),
slug: artist.slug,
}),
};
}
extractRawRelease(nextData: BeatportNextData): BeatportRelease {
const release = nextData.props.pageProps.release;
if (!release) {
throw new ProviderError(this.provider.name, 'Failed to extract release from embedded JSON');
} else if (release.track_count > 100) {
throw new ProviderError(this.provider.name, 'Releases with more than 100 tracks are not currently supported');
}
const tracksResult = nextData.props.pageProps.dehydratedState.queries[1];
if (!tracksResult || !('results' in tracksResult.state.data)) {
throw new ProviderError(this.provider.name, 'Failed to extract tracks from embedded JSON');
}
const tracks = tracksResult.state.data.results;
// tracks are listed in reverse order
const releaseTracks = release.tracks.slice().reverse().map((url) => {
const track = tracks.find((t) => url === t.url);
if (!track) {
throw new ProviderError(this.provider.name, `Track ${url} not found in embedded JSON`);
}
return track;
});
return { ...release, track_objects: releaseTracks };
}
}