Files
EchoionCore/include/echoion/core/commands/SearchCommand.hpp
T

131 lines
3.2 KiB
C++

#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core
{
class SearchCommand : public Command
{
public:
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
ctx.reply("Usage: search <query>\nExample: search "
"never gonna give you up");
return;
}
auto result = manager->search(ctx.args);
if (!result) {
ECHOION_LOG_ERROR(
std::format("Search failed for '{}': {}", ctx.args,
result.error().message));
if (result.error().code ==
Api::ErrorCode::NetworkError) {
ctx.reply("Couldn't connect to search service. "
"Please check your connection.");
} else {
ctx.reply("Search failed. Please try again later.");
}
return;
}
if (result->tracks.empty()) {
ctx.reply("No results found. Try different keywords.");
return;
}
// Store results for this client so they can use select
manager->storePendingSearch(ctx.clientId, result->tracks);
std::stringstream msg;
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args
<< "\":\n\n";
for (size_t i = 0; i < result->tracks.size() && i < 5;
++i) {
const auto& track = result->tracks[i];
// Format as [Title by Artist](shortenedUrl) with
// duration
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText = std::format("{} by {}", track.title,
track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
msg << std::format("{}. {}", i + 1, linkText);
if (track.duration.has_value()) {
msg << std::format(" [{}]",
formatDuration(*track.duration));
}
msg << "\n";
}
msg << std::format(
"\nUse {}select <number> to play a result.",
ctx.prefix);
ctx.reply(msg.str());
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Search command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override
{
return "Searches for tracks and shows results.";
}
std::string_view getUsage() const override { return "<query>"; }
CommandCategory getCategory() const override
{
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override
{
return {"find", "s"};
}
private:
static std::string
formatDuration(std::chrono::milliseconds duration)
{
auto totalSeconds = duration.count() / 1000;
auto hours = totalSeconds / 3600;
auto mins = (totalSeconds % 3600) / 60;
auto secs = totalSeconds % 60;
if (hours > 0) {
return std::format("{}:{:02}:{:02}", hours, mins, secs);
}
return std::format("{}:{:02}", mins, secs);
}
};
} // namespace Echoion::Core