Merge pull request #194 from BinaryAlley/feature/implement-music-library-scanner

Feature/implement music library scanner
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-10-10 16:02:00 +03:00
commit d254a4bdcc
1161 files changed
+70446 -7467

No files matched your search

+1
View File
@@ -68,6 +68,7 @@
<PackageVersion Include="System.IO.Abstractions.TestingHelpers" Version="22.2.0" /> <PackageVersion Include="System.IO.Abstractions.TestingHelpers" Version="22.2.0" />
<PackageVersion Include="System.IO.Hashing" Version="10.0.11" /> <PackageVersion Include="System.IO.Hashing" Version="10.0.11" />
<PackageVersion Include="System.Linq.Async" Version="7.0.1" /> <PackageVersion Include="System.Linq.Async" Version="7.0.1" />
<PackageVersion Include="TagLibSharp" Version="2.3.0" />
<PackageVersion Include="xunit" Version="2.9.3" /> <PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.0" /> <PackageVersion Include="xunit.runner.visualstudio" Version="4.0.0" />
</ItemGroup> </ItemGroup>
@@ -41,6 +41,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -49,10 +50,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
"releaseType": "Album",
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"language": { "language": {
"languageCode": "en", "languageCode": "en",
"languageName": "English", "languageName": "English",
@@ -63,18 +60,27 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "vinyl" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "script": "Latn",
{ "name": "classic" }, "releaseTypes": [ "Album" ],
{ "name": "vinyl" } "releaseStatus": "Official",
] "totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -103,12 +109,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -127,24 +128,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 354,
{ "name": "epic" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
@@ -162,13 +189,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"source": "LastFm", "source": "LastFm",
"voteCount": 1234 "voteCount": 1234
} }
],
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
] ]
}, },
{ {
@@ -177,12 +197,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"durationInSeconds": 181, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
@@ -201,24 +216,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "love" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Pop Rock" } { "name": "Pop Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 181,
{ "name": "love" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" }
@@ -236,13 +277,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"source": "LastFm", "source": "LastFm",
"voteCount": 567 "voteCount": 567
} }
],
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
] ]
} }
] ]
@@ -264,10 +298,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseType": "Album", "disambiguation": null,
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -286,26 +317,27 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"genres": [
{
"name": "Rock"
},
{
"name": "Progressive Rock"
}
],
"tags": [ "tags": [
{ { "name": "classic" },
"name": "classic" { "name": "vinyl" }
}, ],
{ "genres": [
"name": "vinyl" { "name": "Rock" },
} { "name": "Progressive Rock" }
] ],
"script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -345,50 +377,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"releaseInfo": { "disambiguation": null,
"originalReleaseDate": "1975-10-31", "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"originalReleaseYear": 1975, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"reReleaseDate": null, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"reReleaseYear": null, "tags": [ { "name": "classic" }, { "name": "epic" } ],
"releaseCountry": "GB", "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"releaseVersion": "Original" "isVideo": false,
},
"language": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"originalLanguage": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [
{ "name": "Rock" },
{ "name": "Progressive Rock" }
],
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
],
"contributors": [ "contributors": [
{ {
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
@@ -412,13 +444,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"source": "LastFm", "source": "LastFm",
"voteCount": 1234 "voteCount": 1234
} }
],
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
] ]
}, },
{ {
@@ -430,50 +455,50 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"releaseInfo": { "disambiguation": null,
"originalReleaseDate": "1976-06-18", "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"originalReleaseYear": 1976, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"reReleaseDate": null, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"reReleaseYear": null, "tags": [ { "name": "classic" }, { "name": "love" } ],
"releaseCountry": "GB", "genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ],
"releaseVersion": "Original" "isVideo": false,
},
"language": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"originalLanguage": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"tags": [
{ "name": "classic" },
{ "name": "love" }
],
"genres": [
{ "name": "Rock" },
{ "name": "Pop Rock" }
],
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
],
"contributors": [ "contributors": [
{ {
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
@@ -497,13 +522,6 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"source": "LastFm", "source": "LastFm",
"voteCount": 567 "voteCount": 567
} }
],
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
] ]
} }
] ]
@@ -535,10 +553,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseType": "Album", "disambiguation": null,
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -557,26 +572,27 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"genres": [
{
"name": "Rock"
},
{
"name": "Progressive Rock"
}
],
"tags": [ "tags": [
{ { "name": "classic" },
"name": "classic" { "name": "vinyl" }
}, ],
{ "genres": [
"name": "vinyl" { "name": "Rock" },
} { "name": "Progressive Rock" }
] ],
"script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -671,10 +687,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseType": "Album", "disambiguation": null,
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -693,26 +706,27 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"genres": [
{
"name": "Rock"
},
{
"name": "Progressive Rock"
}
],
"tags": [ "tags": [
{ { "name": "classic" },
"name": "classic" { "name": "vinyl" }
}, ],
{ "genres": [
"name": "vinyl" { "name": "Rock" },
} { "name": "Progressive Rock" }
] ],
"script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -761,6 +775,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -769,10 +784,6 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
"releaseType": "Album",
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"language": { "language": {
"languageCode": "en", "languageCode": "en",
"languageName": "English", "languageName": "English",
@@ -783,18 +794,27 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "vinyl" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "script": "Latn",
{ "name": "classic" }, "releaseTypes": [ "Album" ],
{ "name": "vinyl" } "releaseStatus": "Official",
] "totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -834,10 +854,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseType": "Album", "disambiguation": null,
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -856,26 +873,27 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"genres": [
{
"name": "Rock"
},
{
"name": "Progressive Rock"
}
],
"tags": [ "tags": [
{ { "name": "classic" },
"name": "classic" { "name": "vinyl" }
}, ],
{ "genres": [
"name": "vinyl" { "name": "Rock" },
} { "name": "Progressive Rock" }
] ],
"script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -948,27 +966,41 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -1048,7 +1080,3 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"numberOfPages": 1 "numberOfPages": 1
} }
``` ```
@@ -31,19 +31,68 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
```json ```json
{ {
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": [ "albums": [
{ {
"metadata": { "metadata": {
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -70,14 +119,19 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"releaseType": "Album", "script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official", "releaseStatus": "Official",
"totalDiscs": 1, "totalDiscs": 1,
"totalTracks": 12 "totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -106,6 +160,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -132,22 +187,35 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -180,6 +248,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
@@ -206,22 +275,35 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Pop Rock" } { "name": "Pop Rock" }
], ],
"isVideo": false,
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"moods": [ "moods": [
{ "name": "happy" }, { "name": "happy" },
{ "name": "warm" } { "name": "warm" }
@@ -264,13 +346,63 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
{ {
"id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null,
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": [ "albums": [
{ {
"id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
@@ -280,10 +412,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseType": "Album", "disambiguation": null,
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -302,26 +431,27 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"genres": [
{
"name": "Rock"
},
{
"name": "Progressive Rock"
}
],
"tags": [ "tags": [
{ { "name": "classic" },
"name": "classic" { "name": "vinyl" }
}, ],
{ "genres": [
"name": "vinyl" { "name": "Rock" },
} { "name": "Progressive Rock" }
] ],
"script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -361,27 +491,41 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -425,27 +569,41 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "love" } ], "tags": [ { "name": "classic" }, { "name": "love" } ],
"genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ],
"isVideo": false,
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -482,9 +640,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists
} }
] ]
} }
], ]
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null
} }
``` ```
@@ -515,13 +671,32 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1&
{ {
"id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": null,
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [],
"tags": [],
"aliases": []
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"contributors": [], "ipis": [],
"albums": [], "isnis": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null "updatedOnUtc": null,
"contributors": [],
"ratings": [],
"albums": []
} }
], ],
"currentPage": 1, "currentPage": 1,
@@ -586,16 +761,64 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
{ {
"id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null,
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"albums": [], "ratings": [
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", {
"updatedOnUtc": null "value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": []
} }
``` ```
@@ -610,13 +833,61 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
```json ```json
{ {
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": [ "albums": [
{ {
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
@@ -624,6 +895,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -650,14 +922,19 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"releaseType": "Album", "script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official", "releaseStatus": "Official",
"totalDiscs": 1, "totalDiscs": 1,
"totalTracks": 12 "totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -687,6 +964,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -713,22 +991,35 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -762,6 +1053,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
@@ -788,22 +1080,35 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Pop Rock" } { "name": "Pop Rock" }
], ],
"isVideo": false,
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"moods": [ "moods": [
{ "name": "happy" }, { "name": "happy" },
{ "name": "warm" } { "name": "warm" }
@@ -846,13 +1151,63 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
{ {
"id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-02-01T12:00:00.0000000Z",
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": [ "albums": [
{ {
"id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
@@ -862,10 +1217,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseType": "Album", "disambiguation": null,
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -884,26 +1236,27 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"genres": [
{
"name": "Rock"
},
{
"name": "Progressive Rock"
}
],
"tags": [ "tags": [
{ { "name": "classic" },
"name": "classic" { "name": "vinyl" }
}, ],
{ "genres": [
"name": "vinyl" { "name": "Rock" },
} { "name": "Progressive Rock" }
] ],
"script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -943,27 +1296,41 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -1007,27 +1374,41 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "love" } ], "tags": [ { "name": "classic" }, { "name": "love" } ],
"genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ],
"isVideo": false,
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -1064,9 +1445,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
} }
] ]
} }
], ]
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-02-01T12:00:00.0000000Z"
} }
``` ```
@@ -1082,4 +1461,3 @@ DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}
``` ```
Deletes the artist identified by the route, together with its albums and tracks. Deletes the artist identified by the route, together with its albums and tracks.
@@ -30,12 +30,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -54,24 +49,43 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 354,
{ "name": "epic" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -116,27 +130,41 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -204,27 +232,41 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -283,12 +325,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -307,24 +344,43 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 354,
{ "name": "epic" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -369,27 +425,41 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ], "genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"moods": [ "moods": [
@@ -38,6 +38,9 @@
- [Cancel Library Scan](#cancel-library-scan) - [Cancel Library Scan](#cancel-library-scan)
- [Cancel Library Scan Request](#cancel-library-scan-request) - [Cancel Library Scan Request](#cancel-library-scan-request)
- [Cancel Library Scan Response](#cancel-library-scan-response) - [Cancel Library Scan Response](#cancel-library-scan-response)
- [Get Library Path Template Parts](#get-library-path-template-parts)
- [Get Library Path Template Parts Request](#get-library-path-template-parts-request)
- [Get Library Path Template Parts Response](#get-library-path-template-parts-response)
## Library ## Library
@@ -59,9 +62,10 @@ POST api/v1/libraries
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": []
} }
``` ```
@@ -83,9 +87,10 @@ POST api/v1/libraries
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true, "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null "updatedOnUtc": null
} }
@@ -118,9 +123,10 @@ GET api/v1/libraries
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true, "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null "updatedOnUtc": null
} }
@@ -154,9 +160,10 @@ GET api/v1/libraries/enabled
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true, "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null "updatedOnUtc": null
} }
@@ -189,9 +196,10 @@ GET api/v1/libraries/{id}
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true, "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null "updatedOnUtc": null
} }
@@ -217,9 +225,10 @@ PUT api/v1/libraries/{id}
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": []
} }
``` ```
@@ -241,9 +250,10 @@ PUT api/v1/libraries/{id}
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true, "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [],
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null "updatedOnUtc": null
} }
@@ -400,3 +410,43 @@ POST api/v1/libraries/{libraryId}/scans/{scanId}/cancel
```js ```js
204 No Content 204 No Content
``` ```
### Get Library Path Template Parts
#### Get Library Path Template Parts Request
```js
GET api/v1/libraries/path-template-parts/{libraryType}
```
#### Get Library Path Template Parts Response
```js
200 Ok
```
```json
{
"parts": [
{
"kind": "Artist",
"valueType": "Text",
"defaultRepresentation": "{0}",
"isOptionalByDefault": false
},
{
"kind": "DiscNumber",
"valueType": "Integer",
"defaultRepresentation": "{0:00}",
"isOptionalByDefault": true
}
],
"defaultTemplateParts": [
{
"kind": "Artist",
"representation": "{0}",
"isOptional": false
}
]
}
```
+163 -20
View File
@@ -23,12 +23,22 @@
- [Reorder Library Metadata Providers](#reorder-library-metadata-providers) - [Reorder Library Metadata Providers](#reorder-library-metadata-providers)
- [Reorder Library Metadata Providers Request](#reorder-library-metadata-providers-request) - [Reorder Library Metadata Providers Request](#reorder-library-metadata-providers-request)
- [Reorder Library Metadata Providers Response](#reorder-library-metadata-providers-response) - [Reorder Library Metadata Providers Response](#reorder-library-metadata-providers-response)
- [Get Library Artwork Providers](#get-library-artwork-providers)
- [Get Library Artwork Providers Request](#get-library-artwork-providers-request)
- [Get Library Artwork Providers Response](#get-library-artwork-providers-response)
- [Set Library Artwork Provider Enabled](#set-library-artwork-provider-enabled)
- [Set Library Artwork Provider Enabled Request](#set-library-artwork-provider-enabled-request)
- [Set Library Artwork Provider Enabled Response](#set-library-artwork-provider-enabled-response)
- [Reorder Library Artwork Providers](#reorder-library-artwork-providers)
- [Reorder Library Artwork Providers Request](#reorder-library-artwork-providers-request)
- [Reorder Library Artwork Providers Response](#reorder-library-artwork-providers-response)
- [Get Library Book Readers](#get-library-book-readers) - [Get Library Book Readers](#get-library-book-readers)
- [Get Library Book Readers Request](#get-library-book-readers-request) - [Get Library Book Readers Request](#get-library-book-readers-request)
- [Get Library Book Readers Response](#get-library-book-readers-response) - [Get Library Book Readers Response](#get-library-book-readers-response)
- [Set Library Book Reader Enabled](#set-library-book-reader-enabled) - [Set Library Book Reader Enabled](#set-library-book-reader-enabled)
- [Set Library Book Reader Enabled Request](#set-library-book-reader-enabled-request) - [Set Library Book Reader Enabled Request](#set-library-book-reader-enabled-request)
- [Set Library Book Reader Enabled Response](#set-library-book-reader-enabled-response) - [Set Library Book Reader Enabled Response](#set-library-book-reader-enabled-response)
- [Music Plugins](#music-plugins)
## Plugins ## Plugins
@@ -65,15 +75,20 @@ GET api/v1/plugins
```json ```json
[ [
{ {
"id": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", "id": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3",
"name": "OpenLibrary", "name": "MusicBrainz Metadata",
"author": "Binary Alley", "author": "Lumina",
"version": "1.0.0", "version": "1.0.0",
"description": "Downloads book metadata from Open Library.", "description": "Retrieves artist, album and track metadata from MusicBrainz.",
"loadStatus": "Loaded", "loadStatus": "Loaded",
"loadError": null, "loadError": null,
"settings": { "settings": {
"language": "en" "BaseUrl": "https://musicbrainz.org/ws/2/",
"DoesAllowPrivateBaseUrl": "false",
"ContactEmail": "",
"SearchResultLimit": "10",
"ReleaseLookupLimit": "25",
"MinimumRequestIntervalSeconds": "1.0"
} }
} }
] ]
@@ -93,28 +108,62 @@ GET api/v1/plugins/{pluginId}/settings
200 Ok 200 Ok
``` ```
The `type` of a setting descriptor is one of `Text`, `Number`, `Boolean` or `Select`. A `Select` setting also carries the list of `allowedValues` it can take.
```json ```json
{ {
"pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3",
"schema": [ "schema": [
{ {
"key": "language", "key": "BaseUrl",
"label": "Language", "label": "Base URL",
"type": "Text", "type": "Text",
"defaultValue": "en", "defaultValue": "https://musicbrainz.org/ws/2/",
"allowedValues": null "allowedValues": null
}, },
{ {
"key": "maxResults", "key": "DoesAllowPrivateBaseUrl",
"label": "Maximum results", "label": "Allow LAN/Private Base URL",
"type": "Boolean",
"defaultValue": "false",
"allowedValues": null
},
{
"key": "ContactEmail",
"label": "Contact Email",
"type": "Text",
"defaultValue": null,
"allowedValues": null
},
{
"key": "SearchResultLimit",
"label": "Search Result Limit",
"type": "Number", "type": "Number",
"defaultValue": "10", "defaultValue": "10",
"allowedValues": null "allowedValues": null
},
{
"key": "ReleaseLookupLimit",
"label": "Release Lookup Limit",
"type": "Number",
"defaultValue": "25",
"allowedValues": null
},
{
"key": "MinimumRequestIntervalSeconds",
"label": "Minimum Request Interval (seconds)",
"type": "Number",
"defaultValue": "1.0",
"allowedValues": null
} }
], ],
"settings": { "settings": {
"language": "en", "BaseUrl": "https://musicbrainz.org/ws/2/",
"maxResults": "10" "DoesAllowPrivateBaseUrl": "false",
"ContactEmail": "",
"SearchResultLimit": "10",
"ReleaseLookupLimit": "25",
"MinimumRequestIntervalSeconds": "1.0"
} }
} }
``` ```
@@ -129,10 +178,10 @@ PUT api/v1/plugins/{pluginId}/settings
```json ```json
{ {
"pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3",
"settings": { "settings": {
"language": "en", "BaseUrl": "https://musicbrainz.org/ws/2/",
"maxResults": "25" "SearchResultLimit": "25"
} }
} }
``` ```
@@ -151,6 +200,8 @@ PUT api/v1/plugins/{pluginId}/settings
GET api/v1/libraries/{libraryId}/metadata-providers GET api/v1/libraries/{libraryId}/metadata-providers
``` ```
Returns the metadata providers available for the media library, one entry per plugin that provides metadata, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried.
#### Get Library Metadata Providers Response #### Get Library Metadata Providers Response
```js ```js
@@ -160,8 +211,8 @@ GET api/v1/libraries/{libraryId}/metadata-providers
```json ```json
[ [
{ {
"pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3",
"name": "OpenLibrary", "name": "MusicBrainz Metadata",
"isEnabled": true, "isEnabled": true,
"rank": 1 "rank": 1
} }
@@ -179,7 +230,7 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled
```json ```json
{ {
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3",
"isEnabled": true "isEnabled": true
} }
``` ```
@@ -202,7 +253,7 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/reorder
{ {
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"pluginIds": [ "pluginIds": [
"f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3",
"a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
] ]
} }
@@ -214,6 +265,85 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/reorder
200 Ok 200 Ok
``` ```
### Get Library Artwork Providers
#### Get Library Artwork Providers Request
```js
GET api/v1/libraries/{libraryId}/artwork-providers
```
Returns the artwork providers available for the media library, one entry per plugin that provides artwork, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried when resolving the artwork.
#### Get Library Artwork Providers Response
```js
200 Ok
```
```json
[
{
"pluginId": "c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42",
"name": "Local Music Artwork",
"isEnabled": true,
"rank": 1
},
{
"pluginId": "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14",
"name": "Cover Art Archive",
"isEnabled": true,
"rank": 2
}
]
```
### Set Library Artwork Provider Enabled
#### Set Library Artwork Provider Enabled Request
```js
PUT api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled
```
```json
{
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"pluginId": "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14",
"isEnabled": true
}
```
#### Set Library Artwork Provider Enabled Response
```js
200 Ok
```
### Reorder Library Artwork Providers
#### Reorder Library Artwork Providers Request
```js
PUT api/v1/libraries/{libraryId}/artwork-providers/reorder
```
```json
{
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"pluginIds": [
"c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42",
"b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14"
]
}
```
#### Reorder Library Artwork Providers Response
```js
200 Ok
```
### Get Library Book Readers ### Get Library Book Readers
#### Get Library Book Readers Request #### Get Library Book Readers Request
@@ -272,3 +402,16 @@ PUT api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled
```js ```js
200 Ok 200 Ok
``` ```
## Music Plugins
The music media library type is served by four plugins, which register their capabilities through `IPluginServiceRegistrator`. A single plugin can expose more than one capability, and the capabilities are enabled and ranked per media library through the endpoints above.
| Plugin | Capability | Web access | Description |
| --- | --- | --- | --- |
| `MusicBrainz Metadata` | Metadata provider (artist, album, track) | Yes | Retrieves artist, album and track metadata from MusicBrainz. |
| `ID3 Metadata` | Metadata provider (artist, album, track) | No | Populates artist, album and track metadata from the embedded tags of the audio files. |
| `Local Music Artwork` | Artwork provider (artist, album) | No | Reads the artwork of the artists and the albums from the images stored in the folders of a local music library, and can extract the embedded album cover from the audio files. |
| `Cover Art Archive` | Artwork provider (album) | Yes | Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive. |
The metadata providers are resolved during the metadata enrichment phase of a scan, and the artwork providers during the artwork enrichment phase, in the order given by their rank.
@@ -39,13 +39,25 @@ end note
interface IBooksFileSystemDiscoveryJob { interface IBooksFileSystemDiscoveryJob {
} }
interface IMusicFileSystemDiscoveryJob {
}
interface IMusicMetadataExtractionJob {
}
interface IMediaLibraryScanDiffJob { interface IMediaLibraryScanDiffJob {
} }
interface IMediaLibraryScanHashJob { interface IMediaLibraryScanHashJob {
} }
interface IGoodReadsMetadataScrapJob { interface IMediaLibraryScanProviderConfigurationInvalidationJob {
}
interface IMediaLibraryScanMetadataEnrichmentJob {
}
interface IMediaLibraryScanArtworkEnrichmentJob {
} }
interface IMediaLibraryScanResultsSaveJob { interface IMediaLibraryScanResultsSaveJob {
@@ -56,6 +68,16 @@ class BooksFileSystemDiscoveryJob {
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task + ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
} }
class MusicFileSystemDiscoveryJob {
- STAGING_BATCH_SIZE: int = 1000
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
}
class MusicMetadataExtractionJob {
- EXTRACTION_BATCH_SIZE: int = 1000
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
}
class MediaLibraryScanDiffJob { class MediaLibraryScanDiffJob {
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task + ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
} }
@@ -65,8 +87,15 @@ class MediaLibraryScanHashJob {
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task + ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
} }
class GoodReadsMetadataScrapJob { class MediaLibraryScanProviderConfigurationInvalidationJob {
- ENRICHMENT_PAGE_SIZE: int = 1000 + ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
}
class MediaLibraryScanMetadataEnrichmentJob {
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
}
class MediaLibraryScanArtworkEnrichmentJob {
+ ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task + ExecuteAsync<TInput>(id: Guid, input: TInput, token: CancellationToken): Task
} }
@@ -94,8 +123,8 @@ end note
note right of MediaLibraryScanResultsSaveJob note right of MediaLibraryScanResultsSaveJob
Persists the results of the current scan and swaps the scan Persists the results of the current scan and swaps the scan
snapshot in a single transaction. Always the last job in the snapshot in a single transaction, then triggers the provider
directed acyclic job graph. configuration invalidation job.
end note end note
class ScanFailurePublisher { class ScanFailurePublisher {
@@ -108,30 +137,6 @@ note top of ScanFailurePublisher
releases its processing resources (see ADR-0009). releases its processing resources (see ADR-0009).
end note end note
' ============================== HOOKS AND REGISTRY ==============================
class ScanJobHooks {
+ AFTER_FILE_SYSTEM_DISCOVERY: string
+ AFTER_SCAN_DIFF: string
+ BEFORE_METADATA_ENRICHMENT: string
+ AFTER_METADATA_ENRICHMENT: string
+ BEFORE_SCAN_RESULTS_SAVE: string
}
note bottom of ScanJobHooks
Named junction points of the scan job graph where plugin
jobs can be injected (see ADR-0008).
end note
interface IScanJobRegistry {
+ GetJobsForHook(hookName: string, libraryId: LibraryId): IEnumerable<IMediaLibraryScanJob>
}
class ScanJobRegistry {
- _jobsByHook: IReadOnlyDictionary<string, IReadOnlyList<Type>>
+ GetJobsForHook(hookName: string, libraryId: LibraryId): IEnumerable<IMediaLibraryScanJob>
}
' ============================== FACTORIES AND SCANNERS ============================== ' ============================== FACTORIES AND SCANNERS ==============================
interface IMediaLibraryScanJobFactory { interface IMediaLibraryScanJobFactory {
@@ -151,25 +156,103 @@ class MediaLibraryScannerFactory {
} }
interface IMediaTypeScanner { interface IMediaTypeScanner {
+ SupportedType: LibraryType + SupportedLibraryType: LibraryType
+ CreateScanJobsForLibrary(libraryId: LibraryId, downloadMetadataFromWeb: bool): IEnumerable<IMediaLibraryScanJob> + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable<IMediaLibraryScanJob>
} }
interface IBookLibraryTypeScanner { interface IBookLibraryTypeScanner {
} }
interface IMusicLibraryTypeScanner {
}
class BookLibraryTypeScanner { class BookLibraryTypeScanner {
- _mediaScanJobFactory: IMediaLibraryScanJobFactory - _mediaScanJobFactory: IMediaLibraryScanJobFactory
- _scanJobRegistry: IScanJobRegistry + SupportedLibraryType: LibraryType
+ SupportedType: LibraryType + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable<IMediaLibraryScanJob>
+ CreateScanJobsForLibrary(libraryId: LibraryId, downloadMetadataFromWeb: bool): IEnumerable<IMediaLibraryScanJob> }
class MusicLibraryTypeScanner {
- _mediaScanJobFactory: IMediaLibraryScanJobFactory
+ SupportedLibraryType: LibraryType
+ CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable<IMediaLibraryScanJob>
}
' ============================== MEDIA TYPE STRATEGIES ==============================
interface IMediaLibraryScanItemMaterializer {
+ SupportedLibraryType: LibraryType
+ ResetEnrichmentStateForChangedPathsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, paths: IReadOnlyCollection<string>, token: CancellationToken): Task<Result<Updated>>
+ MaterializeItemsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, scanId: Guid, paths: IReadOnlyList<string>, token: CancellationToken): Task<Result<Success>>
+ ResetMetadataStatusForLibraryAsync(unitOfWork: IUnitOfWork, libraryId: Guid, token: CancellationToken): Task<Result<Updated>>
+ ResetArtworkStatusForLibraryAsync(unitOfWork: IUnitOfWork, libraryId: Guid, token: CancellationToken): Task<Result<Updated>>
}
interface IMediaLibraryScanMetadataEnricher {
+ SupportedLibraryType: LibraryType
+ EnrichAsync(libraryId: LibraryId, scanId: ScanId, userId: UserId, token: CancellationToken): Task
}
interface IMediaLibraryScanArtworkEnricher {
+ SupportedLibraryType: LibraryType
+ EnrichAsync(libraryId: LibraryId, scanId: ScanId, userId: UserId, token: CancellationToken): Task
}
class BooksMediaLibraryScanItemMaterializer {
}
class MusicMediaLibraryScanItemMaterializer {
}
class BooksMediaLibraryScanMetadataEnricher {
- ENRICHMENT_PAGE_SIZE: int = 1000
}
class MusicMediaLibraryScanMetadataEnricher {
- ENRICHMENT_PAGE_SIZE: int = 200
}
class BooksMediaLibraryScanArtworkEnricher {
- ENRICHMENT_PAGE_SIZE: int = 1000
}
class MusicMediaLibraryScanArtworkEnricher {
- ENRICHMENT_PAGE_SIZE: int = 200
} }
note top of BookLibraryTypeScanner note top of BookLibraryTypeScanner
Builds the books scan job graph: file system discovery, Builds the books scan job graph: file system discovery,
scan diff, hashing, optional GoodReads metadata enrichment scan diff, hashing, scan results save, provider configuration
and scan results save, splicing the plugin jobs registered invalidation, metadata enrichment and artwork enrichment.
at the ScanJobHooks hook points (see ADR-0008). end note
' ============================== PATH TEMPLATE ==============================
interface ILibraryPathTemplateService {
+ GetDefaultTemplate(libraryType: LibraryType): LibraryPathTemplate
+ ResolveTemplate(libraryType: LibraryType, providedParts: IReadOnlyList<LibraryPathPart>): Result<LibraryPathTemplate>
+ Validate(libraryType: LibraryType, template: LibraryPathTemplate): Result<Success>
+ Parse(libraryType: LibraryType, template: LibraryPathTemplate, relativePath: string, pathSeparator: char): Result<Optional<ParsedLibraryPath>>
}
class LibraryPathTemplateService {
}
interface ILibraryPathPartCatalog {
+ SupportedLibraryType: LibraryType
+ GetPartDefinitions(): IReadOnlyList<LibraryPathPartDefinition>
+ GetDefaultTemplate(): LibraryPathTemplate
}
class MusicLibraryPathPartCatalog {
}
class BookLibraryPathPartCatalog {
}
note bottom of ILibraryPathTemplateService
Validates media library path templates and derives item
metadata from paths, using the catalog of each library type.
end note end note
' ============================== SCAN ORCHESTRATION ============================== ' ============================== SCAN ORCHESTRATION ==============================
@@ -179,12 +262,12 @@ class LibraryScan {
+ LibraryId: LibraryId + LibraryId: LibraryId
+ UserId: UserId + UserId: UserId
+ Status: LibraryScanJobStatus + Status: LibraryScanJobStatus
+ {static} Create(libraryId: LibraryId, userId: UserId, pastScans: List<LibraryScan>): ErrorOr<LibraryScan> + {static} Create(libraryId: LibraryId, userId: UserId, pastScans: List<LibraryScan>): Result<LibraryScan>
+ QueueScan(): ErrorOr<Success> + QueueScan(): Result<Success>
+ StartScan(): ErrorOr<Success> + StartScan(): Result<Success>
+ FinishScan(): ErrorOr<Success> + FinishScan(): Result<Success>
+ CancelScan(): ErrorOr<Success> + CancelScan(): Result<Success>
+ FailScan(): ErrorOr<Success> + FailScan(): Result<Success>
} }
note right of LibraryScan note right of LibraryScan
@@ -193,8 +276,8 @@ note right of LibraryScan
end note end note
interface IMediaLibraryScanningService { interface IMediaLibraryScanningService {
+ StartScanAsync(scan: LibraryScan, libraryType: LibraryType, downloadMetadataFromWeb: bool, token: CancellationToken): Task<ErrorOr<Success>> + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task<Result<Success>>
+ CancelScan(scan: LibraryScan): ErrorOr<Success> + CancelScan(scan: LibraryScan): Result<Success>
} }
class MediaLibraryScanningService { class MediaLibraryScanningService {
@@ -202,9 +285,9 @@ class MediaLibraryScanningService {
- _mediaLibraryScannerFactory: IMediaLibraryScannerFactory - _mediaLibraryScannerFactory: IMediaLibraryScannerFactory
- _mediaLibrariesScanCancellationTracker: IMediaLibrariesScanCancellationTracker - _mediaLibrariesScanCancellationTracker: IMediaLibrariesScanCancellationTracker
- _mediaLibrariesScanProgressTracker: IMediaLibrariesScanProgressTracker - _mediaLibrariesScanProgressTracker: IMediaLibrariesScanProgressTracker
- _publisher: IPublisher - _domainEventPublisher: IDomainEventPublisher
+ StartScanAsync(scan: LibraryScan, libraryType: LibraryType, downloadMetadataFromWeb: bool, token: CancellationToken): Task<ErrorOr<Success>> + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task<Result<Success>>
+ CancelScan(scan: LibraryScan): ErrorOr<Success> + CancelScan(scan: LibraryScan): Result<Success>
} }
note top of MediaLibraryScanningService note top of MediaLibraryScanningService
@@ -259,11 +342,11 @@ class MediaLibrariesScanCancellationTracker {
} }
interface IMediaLibrariesScanProgressTracker { interface IMediaLibrariesScanProgressTracker {
+ InitializeScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, totalJobs: int): ErrorOr<Created> + InitializeScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, totalJobs: int): Result<Created>
+ UpdateScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId): ErrorOr<Updated> + UpdateScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId): Result<Updated>
+ UpdateScanJobProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, progress: MediaLibraryScanJobProgress): ErrorOr<Updated> + UpdateScanJobProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, progress: MediaLibraryScanJobProgress): Result<Updated>
+ GetScanProgress(compositeKey: MediaLibraryScanCompositeId): ErrorOr<MediaLibraryScanProgress> + GetScanProgress(compositeKey: MediaLibraryScanCompositeId): Result<MediaLibraryScanProgress>
+ RemoveScanProgress(compositeKey: MediaLibraryScanCompositeId): ErrorOr<MediaLibraryScanProgress> + RemoveScanProgress(compositeKey: MediaLibraryScanCompositeId): Result<MediaLibraryScanProgress>
} }
class MediaLibrariesScanProgressTracker { class MediaLibrariesScanProgressTracker {
@@ -285,7 +368,7 @@ class DebouncedMediaLibraryScanProgressNotifier {
} }
class MediaLibraryScanProgressHub { class MediaLibraryScanProgressHub {
+ SubscribeToScan(scanId: Guid, userId: Guid): Task + SubscribeToScan(scanId: Guid): Task
} }
note top of MediaLibraryScanProgressHub note top of MediaLibraryScanProgressHub
@@ -296,31 +379,31 @@ end note
' ============================== DOMAIN EVENT HANDLERS ============================== ' ============================== DOMAIN EVENT HANDLERS ==============================
class LibraryScanQueuedDomainEventHandler { class LibraryScanQueuedDomainEventHandler {
+ Handle(domainEvent: LibraryScanQueuedDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanQueuedDomainEvent, token: CancellationToken): ValueTask
} }
class LibraryScanStartedDomainEventHandler { class LibraryScanStartedDomainEventHandler {
+ Handle(domainEvent: LibraryScanStartedDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanStartedDomainEvent, token: CancellationToken): ValueTask
} }
class LibraryScanFinishedDomainEventHandler { class LibraryScanFinishedDomainEventHandler {
+ Handle(domainEvent: LibraryScanFinishedDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanFinishedDomainEvent, token: CancellationToken): ValueTask
} }
class LibraryScanFailedDomainEventHandler { class LibraryScanFailedDomainEventHandler {
+ Handle(domainEvent: LibraryScanFailedDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanFailedDomainEvent, token: CancellationToken): ValueTask
} }
class LibraryScanCancelledDomainEventHandler { class LibraryScanCancelledDomainEventHandler {
+ Handle(domainEvent: LibraryScanCancelledDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanCancelledDomainEvent, token: CancellationToken): ValueTask
} }
class LibraryScanProgressChangedDomainEventHandler { class LibraryScanProgressChangedDomainEventHandler {
+ Handle(domainEvent: LibraryScanProgressChangedDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanProgressChangedDomainEvent, token: CancellationToken): ValueTask
} }
class LibraryScanJobProgressChangedDomainEventHandler { class LibraryScanJobProgressChangedDomainEventHandler {
+ Handle(domainEvent: LibraryScanJobProgressChangedDomainEvent, token: CancellationToken): ValueTask + HandleAsync(domainEvent: LibraryScanJobProgressChangedDomainEvent, token: CancellationToken): ValueTask
} }
' ============================== JOB MODEL RELATIONSHIPS ============================== ' ============================== JOB MODEL RELATIONSHIPS ==============================
@@ -328,30 +411,46 @@ class LibraryScanJobProgressChangedDomainEventHandler {
IMediaLibraryScanJob <|.. MediaLibraryScanJob : implements IMediaLibraryScanJob <|.. MediaLibraryScanJob : implements
IMediaLibraryScanJob <|-- IBooksFileSystemDiscoveryJob IMediaLibraryScanJob <|-- IBooksFileSystemDiscoveryJob
IMediaLibraryScanJob <|-- IMusicFileSystemDiscoveryJob
IMediaLibraryScanJob <|-- IMusicMetadataExtractionJob
IMediaLibraryScanJob <|-- IMediaLibraryScanDiffJob IMediaLibraryScanJob <|-- IMediaLibraryScanDiffJob
IMediaLibraryScanJob <|-- IMediaLibraryScanHashJob IMediaLibraryScanJob <|-- IMediaLibraryScanHashJob
IMediaLibraryScanJob <|-- IGoodReadsMetadataScrapJob IMediaLibraryScanJob <|-- IMediaLibraryScanProviderConfigurationInvalidationJob
IMediaLibraryScanJob <|-- IMediaLibraryScanMetadataEnrichmentJob
IMediaLibraryScanJob <|-- IMediaLibraryScanArtworkEnrichmentJob
IMediaLibraryScanJob <|-- IMediaLibraryScanResultsSaveJob IMediaLibraryScanJob <|-- IMediaLibraryScanResultsSaveJob
MediaLibraryScanJob <|-- BooksFileSystemDiscoveryJob : inherits MediaLibraryScanJob <|-- BooksFileSystemDiscoveryJob : inherits
MediaLibraryScanJob <|-- MusicFileSystemDiscoveryJob : inherits
MediaLibraryScanJob <|-- MusicMetadataExtractionJob : inherits
MediaLibraryScanJob <|-- MediaLibraryScanDiffJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanDiffJob : inherits
MediaLibraryScanJob <|-- MediaLibraryScanHashJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanHashJob : inherits
MediaLibraryScanJob <|-- GoodReadsMetadataScrapJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanProviderConfigurationInvalidationJob : inherits
MediaLibraryScanJob <|-- MediaLibraryScanMetadataEnrichmentJob : inherits
MediaLibraryScanJob <|-- MediaLibraryScanArtworkEnrichmentJob : inherits
MediaLibraryScanJob <|-- MediaLibraryScanResultsSaveJob : inherits MediaLibraryScanJob <|-- MediaLibraryScanResultsSaveJob : inherits
IBooksFileSystemDiscoveryJob <|.. BooksFileSystemDiscoveryJob : implements IBooksFileSystemDiscoveryJob <|.. BooksFileSystemDiscoveryJob : implements
IMusicFileSystemDiscoveryJob <|.. MusicFileSystemDiscoveryJob : implements
IMusicMetadataExtractionJob <|.. MusicMetadataExtractionJob : implements
IMediaLibraryScanDiffJob <|.. MediaLibraryScanDiffJob : implements IMediaLibraryScanDiffJob <|.. MediaLibraryScanDiffJob : implements
IMediaLibraryScanHashJob <|.. MediaLibraryScanHashJob : implements IMediaLibraryScanHashJob <|.. MediaLibraryScanHashJob : implements
IGoodReadsMetadataScrapJob <|.. GoodReadsMetadataScrapJob : implements IMediaLibraryScanProviderConfigurationInvalidationJob <|.. MediaLibraryScanProviderConfigurationInvalidationJob : implements
IMediaLibraryScanMetadataEnrichmentJob <|.. MediaLibraryScanMetadataEnrichmentJob : implements
IMediaLibraryScanArtworkEnrichmentJob <|.. MediaLibraryScanArtworkEnrichmentJob : implements
IMediaLibraryScanResultsSaveJob <|.. MediaLibraryScanResultsSaveJob : implements IMediaLibraryScanResultsSaveJob <|.. MediaLibraryScanResultsSaveJob : implements
' ============================== JOB TRIGGER CHAIN ============================== ' ============================== JOB TRIGGER CHAIN ==============================
BooksFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers BooksFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers
MusicFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers
MediaLibraryScanDiffJob ..> MediaLibraryScanHashJob : triggers MediaLibraryScanDiffJob ..> MediaLibraryScanHashJob : triggers
MediaLibraryScanHashJob ..> GoodReadsMetadataScrapJob : triggers when metadata enrichment is enabled MediaLibraryScanHashJob ..> MediaLibraryScanResultsSaveJob : triggers
GoodReadsMetadataScrapJob ..> MediaLibraryScanResultsSaveJob : triggers MediaLibraryScanHashJob ..> MusicMetadataExtractionJob : triggers
MediaLibraryScanHashJob ..> MediaLibraryScanResultsSaveJob : triggers when metadata enrichment is disabled MusicMetadataExtractionJob ..> MediaLibraryScanResultsSaveJob : triggers
MediaLibraryScanResultsSaveJob ..> MediaLibraryScanProviderConfigurationInvalidationJob : triggers
MediaLibraryScanProviderConfigurationInvalidationJob ..> MediaLibraryScanMetadataEnrichmentJob : triggers
MediaLibraryScanMetadataEnrichmentJob ..> MediaLibraryScanArtworkEnrichmentJob : triggers
MediaLibraryScanJob ..> ScanFailurePublisher : publishes failure on unhandled exception MediaLibraryScanJob ..> ScanFailurePublisher : publishes failure on unhandled exception
@@ -359,21 +458,48 @@ MediaLibraryScanJob ..> ScanFailurePublisher : publishes failure on unhandled ex
IMediaLibraryScannerFactory <|.. MediaLibraryScannerFactory : implements IMediaLibraryScannerFactory <|.. MediaLibraryScannerFactory : implements
IMediaLibraryScanJobFactory <|.. MediaLibraryScanJobFactory : implements IMediaLibraryScanJobFactory <|.. MediaLibraryScanJobFactory : implements
IScanJobRegistry <|.. ScanJobRegistry : implements
IMediaTypeScanner <|-- IBookLibraryTypeScanner IMediaTypeScanner <|-- IBookLibraryTypeScanner
IBookLibraryTypeScanner <|.. BookLibraryTypeScanner : implements IBookLibraryTypeScanner <|.. BookLibraryTypeScanner : implements
IMediaTypeScanner <|-- IMusicLibraryTypeScanner
IMusicLibraryTypeScanner <|.. MusicLibraryTypeScanner : implements
MediaLibraryScannerFactory ..> IMediaTypeScanner : creates MediaLibraryScannerFactory ..> IMediaTypeScanner : creates
BookLibraryTypeScanner --> IMediaLibraryScanJobFactory : uses BookLibraryTypeScanner --> IMediaLibraryScanJobFactory : uses
BookLibraryTypeScanner --> IScanJobRegistry : splices plugin jobs
BookLibraryTypeScanner ..> IBooksFileSystemDiscoveryJob : creates BookLibraryTypeScanner ..> IBooksFileSystemDiscoveryJob : creates
BookLibraryTypeScanner ..> IMediaLibraryScanDiffJob : creates BookLibraryTypeScanner ..> IMediaLibraryScanDiffJob : creates
BookLibraryTypeScanner ..> IMediaLibraryScanHashJob : creates BookLibraryTypeScanner ..> IMediaLibraryScanHashJob : creates
BookLibraryTypeScanner ..> IGoodReadsMetadataScrapJob : creates
BookLibraryTypeScanner ..> IMediaLibraryScanResultsSaveJob : creates BookLibraryTypeScanner ..> IMediaLibraryScanResultsSaveJob : creates
BookLibraryTypeScanner ..> IMediaLibraryScanProviderConfigurationInvalidationJob : creates
BookLibraryTypeScanner ..> IMediaLibraryScanMetadataEnrichmentJob : creates
BookLibraryTypeScanner ..> IMediaLibraryScanArtworkEnrichmentJob : creates
MusicLibraryTypeScanner --> IMediaLibraryScanJobFactory : uses
MusicLibraryTypeScanner ..> IMusicFileSystemDiscoveryJob : creates
MusicLibraryTypeScanner ..> IMediaLibraryScanDiffJob : creates
MusicLibraryTypeScanner ..> IMediaLibraryScanHashJob : creates
MusicLibraryTypeScanner ..> IMusicMetadataExtractionJob : creates
MusicLibraryTypeScanner ..> IMediaLibraryScanResultsSaveJob : creates
MusicLibraryTypeScanner ..> IMediaLibraryScanProviderConfigurationInvalidationJob : creates
MusicLibraryTypeScanner ..> IMediaLibraryScanMetadataEnrichmentJob : creates
MusicLibraryTypeScanner ..> IMediaLibraryScanArtworkEnrichmentJob : creates
IMediaLibraryScanResultsSaveJob --> IMediaLibraryScanItemMaterializer : delegates to
IMediaLibraryScanProviderConfigurationInvalidationJob --> IMediaLibraryScanItemMaterializer : delegates to
IMediaLibraryScanMetadataEnrichmentJob --> IMediaLibraryScanMetadataEnricher : delegates to
IMediaLibraryScanArtworkEnrichmentJob --> IMediaLibraryScanArtworkEnricher : delegates to
IMediaLibraryScanItemMaterializer <|.. BooksMediaLibraryScanItemMaterializer : implements
IMediaLibraryScanItemMaterializer <|.. MusicMediaLibraryScanItemMaterializer : implements
IMediaLibraryScanMetadataEnricher <|.. BooksMediaLibraryScanMetadataEnricher : implements
IMediaLibraryScanMetadataEnricher <|.. MusicMediaLibraryScanMetadataEnricher : implements
IMediaLibraryScanArtworkEnricher <|.. BooksMediaLibraryScanArtworkEnricher : implements
IMediaLibraryScanArtworkEnricher <|.. MusicMediaLibraryScanArtworkEnricher : implements
ILibraryPathTemplateService <|.. LibraryPathTemplateService : implements
ILibraryPathPartCatalog <|.. MusicLibraryPathPartCatalog : implements
ILibraryPathPartCatalog <|.. BookLibraryPathPartCatalog : implements
LibraryPathTemplateService --> ILibraryPathPartCatalog : uses
MusicMetadataExtractionJob --> ILibraryPathTemplateService : derives metadata from paths
ScanJobRegistry ..> IMediaLibraryScanJob : resolves plugin jobs for hooks
MediaLibraryScanJobFactory ..> IMediaLibraryScanJob : creates MediaLibraryScanJobFactory ..> IMediaLibraryScanJob : creates
' ============================== SERVICE RELATIONSHIPS ============================== ' ============================== SERVICE RELATIONSHIPS ==============================
@@ -392,7 +518,7 @@ IMediaLibrariesScanQueue <|.. MediaLibrariesScanQueue : implements
MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanQueue : reads from MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanQueue : reads from
MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanCancellationTracker : links scan token MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanCancellationTracker : links scan token
MediaLibraryScanJobProcessorJob ..> BooksFileSystemDiscoveryJob : triggers root job MediaLibraryScanJobProcessorJob ..> IMediaLibraryScanJob : triggers root job
' ============================== TRACKER RELATIONSHIPS ============================== ' ============================== TRACKER RELATIONSHIPS ==============================
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="4878px" preserveAspectRatio="none" style="width:3794px;height:4878px;background:#FFFFFF;" version="1.1" viewBox="0 0 3794 4878" width="3794px" zoomAndPan="magnify"><title>Code diagram for Background Services 3.2.1</title><defs/><g><text fill="#000000" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="297.9922" x="1741.4482" y="24.5332">Code diagram for Background Services 3.2.1</text><!--class IMediaLibraryScanJob--><g id="elem_IMediaLibraryScanJob"><rect codeLine="13" fill="#FFFFFF" height="312.1406" id="IMediaLibraryScanJob" rx="2.5" ry="2.5" style="stroke:#000000;stroke-width:0.5;" width="210.4336" x="2495" y="3008.6094"/><ellipse cx="2527.612" cy="3024.6094" fill="#B4A7E5" rx="11" ry="11" style="stroke:#181818;stroke-width:1;"/><path d="M2528.5651,3021.25 L2528.5651,3027.9063 L2530.2838,3027.9063 Q2530.8932,3027.9063 2531.1588,3028.1406 Q2531.4245,3028.375 2531.4245,3028.7656 Q2531.4245,3029.1406 2531.1588,3029.375 Q2530.8932,3029.6094 2530.2838,3029.6094 L2525.1432,3029.6094 Q2524.5338,3029.6094 2524.2682,3029.375 Q2524.0026,3029.1406 2524.0026,3028.75 Q2524.0026,3028.375 2524.2682,3028.1406 Q2524.5338,3027.9063 2525.1432,3027.9063 L2526.862,3027.9063 L2526.862,3021.25 L2525.1432,3021.25 Q2524.5338,3021.25 2524.2682,3021.0156 Q2524.0026,3020.7813 2524.0026,3020.3906 Q2524.0026,3020.0156 2524.2682,3019.7813 Q2524.5338,3019.5469 2525.1432,3019.5469 L2530.2838,3019.5469 Q2530.8932,3019.5469 2531.1588,3019.7813 Q2531.4245,3020.0156 2531.4245,3020.3906 Q2531.4245,3020.7813 2531.1588,3021.0156 Q2530.8932,3021.25 2530.2838,3021.25 L2528.5651,3021.25 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" font-style="italic" lengthAdjust="spacing" textLength="139.2959" x="2545.5257" y="3030.3379">IMediaLibraryScanJob</text><line style="stroke:#000000;stroke-width:0.5;" x1="2496" x2="2704.4336" y1="3040.6094" y2="3040.6094"/><ellipse cx="2506" cy="3054.9141" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="47.4756" x="2515" y="3059.1426">ScanId:</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="3.8896" x="2562.4756" y="3059.1426">&#160;</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="43.5859" x="2566.3652" y="3059.1426">ScanId</text><ellipse cx="2506" cy="3072.5234" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="45.124" x="2515" y="3076.752">UserId:</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="3.8896" x="2560.124" y="3076.752">&#160;</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="41.2344" x="2564.0137" y="3076.752">UserId</text><ellipse cx="2506" cy="3090.1328" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="58.3584" x="2515" y="3094.3613">LibraryId:</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="3.8896" x="2573.3584" y="3094.3613">&#160;</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="54.4688" x="2577.248" y="3094.3613">LibraryId</text><ellipse cx="2506" cy="3116.5469" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="56.0273" x="2515" y="3111.9707">Children:</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="177.4336" x="2515" y="3129.5801">List&lt;IMediaLibraryScanJob&gt;</text><ellipse cx="2506" cy="3151.7656" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="52.1377" x="2515" y="3147.1895">Parents:</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="177.4336" x="2515" y="3164.7988">List&lt;IMediaLibraryScanJob&gt;</text><ellipse cx="2506" cy="3178.1797" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="43.5791" x="2515" y="3182.4082">Status:</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="3.8896" x="2558.5791" y="3182.4082">&#160;</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="136.9648" x="2562.4688" y="3182.4082">LibraryScanJobSLine truncated <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="CLASS" style="width:4278px;height:5609px;background:#FFFFFF;" width="4278px" height="5609px" viewBox="0 0 4278 5609" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="1986.931" y="24.533" fill="#000" font-size="14" textLength="297.992" font-weight="700">Code diagram for Background Services 3.2.1</text></g><!--class IMediaLibraryScanJob--><g class="entity" data-qualified-name="IMediaLibraryScanJob" id="ent0001" data-source-line="13"><rect x="2288.5" y="2658.609" width="210.434" height="312.141" fill="#FFF" style="stroke:#000;stroke-width:0.5;" rx="2.5" ry="2.5"/><ellipse cx="2321.112" cy="2674.609" rx="11" ry="11" fill="#B4A7E5" style="stroke:#181818;stroke-width:1;"/><path d="M2322.065,2671.25 L2322.065,2677.906 L2323.784,2677.906 Q2324.393,2677.906 2324.659,2678.141 Q2324.924,2678.375 2324.924,2678.766 Q2324.924,2679.141 2324.659,2679.375 Q2324.393,2679.609 2323.784,2679.609 L2318.643,2679.609 Q2318.034,2679.609 2317.768,2679.375 Q2317.503,2679.141 2317.503,2678.75 Q2317.503,2678.375 2317.768,2678.141 Q2318.034,2677.906 2318.643,2677.906 L2320.362,2677.906 L2320.362,2671.25 L2318.643,2671.25 Q2318.034,2671.25 2317.768,2671.016 Q2317.503,2670.781 2317.503,2670.391 Q2317.503,2670.016 2317.768,2669.781 Q2318.034,2669.547 2318.643,2669.547 L2323.784,2669.547 Q2324.393,2669.547 2324.659,2669.781 Q2324.924,2670.016 2324.924,2670.391 Q2324.924,2670.781 2324.659,2671.016 Q2324.393,2671.25 2323.784,2671.25 L2322.065,2671.25 Z " fill="#000"/><text x="2339.026" y="2680.338" fill="#000" font-size="14" textLength="139.296" font-style="italic">IMediaLibraryScanJob</text><line x1="2289.5" y1="2690.609" x2="2497.934" y2="2690.609" style="stroke:#000;stroke-width:0.5;"/><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2299.5" cy="2704.914" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2709.143" fill="#000" font-size="14" textLength="47.476">ScanId:</text><text x="2355.976" y="2709.143" fill="#000" font-size="14"> </text><text x="2359.865" y="2709.143" fill="#000" font-size="14" textLength="43.586">ScanId</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2299.5" cy="2722.523" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2726.752" fill="#000" font-size="14" textLength="45.124">UserId:</text><text x="2353.624" y="2726.752" fill="#000" font-size="14"> </text><text x="2357.514" y="2726.752" fill="#000" font-size="14" textLength="41.234">UserId</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2299.5" cy="2740.133" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2744.361" fill="#000" font-size="14" textLength="58.358">LibraryId:</text><text x="2366.858" y="2744.361" fill="#000" font-size="14"> </text><text x="2370.748" y="2744.361" fill="#000" font-size="14" textLength="54.469">LibraryId</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2299.5" cy="2766.547" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2761.971" fill="#000" font-size="14" textLength="56.027">Children:</text><text x="2308.5" y="2779.58" fill="#000" font-size="14" textLength="177.434">List&lt;IMediaLibraryScanJob></text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2299.5" cy="2801.766" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2797.189" fill="#000" font-size="14" textLength="52.138">Parents:</text><text x="2308.5" y="2814.799" fill="#000" font-size="14" textLength="177.434">List&lt;IMediaLibraryScanJob></text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2299.5" cy="2828.18" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2832.408" fill="#000" font-size="14" textLength="43.579">Status:</text><text x="2352.079" y="2832.408" fill="#000" font-size="14"> </text><text x="2355.969" y="2832.408" fill="#000" font-size="14" textLength="136.965">LibraryScanJobStatus</text><line x1="2289.5" y1="2839.484" x2="2497.934" y2="2839.484" style="stroke:#000;stroke-width:0.5;"/><g data-visibility-modifier="PUBLIC_METHOD"><ellipse cx="2299.5" cy="2862.594" rx="3" ry="3" fill="#84BE84" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2858.018" fill="#000" font-size="14" textLength="84.048">AddChild(job:</text><text x="2308.5" y="2875.627" fill="#000" font-size="14" textLength="143.958">IMediaLibraryScanJob)</text><g data-visibility-modifier="PUBLIC_METHOD"><ellipse cx="2299.5" cy="2897.813" rx="3" ry="3" fill="#84BE84" style="stroke:#038048;stroke-width:1;"/></g><text x="2308.5" y="2893.236" fill="#000" font-size="14" textLength="93.393">AddParent(job:</text><text x="2308.5" y="Line truncated

Before

Width:  |  Height:  |  Size: 310 KiB

After

Width:  |  Height:  |  Size: 326 KiB

@@ -36,6 +36,10 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
} }
} }
``` ```
## Amendments
- **2026-10-09**: The generic `FileSystemDiscoveryJob` / `IFileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`), and the job execution contract is now `ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken token)` on `IMediaLibraryScanJob`. The `IServiceScopeFactory` decision itself is unchanged.
## Consequences ## Consequences
### Positive Outcomes ### Positive Outcomes
@@ -26,7 +26,11 @@ private static List<FileInfo> GetFiles(...)
``` ```
## Consequences ## Amendments
- **2026-10-09**: The single generic `FileSystemDiscoveryJob` was split into per-type discovery jobs (`BooksFileSystemDiscoveryJob`, `MusicFileSystemDiscoveryJob`). The `System.IO` guidance of this ADR applies to the books discovery job, which still traverses the file system directly. The music discovery job uses the domain file system provider services (`IFileProviderService`, `IDirectoryProviderService`) instead.
## Consequences
### Performance vs Purity Tradeoff ### Performance vs Purity Tradeoff
| Metric | Before (Domain) | After (System.IO) | Delta | | Metric | Before (Domain) | After (System.IO) | Delta |
@@ -4,13 +4,13 @@
**Accepted** (2026-08-08) **Accepted** (2026-08-08)
## Context ## Context
The media library scan pipeline stages the file system items discovered during a scan before comparing them against the `LibraryScanSnapshots` table (ADR-0004). A staging store is needed that: The media library scan pipeline stages the file system items discovered during a scan before comparing them against the `LibraryScanSnapshots` table ([ADR-0004](architecture-decision-record-0004.md)). A staging store is needed that:
1. receives the discovered file system items in bounded batches, 1. receives the discovered file system items in bounded batches,
2. is read by the diff, hash and metadata enrichment jobs, 2. is read by the diff, hash and metadata enrichment jobs,
3. is written by the discovery job and read by later jobs, which run in separate dependency injection scopes (see ADR-0001), hence on separate database connections. 3. is written by the discovery job and read by later jobs, which run in separate dependency injection scopes (see [ADR-0001](architecture-decision-record-0001.md)), hence on separate database connections.
A real SQLite `TEMP` table was considered, but SQLite `TEMP` tables are scoped to a single database connection. Because each media library scan job creates its own `AsyncServiceScope`, and therefore its own `LuminaDbContext` and connection (ADR-0001), a `TEMP` table created by the discovery job would be invisible to the diff job, which runs on a different connection. Making a `TEMP` table work would require pinning a single dedicated connection for the whole staging phase of a scan, a larger architectural carve-out. A real SQLite `TEMP` table was considered, but SQLite `TEMP` tables are scoped to a single database connection. Because each media library scan job creates its own `AsyncServiceScope`, and therefore its own `LuminaDbContext` and connection ([ADR-0001](architecture-decision-record-0001.md)), a `TEMP` table created by the discovery job would be invisible to the diff job, which runs on a different connection. Making a `TEMP` table work would require pinning a single dedicated connection for the whole staging phase of a scan, a larger architectural carve-out.
## Decision ## Decision
Use a permanent table, `LibraryScanStagingResults`, keyed by `(LibraryScanId, Path)`. Its rows are deleted at the end of the scan (as part of the snapshot swap transaction of the save job) and on scan failure or cancellation. Leftover rows of a crashed scan are inert, because every scan has a unique id, and can be purged by the audit cleanup job. Use a permanent table, `LibraryScanStagingResults`, keyed by `(LibraryScanId, Path)`. Its rows are deleted at the end of the scan (as part of the snapshot swap transaction of the save job) and on scan failure or cancellation. Leftover rows of a crashed scan are inert, because every scan has a unique id, and can be purged by the audit cleanup job.
@@ -35,9 +35,9 @@ Use a permanent table, `LibraryScanStagingResults`, keyed by `(LibraryScanId, Pa
### 1. SQLite `TEMP` table with a single pinned connection ### 1. SQLite `TEMP` table with a single pinned connection
The whole staging phase would hold one dedicated connection open, and all jobs would share it. The whole staging phase would hold one dedicated connection open, and all jobs would share it.
**Rejected**: It conflicts with the per-job scope model of ADR-0001, holds a database connection open for the entire scan duration, and makes the pipeline harder to compose and test. **Rejected**: It conflicts with the per-job scope model of [ADR-0001](architecture-decision-record-0001.md), holds a database connection open for the entire scan duration, and makes the pipeline harder to compose and test.
### 2. In-memory staging (list of discovered items passed between jobs) ### 2. In-memory staging (list of discovered items passed between jobs)
The discovery job would pass the full list of discovered items to the diff job. The discovery job would pass the full list of discovered items to the diff job.
**Rejected**: It brings back the unbounded memory problem that ADR-0004 eliminates. The staging table is what allows bounded, batched writes. **Rejected**: It brings back the unbounded memory problem that [ADR-0004](architecture-decision-record-0004.md) eliminates. The staging table is what allows bounded, batched writes.
@@ -1,7 +1,7 @@
# Architecture Decision Record (ADR): 0008 - Plugin Hook Points and the Media Library Scan Job Graph # Architecture Decision Record (ADR): 0008 - Plugin Hook Points and the Media Library Scan Job Graph
## Status ## Status
**Accepted** (2026-08-08) **Superseded by [ADR-0015](architecture-decision-record-0015.md)** (2026-10-09)
## Context ## Context
The media library scanning subsystem is meant to be modular: generic jobs, like the scan diff, hashing and results save jobs, are shared by all media library types, while media-type specific jobs, like the GoodReads metadata scrap job for books or a TMDB cover art job for movies, are decoupled and composed into a directed acyclic graph. The media library scanning subsystem is meant to be modular: generic jobs, like the scan diff, hashing and results save jobs, are shared by all media library types, while media-type specific jobs, like the GoodReads metadata scrap job for books or a TMDB cover art job for movies, are decoupled and composed into a directed acyclic graph.
@@ -15,24 +15,30 @@ Define named hook points for the scan job graph in `ScanJobHooks`: `AfterFileSys
Define the `IScanJobRegistry` interface, which maps a hook name to the plugin jobs registered at that hook. The media type scanners (for example `BookLibraryTypeScanner`) splice the plugin jobs returned by the registry into the graph at the corresponding hook points, preserving the parent-child relationships. The composition root of the plugin system provides the registry with the plugin job types; the default registry registers no plugin jobs. Define the `IScanJobRegistry` interface, which maps a hook name to the plugin jobs registered at that hook. The media type scanners (for example `BookLibraryTypeScanner`) splice the plugin jobs returned by the registry into the graph at the corresponding hook points, preserving the parent-child relationships. The composition root of the plugin system provides the registry with the plugin job types; the default registry registers no plugin jobs.
The payload passing between jobs keeps the generic `ExecuteAsync<TInput>` contract. The core scan jobs are database-centric and ignore the payload, because they exchange the scan state through the staging and snapshot tables (ADR-0004, ADR-0005). Payload passing remains available for plugin jobs that need to exchange data in memory, and the runtime type switching that was used in the previous `HashComparerJob` is eliminated. The payload passing between jobs keeps the generic `ExecuteAsync<TInput>` contract. The core scan jobs are database-centric and ignore the payload, because they exchange the scan state through the staging and snapshot tables ([ADR-0004](architecture-decision-record-0004.md), [ADR-0005](architecture-decision-record-0005.md)). Payload passing remains available for plugin jobs that need to exchange data in memory, and the runtime type switching that was used in the previous `HashComparerJob` is eliminated.
## Amendments
- **2026-10-09**: Superseded by [ADR-0015](architecture-decision-record-0015.md). The `ScanJobHooks` hook points and the `IScanJobRegistry` / `ScanJobRegistry` were removed, and plugins now contribute capability providers (`IMetadataProvider`, `IArtworkProvider`, `IBookReader`) instead of scan jobs. This ADR is marked superseded rather than amended because its decision is replaced in full by [ADR-0015](architecture-decision-record-0015.md); [ADR-0001](architecture-decision-record-0001.md), [ADR-0003](architecture-decision-record-0003.md) and [ADR-0010](architecture-decision-record-0010.md) stay accepted because only part of their decisions changed.
## Consequences ## Consequences
> The rows struck through reflect the superseded hook point and scan job registry model. They no longer hold, see [ADR-0015](architecture-decision-record-0015.md).
### Positive Outcomes ### Positive Outcomes
| Aspect | Benefit | | Aspect | Benefit |
|-----------------------|-----------------------------------------------------------| |-----------------------|-----------------------------------------------------------|
| Modularity | Media-type specific jobs are composed per scanner | | Modularity | Media-type specific jobs are composed per scanner |
| Extensibility | Plugins inject jobs at documented hook points | | ~~Extensibility~~ | ~~Plugins inject jobs at documented hook points~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) |
| Multi-parent support | The base job model keeps full parent-child capabilities | | Multi-parent support | The base job model keeps full parent-child capabilities |
| Fail fast composition | Wrong payload wiring produces loud errors instead of silent no-ops | | ~~Fail fast composition~~ | ~~Wrong payload wiring produces loud errors instead of silent no-ops~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) |
### Risks and Tradeoffs ### Risks and Tradeoffs
| Risk | Mitigation Strategy | | Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------| |-------------------------------|-------------------------------------------------------------------|
| Plugin job conflicts | Hook points are named and documented, the composition is validated when the graph is built | | ~~Plugin job conflicts~~ | ~~Hook points are named and documented, the composition is validated when the graph is built~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) |
| Payload contract misuse | Jobs that expect a payload fail loudly when the edge type does not match | | Payload contract misuse | Jobs that expect a payload fail loudly when the edge type does not match |
| Scope creep | Only the sensible hook points are defined, arbitrary injection is not supported | | ~~Scope creep~~ | ~~Only the sensible hook points are defined, arbitrary injection is not supported~~ (removed, see [ADR-0015](architecture-decision-record-0015.md)) |
## Alternatives Considered ## Alternatives Considered
@@ -4,7 +4,7 @@
**Accepted** (2026-08-08) **Accepted** (2026-08-08)
## Context ## Context
Media library scan jobs are launched in a fire-and-forget manner from the background job processor (`MediaLibraryScanJobProcessorJob`), because only the root jobs are placed on the in-memory queue, and they trigger their children recursively (see ADR-0001 and ADR-0008). The launch mechanism uses `FireAndForgetSafeAsync`, which observes the launched task but does not crash the queue consumer. Media library scan jobs are launched in a fire-and-forget manner from the background job processor (`MediaLibraryScanJobProcessorJob`), because only the root jobs are placed on the in-memory queue, and they trigger their children recursively (see [ADR-0001](architecture-decision-record-0001.md) and [ADR-0008](architecture-decision-record-0008.md)). The launch mechanism uses `FireAndForgetSafeAsync`, which observes the launched task but does not crash the queue consumer.
The scan jobs must report their failures through the existing eventual consistency mechanism, the `LibraryScanFailedDomainEvent`, whose handler marks the scan as failed, releases the scan processing resources and notifies the clients. The previous job implementations only published the failure event on a few specific error paths, so any other exception was silently swallowed, leaving the scan stuck in the `Running` state, leaking its cancellation source and progress entry. The scan jobs must report their failures through the existing eventual consistency mechanism, the `LibraryScanFailedDomainEvent`, whose handler marks the scan as failed, releases the scan processing resources and notifies the clients. The previous job implementations only published the failure event on a few specific error paths, so any other exception was silently swallowed, leaving the scan stuck in the `Running` state, leaking its cancellation source and progress entry.
@@ -4,20 +4,28 @@
**Accepted** (2026-08-09) **Accepted** (2026-08-09)
## Context ## Context
ADR-0009 established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed. [ADR-0009](architecture-decision-record-0009.md) established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed.
The metadata enrichment phase runs after the scan results save job, once the file state of the library is committed and the books are materialized. The enrichment phase is best-effort: a book whose metadata could not be retrieved is still browsable with its shell metadata (path and filename-derived title), and a crash mid-enrichment must not roll back the already committed scan results, nor hide the successfully enriched books. This was an explicit product decision: partial enrichment survives a crash, and the scan is not considered failed because a remote metadata provider was unreachable or a provider crashed. The metadata enrichment phase runs after the scan results save job, once the file state of the library is committed and the books are materialized. The enrichment phase is best-effort: a book whose metadata could not be retrieved is still browsable with its shell metadata (path and filename-derived title), and a crash mid-enrichment must not roll back the already committed scan results, nor hide the successfully enriched books. This was an explicit product decision: partial enrichment survives a crash, and the scan is not considered failed because a remote metadata provider was unreachable or a provider crashed.
## Decision ## Decision
The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of ADR-0009: The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of [ADR-0009](architecture-decision-record-0009.md):
- Per-book failures are isolated: a metadata provider that throws, returns unusable metadata, or fails to be applied marks the book as `Failed` (`MetadataStatus.Failed`) and moves to the next book. The other providers are still tried for the same book, and the other books are still processed. - Per-book failures are isolated: a metadata provider that throws, returns unusable metadata, or fails to be applied marks the book as `Failed` (`MetadataStatus.Failed`) and moves to the next book. The other providers are still tried for the same book, and the other books are still processed.
- Per-provider failures are isolated: a crashing metadata provider does not prevent the other providers from being tried, in their configured order. - Per-provider failures are isolated: a crashing metadata provider does not prevent the other providers from being tried, in their configured order.
- The scan is considered completed (`LibraryScanFinishedDomainEvent`) after the enrichment phase, even when some books failed to be enriched. The failure is recorded on the books, not on the scan. - The scan is considered completed (`LibraryScanFinishedDomainEvent`) after the enrichment phase, even when some books failed to be enriched. The failure is recorded on the books, not on the scan.
- Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of ADR-0009. In that case the file state is already committed, and a re-scan retries the enrichment. - Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of [ADR-0009](architecture-decision-record-0009.md). In that case the file state is already committed, and a re-scan retries the enrichment.
The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise. The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise.
## Amendments
- **2026-10-09**: The enrichment phase is now three sequential jobs, and the last job of the graph is the artwork enrichment job.
- `MediaLibraryScanProviderConfigurationInvalidationJob` invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, and the metadata derived from the paths when the path template changed.
- `MediaLibraryScanMetadataEnrichmentJob` enriches the metadata and links the media contributors.
- `MediaLibraryScanArtworkEnrichmentJob` resolves the artwork and is always the last job, publishing `LibraryScanFinishedDomainEvent` (see `MediaLibraryScanArtworkEnrichmentJob`).
- **2026-10-09**: The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`; it triggers the provider configuration invalidation job. The metadata enrichment semantics described below apply to both the metadata and the artwork enrichment jobs, and across every media library type with enrichers, including music (`MusicMediaLibraryScanMetadataEnricher`, `MusicMediaLibraryScanArtworkEnricher`), not only books.
## Consequences ## Consequences
### Positive Outcomes ### Positive Outcomes
@@ -37,7 +45,7 @@ The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDom
## Alternatives Considered ## Alternatives Considered
### 1. Fail the scan on any enrichment failure ### 1. Fail the scan on any enrichment failure
Keep ADR-0009 semantics for the enrichment job. Keep [ADR-0009](architecture-decision-record-0009.md) semantics for the enrichment job.
**Rejected**: The file state is already committed, and partial enrichment is better than failing a scan that saved the library. Failing the scan would also roll back nothing, while misleading the user about the scan outcome. **Rejected**: The file state is already committed, and partial enrichment is better than failing a scan that saved the library. Failing the scan would also roll back nothing, while misleading the user about the scan outcome.
@@ -12,7 +12,7 @@ Key constraints that shaped this decision:
1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems. 1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems.
2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see ADR-0013). 2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see [ADR-0013](architecture-decision-record-0013.md)).
3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection. 3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection.
@@ -14,7 +14,7 @@ Domain event publishing, the mechanism that fires the `IDomainEvent` objects rai
3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events). 3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events).
The remaining publish half carries the same third-party dependency and source-generated registration that ADR-0011 removed from the dispatch half. The remaining publish half carries the same third-party dependency and source-generated registration that [ADR-0011](architecture-decision-record-0011.md) removed from the dispatch half.
## Decision ## Decision
@@ -38,7 +38,7 @@ The existing assembly scan that registers `ICommandHandler<>`, `IQueryHandler<>`
### Consistency Guarantees Preserved ### Consistency Guarantees Preserved
- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see ADR-0002). - Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see [ADR-0002](architecture-decision-record-0002.md)).
- Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider. - Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider.
- Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`. - Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`.
@@ -73,4 +73,4 @@ Introduce `IIntegrationEvent` now, with a durable outbox, for inter-bounded-cont
Keep the Mediator library for the domain event publishing half. Keep the Mediator library for the domain event publishing half.
**Rejected**: for the same reason ADR-0011 rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house. **Rejected**: for the same reason [ADR-0011](architecture-decision-record-0011.md) rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house.
@@ -0,0 +1,79 @@
# Architecture Decision Record (ADR): 0015 - Plugin Capability Providers for Media Library Enrichment
## Status
**Accepted** (2026-10-09)
Supersedes [ADR-0008](architecture-decision-record-0008.md).
## Context
[ADR-0008](architecture-decision-record-0008.md) extended the media library scanning subsystem with plugin jobs: it defined named scan job hook points in `ScanJobHooks` and a scan job registry (`IScanJobRegistry` / `ScanJobRegistry`) that mapped a hook name to the plugin job types to splice into the scan job graph at that junction.
That model coupled plugins to the host scan graph. A plugin had to know the internal job model and the junction semantics to contribute anything, the host had to know every plugin job type up front to build the graph, and the resulting graph mixed host jobs and plugin jobs with no clear ownership of the enrichment behavior. It also kept the `HashComparerJob` runtime type switching around, because jobs of different types exchanged differently typed payloads.
What a plugin actually contributes is data: metadata for a media item, artwork for a media item, or the ability to decode a book. Which jobs run, in what order, and how their results are persisted is a host concern that should not be delegated to plugins.
## Decision
Separate plugin capabilities from the host scan graph. Plugins contribute capability providers, and the host owns the graph and decides when to invoke the capabilities.
### Plugin contracts
- `IPlugin` carries the identity of the plugin (`Id`, `Name`, `Author`, `Version`, `Description`) and its settings schema (`GetSettingsSchema()`).
- `IPluginServiceRegistrator` registers the services of the plugin into the host dependency injection container through `RegisterServices(IServiceCollection)`.
### Capability contracts
The host defines the capability contracts, and a plugin implements the ones it supports:
| Capability | Contract | Purpose |
|---|---|---|
| Metadata provider | `IMetadataProvider` | Searches for and returns the metadata of a media item (`GetSearchResultsAsync`, `GetMetadataAsync`), declaring its `SupportedLibraryTypes`, the `LookupType` it accepts, and whether it `RequiresWebAccess` |
| Artwork provider | `IArtworkProvider` | Returns the artwork of a media item (`GetArtworkAsync`), declaring its `SupportedLibraryTypes` and whether it `RequiresWebAccess` |
| Book reader | `IBookReader` | Decodes a book format into a normalized reading document (`OpenAsync`, `GetResourceAsync`), declaring its `SupportedExtensions` and `SupportedLibraryTypes` |
### Registration and selection
- A plugin registers each capability as a keyed transient service, keyed by its plugin `Id` (for example `AddKeyedTransient<IMetadataProvider, MusicBrainzTrackMetadataProvider>(pluginId)`). A single plugin can register several providers, of the same or of different capabilities.
- Plugins contribute zero scan jobs. The scan job graph of each media library type is built entirely by its own scanner from host jobs created through `IMediaLibraryScanJobFactory`.
- The host persists which providers are enabled for each media library and their rank, and exposes that configuration through the media library management endpoints.
- The enrichment jobs resolve the configured, enabled providers of the media library and invoke them in rank order: the metadata enrichment job delegates to `IMediaLibraryScanMetadataEnricher`, the artwork enrichment job delegates to `IMediaLibraryScanArtworkEnricher`, and the results save job delegates to `IMediaLibraryScanItemMaterializer`.
### Removed
`ScanJobHooks`, `IScanJobRegistry` and `ScanJobRegistry` are removed, along with the `HashComparerJob` runtime type switching they depended on. [ADR-0008](architecture-decision-record-0008.md) is superseded.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|---|---|
| Ownership | Plugins contribute data capabilities; the host owns the scan graph and when to invoke them |
| Decoupling | A plugin depends only on the capability contracts, not on the internal job model or the graph junctions |
| Extensibility | A new plugin adds keyed capability services and no host code, and a plugin can expose several capabilities |
| Per-library control | Providers are enabled and ranked per media library, independent of plugin installation |
| Simplicity | No hook registry, no graph splicing across the plugin boundary, and no runtime payload type switching |
### Risks and Mitigations
| Risk | Mitigation Strategy |
|---|---|
| A plugin registers a capability a library type does not support | Providers declare `SupportedLibraryTypes`, and the host only offers and invokes providers that support the library being processed |
| Two enabled providers return conflicting metadata | Providers are tried in the configured rank order, so precedence is explicit and user controlled |
| A crashing provider fails the enrichment | Enrichment is best effort and isolates provider failures ([ADR-0010](architecture-decision-record-0010.md)), so one provider cannot fail the scan |
## Alternatives Considered
### 1. Keep the scan job hook points and the scan job registry
**Rejected**: it couples plugins to the host scan graph, forces the host to know plugin job types up front, and mixes host and plugin jobs without a clear owner. It is the model this ADR replaces.
### 2. Let plugins register scan jobs directly, without a registry
**Rejected**: it removes the named junction points but keeps the coupling: plugins still have to know the job model, the graph shape and the payload contracts, and the graph still has no single owner.
### 3. Resolve capability providers by convention, without per-library configuration
**Rejected**: enabling and ranking providers per media library is a requirement. It lets a user run several metadata or artwork sources for one library, in a chosen precedence, and turn providers off without uninstalling the plugin.
+142 -28
View File
@@ -1,14 +1,15 @@
- [Lumina Domain](#lumina-domain) - [Lumina Domain](#lumina-domain)
- [Audio Library Aggregate](#audio-library-aggregate) - [Music Library Aggregate](#music-library-aggregate)
- [Artist](#artist) - [Artist](#artist)
- [Album](#album) - [Album](#album)
- [Track](#track) - [Track](#track)
- [Audio Rating](#audio-rating)
# [Lumina Domain](#lumina-domain) # [Lumina Domain](#lumina-domain)
## [Audio Library Aggregate](#audio-library-aggregate) ## [Music Library Aggregate](#music-library-aggregate)
The audio library aggregate is the aggregate root of the `MusicLibrary` aggregate, which models the music of a media library. An artist is the aggregate root, owning its albums, and each album owns its tracks. Albums and tracks carry full metadata: title, description, release information, languages, genres and tags, and the tracks additionally carry the audio characteristics of their file, their moods and their ISRC codes. The media contributors that make up an artist, or that performed on an album or a track, are carried as `MusicMediaContributor` value objects. The music library aggregate models the music of a media library. `Artist` is the aggregate root, owning its albums, and each album owns its tracks. Albums and tracks carry full metadata: title, description, release information, languages, genres and tags, and the tracks additionally carry the audio characteristics of their file, their moods and their ISRC codes. The media contributors that make up an artist, or that performed on an album or a track, are carried as `MusicMediaContributor` value objects.
### [Artist](#artist) ### [Artist](#artist)
@@ -18,8 +19,25 @@ class Artist
Result<Artist> Create( Result<Artist> Create(
LibraryId libraryId, LibraryId libraryId,
string name, string name,
Optional<string> sortName,
Optional<string> disambiguation,
Optional<MusicArtistType> type,
Optional<MusicArtistGender> gender,
Optional<string> country,
Optional<MusicArea> area,
Optional<MusicArea> beginArea,
Optional<MusicArea> endArea,
Optional<DateOnly> lifeSpanBegin,
Optional<DateOnly> lifeSpanEnd,
bool isEnded,
Optional<string> website, Optional<string> website,
Optional<MusicBrainzId> musicBrainzArtistId, Optional<MusicBrainzId> musicBrainzArtistId,
List<string> ipis,
List<string> isnis,
List<MusicArtistAlias> aliases,
List<Genre> genres,
List<Tag> tags,
List<AudioRating> ratings,
List<MusicMediaContributor> contributors, List<MusicMediaContributor> contributors,
List<Album> albums); List<Album> albums);
} }
@@ -34,10 +52,58 @@ class Artist
"value": "00000000-0000-0000-0000-000000000000" "value": "00000000-0000-0000-0000-000000000000"
}, },
"name": "Queen", "name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": {
"value": "00000000-0000-0000-0000-000000000000"
},
"name": "United Kingdom",
"sortName": null,
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": { "musicBrainzArtistId": {
"value": "00000000-0000-0000-0000-000000000000" "value": "00000000-0000-0000-0000-000000000000"
}, },
"ipis": [],
"isnis": [],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
],
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"contributors": [], "contributors": [],
"albums": [ "albums": [
{ {
@@ -54,9 +120,14 @@ class Album
{ {
Result<Album> Create( Result<Album> Create(
AlbumMetadata metadata, AlbumMetadata metadata,
Optional<string> disambiguation,
Optional<MusicMediaFormat> mediaFormat, Optional<MusicMediaFormat> mediaFormat,
Optional<MusicReleasePackaging> packaging,
Optional<string> script,
Optional<Barcode> barcode, Optional<Barcode> barcode,
Optional<string> catalogNumber, List<string> catalogNumbers,
Optional<string> label,
Optional<string> asin,
Optional<MusicBrainzId> musicBrainzReleaseId, Optional<MusicBrainzId> musicBrainzReleaseId,
Optional<MusicBrainzId> musicBrainzReleaseGroupId, Optional<MusicBrainzId> musicBrainzReleaseGroupId,
Optional<MusicBrainzId> musicBrainzReleaseArtistId, Optional<MusicBrainzId> musicBrainzReleaseArtistId,
@@ -74,6 +145,7 @@ class Album
"metadata": { "metadata": {
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"releaseTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
@@ -101,16 +173,21 @@ class Album
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"releaseType": "Album", "releaseTypes": [ "Album" ],
"releaseStatus": "Official", "releaseStatus": "Official",
"totalDiscs": 1, "totalDiscs": 1,
"totalTracks": 12 "totalTracks": 12
}, },
"disambiguation": null,
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"script": "Latn",
"barcode": { "barcode": {
"value": "0042282778329" "value": "0042282778329"
}, },
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": { "musicBrainzReleaseId": {
"value": "00000000-0000-0000-0000-000000000000" "value": "00000000-0000-0000-0000-000000000000"
}, },
@@ -149,20 +226,20 @@ class Album
class Track class Track
{ {
Result<Track> Create( Result<Track> Create(
LibraryId libraryId,
string path, string path,
AudioMetadata metadata, AudioMetadata metadata,
Optional<string> disambiguation,
int trackNumber, int trackNumber,
Optional<int> discNumber, Optional<int> discNumber,
List<Isrc> isrcs, List<Mood> moods,
Optional<string> script, Optional<string> script,
Optional<MusicKey> key, Optional<MusicKey> key,
Optional<int> bpm, Optional<int> bpm,
List<Mood> moods, bool isVideo,
Optional<string> work, List<Isrc> isrcs,
Optional<MusicWork> work,
Optional<MusicBrainzId> musicBrainzRecordingId, Optional<MusicBrainzId> musicBrainzRecordingId,
Optional<MusicBrainzId> musicBrainzTrackId, Optional<MusicBrainzId> musicBrainzTrackId,
Optional<MusicBrainzId> musicBrainzWorkId,
List<MusicMediaContributor> contributors, List<MusicMediaContributor> contributors,
List<AudioRating> ratings); List<AudioRating> ratings);
} }
@@ -173,9 +250,6 @@ class Track
"id": { "id": {
"value": "00000000-0000-0000-0000-000000000000" "value": "00000000-0000-0000-0000-000000000000"
}, },
"libraryId": {
"value": "00000000-0000-0000-0000-000000000000"
},
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"metadata": { "metadata": {
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
@@ -212,32 +286,50 @@ class Track
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"disambiguation": null,
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"isrcs": [
{
"value": "GBUM71029604"
}
],
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"moods": [ "isVideo": false,
{ "name": "dramatic" }, "work": {
{ "name": "anxious" } "musicBrainzWorkId": {
], "value": "00000000-0000-0000-0000-000000000000"
"work": "Bohemian Rhapsody", },
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
}
],
"iswcs": []
},
"musicBrainzRecordingId": { "musicBrainzRecordingId": {
"value": "00000000-0000-0000-0000-000000000000" "value": "00000000-0000-0000-0000-000000000000"
}, },
"musicBrainzTrackId": { "musicBrainzTrackId": {
"value": "00000000-0000-0000-0000-000000000000" "value": "00000000-0000-0000-0000-000000000000"
}, },
"musicBrainzWorkId": { "moods": [
"value": "00000000-0000-0000-0000-000000000000" { "name": "dramatic" },
}, { "name": "anxious" }
],
"isrcs": [
{
"value": "GBUM71029604"
}
],
"contributors": [], "contributors": [],
"ratings": [ "ratings": [
{ {
@@ -249,3 +341,25 @@ class Track
] ]
} }
``` ```
### [Audio Rating](#audio-rating)
The rating of a music media element derives from the common `Rating` value object and adds the source the rating came from.
```csharp
class AudioRating : Rating
{
Result<AudioRating> Create(decimal value, decimal maxValue, Optional<AudioRatingSource> source, Optional<int> voteCount);
}
```
```json
{
"value": 9.3,
"maxValue": 10.0,
"source": "MusicBrainz",
"voteCount": 84
}
```
`AudioRatingSource` is `User`, `MusicBrainz`, `Discogs` or `LastFm`.
+23 -11
View File
@@ -4,6 +4,7 @@
- [Genre](#genre) - [Genre](#genre)
- [Tag](#tag) - [Tag](#tag)
- [Rating](#rating) - [Rating](#rating)
- [Mood](#mood)
- [Release Info](#release-info) - [Release Info](#release-info)
- [Language Info](#language-info) - [Language Info](#language-info)
@@ -18,7 +19,7 @@
```csharp ```csharp
class Genre class Genre
{ {
ErrorOr<Genre> Create(string name); Result<Genre> Create(string name);
} }
``` ```
@@ -33,7 +34,7 @@ class Genre
```csharp ```csharp
class Tag class Tag
{ {
ErrorOr<Tag> Create(string name); Result<Tag> Create(string name);
} }
``` ```
@@ -45,19 +46,30 @@ class Tag
#### [Rating](#rating) #### [Rating](#rating)
`Rating` is the abstract base of the ratings of media elements. It carries the numeric value, its maximum and an optional vote count, but no factory of its own, because the concrete ratings of each media type derive from it and add their own source. The rating of the audio library context, `AudioRating` with its `AudioRatingSource`, is documented alongside the music library aggregate.
```csharp ```csharp
class Rating abstract class Rating
{ {
ErrorOr<Rating> Create(decimal value, decimal maxValue, Optional<RatingSource> source = default, Optional<int> voteCount = default); decimal Value { get; }
decimal MaxValue { get; }
Optional<int> VoteCount { get; }
decimal AsPercentage();
}
```
#### [Mood](#mood)
```csharp
class Mood
{
Result<Mood> Create(string name);
} }
``` ```
```json ```json
{ {
"value": 9.3, "name": "dramatic"
"maxValue": 10.0,
"source": "Imdb",
"voteCount": 84
} }
``` ```
@@ -66,8 +78,8 @@ class Rating
```csharp ```csharp
class ReleaseInfo class ReleaseInfo
{ {
ErrorOr<ReleaseInfo> Create(Optional<DateOnly> originalReleaseDate, Optional<int> originalReleaseYear, Result<ReleaseInfo> Create(Optional<DateOnly> originalReleaseDate, Optional<int> originalReleaseYear,
Optional<DateOnly> reReleaseDate, Optional<int> reReleaseYear, Optional<string> releaseCountry, Optional<string> releaseVersion); Optional<DateOnly> reReleaseDate, Optional<int> reReleaseYear, Optional<ReleaseCountry> releaseCountry, Optional<string> releaseVersion);
} }
``` ```
@@ -97,4 +109,4 @@ class LanguageInfo
"languageName": "French", "languageName": "French",
"nativeName": "Française", "nativeName": "Française",
} }
``` ```
+18 -2
View File
@@ -1,7 +1,23 @@
<span style="color: #FF0000;">Domain</span> <span style="color: #FF0000;">Domain</span>
├── <span style="color: #004BFF;">Audio Library Bounded Context</span> ├── <span style="color: #004BFF;">Audio Library Bounded Context</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── <span style="color: #F589DD;">Audio Library Aggregate</span> │&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── <span style="color: #F589DD;">Music Library Aggregate</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── <span style="color: #BDE180;">Audio Metadata</span> │&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Artist Id</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Album Id</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Track Id</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Music Media Contributor</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Music Brainz Id</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Music Area</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Music Artist Alias</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Music Work</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Isrc</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Barcode</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Album Metadata</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Audio Metadata</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Audio Rating</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #80B0E0;">Album</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #80B0E0;">Track</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #FEB423;">Music Library Type Scanner</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── <span style="color: #B46DD4;">Artist</span>
├── <span style="color: #004BFF;">Video Library Bounded Context</span> ├── <span style="color: #004BFF;">Video Library Bounded Context</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #F589DD;">Movie Library Aggregate</span> │&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #F589DD;">Movie Library Aggregate</span>
│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Movie Id</span> │&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── <span style="color: #BDE180;">Movie Id</span>
+22 -26
View File
@@ -28,19 +28,10 @@
- _**Music Video**_: A video representation of a song - _**Music Video**_: A video representation of a song
## Audio Content ## Audio Content
- _**Song**_: An individual music track - _**Track**_: An individual music track, the smallest unit of music in a music library (the entity is named Track, not Song)
- _**Album**_: A collection of songs - _**Album**_: A release that gathers the tracks of an artist
- _**Artist**_: The creator of music content - _**Artist**_: The creator of music content, the root of the music library aggregate
- _**Audiobook**_: A narrated version of a book - _**MusicReleaseType**_: The set of content types a music release can carry, like Album, Single, Ep, Compilation, AudioBook, Interview, Live, Remix, Soundtrack or SpokenWord
- _**Live Recording**_: Audio or video of a live performance
- _**Interview**_: Audio or video recording of a conversation
- _**Cover Song**_: A rendition of a song performed by an artist other than the original
- _**Remix**_: A modified version of an original song
- _**Sound Effect**_: A short audio clip used for specific purposes
- _**Soundtrack**_: A collection of music used in a film or TV show
- _**Podcast**_: A series of audio episodes
- _**Podcast Episode**_: An individual installment of a podcast
- _**Radio Show**_: An audio program broadcast on the radio
## Written Content ## Written Content
- _**Book**_: A standalone written work - _**Book**_: A standalone written work
@@ -79,15 +70,9 @@
- Anime - Anime
- YouTubeVideo - YouTubeVideo
- MusicVideo - MusicVideo
- Song - Track
- Album - Album
- Artist - Artist
- Audiobook
- LiveRecording
- Interview
- CoverSong
- Remix
- SoundEffect
- Podcast - Podcast
- PodcastEpisode - PodcastEpisode
- Book - Book
@@ -118,7 +103,7 @@
## Aggregates ## Aggregates
- VideoLibrary (root: VideoLibrary, entities: TVShow, Season, Episode, Movie, FilmSeries, ConcertVideo, Documentary, TutorialVideo, HomeVideo, Anime, YouTubeVideo, MusicVideo) - VideoLibrary (root: VideoLibrary, entities: TVShow, Season, Episode, Movie, FilmSeries, ConcertVideo, Documentary, TutorialVideo, HomeVideo, Anime, YouTubeVideo, MusicVideo)
- AudioLibrary (root: AudioLibrary, entities: Song, Album, Artist, Audiobook, LiveRecording, Interview, CoverSong, Remix, SoundEffect) - MusicLibrary (root: Artist, entities: Album, Track)
- PodcastLibrary (root: PodcastLibrary, entities: Podcast, PodcastEpisode) - PodcastLibrary (root: PodcastLibrary, entities: Podcast, PodcastEpisode)
- WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay) - WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay)
- PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster) - PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster)
@@ -175,14 +160,25 @@
- StreamInfo - StreamInfo
- StreamingQuality - StreamingQuality
- UserPreferences - UserPreferences
- Rating - Rating (abstract)
- AudioRating
- Genre - Genre
- Mood
- ReleaseInfo - ReleaseInfo
- LanguageInfo - LanguageInfo
- AlbumMetadata
- MusicMediaContributor
- MusicBrainzId
- MusicArea
- MusicArtistAlias
- MusicWork
- Isrc
- Barcode
## Domain Services ## Domain Services
- MediaScanner (with specialized scanners for each media type) - Music Library Type Scanner
- MetadataFetcher (with different strategies for various media types and sources) - Music File System Discovery Job
- Music Metadata Extraction Job
- TranscodingService - TranscodingService
- StreamingService - StreamingService
- AudiobookPlaybackService - AudiobookPlaybackService
@@ -216,8 +212,8 @@
## Bounded Contexts ## Bounded Contexts
- MediaManagement - MediaManagement
- Aggregates: VideoLibrary, AudioLibrary, PodcastLibrary, WrittenContentLibrary, PhotoLibrary - Aggregates: VideoLibrary, MusicLibrary, PodcastLibrary, WrittenContentLibrary, PhotoLibrary
- Services: MediaScanner, MetadataFetcher, TranscodingService - Services: Music Library Type Scanner, Music File System Discovery Job, Music Metadata Extraction Job
- UserExperience - UserExperience
- Aggregates: UserProfile - Aggregates: UserProfile
- Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService - Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService
@@ -7,6 +7,7 @@ Content-Type: application/json
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -15,10 +16,6 @@ Content-Type: application/json
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
"releaseType": "Album",
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"language": { "language": {
"languageCode": "en", "languageCode": "en",
"languageName": "English", "languageName": "English",
@@ -29,18 +26,27 @@ Content-Type: application/json
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "vinyl" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "script": "Latn",
{ "name": "classic" }, "releaseTypes": [ "Album" ],
{ "name": "vinyl" } "releaseStatus": "Official",
] "totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -69,12 +75,7 @@ Content-Type: application/json
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -93,24 +94,50 @@ Content-Type: application/json
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 354,
{ "name": "epic" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", "moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
@@ -128,13 +155,6 @@ Content-Type: application/json
"source": "LastFm", "source": "LastFm",
"voteCount": 1234 "voteCount": 1234
} }
],
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
] ]
}, },
{ {
@@ -143,12 +163,7 @@ Content-Type: application/json
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"durationInSeconds": 181, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
@@ -167,24 +182,50 @@ Content-Type: application/json
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "love" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Pop Rock" } { "name": "Pop Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 181,
{ "name": "love" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", "moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" }
@@ -202,13 +243,6 @@ Content-Type: application/json
"source": "LastFm", "source": "LastFm",
"voteCount": 567 "voteCount": 567
} }
],
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
] ]
} }
] ]
@@ -7,6 +7,7 @@ Content-Type: application/json
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -15,10 +16,6 @@ Content-Type: application/json
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
"releaseType": "Album",
"releaseStatus": "Official",
"totalDiscs": 1,
"totalTracks": 12,
"language": { "language": {
"languageCode": "en", "languageCode": "en",
"languageName": "English", "languageName": "English",
@@ -29,18 +26,27 @@ Content-Type: application/json
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "vinyl" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "script": "Latn",
{ "name": "classic" }, "releaseTypes": [ "Album" ],
{ "name": "vinyl" } "releaseStatus": "Official",
] "totalDiscs": 1,
"totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -3,19 +3,68 @@ Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: application/json Content-Type: application/json
{ {
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": [ "albums": [
{ {
"metadata": { "metadata": {
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -42,14 +91,19 @@ Content-Type: application/json
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"releaseType": "Album", "script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official", "releaseStatus": "Official",
"totalDiscs": 1, "totalDiscs": 1,
"totalTracks": 12 "totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -78,6 +132,7 @@ Content-Type: application/json
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -104,22 +159,35 @@ Content-Type: application/json
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -152,6 +220,7 @@ Content-Type: application/json
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
@@ -178,22 +247,35 @@ Content-Type: application/json
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Pop Rock" } { "name": "Pop Rock" }
], ],
"isVideo": false,
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"moods": [ "moods": [
{ "name": "happy" }, { "name": "happy" },
{ "name": "warm" } { "name": "warm" }
@@ -3,13 +3,61 @@ Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: application/json Content-Type: application/json
{ {
"name": "Queen", "metadata": {
"name": "Queen",
"sortName": "Queen",
"disambiguation": null,
"type": "Group",
"gender": null,
"country": "GB",
"area": {
"musicBrainzAreaId": "7f2a1b3c-4d5e-4f6a-8b9c-0d1e2f3a4b5c",
"name": "United Kingdom",
"sortName": "United Kingdom",
"disambiguation": null,
"type": "Country",
"iso3166Code": "GB"
},
"beginArea": null,
"endArea": null,
"lifeSpanBegin": "1970-06-27",
"lifeSpanEnd": null,
"isEnded": false,
"genres": [
{ "name": "Rock" }
],
"tags": [
{ "name": "classic" }
],
"aliases": [
{
"name": "Queen",
"sortName": "Queen",
"type": "Artist name",
"locale": "en",
"isPrimary": true,
"beginDate": "1970-06-27",
"endDate": null,
"isEnded": false
}
]
},
"website": "https://www.queenonline.com", "website": "https://www.queenonline.com",
"musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d",
"ipis": [],
"isnis": [],
"contributors": [ "contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
], ],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
}
],
"albums": [ "albums": [
{ {
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
@@ -17,6 +65,7 @@ Content-Type: application/json
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -43,14 +92,19 @@ Content-Type: application/json
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"releaseType": "Album", "script": "Latn",
"releaseTypes": [ "Album" ],
"releaseStatus": "Official", "releaseStatus": "Official",
"totalDiscs": 1, "totalDiscs": 1,
"totalTracks": 12 "totalTracks": 12,
"releaseTitle": "A Night at the Opera"
}, },
"mediaFormat": "CD", "mediaFormat": "CD",
"packaging": "JewelCase",
"barcode": "0042282778329", "barcode": "0042282778329",
"catalogNumber": "EMC 4008", "catalogNumbers": ["EMC 4008"],
"label": "EMI",
"asin": "B000000000",
"musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
@@ -80,6 +134,7 @@ Content-Type: application/json
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -106,22 +161,35 @@ Content-Type: application/json
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"isVideo": false,
"durationInSeconds": 354, "durationInSeconds": 354,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 980 "bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -155,6 +223,7 @@ Content-Type: application/json
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
@@ -181,22 +250,35 @@ Content-Type: application/json
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Pop Rock" } { "name": "Pop Rock" }
], ],
"isVideo": false,
"durationInSeconds": 181, "durationInSeconds": 181,
"sampleRate": 44100, "sampleRate": 44100,
"channels": 2, "channels": 2,
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912 "bitrate": 912,
"acoustId": null,
"replayGainTrackGain": null,
"replayGainTrackPeak": null,
"replayGainAlbumGain": null,
"replayGainAlbumPeak": null
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "BMajor", "key": "BMajor",
"bpm": 118, "bpm": 118,
"work": "You're My Best Friend", "work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"moods": [ "moods": [
{ "name": "happy" }, { "name": "happy" },
{ "name": "warm" } { "name": "warm" }
@@ -8,12 +8,7 @@ Content-Type: application/json
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -32,24 +27,43 @@ Content-Type: application/json
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 354,
{ "name": "epic" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -8,12 +8,7 @@ Content-Type: application/json
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354, "disambiguation": null,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
@@ -32,24 +27,43 @@ Content-Type: application/json
"languageName": "English", "languageName": "English",
"nativeName": "English" "nativeName": "English"
}, },
"tags": [
{ "name": "classic" },
{ "name": "epic" }
],
"genres": [ "genres": [
{ "name": "Rock" }, { "name": "Rock" },
{ "name": "Progressive Rock" } { "name": "Progressive Rock" }
], ],
"tags": [ "isVideo": false,
{ "name": "classic" }, "durationInSeconds": 354,
{ "name": "epic" } "sampleRate": 44100,
] "channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
}, },
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1, "discNumber": 1,
"script": "Latn", "script": "Latn",
"key": "CMajor", "key": "CMajor",
"bpm": 72, "bpm": 72,
"work": "Bohemian Rhapsody", "work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": []
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -11,7 +11,11 @@ Content-Type: application/json
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [
{ "kind": "Artist", "representation": "{0}", "isOptional": false },
{ "kind": "Separator", "representation": "", "isOptional": false }
]
} }
@@ -0,0 +1,2 @@
GET {{host}}/api/v1/libraries/path-template-parts/Music
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -13,7 +13,11 @@ Content-Type: application/json
"coverImage": null, "coverImage": null,
"isEnabled": true, "isEnabled": true,
"isLocked": false, "isLocked": false,
"downloadMetadataFromWeb": true, "canDownloadMetadataFromWeb": true,
"shouldSaveMetadataInMediaDirectories": true, "shouldSaveMetadataInMediaDirectories": true,
"shouldSkipUnchangedDirectoriesDuringScan": true "shouldSkipUnchangedDirectoriesDuringScan": true,
"pathTemplateParts": [
{ "kind": "Artist", "representation": "{0}", "isOptional": false },
{ "kind": "Separator", "representation": "", "isOptional": false }
]
} }
@@ -5,7 +5,7 @@ Content-Type: application/json
{ {
"pluginId": "{{$guid}}", "pluginId": "{{$guid}}",
"settings": { "settings": {
"language": "en", "BaseUrl": "https://musicbrainz.org/ws/2/",
"includeSeries": "true" "SearchResultLimit": "25"
} }
} }
@@ -38,30 +38,30 @@ internal sealed class CalibreArtworkProvider : IArtworkProvider<BookMetadataLook
/// </summary> /// </summary>
/// <param name="lookup">The lookup describing the book to get the cover for.</param> /// <param name="lookup">The lookup describing the book to get the cover for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The cover of the book, or <see langword="null"/> when no cover was found.</returns> /// <returns>The cover of the book, or an empty collection when no cover was found.</returns>
public Task<ArtworkDto?> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
{ {
if (string.IsNullOrWhiteSpace(lookup.Path)) if (string.IsNullOrWhiteSpace(lookup.Path))
return Task.FromResult<ArtworkDto?>(null); return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty; string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty;
string opfFilePath = Path.Combine(bookDirectory, "metadata.opf"); string opfFilePath = Path.Combine(bookDirectory, "metadata.opf");
if (!File.Exists(opfFilePath)) if (!File.Exists(opfFilePath))
return Task.FromResult<ArtworkDto?>(null); return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
OpfDocumentDto document = OpfReader.Read(opfFilePath); OpfDocumentDto document = OpfReader.Read(opfFilePath);
if (string.IsNullOrWhiteSpace(document.CoverHref)) if (string.IsNullOrWhiteSpace(document.CoverHref))
return Task.FromResult<ArtworkDto?>(null); return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
// the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed // the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed
string coverFileName = Path.GetFileName(document.CoverHref); string coverFileName = Path.GetFileName(document.CoverHref);
if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref)) if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref))
return Task.FromResult<ArtworkDto?>(null); return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
string coverFilePath = Path.Combine(bookDirectory, coverFileName); string coverFilePath = Path.Combine(bookDirectory, coverFileName);
if (!File.Exists(coverFilePath)) if (!File.Exists(coverFilePath))
return Task.FromResult<ArtworkDto?>(null); return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
return Task.FromResult<ArtworkDto?>(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null)); return Task.FromResult<IReadOnlyList<ArtworkDto>>([new ArtworkDto(ArtworkType.Cover, Ordinal: 0, LocalPath: coverFilePath, RemoteUrl: null)]);
} }
} }
@@ -1,5 +1,6 @@
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.SecurityTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.IntegrationTests")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.IntegrationTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")] [assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")]
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
using Lumina.Plugins.CoverArtArchive.Core;
using Lumina.Plugins.CoverArtArchive.Core.Api;
using Lumina.Plugins.CoverArtArchive.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Http;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
/// <summary>
/// Utility class for registering the services of the Cover Art Archive artwork provider into the Dependency Injection container.
/// </summary>
internal static class CoverArtArchiveServices
{
/// <summary>
/// Registers the services of the Cover Art Archive artwork provider into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the artwork.</param>
/// <param name="settingsCallback">Action used to configure the <see cref="CoverArtArchiveSettingsDto"/>.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddCoverArtArchiveArtworkProvider(this IServiceCollection services, Guid pluginId, Action<CoverArtArchiveSettingsDto>? settingsCallback = null)
{
ArgumentNullException.ThrowIfNull(services);
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
services.TryAddScoped(serviceProvider =>
{
CoverArtArchiveSettingsDto defaults = new();
settingsCallback?.Invoke(defaults);
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
return new CoverArtArchiveSettingsProvider(settingsStore, pluginId, defaults);
});
// The throttle must be process-wide, because the Cover Art Archive API enforces its request policy across all callers, not per scope.
services.TryAddSingleton<CoverArtArchiveRequestThrottle>();
// The response cache is process-wide, so that an entity shared by many items, like the release group shared by the releases of an album,
// is fetched only once during a run.
services.TryAddSingleton<CoverArtArchiveResponseCache>();
// Automatic redirects are disabled on purpose: the metadata endpoints answer with a temporary redirect to the Internet Archive, and the client
// follows that redirect itself, checking every hop against CoverArtArchiveHosts. Letting the primary handler follow redirects automatically
// would make it follow whatever Location the response carries, which is server controlled, and would bypass that host check, which is the SSRF
// control here; the base URL being a constant does not make the redirect target trustworthy.
services.AddHttpClient<CoverArtArchiveHttpClient>()
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
// Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations.
services.AddKeyedTransient<IArtworkProvider, CoverArtArchiveAlbumArtworkProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the artwork of a release or a release group from the Cover Art Archive API.
/// </summary>
internal sealed record CoverArtArchiveArtworkResponse
{
/// <summary>
/// Gets the images of the artwork. It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements.
/// </summary>
[JsonPropertyName("images")]
public List<CoverArtArchiveImageResponse?>? Images { get; init; }
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a single image of the artwork of a release or a release group from the Cover Art Archive API.
/// </summary>
internal sealed record CoverArtArchiveImageResponse
{
/// <summary>
/// Gets the URL of the full size image.
/// </summary>
[JsonPropertyName("image")]
public string? Image { get; init; }
/// <summary>
/// Gets the URL of the thumbnail of the image.
/// </summary>
[JsonPropertyName("thumbnail")]
public string? Thumbnail { get; init; }
/// <summary>
/// Gets the types of the image, like "Front", "Back", "Booklet", "Medium", "Tray", "Spine" or "Poster".
/// It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements.
/// </summary>
[JsonPropertyName("types")]
public List<string?>? Types { get; init; }
/// <summary>
/// Gets a value indicating whether the image is the front cover.
/// </summary>
[JsonPropertyName("front")]
public bool IsFront { get; init; }
/// <summary>
/// Gets a value indicating whether the image is the back cover.
/// </summary>
[JsonPropertyName("back")]
public bool IsBack { get; init; }
/// <summary>
/// Gets the optional comment describing the image.
/// </summary>
[JsonPropertyName("comment")]
public string? Comment { get; init; }
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the Cover Art Archive artwork plugin.
/// </summary>
internal sealed class CoverArtArchiveSettingsDto
{
/// <summary>
/// Gets or sets the user agent sent with every request to the Cover Art Archive API.
/// </summary>
public string UserAgent { get; set; } = "Lumina-CoverArtArchive/1.0";
/// <summary>
/// Gets or sets the contact email sent with every request to the Cover Art Archive API.
/// The MetaBrainz services expect a meaningful user agent that carries a way to contact its author.
/// </summary>
public string? ContactEmail { get; set; }
/// <summary>
/// Gets or sets the minimum interval between consecutive requests to the Cover Art Archive API, so that the public service is not overwhelmed.
/// </summary>
public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
}
@@ -0,0 +1,256 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
using Lumina.Plugins.CoverArtArchive.Core.Settings;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core.Api;
/// <summary>
/// HTTP client that calls the Cover Art Archive API and deserializes its JSON responses into typed response models.
/// </summary>
internal sealed class CoverArtArchiveHttpClient
{
private const string BASE_URL = "https://coverartarchive.org/";
// Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
private const int MAXIMUM_ATTEMPT_COUNT = 3;
// The metadata endpoints of the Cover Art Archive answer with a temporary redirect to the Internet Archive, so a bounded number of redirects is followed.
private const int MAXIMUM_REDIRECT_COUNT = 3;
// The delay requested by a rate limited response is honored, but only up to this many seconds, so a misbehaving server cannot stall the scan.
private const double MAXIMUM_RETRY_DELAY_SECONDS = 60;
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web);
private readonly HttpClient _httpClient;
private readonly CoverArtArchiveSettingsProvider _settingsProvider;
private readonly CoverArtArchiveRequestThrottle _requestThrottle;
private readonly CoverArtArchiveResponseCache _responseCache;
/// <summary>
/// Initializes a new instance of the <see cref="CoverArtArchiveHttpClient"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the Cover Art Archive API.</param>
/// <param name="settingsProvider">The provider of the settings that configure the Cover Art Archive API requests.</param>
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the Cover Art Archive API.</param>
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
public CoverArtArchiveHttpClient(HttpClient httpClient, CoverArtArchiveSettingsProvider settingsProvider, CoverArtArchiveRequestThrottle requestThrottle, CoverArtArchiveResponseCache responseCache)
{
_httpClient = httpClient;
_settingsProvider = settingsProvider;
_requestThrottle = requestThrottle;
_responseCache = responseCache;
}
/// <summary>
/// Gets the artwork of the release identified by <paramref name="musicBrainzReleaseId"/>.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artwork of the release, or <see langword="null"/> when the release has no artwork.</returns>
public Task<CoverArtArchiveArtworkResponse?> GetReleaseArtworkAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<CoverArtArchiveArtworkResponse>($"release/{musicBrainzReleaseId:D}", cancellationToken);
}
/// <summary>
/// Gets the artwork of the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artwork of the release group, or <see langword="null"/> when the release group has no artwork.</returns>
public Task<CoverArtArchiveArtworkResponse?> GetReleaseGroupArtworkAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<CoverArtArchiveArtworkResponse>($"release-group/{musicBrainzReleaseGroupId:D}", cancellationToken);
}
/// <summary>
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="TModel"/>.
/// </summary>
/// <typeparam name="TModel">The type to deserialize the JSON response into.</typeparam>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
private async Task<TModel?> GetJsonOrNullAsync<TModel>(string relativeUrl, CancellationToken cancellationToken)
{
// A cached response, including a confirmed absence of artwork, removes the repeated lookups of the same entity, like the release group that the
// releases of an edition heavy library share, or the same library scanned again while the entry is still valid.
if (_responseCache.TryGet(relativeUrl, out string? cachedJson))
return string.IsNullOrEmpty(cachedJson) ? default : JsonSerializer.Deserialize<TModel>(cachedJson, s_serializerOptions);
CoverArtArchiveSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
// A 404 means the entity exists but has no artwork, which is a normal miss rather than an error, so it is reported as no result and cached as such.
if (response.StatusCode == HttpStatusCode.NotFound)
{
_responseCache.Set(relativeUrl, string.Empty);
return default;
}
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
TModel? model = JsonSerializer.Deserialize<TModel>(json, s_serializerOptions);
_responseCache.Set(relativeUrl, json);
return model;
}
/// <summary>
/// Sends a GET request to the Cover Art Archive API, throttled to respect the configured minimum request interval. Transient failures and
/// rate limiting are retried, so a single hiccup does not surface as a failed resolution.
/// </summary>
/// <param name="settings">The settings that configure the Cover Art Archive API requests.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> SendAsync(CoverArtArchiveSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
{
EnsureRequestHeaders(settings);
Uri requestUri = new(new Uri(BASE_URL, UriKind.Absolute), relativeUrl);
// The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the
// automatic redirects disabled and confines the following to the hosts the Cover Art Archive is allowed to delegate its responses to.
for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++)
{
HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, cancellationToken).ConfigureAwait(false);
if (!IsRedirect(response.StatusCode) || response.Headers.Location is null)
return response;
Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location);
// The response of a redirect is not returned, so it must be disposed here to release its connection.
response.Dispose();
// A redirect that is not an absolute HTTPS URL, or that points to a host other than the Cover Art Archive or the Internet Archive, is refused,
// so a compromised or misbehaving endpoint cannot redirect the request to any other host.
if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !CoverArtArchiveHosts.IsAllowed(redirectUri.Host))
throw new HttpRequestException($"The Cover Art Archive redirected the request to the disallowed host '{redirectUri?.Host}'.");
requestUri = redirectUri;
}
throw new HttpRequestException("The Cover Art Archive redirected the request too many times.");
}
/// <summary>
/// Sends a GET request to <paramref name="requestUri"/>, throttled to respect the configured minimum request interval.
/// Transient failures and rate limiting are retried, so a single hiccup does not surface as a failed resolution.
/// </summary>
/// <param name="settings">The settings that configure the Cover Art Archive API requests.</param>
/// <param name="requestUri">The absolute URI of the resource to request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> SendWithRetriesAsync(CoverArtArchiveSettingsDto settings, Uri requestUri, CancellationToken cancellationToken)
{
// A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every
// attempt, so that the retries of a failed request cannot burst past the rate limit of the public service.
for (int attempt = 1; ; attempt++)
{
await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false);
bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT;
HttpResponseMessage response;
try
{
HttpRequestMessage request = new(HttpMethod.Get, requestUri);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException) when (!isLastAttempt)
{
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
continue;
}
if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
{
// The delay is read before the response is disposed, because a rate limited response tells the caller how long to wait.
TimeSpan retryDelay = GetRetryDelay(attempt, response);
// The response of a failed attempt is not returned, so it must be disposed here to release its connection.
response.Dispose();
await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
continue;
}
return response;
}
}
/// <summary>
/// Determines whether the provided status code is a redirect.
/// </summary>
/// <param name="statusCode">The status code to check.</param>
/// <returns><see langword="true"/> when the status code is a redirect, otherwise <see langword="false"/>.</returns>
private static bool IsRedirect(HttpStatusCode statusCode)
{
return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther
or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect;
}
/// <summary>
/// Resolves the location of a redirect against the URI of the request it was returned for.
/// </summary>
/// <param name="requestUri">The URI of the request the redirect was returned for.</param>
/// <param name="location">The location of the redirect.</param>
/// <returns>The absolute URI of the redirect, or <see langword="null"/> when it could not be resolved.</returns>
private static Uri? ResolveRedirect(Uri requestUri, Uri location)
{
if (location.IsAbsoluteUri)
return location;
return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null;
}
/// <summary>
/// Gets the delay to wait before the next attempt, preferring the delay requested by the Cover Art Archive when it is provided.
/// </summary>
/// <param name="attempt">The one based number of the attempt that just failed.</param>
/// <param name="response">The response of the failed attempt, when the failure was a response rather than a transport exception.</param>
/// <returns>The delay to wait before the next attempt.</returns>
internal static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
{
// The delay requested by the response is preferred when it is provided, so the rate limit policy of the Cover Art Archive is honored.
if (response?.Headers.RetryAfter is { } retryAfter)
{
TimeSpan? requestedDelay = retryAfter.Delta;
if (requestedDelay is null && retryAfter.Date is DateTimeOffset date)
{
TimeSpan wait = date - DateTimeOffset.UtcNow;
if (wait > TimeSpan.Zero)
requestedDelay = wait;
}
if (requestedDelay is TimeSpan delay)
{
// A misbehaving server could ask for an extremely long delay, which would stall the scan until it is cancelled, so the wait is capped.
TimeSpan maximumDelay = TimeSpan.FromSeconds(MAXIMUM_RETRY_DELAY_SECONDS);
return delay > maximumDelay ? maximumDelay : delay;
}
}
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
}
/// <summary>
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
/// </summary>
/// <param name="settings">The settings that configure the Cover Art Archive API requests.</param>
private void EnsureRequestHeaders(CoverArtArchiveSettingsDto settings)
{
// The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once.
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
{
string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail)
? settings.UserAgent
: $"{settings.UserAgent} ( {settings.ContactEmail} )";
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
}
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core.Api;
/// <summary>
/// Class for spacing out the requests sent to the Cover Art Archive API, so the configured minimum request interval is respected across every caller in the process.
/// </summary>
internal sealed class CoverArtArchiveRequestThrottle
{
private readonly SemaphoreSlim _gate = new(1, 1);
// The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter which caller sends them.
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
/// <summary>
/// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
/// </summary>
/// <param name="minimumRequestInterval">The minimum amount of time that must elapse between two consecutive requests.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that completes once the caller may send its request.</returns>
public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
{
// The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
// previous reserved slot.
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
if (minimumRequestInterval > TimeSpan.Zero)
{
DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
_lastRequestAt = DateTimeOffset.UtcNow;
}
finally
{
_gate.Release();
}
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core.Api;
/// <summary>
/// In-memory cache of the responses returned by the Cover Art Archive API, keyed by the requested URL.
/// It removes the repeated lookups of the same entity during a run, which is significant because the releases of an edition heavy library share their
/// release groups, and it expires its entries after a bounded time.
/// </summary>
internal sealed class CoverArtArchiveResponseCache
{
/// <summary>
/// The maximum number of responses the cache keeps.
/// </summary>
internal const int MAXIMUM_ENTRY_COUNT = 20_000;
/// <summary>
/// The maximum total number of characters of the cached response bodies.
/// </summary>
internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
/// <summary>
/// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
/// eviction from running on every write once a budget is reached.
/// </summary>
private const int TRIM_TARGET_PERCENT = 90;
private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
private readonly int _maximumEntryCount;
private readonly long _maximumCharacterCount;
private readonly TimeSpan _timeToLive;
private readonly ConcurrentDictionary<string, CacheEntry> _entries = new(StringComparer.Ordinal);
// The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
// are guarded by a lock, while reads stay lock free.
private readonly Lock _sizeGate = new();
private long _cachedCharacterCount;
// Monotonically increasing insertion stamp, used to evict the oldest entries first.
private long _sequence;
/// <summary>
/// Initializes a new instance of the <see cref="CoverArtArchiveResponseCache"/> class with the default budgets and time to live.
/// </summary>
public CoverArtArchiveResponseCache()
{
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
_timeToLive = s_timeToLive;
}
/// <summary>
/// Initializes a new instance of the <see cref="CoverArtArchiveResponseCache"/> class with the provided budgets and time to live.
/// </summary>
/// <param name="maximumEntryCount">The maximum number of responses the cache keeps.</param>
/// <param name="maximumCharacterCount">The maximum total number of characters of the cached response bodies.</param>
/// <param name="timeToLive">The amount of time a cached response stays valid.</param>
internal CoverArtArchiveResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
{
_maximumEntryCount = maximumEntryCount;
_maximumCharacterCount = maximumCharacterCount;
_timeToLive = timeToLive;
}
/// <summary>
/// Tries to get the cached response body for <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The cached response body, when found.</param>
/// <returns><see langword="true"/> when an unexpired response was found, otherwise <see langword="false"/>.</returns>
public bool TryGet(string key, out string? json)
{
// An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
{
json = entry.Json;
return true;
}
json = null;
return false;
}
/// <summary>
/// Adds or replaces the cached response body for <paramref name="key"/>, then trims the cache back to its budgets.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The response body to cache.</param>
public void Set(string key, string json)
{
// A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
if (json.Length > _maximumCharacterCount)
return;
lock (_sizeGate)
{
if (_entries.TryRemove(key, out CacheEntry? existing))
_cachedCharacterCount -= existing.Json.Length;
_entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
_cachedCharacterCount += json.Length;
if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
TrimToBudget();
}
}
/// <summary>
/// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
/// </summary>
private void TrimToBudget()
{
DateTime utcNow = DateTime.UtcNow;
bool isOverEntryCount = _entries.Count > _maximumEntryCount;
bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
// Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
// a budget was not exceeded, so the cache keeps reclaiming dead entries.
foreach (KeyValuePair<string, CacheEntry> candidate in _entries.OrderBy(entry => entry.Value.Sequence))
{
bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
break;
if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
_cachedCharacterCount -= removed.Json.Length;
}
}
private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
using Lumina.Plugins.CoverArtArchive.Core.Api;
using Lumina.Plugins.CoverArtArchive.Core.Mapping;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core;
/// <summary>
/// Provides the artwork of an album from the Cover Art Archive, by resolving the MusicBrainz identifiers of the album into artwork DTOs.
/// The artwork of the exact release is preferred, and the artwork of its release group is used when the release itself carries none.
/// </summary>
internal sealed class CoverArtArchiveAlbumArtworkProvider : IArtworkProvider<AlbumMetadataLookupDto>
{
private readonly CoverArtArchiveHttpClient _coverArtArchiveHttpClient;
/// <summary>
/// Gets the display name of the artwork provider.
/// </summary>
public string Name => "Cover Art Archive";
/// <summary>
/// Gets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="CoverArtArchiveAlbumArtworkProvider"/> class.
/// </summary>
/// <param name="coverArtArchiveHttpClient">The HTTP client used to call the Cover Art Archive API.</param>
public CoverArtArchiveAlbumArtworkProvider(CoverArtArchiveHttpClient coverArtArchiveHttpClient)
{
_coverArtArchiveHttpClient = coverArtArchiveHttpClient;
}
/// <summary>
/// Gets the artworks of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the artwork for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artworks of the album, or an empty collection when no artwork was found.</returns>
public async Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
CoverArtArchiveArtworkResponse? artwork = null;
// The identifier of the exact release pins the edition the local files match, so its artwork is preferred.
if (lookup.MusicBrainzReleaseId is not null)
artwork = await _coverArtArchiveHttpClient.GetReleaseArtworkAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
// A release can carry no artwork of its own while its release group does, so the release group is the fallback.
// The collection is guarded here too, because the deserializer can produce a null collection regardless of the initializer.
if ((artwork?.Images is null || artwork.Images.Count == 0) && lookup.MusicBrainzReleaseGroupId is not null)
artwork = await _coverArtArchiveHttpClient.GetReleaseGroupArtworkAsync(lookup.MusicBrainzReleaseGroupId.Value, cancellationToken).ConfigureAwait(false);
return CoverArtArchiveMapper.MapArtwork(artwork);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core;
/// <summary>
/// Defines the hosts of the Cover Art Archive and the Internet Archive, which are the only hosts the plugin queries, the only hosts it may follow a
/// redirect to, and the only hosts it may fetch artwork from. The Cover Art Archive is not self hostable, so no other host can be a legitimate source.
/// </summary>
internal static class CoverArtArchiveHosts
{
/// <summary>
/// Determines whether the provided host is one of the hosts the Cover Art Archive may delegate its responses to.
/// </summary>
/// <param name="host">The host to check.</param>
/// <returns><see langword="true"/> when the host is allowed, otherwise <see langword="false"/>.</returns>
public static bool IsAllowed(string host)
{
return host.Equals("coverartarchive.org", StringComparison.OrdinalIgnoreCase)
|| host.EndsWith(".coverartarchive.org", StringComparison.OrdinalIgnoreCase)
|| host.Equals("archive.org", StringComparison.OrdinalIgnoreCase)
|| host.EndsWith(".archive.org", StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,77 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
using Lumina.Plugins.CoverArtArchive.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core;
/// <summary>
/// Plugin that provides music album artwork retrieval from the Cover Art Archive.
/// </summary>
public sealed class CoverArtArchivePlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "Cover Art Archive";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return
[
new PluginSettingDescriptorDto(
Key: CoverArtArchiveSettingsKeys.CONTACT_EMAIL,
Label: "Contact Email",
Type: PluginSettingType.Text),
new PluginSettingDescriptorDto(
Key: CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS,
Label: "Minimum Request Interval (seconds)",
Type: PluginSettingType.Number,
DefaultValue: "1.0")
];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddCoverArtArchiveArtworkProvider(pluginId: Id);
}
}
@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core.Mapping;
/// <summary>
/// Maps the responses of the Cover Art Archive API into artwork DTOs.
/// </summary>
internal static class CoverArtArchiveMapper
{
/// <summary>
/// Maps the artwork carried by <paramref name="response"/> into artwork DTOs, one for every type each image is tagged with.
/// </summary>
/// <param name="response">The artwork response to map.</param>
/// <returns>The mapped artworks, ordered as they appear in the response, or an empty collection when there is no artwork.</returns>
public static IReadOnlyList<ArtworkDto> MapArtwork(CoverArtArchiveArtworkResponse? response)
{
// The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers.
if (response?.Images is null)
return [];
List<ArtworkDto> artworks = [];
// The ordinals are tracked per type, so that multiple images of the same type, like the pages of a booklet, are ordered among themselves.
Dictionary<ArtworkType, int> nextOrdinals = [];
foreach (CoverArtArchiveImageResponse? image in response.Images)
{
if (image is null || !TryResolveArtworkUrl(image.Image, out string artworkUrl))
continue;
foreach (ArtworkType artworkType in ResolveArtworkTypes(image))
{
int ordinal = nextOrdinals.TryGetValue(artworkType, out int nextOrdinal) ? nextOrdinal : 0;
nextOrdinals[artworkType] = ordinal + 1;
artworks.Add(new ArtworkDto(artworkType, ordinal, LocalPath: null, RemoteUrl: artworkUrl));
}
}
return artworks;
}
/// <summary>
/// Resolves the URL of an artwork image, keeping it only when it points, over an encrypted connection, at a host the Cover Art Archive may serve
/// artwork from. An image URL of any other shape or host is dropped, so a compromised response cannot make the host download from an internal address.
/// </summary>
/// <param name="candidate">The image URL carried by the response.</param>
/// <param name="artworkUrl">The resolved, encrypted image URL, when it is usable.</param>
/// <returns><see langword="true"/> when the image URL is usable, otherwise <see langword="false"/>.</returns>
private static bool TryResolveArtworkUrl(string? candidate, out string artworkUrl)
{
artworkUrl = string.Empty;
if (string.IsNullOrWhiteSpace(candidate))
return false;
if (!Uri.TryCreate(candidate.Trim(), UriKind.Absolute, out Uri? uri) || !CoverArtArchiveHosts.IsAllowed(uri.Host))
return false;
// The artwork is always fetched over an encrypted connection, so a plain HTTP reference to a trusted host is upgraded to HTTPS,
// and a reference that uses any other scheme is dropped.
if (uri.Scheme == Uri.UriSchemeHttps)
artworkUrl = uri.AbsoluteUri;
else if (uri.Scheme == Uri.UriSchemeHttp)
artworkUrl = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps, Port = -1 }.Uri.AbsoluteUri;
else
return false;
return true;
}
/// <summary>
/// Resolves the artwork types an image is tagged with, falling back to the front and back flags when the image carries no type.
/// </summary>
/// <param name="image">The image whose types are resolved.</param>
/// <returns>The distinct artwork types of the image, in the order they appear in the response.</returns>
private static List<ArtworkType> ResolveArtworkTypes(CoverArtArchiveImageResponse image)
{
// A list de-duplicated on insertion keeps the order of the response, unlike a set, whose iteration order is not deterministic.
List<ArtworkType> artworkTypes = [];
// The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers.
foreach (string? type in image.Types ?? [])
if (TryMapArtworkType(type, out ArtworkType artworkType) && !artworkTypes.Contains(artworkType))
artworkTypes.Add(artworkType);
// An image that carries no known type still describes the front or the back of the release when it is flagged as such.
if (artworkTypes.Count == 0)
{
if (image.IsFront)
artworkTypes.Add(ArtworkType.Cover);
if (image.IsBack)
artworkTypes.Add(ArtworkType.Back);
}
return artworkTypes;
}
/// <summary>
/// Maps a Cover Art Archive image type onto an artwork type.
/// </summary>
/// <param name="type">The Cover Art Archive image type.</param>
/// <param name="artworkType">The mapped artwork type, when the type is recognized.</param>
/// <returns><see langword="true"/> when the type was recognized, otherwise <see langword="false"/>.</returns>
private static bool TryMapArtworkType(string? type, out ArtworkType artworkType)
{
if (string.IsNullOrWhiteSpace(type))
{
artworkType = ArtworkType.Other;
return false;
}
switch (type.Trim().ToLowerInvariant())
{
case "front":
artworkType = ArtworkType.Cover;
return true;
case "back":
artworkType = ArtworkType.Back;
return true;
case "booklet":
artworkType = ArtworkType.Booklet;
return true;
case "medium":
artworkType = ArtworkType.Medium;
return true;
case "tray":
artworkType = ArtworkType.Tray;
return true;
case "spine":
artworkType = ArtworkType.Spine;
return true;
case "obi":
artworkType = ArtworkType.Obi;
return true;
case "sticker":
artworkType = ArtworkType.Sticker;
return true;
case "poster":
artworkType = ArtworkType.Poster;
return true;
case "liner":
artworkType = ArtworkType.Liner;
return true;
case "watermark":
artworkType = ArtworkType.Watermark;
return true;
default:
// The Cover Art Archive also uses a free form "Other" type and may add new types over time, which are all kept as generic artwork.
artworkType = ArtworkType.Other;
return true;
}
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Plugins.CoverArtArchive.Core.Settings;
/// <summary>
/// Keys of the settings of the Cover Art Archive artwork plugin, shared by the settings schema and the settings loader.
/// </summary>
internal static class CoverArtArchiveSettingsKeys
{
/// <summary>
/// The key of the setting defining the contact email sent to the Cover Art Archive API.
/// </summary>
internal const string CONTACT_EMAIL = "ContactEmail";
/// <summary>
/// The key of the setting defining the minimum interval between consecutive requests to the Cover Art Archive API, in seconds.
/// </summary>
internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.CoverArtArchive.Core.Settings;
/// <summary>
/// Provides the runtime settings of the Cover Art Archive artwork plugin, overlaying the settings persisted by the host over the configured defaults.
/// </summary>
internal sealed class CoverArtArchiveSettingsProvider
{
// The minimum request interval is clamped to a sane range, so a persisted value can neither be a non finite value that cannot be turned into a
// duration, nor be so large that waiting for it overflows the delay of the requests.
private const double MAXIMUM_REQUEST_INTERVAL_SECONDS = 60;
private readonly IPluginSettingsStore? _settingsStore;
private readonly Guid _pluginId;
private readonly CoverArtArchiveSettingsDto _defaults;
// The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already
// resolved path lock free; the gate is only needed by the first callers that race to resolve it.
private readonly SemaphoreSlim _gate = new(1, 1);
private CoverArtArchiveSettingsDto? _runtimeSettings;
/// <summary>
/// Initializes a new instance of the <see cref="CoverArtArchiveSettingsProvider"/> class.
/// </summary>
/// <param name="settingsStore">The store of the settings persisted by the host, or <see langword="null"/> when no store is available.</param>
/// <param name="pluginId">The unique identifier of the plugin whose settings are read.</param>
/// <param name="defaults">The runtime settings with the default values and the optional configuration callback already applied.</param>
public CoverArtArchiveSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, CoverArtArchiveSettingsDto defaults)
{
_settingsStore = settingsStore;
_pluginId = pluginId;
_defaults = defaults;
}
/// <summary>
/// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The runtime settings of the plugin.</returns>
public async Task<CoverArtArchiveSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
CoverArtArchiveSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
if (runtimeSettings is not null)
return runtimeSettings;
// Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once.
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Second check inside the gate: another caller may have resolved the settings while this one was waiting for it.
runtimeSettings = Volatile.Read(ref _runtimeSettings);
if (runtimeSettings is null)
{
runtimeSettings = await ResolveAsync(cancellationToken).ConfigureAwait(false);
// Publishing through Volatile makes the fully built instance visible to the lock free readers above.
Volatile.Write(ref _runtimeSettings, runtimeSettings);
}
return runtimeSettings;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Builds the runtime settings by overlaying the settings persisted by the host over the configured defaults.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The runtime settings of the plugin.</returns>
private async Task<CoverArtArchiveSettingsDto> ResolveAsync(CancellationToken cancellationToken)
{
// The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes.
CoverArtArchiveSettingsDto runtimeSettings = new()
{
UserAgent = _defaults.UserAgent,
ContactEmail = _defaults.ContactEmail,
MinimumRequestInterval = _defaults.MinimumRequestInterval
};
if (_settingsStore is null)
return runtimeSettings;
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
if (storedSettings is null)
return runtimeSettings;
if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.CONTACT_EMAIL, out string? contactEmail))
{
string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
runtimeSettings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null;
}
// A persisted value that is not a finite number is rejected, and a finite one is clamped, so that neither a NaN, nor an infinity, nor an
// out of range value can make the conversion to a duration or the waiting for it throw.
if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue) &&
double.IsFinite(minimumRequestIntervalValue))
runtimeSettings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Clamp(minimumRequestIntervalValue, 0, MAXIMUM_REQUEST_INTERVAL_SECONDS));
return runtimeSettings;
}
/// <summary>
/// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header.
/// </summary>
/// <param name="contactEmail">The persisted contact email.</param>
/// <returns><see langword="true"/> when the email is safe, otherwise <see langword="false"/>.</returns>
private static bool IsSafeContactEmail(string contactEmail)
{
// The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin,
// so, anything outside a conservative email charset is rejected.
foreach (char character in contactEmail)
if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+'))
return false;
return true;
}
}
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.SecurityTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.Fixtures")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Core;
using Lumina.Plugins.ID3.Core.Tags;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
#endregion
namespace Lumina.Plugins.ID3.Common.DependencyInjection;
/// <summary>
/// Utility class for registering the services of the ID3 metadata provider into the Dependency Injection container.
/// </summary>
internal static class Id3Services
{
/// <summary>
/// Registers the services of the ID3 metadata providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddId3MetadataProviders(this IServiceCollection services, Guid pluginId)
{
ArgumentNullException.ThrowIfNull(services);
// The reader is scoped, so that the tags of a single file are read only once across the artist, album and track providers of the same enrichment scope.
services.TryAddScoped<Id3TagReader>();
// Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations.
// A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair.
services.AddKeyedTransient<IMetadataProvider, Id3ArtistMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, Id3AlbumMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, Id3TrackMetadataProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,258 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.ID3.Common.Models.DTO.Tags;
/// <summary>
/// Snapshot of the metadata read from the embedded tags of a single audio file.
/// Every audio property that the tags do not carry is left empty, so that the local values already extracted from the file are never overwritten with blanks.
/// </summary>
internal sealed class Id3TagDto
{
/// <summary>
/// Gets or initializes the title of the track.
/// </summary>
public string? Title { get; init; }
/// <summary>
/// Gets or initializes the title of the album the track belongs to.
/// </summary>
public string? Album { get; init; }
/// <summary>
/// Gets or initializes the artists credited on the track.
/// </summary>
public List<string> TrackArtists { get; init; } = [];
/// <summary>
/// Gets or initializes the artists credited on the album.
/// </summary>
public List<string> AlbumArtists { get; init; } = [];
/// <summary>
/// Gets or initializes the sort name of the album artist.
/// </summary>
public string? AlbumArtistSortName { get; init; }
/// <summary>
/// Gets or initializes the sort name of the track artist.
/// </summary>
public string? TrackArtistSortName { get; init; }
/// <summary>
/// Gets or initializes the number of the track on its disc.
/// </summary>
public uint TrackNumber { get; init; }
/// <summary>
/// Gets or initializes the number of tracks on the disc, as reported by the tags.
/// </summary>
public uint TrackCount { get; init; }
/// <summary>
/// Gets or initializes the number of the disc the track belongs to.
/// </summary>
public uint DiscNumber { get; init; }
/// <summary>
/// Gets or initializes the number of discs of the release, as reported by the tags.
/// </summary>
public uint DiscCount { get; init; }
/// <summary>
/// Gets or initializes the year the track was released.
/// </summary>
public int? Year { get; init; }
/// <summary>
/// Gets or initializes the original release date of the track.
/// </summary>
public DateOnly? OriginalReleaseDate { get; init; }
/// <summary>
/// Gets or initializes the original release year of the track.
/// </summary>
public int? OriginalReleaseYear { get; init; }
/// <summary>
/// Gets or initializes the genres the tags associate with the track.
/// </summary>
public List<string> Genres { get; init; } = [];
/// <summary>
/// Gets or initializes the composers credited on the track.
/// </summary>
public List<string> Composers { get; init; } = [];
/// <summary>
/// Gets or initializes the lyricists credited on the track.
/// </summary>
public List<string> Lyricists { get; init; } = [];
/// <summary>
/// Gets or initializes the conductors credited on the track.
/// </summary>
public List<string> Conductors { get; init; } = [];
/// <summary>
/// Gets or initializes the remixers credited on the track.
/// </summary>
public List<string> Remixers { get; init; } = [];
/// <summary>
/// Gets or initializes the people credited on the track, each with the free-form role read from the tags.
/// </summary>
public List<(string Role, string Name)> InvolvedPeople { get; init; } = [];
/// <summary>
/// Gets or initializes the language of the track.
/// </summary>
public string? Language { get; init; }
/// <summary>
/// Gets or initializes the script used by the language of the track.
/// </summary>
public string? Script { get; init; }
/// <summary>
/// Gets or initializes the label that issued the album.
/// </summary>
public string? Label { get; init; }
/// <summary>
/// Gets or initializes the catalog numbers of the album.
/// </summary>
public List<string> CatalogNumbers { get; init; } = [];
/// <summary>
/// Gets or initializes the barcode of the album.
/// </summary>
public string? Barcode { get; init; }
/// <summary>
/// Gets or initializes the types of the release, as read from the tags.
/// </summary>
public List<string> ReleaseTypes { get; init; } = [];
/// <summary>
/// Gets or initializes the status of the release.
/// </summary>
public string? ReleaseStatus { get; init; }
/// <summary>
/// Gets or initializes the country the release was issued in.
/// </summary>
public string? ReleaseCountry { get; init; }
/// <summary>
/// Gets or initializes the physical or digital medium of the release.
/// </summary>
public string? MediaFormat { get; init; }
/// <summary>
/// Gets or initializes the outermost packaging of the release.
/// </summary>
public string? Packaging { get; init; }
/// <summary>
/// Gets or initializes the ASIN of the album.
/// </summary>
public string? Asin { get; init; }
/// <summary>
/// Gets or initializes the ISRCs of the track.
/// </summary>
public List<string> Isrcs { get; init; } = [];
/// <summary>
/// Gets or initializes the moods of the track.
/// </summary>
public List<string> Moods { get; init; } = [];
/// <summary>
/// Gets or initializes the title of the work the track is a recording of.
/// </summary>
public string? WorkTitle { get; init; }
/// <summary>
/// Gets or initializes the musical key of the track.
/// </summary>
public string? MusicKey { get; init; }
/// <summary>
/// Gets or initializes the tempo of the track in beats per minute.
/// </summary>
public int? Bpm { get; init; }
/// <summary>
/// Gets or initializes the duration of the audio of the track in seconds.
/// </summary>
public int? DurationInSeconds { get; init; }
/// <summary>
/// Gets or initializes the sample rate of the audio of the track in Hz.
/// </summary>
public int? SampleRate { get; init; }
/// <summary>
/// Gets or initializes the number of audio channels of the track.
/// </summary>
public int? Channels { get; init; }
/// <summary>
/// Gets or initializes the bit depth of the audio of the track.
/// </summary>
public int? BitDepth { get; init; }
/// <summary>
/// Gets or initializes the bitrate of the audio of the track in kbps.
/// </summary>
public int? Bitrate { get; init; }
/// <summary>
/// Gets or initializes the description of the audio codec of the track.
/// </summary>
public string? AudioCodec { get; init; }
/// <summary>
/// Gets or initializes the official website associated with the artist.
/// </summary>
public string? Website { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the artist.
/// </summary>
public string? MusicBrainzArtistId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the release artist.
/// </summary>
public string? MusicBrainzReleaseArtistId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the release group.
/// </summary>
public string? MusicBrainzReleaseGroupId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the release.
/// </summary>
public string? MusicBrainzReleaseId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the recording of the track.
/// </summary>
public string? MusicBrainzRecordingId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the track on its release.
/// </summary>
public string? MusicBrainzReleaseTrackId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the work the track is a recording of.
/// </summary>
public string? MusicBrainzWorkId { get; init; }
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using Lumina.Plugins.ID3.Core.Mapping;
using Lumina.Plugins.ID3.Core.Tags;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Provides album metadata from the embedded tags of one of its audio files, by resolving lookups into album metadata DTOs.
/// </summary>
internal sealed class Id3AlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
{
private readonly Id3TagReader _tagReader;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "ID3";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="Id3AlbumMetadataProvider"/> class.
/// </summary>
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
public Id3AlbumMetadataProvider(Id3TagReader tagReader)
{
_tagReader = tagReader;
}
/// <summary>
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of album metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
AlbumMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false);
IReadOnlyList<AlbumMetadataDto> results = metadata is null ? [] : [metadata];
return results;
}
/// <summary>
/// Gets the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when the file carries none.</returns>
public Task<AlbumMetadataDto?> GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return ReadMetadataAsync(lookup.Path, cancellationToken);
}
/// <summary>
/// Reads the metadata of the album from the embedded tags of the track stored at <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of a track of the album.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when the tags carry no album title.</returns>
private Task<AlbumMetadataDto?> ReadMetadataAsync(string path, CancellationToken cancellationToken)
{
// The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file.
return Task.Run(() =>
{
Id3TagDto? data = _tagReader.Read(path);
if (data is null || string.IsNullOrWhiteSpace(data.Album))
return null;
return Id3TagMapper.MapAlbum(data);
}, cancellationToken);
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using Lumina.Plugins.ID3.Core.Mapping;
using Lumina.Plugins.ID3.Core.Tags;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Provides music artist metadata from the embedded tags of one of its audio files, by resolving lookups into artist metadata DTOs.
/// </summary>
internal sealed class Id3ArtistMetadataProvider : IMetadataProvider<ArtistMetadataLookupDto, ArtistMetadataDto>
{
private readonly Id3TagReader _tagReader;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "ID3";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="Id3ArtistMetadataProvider"/> class.
/// </summary>
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
public Id3ArtistMetadataProvider(Id3TagReader tagReader)
{
_tagReader = tagReader;
}
/// <summary>
/// Searches for the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of artist metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
public async Task<IReadOnlyList<ArtistMetadataDto>> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
ArtistMetadataDto? metadata = await ReadMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
IReadOnlyList<ArtistMetadataDto> results = metadata is null ? [] : [metadata];
return results;
}
/// <summary>
/// Gets the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when the file carries none.</returns>
public Task<ArtistMetadataDto?> GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return ReadMetadataAsync(lookup, cancellationToken);
}
/// <summary>
/// Reads the metadata of the artist described by <paramref name="lookup"/> from the embedded tags of the track stored at its path.
/// </summary>
/// <param name="lookup">The lookup describing the artist.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when the tags carry no artist name.</returns>
private Task<ArtistMetadataDto?> ReadMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file.
return Task.Run(() =>
{
Id3TagDto? data = _tagReader.Read(lookup.Path);
if (data is null || (data.AlbumArtists.Count == 0 && data.TrackArtists.Count == 0))
return null;
return Id3TagMapper.MapArtist(data, lookup.Name);
}, cancellationToken);
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.ID3.Common.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Plugin that populates music metadata exclusively from the embedded tags of the audio files, without accessing the web.
/// </summary>
public sealed class Id3Plugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "ID3 Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return [];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddId3MetadataProviders(pluginId: Id);
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using Lumina.Plugins.ID3.Core.Mapping;
using Lumina.Plugins.ID3.Core.Tags;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Provides track metadata from the embedded tags of the audio file, by resolving lookups into audio metadata DTOs.
/// </summary>
internal sealed class Id3TrackMetadataProvider : IMetadataProvider<TrackMetadataLookupDto, AudioMetadataDto>
{
private readonly Id3TagReader _tagReader;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "ID3";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="Id3TrackMetadataProvider"/> class.
/// </summary>
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
public Id3TrackMetadataProvider(Id3TagReader tagReader)
{
_tagReader = tagReader;
}
/// <summary>
/// Searches for the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of track metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
public async Task<IReadOnlyList<AudioMetadataDto>> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
AudioMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false);
IReadOnlyList<AudioMetadataDto> results = metadata is null ? [] : [metadata];
return results;
}
/// <summary>
/// Gets the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when the file carries none.</returns>
public Task<AudioMetadataDto?> GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return ReadMetadataAsync(lookup.Path, cancellationToken);
}
/// <summary>
/// Reads the metadata of the track stored at <paramref name="path"/> from its embedded tags.
/// </summary>
/// <param name="path">The file system path of the track.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when the tags carry no title.</returns>
private Task<AudioMetadataDto?> ReadMetadataAsync(string path, CancellationToken cancellationToken)
{
// The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file.
return Task.Run(() =>
{
Id3TagDto? data = _tagReader.Read(path);
if (data is null || string.IsNullOrWhiteSpace(data.Title))
return null;
return Id3TagMapper.MapTrack(data);
}, cancellationToken);
}
}
@@ -0,0 +1,644 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#endregion
namespace Lumina.Plugins.ID3.Core.Mapping;
/// <summary>
/// Maps the metadata read from the embedded tags of an audio file into the application's media metadata DTOs.
/// </summary>
internal static class Id3TagMapper
{
/// <summary>
/// The neutral cultures of the application, keyed by both their two letter and three letter language codes, so that a language code is resolved without enumerating the cultures of the system for every mapped file.
/// </summary>
private static readonly Dictionary<string, CultureInfo> s_culturesByLanguageCode = BuildCulturesByLanguageCode();
/// <summary>
/// Builds the map of the neutral cultures of the application, keyed by their language codes.
/// </summary>
/// <returns>The cultures, keyed by both their two letter and three letter language codes.</returns>
private static Dictionary<string, CultureInfo> BuildCulturesByLanguageCode()
{
Dictionary<string, CultureInfo> cultures = new(StringComparer.OrdinalIgnoreCase);
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
if (culture.ThreeLetterISOLanguageName.Length == 3 && !cultures.ContainsKey(culture.ThreeLetterISOLanguageName))
cultures[culture.ThreeLetterISOLanguageName] = culture;
if (culture.TwoLetterISOLanguageName.Length == 2 && !cultures.ContainsKey(culture.TwoLetterISOLanguageName))
cultures[culture.TwoLetterISOLanguageName] = culture;
}
return cultures;
}
/// <summary>
/// Maps the tags of an audio file into artist metadata.
/// </summary>
/// <param name="data">The tags of a track of the artist.</param>
/// <param name="artistName">The name of the artist the metadata is mapped for, when known, used to select the matching credited artist.</param>
/// <returns>The mapped artist metadata.</returns>
public static ArtistMetadataDto MapArtist(Id3TagDto data, string? artistName)
{
bool doesMatchTrackArtist = !string.IsNullOrWhiteSpace(artistName) && data.TrackArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase));
bool doesMatchAlbumArtist = !string.IsNullOrWhiteSpace(artistName) && data.AlbumArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase));
string? mappedName;
string? mappedSortName;
Guid? musicBrainzArtistId;
if (doesMatchTrackArtist)
{
mappedName = NullIfWhiteSpace(artistName);
mappedSortName = data.TrackArtistSortName ?? data.AlbumArtistSortName;
musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId);
}
else if (doesMatchAlbumArtist)
{
mappedName = NullIfWhiteSpace(artistName);
mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName;
musicBrainzArtistId = ParseGuid(data.MusicBrainzReleaseArtistId) ?? ParseGuid(data.MusicBrainzArtistId);
}
else
{
mappedName = NullIfWhiteSpace(data.AlbumArtists.FirstOrDefault()) ?? NullIfWhiteSpace(data.TrackArtists.FirstOrDefault());
mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName;
musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId);
}
return new ArtistMetadataDto(
Name: mappedName,
SortName: mappedSortName,
Disambiguation: null,
Type: null,
Gender: null,
Country: null,
Area: null,
BeginArea: null,
EndArea: null,
LifeSpanBegin: null,
LifeSpanEnd: null,
IsEnded: false,
Website: data.Website,
MusicBrainzArtistId: musicBrainzArtistId,
Ipis: null,
Isnis: null,
Aliases: null,
Genres: null,
Tags: null,
Ratings: null,
Contributors: null);
}
/// <summary>
/// Maps the tags of an audio file into album metadata.
/// </summary>
/// <param name="data">The tags of a track of the album.</param>
/// <returns>The mapped album metadata.</returns>
public static AlbumMetadataDto MapAlbum(Id3TagDto data)
{
return new AlbumMetadataDto(
Title: NullIfWhiteSpace(data.Album),
OriginalTitle: null,
Description: null,
Disambiguation: null,
ReleaseInfo: BuildReleaseInfo(data),
Language: MapLanguage(data.Language),
OriginalLanguage: null,
Tags: null,
Genres: MapGenres(data.Genres),
Script: NullIfWhiteSpace(data.Script),
ReleaseTypes: MapReleaseTypes(data.ReleaseTypes),
ReleaseStatus: MapReleaseStatus(data.ReleaseStatus),
MediaFormat: MapMediaFormat(data.MediaFormat),
Packaging: MapPackaging(data.Packaging),
TotalDiscs: data.DiscCount > 0 ? (int)data.DiscCount : null,
TotalTracks: data.TrackCount > 0 ? (int)data.TrackCount : null,
Barcode: NullIfWhiteSpace(data.Barcode),
CatalogNumbers: data.CatalogNumbers.Count > 0 ? [.. data.CatalogNumbers] : null,
Label: NullIfWhiteSpace(data.Label),
ASIN: NullIfWhiteSpace(data.Asin),
MusicBrainzReleaseId: ParseGuid(data.MusicBrainzReleaseId),
MusicBrainzReleaseGroupId: ParseGuid(data.MusicBrainzReleaseGroupId),
MusicBrainzReleaseArtistId: ParseGuid(data.MusicBrainzReleaseArtistId),
Contributors: MapAlbumContributors(data),
Ratings: null,
ReleaseTitle: null);
}
/// <summary>
/// Maps the tags of an audio file into track metadata.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The mapped track metadata.</returns>
public static AudioMetadataDto MapTrack(Id3TagDto data)
{
return new AudioMetadataDto(
Title: NullIfWhiteSpace(data.Title),
OriginalTitle: null,
Description: null,
Disambiguation: null,
ReleaseInfo: BuildReleaseInfo(data),
Language: MapLanguage(data.Language),
OriginalLanguage: null,
Tags: null,
Genres: MapGenres(data.Genres),
Script: NullIfWhiteSpace(data.Script),
Key: MapKey(data.MusicKey),
Bpm: data.Bpm,
IsVideo: false,
Work: MapWork(data),
Isrcs: MapIsrcs(data.Isrcs),
Moods: MapMoods(data.Moods),
DurationInSeconds: data.DurationInSeconds,
SampleRate: data.SampleRate,
Channels: data.Channels,
BitDepth: data.BitDepth,
AudioCodec: NullIfWhiteSpace(data.AudioCodec),
Bitrate: data.Bitrate,
MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId),
MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId),
Contributors: MapTrackContributors(data),
Ratings: null);
}
/// <summary>
/// Builds the release information of the metadata from the tags, or <see langword="null"/> when the tags carry none of it.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The release information, or <see langword="null"/> when the tags carry no release field.</returns>
private static ReleaseInfoDto? BuildReleaseInfo(Id3TagDto data)
{
ReleaseCountry? releaseCountry = MapReleaseCountry(data.ReleaseCountry);
if (data.OriginalReleaseDate is null && data.OriginalReleaseYear is null && releaseCountry is null)
return null;
return new ReleaseInfoDto(
OriginalReleaseDate: data.OriginalReleaseDate,
OriginalReleaseYear: data.OriginalReleaseYear,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: releaseCountry,
ReleaseVersion: null);
}
/// <summary>
/// Maps the work of the track, or <see langword="null"/> when the tags carry none.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The mapped work, or <see langword="null"/>.</returns>
private static MusicWorkDto? MapWork(Id3TagDto data)
{
Guid? workId = ParseFirstGuid(data.MusicBrainzWorkId);
string? workTitle = FirstValue(data.WorkTitle);
// The work is only mapped when both its identifier and its title are known, because the domain requires both and would otherwise reject the whole track.
if (workId is null || string.IsNullOrWhiteSpace(workTitle))
return null;
return new MusicWorkDto(
MusicBrainzWorkId: workId,
Title: workTitle,
Type: null,
Languages: null,
Iswcs: null);
}
/// <summary>
/// Maps the contributors credited on the track, each with its canonical role.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The mapped contributors, or <see langword="null"/> when the tags credit none.</returns>
private static List<MediaContributorDto>? MapTrackContributors(Id3TagDto data)
{
List<MediaContributorDto> contributors = [];
foreach (string artist in data.TrackArtists)
AddContributor(contributors, artist, MediaContributorRole.Performer);
foreach (string composer in data.Composers)
AddContributor(contributors, composer, MediaContributorRole.Composer);
foreach (string lyricist in data.Lyricists)
AddContributor(contributors, lyricist, MediaContributorRole.Lyricist);
foreach (string conductor in data.Conductors)
AddContributor(contributors, conductor, MediaContributorRole.Conductor);
foreach (string remixer in data.Remixers)
AddContributor(contributors, remixer, MediaContributorRole.Remixer);
foreach ((string role, string name) in data.InvolvedPeople)
AddContributor(contributors, name, MapRole(role));
return contributors.Count > 0 ? contributors : null;
}
/// <summary>
/// Maps the contributors credited on the album, which the tags only expose as the album artists.
/// </summary>
/// <param name="data">The tags of a track of the album.</param>
/// <returns>The mapped contributors, or <see langword="null"/> when the tags credit none.</returns>
private static List<MediaContributorDto>? MapAlbumContributors(Id3TagDto data)
{
List<string> artists = data.AlbumArtists.Count > 0 ? data.AlbumArtists : data.TrackArtists;
List<MediaContributorDto> contributors = [];
foreach (string artist in artists)
AddContributor(contributors, artist, MediaContributorRole.Performer);
return contributors.Count > 0 ? contributors : null;
}
/// <summary>
/// Maps the genres of the metadata, without duplicates.
/// </summary>
/// <param name="genres">The genre names read from the tags.</param>
/// <returns>The mapped genres, or <see langword="null"/> when there are none.</returns>
private static List<GenreDto>? MapGenres(List<string> genres)
{
List<GenreDto> result = [.. genres
.Where(genre => !string.IsNullOrWhiteSpace(genre))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(genre => new GenreDto(genre))];
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps the moods of the metadata, without duplicates.
/// </summary>
/// <param name="moods">The mood names read from the tags.</param>
/// <returns>The mapped moods, or <see langword="null"/> when there are none.</returns>
private static List<MoodDto>? MapMoods(List<string> moods)
{
List<MoodDto> result = [.. moods
.Where(mood => !string.IsNullOrWhiteSpace(mood))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(mood => new MoodDto(mood))];
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps the ISRCs of the track, without duplicates.
/// </summary>
/// <param name="isrcs">The ISRC values read from the tags.</param>
/// <returns>The mapped ISRCs, or <see langword="null"/> when there are none.</returns>
private static List<IsrcDto>? MapIsrcs(List<string> isrcs)
{
List<IsrcDto> result = [.. isrcs
.Where(isrc => !string.IsNullOrWhiteSpace(isrc))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(isrc => new IsrcDto(isrc))];
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps the types of the release into the application enum, without duplicates.
/// </summary>
/// <param name="releaseTypes">The free-form release types read from the tags.</param>
/// <returns>The mapped release types, or <see langword="null"/> when there are none.</returns>
private static List<MusicReleaseType>? MapReleaseTypes(List<string> releaseTypes)
{
List<MusicReleaseType> result = [];
foreach (string releaseType in releaseTypes)
{
MusicReleaseType? mapped = MapReleaseType(releaseType);
if (mapped is not null && !result.Contains(mapped.Value))
result.Add(mapped.Value);
}
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps a single free-form release type into the application enum.
/// </summary>
/// <param name="releaseType">The release type to map.</param>
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicReleaseType? MapReleaseType(string? releaseType)
{
if (string.IsNullOrWhiteSpace(releaseType))
return null;
return releaseType.Trim().ToLowerInvariant() switch
{
"album" => MusicReleaseType.Album,
"single" => MusicReleaseType.Single,
"ep" => MusicReleaseType.Ep,
"broadcast" => MusicReleaseType.Broadcast,
"other" => MusicReleaseType.Other,
"compilation" => MusicReleaseType.Compilation,
"live" => MusicReleaseType.Live,
"soundtrack" => MusicReleaseType.Soundtrack,
"spokenword" => MusicReleaseType.SpokenWord,
"audio drama" => MusicReleaseType.AudioDrama,
"audiobook" => MusicReleaseType.AudioBook,
"demo" => MusicReleaseType.Demo,
"dj-mix" => MusicReleaseType.DjMix,
"field recording" => MusicReleaseType.FieldRecording,
"interview" => MusicReleaseType.Interview,
"mixtape/street" => MusicReleaseType.Mixtape,
"remix" => MusicReleaseType.Remix,
_ => null
};
}
/// <summary>
/// Maps a free-form release status into the application enum.
/// </summary>
/// <param name="releaseStatus">The release status to map.</param>
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
private static MusicReleaseStatus? MapReleaseStatus(string? releaseStatus)
{
if (string.IsNullOrWhiteSpace(releaseStatus))
return null;
return releaseStatus.Trim().ToLowerInvariant() switch
{
"official" => MusicReleaseStatus.Official,
"promotion" => MusicReleaseStatus.Promotion,
"bootleg" => MusicReleaseStatus.Bootleg,
"pseudo-release" => MusicReleaseStatus.PseudoRelease,
"withdrawn" => MusicReleaseStatus.Withdrawn,
"cancelled" => MusicReleaseStatus.Cancelled,
"expunged" => MusicReleaseStatus.Expunged,
_ => null
};
}
/// <summary>
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
/// </summary>
/// <param name="country">The country code to map.</param>
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
private static ReleaseCountry? MapReleaseCountry(string? country)
{
if (string.IsNullOrWhiteSpace(country))
return null;
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
}
/// <summary>
/// Maps a free-form media format into the application enum.
/// </summary>
/// <param name="mediaFormat">The media format to map.</param>
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
private static MusicMediaFormat? MapMediaFormat(string? mediaFormat)
{
if (string.IsNullOrWhiteSpace(mediaFormat))
return null;
string value = mediaFormat.Trim().ToLowerInvariant();
MusicMediaFormat? mapped = value switch
{
"12\" vinyl" => MusicMediaFormat.Inch12Vinyl,
"10\" vinyl" => MusicMediaFormat.Inch10Vinyl,
"7\" vinyl" => MusicMediaFormat.Inch7Vinyl,
"3\" vinyl" => MusicMediaFormat.Inch3Vinyl,
"vinyl" => MusicMediaFormat.Vinyl,
"cd" => MusicMediaFormat.CD,
"sacd" => MusicMediaFormat.SACD,
"hybrid sacd" => MusicMediaFormat.HybridSACD,
"digital media" => MusicMediaFormat.DigitalMedia,
"cassette" => MusicMediaFormat.Cassette,
"dvd" => MusicMediaFormat.DVD,
"dvd-video" => MusicMediaFormat.DVDVideo,
"dvd-audio" => MusicMediaFormat.DVDAudio,
"blu-ray" => MusicMediaFormat.BluRay,
"minidisc" => MusicMediaFormat.MiniDisc,
"8cm cd" => MusicMediaFormat.Cm8CD,
"dat" => MusicMediaFormat.DAT,
"vinyl disc" => MusicMediaFormat.VinylDisc,
"other" => MusicMediaFormat.Other,
_ => null
};
if (mapped is not null)
return mapped;
// Fall back to a direct parse for the values whose free-form name already matches an enum member, ignoring the separators.
string normalized = value.Replace("\"", string.Empty, StringComparison.Ordinal).Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
return Enum.TryParse(normalized, ignoreCase: true, out MusicMediaFormat parsed) ? parsed : null;
}
/// <summary>
/// Maps a free-form packaging into the application enum.
/// </summary>
/// <param name="packaging">The packaging to map.</param>
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
private static MusicReleasePackaging? MapPackaging(string? packaging)
{
if (string.IsNullOrWhiteSpace(packaging))
return null;
string value = packaging.Trim().ToLowerInvariant().Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal).Replace("/", string.Empty, StringComparison.Ordinal);
return Enum.TryParse(value, ignoreCase: true, out MusicReleasePackaging parsed) ? parsed : null;
}
/// <summary>
/// Maps a free-form musical key into the application enum.
/// </summary>
/// <param name="musicKey">The musical key to map.</param>
/// <returns>The mapped musical key, or <see langword="null"/> when the key is unknown.</returns>
private static MusicKey? MapKey(string? musicKey)
{
if (string.IsNullOrWhiteSpace(musicKey))
return null;
string value = musicKey.Trim();
bool isMinor = false;
if (value.EndsWith("minor", StringComparison.OrdinalIgnoreCase))
{
isMinor = true;
value = value[..^5];
}
else if (value.EndsWith("major", StringComparison.OrdinalIgnoreCase))
value = value[..^5];
else if (value.EndsWith("min", StringComparison.OrdinalIgnoreCase))
{
isMinor = true;
value = value[..^3];
}
else if (value.EndsWith("maj", StringComparison.OrdinalIgnoreCase))
value = value[..^3];
else if (value.EndsWith("m", StringComparison.OrdinalIgnoreCase))
{
isMinor = true;
value = value[..^1];
}
value = value.Trim().ToUpperInvariant().Replace("\u266f", "#", StringComparison.Ordinal).Replace("\u266d", "B", StringComparison.Ordinal);
return value switch
{
"C" => isMinor ? MusicKey.CMinor : MusicKey.CMajor,
"C#" or "DB" => isMinor ? MusicKey.CSharpMinor : MusicKey.CSharpMajor,
"D" => isMinor ? MusicKey.DMinor : MusicKey.DMajor,
"D#" or "EB" => isMinor ? MusicKey.DSharpMinor : MusicKey.DSharpMajor,
"E" => isMinor ? MusicKey.EMinor : MusicKey.EMajor,
"F" => isMinor ? MusicKey.FMinor : MusicKey.FMajor,
"F#" or "GB" => isMinor ? MusicKey.FSharpMinor : MusicKey.FSharpMajor,
"G" => isMinor ? MusicKey.GMinor : MusicKey.GMajor,
"G#" or "AB" => isMinor ? MusicKey.GSharpMinor : MusicKey.GSharpMajor,
"A" => isMinor ? MusicKey.AMinor : MusicKey.AMajor,
"A#" or "BB" => isMinor ? MusicKey.ASharpMinor : MusicKey.ASharpMajor,
"B" => isMinor ? MusicKey.BMinor : MusicKey.BMajor,
_ => null
};
}
/// <summary>
/// Maps a free-form ISO 639 language code into language information.
/// </summary>
/// <param name="rawCode">The code to map.</param>
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
// A language code can list several languages, such as "eng/ara"; the first one is the language of the release.
string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code;
switch (primaryCode)
{
case "zxx":
return new LanguageInfoDto(primaryCode, "No linguistic content", null);
case "mul":
return new LanguageInfoDto(primaryCode, "Multiple languages", null);
case "und":
return new LanguageInfoDto(primaryCode, "Undetermined", null);
}
if (s_culturesByLanguageCode.TryGetValue(primaryCode, out CultureInfo? culture))
return new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName);
return new LanguageInfoDto(primaryCode, primaryCode, null);
}
/// <summary>
/// Maps a free-form contributor role into a canonical media contributor role.
/// </summary>
/// <param name="role">The role to map.</param>
/// <returns>The mapped contributor role.</returns>
private static MediaContributorRole MapRole(string? role)
{
if (string.IsNullOrWhiteSpace(role))
return MediaContributorRole.Other;
string value = role.Trim().ToLowerInvariant();
// An instrument is more specific than a generic role, so the instruments are matched first.
if (value.Contains("backing vocal", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (value.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (value.Contains("bass guitar", StringComparison.Ordinal) || value.Contains("electric bass", StringComparison.Ordinal) || string.Equals(value, "bass", StringComparison.Ordinal))
return MediaContributorRole.BassGuitar;
if (value.Contains("guitar", StringComparison.Ordinal))
return MediaContributorRole.Guitar;
if (value.Contains("drum", StringComparison.Ordinal) || value.Contains("membranophone", StringComparison.Ordinal))
return MediaContributorRole.Drums;
if (value.Contains("percussion", StringComparison.Ordinal) || value.Contains("tambourine", StringComparison.Ordinal) || value.Contains("handclap", StringComparison.Ordinal) || value.Contains("stomp", StringComparison.Ordinal))
return MediaContributorRole.Percussion;
if (value.Contains("keyboard", StringComparison.Ordinal))
return MediaContributorRole.Keyboards;
if (value.Contains("piano", StringComparison.Ordinal))
return MediaContributorRole.Piano;
if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal) || value.Contains("sampler", StringComparison.Ordinal))
return MediaContributorRole.Synthesizer;
if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal))
return MediaContributorRole.Strings;
if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal))
return MediaContributorRole.Brass;
if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal))
return MediaContributorRole.Woodwinds;
if (value.Contains("executive producer", StringComparison.Ordinal))
return MediaContributorRole.ExecutiveProducer;
if (value.Contains("producer", StringComparison.Ordinal))
return MediaContributorRole.Producer;
if (value.Contains("remix", StringComparison.Ordinal))
return MediaContributorRole.Remixer;
if (value.Contains("engineer", StringComparison.Ordinal) || value.Contains("mastering", StringComparison.Ordinal))
return MediaContributorRole.Engineer;
if (value.Contains("mix", StringComparison.Ordinal))
return MediaContributorRole.Mixer;
if (value.Contains("arranger", StringComparison.Ordinal))
return MediaContributorRole.Arranger;
if (value.Contains("conductor", StringComparison.Ordinal))
return MediaContributorRole.Conductor;
if (value.Contains("orchestrator", StringComparison.Ordinal))
return MediaContributorRole.Orchestrator;
if (value.Contains("composer", StringComparison.Ordinal))
return MediaContributorRole.Composer;
if (value.Contains("lyricist", StringComparison.Ordinal) || value.Contains("librettist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (value.Contains("writer", StringComparison.Ordinal) || value.Contains("author", StringComparison.Ordinal))
return MediaContributorRole.Author;
if (value.Contains("choir", StringComparison.Ordinal) || value.Contains("chorus", StringComparison.Ordinal))
return MediaContributorRole.Choir;
if (value.Contains("performer", StringComparison.Ordinal) || value.Contains("member of band", StringComparison.Ordinal) || value.Contains("orchestra", StringComparison.Ordinal))
return MediaContributorRole.Performer;
return MediaContributorRole.Other;
}
/// <summary>
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="displayName">The display name of the contributor.</param>
/// <param name="role">The role the contributor played.</param>
private static void AddContributor(List<MediaContributorDto> contributors, string displayName, MediaContributorRole role)
{
if (string.IsNullOrWhiteSpace(displayName))
return;
if (contributors.Any(contributor =>
string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) &&
contributor.Role == role))
return;
contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), null), role));
}
/// <summary>
/// Parses the provided value as a globally unique identifier.
/// </summary>
/// <param name="value">The value to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is missing or malformed.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
}
/// <summary>
/// Parses the first globally unique identifier of a value that may hold several slash-separated identifiers.
/// </summary>
/// <param name="value">The value to parse.</param>
/// <returns>The first parsed identifier, or <see langword="null"/> when the value holds none.</returns>
private static Guid? ParseFirstGuid(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
foreach (string candidate in value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
if (Guid.TryParse(candidate, out Guid parsed))
return parsed;
return null;
}
/// <summary>
/// Gets the first value of a tag that may hold several slash-separated values.
/// </summary>
/// <param name="value">The value to read.</param>
/// <returns>The first non-empty value, or <see langword="null"/> when the value is empty.</returns>
private static string? FirstValue(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
return NullIfWhiteSpace(value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault());
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,434 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
#endregion
namespace Lumina.Plugins.ID3.Core.Tags;
/// <summary>
/// Reads the embedded tags of an audio file into a snapshot, caching the snapshot per path so that the tags of a single file are read only once.
/// </summary>
internal sealed class Id3TagReader
{
/// <summary>
/// The container tag types whose extended tags are searched, in the order they are tried.
/// </summary>
private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape];
/// <summary>
/// The keys of the free-form Apple tags that carry the involved people of a track, paired with the role each of them describes.
/// </summary>
private static readonly (string Role, string Key)[] s_appleInvolvedPeopleKeys =
[
("performer", "performer"),
("producer", "PRODUCER"),
("engineer", "ENGINEER"),
("mixer", "MIXER"),
("arranger", "arranger"),
("writer", "writer")
];
/// <summary>
/// Matches a four digit year.
/// </summary>
private static readonly Regex s_yearPattern = new(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b", RegexOptions.Compiled);
/// <summary>
/// The maximum number of tag snapshots the cache retains, so that reading a large library does not retain the tags of every file it visits.
/// </summary>
private const int MAX_CACHED_SNAPSHOTS = 512;
private readonly Dictionary<string, Id3TagDto> _cache = new(StringComparer.Ordinal);
private readonly Queue<string> _cacheOrder = new();
private readonly Lock _cacheLock = new();
/// <summary>
/// Reads the embedded tags of the audio file stored at <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of the audio file whose tags are read.</param>
/// <returns>The snapshot of the tags, or <see langword="null"/> when the file does not exist or its tags cannot be read.</returns>
public Id3TagDto? Read(string path)
{
if (string.IsNullOrWhiteSpace(path))
return null;
lock (_cacheLock)
{
if (_cache.TryGetValue(path, out Id3TagDto? cached))
return cached;
}
Id3TagDto? data = ReadTagData(path);
// A file whose tags cannot be read is not cached, so that a transient failure does not skip the file for the rest of the scan.
if (data is null)
return null;
lock (_cacheLock)
{
if (!_cache.ContainsKey(path))
{
if (_cache.Count >= MAX_CACHED_SNAPSHOTS)
EvictOldestSnapshot();
_cache[path] = data;
_cacheOrder.Enqueue(path);
}
}
return data;
}
/// <summary>
/// Removes the snapshot that was cached first, keeping the cache within its maximum size.
/// </summary>
private void EvictOldestSnapshot()
{
if (_cacheOrder.Count == 0)
return;
string oldestPath = _cacheOrder.Dequeue();
_cache.Remove(oldestPath);
}
/// <summary>
/// Reads the embedded tags of the audio file stored at <paramref name="path"/> into a snapshot.
/// </summary>
/// <param name="path">The file system path of the audio file whose tags are read.</param>
/// <returns>The snapshot of the tags, or <see langword="null"/> when the file does not exist or its tags cannot be read.</returns>
private static Id3TagDto? ReadTagData(string path)
{
// A file whose path cannot be represented by the operating system, or that is not an audio container, yields no metadata rather than an error.
if (!File.Exists(path))
return null;
try
{
// A link inside a library root must not cause the tags of a file outside the library to be read.
if (File.GetAttributes(path).HasFlag(FileAttributes.ReparsePoint))
return null;
using (TagLib.File tagFile = TagLib.File.Create(path))
{
TagLib.Tag tag = tagFile.Tag;
TagLib.Properties audioProperties = tagFile.Properties;
List<Func<string, List<string>>> extendedFields = BuildExtendedFieldSources(tagFile);
(DateOnly? releaseDate, int? releaseYear) = ParseDate(GetExtendedField(extendedFields, "TDRC", "DATE"));
(DateOnly? originalDate, int? originalYear) = ParseDate(GetExtendedField(extendedFields, "TDOR", "originaldate", "ORIGINALDATE", "originalyear"));
int? year = releaseYear ?? (tag.Year > 0 ? (int)tag.Year : null);
// The original release date and year must describe the same point in time, so the explicit original date is preferred and the year of the chosen date is used whenever a date is known, rather than the year of the release described by the tags.
DateOnly? originalReleaseDate = originalDate ?? releaseDate;
int? originalReleaseYear = originalReleaseDate?.Year ?? originalYear ?? year;
return new Id3TagDto
{
Title = NullIfWhiteSpace(tag.Title),
Album = NullIfWhiteSpace(tag.Album),
TrackArtists = Filter(tag.Performers),
AlbumArtists = Filter(tag.AlbumArtists),
AlbumArtistSortName = NullIfWhiteSpace(tag.AlbumArtistsSort?.FirstOrDefault()),
TrackArtistSortName = NullIfWhiteSpace(tag.PerformersSort?.FirstOrDefault()),
TrackNumber = tag.Track,
TrackCount = tag.TrackCount,
DiscNumber = tag.Disc,
DiscCount = tag.DiscCount,
Year = year,
OriginalReleaseDate = originalReleaseDate,
OriginalReleaseYear = originalReleaseYear,
Genres = SplitValues(Filter(tag.Genres)),
Composers = SplitValues(Filter(tag.Composers)),
Lyricists = SplitValues(GetExtendedFields(extendedFields, "LYRICIST", "lyricist", "TEXT")),
Conductors = Filter([tag.Conductor]),
Remixers = Filter([tag.RemixedBy]),
InvolvedPeople = ReadInvolvedPeople(extendedFields),
Language = NullIfWhiteSpace(GetExtendedField(extendedFields, "LANGUAGE", "TLAN")),
Script = NullIfWhiteSpace(GetExtendedField(extendedFields, "SCRIPT")),
Label = NullIfWhiteSpace(tag.Publisher) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "LABEL")),
CatalogNumbers = SplitValuesOnSemicolons(GetExtendedFields(extendedFields, "CATALOGNUMBER")),
Barcode = NullIfWhiteSpace(GetExtendedField(extendedFields, "BARCODE", "barcode")),
ReleaseTypes = SplitValuesOnSemicolons([tag.MusicBrainzReleaseType]),
ReleaseStatus = NullIfWhiteSpace(tag.MusicBrainzReleaseStatus),
ReleaseCountry = NullIfWhiteSpace(tag.MusicBrainzReleaseCountry),
MediaFormat = NullIfWhiteSpace(GetExtendedField(extendedFields, "MEDIA", "TMED")),
Packaging = NullIfWhiteSpace(GetExtendedField(extendedFields, "PACKAGING")),
Asin = NullIfWhiteSpace(tag.AmazonId) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "ASIN")),
Isrcs = ReadIsrcs(extendedFields, tag),
Moods = SplitValues(GetExtendedFields(extendedFields, "mood", "MOOD", "MOODS")),
WorkTitle = NullIfWhiteSpace(GetExtendedField(extendedFields, "WORK", "MUSICBRAINZ_WORK")),
MusicKey = NullIfWhiteSpace(tag.InitialKey),
Bpm = tag.BeatsPerMinute > 0 ? (int)tag.BeatsPerMinute : null,
DurationInSeconds = audioProperties.Duration > TimeSpan.Zero ? (int)audioProperties.Duration.TotalSeconds : null,
SampleRate = audioProperties.AudioSampleRate > 0 ? audioProperties.AudioSampleRate : null,
Channels = audioProperties.AudioChannels > 0 ? audioProperties.AudioChannels : null,
BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null,
Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null,
AudioCodec = NullIfWhiteSpace(audioProperties.Description),
Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")),
MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId),
MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId),
MusicBrainzReleaseGroupId = NullIfWhiteSpace(tag.MusicBrainzReleaseGroupId),
MusicBrainzReleaseId = NullIfWhiteSpace(tag.MusicBrainzReleaseId),
MusicBrainzRecordingId = NullIfWhiteSpace(tag.MusicBrainzTrackId),
MusicBrainzReleaseTrackId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")),
MusicBrainzWorkId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID"))
};
}
}
catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException)
{
// A file whose tags cannot be read still contributes the metadata derived from its path, so the failure is not propagated.
return null;
}
}
/// <summary>
/// Reads the people credited on the track, together with the free-form role each of them is credited for.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <returns>The people credited on the track, as role and name pairs.</returns>
private static List<(string Role, string Name)> ReadInvolvedPeople(List<Func<string, List<string>>> extendedFields)
{
List<(string Role, string Name)> people = [];
// The ID3v2.3 involved people list (IPLS) and the ID3v2.4 equivalent (TIPL) store roles and names as a single flat sequence of alternating values.
List<string> id3People = GetExtendedFields(extendedFields, "IPLS", "TIPL", "TMCL");
for (int index = 0; index + 1 < id3People.Count; index += 2)
people.Add((id3People[index], id3People[index + 1]));
// The Apple containers store each role as its own free-form tag, carrying one or more names.
foreach ((string role, string key) in s_appleInvolvedPeopleKeys)
foreach (string name in GetExtendedFields(extendedFields, key))
if (!string.IsNullOrWhiteSpace(name))
people.Add((role, name));
return people;
}
/// <summary>
/// Reads the ISRCs of the track, from both the dedicated tag and the extended tags, without duplicates.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <param name="tag">The combined tag of the file.</param>
/// <returns>The ISRCs of the track.</returns>
private static List<string> ReadIsrcs(List<Func<string, List<string>>> extendedFields, TagLib.Tag tag)
{
List<string> values = SplitValues(GetExtendedFields(extendedFields, "ISRC", "TSRC"));
if (!string.IsNullOrWhiteSpace(tag.ISRC))
values.AddRange(SplitValues([tag.ISRC]));
return [.. values.Distinct(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Builds the ordered accessors that resolve an extended tag value from whichever container tag of the file carries it.
/// </summary>
/// <param name="tagFile">The file whose extended tags are read.</param>
/// <returns>The accessors, in the order the containers are searched.</returns>
private static List<Func<string, List<string>>> BuildExtendedFieldSources(TagLib.File tagFile)
{
List<Func<string, List<string>>> sources = [];
foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes)
{
TagLib.Tag? tag = tagFile.GetTag(tagType);
if (tag is TagLib.Ogg.XiphComment xiphComment)
sources.Add(key => [.. (xiphComment.GetField(key) ?? [])]);
else if (tag is TagLib.Id3v2.Tag id3v2Tag)
{
Dictionary<string, List<string>> id3Fields = BuildId3v2Fields(id3v2Tag);
sources.Add(key => id3Fields.TryGetValue(key, out List<string>? values) ? values : []);
}
else if (tag is TagLib.Mpeg4.AppleTag appleTag)
sources.Add(key => GetAppleFields(appleTag, key));
else if (tag is TagLib.Ape.Tag apeTag)
sources.Add(key => GetApeFields(apeTag, key));
}
return sources;
}
/// <summary>
/// Builds the map of the ID3v2 frames of the file, keyed by the name each frame is looked up with, so that the frames are enumerated only once per file.
/// </summary>
/// <param name="id3v2Tag">The ID3v2 tag whose frames are indexed.</param>
/// <returns>The values of every frame, keyed by the frame identifier or the description of a user defined frame.</returns>
private static Dictionary<string, List<string>> BuildId3v2Fields(TagLib.Id3v2.Tag id3v2Tag)
{
Dictionary<string, List<string>> fields = new(StringComparer.OrdinalIgnoreCase);
foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames())
{
string key;
List<string> values;
if (frame is TagLib.Id3v2.UserTextInformationFrame userTextViewFrame)
{
key = userTextViewFrame.Description;
values = [.. userTextViewFrame.Text];
}
else if (frame is TagLib.Id3v2.UrlLinkFrame urlFrame)
{
key = urlFrame.FrameId.ToString();
values = [.. urlFrame.Text];
}
else if (frame is TagLib.Id3v2.TextInformationFrame textFrame)
{
key = textFrame.FrameId.ToString();
values = [.. textFrame.Text];
}
else
continue;
// A user defined frame without a description carries no lookup key, so it is not indexed.
if (string.IsNullOrEmpty(key))
continue;
if (fields.TryGetValue(key, out List<string>? existing))
existing.AddRange(values);
else
fields[key] = values;
}
return fields;
}
/// <summary>
/// Reads the values of a free-form Apple tag with the provided <paramref name="key"/>.
/// </summary>
/// <param name="appleTag">The Apple tag whose values are read.</param>
/// <param name="key">The name of the free-form tag to read.</param>
/// <returns>Every value of the tag.</returns>
private static List<string> GetAppleFields(TagLib.Mpeg4.AppleTag appleTag, string key)
{
List<string> values = [];
foreach (string appleValue in appleTag.GetDashBoxes("com.apple.iTunes", key) ?? [])
values.AddRange(appleValue.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
return values;
}
/// <summary>
/// Reads the values of an APE tag with the provided <paramref name="key"/>.
/// </summary>
/// <param name="apeTag">The APE tag whose values are read.</param>
/// <param name="key">The name of the tag to read.</param>
/// <returns>Every value of the tag.</returns>
private static List<string> GetApeFields(TagLib.Ape.Tag apeTag, string key)
{
if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem)
return [.. apeItem.ToStringArray()];
return [];
}
/// <summary>
/// Reads the first non-empty value of an extended tag, from whichever container tag of the file carries it.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
/// <returns>The first non-empty value found, or <see langword="null"/> when the file carries none of the provided tags.</returns>
private static string? GetExtendedField(List<Func<string, List<string>>> extendedFields, params string[] keys)
{
foreach (Func<string, List<string>> extendedField in extendedFields)
{
foreach (string key in keys)
{
List<string> values = extendedField(key);
string? value = values.FirstOrDefault(candidate => !string.IsNullOrWhiteSpace(candidate));
if (!string.IsNullOrWhiteSpace(value))
return value;
}
}
return null;
}
/// <summary>
/// Reads every value of an extended tag, from whichever container tag of the file carries it.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
/// <returns>Every non-empty value found, or an empty list when the file carries none of the provided tags.</returns>
private static List<string> GetExtendedFields(List<Func<string, List<string>>> extendedFields, params string[] keys)
{
List<string> values = [];
foreach (Func<string, List<string>> extendedField in extendedFields)
foreach (string key in keys)
// A container whose keys are matched case insensitively resolves several case variant aliases to the same entry, so the values already read are not added again.
foreach (string value in extendedField(key))
if (!string.IsNullOrWhiteSpace(value) && !values.Contains(value, StringComparer.Ordinal))
values.Add(value);
return values;
}
/// <summary>
/// Keeps only the non-empty values of the provided collection, trimmed.
/// </summary>
/// <param name="values">The values to filter.</param>
/// <returns>The non-empty, trimmed values.</returns>
private static List<string> Filter(IEnumerable<string>? values)
{
return [.. (values ?? []).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())];
}
/// <summary>
/// Splits every provided value on the separators used to pack several values into a single tag, and keeps the non-empty results.
/// </summary>
/// <param name="values">The values to split.</param>
/// <returns>The individual values found.</returns>
private static List<string> SplitValues(IEnumerable<string> values)
{
return SplitValues(values, ['/', ';']);
}
/// <summary>
/// Splits every provided value on semicolons only, for the tags whose own values may contain a slash.
/// </summary>
/// <param name="values">The values to split.</param>
/// <returns>The individual values found.</returns>
private static List<string> SplitValuesOnSemicolons(IEnumerable<string> values)
{
return SplitValues(values, [';']);
}
/// <summary>
/// Splits every provided value on the provided separators, and keeps the non-empty results.
/// </summary>
/// <param name="values">The values to split.</param>
/// <param name="separators">The separators to split the values on.</param>
/// <returns>The individual values found.</returns>
private static List<string> SplitValues(IEnumerable<string> values, char[] separators)
{
List<string> result = [];
foreach (string value in values)
{
if (string.IsNullOrWhiteSpace(value))
continue;
foreach (string part in value.Split(separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
if (!string.IsNullOrWhiteSpace(part))
result.Add(part);
}
return result;
}
/// <summary>
/// Parses a date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
private static (DateOnly? Date, int? Year) ParseDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return (null, null);
if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact))
return (exact, exact.Year);
Match yearMatch = s_yearPattern.Match(value);
return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TagLibSharp" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.IntegrationTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.Fixtures")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
using Lumina.Plugins.LocalMusicArtwork.Core;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection;
/// <summary>
/// Utility class for registering the services of the local music artwork providers into the Dependency Injection container.
/// </summary>
internal static class LocalMusicArtworkServices
{
/// <summary>
/// Registers the services of the local music artwork providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the artwork.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddLocalMusicArtworkProviders(this IServiceCollection services, Guid pluginId)
{
ArgumentNullException.ThrowIfNull(services);
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults.
services.TryAddScoped(serviceProvider =>
{
LocalMusicArtworkSettingsDto defaults = new();
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
return new LocalMusicArtworkSettingsProvider(settingsStore, pluginId, defaults);
});
// Register the artwork providers as keyed by pluginId transient services, so they can be resolved specifically among other IArtworkProvider implementations.
services.AddKeyedTransient<IArtworkProvider, LocalMusicAlbumArtworkProvider>(pluginId);
services.AddKeyedTransient<IArtworkProvider, LocalMusicArtistArtworkProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,13 @@
namespace Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the local music artwork plugin.
/// </summary>
internal sealed class LocalMusicArtworkSettingsDto
{
/// <summary>
/// Gets or sets a value indicating whether the cover embedded in the audio files is extracted when the album has no cover image on disk.
/// Defaults to <see langword="true"/>, so that a cover is found even when the library stores none on disk.
/// </summary>
public bool ShouldExtractEmbeddedCover { get; set; } = true;
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Core;
/// <summary>
/// Provides the artwork of an album from the images stored in the folders of the local music library of the user.
/// When the album has no cover image on disk and the settings allow it, the cover embedded in the audio files is extracted as a fallback.
/// </summary>
internal sealed class LocalMusicAlbumArtworkProvider : IArtworkProvider<AlbumMetadataLookupDto>
{
private readonly LocalMusicArtworkSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the artwork provider.
/// </summary>
public string Name => "Local Music Artwork";
/// <summary>
/// Gets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicAlbumArtworkProvider"/> class.
/// </summary>
/// <param name="settingsProvider">The provider of the runtime settings of the plugin.</param>
public LocalMusicAlbumArtworkProvider(LocalMusicArtworkSettingsProvider settingsProvider)
{
_settingsProvider = settingsProvider;
}
/// <summary>
/// Gets the artworks of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the artwork for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artworks of the album, or an empty collection when no artwork was found.</returns>
public async Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
IReadOnlyList<ArtworkDto> artworks = LocalMusicArtworkScanner.ScanAlbumArtwork(lookup.Path);
// The cover stored on disk always wins; the embedded one only fills the gap when the album carries no cover on disk at all.
if (artworks.Any(artwork => artwork.Type == ArtworkType.Cover))
return artworks;
LocalMusicArtworkSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
if (!settings.ShouldExtractEmbeddedCover)
return artworks;
ArtworkDto? embeddedCover = LocalMusicArtworkEmbeddedCoverExtractor.Extract(lookup.Path);
if (embeddedCover is null)
return artworks;
return [.. artworks, embeddedCover];
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Core;
/// <summary>
/// Provides the artwork of an artist from the images stored in the folders of the local music library of the user.
/// </summary>
internal sealed class LocalMusicArtistArtworkProvider : IArtworkProvider<ArtistMetadataLookupDto>
{
/// <summary>
/// Gets the display name of the artwork provider.
/// </summary>
public string Name => "Local Music Artwork";
/// <summary>
/// Gets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Gets the artworks of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the artwork for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artworks of the artist, or an empty collection when no artwork was found.</returns>
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return Task.FromResult(LocalMusicArtworkScanner.ScanArtistArtwork(lookup.Path));
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Core;
/// <summary>
/// Extracts the cover image embedded in the metadata of an audio file into a temporary file, so that it can be stored as the artwork of an album.
/// </summary>
internal static class LocalMusicArtworkEmbeddedCoverExtractor
{
private const int MAX_EMBEDDED_COVER_SIZE_BYTES = 10 * 1024 * 1024; // The maximum size of an embedded cover, matching the size limit the artwork storage enforces.
/// <summary>
/// Extracts the first embedded cover image of the audio file stored at <paramref name="trackPath"/> into a temporary file.
/// </summary>
/// <param name="trackPath">The file system path of the audio file whose embedded cover is extracted.</param>
/// <returns>The extracted cover artwork, which points to a temporary file, or <see langword="null"/> when the file carries no usable embedded cover.</returns>
public static ArtworkDto? Extract(string? trackPath)
{
if (string.IsNullOrWhiteSpace(trackPath) || !File.Exists(trackPath))
return null;
try
{
// A link must not cause the metadata of a file outside the library to be read.
if (File.GetAttributes(trackPath).HasFlag(FileAttributes.ReparsePoint))
return null;
using (TagLib.File tagFile = TagLib.File.Create(trackPath))
{
TagLib.IPicture? cover = tagFile.Tag.Pictures?.FirstOrDefault(picture => picture is not null && picture.Data is not null);
if (cover?.Data is null)
return null;
byte[] imageBytes = cover.Data.Data;
if (imageBytes is null || imageBytes.Length == 0 || imageBytes.Length > MAX_EMBEDDED_COVER_SIZE_BYTES)
return null;
string temporaryPath = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artwork-{Guid.NewGuid():N}{ResolveImageExtension(cover.MimeType)}");
File.WriteAllBytes(temporaryPath, imageBytes);
return new ArtworkDto(ArtworkType.Cover, 0, LocalPath: temporaryPath, RemoteUrl: null, IsTemporary: true);
}
}
catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException)
{
// A file whose embedded cover cannot be read contributes no cover, rather than failing the artwork resolution of the whole album.
return null;
}
}
/// <summary>
/// Resolves the file extension of an embedded cover image from its MIME type.
/// </summary>
/// <param name="mimeType">The MIME type of the embedded cover image.</param>
/// <returns>The file extension matching the MIME type, falling back to the JPEG extension.</returns>
private static string ResolveImageExtension(string? mimeType)
{
return mimeType?.Trim().ToLowerInvariant() switch
{
"image/png" => ".png",
"image/webp" => ".webp",
"image/bmp" or "image/x-ms-bmp" => ".bmp",
"image/gif" => ".gif",
"image/tiff" => ".tiff",
_ => ".jpg"
};
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection;
using Lumina.Plugins.LocalMusicArtwork.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Core;
/// <summary>
/// Plugin that provides the artwork of music artists and albums from the images stored in the folders of a local music library.
/// </summary>
public sealed class LocalMusicArtworkPlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "Local Music Artwork";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Reads the artwork of the artists and the albums from the images stored in the folders of a local music library.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return
[
new PluginSettingDescriptorDto(
Key: LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER,
Label: "Extract embedded album cover image from audio files when it is not already present on disk",
Type: PluginSettingType.Boolean,
DefaultValue: "true")
];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddLocalMusicArtworkProviders(pluginId: Id);
}
}
@@ -0,0 +1,270 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Core;
/// <summary>
/// Scans the folders of a local music library and classifies the images they contain into artwork DTOs, following the naming
/// conventions that music media servers use for the images of an artist and of an album.
/// The file names are matched case sensitively, so that a library that stores them with a different casing is left alone.
/// </summary>
internal static class LocalMusicArtworkScanner
{
private const int MAX_ALBUM_ANCESTOR_LEVELS = 2; // The number of directories, the one of a track and its parent, that are inspected when locating the folder of an album.
private const int MAX_ARTIST_ANCESTOR_LEVELS = 5; // The number of parent directories that are inspected when locating the folder of an artist.
private static readonly HashSet<string> s_imageExtensions = new([".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff"], StringComparer.Ordinal);
/// <summary>
/// Scans the directory of the provided track, and its parent directory, for the artwork of an album.
/// </summary>
/// <param name="trackPath">The file system path of a track of the album.</param>
/// <returns>The artwork of the album, or an empty collection when no artwork was found.</returns>
public static IReadOnlyList<ArtworkDto> ScanAlbumArtwork(string? trackPath)
{
string? trackDirectory = GetDirectoryOrNull(trackPath);
if (trackDirectory is null)
return [];
// A multi disc album nests its tracks in disc subdirectories, so both the track directory and its parent are inspected, the nearest one taking precedence.
List<ArtworkDto> artworks = [];
HashSet<(ArtworkType Type, int Ordinal)> seenArtworks = [];
DirectoryInfo? currentDirectory = new(trackDirectory);
int level = 0;
while (currentDirectory is not null && level < MAX_ALBUM_ANCESTOR_LEVELS)
{
foreach (ArtworkDto artwork in ClassifyImages(currentDirectory, isArtist: false))
if (seenArtworks.Add((artwork.Type, artwork.Ordinal)))
artworks.Add(artwork);
currentDirectory = currentDirectory.Parent;
level++;
}
return artworks;
}
/// <summary>
/// Scans the ancestor directories of the provided track for the artwork of an artist.
/// </summary>
/// <param name="trackPath">The file system path of a track of the artist.</param>
/// <returns>The artwork of the artist, or an empty collection when no artwork was found.</returns>
public static IReadOnlyList<ArtworkDto> ScanArtistArtwork(string? trackPath)
{
string? trackDirectory = GetDirectoryOrNull(trackPath);
if (trackDirectory is null)
return [];
// The artist directory is the nearest ancestor that carries an artist level image, like a folder, a backdrop or a logo.
DirectoryInfo? currentDirectory = new(trackDirectory);
int level = 0;
while (currentDirectory is not null && level < MAX_ARTIST_ANCESTOR_LEVELS)
{
IReadOnlyList<ArtworkDto> artworks = ClassifyImages(currentDirectory, isArtist: true);
if (artworks.Count > 0)
return artworks;
currentDirectory = currentDirectory.Parent;
level++;
}
return [];
}
/// <summary>
/// Classifies the images directly contained in <paramref name="directory"/>.
/// </summary>
/// <param name="directory">The directory whose images are classified.</param>
/// <param name="isArtist">Whether the images belong to an artist, as opposed to an album.</param>
/// <returns>The classified artwork, one for every recognized file, ordered by type and ordinal.</returns>
private static IReadOnlyList<ArtworkDto> ClassifyImages(DirectoryInfo directory, bool isArtist)
{
FileInfo[] files;
try
{
files = [.. directory.EnumerateFiles()];
}
catch (IOException)
{
return [];
}
catch (UnauthorizedAccessException)
{
return [];
}
List<ClassifiedArtwork> candidates = [];
foreach (FileInfo file in files)
{
if (!s_imageExtensions.Contains(file.Extension))
continue;
(string baseName, int ordinal) = SplitStem(Path.GetFileNameWithoutExtension(file.Name));
bool isRecognized = isArtist
? TryMapArtistName(baseName, out ArtworkType artworkType, out int priority)
: TryMapAlbumName(baseName, out artworkType, out priority);
if (!isRecognized)
continue;
candidates.Add(new ClassifiedArtwork(artworkType, ordinal, priority, file.Name, file.FullName));
}
// Multiple file names can describe the same piece of artwork, like a cover and a front image, so only the preferred one is kept per type and ordinal.
List<ArtworkDto> artworks = [];
HashSet<(ArtworkType Type, int Ordinal)> seenArtworks = [];
foreach (ClassifiedArtwork candidate in candidates
.OrderBy(candidate => candidate.Type)
.ThenBy(candidate => candidate.Ordinal)
.ThenBy(candidate => candidate.Priority)
.ThenBy(candidate => candidate.FileName, StringComparer.Ordinal))
{
if (!seenArtworks.Add((candidate.Type, candidate.Ordinal)))
continue;
artworks.Add(new ArtworkDto(candidate.Type, candidate.Ordinal, LocalPath: candidate.FilePath, RemoteUrl: null));
}
return artworks;
}
/// <summary>
/// Splits the stem of an image file into the base name that identifies the artwork and the ordinal that orders it within its type.
/// </summary>
/// <param name="stem">The stem of the image file, without its extension.</param>
/// <returns>The base name of the artwork and the ordinal it carries, which is zero when the stem carries no number.</returns>
private static (string BaseName, int Ordinal) SplitStem(string stem)
{
int index = stem.Length;
while (index > 0 && char.IsAsciiDigit(stem[index - 1]))
index--;
string ordinalPart = stem[index..];
string baseName = stem[..index].TrimEnd(' ', '-', '_');
int ordinal = ordinalPart.Length > 0 && int.TryParse(ordinalPart, out int parsedOrdinal) ? parsedOrdinal : 0;
return (baseName, ordinal);
}
/// <summary>
/// Maps the base name of an artist image onto an artwork type.
/// </summary>
/// <param name="baseName">The base name of the image file.</param>
/// <param name="artworkType">The mapped artwork type, when the base name is recognized.</param>
/// <param name="priority">The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred.</param>
/// <returns><see langword="true"/> when the base name was recognized, otherwise <see langword="false"/>.</returns>
private static bool TryMapArtistName(string baseName, out ArtworkType artworkType, out int priority)
{
priority = 0;
switch (baseName)
{
case "folder":
artworkType = ArtworkType.Cover;
return true;
case "backdrop":
artworkType = ArtworkType.Backdrop;
return true;
case "banner":
artworkType = ArtworkType.Banner;
return true;
case "logo":
artworkType = ArtworkType.Logo;
return true;
case "thumb":
artworkType = ArtworkType.Thumb;
return true;
default:
artworkType = ArtworkType.Other;
priority = int.MaxValue;
return false;
}
}
/// <summary>
/// Maps the base name of an album image onto an artwork type.
/// </summary>
/// <param name="baseName">The base name of the image file.</param>
/// <param name="artworkType">The mapped artwork type, when the base name is recognized.</param>
/// <param name="priority">The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred.</param>
/// <returns><see langword="true"/> when the base name was recognized, otherwise <see langword="false"/>.</returns>
private static bool TryMapAlbumName(string baseName, out ArtworkType artworkType, out int priority)
{
switch (baseName)
{
case "cover":
artworkType = ArtworkType.Cover;
priority = 0;
return true;
case "front":
artworkType = ArtworkType.Front;
priority = 0;
return true;
case "back":
artworkType = ArtworkType.Back;
priority = 0;
return true;
case "booklet":
artworkType = ArtworkType.Booklet;
priority = 0;
return true;
case "disk":
case "disc":
artworkType = ArtworkType.Medium;
priority = 0;
return true;
case "liner":
artworkType = ArtworkType.Liner;
priority = 0;
return true;
case "tray":
artworkType = ArtworkType.Tray;
priority = 0;
return true;
case "spine":
artworkType = ArtworkType.Spine;
priority = 0;
return true;
case "obi":
artworkType = ArtworkType.Obi;
priority = 0;
return true;
case "sticker":
artworkType = ArtworkType.Sticker;
priority = 0;
return true;
case "poster":
artworkType = ArtworkType.Poster;
priority = 0;
return true;
default:
artworkType = ArtworkType.Other;
priority = int.MaxValue;
return false;
}
}
/// <summary>
/// Gets the directory of the provided <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path whose directory is retrieved.</param>
/// <returns>The directory of the path, or <see langword="null"/> when the path is empty or has no directory part.</returns>
private static string? GetDirectoryOrNull(string? path)
{
if (string.IsNullOrWhiteSpace(path))
return null;
string? directory = Path.GetDirectoryName(path);
return string.IsNullOrWhiteSpace(directory) ? null : directory;
}
/// <summary>
/// A recognized image of an artist or an album, before it is ordered and de-duplicated.
/// </summary>
/// <param name="Type">The type of the artwork.</param>
/// <param name="Ordinal">The ordinal of the artwork within its type.</param>
/// <param name="Priority">The priority of the file name among the files of the same artwork type and ordinal, lower being preferred.</param>
/// <param name="FileName">The name of the image file.</param>
/// <param name="FilePath">The file system path of the image file.</param>
private sealed record ClassifiedArtwork(
ArtworkType Type,
int Ordinal,
int Priority,
string FileName,
string FilePath
);
}
@@ -0,0 +1,12 @@
namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings;
/// <summary>
/// Keys of the settings of the local music artwork plugin, shared by the settings schema and the settings provider.
/// </summary>
internal static class LocalMusicArtworkSettingsKeys
{
/// <summary>
/// The key of the setting that controls whether the cover embedded in the audio files is extracted when the album has no cover image on disk.
/// </summary>
internal const string SHOULD_EXTRACT_EMBEDDED_COVER = "ShouldExtractEmbeddedCover";
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings;
/// <summary>
/// Provides the runtime settings of the local music artwork plugin, overlaying the settings persisted by the host over the configured defaults.
/// </summary>
internal sealed class LocalMusicArtworkSettingsProvider
{
private readonly IPluginSettingsStore? _settingsStore;
private readonly Guid _pluginId;
private readonly LocalMusicArtworkSettingsDto _defaults;
// The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already
// resolved path lock free; the gate is only needed by the first callers that race to resolve it.
private readonly SemaphoreSlim _gate = new(1, 1);
private LocalMusicArtworkSettingsDto? _runtimeSettings;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtworkSettingsProvider"/> class.
/// </summary>
/// <param name="settingsStore">The store of the settings persisted by the host, or <see langword="null"/> when no store is available.</param>
/// <param name="pluginId">The unique identifier of the plugin whose settings are read.</param>
/// <param name="defaults">The runtime settings with the default values and the optional configuration callback already applied.</param>
public LocalMusicArtworkSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, LocalMusicArtworkSettingsDto defaults)
{
_settingsStore = settingsStore;
_pluginId = pluginId;
_defaults = defaults;
}
/// <summary>
/// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The runtime settings of the plugin.</returns>
public async Task<LocalMusicArtworkSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
LocalMusicArtworkSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
if (runtimeSettings is not null)
return runtimeSettings;
// Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once.
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Second check inside the gate: another caller may have resolved the settings while this one was waiting for it.
runtimeSettings = Volatile.Read(ref _runtimeSettings);
if (runtimeSettings is null)
{
// The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes.
runtimeSettings = new LocalMusicArtworkSettingsDto
{
ShouldExtractEmbeddedCover = _defaults.ShouldExtractEmbeddedCover
};
if (_settingsStore is not null)
{
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
if (storedSettings is not null &&
storedSettings.TryGetValue(LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, out string? shouldExtractEmbeddedCover) &&
bool.TryParse(shouldExtractEmbeddedCover, out bool shouldExtractEmbeddedCoverValue))
runtimeSettings.ShouldExtractEmbeddedCover = shouldExtractEmbeddedCoverValue;
}
// Publishing through Volatile makes the fully built instance visible to the lock free readers above.
Volatile.Write(ref _runtimeSettings, runtimeSettings);
}
return runtimeSettings;
}
finally
{
_gate.Release();
}
}
}
@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="TagLibSharp" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.SecurityTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.IntegrationTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.Fixtures")]
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Http;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
/// <summary>
/// Utility class for registering the services of the MusicBrainz metadata provider into the Dependency Injection container.
/// </summary>
internal static class MusicBrainzServices
{
/// <summary>
/// Registers the services of the MusicBrainz metadata providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <param name="settingsCallback">Action used to configure the <see cref="MusicBrainzSettingsDto"/>.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddMusicBrainzMetadataProviders(this IServiceCollection services, Guid pluginId, Action<MusicBrainzSettingsDto>? settingsCallback = null)
{
ArgumentNullException.ThrowIfNull(services);
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
services.TryAddScoped(serviceProvider =>
{
MusicBrainzSettingsDto defaults = new();
settingsCallback?.Invoke(defaults);
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
return new MusicBrainzSettingsProvider(settingsStore, pluginId, defaults);
});
// The throttle must be process-wide, because the MusicBrainz web service enforces its request policy across all callers, not per scope.
services.TryAddSingleton<MusicBrainzRequestThrottle>();
// The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once.
services.TryAddSingleton<MusicBrainzResponseCache>();
// Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror.
services.AddHttpClient<MusicBrainzHttpClient>()
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
// Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations.
// A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair.
services.AddKeyedTransient<IMetadataProvider, MusicBrainzArtistMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, MusicBrainzAlbumMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, MusicBrainzTrackMetadataProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an alias of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzAliasResponse
{
/// <summary>
/// Gets the name of the alias.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the alias.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the type of the alias.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the locale the alias is used in.
/// </summary>
[JsonPropertyName("locale")]
public string? Locale { get; init; }
/// <summary>
/// Gets a value indicating whether this is the primary alias.
/// </summary>
[JsonPropertyName("primary")]
public bool? IsPrimary { get; init; }
/// <summary>
/// Gets the begin date of the alias.
/// </summary>
[JsonPropertyName("begin")]
public string? Begin { get; init; }
/// <summary>
/// Gets the end date of the alias.
/// </summary>
[JsonPropertyName("end")]
public string? End { get; init; }
/// <summary>
/// Gets a value indicating whether the alias has ended.
/// </summary>
[JsonPropertyName("ended")]
public bool? IsEnded { get; init; }
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an area from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzAreaResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the area.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the area.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the area.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the disambiguation comment of the area.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the area.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the ISO 3166-1 codes of the area.
/// </summary>
[JsonPropertyName("iso-3166-1-codes")]
public List<string> Iso3166Part1Codes { get; init; } = [];
/// <summary>
/// Gets the ISO 3166-2 codes of the area.
/// </summary>
[JsonPropertyName("iso-3166-2-codes")]
public List<string> Iso3166Part2Codes { get; init; } = [];
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a single credit in the artist credit of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzArtistCreditResponse
{
/// <summary>
/// Gets the credited name of the artist.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the join phrase that follows the credit.
/// </summary>
[JsonPropertyName("joinphrase")]
public string? JoinPhrase { get; init; }
/// <summary>
/// Gets the artist the credit refers to.
/// </summary>
[JsonPropertyName("artist")]
public MusicBrainzArtistResponse? Artist { get; init; }
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an artist from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzArtistResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the artist.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the artist.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the artist.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the disambiguation comment of the artist.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the artist.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the gender of the artist.
/// </summary>
[JsonPropertyName("gender")]
public string? Gender { get; init; }
/// <summary>
/// Gets the ISO 3166-1 alpha-2 code of the country of the artist.
/// </summary>
[JsonPropertyName("country")]
public string? Country { get; init; }
/// <summary>
/// Gets the area the artist is primarily identified with.
/// </summary>
[JsonPropertyName("area")]
public MusicBrainzAreaResponse? Area { get; init; }
/// <summary>
/// Gets the area the artist began in.
/// </summary>
[JsonPropertyName("begin-area")]
public MusicBrainzAreaResponse? BeginArea { get; init; }
/// <summary>
/// Gets the area the artist ended in.
/// </summary>
[JsonPropertyName("end-area")]
public MusicBrainzAreaResponse? EndArea { get; init; }
/// <summary>
/// Gets the life span of the artist.
/// </summary>
[JsonPropertyName("life-span")]
public MusicBrainzLifeSpanResponse? LifeSpan { get; init; }
/// <summary>
/// Gets the ISNI codes of the artist.
/// </summary>
[JsonPropertyName("isnis")]
public List<string> Isnis { get; init; } = [];
/// <summary>
/// Gets the IPI codes of the artist.
/// </summary>
[JsonPropertyName("ipis")]
public List<string> Ipis { get; init; } = [];
/// <summary>
/// Gets the alternative names of the artist.
/// </summary>
[JsonPropertyName("aliases")]
public List<MusicBrainzAliasResponse> Aliases { get; init; } = [];
/// <summary>
/// Gets the tags of the artist.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the artist.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the artist to other entities.
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the artist.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an artist search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzArtistSearchResponse
{
/// <summary>
/// Gets the total number of matching artists.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned artists.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching artists.
/// </summary>
[JsonPropertyName("artists")]
public List<MusicBrainzArtistResponse> Artists { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the label information of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzLabelInfoResponse
{
/// <summary>
/// Gets the catalog number assigned by the label.
/// </summary>
[JsonPropertyName("catalog-number")]
public string? CatalogNumber { get; init; }
/// <summary>
/// Gets the label that issued the release.
/// </summary>
[JsonPropertyName("label")]
public MusicBrainzLabelResponse? Label { get; init; }
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a label from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzLabelResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the label.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the label.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the disambiguation comment of the label.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the label code of the label.
/// </summary>
[JsonPropertyName("label-code")]
public int? LabelCode { get; init; }
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the life span of a MusicBrainz artist, label, or area.
/// </summary>
internal sealed record MusicBrainzLifeSpanResponse
{
/// <summary>
/// Gets the begin date of the life span.
/// </summary>
[JsonPropertyName("begin")]
public string? Begin { get; init; }
/// <summary>
/// Gets the end date of the life span.
/// </summary>
[JsonPropertyName("end")]
public string? End { get; init; }
/// <summary>
/// Gets a value indicating whether the life span has ended.
/// </summary>
[JsonPropertyName("ended")]
public bool? IsEnded { get; init; }
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a medium of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzMediumResponse
{
/// <summary>
/// Gets the position of the medium within its release.
/// </summary>
[JsonPropertyName("position")]
public int Position { get; init; }
/// <summary>
/// Gets the title of the medium.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the format of the medium (e.g., CD, Vinyl, Digital Media).
/// </summary>
[JsonPropertyName("format")]
public string? Format { get; init; }
/// <summary>
/// Gets the number of tracks of the medium.
/// </summary>
[JsonPropertyName("track-count")]
public int TrackCount { get; init; }
/// <summary>
/// Gets the tracks of the medium. The tracks are only returned when the recordings are included in the request.
/// </summary>
[JsonPropertyName("tracks")]
public List<MusicBrainzTrackResponse> Tracks { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the aggregated rating of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzRatingResponse
{
/// <summary>
/// Gets the average rating value.
/// </summary>
[JsonPropertyName("value")]
public decimal? Value { get; init; }
/// <summary>
/// Gets the number of votes that contributed to the rating.
/// </summary>
[JsonPropertyName("votes-count")]
public int? VotesCount { get; init; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the recordings returned by an ISRC lookup from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingListResponse
{
/// <summary>
/// Gets the recordings that carry the looked up ISRC.
/// </summary>
[JsonPropertyName("recordings")]
public List<MusicBrainzRecordingResponse> Recordings { get; init; } = [];
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a recording from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the recording.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the recording.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the recording.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the length of the recording in milliseconds.
/// </summary>
[JsonPropertyName("length")]
public long? Length { get; init; }
/// <summary>
/// Gets a value indicating whether the recording is a video recording.
/// </summary>
[JsonPropertyName("video")]
public bool? IsVideo { get; init; }
/// <summary>
/// Gets the date the recording was first released.
/// </summary>
[JsonPropertyName("first-release-date")]
public string? FirstReleaseDate { get; init; }
/// <summary>
/// Gets the artist credit of the recording.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the ISRC (International Standard Recording Code) of the recording.
/// </summary>
[JsonPropertyName("isrcs")]
public List<string> Isrcs { get; init; } = [];
/// <summary>
/// Gets the releases the recording appears on.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the tags of the recording.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the recording.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the recording to other entities (e.g., its work, and its performers).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the recording.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a recording search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingSearchResponse
{
/// <summary>
/// Gets the total number of matching recordings.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned recordings.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching recordings.
/// </summary>
[JsonPropertyName("recordings")]
public List<MusicBrainzRecordingResponse> Recordings { get; init; } = [];
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a relationship between a MusicBrainz entity and another entity.
/// </summary>
internal sealed record MusicBrainzRelationResponse
{
/// <summary>
/// Gets the type of the relationship (e.g., producer, composer, member of band).
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the MusicBrainz identifier of the type of the relationship.
/// </summary>
[JsonPropertyName("type-id")]
public string? TypeId { get; init; }
/// <summary>
/// Gets the direction of the relationship.
/// </summary>
[JsonPropertyName("direction")]
public string? Direction { get; init; }
/// <summary>
/// Gets the type of the entity the relationship targets.
/// </summary>
[JsonPropertyName("target-type")]
public string? TargetType { get; init; }
/// <summary>
/// Gets the artist the relationship targets, when the target is an artist.
/// </summary>
[JsonPropertyName("artist")]
public MusicBrainzArtistResponse? Artist { get; init; }
/// <summary>
/// Gets the work the relationship targets, when the target is a work.
/// </summary>
[JsonPropertyName("work")]
public MusicBrainzWorkResponse? Work { get; init; }
/// <summary>
/// Gets the URL the relationship targets, when the target is a URL.
/// </summary>
[JsonPropertyName("url")]
public MusicBrainzUrlResponse? Url { get; init; }
/// <summary>
/// Gets the attributes of the relationship (e.g., the instrument that was performed).
/// </summary>
[JsonPropertyName("attributes")]
public List<string> Attributes { get; init; } = [];
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the result of browsing the releases linked to another MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzReleaseBrowseResponse
{
/// <summary>
/// Gets the releases returned by the browse request.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the total number of releases linked to the browsed entity.
/// </summary>
[JsonPropertyName("release-count")]
public int ReleaseCount { get; init; }
/// <summary>
/// Gets the offset of the returned releases.
/// </summary>
[JsonPropertyName("release-offset")]
public int ReleaseOffset { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release event of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzReleaseEventResponse
{
/// <summary>
/// Gets the date of the release event.
/// </summary>
[JsonPropertyName("date")]
public string? Date { get; init; }
/// <summary>
/// Gets the area of the release event.
/// </summary>
[JsonPropertyName("area")]
public MusicBrainzAreaResponse? Area { get; init; }
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release group from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseGroupResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the release group.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the release group.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the release group.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the primary type of the release group.
/// </summary>
[JsonPropertyName("primary-type")]
public string? PrimaryType { get; init; }
/// <summary>
/// Gets the secondary types of the release group.
/// </summary>
[JsonPropertyName("secondary-types")]
public List<string> SecondaryTypes { get; init; } = [];
/// <summary>
/// Gets the date the release group was first released.
/// </summary>
[JsonPropertyName("first-release-date")]
public string? FirstReleaseDate { get; init; }
/// <summary>
/// Gets the artist credit of the release group.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the releases of the release group.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the tags of the release group.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the release group.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the release group.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release group search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseGroupSearchResponse
{
/// <summary>
/// Gets the total number of matching release groups.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned release groups.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching release groups.
/// </summary>
[JsonPropertyName("release-groups")]
public List<MusicBrainzReleaseGroupResponse> ReleaseGroups { get; init; } = [];
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the release.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the release.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the release.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the status of the release (e.g., Official, Bootleg).
/// </summary>
[JsonPropertyName("status")]
public string? Status { get; init; }
/// <summary>
/// Gets the date the release was issued.
/// </summary>
[JsonPropertyName("date")]
public string? Date { get; init; }
/// <summary>
/// Gets the ISO 3166-1 alpha-2 code of the country the release was issued in.
/// </summary>
[JsonPropertyName("country")]
public string? Country { get; init; }
/// <summary>
/// Gets the release events of the release.
/// </summary>
[JsonPropertyName("release-events")]
public List<MusicBrainzReleaseEventResponse> ReleaseEvents { get; init; } = [];
/// <summary>
/// Gets the barcode of the release.
/// </summary>
[JsonPropertyName("barcode")]
public string? Barcode { get; init; }
/// <summary>
/// Gets the outermost packaging of the release.
/// </summary>
[JsonPropertyName("packaging")]
public string? Packaging { get; init; }
/// <summary>
/// Gets the language and script of the titles of the release.
/// </summary>
[JsonPropertyName("text-representation")]
public MusicBrainzTextRepresentationResponse? TextRepresentation { get; init; }
/// <summary>
/// Gets the artist credit of the release.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the release group the release belongs to.
/// </summary>
[JsonPropertyName("release-group")]
public MusicBrainzReleaseGroupResponse? ReleaseGroup { get; init; }
/// <summary>
/// Gets the label information of the release.
/// </summary>
[JsonPropertyName("label-info")]
public List<MusicBrainzLabelInfoResponse> LabelInfo { get; init; } = [];
/// <summary>
/// Gets the media of the release.
/// </summary>
[JsonPropertyName("media")]
public List<MusicBrainzMediumResponse> Media { get; init; } = [];
/// <summary>
/// Gets the ASIN (Amazon Standard Identification Number) of the release.
/// </summary>
[JsonPropertyName("asin")]
public string? Asin { get; init; }
/// <summary>
/// Gets the tags of the release.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the release.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the release to other entities (e.g., its producers and engineers).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a tag or a genre of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzTagResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the genre, when the tag is a genre.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the tag.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the disambiguation comment of the genre, when the tag is a genre.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the number of votes the tag received.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the language and script of the titles of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzTextRepresentationResponse
{
/// <summary>
/// Gets the ISO 639-3 language code of the release.
/// </summary>
[JsonPropertyName("language")]
public string? Language { get; init; }
/// <summary>
/// Gets the ISO 15924 script code of the release.
/// </summary>
[JsonPropertyName("script")]
public string? Script { get; init; }
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a track of a medium of a MusicBrainz release, including the recording it is a performance of.
/// </summary>
internal sealed record MusicBrainzTrackResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the track.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the track number, as displayed on the medium (for example, "1" or "A1").
/// </summary>
[JsonPropertyName("number")]
public string? Number { get; init; }
/// <summary>
/// Gets the position of the track within its medium.
/// </summary>
[JsonPropertyName("position")]
public int Position { get; init; }
/// <summary>
/// Gets the title of the track.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the length of the track in milliseconds.
/// </summary>
[JsonPropertyName("length")]
public long? Length { get; init; }
/// <summary>
/// Gets the recording the track is a performance of.
/// </summary>
[JsonPropertyName("recording")]
public MusicBrainzRecordingResponse? Recording { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a URL from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzUrlResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the URL.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the resource the URL points to.
/// </summary>
[JsonPropertyName("resource")]
public string? Resource { get; init; }
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a work from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzWorkResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the work.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the work.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the work.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the disambiguation comment of the work.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the languages of the work.
/// </summary>
[JsonPropertyName("languages")]
public List<string> Languages { get; init; } = [];
/// <summary>
/// Gets the ISWC (International Standard Musical Work Code) of the work.
/// </summary>
[JsonPropertyName("iswcs")]
public List<string> Iswcs { get; init; } = [];
/// <summary>
/// Gets the relationships of the work to other entities (e.g., its composers and lyricists).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the tags of the work.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the work.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the MusicBrainz metadata plugin.
/// </summary>
internal sealed class MusicBrainzSettingsDto
{
/// <summary>
/// Gets or sets the base URL of the MusicBrainz web service the requests are sent to.
/// Defaults to the public MusicBrainz web service, and can point to a self hosted mirror instead.
/// </summary>
public string BaseUrl { get; set; } = "https://musicbrainz.org/ws/2/";
/// <summary>
/// Gets or sets a value indicating whether the base URL is allowed to point at a private or local host, for a self hosted mirror on a local
/// network. Defaults to <see langword="false"/>, so that a misconfigured base URL cannot silently reach a local service.
/// </summary>
public bool DoesAllowPrivateBaseUrl { get; set; }
/// <summary>
/// Gets or sets the user agent sent with every request to the MusicBrainz API.
/// </summary>
public string UserAgent { get; set; } = "Lumina-MusicBrainz/1.0";
/// <summary>
/// Gets or sets the contact email sent with every request to the MusicBrainz API.
/// </summary>
public string? ContactEmail { get; set; }
/// <summary>
/// Gets or sets the maximum number of results returned by a single search.
/// </summary>
public int SearchResultLimit { get; set; } = 10;
/// <summary>
/// Gets or sets the maximum number of releases fetched for a single release group.
/// </summary>
public int ReleaseLookupLimit { get; set; } = 25;
/// <summary>
/// Gets or sets the minimum interval between consecutive requests to the MusicBrainz API.
/// MusicBrainz requires client applications to make no more than one request per second.
/// </summary>
public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
}
@@ -0,0 +1,336 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models.
/// </summary>
internal sealed class MusicBrainzHttpClient
{
private readonly HttpClient _httpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
private readonly MusicBrainzRequestThrottle _requestThrottle;
private readonly MusicBrainzResponseCache _responseCache;
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
// Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
private const int MAXIMUM_ATTEMPT_COUNT = 4;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzHttpClient"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the MusicBrainz web service.</param>
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache)
{
_httpClient = httpClient;
_settingsProvider = settingsProvider;
_requestThrottle = requestThrottle;
_responseCache = responseCache;
}
/// <summary>
/// Looks up the artist identified by <paramref name="musicBrainzArtistId"/>.
/// </summary>
/// <param name="musicBrainzArtistId">The MusicBrainz identifier of the artist.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artist, or <see langword="null"/> when no artist was found.</returns>
public Task<MusicBrainzArtistResponse?> GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzArtistResponse>(
$"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for artists matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching artists.</returns>
public async Task<IReadOnlyList<MusicBrainzArtistResponse>> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzArtistSearchResponse>(
$"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Artists ?? [];
}
/// <summary>
/// Looks up the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release group, or <see langword="null"/> when no release group was found.</returns>
public Task<MusicBrainzReleaseGroupResponse?> GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseGroupResponse>(
$"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for release groups matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching release groups.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseGroupResponse>> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseGroupSearchResponse>(
$"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.ReleaseGroups ?? [];
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken);
}
/// <summary>
/// Browses the releases that belong to the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="limit">The maximum number of releases to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of releases of the release group.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseResponse>> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseBrowseResponse>(
$"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Releases ?? [];
}
/// <summary>
/// Looks up the recording identified by <paramref name="musicBrainzRecordingId"/>.
/// </summary>
/// <param name="musicBrainzRecordingId">The MusicBrainz identifier of the recording.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The recording, or <see langword="null"/> when no recording was found.</returns>
public Task<MusicBrainzRecordingResponse?> GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzRecordingResponse>(
$"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for recordings matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching recordings.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingSearchResponse>(
$"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the recordings that carry the provided ISRC.
/// </summary>
/// <param name="isrc">The ISRC to look up.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of recordings that carry the ISRC.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken)
{
MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingListResponse>(
$"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the work identified by <paramref name="musicBrainzWorkId"/>, together with its credited contributors.
/// </summary>
/// <param name="musicBrainzWorkId">The MusicBrainz identifier of the work.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work, or <see langword="null"/> when no work was found.</returns>
public Task<MusicBrainzWorkResponse?> GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzWorkResponse>(
$"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken);
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>, together with its media, tracks, recordings and all the data needed
/// to enrich those tracks, so that every track of the release is enriched from a single request.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release, with its media, tracks and recordings, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", cancellationToken);
}
/// <summary>
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="TModel"/>.
/// </summary>
/// <typeparam name="TModel">The type to deserialize the JSON response into.</typeparam>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
/// <remarks>Transient failures and rate limiting are handled by retrying the request up to three times.</remarks>
private async Task<TModel?> GetJsonOrNullAsync<TModel>(string relativeUrl, CancellationToken cancellationToken)
{
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
string cacheKey = string.Concat(settings.BaseUrl, relativeUrl);
if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null)
return JsonSerializer.Deserialize<TModel>(cachedJson, s_serializerOptions);
using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
// A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result.
if (response.StatusCode == HttpStatusCode.NotFound)
return default;
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
_responseCache.Set(cacheKey, json);
return JsonSerializer.Deserialize<TModel>(json, s_serializerOptions);
}
/// <summary>
/// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured
/// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport
/// exceptions are retried, preferring the delay requested by the web service when it is provided.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
{
EnsureRequestHeaders(settings);
// The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted
// mirror, or any other configured base URL that is not the real service, is not limited by this process.
bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl);
// A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every
// attempt, so that the retries of a failed request cannot burst past the rate limit of the real MusicBrainz web service.
for (int attempt = 1; ; attempt++)
{
if (shouldThrottle)
await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false);
bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT;
HttpResponseMessage response;
try
{
HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException) when (!isLastAttempt)
{
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
continue;
}
if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
{
TimeSpan retryDelay = GetRetryDelay(attempt, response);
// The response of a failed attempt is not returned, so it must be disposed here to release its connection.
response.Dispose();
await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
continue;
}
return response;
}
}
/// <summary>
/// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided.
/// </summary>
/// <param name="attempt">The one based number of the attempt that just failed.</param>
/// <param name="response">The response of the failed attempt, when the failure was a response rather than a transport exception.</param>
/// <returns>The delay to wait before the next attempt.</returns>
private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
{
if (response?.Headers.RetryAfter is { } retryAfter)
{
if (retryAfter.Delta is TimeSpan delta)
return delta;
if (retryAfter.Date is DateTimeOffset date)
{
TimeSpan wait = date - DateTimeOffset.UtcNow;
if (wait > TimeSpan.Zero)
return wait;
}
}
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
}
/// <summary>
/// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <returns><see langword="true"/> when the base URL points to the real MusicBrainz web service, otherwise <see langword="false"/>.</returns>
private static bool IsRealMusicBrainzService(string baseUrl)
{
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri))
return false;
return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase)
|| baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
private void EnsureRequestHeaders(MusicBrainzSettingsDto settings)
{
// The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once.
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
{
string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail)
? settings.UserAgent
: $"{settings.UserAgent} ( {settings.ContactEmail} )";
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
}
}
/// <summary>
/// Combines the configured base URL with the given relative URL into the absolute URI of a request.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base URL.</param>
/// <returns>The absolute URI of the request.</returns>
private static Uri BuildRequestUri(string baseUrl, string relativeUrl)
{
string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/");
return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process.
/// </summary>
internal sealed class MusicBrainzRequestThrottle
{
private readonly SemaphoreSlim _gate = new(1, 1);
// The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter
// which caller sends them.
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
/// <summary>
/// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
/// </summary>
/// <param name="minimumRequestInterval">The minimum amount of time that must elapse between two consecutive requests.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that completes once the caller may send its request.</returns>
public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
{
// The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
// previous reserved slot.
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
if (minimumRequestInterval > TimeSpan.Zero)
{
DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
_lastRequestAt = DateTimeOffset.UtcNow;
}
finally
{
_gate.Release();
}
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL.
/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time.
/// </summary>
internal sealed class MusicBrainzResponseCache
{
/// <summary>
/// The maximum number of responses the cache keeps.
/// </summary>
internal const int MAXIMUM_ENTRY_COUNT = 20_000;
/// <summary>
/// The maximum total number of characters of the cached response bodies.
/// </summary>
internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
/// <summary>
/// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
/// eviction from running on every write once a budget is reached.
/// </summary>
private const int TRIM_TARGET_PERCENT = 90;
private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
private readonly int _maximumEntryCount;
private readonly long _maximumCharacterCount;
private readonly TimeSpan _timeToLive;
private readonly ConcurrentDictionary<string, CacheEntry> _entries = new(StringComparer.Ordinal);
// The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
// are guarded by a lock, while reads stay lock free.
private readonly Lock _sizeGate = new();
private long _cachedCharacterCount;
// Monotonically increasing insertion stamp, used to evict the oldest entries first.
private long _sequence;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the default budgets and time to live.
/// </summary>
public MusicBrainzResponseCache()
{
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
_timeToLive = s_timeToLive;
}
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the provided budgets and time to live.
/// </summary>
/// <param name="maximumEntryCount">The maximum number of responses the cache keeps.</param>
/// <param name="maximumCharacterCount">The maximum total number of characters of the cached response bodies.</param>
/// <param name="timeToLive">The amount of time a cached response stays valid.</param>
internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
{
_maximumEntryCount = maximumEntryCount;
_maximumCharacterCount = maximumCharacterCount;
_timeToLive = timeToLive;
}
/// <summary>
/// Tries to get the cached response body for <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The cached response body, when found.</param>
/// <returns><see langword="true"/> when an unexpired response was found, otherwise <see langword="false"/>.</returns>
public bool TryGet(string key, out string? json)
{
// An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
{
json = entry.Json;
return true;
}
json = null;
return false;
}
/// <summary>
/// Adds or replaces the cached response body for <paramref name="key"/>, then trims the cache back to its budgets.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The response body to cache.</param>
public void Set(string key, string json)
{
// A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
if (json.Length > _maximumCharacterCount)
return;
lock (_sizeGate)
{
if (_entries.TryRemove(key, out CacheEntry? existing))
_cachedCharacterCount -= existing.Json.Length;
_entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
_cachedCharacterCount += json.Length;
if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
TrimToBudget();
}
}
/// <summary>
/// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
/// </summary>
private void TrimToBudget()
{
DateTime utcNow = DateTime.UtcNow;
bool isOverEntryCount = _entries.Count > _maximumEntryCount;
bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
// Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
// a budget was not exceeded, so the cache keeps reclaiming dead entries.
foreach (KeyValuePair<string, CacheEntry> candidate in _entries.OrderBy(entry => entry.Value.Sequence))
{
bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
break;
if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
_cachedCharacterCount -= removed.Json.Length;
}
}
private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
}
@@ -0,0 +1,759 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Mapping;
/// <summary>
/// Maps MusicBrainz web service responses into the application's media metadata DTOs.
/// </summary>
internal static partial class MusicBrainzMapper
{
/// <summary>
/// The neutral cultures of the process, indexed by both their two letter and three letter ISO 639 codes.
/// Built once, because the available cultures do not change during the lifetime of the process.
/// </summary>
private static readonly IReadOnlyDictionary<string, CultureInfo> s_neutralCulturesByCode = BuildNeutralCultureLookup();
/// <summary>
/// Matches a four digit year.
/// </summary>
[GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")]
private static partial Regex YearPattern();
/// <summary>
/// Maps a MusicBrainz artist response into artist metadata.
/// </summary>
/// <param name="artist">The artist response to map.</param>
/// <returns>The mapped artist metadata.</returns>
public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist)
{
(List<MediaContributorDto> contributors, string? website) = MapArtistRelations(artist.Relations);
return new ArtistMetadataDto(
Name: NullIfWhiteSpace(artist.Name),
SortName: NullIfWhiteSpace(artist.SortName),
Disambiguation: NullIfWhiteSpace(artist.Disambiguation),
Type: MapArtistType(artist.Type),
Gender: MapArtistGender(artist.Gender),
Country: NullIfWhiteSpace(artist.Country),
Area: MapArea(artist.Area),
BeginArea: MapArea(artist.BeginArea),
EndArea: MapArea(artist.EndArea),
LifeSpanBegin: ParseDate(artist.LifeSpan?.Begin).Date,
LifeSpanEnd: ParseDate(artist.LifeSpan?.End).Date,
IsEnded: artist.LifeSpan?.IsEnded ?? false,
Website: website,
MusicBrainzArtistId: ParseGuid(artist.Id),
Ipis: [.. artist.Ipis.Where(ipi => !string.IsNullOrWhiteSpace(ipi))],
Isnis: [.. artist.Isnis.Where(isni => !string.IsNullOrWhiteSpace(isni))],
Aliases: [.. artist.Aliases.Select(MapAlias)],
Genres: MapGenres(artist.Genres),
Tags: MapTags(artist.Tags),
Ratings: MapRating(artist.Rating),
Contributors: contributors);
}
/// <summary>
/// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata.
/// </summary>
/// <param name="releaseGroup">The release group response to map.</param>
/// <param name="release">The selected release of the release group, or <see langword="null"/> when no release was selected.</param>
/// <returns>The mapped album metadata.</returns>
public static AlbumMetadataDto MapAlbum(MusicBrainzReleaseGroupResponse releaseGroup, MusicBrainzReleaseResponse? release)
{
(DateOnly? originalDate, int? originalYear) = ParseDate(releaseGroup.FirstReleaseDate);
(DateOnly? reReleaseDate, int? reReleaseYear) = ParseDate(release?.Date);
if (reReleaseDate is not null && originalDate is not null && reReleaseDate.Value.Year == originalDate.Value.Year)
{
reReleaseDate = null;
reReleaseYear = null;
}
string? releaseArtistId = releaseGroup.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id))
?? release?.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
List<MediaContributorDto> contributors = MapArtistCredit(releaseGroup.ArtistCredit);
if (contributors.Count == 0 && release is not null)
contributors = MapArtistCredit(release.ArtistCredit);
if (release is not null)
AddContributors(contributors, MapContributorsFromRelations(release.Relations));
List<MusicBrainzMediumResponse> media = release?.Media ?? [];
int totalTracks = media.Sum(medium => medium.TrackCount);
// A MusicBrainz release can carry several labels and catalog numbers: the label stores the first one, while every catalog number is kept.
string? label = release?.LabelInfo.FirstOrDefault()?.Label?.Name;
List<string> catalogNumbers = [.. (release?.LabelInfo ?? [])
.Select(labelInfo => NullIfWhiteSpace(labelInfo.CatalogNumber))
.Where(catalogNumber => catalogNumber is not null)
.Select(catalogNumber => catalogNumber!)
.Distinct(StringComparer.OrdinalIgnoreCase)];
return new AlbumMetadataDto(
Title: NullIfWhiteSpace(releaseGroup.Title) ?? NullIfWhiteSpace(release?.Title),
OriginalTitle: null,
Description: null,
Disambiguation: NullIfWhiteSpace(releaseGroup.Disambiguation),
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: originalDate,
OriginalReleaseYear: originalYear,
ReReleaseDate: reReleaseDate,
ReReleaseYear: reReleaseYear,
ReleaseCountry: MapReleaseCountry(release?.Country),
ReleaseVersion: NullIfWhiteSpace(release?.Disambiguation)),
Language: MapLanguage(release?.TextRepresentation?.Language),
OriginalLanguage: null,
Tags: MapTags(releaseGroup.Tags),
Genres: MapGenres(releaseGroup.Genres),
Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
ReleaseTypes: MapReleaseTypes(releaseGroup.PrimaryType, releaseGroup.SecondaryTypes),
ReleaseStatus: MapReleaseStatus(release?.Status),
MediaFormat: MapMediaFormat(media.FirstOrDefault()?.Format),
Packaging: MapPackaging(release?.Packaging),
TotalDiscs: media.Count > 0 ? media.Count : null,
TotalTracks: totalTracks > 0 ? totalTracks : null,
Barcode: NullIfWhiteSpace(release?.Barcode),
CatalogNumbers: catalogNumbers,
Label: NullIfWhiteSpace(label),
ASIN: NullIfWhiteSpace(release?.Asin),
MusicBrainzReleaseId: ParseGuid(release?.Id),
MusicBrainzReleaseGroupId: ParseGuid(releaseGroup.Id),
MusicBrainzReleaseArtistId: ParseGuid(releaseArtistId),
Contributors: contributors,
Ratings: MapRating(releaseGroup.Rating),
ReleaseTitle: NullIfWhiteSpace(release?.Title));
}
/// <summary>
/// Maps a MusicBrainz recording, and optionally its work and release, into track metadata.
/// </summary>
/// <param name="recording">The recording response to map.</param>
/// <param name="work">The work the recording is an instance of, or <see langword="null"/> when the recording has no work.</param>
/// <param name="release">The release the recording appears on, or <see langword="null"/> when it is not known.</param>
/// <returns>The mapped track metadata.</returns>
public static AudioMetadataDto MapTrack(MusicBrainzRecordingResponse recording, MusicBrainzWorkResponse? work, MusicBrainzReleaseResponse? release)
{
(DateOnly? releaseDate, int? releaseYear) = ParseDate(recording.FirstReleaseDate);
// A recording embedded in a release lookup does not carry its own first release date, so the date of the release the track appears on is used
// instead, rather than leaving the track without any release date at all.
if (releaseYear is null)
(releaseDate, releaseYear) = ParseDate(release?.Date);
List<MediaContributorDto> contributors = MapArtistCredit(recording.ArtistCredit);
AddContributors(contributors, MapContributorsFromRelations(recording.Relations));
if (work is not null)
AddContributors(contributors, MapContributorsFromRelations(work.Relations));
return new AudioMetadataDto(
Title: NullIfWhiteSpace(recording.Title),
OriginalTitle: null,
Description: null,
Disambiguation: NullIfWhiteSpace(recording.Disambiguation),
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: releaseDate,
OriginalReleaseYear: releaseYear,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: null,
ReleaseVersion: null),
Language: MapLanguage(release?.TextRepresentation?.Language),
OriginalLanguage: null,
Tags: MapTags(recording.Tags),
Genres: MapGenres(recording.Genres),
Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
Key: null,
Bpm: null,
IsVideo: recording.IsVideo ?? false,
Work: work is null ? null : MapWork(work),
Isrcs: [.. recording.Isrcs.Where(isrc => !string.IsNullOrWhiteSpace(isrc)).Select(isrc => new IsrcDto(isrc))],
Moods: null,
DurationInSeconds: recording.Length is long length && length > 0 ? (int)(length / 1000) : null,
SampleRate: null,
Channels: null,
BitDepth: null,
AudioCodec: null,
Bitrate: null,
MusicBrainzRecordingId: ParseGuid(recording.Id),
MusicBrainzTrackId: null,
Contributors: contributors,
Ratings: MapRating(recording.Rating));
}
/// <summary>
/// Maps a MusicBrainz work into a work DTO.
/// </summary>
/// <param name="work">The work response to map.</param>
/// <returns>The mapped work.</returns>
public static MusicWorkDto MapWork(MusicBrainzWorkResponse work)
{
return new MusicWorkDto(
MusicBrainzWorkId: ParseGuid(work.Id),
Title: NullIfWhiteSpace(work.Title),
Type: NullIfWhiteSpace(work.Type),
Languages: [.. work.Languages.Select(MapLanguage).Where(language => language is not null).Select(language => language!)],
Iswcs: [.. work.Iswcs.Where(iswc => !string.IsNullOrWhiteSpace(iswc))]);
}
/// <summary>
/// Maps a MusicBrainz area into an area DTO.
/// </summary>
/// <param name="area">The area response to map.</param>
/// <returns>The mapped area, or <see langword="null"/> when no area is provided.</returns>
public static MusicAreaDto? MapArea(MusicBrainzAreaResponse? area)
{
if (area is null)
return null;
string? isoCode = area.Iso3166Part1Codes.FirstOrDefault() ?? area.Iso3166Part2Codes.FirstOrDefault();
return new MusicAreaDto(
MusicBrainzAreaId: ParseGuid(area.Id),
Name: NullIfWhiteSpace(area.Name),
SortName: NullIfWhiteSpace(area.SortName),
Disambiguation: NullIfWhiteSpace(area.Disambiguation),
Type: NullIfWhiteSpace(area.Type),
Iso3166Code: NullIfWhiteSpace(isoCode));
}
/// <summary>
/// Maps a MusicBrainz alias into an alias DTO.
/// </summary>
/// <param name="alias">The alias response to map.</param>
/// <returns>The mapped alias.</returns>
private static MusicArtistAliasDto MapAlias(MusicBrainzAliasResponse alias)
{
return new MusicArtistAliasDto(
Name: NullIfWhiteSpace(alias.Name),
SortName: NullIfWhiteSpace(alias.SortName),
Type: NullIfWhiteSpace(alias.Type),
Locale: NullIfWhiteSpace(alias.Locale),
IsPrimary: alias.IsPrimary ?? false,
BeginDate: ParseDate(alias.Begin).Date,
EndDate: ParseDate(alias.End).Date,
IsEnded: alias.IsEnded ?? false);
}
/// <summary>
/// Maps the genres of a MusicBrainz entity into genre DTOs.
/// </summary>
/// <param name="genres">The genre responses to map.</param>
/// <returns>The mapped genre DTOs.</returns>
private static List<GenreDto> MapGenres(IReadOnlyCollection<MusicBrainzTagResponse> genres)
{
return [.. genres
.Where(genre => !string.IsNullOrWhiteSpace(genre.Name))
.Select(genre => new GenreDto(genre.Name))
.DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the tags of a MusicBrainz entity into tag DTOs.
/// </summary>
/// <param name="tags">The tag responses to map.</param>
/// <returns>The mapped tag DTOs.</returns>
private static List<TagDto> MapTags(IReadOnlyCollection<MusicBrainzTagResponse> tags)
{
return [.. tags
.Where(tag => !string.IsNullOrWhiteSpace(tag.Name))
.Select(tag => new TagDto(tag.Name))
.DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the rating of a MusicBrainz entity into a rating DTO.
/// </summary>
/// <param name="rating">The rating response to map.</param>
/// <returns>The mapped rating DTO, or an empty list when no rating is provided.</returns>
private static List<AudioRatingDto> MapRating(MusicBrainzRatingResponse? rating)
{
if (rating is null || (rating.Value is null && rating.VotesCount is null))
return [];
return [new AudioRatingDto(rating.Value, 5m, AudioRatingSource.MusicBrainz, rating.VotesCount)];
}
/// <summary>
/// Maps an ISO 639-3 language code into a language DTO.
/// </summary>
/// <param name="rawCode">The code to map.</param>
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
// A language code can list several languages, such as "eng/ara"; the first one is the language of the release.
string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code;
// These ISO 639-3 codes describe a language absence rather than a culture, so they cannot be resolved through a culture.
switch (primaryCode)
{
case "zxx":
return new LanguageInfoDto(primaryCode, "No linguistic content", null);
case "mul":
return new LanguageInfoDto(primaryCode, "Multiple languages", null);
case "und":
return new LanguageInfoDto(primaryCode, "Undetermined", null);
default:
break;
}
// Only neutral cultures are matched, because a specific culture would resolve to an arbitrary regional name such as "German (Austria)".
return s_neutralCulturesByCode.TryGetValue(primaryCode, out CultureInfo? culture)
? new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName)
: new LanguageInfoDto(primaryCode, primaryCode, null);
}
/// <summary>
/// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes.
/// </summary>
/// <returns>The neutral cultures, indexed by their ISO 639 codes.</returns>
private static IReadOnlyDictionary<string, CultureInfo> BuildNeutralCultureLookup()
{
Dictionary<string, CultureInfo> culturesByCode = new(StringComparer.OrdinalIgnoreCase);
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
// A culture without a two letter ISO 639 code is not a language, so it is skipped; the two letter code is the one carried by the DTOs.
if (culture.TwoLetterISOLanguageName.Length != 2)
continue;
culturesByCode.TryAdd(culture.ThreeLetterISOLanguageName, culture);
culturesByCode.TryAdd(culture.TwoLetterISOLanguageName, culture);
}
return culturesByCode;
}
/// <summary>
/// Maps the artist credit of a MusicBrainz entity into attributed performing contributors.
/// </summary>
/// <param name="artistCredit">The artist credit to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapArtistCredit(IReadOnlyCollection<MusicBrainzArtistCreditResponse> artistCredit)
{
List<MediaContributorDto> contributors = [];
foreach (MusicBrainzArtistCreditResponse credit in artistCredit)
{
string? name = NullIfWhiteSpace(credit.Name) ?? NullIfWhiteSpace(credit.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MediaContributorRole.Performer);
}
return contributors;
}
/// <summary>
/// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations.
/// </summary>
/// <param name="relations">The relations to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapContributorsFromRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> contributors = [];
foreach (MusicBrainzRelationResponse relation in relations)
{
if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
continue;
string? name = NullIfWhiteSpace(relation.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
}
return contributors;
}
/// <summary>
/// Maps the relations of an artist into its contributing members, and its official homepage.
/// </summary>
/// <param name="relations">The relations of the artist.</param>
/// <returns>The mapped contributors, and the official homepage of the artist.</returns>
private static (List<MediaContributorDto> Contributors, string? Website) MapArtistRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> contributors = [];
string? website = null;
foreach (MusicBrainzRelationResponse relation in relations)
{
if (string.Equals(relation.TargetType, "url", StringComparison.OrdinalIgnoreCase))
{
if (website is null && string.Equals(relation.Type, "official homepage", StringComparison.OrdinalIgnoreCase))
website = NullIfWhiteSpace(relation.Url?.Resource);
continue;
}
if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
continue;
string? name = NullIfWhiteSpace(relation.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
}
return (contributors, website);
}
/// <summary>
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="displayName">The display name of the contributor.</param>
/// <param name="role">The role the contributor played.</param>
private static void AddContributor(List<MediaContributorDto> contributors, string displayName, MediaContributorRole role)
{
if (contributors.Any(contributor =>
string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) &&
contributor.Role == role))
return;
contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName, null), role));
}
/// <summary>
/// Adds the <paramref name="incoming"/> contributors to <paramref name="contributors"/>, skipping the duplicate name and role pairs.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="incoming">The contributors to add.</param>
private static void AddContributors(List<MediaContributorDto> contributors, IReadOnlyCollection<MediaContributorDto> incoming)
{
foreach (MediaContributorDto contributor in incoming)
{
if (contributor.Name?.DisplayName is not string displayName)
continue;
AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other);
}
}
/// <summary>
/// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role.
/// </summary>
/// <param name="relationType">The relationship type to map.</param>
/// <param name="attributes">The attributes of the relationship.</param>
/// <returns>The mapped contributor role.</returns>
private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection<string> attributes)
{
// An instrument attribute is more specific than the generic relationship type, so it is preferred.
foreach (string attribute in attributes)
{
MediaContributorRole? attributed = MapInstrument(attribute);
if (attributed is not null)
return attributed.Value;
}
if (string.IsNullOrWhiteSpace(relationType))
return MediaContributorRole.Other;
string type = relationType.Trim().ToLowerInvariant();
if (type.Contains("executive producer", StringComparison.Ordinal))
return MediaContributorRole.ExecutiveProducer;
if (type.Contains("producer", StringComparison.Ordinal))
return MediaContributorRole.Producer;
if (type.Contains("remixer", StringComparison.Ordinal))
return MediaContributorRole.Remixer;
if (type.Contains("mix", StringComparison.Ordinal))
return MediaContributorRole.Mixer;
if (type.Contains("engineer", StringComparison.Ordinal) || type.Contains("mastering", StringComparison.Ordinal))
return MediaContributorRole.Engineer;
if (type.Contains("composer", StringComparison.Ordinal))
return MediaContributorRole.Composer;
if (type.Contains("writer", StringComparison.Ordinal))
return MediaContributorRole.Author;
if (type.Contains("lyricist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (type.Contains("librettist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (type.Contains("arranger", StringComparison.Ordinal))
return MediaContributorRole.Arranger;
if (type.Contains("conductor", StringComparison.Ordinal))
return MediaContributorRole.Conductor;
if (type.Contains("orchestrator", StringComparison.Ordinal))
return MediaContributorRole.Orchestrator;
if (type.Contains("backing vocals", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (type.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (type.Contains("member of band", StringComparison.Ordinal) || type.Contains("performer", StringComparison.Ordinal) || type.Contains("orchestra", StringComparison.Ordinal) || type.Contains("choir", StringComparison.Ordinal))
return MediaContributorRole.Performer;
return MediaContributorRole.Other;
}
/// <summary>
/// Maps a MusicBrainz instrument attribute into a canonical media contributor role.
/// </summary>
/// <param name="attribute">The instrument attribute to map.</param>
/// <returns>The mapped contributor role, or <see langword="null"/> when the attribute is not an instrument.</returns>
private static MediaContributorRole? MapInstrument(string? attribute)
{
if (string.IsNullOrWhiteSpace(attribute))
return null;
string value = attribute.Trim().ToLowerInvariant();
if (value.Contains("backing vocal", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (value.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (value.Contains("bass guitar", StringComparison.Ordinal))
return MediaContributorRole.BassGuitar;
if (value.Contains("guitar", StringComparison.Ordinal))
return MediaContributorRole.Guitar;
if (value.Contains("drum", StringComparison.Ordinal))
return MediaContributorRole.Drums;
if (value.Contains("percussion", StringComparison.Ordinal))
return MediaContributorRole.Percussion;
if (value.Contains("keyboard", StringComparison.Ordinal))
return MediaContributorRole.Keyboards;
if (value.Contains("piano", StringComparison.Ordinal))
return MediaContributorRole.Piano;
if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal))
return MediaContributorRole.Synthesizer;
if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal))
return MediaContributorRole.Strings;
if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal))
return MediaContributorRole.Brass;
if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal))
return MediaContributorRole.Woodwinds;
return null;
}
/// <summary>
/// Maps a MusicBrainz artist type into the application enum.
/// </summary>
/// <param name="type">The artist type to map.</param>
/// <returns>The mapped artist type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicArtistType? MapArtistType(string? type)
{
if (string.IsNullOrWhiteSpace(type))
return null;
return type.Trim().ToLowerInvariant() switch
{
"person" => MusicArtistType.Person,
"group" => MusicArtistType.Group,
"orchestra" => MusicArtistType.Orchestra,
"choir" => MusicArtistType.Choir,
"character" => MusicArtistType.Character,
"other" => MusicArtistType.Other,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz gender into the application enum.
/// </summary>
/// <param name="gender">The gender to map.</param>
/// <returns>The mapped gender, or <see langword="null"/> when the gender is unknown.</returns>
private static MusicArtistGender? MapArtistGender(string? gender)
{
if (string.IsNullOrWhiteSpace(gender))
return null;
return gender.Trim().ToLowerInvariant() switch
{
"male" => MusicArtistGender.Male,
"female" => MusicArtistGender.Female,
"other" => MusicArtistGender.Other,
"not applicable" => MusicArtistGender.NotApplicable,
_ => null
};
}
/// <summary>
/// Maps the primary and secondary types of a release group into the application enum.
/// </summary>
/// <param name="primaryType">The primary type of the release group.</param>
/// <param name="secondaryTypes">The secondary types of the release group.</param>
/// <returns>The mapped release types.</returns>
private static List<MusicReleaseType> MapReleaseTypes(string? primaryType, IReadOnlyCollection<string> secondaryTypes)
{
List<MusicReleaseType> releaseTypes = [];
MusicReleaseType? primary = MapReleaseType(primaryType);
if (primary is not null)
releaseTypes.Add(primary.Value);
foreach (string secondaryType in secondaryTypes)
{
MusicReleaseType? mapped = MapReleaseType(secondaryType);
if (mapped is not null && !releaseTypes.Contains(mapped.Value))
releaseTypes.Add(mapped.Value);
}
return releaseTypes;
}
/// <summary>
/// Maps a single MusicBrainz release type into the application enum.
/// </summary>
/// <param name="type">The release type to map.</param>
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicReleaseType? MapReleaseType(string? type)
{
if (string.IsNullOrWhiteSpace(type))
return null;
return type.Trim().ToLowerInvariant() switch
{
"album" => MusicReleaseType.Album,
"single" => MusicReleaseType.Single,
"ep" => MusicReleaseType.Ep,
"broadcast" => MusicReleaseType.Broadcast,
"other" => MusicReleaseType.Other,
"compilation" => MusicReleaseType.Compilation,
"live" => MusicReleaseType.Live,
"soundtrack" => MusicReleaseType.Soundtrack,
"spokenword" => MusicReleaseType.SpokenWord,
"audio drama" => MusicReleaseType.AudioDrama,
"audiobook" => MusicReleaseType.AudioBook,
"demo" => MusicReleaseType.Demo,
"dj-mix" => MusicReleaseType.DjMix,
"field recording" => MusicReleaseType.FieldRecording,
"interview" => MusicReleaseType.Interview,
"mixtape/street" => MusicReleaseType.Mixtape,
"remix" => MusicReleaseType.Remix,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz release status into the application enum.
/// </summary>
/// <param name="status">The release status to map.</param>
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
private static MusicReleaseStatus? MapReleaseStatus(string? status)
{
if (string.IsNullOrWhiteSpace(status))
return null;
return status.Trim().ToLowerInvariant() switch
{
"official" => MusicReleaseStatus.Official,
"promotion" => MusicReleaseStatus.Promotion,
"bootleg" => MusicReleaseStatus.Bootleg,
"pseudo-release" => MusicReleaseStatus.PseudoRelease,
"withdrawn" => MusicReleaseStatus.Withdrawn,
"cancelled" => MusicReleaseStatus.Cancelled,
"expunged" => MusicReleaseStatus.Expunged,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz medium format into the application enum.
/// </summary>
/// <param name="format">The format to map.</param>
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
private static MusicMediaFormat? MapMediaFormat(string? format)
{
if (string.IsNullOrWhiteSpace(format))
return null;
return format.Trim().ToLowerInvariant() switch
{
"cd" => MusicMediaFormat.CD,
"vinyl" => MusicMediaFormat.Vinyl,
"12\" vinyl" => MusicMediaFormat.Inch12Vinyl,
"10\" vinyl" => MusicMediaFormat.Inch10Vinyl,
"7\" vinyl" => MusicMediaFormat.Inch7Vinyl,
"digital media" => MusicMediaFormat.DigitalMedia,
"cassette" => MusicMediaFormat.Cassette,
"dvd" => MusicMediaFormat.DVD,
"dvd-video" => MusicMediaFormat.DVDVideo,
"dvd-audio" => MusicMediaFormat.DVDAudio,
"sacd" => MusicMediaFormat.SACD,
"hybrid sacd" => MusicMediaFormat.HybridSACD,
"blu-ray" => MusicMediaFormat.BluRay,
"minidisc" => MusicMediaFormat.MiniDisc,
"8cm cd" => MusicMediaFormat.Cm8CD,
"dat" => MusicMediaFormat.DAT,
"other" => MusicMediaFormat.Other,
_ => MusicMediaFormat.Other
};
}
/// <summary>
/// Maps a MusicBrainz release packaging into the application enum.
/// </summary>
/// <param name="packaging">The packaging to map.</param>
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
private static MusicReleasePackaging? MapPackaging(string? packaging)
{
if (string.IsNullOrWhiteSpace(packaging))
return null;
return packaging.Trim().ToLowerInvariant() switch
{
"book" => MusicReleasePackaging.Book,
"box" => MusicReleasePackaging.Box,
"cardboard/paper sleeve" => MusicReleasePackaging.CardboardPaperSleeve,
"cassette case" => MusicReleasePackaging.CassetteCase,
"clamshell case" => MusicReleasePackaging.ClamshellCase,
"digibook" => MusicReleasePackaging.Digibook,
"digifile" => MusicReleasePackaging.Digifile,
"digipak" => MusicReleasePackaging.Digipak,
"discbox slider" => MusicReleasePackaging.DiscboxSlider,
"fatbox" => MusicReleasePackaging.Fatbox,
"gatefold cover" => MusicReleasePackaging.GatefoldCover,
"jewel case" => MusicReleasePackaging.JewelCase,
"keep case" => MusicReleasePackaging.KeepCase,
"longbox" => MusicReleasePackaging.Longbox,
"metal tin" => MusicReleasePackaging.MetalTin,
"plastic sleeve" => MusicReleasePackaging.PlasticSleeve,
"slidepack" => MusicReleasePackaging.Slidepack,
"slim jewel case" => MusicReleasePackaging.SlimJewelCase,
"slipcase" => MusicReleasePackaging.Slipcase,
"snap case" => MusicReleasePackaging.SnapCase,
"snappack" => MusicReleasePackaging.SnapPack,
"super jewel box" => MusicReleasePackaging.SuperJewelBox,
"none" => MusicReleasePackaging.None,
"other" => MusicReleasePackaging.Other,
_ => MusicReleasePackaging.Other
};
}
/// <summary>
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
/// </summary>
/// <param name="country">The country code to map.</param>
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
private static ReleaseCountry? MapReleaseCountry(string? country)
{
if (string.IsNullOrWhiteSpace(country))
return null;
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
}
/// <summary>
/// Parses a MusicBrainz identifier into a <see cref="Guid"/>.
/// </summary>
/// <param name="value">The MusicBrainz identifier to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is not a valid identifier.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
}
/// <summary>
/// Parses a MusicBrainz date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
private static (DateOnly? Date, int? Year) ParseDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return (null, null);
if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact))
return (exact, exact.Year);
Match yearMatch = YearPattern().Match(value);
return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,206 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides album metadata from MusicBrainz by resolving lookups into album metadata DTOs.
/// A MusicBrainz release group is the logical album, while one of its releases is selected as the edition the local files match.
/// </summary>
internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzAlbumMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of album metadata candidates found.</returns>
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzReleaseGroupResponse> releaseGroups = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AlbumMetadataDto> candidates = [];
foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups)
if (!string.IsNullOrWhiteSpace(releaseGroup.Title))
candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when no album was found.</returns>
public async Task<AlbumMetadataDto?> GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseResponse? release = null;
MusicBrainzReleaseGroupResponse? releaseGroup = null;
// A release identifier pins the exact edition, so it is fetched first, and its release group is then resolved for the album level fields.
// The release is fetched together with its recordings, so that the track level enrichment of the same release is served from the response cache.
if (lookup.MusicBrainzReleaseId is not null)
release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
Guid? releaseGroupId = lookup.MusicBrainzReleaseGroupId;
if (releaseGroupId is null && release?.ReleaseGroup?.Id is string releaseGroupIdValue && Guid.TryParse(releaseGroupIdValue, out Guid parsedReleaseGroupId))
releaseGroupId = parsedReleaseGroupId;
if (releaseGroupId is not null)
releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(releaseGroupId.Value, cancellationToken).ConfigureAwait(false);
// Without any identifier, the album is searched by title and artist, and the first match is resolved in full.
if (release is null && releaseGroup is null && !string.IsNullOrWhiteSpace(lookup.Title))
{
IReadOnlyList<MusicBrainzReleaseGroupResponse> results = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), 1, cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseGroupResponse? searchResult = results.Count > 0 ? results[0] : null;
if (searchResult?.Id is string searchResultId && Guid.TryParse(searchResultId, out Guid parsedSearchResultId))
releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(parsedSearchResultId, cancellationToken).ConfigureAwait(false);
}
if (releaseGroup is null)
return release is null ? null : MusicBrainzMapper.MapAlbum(new MusicBrainzReleaseGroupResponse { Id = release.ReleaseGroup?.Id, Title = release.Title }, release);
// When the exact release was not pinned by the lookup, the best edition of the release group is selected.
if (release is null && releaseGroup.Id is string releaseGroupIdentifier && Guid.TryParse(releaseGroupIdentifier, out Guid releaseGroupGuid))
{
IReadOnlyList<MusicBrainzReleaseResponse> releases = await _musicBrainzHttpClient
.BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false);
release = SelectRelease(releases, lookup);
}
return MusicBrainzMapper.MapAlbum(releaseGroup, release);
}
/// <summary>
/// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year.
/// </summary>
/// <param name="releases">The releases to select from.</param>
/// <param name="lookup">The lookup the selected release must match.</param>
/// <returns>The best matching release, or <see langword="null"/> when no release was provided.</returns>
private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList<MusicBrainzReleaseResponse> releases, AlbumMetadataLookupDto lookup)
{
// Only a release whose tracklist matches the local album is selected, so that an edition of the release group that does not correspond to the
// local files is never attached to the album; without a known local track count, no release can be confidently matched, so none is selected.
if (lookup.TrackCount is not int trackCount)
return null;
List<MusicBrainzReleaseResponse> matchingReleases = [.. releases.Where(release => release.Media.Sum(medium => medium.TrackCount) == trackCount)];
if (matchingReleases.Count == 0)
return null;
return matchingReleases
.Select((release, index) => new
{
Release = release,
Index = index,
Score = ScoreRelease(release, lookup)
})
.OrderByDescending(item => item.Score)
.ThenBy(item => item.Index)
.Select(item => item.Release)
.First();
}
/// <summary>
/// Scores a release against the lookup to rank how well it matches.
/// </summary>
/// <param name="release">The release to score.</param>
/// <param name="lookup">The lookup the release must match.</param>
/// <returns>The match score of the release, where a higher score is a better match.</returns>
private static int ScoreRelease(MusicBrainzReleaseResponse release, AlbumMetadataLookupDto lookup)
{
int score = 0;
if (string.Equals(release.Status, "Official", StringComparison.OrdinalIgnoreCase))
score += 10_000;
if (lookup.ReleaseYear is int wantedYear && TryGetYear(release.Date) is int releaseYear && releaseYear == wantedYear)
score += 1_000;
if (!string.IsNullOrWhiteSpace(release.Barcode))
score += 100;
if (release.LabelInfo.Count > 0)
score += 50;
if (release.Media.Count > 0)
score += 10;
return score;
}
/// <summary>
/// Gets the year of a MusicBrainz date string.
/// </summary>
/// <param name="date">The date string to read.</param>
/// <returns>The year of the date, or <see langword="null"/> when it could not be read.</returns>
private static int? TryGetYear(string? date)
{
if (string.IsNullOrWhiteSpace(date))
return null;
string year = date.Length >= 4 ? date[..4] : date;
return int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : null;
}
/// <summary>
/// Builds the MusicBrainz release group search query for the provided title and artist.
/// </summary>
/// <param name="title">The title of the release group.</param>
/// <param name="artistName">The name of the artist, if applicable.</param>
/// <returns>The built search query.</returns>
private static string BuildReleaseGroupQuery(string title, string? artistName)
{
string query = $"releasegroup:\"{title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
if (!string.IsNullOrWhiteSpace(artistName))
query += $" AND artist:\"{artistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
return query;
}
}
Loaded 100 of 1161 files, more files were not shown because too many files have changed in this diff. Show more