-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmod.ts
More file actions
329 lines (281 loc) · 10.7 KB
/
mod.ts
File metadata and controls
329 lines (281 loc) · 10.7 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { availableRegions } from './regions.ts';
import { type ApiQueryOptions, type CacheEntry, MetadataApiProvider, ReleaseApiLookup } from '@/providers/base.ts';
import { DurationPrecision, FeatureQuality, FeatureQualityMap } from '@/providers/features.ts';
import { fillMediumsTracklistGaps } from '@/harmonizer/tracklist_gap.ts';
import { parseISODateTime, PartialDate } from '@/utils/date.ts';
import { isEqualGTIN, isValidGTIN } from '@/utils/gtin.ts';
import type { Collection, Kind, ReleaseResult, Track } from './api_types.ts';
import type {
ArtistCreditName,
Artwork,
ArtworkType,
CountryCode,
EntityId,
GTIN,
HarmonyMedium,
HarmonyRelease,
LinkType,
ReleaseGroupType,
} from '@/harmonizer/types.ts';
// See https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/iTuneSearchAPI
export default class iTunesProvider extends MetadataApiProvider {
readonly name = 'iTunes';
readonly supportedUrls = new URLPattern({
hostname: '{geo.}?(itunes|music).apple.com',
pathname: String.raw`/:region(\w{2})?/:type(album|artist|song|music-video)/:slug?/{id}?:id(\d+)`,
});
override readonly features: FeatureQualityMap = {
'cover size': 3000,
'duration precision': DurationPrecision.MS,
'GTIN lookup': FeatureQuality.PRESENT,
'MBID resolving': FeatureQuality.EXPENSIVE,
};
readonly entityTypeMap = {
artist: 'artist',
release: 'album',
recording: ['song', 'music-video'],
};
override readonly availableRegions = new Set(availableRegions);
readonly releaseLookup = iTunesReleaseLookup;
override readonly launchDate: PartialDate = {
year: 2003,
month: 4,
day: 28,
};
readonly apiBaseUrl = 'https://itunes.apple.com';
/** URLs without specified region implicitly query the US iTunes store. */
readonly defaultRegion: CountryCode = 'US';
constructUrl(entity: EntityId): URL {
const region = entity.region ?? this.defaultRegion;
return new URL([region.toLowerCase(), entity.type, entity.id].join('/'), 'https://music.apple.com');
}
override extractEntityFromUrl(url: URL): EntityId | undefined {
const entity = super.extractEntityFromUrl(url);
if (entity && !entity.region) {
entity.region = this.defaultRegion;
}
return entity;
}
override getLinkTypesForEntity(): LinkType[] {
// There is no way to appropriately determine this for an artist page.
return ['paid streaming'];
}
async query<Data>(apiUrl: URL, options: ApiQueryOptions): Promise<CacheEntry<Data>> {
const cacheEntry = await this.fetchJSON<Data>(apiUrl, {
policy: { maxTimestamp: options.snapshotMaxTimestamp },
});
return cacheEntry;
}
}
export class iTunesReleaseLookup extends ReleaseApiLookup<iTunesProvider, ReleaseResult> {
constructReleaseApiUrl(): URL {
const { method, value, region } = this.lookup;
const lookupUrl = new URL('lookup', this.provider.apiBaseUrl);
const query = new URLSearchParams({
entity: 'song', // include tracks of the release in the response
limit: '200', // number of returned entities (default: 50; maximum: 200)
});
if (method === 'gtin') {
query.append('upc', value);
} else if (method === 'id') {
query.append('id', value);
}
if (region) {
query.append('country', region.toLowerCase());
}
lookupUrl.search = query.toString();
return lookupUrl;
}
protected async getRawRelease(): Promise<ReleaseResult> {
if (!this.options.regions?.size) {
this.options.regions = new Set([this.provider.defaultRegion]);
}
return await this.queryAllRegions<ReleaseResult>({
isValidData: (data) => Boolean(data?.resultCount),
});
}
protected convertRawRelease(data: ReleaseResult): HarmonyRelease {
// API sometimes also returns other release variants for GTIN lookups, only use the first collection result.
const collections = data.results.filter((result) => result.wrapperType === 'collection') as Collection[];
let collection = collections[0];
if (collections.length > 1 && this.lookup.method === 'gtin') {
// Try to select the correct collection by GTIN instead, if applicable.
const lookupGtin = this.lookup.value;
collection = collections.find((candidate) => {
const gtin = this.extractGTINFromUrl(candidate.artworkUrl100);
return gtin ? isEqualGTIN(gtin, lookupGtin) : false;
}) ?? collection;
}
this.entity = {
id: collection.collectionId.toString(),
type: 'album',
region: this.lookup.region,
};
// Skip bonus items like booklets.
const validTrackKinds: Kind[] = ['song', 'music-video'];
const tracks = data.results.filter((result) =>
result.wrapperType === 'track' && 'collectionId' in result && result.collectionId === collection.collectionId &&
validTrackKinds.includes(result.kind)
) as Track[];
// Warn about releases without returned tracks.
if (!tracks.length) {
this.addMessage('The API returned no tracks, which usually happens for streaming-only releases', 'warning');
}
// Warn about results which belong to a different collection.
const skippedResults = data.results.filter((result) =>
'collectionId' in result && result.collectionId !== collection.collectionId
) as Array<Collection | Track>;
if (skippedResults.length) {
const uniqueSkippedIds = [...new Set(skippedResults.map((result) => result.collectionId))];
const skippedUrls = uniqueSkippedIds.map((id) =>
this.cleanViewUrl(skippedResults.find((result) => result.collectionId === id)!.collectionViewUrl)
);
this.warnMultipleResults(skippedUrls);
}
const { title, types } = this.getTypesFromTitle(collection.collectionName);
const linkTypes: LinkType[] = [];
if (collection.collectionPrice) {
// A missing price might also indicate that the release date is in the future,
// but then it is technically also not yet available for download.
linkTypes.push('paid download');
}
if (tracks.every((track) => track.isStreamable || track.kind === 'music-video')) {
// All audio tracks should be streamable, music videos are always streamable but have no `isStreamable` property.
linkTypes.push('paid streaming');
}
const releaseUrl = this.cleanViewUrl(collection.collectionViewUrl);
const gtin = this.extractGTINFromUrl(collection.artworkUrl100);
if (!gtin) {
this.addMessage('Failed to extract GTIN from artwork URL', 'warning');
} else if (this.lookup.method === 'gtin' && !isEqualGTIN(gtin, this.lookup.value)) {
this.addMessage(
`Extracted GTIN ${gtin} (from artwork URL) does not match the looked up value ${this.lookup.value}`,
'error',
);
} else {
this.addMessage(`Successfully extracted GTIN ${gtin} from artwork URL`);
}
const release: HarmonyRelease = {
title,
artists: [this.convertRawArtist(collection.artistName, collection.artistViewUrl)],
gtin: gtin,
externalLinks: [{
url: releaseUrl.href,
types: linkTypes,
}],
media: this.convertRawTracklist(tracks),
releaseDate: parseISODateTime(collection.releaseDate),
status: 'Official',
types,
packaging: 'None',
images: [this.processImage(collection.artworkUrl100, ['front'])],
copyright: collection.copyright,
info: this.generateReleaseInfo(),
};
return release;
}
private convertRawTracklist(tracklist: Track[]): HarmonyMedium[] {
if (!tracklist.length) {
return [];
}
const mediumCount = tracklist[0].discCount;
const totalTrackCount = tracklist[0].trackCount;
const media: HarmonyMedium[] = new Array(mediumCount).fill(null).map((_, index) => ({
format: 'Digital Media',
number: index + 1,
tracklist: [],
}));
// split flat tracklist into media
tracklist.forEach((track) => {
const medium = media[track.discNumber - 1];
// sometimes the censored name is not censored but more complete with extra title information
let title = track.trackName;
if (track.trackCensoredName.length > title.length) {
title = track.trackCensoredName;
}
const linkTypes: LinkType[] = [];
if (track.trackPrice) {
linkTypes.push('paid download');
}
if (track.isStreamable || track.kind === 'music-video') {
// Audio tracks should be streamable, music videos are always streamable but have no `isStreamable` property.
linkTypes.push('paid streaming');
}
medium.tracklist.push({
number: track.trackNumber,
title,
length: track.trackTimeMillis,
artists: [this.convertRawArtist(track.artistName, track.artistViewUrl)],
type: track.kind === 'music-video' ? 'video' : undefined,
recording: {
externalIds: this.provider.makeExternalIds({
type: track.kind,
id: track.trackId.toString(),
region: this.lookup.region,
linkTypes,
}),
},
});
});
if (tracklist.length < totalTrackCount) {
this.addMessage(
`The API returned only ${tracklist.length} of ${totalTrackCount} tracks for ${this.lookup.region}, other regions may have more`,
'warning',
);
fillMediumsTracklistGaps(media, totalTrackCount);
}
return media;
}
private convertRawArtist(name: string, url?: string): ArtistCreditName {
const artistId = url ? this.provider.extractEntityFromUrl(new URL(url)) : undefined;
return {
name,
creditedName: name,
externalIds: artistId ? this.provider.makeExternalIds(artistId) : undefined,
};
}
private processImage(url: string, types?: ArtworkType[]): Artwork {
return {
url: getSourceImage(url).href,
thumbUrl: url.replace('100x100bb', '250x250bb'),
types,
};
}
extractGTINFromUrl(url: string): GTIN | undefined {
const gtinCandidate = url.match(/(?<!\d)\d{12,14}(?!\d)/)?.[0];
if (gtinCandidate && isValidGTIN(gtinCandidate)) {
return gtinCandidate;
}
}
private cleanViewUrl(viewUrl: string) {
// remove tracking(?) query parameters and blurb before ID
// TODO: Generate canonical URL using `extractEntityFromUrl` and `constructUrl`.
const url = new URL(viewUrl);
url.search = '';
url.pathname = url.pathname.replace(/(?<=\/(artist|album))\/[^/]+(?=\/\d+)/, '');
return url;
}
private getTypesFromTitle(title: string): { title: string; types: ReleaseGroupType[] } {
const re = /\s- (EP|Single)$/;
const match = title.match(re);
const types: ReleaseGroupType[] = [];
if (match) {
title = title.replace(re, '');
types.push(match[1] as ReleaseGroupType);
}
return { title, types };
}
}
/** Transform Apple image URL to point to the source image in its original resolution. */
export function getSourceImage(url: string) {
const imageUrl = new URL(url);
imageUrl.hostname = 'a1.mzstatic.com';
imageUrl.pathname = imageUrl.pathname.replace(/^\/image\/thumb\//, '/us/r1000/063/');
const pathComponents = imageUrl.pathname.split('/');
const penultimate = pathComponents[pathComponents.length - 2];
if (penultimate === 'source' || /\.(jpe?g|png|tiff?)$/.test(penultimate)) {
// drop trailing path component which did the image conversion
imageUrl.pathname = pathComponents.slice(0, -1).join('/');
}
return imageUrl;
}