Skip to content

Instantly share code, notes, and snippets.

@duganchen
Last active September 5, 2021 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duganchen/e40ff8a31d749f8b942e89022ba4271e to your computer and use it in GitHub Desktop.
Save duganchen/e40ff8a31d749f8b942e89022ba4271e to your computer and use it in GitHub Desktop.
A Go-style C++ wrapper for libmpdclient
#include <iostream>
#include <memory>
#include <mpd/client.h>
#include <string>
#include <tuple>
#include <vector>
namespace mpd {
using namespace std::string_literals;
typedef std::unique_ptr<mpd_connection, decltype(&mpd_connection_free)> connection;
auto get_error(const connection &conn) {
mpd_error error_code{mpd_connection_get_error(conn.get())};
if (MPD_ERROR_SUCCESS != error_code) {
std::string message{mpd_connection_get_error_message(conn.get())};
return std::make_tuple(error_code, message);
}
return std::make_tuple(error_code, ""s);
}
auto connection_new(const char *host, unsigned port, unsigned timeout_ms) {
auto ptr{mpd_connection_new(host, port, timeout_ms)};
connection conn(ptr, &mpd_connection_free);
if (!conn) {
return std::make_tuple(std::move(conn), MPD_ERROR_OOM, ""s);
}
auto [error_code, error_message] = get_error(conn);
return std::make_tuple(std::move(conn), error_code, error_message);
}
auto search_db_tags(const connection &conn, mpd_tag_type tag_type) {
if (mpd_search_db_tags(conn.get(), tag_type)) {
return std::make_tuple(MPD_ERROR_SUCCESS, ""s);
}
return get_error(conn);
}
auto search_commit(const connection &conn) {
if (mpd_search_commit(conn.get())) {
return std::make_tuple(MPD_ERROR_SUCCESS, ""s);
}
return get_error(conn);
}
auto recv_tags(const connection &conn, mpd_tag_type tag_type) {
std::vector<std::string> tags;
mpd_pair *pair{};
while ((pair = mpd_recv_pair_tag(conn.get(), tag_type)) != nullptr) {
tags.emplace_back(pair->value);
mpd_return_pair(conn.get(), pair);
}
auto [error_code, message] = get_error(conn);
return std::make_tuple(std::move(tags), error_code, message);
}
}; // namespace mpd
int main() {
auto [connection, error_code, error_message] = mpd::connection_new("localhost", 6600, 0);
if (MPD_ERROR_SUCCESS != error_code) {
std::cout << error_message << "\n";
return 1;
}
std::tie(error_code, error_message) = mpd::search_db_tags(connection, MPD_TAG_ALBUM);
if (MPD_ERROR_SUCCESS != error_code) {
std::cout << error_message << "\n";
return 1;
}
std::tie(error_code, error_message) = mpd::search_commit(connection);
if (MPD_ERROR_SUCCESS != error_code) {
std::cout << error_message << "\n";
return 1;
}
std::vector<std::string> tags;
std::tie(tags, error_code, error_message) = mpd::recv_tags(connection, MPD_TAG_ALBUM);
if (MPD_ERROR_SUCCESS != error_code) {
std::cout << error_message << "\n";
return 1;
}
for (auto tag : tags) {
std::cout << tag << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment