Compare commits

...

3 commits

Author SHA1 Message Date
1bcbad8f80 Word on recording id test 2025-03-07 19:44:33 -05:00
daff0dc8c9 Make tests 2025-03-07 13:01:59 -05:00
a8d485ffe1 Fix memory leak
I'm not sure I'm happy with this yet, but it works, so who am I to judge
2025-03-07 10:23:03 -05:00
6 changed files with 248 additions and 66 deletions

View file

View file

@ -29,20 +29,20 @@ pub fn build(b: *std.Build) void {
}); });
// We will also create a module for our other entry point, 'main.zig'. // We will also create a module for our other entry point, 'main.zig'.
const exe_mod = b.createModule(.{ //const exe_mod = b.createModule(.{
// `root_source_file` is the Zig "entry point" of the module. If a module // // `root_source_file` is the Zig "entry point" of the module. If a module
// only contains e.g. external object files, you can make this `null`. // // only contains e.g. external object files, you can make this `null`.
// In this case the main source file is merely a path, however, in more // // In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file. // // complicated build scripts, this could be a generated file.
.root_source_file = b.path("src/main.zig"), // .root_source_file = b.path("src/main.zig"),
.target = target, // .target = target,
.optimize = optimize, // .optimize = optimize,
}); //});
// Modules can depend on one another using the `std.Build.Module.addImport` function. // Modules can depend on one another using the `std.Build.Module.addImport` function.
// This is what allows Zig source code to use `@import("foo")` where 'foo' is not a // This is what allows Zig source code to use `@import("foo")` where 'foo' is not a
// file path. In this case, we set up `exe_mod` to import `lib_mod`. // file path. In this case, we set up `exe_mod` to import `lib_mod`.
exe_mod.addImport("muzigbrainz_lib", lib_mod); //exe_mod.addImport("muzigbrainz_lib", lib_mod);
// Now, we will create a static library based on the module we created above. // Now, we will create a static library based on the module we created above.
// This creates a `std.Build.Step.Compile`, which is the build step responsible // This creates a `std.Build.Step.Compile`, which is the build step responsible
@ -60,41 +60,41 @@ pub fn build(b: *std.Build) void {
// This creates another `std.Build.Step.Compile`, but this one builds an executable // This creates another `std.Build.Step.Compile`, but this one builds an executable
// rather than a static library. // rather than a static library.
const exe = b.addExecutable(.{ //const exe = b.addExecutable(.{
.name = "muzigbrainz", // .name = "muzigbrainz",
.root_module = exe_mod, // .root_module = exe_mod,
}); //});
const zig_time_dep = b.dependency("zeit", .{}); const zig_time_dep = b.dependency("zeit", .{});
exe.root_module.addImport("zeit", zig_time_dep.module("zeit")); lib.root_module.addImport("zeit", zig_time_dep.module("zeit"));
// This declares intent for the executable to be installed into the // This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default // standard location when the user invokes the "install" step (the default
// step when running `zig build`). // step when running `zig build`).
b.installArtifact(exe); //b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another // This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish // step is evaluated that depends on it. The next line below will establish
// such a dependency. // such a dependency.
const run_cmd = b.addRunArtifact(exe); //const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the // By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory. // installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed // This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location. // files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep()); //run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build // This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc` // command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| { //if (b.args) |args| {
run_cmd.addArgs(args); // run_cmd.addArgs(args);
} //}
// This creates a build step. It will be visible in the `zig build --help` menu, // This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run` // and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install". // This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app"); //const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step); //run_step.dependOn(&run_cmd.step);
// Creates a step for unit testing. This only builds the test executable // Creates a step for unit testing. This only builds the test executable
// but does not run it. // but does not run it.
@ -102,18 +102,20 @@ pub fn build(b: *std.Build) void {
.root_module = lib_mod, .root_module = lib_mod,
}); });
lib_unit_tests.root_module.addImport("zeit", zig_time_dep.module("zeit"));
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const exe_unit_tests = b.addTest(.{ //const exe_unit_tests = b.addTest(.{
.root_module = exe_mod, // .root_module = exe_mod,
}); //});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); //const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to // Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request // the `zig build --help` menu, providing a way for the user to request
// running the unit tests. // running the unit tests.
const test_step = b.step("test", "Run unit tests"); const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step); test_step.dependOn(&run_lib_unit_tests.step);
test_step.dependOn(&run_exe_unit_tests.step); //test_step.dependOn(&run_exe_unit_tests.step);
} }

View file

@ -1,14 +1,14 @@
pub const Alias = struct { pub const Alias = struct {
@"sort-name": []const u8, @"sort-name": []const u8,
//sort_name: []const u8, //sort_name: []const u8,
@"type-id": []const u8, @"type-id": ?[]const u8 = null,
//type_id: []const u8, //type_id: []const u8,
name: []const u8, name: []const u8,
locale: ?[]const u8, locale: ?[]const u8 = null,
type: []const u8, type: ?[]const u8 = null,
primary: ?[]const u8, primary: ?[]const u8 = null,
@"begin-date": ?[]const u8, @"begin-date": ?[]const u8 = null,
//begin_date: []const u8, //begin_date: []const u8,
@"end-date": ?[]const u8, @"end-date": ?[]const u8 = null,
//end_date: []const u8, //end_date: []const u8,
}; };

View file

@ -2,6 +2,7 @@
//! Fields based on JSON response fields //! Fields based on JSON response fields
const Alias = @import("Alias.zig").Alias; const Alias = @import("Alias.zig").Alias;
const zeit = @import("zeit");
pub const Artist = struct { pub const Artist = struct {
id: []const u8, id: []const u8,
@ -9,12 +10,15 @@ pub const Artist = struct {
@"sort-name": []const u8, @"sort-name": []const u8,
//sort_name: []const u8, //sort_name: []const u8,
aliases: ?[]Alias = null, aliases: ?[]Alias = null,
disambiguation: ?[]const u8 = null,
}; };
pub const ArtistCredit = struct { pub const ArtistCredit = struct {
joinphrase: ?[]const u8 = null,
name: []const u8, name: []const u8,
artist: Artist, artist: Artist,
}; };
pub const Recording = struct { pub const Recording = struct {
id: []const u8, id: []const u8,
score: u8, score: u8,
@ -23,15 +27,19 @@ pub const Recording = struct {
video: ?bool, video: ?bool,
@"artist-credit": []ArtistCredit, @"artist-credit": []ArtistCredit,
//artist_credit: []ArtistCredit, //artist_credit: []ArtistCredit,
@"first-release-date": []const u8, //@"first-release-date": ?[]const u8 = null,
@"first-release-date": ?union(enum) { slice: []const u8, dt: zeit.Date } = null,
//first_release_date: []const u8, //first_release_date: []const u8,
releases: []Release, releases: []Release,
isrcs: ?[][]const u8 = null,
tags: ?[]Tag = null,
disambiguation: ?[]const u8 = null,
}; };
pub const Release = struct { pub const Release = struct {
id: []const u8, id: []const u8,
@"status-id": ?[]const u8 = null, @"status-id": ?[]const u8 = null,
//status_id: ?[]const u8 = null, //status_id: ?[]const u8 = null,
count: i32, count: u8,
title: []const u8, title: []const u8,
@"artist-credit": []ArtistCredit, @"artist-credit": []ArtistCredit,
//artist_credit: []ArtistCredit, //artist_credit: []ArtistCredit,
@ -45,10 +53,11 @@ pub const Release = struct {
country: ?[]const u8 = null, country: ?[]const u8 = null,
@"release-events": ?[]ReleaseEvent = null, @"release-events": ?[]ReleaseEvent = null,
//release_events: ?[]ReleaseEvent = null, //release_events: ?[]ReleaseEvent = null,
disambiguation: ?[]const u8 = null,
}; };
pub const Medium = struct { pub const Medium = struct {
position: u8, position: u8,
format: []const u8, format: ?[]const u8 = null,
track: []Track, track: []Track,
@"track-count": u8, @"track-count": u8,
//track_count: u8, //track_count: u8,
@ -82,4 +91,11 @@ pub const ReleaseGroup = struct {
title: []const u8, title: []const u8,
@"primary-type": []const u8, @"primary-type": []const u8,
//primary_type: []const u8, //primary_type: []const u8,
@"secondary-types": ?[][]const u8 = null,
@"secondary-type-ids": ?[][]const u8 = null,
};
const Tag = struct {
count: u8,
name: []const u8,
}; };

View file

@ -1,11 +1,91 @@
const std = @import("std");
const zeit = @import("zeit");
const Entities = @import("Entities.zig"); const Entities = @import("Entities.zig");
const Artist = Entities.Artist;
const Recording = Entities.Recording; const Recording = Entities.Recording;
pub const Result = struct { pub const Result = struct {
created: ?[]const u8 = null, created: ?[]const u8 = null,
//created: ?zeit.Instant.Source.iso8601 = null,
count: ?u32 = null, count: ?u32 = null,
offset: ?u32 = null, offset: ?u32 = null,
artists: ?[]Artist = null,
recordings: ?[]Recording = null, recordings: ?[]Recording = null,
@"error": ?[]const u8 = null, @"error": ?[]const u8 = null,
help: ?[]const u8 = null, help: ?[]const u8 = null,
pub fn getSpecifiedARID(self: *const Result, an: []const u8, tn: []const u8) ?[]const u8 {
if (self.count) |count| { // Otherwise there was an error
switch (count) {
0 => return null, // No results
1 => {
switch (self.recordings.?[0].@"artist-credit".len) {
0 => unreachable, // All recordings have at least one ArtistCredit
1 => return self.recordings.?[0].@"artist-credit"[0].artist.id,
else => {
for (self.recordings.?[0].@"artist-credit") |ac| {
if (std.mem.eql(u8, ac.name, an)) return ac.artist.id;
}
},
}
},
else => {
for (self.recordings.?) |rc| {
if (std.mem.eql(u8, rc.title, tn)) { // I'd really prefer not including track name, but for complete accuracy
for (rc.@"artist-credit") |ac| {
if (std.mem.eql(u8, ac.name, an)) return ac.artist.id;
}
}
}
},
}
}
return null; // Maybe return error here instead
}
// Not sure if I want to get a ReleaseGroup or Release yet. Start with ReleaseGroup
pub fn getSpecifiedRGID(self: *const Result, tn: []const u8, rgn: []const u8) ?[]const u8 {
if (self.count) |count| {
switch (count) {
0 => return null,
1 => {
switch (self.recordings.?[0].releases.len) {
0 => unreachable,
1 => return self.recordings.?[0].releases[0].id,
else => {
for (self.recordings.?[0].releases) |re| {
if (std.mem.eql(u8, re.title, rgn)) return re.id;
}
},
}
},
else => { // This is not ideal, limit the number of results
for (self.recordings.?) |rc| {
if (std.mem.eql(u8, rc.title, tn)) {
for (rc.releases) |re| {
if (std.mem.eql(u8, re.@"release-group".title, rgn)) return re.@"release-group".id;
}
}
}
},
}
}
return null;
}
pub fn getSpecifiedRID(self: *const Result, tn: []const u8, rgn: []const u8, an: []const u8) ?[]const u8 {
_ = tn;
_ = rgn;
_ = an;
if (self.count) |count| {
switch (count) {
0 => return null,
1 => return self.recording.?[0].id,
else => {
return null; // Sort by date
},
}
}
}
}; };

View file

@ -8,57 +8,39 @@ const Client = std.http.Client;
pub const user_agent: []const u8 = "ZuletztMBClient/0.0.1 (swebbguy@gmail.com)"; pub const user_agent: []const u8 = "ZuletztMBClient/0.0.1 (swebbguy@gmail.com)";
pub fn mbSearch(allocator: std.mem.Allocator, track_name: []const u8, album_name: []const u8, artist_name: []const u8) !?QR.Result { pub fn mbSearch(allocator: std.mem.Allocator, ar: *std.ArrayList(u8), track_name: []const u8, album_name: []const u8, artist_name: []const u8) !?[]const u8 {
var client = Client{ .allocator = allocator }; var client = Client{ .allocator = allocator };
defer client.deinit(); defer client.deinit();
const query: []const u8 = try std.fmt.allocPrint(allocator, "https://musicbrainz.org/ws/2/recording/?query=\"{s}\"%20AND%20artist:\"{s}\"%20AND%20release:\"{s}\"&fmt=json", .{ track_name, artist_name, album_name }); const query: []const u8 = try std.fmt.allocPrint(allocator, "https://musicbrainz.org/ws/2/recording/?query=\"{s}\"%20AND%20artist:\"{s}\"%20AND%20release:\"{s}\"&fmt=json", .{ track_name, artist_name, album_name });
defer allocator.free(query); defer allocator.free(query);
var mb_result = std.ArrayList(u8).init(allocator); const response: Client.FetchResult = try client.fetch(.{ .response_storage = .{ .dynamic = ar }, .location = .{ .url = query }, .method = .GET, .headers = .{ .user_agent = .{ .override = user_agent } } });
errdefer mb_result.deinit();
const response: Client.FetchResult = try client.fetch(.{ .response_storage = .{ .dynamic = &mb_result }, .location = .{ .url = query }, .method = .GET, .headers = .{ .user_agent = .{ .override = user_agent } } });
switch (@intFromEnum(response.status)) { switch (@intFromEnum(response.status)) {
0...299 => std.log.debug("Success", .{}), 0...299 => std.log.debug("Success\n", .{}),
300...399 => { 300...399 => {
std.log.debug("Redirected", .{}); std.log.err("Redirected\n", .{});
return null; return null;
}, },
400...511 => { 400...511 => {
std.log.err("Get rekt\n{s}", .{mb_result.items}); std.log.err("Get rekt\n{s}", .{ar.items});
return Client.ConnectError.ConnectionRefused; return Client.ConnectError.ConnectionRefused;
}, },
512 => { 512 => {
std.log.debug("Need to login", .{}); std.log.err("Need to login\n", .{});
return null; return null;
}, },
else => unreachable, else => unreachable,
} }
//std.log.err("{s}", .{mb_result_slice}); return ar.items;
const result = try std.json.parseFromSlice(QR.Result, allocator, mb_result.items, .{ .ignore_unknown_fields = true });
defer result.deinit();
const query_result = result.value;
return query_result;
} }
//pub fn getAlbumMBID(query: QR.Result)
//pub fn getArtistMBID(query: QR.Result)
//pub fn getSongMBID(query: QR.Result)
//test "basic add functionality" {
// try testing.expect(add(3, 7) == 10);
//}
// This test is very volatile, but I think // This test is very volatile, but I think
// these params are specific enough that // these params are specific enough that
// it shouldn't need changing too often // it shouldn't need changing too often
test "iamthemorning" { test "arid_via_recording" {
const test_alloc = std.testing.allocator; const test_alloc = std.testing.allocator;
const track: []const u8 = "Veni%20Veni%20Emmanuel"; const track: []const u8 = "Veni%20Veni%20Emmanuel";
const album: []const u8 = "Counting%20the%20Ghosts"; const album: []const u8 = "Counting%20the%20Ghosts";
@ -66,9 +48,111 @@ test "iamthemorning" {
const iatm_id: []const u8 = "5854a6de-af8f-4b99-8710-cb47d6436a19"; const iatm_id: []const u8 = "5854a6de-af8f-4b99-8710-cb47d6436a19";
const search_result: ?QR.Result = try mbSearch(test_alloc, track, album, artist); var mb_result = std.ArrayList(u8).init(test_alloc);
defer mb_result.deinit();
const search_result = try mbSearch(test_alloc, &mb_result, track, album, artist);
if (search_result) |sr| { if (search_result) |sr| {
const recording = sr.recordings.?[0]; const json = try std.json.parseFromSlice(QR.Result, test_alloc, sr, .{ .ignore_unknown_fields = true });
try testing.expect(std.mem.eql(u8, recording.id, iatm_id)); defer json.deinit();
const result: QR.Result = json.value;
try testing.expect(std.mem.eql(u8, result.getSpecifiedARID(artist, "Veni veni Emmanuel").?, iatm_id));
} }
} }
test "arid_via_recording_multiple_artists_1" {
const test_alloc = std.testing.allocator;
const track: []const u8 = "Roll%20Me%20Up%20And%20Smoke%20Me%20When%20I%20Die";
const album: []const u8 = "Willie%20Nelson%20American%20Outlaw";
const artist: []const u8 = "Lyle%20Lovett";
const ll_id: []const u8 = "7241e3ed-5ad4-4849-94df-6858ea833472";
var mb_result = std.ArrayList(u8).init(test_alloc);
defer mb_result.deinit();
const search_result = try mbSearch(test_alloc, &mb_result, track, album, artist);
if (search_result) |sr| {
const json = try std.json.parseFromSlice(QR.Result, test_alloc, sr, .{ .ignore_unknown_fields = true });
defer json.deinit();
const result: QR.Result = json.value;
try testing.expect(std.mem.eql(u8, result.getSpecifiedARID("Lyle Lovett", "Roll Me Up and Smoke Me When I Die").?, ll_id));
}
}
test "rgid_via_recording" {
const test_alloc = std.testing.allocator;
const track: []const u8 = "I%20Of%20The%20Storm";
const album: []const u8 = "Beneath%20The%20Skin";
const artist: []const u8 = "Of%20Monsters%20and%20Men";
const bts_id: []const u8 = "2e1e605d-5090-420d-beae-e7ff73791082";
var mb_result = std.ArrayList(u8).init(test_alloc);
defer mb_result.deinit();
const search_result = try mbSearch(test_alloc, &mb_result, track, album, artist);
if (search_result) |sr| {
const json = try std.json.parseFromSlice(QR.Result, test_alloc, sr, .{ .ignore_unknown_fields = true });
defer json.deinit();
const result: QR.Result = json.value;
try testing.expect(std.mem.eql(u8, result.getSpecifiedRGID("I of the Storm", "Beneath the Skin").?, bts_id));
}
}
test "rgid_via_recording_multiple_artists_2" {
const test_alloc = std.testing.allocator;
const track: []const u8 = "Hesitating%20Beauty";
const album: []const u8 = "Mermaid%20Avenue";
const artist: []const u8 = "Wilco";
const wilco_id: []const u8 = "9e53f84d-ef44-4c16-9677-5fd4d78cbd7d";
var mb_result = std.ArrayList(u8).init(test_alloc);
defer mb_result.deinit();
const search_result = try mbSearch(test_alloc, &mb_result, track, album, artist);
if (search_result) |sr| {
const json = try std.json.parseFromSlice(QR.Result, test_alloc, sr, .{ .ignore_unknown_fields = true });
defer json.deinit();
const result: QR.Result = json.value;
try testing.expect(std.mem.eql(u8, result.getSpecifiedARID("Wilco", "Hesitating Beauty").?, wilco_id));
}
//try testing.expect(false);
}
//test "rid" {
// const test_alloc = std.testing.allocator;
// const track: []const u8 = "Battery";
// const album: []const u8 = "Master%20of%20Puppets";
// const artist: []const u8 = "Metallica";
//
// const battery_id: []const u8 = "3bfda26a-49fa-4bc4-a4d6-8bbfa0767ab7";
//
// var mb_result = std.ArrayList(u8).init(test_alloc);
// defer mb_result.deinit();
//
// const search_result = try mbSearch(test_alloc, &mb_result, track, album, artist);
//
// if (search_result) |sr| {
// const json = try std.json.parseFromSlice(QR.Result, test_alloc, sr, .{ .ignore_unknown_fields = true });
// defer json.deinit();
//
// const result: QR.Result = json.value;
//
// try testing.expect(std.mem.eql(u8, result.getSpecifiedARID("Wilco", "Hesitating Beauty").?, battery_id));
// }
//}