60 lines
1.5 KiB
C++
60 lines
1.5 KiB
C++
// GNU Lesser General Public License v3.0
|
|
// Copyright (c) 2025 Bart Beumer <bart@4beumer.nl>
|
|
//
|
|
// This program is free software; you can redistribute it and/or modify it
|
|
// under the terms of the GNU Lesser General Public License v3.0 as published by
|
|
// the Free Software Foundation.
|
|
//
|
|
#include <bmrshared/magic_file_info.hpp>
|
|
|
|
namespace bmrshared
|
|
{
|
|
magic_file_info::magic_file_info(const std::filesystem::path& path)
|
|
: m_magic_cookie(nullptr)
|
|
{
|
|
bool load_ok = false;
|
|
m_magic_cookie = magic_open(MAGIC_MIME_TYPE);
|
|
|
|
if (m_magic_cookie != nullptr && std::filesystem::is_regular_file(path))
|
|
{
|
|
load_ok = (magic_load(m_magic_cookie, path.native().c_str()) == 0);
|
|
}
|
|
|
|
if (m_magic_cookie && !load_ok)
|
|
{
|
|
magic_close(m_magic_cookie);
|
|
m_magic_cookie = nullptr;
|
|
}
|
|
|
|
if (!load_ok)
|
|
{
|
|
throw std::runtime_error("Could not initialize libmagic.");
|
|
}
|
|
}
|
|
|
|
magic_file_info::~magic_file_info()
|
|
{
|
|
magic_close(m_magic_cookie);
|
|
}
|
|
|
|
std::string magic_file_info::get_mime(const std::filesystem::path& path) const
|
|
{
|
|
std::string mime;
|
|
if (std::filesystem::is_regular_file(path))
|
|
{
|
|
const char* file_name = path.native().c_str();
|
|
const char* magic_full = nullptr;
|
|
if (file_name != nullptr)
|
|
{
|
|
magic_full = magic_file(m_magic_cookie, file_name);
|
|
}
|
|
if (magic_full != nullptr)
|
|
{
|
|
mime = magic_full;
|
|
}
|
|
}
|
|
return mime;
|
|
}
|
|
|
|
} // namespace bmrshared
|