From f6c5bcca398418da7c48a260609f9f6ba70ea86f Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 18 Jan 2026 18:22:09 +0300 Subject: [PATCH] Initial commit --- .gitignore | 3 + CMakeLists.txt | 110 + cmake/FindGStreamer.cmake | 458 + config/example.json | 32 + include/Core/Plugin.hpp | 419 + include/Core/PluginDefinitions.hpp | 76 + include/Core/Spotify/Client.hpp | 332 + include/Core/Spotify/HttpCallbackServer.hpp | 28 + include/Core/Spotify/PkceAuth.hpp | 57 + include/Core/Spotify/RequestParams.hpp | 496 + include/Core/Spotify/Types/Album.hpp | 178 + include/Core/Spotify/Types/Artist.hpp | 84 + include/Core/Spotify/Types/Common.hpp | 185 + include/Core/Spotify/Types/Other.hpp | 133 + include/Core/Spotify/Types/Player.hpp | 218 + include/Core/Spotify/Types/Playlist.hpp | 139 + include/Core/Spotify/Types/Track.hpp | 318 + include/Core/Spotify/Types/User.hpp | 77 + include/Core/Youtube/Client.hpp | 274 + include/Core/Youtube/EmbeddedJs.hpp | 13240 +++++++ include/Core/Youtube/SolverCore.hpp | 1422 + include/Core/Youtube/SolverLib.hpp | 30565 ++++++++++++++++ include/Core/ts6bot/AudioDecoder.hpp | 55 + include/Core/ts6bot/Config.hpp | 118 + include/Core/ts6bot/Crypto.hpp | 23 + include/Core/ts6bot/Log.hpp | 22 + include/Core/ts6bot/MusicManager.hpp | 100 + include/Core/ts6bot/Proxy.hpp | 14 + include/Core/ts6bot/SignalShutdown.hpp | 17 + include/Core/ts6bot/Url.hpp | 22 + include/Core/ts6bot/VirtualMicrophone.bak | 114 + include/Shared/PluginInterface.hpp | 360 + include/Teamspeak/plugin_definitions.h | 53 + include/Teamspeak/teamlog/logtypes.h | 23 + .../Teamspeak/teamspeak/public_definitions.h | 579 + include/Teamspeak/teamspeak/public_errors.h | 200 + .../Teamspeak/teamspeak/public_errors_rare.h | 108 + .../teamspeak/public_rare_definitions.h | 368 + include/Teamspeak/ts3_functions.h | 312 + src/Core/AudioDecoder.cpp | 225 + src/Core/Crypto.cpp | 105 + src/Core/MusicManager.cpp | 453 + src/Core/Plugin.cpp | 233 + src/Core/SignalShutdown.cpp | 39 + src/Core/Spotify/Client.cpp | 497 + src/Core/Spotify/HttpCallbackServer.cpp | 156 + src/Core/Spotify/PkceAuth.cpp | 244 + src/Core/Url.cpp | 64 + src/Core/Youtube/Client.cpp | 660 + src/Plugin/.harper-dictionary.txt | 1 + src/Plugin/Plugin.cpp | 1020 + src/VirtualMicrophone.bak | 420 + 52 files changed, 55449 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 cmake/FindGStreamer.cmake create mode 100644 config/example.json create mode 100644 include/Core/Plugin.hpp create mode 100644 include/Core/PluginDefinitions.hpp create mode 100644 include/Core/Spotify/Client.hpp create mode 100644 include/Core/Spotify/HttpCallbackServer.hpp create mode 100644 include/Core/Spotify/PkceAuth.hpp create mode 100644 include/Core/Spotify/RequestParams.hpp create mode 100644 include/Core/Spotify/Types/Album.hpp create mode 100644 include/Core/Spotify/Types/Artist.hpp create mode 100644 include/Core/Spotify/Types/Common.hpp create mode 100644 include/Core/Spotify/Types/Other.hpp create mode 100644 include/Core/Spotify/Types/Player.hpp create mode 100644 include/Core/Spotify/Types/Playlist.hpp create mode 100644 include/Core/Spotify/Types/Track.hpp create mode 100644 include/Core/Spotify/Types/User.hpp create mode 100644 include/Core/Youtube/Client.hpp create mode 100644 include/Core/Youtube/EmbeddedJs.hpp create mode 100644 include/Core/Youtube/SolverCore.hpp create mode 100644 include/Core/Youtube/SolverLib.hpp create mode 100644 include/Core/ts6bot/AudioDecoder.hpp create mode 100644 include/Core/ts6bot/Config.hpp create mode 100644 include/Core/ts6bot/Crypto.hpp create mode 100644 include/Core/ts6bot/Log.hpp create mode 100644 include/Core/ts6bot/MusicManager.hpp create mode 100644 include/Core/ts6bot/Proxy.hpp create mode 100644 include/Core/ts6bot/SignalShutdown.hpp create mode 100644 include/Core/ts6bot/Url.hpp create mode 100644 include/Core/ts6bot/VirtualMicrophone.bak create mode 100644 include/Shared/PluginInterface.hpp create mode 100644 include/Teamspeak/plugin_definitions.h create mode 100755 include/Teamspeak/teamlog/logtypes.h create mode 100644 include/Teamspeak/teamspeak/public_definitions.h create mode 100644 include/Teamspeak/teamspeak/public_errors.h create mode 100644 include/Teamspeak/teamspeak/public_errors_rare.h create mode 100644 include/Teamspeak/teamspeak/public_rare_definitions.h create mode 100644 include/Teamspeak/ts3_functions.h create mode 100644 src/Core/AudioDecoder.cpp create mode 100644 src/Core/Crypto.cpp create mode 100644 src/Core/MusicManager.cpp create mode 100644 src/Core/Plugin.cpp create mode 100644 src/Core/SignalShutdown.cpp create mode 100644 src/Core/Spotify/Client.cpp create mode 100644 src/Core/Spotify/HttpCallbackServer.cpp create mode 100644 src/Core/Spotify/PkceAuth.cpp create mode 100644 src/Core/Url.cpp create mode 100644 src/Core/Youtube/Client.cpp create mode 100644 src/Plugin/.harper-dictionary.txt create mode 100644 src/Plugin/Plugin.cpp create mode 100644 src/VirtualMicrophone.bak diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39e742a --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*build* +.cache +.idea diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..ecf323d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,110 @@ +cmake_minimum_required(VERSION 3.24) +project(Echoion LANGUAGES CXX) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + + +file( + DOWNLOAD + https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake + ${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake + EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791 +) +include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake) + +# ---- Deps: libssh2 ---- +find_package(quill REQUIRED) +find_package(glaze REQUIRED) +find_package(GStreamer REQUIRED) +find_package(PkgConfig REQUIRED) +pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET + libavformat + libavcodec + libswresample + libavutil +) +CPMAddPackage( + NAME cpr + GITHUB_REPOSITORY libcpr/cpr + GIT_TAG 1.14.1 + OPTIONS + "CPR_USE_SYSTEM_CURL ON" + "CPR_CURL_USE_LIBPSL OFF" +) +CPMAddPackage( + NAME quickjs + GITHUB_REPOSITORY quickjs-ng/quickjs + GIT_TAG v0.11.0 +) +CPMAddPackage( + NAME singleton + GITHUB_REPOSITORY jimmy-park/singleton + GIT_TAG 1.6.0 + OPTIONS + "SINGLETON_INSTALL ON" + "SINGLETON_INJECT_ABSTRACT_CLASS ON" +) + +file(GLOB_RECURSE PSOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/Plugin/**.cpp") + +file(GLOB_RECURSE CSOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/Core/**.cpp") + + +add_library(${CMAKE_PROJECT_NAME}Core SHARED + ${CSOURCES} +) + +add_library(${CMAKE_PROJECT_NAME}Plugin SHARED + ${PSOURCES} +) + +target_include_directories(${CMAKE_PROJECT_NAME}Core PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include/Shared" +) + +target_include_directories(${CMAKE_PROJECT_NAME}Core PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include/Teamspeak" +) + +target_include_directories(${CMAKE_PROJECT_NAME}Core PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include/Core" +) + +target_include_directories(${CMAKE_PROJECT_NAME}Plugin PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include/Shared" +) +target_include_directories(${CMAKE_PROJECT_NAME}Plugin PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}/include/Teamspeak" +) + +target_compile_options(${CMAKE_PROJECT_NAME}Core PRIVATE + -Wall -Wextra -Wpedantic +) + +target_compile_options(${CMAKE_PROJECT_NAME}Plugin PRIVATE + -Wall -Wextra -Wpedantic +) + +target_link_libraries(${CMAKE_PROJECT_NAME}Core PUBLIC + quill::quill + glaze::glaze + cpr::cpr + singleton::singleton-atomic + pthread PkgConfig::LIBAV qjs +) +target_link_libraries(${CMAKE_PROJECT_NAME}Plugin PUBLIC + ${CMAKE_DL_LIBS} + pthread) + +# Ensure predictable output name +set_target_properties(${CMAKE_PROJECT_NAME}Plugin PROPERTIES + OUTPUT_NAME "Echoion" + PREFIX "" +) + +set_target_properties(${CMAKE_PROJECT_NAME}Core PROPERTIES + OUTPUT_NAME "Echoion" + PREFIX "" + SUFFIX ".ts" +) diff --git a/cmake/FindGStreamer.cmake b/cmake/FindGStreamer.cmake new file mode 100644 index 0000000..f16e861 --- /dev/null +++ b/cmake/FindGStreamer.cmake @@ -0,0 +1,458 @@ +# SPDX-FileCopyrightText: 2024 L. E. Segovia +# SPDX-License-Ref: LGPL-2.1-or-later + +#[=======================================================================[.rst: +FindGStreamer +------- + +Finds the GStreamer library. Requires ``pkg-config`` to be installed. + +Configuration +^^^^^^^^^^^^^ + +This module can be configured with the following variables: + +``GStreamer_STATIC`` + Link against GStreamer statically (see below). + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module defines the following :prop_tgt:`IMPORTED` targets: + +``GStreamer::GStreamer`` + The GStreamer library. + +Result Variables +^^^^^^^^^^^^^^^^ + +This will define the following variables: + +``GStreamer_FOUND`` + True if the system has the GStreamer library. +``GStreamer_VERSION`` + The version of the GStreamer library which was found. +``GStreamer_INCLUDE_DIRS`` + Include directories needed to use GStreamer. +``GStreamer_LIBRARIES`` + Libraries needed to link to GStreamer. + +Cache Variables +^^^^^^^^^^^^^^^ + +The following cache variables may also be set: + +``GStreamer_INCLUDE_DIR`` + The directory containing ``gst/gstversion.h``. +``GStreamer_LIBRARY`` + The path to the GStreamer library. + +Configuration Variables +^^^^^^^^^^^^^^^ + +Setting the following variables is required, depending on the operating system: + +``GStreamer_ROOT_DIR`` + Installation prefix of the GStreamer SDK. + +``GStreamer_USE_STATIC_LIBS` + Set to ON to force the use of the static libraries. Default is OFF. + +``GStreamer_EXTRA_DEPS`` + pkg-config names of the extra dependencies that will be included whenever linking against GStreamer. + +#]=======================================================================] + +if(GStreamer_FOUND) + return() +endif() + +##################### +# Setup variables # +##################### + +if(NOT DEFINED GStreamer_ROOT_DIR AND DEFINED GSTREAMER_ROOT) + set(GStreamer_ROOT_DIR ${GSTREAMER_ROOT}) +endif() + +if(NOT GStreamer_ROOT_DIR) + set(GStreamer_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/../../") +endif() + +if(NOT EXISTS "${GStreamer_ROOT_DIR}") + message(FATAL_ERROR "The directory GStreamer_ROOT_DIR=${GStreamer_ROOT_DIR} does not exist") +endif() + +if(NOT DEFINED GStreamer_USE_STATIC_LIBS) + set(GStreamer_USE_STATIC_LIBS OFF) +endif() + +# Set the environment for pkg-config +if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") + set(ENV{PKG_CONFIG_PATH} "${GStreamer_ROOT_DIR}/lib/pkgconfig;${GStreamer_ROOT_DIR}/lib/gstreamer-1.0/pkgconfig;${GStreamer_ROOT_DIR}/lib/gio/modules/pkgconfig") + # Block pkgconf's forced relocation for non-lib/pkgconfig modules on Windows -- https://github.com/pkgconf/pkgconf/commit/dcf529b83d621ed09e99e41fc35fdffd068bd87a + set(ENV{PKG_CONFIG_DONT_DEFINE_PREFIX} 1) +else() + set(ENV{PKG_CONFIG_PATH} "${GStreamer_ROOT_DIR}/lib/pkgconfig:${GStreamer_ROOT_DIR}/lib/gstreamer-1.0/pkgconfig:${GStreamer_ROOT_DIR}/lib/gio/modules/pkgconfig") +endif() + +# Set the list of extra dependencies +if(NOT DEFINED GStreamer_EXTRA_DEPS) + set(GStreamer_EXTRA_DEPS) + if(DEFINED GSTREAMER_EXTRA_DEPS) + set(GStreamer_EXTRA_DEPS ${GSTREAMER_EXTRA_DEPS}) + endif() +endif() + +# Find libraries. This is meant to be used with static libraries +# (hence the reprioritization) but I've added a fallback to shared libraries +# and stub modules in case any are non-existent. +function(_gst_find_library LOCAL_LIB GST_LOCAL_LIB) + if(DEFINED ${GST_LOCAL_LIB}) + return() + endif() + + set(_gst_suffixes ${CMAKE_FIND_LIBRARY_SUFFIXES}) + set(_gst_prefixes ${CMAKE_FIND_LIBRARY_PREFIXES}) + if(APPLE) + set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".dylib" ".so" ".tbd") + set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib") + elseif(UNIX) + set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".so") + set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib") + else() + set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".lib") + set(CMAKE_FIND_LIBRARY_PREFIXES "" "lib") + endif() + + if("${LOCAL_LIB}" IN_LIST _gst_IGNORED_SYSTEM_LIBRARIES) + set(${GST_LOCAL_LIB} ${LOCAL_LIB} PARENT_SCOPE) + else() + find_library(${GST_LOCAL_LIB} + ${LOCAL_LIB} + HINTS ${ARGN} + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED + ) + set(${GST_LOCAL_LIB} "${${GST_LOCAL_LIB}}" PARENT_SCOPE) + if(NOT ${GST_LOCAL_LIB}) + message(FATAL_ERROR "${LOCAL_LIB} was unexpectedly not found.") + endif() + endif() + + set(CMAKE_FIND_LIBRARY_SUFFIXES ${_gst_suffixes}) + set(CMAKE_FIND_LIBRARY_PREFIXES ${_gst_prefixes}) +endfunction() + +macro(_gst_apply_link_libraries HIDE PC_LIBRARIES PC_HINTS GST_TARGET) + if(APPLE AND ${HIDE}) + target_link_directories(${GST_TARGET} INTERFACE + ${${PC_HINTS}} + ) + endif() + foreach(LOCAL_LIB IN LISTS ${PC_LIBRARIES}) + if(LOCAL_LIB MATCHES "${_gst_SRT_REGEX_PATCH}") + string(REGEX REPLACE "${_gst_SRT_REGEX_PATCH}" "\\1" LOCAL_LIB "${LOCAL_LIB}") + endif() + string(MAKE_C_IDENTIFIER "_gst_${LOCAL_LIB}" GST_LOCAL_LIB) + if(NOT ${GST_LOCAL_LIB}) + _gst_find_library(${LOCAL_LIB} ${GST_LOCAL_LIB} ${${PC_HINTS}}) + endif() + if("${${GST_LOCAL_LIB}}" IN_LIST _gst_IGNORED_SYSTEM_LIBRARIES) + target_link_libraries(${GST_TARGET} INTERFACE + ${${GST_LOCAL_LIB}}) + elseif(APPLE AND ${HIDE}) + set(LOCAL_FILE) + get_filename_component(LOCAL_FILE ${${GST_LOCAL_LIB}} NAME) + target_link_libraries(${GST_TARGET} INTERFACE + "-hidden-l${LOCAL_FILE}") + elseif((UNIX OR ANDROID) AND ${HIDE}) + target_link_libraries(${GST_TARGET} INTERFACE + -Wl,--exclude-libs,${${GST_LOCAL_LIB}}) + else() + target_link_libraries(${GST_TARGET} INTERFACE + ${${GST_LOCAL_LIB}}) + endif() + endforeach() +endmacro() + +macro(_gst_filter_missing_directories GST_INCLUDE_DIRS) + set(_gst_include_dirs) + foreach(DIR IN LISTS ${GST_INCLUDE_DIRS}) + string(MAKE_C_IDENTIFIER "${DIR}" _gst_dir_id) + if(DEFINED _gst_exists_${_gst_dir_id}) + if(_gst_exists_${_gst_dir_id}) + list(APPEND _gst_include_dirs "${DIR}") + endif() + elseif(EXISTS "${DIR}") + list(APPEND _gst_include_dirs "${DIR}") + set(_gst_exists_${_gst_dir_id} TRUE) + else() + message(WARNING "Skipping missing include folder ${DIR}.") + set(_gst_exists_${_gst_dir_id} FALSE) + endif() + endforeach() + set(${GST_INCLUDE_DIRS} "${_gst_include_dirs}") +endmacro() + +macro(_gst_apply_frameworks PC_STATIC_LDFLAGS_OTHER GST_TARGET) + if(APPLE) + # LDFLAGS_OTHER may include framework linkage. Because CMake + # iterates over arguments separated by spaces, it doesn't realise + # that those arguments must not be split. + set(new_ldflags) + set(assemble_framework FALSE) + foreach(_arg IN LISTS ${PC_STATIC_LDFLAGS_OTHER}) + if(assemble_framework) + set(assemble_framework FALSE) + find_library(GST_${_arg}_LIB ${_arg} REQUIRED) + target_link_libraries(${GST_TARGET} + INTERFACE + "${GST_${_arg}_LIB}" + ) + elseif(_arg STREQUAL "-framework") + set(assemble_framework TRUE) + else() + set(assemble_framework FALSE) + list(APPEND new_ldflags "${_arg}") + endif() + endforeach() + set_target_properties(${GST_TARGET} PROPERTIES + INTERFACE_LINK_OPTIONS "${new_ldflags}" + ) + else() + set_target_properties(${TARGET} PROPERTIES + INTERFACE_LINK_OPTIONS "${${PC_STATIC_LDFLAGS_OTHER}}" + ) + endif() +endmacro() + +################################ +# Set up the targets # +################################ + +find_package(PkgConfig REQUIRED) + +# GStreamer's pkg-config modules are a MUST -- but we'll test them below +pkg_check_modules(PC_GStreamer gstreamer-1.0 ${GStreamer_EXTRA_DEPS}) +# Simulate the list that'll be wholearchive'd. +# Unfortunately, this uses an option only available with pkgconf. +# set(_old_pkg_config_executable "${PKG_CONFIG_EXECUTABLE}") +# set(PKG_CONFIG_EXECUTABLE ${PKG_CONFIG_EXECUTABLE} --maximum-traverse-depth=1) +# pkg_check_modules(PC_GStreamer_NoDeps QUIET REQUIRED gstreamer-1.0 ${GStreamer_EXTRA_DEPS}) +# set(PKG_CONFIG_EXECUTABLE "${_old_pkg_config_executable}") + +set(GStreamer_VERSION "${PC_GStreamer_VERSION}") + +# Test validity of the paths +# NOTE: only paths that must be considered are those provided by pkg-config +# NOTE 2: also exclude sysroots +find_path(GStreamer_INCLUDE_DIR + NAMES gst/gstversion.h + PATHS ${PC_GStreamer_INCLUDE_DIRS} + PATH_SUFFIXES gstreamer-1.0 + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +find_library(GStreamer_LIBRARY + NAMES gstreamer-1.0 + PATHS ${PC_GStreamer_LIBRARY_DIRS} + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH + REQUIRED +) + +# Android: Ignore these libraries when constructing the IMPORTED_LOCATION +set(_gst_IGNORED_SYSTEM_LIBRARIES c c++ unwind m dl atomic) +if(ANDROID) + list(APPEND _gst_IGNORED_SYSTEM_LIBRARIES log GLESv2 EGL OpenSLES android vulkan) +elseif(APPLE) + list(APPEND _gst_IGNORED_SYSTEM_LIBRARIES iconv resolv System) +endif() + +# Normalize library flags coming from srt/haisrt +# https://github.com/Haivision/srt/commit/b90b64d26f850fb0efcc4cdd8b31cbf74bd4db0c +set(_gst_SRT_REGEX_PATCH "^:lib(.+)\\.(a|so|lib|dylib)$") + +if(PC_GStreamer_FOUND AND (NOT TARGET GStreamer::GStreamer)) + # This is not UNKNOWN but INTERFACE, as we only intend to + # make a target suitable for downstream consumption. + # FindPkgConfig already takes care of things, however it is totally unable + # to discern between shared and static libraries when populating + # xxx_STATIC_LINK_LIBRARIES, so we need to populate them manually. + add_library(GStreamer::GStreamer INTERFACE IMPORTED) + + if(GStreamer_USE_STATIC_LIBS) + _gst_filter_missing_directories(PC_GStreamer_STATIC_INCLUDE_DIRS) + set_target_properties(GStreamer::GStreamer PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_STATIC_CFLAGS_OTHER}" + ) + if(PC_GStreamer_STATIC_INCLUDE_DIRS) + set_target_properties(GStreamer::GStreamer PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_STATIC_INCLUDE_DIRS}" + ) + endif() + _gst_apply_frameworks(PC_GStreamer_STATIC_LDFLAGS_OTHER GStreamer::GStreamer) + else() + set_target_properties(GStreamer::GStreamer PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_CFLAGS_OTHER}" + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_INCLUDE_DIRS}" + INTERFACE_LINK_OPTIONS "${PC_GStreamer_LDFLAGS_OTHER}" + ) + endif() + + add_library(GStreamer::deps INTERFACE IMPORTED) + + if(NOT GStreamer_USE_STATIC_LIBS) + set_target_properties(GStreamer::deps PROPERTIES + INTERFACE_LINK_LIBRARIES "${PC_GStreamer_LINK_LIBRARIES}" + ) + # We're done + else() + # Handle all libraries, even those specified with -l:libfoo.a (srt) + # Due to the unavailability of pkgconf's `--maximum-traverse-depth` + # on stock pkg-config, I attempt to simulate it through the shared + # libraries listing. + # If pkgconf is available, replace all PC_GStreamer_ entries with + # PC_GStreamer_NoDeps and uncomment the code block above. + foreach(LOCAL_LIB IN LISTS PC_GStreamer_LIBRARIES) + # list(TRANSFORM REPLACE) is of no use here + # https://gitlab.kitware.com/cmake/cmake/-/issues/16899 + if(LOCAL_LIB MATCHES "${_gst_SRT_REGEX_PATCH}") + string(REGEX REPLACE "${_gst_SRT_REGEX_PATCH}" "\\1" LOCAL_LIB "${LOCAL_LIB}") + endif() + string(MAKE_C_IDENTIFIER "_gst_${LOCAL_LIB}" GST_LOCAL_LIB) + if(NOT ${GST_LOCAL_LIB}) + _gst_find_library(${LOCAL_LIB} ${GST_LOCAL_LIB} ${PC_GStreamer_STATIC_LIBRARY_DIRS}) + endif() + target_link_libraries(GStreamer::GStreamer INTERFACE + "${${GST_LOCAL_LIB}}" + ) + endforeach() + + _gst_apply_link_libraries(ON PC_GStreamer_STATIC_LIBRARIES PC_GStreamer_STATIC_LIBRARY_DIRS GStreamer::deps) + endif() + + target_link_libraries(GStreamer::GStreamer + INTERFACE + GStreamer::deps + ) +endif() + +foreach(_gst_PLUGIN IN LISTS GSTREAMER_PLUGINS) + # Safety valve for the custom targets above + if("${_gst_plugin}" IN_LIST _gst_CUSTOM_TARGETS) + continue() + endif() + + if(TARGET GStreamer::${_gst_PLUGIN}) + continue() + endif() + + if(GStreamer_FIND_REQUIRED_${_gst_PLUGIN}) + set(_gst_PLUGIN_REQUIRED REQUIRED) + else() + set(_gst_PLUGIN_REQUIRED) + endif() + + pkg_check_modules(PC_GStreamer_${_gst_PLUGIN} "gst${_gst_PLUGIN}") + + set(GStreamer_${_gst_PLUGIN}_FOUND "${PC_GStreamer_${_gst_PLUGIN}_FOUND}") + if(NOT GStreamer_${_gst_PLUGIN}_FOUND) + continue() + endif() + + add_library(GStreamer::${_gst_PLUGIN} INTERFACE IMPORTED) + _gst_filter_missing_directories(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_CFLAGS_OTHER}" + ) + if(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS}" + ) + endif() + if(GStreamer_USE_STATIC_LIBS) + _gst_apply_frameworks(PC_GStreamer_${_gst_PLUGIN}_STATIC_LDFLAGS_OTHER GStreamer::${_gst_PLUGIN}) + else() + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}" + INTERFACE_LINK_LIBRARIES "${PC_GStreamer_${_gst_PLUGIN}_LINK_LIBRARIES}" + ) + # We're done + continue() + endif() + + # Handle all libraries, even those specified with -l:libfoo.a (srt) + _gst_apply_link_libraries(OFF PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARIES PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARY_DIRS GStreamer::${_gst_PLUGIN}) +endforeach() + +foreach(_gst_PLUGIN IN LISTS GSTREAMER_APIS) + # Safety valve for the custom targets above + if("${_gst_plugin}" IN_LIST _gst_CUSTOM_TARGETS) + continue() + endif() + + if(TARGET GStreamer::${_gst_PLUGIN}) + continue() + endif() + + if(GStreamer_FIND_REQUIRED_${_gst_PLUGIN}) + set(_gst_PLUGIN_REQUIRED REQUIRED) + else() + set(_gst_PLUGIN_REQUIRED) + endif() + + string(REGEX REPLACE "^api_(.+)" "\\1" _gst_PLUGIN_PC "${_gst_PLUGIN}") + string(REPLACE "_" "-" _gst_PLUGIN_PC "${_gst_PLUGIN_PC}") + + pkg_check_modules(PC_GStreamer_${_gst_PLUGIN} "gstreamer-${_gst_PLUGIN_PC}-1.0") + + set(GStreamer_${_gst_PLUGIN}_FOUND "${PC_GStreamer_${_gst_PLUGIN}_FOUND}") + if(NOT GStreamer_${_gst_PLUGIN}_FOUND) + continue() + endif() + + add_library(GStreamer::${_gst_PLUGIN} INTERFACE IMPORTED) + _gst_filter_missing_directories(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_COMPILE_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_CFLAGS_OTHER}" + INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}" + ) + if(PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS) + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${PC_GStreamer_${_gst_PLUGIN}_INCLUDE_DIRS}" + ) + endif() + if(GStreamer_USE_STATIC_LIBS) + _gst_apply_frameworks(PC_GStreamer_${_gst_PLUGIN}_STATIC_LDFLAGS_OTHER GStreamer::${_gst_PLUGIN}) + else() + set_target_properties(GStreamer::${_gst_PLUGIN} PROPERTIES + INTERFACE_LINK_OPTIONS "${PC_GStreamer_${_gst_PLUGIN}_LDFLAGS_OTHER}" + INTERFACE_LINK_LIBRARIES "${PC_GStreamer_${_gst_PLUGIN}_LINK_LIBRARIES}" + ) + # We're done + continue() + endif() + + # Handle all libraries, even those specified with -l:libfoo.a (srt) + _gst_apply_link_libraries(OFF PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARIES PC_GStreamer_${_gst_PLUGIN}_STATIC_LIBRARY_DIRS GStreamer::${_gst_PLUGIN}) +endforeach() + +# Perform final validation +include(FindPackageHandleStandardArgs) +set(_gst_handle_version_range) +if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.19.0") + set(_gst_handle_version_range "HANDLE_VERSION_RANGE") +endif() +find_package_handle_standard_args(GStreamer + REQUIRED_VARS + GStreamer_LIBRARY + GStreamer_INCLUDE_DIR + VERSION_VAR GStreamer_VERSION + ${_gst_handle_version_range} + HANDLE_COMPONENTS +) diff --git a/config/example.json b/config/example.json new file mode 100644 index 0000000..f6d1bd4 --- /dev/null +++ b/config/example.json @@ -0,0 +1,32 @@ +{ + "nickname": "Echoion", + "host": "localhost", + "channel":"", + "password": "", + "loggingLevel":"Trace", + "serverquery": { + "host": "127.0.0.1", + "port": 10022, + "username": "serveradmin", + "password": "CHANGE_ME", + "virtual_server_id": 1, + "nickname": "ts6bot" + }, + "afk": { + "enabled": true, + "idle_seconds": 600, + "afk_channel_id": 42, + "poll_interval_ms": 5000 + }, + "music": { + "enabled": true, + "youtubeApiToken": "" + }, + "proxy": { + "enabled": true, + "url": "", + "type": "SOCKS5", + "username": "", + "password": "" + } +} diff --git a/include/Core/Plugin.hpp b/include/Core/Plugin.hpp new file mode 100644 index 0000000..c678a51 --- /dev/null +++ b/include/Core/Plugin.hpp @@ -0,0 +1,419 @@ +#pragma once +#include "PluginInterface.hpp" +// #include "Youtube/Client.hpp" +#include "ts6bot/AudioDecoder.hpp" +#include +#include +#include +#include +#include +#include +#include +#include "ts6bot/Config.hpp" +#include +#include "quill/sinks/FileSink.h" +#include "quill/sinks/ConsoleSink.h" +#include + +#include "PluginDefinitions.hpp" +#include "ts6bot/MusicManager.hpp" + +class EchoionCore : public IEchoionPlugin { + // Dependencies + quill::Logger *m_logger = nullptr; + std::shared_ptr m_ts3; + std::unique_ptr m_musicManager; + +public: + explicit EchoionCore(std::shared_ptr funcs) { + m_ts3 = std::move(funcs); + } + + void Initialize(bool start = true) override; + + void Shutdown() override; + + // --- HOT RELOAD --- + void RequestGracefulStop() override ; + + bool IsStopped() override; + + std::string SerializeState() override; + + void DeserializeState(const std::string &jsonState) override; + + void onConnectStatusChangeEvent(uint64 serverConnectionHandlerID, int newStatus, unsigned errorNumber) override { + } + + void onNewChannelEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 channelParentID) override { + } + + void onNewChannelCreatedEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 channelParentID, + anyID invokerID, const char *invokerName, + const char *invokerUniqueIdentifier) override { + } + + void onDelChannelEvent(uint64 serverConnectionHandlerID, uint64 channelID, anyID invokerID, const char *invokerName, + const char *invokerUniqueIdentifier) override { + } + + void onChannelMoveEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 newChannelParentID, + anyID invokerID, const char *invokerName, const char *invokerUniqueIdentifier) override { + } + + void onUpdateChannelEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { + } + + void onUpdateChannelEditedEvent(uint64 serverConnectionHandlerID, uint64 channelID, anyID invokerID, + const char *invokerName, const char *invokerUniqueIdentifier) override { + } + + void onUpdateClientEvent(uint64 serverConnectionHandlerID, anyID clientID, anyID invokerID, const char *invokerName, + const char *invokerUniqueIdentifier) override { + } + + void onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID, + int visibility, const char *moveMessage) override; + + void onClientMoveSubscriptionEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility) override { + } + + void onClientMoveTimeoutEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, const char *timeoutMessage) override { + } + + void onClientMoveMovedEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, anyID moverID, const char *moverName, + const char *moverUniqueIdentifier, + const char *moveMessage) override { + } + + void onClientKickFromChannelEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, anyID kickerID, const char *kickerName, + const char *kickerUniqueIdentifier, + const char *kickMessage) override { + } + + void onClientKickFromServerEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, anyID kickerID, const char *kickerName, + const char *kickerUniqueIdentifier, + const char *kickMessage) override { + } + + void onClientIDsEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, anyID clientID, + const char *clientName) override { + } + + void onClientIDsFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onServerEditedEvent(uint64 serverConnectionHandlerID, anyID editerID, const char *editerName, + const char *editerUniqueIdentifier) override { + } + + void onServerUpdatedEvent(uint64 serverConnectionHandlerID) override { + } + + int onServerErrorEvent(uint64 serverConnectionHandlerID, const char *errorMessage, unsigned error, + const char *returnCode, const char *extraMessage) override { + return 0; + } + + void onServerStopEvent(uint64 serverConnectionHandlerID, const char *shutdownMessage) override { + } + + int onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targetMode, anyID toID, anyID fromID, + const char *fromName, const char *fromUniqueIdentifier, const char *message, + int ffIgnored) override; + + void onTalkStatusChangeEvent(uint64 serverConnectionHandlerID, int status, int isReceivedWhisper, + anyID clientID) override { + } + + void onConnectionInfoEvent(uint64 serverConnectionHandlerID, anyID clientID) override { + } + + void onServerConnectionInfoEvent(uint64 serverConnectionHandlerID) override { + } + + void onChannelSubscribeEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { + } + + void onChannelSubscribeFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onChannelUnsubscribeEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { + } + + void onChannelUnsubscribeFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onChannelDescriptionUpdateEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { + } + + void onChannelPasswordChangedEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { + } + + void onPlaybackShutdownCompleteEvent(uint64 serverConnectionHandlerID) override { + } + + void onSoundDeviceListChangedEvent(const char *modeID, int playOrCap) override { + } + + void onEditPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID, anyID clientID, short *samples, int sampleCount, + int channels) override { + } + + void onEditPostProcessVoiceDataEvent(uint64 serverConnectionHandlerID, anyID clientID, short *samples, + int sampleCount, int channels, const unsigned *channelSpeakerArray, + unsigned *channelFillMask) override { + } + + void onEditMixedPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID, short *samples, int sampleCount, + int channels, const unsigned *channelSpeakerArray, + unsigned *channelFillMask) override { + } + + void onEditCapturedVoiceDataEvent(uint64 serverConnectionHandlerID, short *samples, int sampleCount, int channels, + int *edited) override { + } + + void onCustom3dRolloffCalculationClientEvent(uint64 serverConnectionHandlerID, anyID clientID, float distance, + float *volume) override { + } + + void onCustom3dRolloffCalculationWaveEvent(uint64 serverConnectionHandlerID, uint64 waveHandle, float distance, + float *volume) override { + } + + void onUserLoggingMessageEvent(const char *logMessage, int logLevel, const char *logChannel, uint64 logID, + const char *logTime, const char *completeLogString) override { + } + + void onClientBanFromServerEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, anyID kickerID, const char *kickerName, + const char *kickerUniqueIdentifier, + uint64 time, const char *kickMessage) override { + } + + int onClientPokeEvent(uint64 serverConnectionHandlerID, anyID fromClientID, const char *pokerName, + const char *pokerUniqueIdentity, const char *message, int ffIgnored) override { + return 0; + } + + void onClientSelfVariableUpdateEvent(uint64 serverConnectionHandlerID, int flag, const char *oldValue, + const char *newValue) override { + } + + void onFileListEvent(uint64 serverConnectionHandlerID, uint64 channelID, const char *path, const char *name, + uint64 size, uint64 datetime, int type, uint64 incompletesize, const char *returnCode) override { + } + + void onFileListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelID, const char *path) override { + } + + void onFileInfoEvent(uint64 serverConnectionHandlerID, uint64 channelID, const char *name, uint64 size, + uint64 datetime) override { + } + + void onServerGroupListEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID, const char *name, int type, + int iconID, int saveDB) override { + } + + void onServerGroupListFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onServerGroupByClientIDEvent(uint64 serverConnectionHandlerID, const char *name, uint64 serverGroupList, + uint64 clientDatabaseID) override { + } + + void onServerGroupPermListEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID, unsigned permissionID, + int permissionValue, int permissionNegated, int permissionSkip) override { + } + + void onServerGroupPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID) override { + } + + void onServerGroupClientListEvent(uint64 serverConnectionHandlerID, uint64 serverGroupID, uint64 clientDatabaseID, + const char *clientNameIdentifier, const char *clientUniqueID) override { + } + + void onChannelGroupListEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID, const char *name, int type, + int iconID, int saveDB) override { + } + + void onChannelGroupListFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onChannelGroupPermListEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID, unsigned permissionID, + int permissionValue, int permissionNegated, int permissionSkip) override { + } + + void onChannelGroupPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID) override { + } + + void onChannelPermListEvent(uint64 serverConnectionHandlerID, uint64 channelID, unsigned permissionID, + int permissionValue, int permissionNegated, int permissionSkip) override { + } + + void onChannelPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelID) override { + } + + void onClientPermListEvent(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, unsigned permissionID, + int permissionValue, int permissionNegated, int permissionSkip) override { + } + + void onClientPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 clientDatabaseID) override { + } + + void onChannelClientPermListEvent(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, + unsigned permissionID, int permissionValue, int permissionNegated, + int permissionSkip) override { + } + + void onChannelClientPermListFinishedEvent(uint64 serverConnectionHandlerID, uint64 channelID, + uint64 clientDatabaseID) override { + } + + void onClientChannelGroupChangedEvent(uint64 serverConnectionHandlerID, uint64 channelGroupID, uint64 channelID, + anyID clientID, anyID invokerClientID, const char *invokerName, + const char *invokerUniqueIdentity) override { + } + + int onServerPermissionErrorEvent(uint64 serverConnectionHandlerID, const char *errorMessage, unsigned error, + const char *returnCode, unsigned failedPermissionID) override { + } + + void onPermissionListGroupEndIDEvent(uint64 serverConnectionHandlerID, unsigned groupEndID) override { + } + + void onPermissionListEvent(uint64 serverConnectionHandlerID, unsigned permissionID, const char *permissionName, + const char *permissionDescription) override { + } + + void onPermissionListFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onPermissionOverviewEvent(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, uint64 channelID, + int overviewType, uint64 overviewID1, uint64 overviewID2, unsigned permissionID, + int permissionValue, + int permissionNegated, int permissionSkip) override { + } + + void onPermissionOverviewFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onServerGroupClientAddedEvent(uint64 serverConnectionHandlerID, anyID clientID, const char *clientName, + const char *clientUniqueIdentity, uint64 serverGroupID, anyID invokerClientID, + const char *invokerName, + const char *invokerUniqueIdentity) override { + } + + void onServerGroupClientDeletedEvent(uint64 serverConnectionHandlerID, anyID clientID, const char *clientName, + const char *clientUniqueIdentity, uint64 serverGroupID, anyID invokerClientID, + const char *invokerName, + const char *invokerUniqueIdentity) override { + } + + void onClientNeededPermissionsEvent(uint64 serverConnectionHandlerID, unsigned permissionID, + int permissionValue) override { + } + + void onClientNeededPermissionsFinishedEvent(uint64 serverConnectionHandlerID) override { + } + + void onFileTransferStatusEvent(anyID transferID, unsigned status, const char *statusMessage, uint64 remotefileSize, + uint64 serverConnectionHandlerID) override { + } + + void onClientChatClosedEvent(uint64 serverConnectionHandlerID, anyID clientID, + const char *clientUniqueIdentity) override { + } + + void onClientChatComposingEvent(uint64 serverConnectionHandlerID, anyID clientID, + const char *clientUniqueIdentity) override { + } + + void onServerLogEvent(uint64 serverConnectionHandlerID, const char *logMsg) override { + } + + void onServerLogFinishedEvent(uint64 serverConnectionHandlerID, uint64 lastPos, uint64 fileSize) override { + } + + void onMessageListEvent(uint64 serverConnectionHandlerID, uint64 messageID, const char *fromClientUniqueIdentity, + const char *subject, uint64 timestamp, int flagRead) override { + } + + void onMessageGetEvent(uint64 serverConnectionHandlerID, uint64 messageID, const char *fromClientUniqueIdentity, + const char *subject, const char *message, uint64 timestamp) override { + } + + void onClientDBIDfromUIDEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, + uint64 clientDatabaseID) override { + } + + void onClientNamefromUIDEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, + uint64 clientDatabaseID, const char *clientNickName) override { + } + + void onClientNamefromDBIDEvent(uint64 serverConnectionHandlerID, const char *uniqueClientIdentifier, + uint64 clientDatabaseID, const char *clientNickName) override { + } + + void onComplainListEvent(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, + const char *targetClientNickName, uint64 fromClientDatabaseID, + const char *fromClientNickName, + const char *complainReason, uint64 timestamp) override { + } + + void onBanListEvent(uint64 serverConnectionHandlerID, uint64 banid, const char *ip, const char *name, const char *uid, + const char *mytsid, uint64 creationTime, uint64 durationTime, const char *invokerName, + uint64 invokercldbid, + const char *invokeruid, const char *reason, int numberOfEnforcements, + const char *lastNickName) override { + } + + void onClientServerQueryLoginPasswordEvent(uint64 serverConnectionHandlerID, const char *loginPassword) override { + } + + void onPluginCommandEvent(uint64 serverConnectionHandlerID, const char *pluginName, const char *pluginCommand, + anyID invokerClientID, const char *invokerName, + const char *invokerUniqueIdentity) override { + } + + void onIncomingClientQueryEvent(uint64 serverConnectionHandlerID, const char *commandText) override { + } + + void onServerTemporaryPasswordListEvent(uint64 serverConnectionHandlerID, const char *clientNickname, + const char *uniqueClientIdentifier, const char *description, + const char *password, uint64 timestampStart, + uint64 timestampEnd, uint64 targetChannelID, + const char *targetChannelPW) override { + } + + void onAvatarUpdated(uint64 serverConnectionHandlerID, anyID clientID, const char *avatarPath) override { + } + + void onMenuItemEvent(uint64 serverConnectionHandlerID, PluginMenuType type, int menuItemID, + uint64 selectedItemID) override { + } + + void onHotkeyEvent(const char *keyword) override { + } + + void onHotkeyRecordedEvent(const char *keyword, const char *key) override { + } + + void onClientDisplayNameChanged(uint64 serverConnectionHandlerID, anyID clientID, const char *displayName, + const char *uniqueClientIdentifier) override { + } +}; + +extern "C" { + IEchoionPlugin *CreatePlugin(const TS3Functions* funcs) { + return new EchoionCore(std::make_shared(*funcs)); +} + + void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; } +} diff --git a/include/Core/PluginDefinitions.hpp b/include/Core/PluginDefinitions.hpp new file mode 100644 index 0000000..df5ed41 --- /dev/null +++ b/include/Core/PluginDefinitions.hpp @@ -0,0 +1,76 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace definitions { + + + struct StreamInfo { + std::string url; + int itag = 0; + std::string mimeType; + int bitrate = 0; + int width = 0; + int height = 0; + }; + + struct Streams { + StreamInfo audio; + StreamInfo video; + }; + + struct QueueItem { + std::string name; + std::string videoId; + std::string requester; + std::optional streams; + + QueueItem() = default; + + QueueItem(std::string name, std::string videoId, std::string requested_by, const std::optional & streams) + : name{std::move(name)}, videoId(std::move(videoId)), requester{std::move(requested_by)}, streams{streams} {} + }; + + + + struct SearchResultItem { + std::string name; + std::string length; + std::string thumbnail; + std::string viewCount; + std::string url; + std::string videoId; + }; + + struct PluginState { + std::vector queue; + std::vector onlineSubscribers; + std::vector offlineSubscribers; + std::uint64_t serverConnection; + bool wasPlaying = false; + }; +} + +template <> struct glz::meta { + using T = definitions::StreamInfo; + static constexpr auto value = + object("url", &T::url, "itag", &T::itag, "mimeType", &T::mimeType, + "bitrate", &T::bitrate, "width", &T::width, "height", &T::height); +}; + +template <> struct glz::meta { + using T = definitions::Streams; + static constexpr auto value = + object("audio", &T::audio, "video", &T::video); +}; + +template <> struct glz::meta { + using T = definitions::QueueItem; + static constexpr auto value = + object("name", &T::name, "videoId", &T::videoId, "requester", &T::requester, + "streams", &T::streams); +}; \ No newline at end of file diff --git a/include/Core/Spotify/Client.hpp b/include/Core/Spotify/Client.hpp new file mode 100644 index 0000000..53d3cff --- /dev/null +++ b/include/Core/Spotify/Client.hpp @@ -0,0 +1,332 @@ +#pragma once +#include "Spotify/RequestParams.hpp" +#include "Spotify/Types/Album.hpp" +#include "Spotify/Types/Artist.hpp" +#include "Spotify/Types/Common.hpp" +#include "Spotify/Types/Other.hpp" +#include "Spotify/Types/Player.hpp" +#include "Spotify/Types/Playlist.hpp" +#include "Spotify/Types/Track.hpp" +#include "Spotify/Types/User.hpp" +#include "ts6bot/Proxy.hpp" +#include +#include +#include +#include + +namespace Spotify { + +// ============================================================================ +// Error Handling +// ============================================================================ + +struct ApiError { + int status; + std::string message; + std::string reason; + + auto GetStatus() const -> int { return status; } + auto GetMessage() const -> const std::string & { return message; } +}; + +template using Result = std::expected; + +// ============================================================================ +// HTTP Client Implementation Details +// ============================================================================ + +struct CurlDeleter { + void operator()(CURL *ptr) const { + if (ptr) + curl_easy_cleanup(ptr); + } +}; + +enum class HttpMethod { GET, POST, PUT, DELETE }; + +// ============================================================================ +// Main Spotify Client +// ============================================================================ + +class Client { +public: + Client(std::string accessToken); + ~Client() = default; + + // Configuration + void SetVerbose(bool verbose) { m_Verbose = verbose; } + void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); } + void SetAccessToken(std::string token) { m_AccessToken = std::move(token); } + + // ======================================================================== + // Albums API + // ======================================================================== + + auto GetAlbum(const std::string &id, std::optional market = {}) + -> Result; + + auto GetAlbums(const std::vector &ids, + std::optional market = {}) + -> Result>; + + auto GetAlbumTracks(const std::string &id, + const Request::AlbumTracksParams ¶ms = {}) + -> Result>; + + auto GetSavedAlbums(const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto SaveAlbums(const std::vector &ids) -> Result; + + auto RemoveSavedAlbums(const std::vector &ids) -> Result; + + auto CheckSavedAlbums(const std::vector &ids) + -> Result>; + + auto GetNewReleases(const Request::PaginationParams ¶ms = {}) + -> Result>; + + // ======================================================================== + // Artists API + // ======================================================================== + + auto GetArtist(const std::string &id) -> Result; + + auto GetArtists(const std::vector &ids) + -> Result>; + + auto GetArtistAlbums(const std::string &id, + const Request::ArtistAlbumsParams ¶ms = {}) + -> Result>; + + auto GetArtistTopTracks(const std::string &id, const std::string &market) + -> Result>; + + auto GetArtistRelatedArtists(const std::string &id) + -> Result>; + + // ======================================================================== + // Tracks API + // ======================================================================== + + auto GetTrack(const std::string &id, std::optional market = {}) + -> Result; + + auto GetTracks(const std::vector &ids, + std::optional market = {}) + -> Result>; + + auto GetSavedTracks(const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto SaveTracks(const std::vector &ids) -> Result; + + auto RemoveSavedTracks(const std::vector &ids) -> Result; + + auto CheckSavedTracks(const std::vector &ids) + -> Result>; + + auto GetAudioFeatures(const std::string &id) -> Result; + + auto GetAudioFeaturesForTracks(const std::vector &ids) + -> Result>; + + auto GetAudioAnalysis(const std::string &id) -> Result; + + auto GetRecommendations(const Request::RecommendationParams ¶ms) + -> Result; + + // ======================================================================== + // Search API + // ======================================================================== + + auto Search(const Request::SearchParams ¶ms) -> Result; + + auto SearchTracks(const Request::TrackSearchFilters &filters, + const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto SearchAlbums(const Request::AlbumSearchFilters &filters, + const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto SearchArtists(const Request::ArtistSearchFilters &filters, + const Request::PaginationParams ¶ms = {}) + -> Result>; + + // ======================================================================== + // Playlists API + // ======================================================================== + + auto GetPlaylist(const std::string &id, + std::optional market = {}) -> Result; + + auto GetPlaylistTracks(const std::string &id, + const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto CreatePlaylist(const std::string &user_id, + const Request::CreatePlaylistParams ¶ms) + -> Result; + + auto UpdatePlaylist(const std::string &id, + const Request::UpdatePlaylistParams ¶ms) + -> Result; + + auto AddTracksToPlaylist(const std::string &id, + const Request::AddTracksToPlaylistParams ¶ms) + -> Result; + + auto RemoveTracksFromPlaylist( + const std::string &id, + const Request::RemoveTracksFromPlaylistParams ¶ms) + -> Result; + + auto ReorderPlaylistTracks(const std::string &id, + const Request::ReorderPlaylistParams ¶ms) + -> Result; + + auto ReplacePlaylistTracks(const std::string &id, + const Request::ReplacePlaylistTracksParams ¶ms) + -> Result; + + auto GetCurrentUserPlaylists(const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto GetUserPlaylists(const std::string &user_id, + const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto GetFeaturedPlaylists(const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto GetCategoryPlaylists(const std::string &category_id, + const Request::PaginationParams ¶ms = {}) + -> Result>; + + // ======================================================================== + // User API + // ======================================================================== + + auto GetCurrentUser() -> Result; + + auto GetUser(const std::string &user_id) -> Result; + + auto GetTopArtists(const Request::TopItemsParams ¶ms = {}) + -> Result>; + + auto GetTopTracks(const Request::TopItemsParams ¶ms = {}) + -> Result>; + + // ======================================================================== + // Follow API + // ======================================================================== + + auto FollowArtistsOrUsers(const Request::FollowParams ¶ms) + -> Result; + + auto UnfollowArtistsOrUsers(const Request::UnfollowParams ¶ms) + -> Result; + + auto CheckFollowingArtistsOrUsers(const Request::CheckFollowingParams ¶ms) + -> Result>; + + auto GetFollowedArtists(std::optional limit = {}, + std::optional after = {}) + -> Result>; + + auto FollowPlaylist(const std::string &playlist_id, + const Request::FollowPlaylistParams ¶ms = {}) + -> Result; + + auto UnfollowPlaylist(const std::string &playlist_id) -> Result; + + auto CheckFollowingPlaylist(const std::string &playlist_id, + const std::vector &user_ids) + -> Result>; + + // ======================================================================== + // Player API + // ======================================================================== + + auto GetPlaybackState(std::optional market = {}) + -> Result; + + auto GetAvailableDevices() -> Result>; + + auto GetCurrentlyPlayingTrack(std::optional market = {}) + -> Result; + + auto StartOrResumePlayback(const Request::PlayParams ¶ms, + std::optional device_id = {}) + -> Result; + + auto PausePlayback(std::optional device_id = {}) -> Result; + + auto SkipToNext(std::optional device_id = {}) -> Result; + + auto SkipToPrevious(std::optional device_id = {}) + -> Result; + + auto SeekToPosition(int position_ms, + std::optional device_id = {}) + -> Result; + + auto SetRepeatMode(RepeatMode mode, std::optional device_id = {}) + -> Result; + + auto SetPlaybackVolume(int volume_percent, + std::optional device_id = {}) + -> Result; + + auto TogglePlaybackShuffle(bool state, + std::optional device_id = {}) + -> Result; + + auto TransferPlayback(const Request::TransferPlaybackParams ¶ms) + -> Result; + + auto AddToQueue(const Request::QueueParams ¶ms) -> Result; + + auto GetRecentlyPlayedTracks(std::optional limit = {}, + std::optional after = {}, + std::optional before = {}) + -> Result>; + + // ======================================================================== + // Browse API + // ======================================================================== + + auto GetCategories(const Request::PaginationParams ¶ms = {}) + -> Result>; + + auto GetCategory(const std::string &category_id, + std::optional locale = {}) -> Result; + + auto GetAvailableGenreSeeds() -> Result>; + + auto GetAvailableMarkets() -> Result>; + +private: + std::string m_AccessToken; + ProxyConfig m_Proxy; + bool m_Verbose = false; + + auto PerformRequest(const std::string &url, + HttpMethod method = HttpMethod::GET, + const std::string &body = "", + const std::vector &extra_headers = {}) + -> Result; + + static auto WriteCallback(void *contents, size_t size, size_t nmemb, + std::string *out) -> size_t; + + auto BuildUrl(const std::string &endpoint, + const std::map ¶ms = {}) const + -> std::string; + auto BuildUrl(const std::string &endpoint, + const Request::RequestParams ¶ms) const -> std::string; + auto UrlEncode(const std::string &value) const -> std::string; +}; + +} // namespace Spotify diff --git a/include/Core/Spotify/HttpCallbackServer.hpp b/include/Core/Spotify/HttpCallbackServer.hpp new file mode 100644 index 0000000..2c58511 --- /dev/null +++ b/include/Core/Spotify/HttpCallbackServer.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include + +namespace Spotify { + +struct CallbackResult { + std::string code; + std::string state; + std::string error; +}; + +class HttpCallbackServer { +public: + HttpCallbackServer(std::string host, uint16_t port, std::string path); + + // Wait for one callback request or timeout. Returns std::nullopt on timeout. + std::optional WaitForCallback(std::chrono::milliseconds timeout); + +private: + std::string m_Host; + uint16_t m_Port; + std::string m_Path; +}; + +} // namespace ts6bot diff --git a/include/Core/Spotify/PkceAuth.hpp b/include/Core/Spotify/PkceAuth.hpp new file mode 100644 index 0000000..0d8428c --- /dev/null +++ b/include/Core/Spotify/PkceAuth.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#include // for ProxyConfig + CurlDeleter + ProxyType + +namespace Spotify { + +struct TokenSet { + std::string access_token; + std::string token_type; + std::string scope; + std::string refresh_token; + std::int64_t expires_at_utc{}; // unix seconds + + bool IsExpired(std::chrono::seconds skew = std::chrono::seconds{60}) const; +}; + +class PkceAuth { +public: + PkceAuth(std::string clientId, std::string redirectUri, std::filesystem::path tokenCachePath); + + void SetProxy(ProxyConfig p) { m_Proxy = std::move(p); } + void SetVerbose(bool v) { m_Verbose = v; } + + // One-time interactive step: prints URL and waits for redirect; stores refresh token. + void AuthorizeAndStore(const std::vector& scopes, + std::chrono::milliseconds timeout = std::chrono::minutes(5)); + + // Headless: load from cache and refresh if needed. + TokenSet LoadOrRefresh(); + +private: + std::string m_ClientId; + std::string m_RedirectUri; + std::filesystem::path m_TokenCachePath; + ProxyConfig m_Proxy; + bool m_Verbose = false; + + TokenSet ExchangeCodeForToken(const std::string& code, const std::string& codeVerifier); + TokenSet RefreshAccessToken(const TokenSet& current); + + void Save(const TokenSet& t) const; + std::optional Load() const; + + static std::int64_t NowUnixSeconds(); + friend TokenSet; +}; + +} // namespace ts6bot diff --git a/include/Core/Spotify/RequestParams.hpp b/include/Core/Spotify/RequestParams.hpp new file mode 100644 index 0000000..8345163 --- /dev/null +++ b/include/Core/Spotify/RequestParams.hpp @@ -0,0 +1,496 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace Spotify::Request { + +// ============================================================================ +// Base Request Parameter Class +// ============================================================================ + +class RequestParams { +public: + virtual ~RequestParams() = default; + virtual auto ToQueryParams() const -> std::map = 0; +}; + +// ============================================================================ +// Search Type Enum +// ============================================================================ + +enum class SearchType { + Album, + Artist, + Playlist, + Track, + Show, + Episode, + Audiobook +}; + +inline auto SearchTypeToString(SearchType type) -> std::string { + switch (type) { + case SearchType::Album: return "album"; + case SearchType::Artist: return "artist"; + case SearchType::Playlist: return "playlist"; + case SearchType::Track: return "track"; + case SearchType::Show: return "show"; + case SearchType::Episode: return "episode"; + case SearchType::Audiobook: return "audiobook"; + } + return ""; +} + +// ============================================================================ +// Time Range Enum +// ============================================================================ + +enum class TimeRange { + LongTerm, + MediumTerm, + ShortTerm +}; + +inline auto TimeRangeToString(TimeRange range) -> std::string { + switch (range) { + case TimeRange::LongTerm: return "long_term"; + case TimeRange::MediumTerm: return "medium_term"; + case TimeRange::ShortTerm: return "short_term"; + } + return "medium_term"; +} + +// ============================================================================ +// Pagination Parameters +// ============================================================================ + +struct PaginationParams : public RequestParams { +public: + std::optional limit = 20; + std::optional offset = 0; + std::optional market; + + auto ToQueryParams() const -> std::map override { + std::map params; + if (limit) params["limit"] = std::to_string(*limit); + if (offset) params["offset"] = std::to_string(*offset); + if (market) params["market"] = *market; + return params; + } +}; + +// ============================================================================ +// Search Parameters +// ============================================================================ + +struct SearchParams : public RequestParams { +public: + //You can narrow down your search using field filters. The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types. + //The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960). + //The album filter can be used while searching albums and tracks. + //The genre filter can be used while searching artists and tracks. + //The isrc and track filters can be used while searching tracks. + //The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity. + //Example: q=remaster%2520track%3ADoxy%2520artist%3AMiles%2520Davis + std::string query; + std::vector types; + std::optional market; + std::optional limit = 20; + std::optional offset = 0; + std::optional include_external; + + auto ToQueryParams() const -> std::map override { + std::map params; + params["q"] = query; + + std::vector type_strings; + for (const auto& type : types) { + type_strings.push_back(SearchTypeToString(type)); + } + params["type"] = std::views::join_with(type_strings, ',') | std::ranges::to(); + + if (market) params["market"] = *market; + if (limit) params["limit"] = std::to_string(*limit); + if (offset) params["offset"] = std::to_string(*offset); + if (include_external) params["include_external"] = *include_external ? "audio" : ""; + + return params; + } +}; + +// ============================================================================ +// Track Search Filters +// ============================================================================ + +struct TrackSearchFilters : public RequestParams { +public: + std::optional track; + std::optional artist; + std::optional album; + std::optional year; + std::optional genre; + std::optional isrc; + std::optional upc; + std::optional is_new; + std::optional hipster; + + auto ToQueryString() const -> std::string { + std::vector parts; + + if (track) parts.push_back(std::format("track:{}", *track)); + if (artist) parts.push_back(std::format("artist:{}", *artist)); + if (album) parts.push_back(std::format("album:{}", *album)); + if (year) parts.push_back(std::format("year:{}", *year)); + if (genre) parts.push_back(std::format("genre:{}", *genre)); + if (isrc) parts.push_back(std::format("isrc:{}", *isrc)); + if (upc) parts.push_back(std::format("upc:{}", *upc)); + if (is_new && *is_new) parts.push_back("tag:new"); + if (hipster && *hipster) parts.push_back("tag:hipster"); + + return std::views::join_with(parts, ' ') | std::ranges::to(); + } + + auto ToQueryParams() const -> std::map override { + return {}; + } +}; + +// ============================================================================ +// Album Search Filters +// ============================================================================ + +struct AlbumSearchFilters : public RequestParams { +public: + std::optional album; + std::optional artist; + std::optional year; + std::optional genre; + std::optional upc; + + auto ToQueryString() const -> std::string { + std::vector parts; + + if (album) parts.push_back(std::format("album:{}", *album)); + if (artist) parts.push_back(std::format("artist:{}", *artist)); + if (year) parts.push_back(std::format("year:{}", *year)); + if (genre) parts.push_back(std::format("genre:{}", *genre)); + if (upc) parts.push_back(std::format("upc:{}", *upc)); + + return std::views::join_with(parts, ' ') | std::ranges::to(); + } + + auto ToQueryParams() const -> std::map override { + return {}; + } +}; + +// ============================================================================ +// Artist Search Filters +// ============================================================================ + +struct ArtistSearchFilters : public RequestParams { +public: + std::optional artist; + std::optional genre; + + auto ToQueryString() const -> std::string { + std::vector parts; + + if (artist) parts.push_back(std::format("artist:{}", *artist)); + if (genre) parts.push_back(std::format("genre:{}", *genre)); + + return std::views::join_with(parts, ' ') | std::ranges::to(); + } + + auto ToQueryParams() const -> std::map override { + return {}; + } +}; + +// ============================================================================ +// Album Tracks Parameters +// ============================================================================ + +struct AlbumTracksParams : public RequestParams { +public: + std::optional limit = 20; + std::optional offset = 0; + std::optional market; + + auto ToQueryParams() const -> std::map override { + std::map params; + if (limit) params["limit"] = std::to_string(*limit); + if (offset) params["offset"] = std::to_string(*offset); + if (market) params["market"] = *market; + return params; + } +}; + +// ============================================================================ +// Artist Albums Parameters +// ============================================================================ + +struct ArtistAlbumsParams : public RequestParams { +public: + std::optional> include_groups; + std::optional market; + std::optional limit = 20; + std::optional offset = 0; + + auto ToQueryParams() const -> std::map override { + std::map params; + + if (include_groups && !include_groups->empty()) { + params["include_groups"] = std::views::join_with(*include_groups, ',') | std::ranges::to(); + } + if (market) params["market"] = *market; + if (limit) params["limit"] = std::to_string(*limit); + if (offset) params["offset"] = std::to_string(*offset); + + return params; + } +}; + +// ============================================================================ +// Top Items Parameters +// ============================================================================ + +struct TopItemsParams : public RequestParams { +public: + std::optional time_range = TimeRange::MediumTerm; + std::optional limit = 20; + std::optional offset = 0; + + auto ToQueryParams() const -> std::map override { + std::map params; + + if (time_range) params["time_range"] = TimeRangeToString(*time_range); + if (limit) params["limit"] = std::to_string(*limit); + if (offset) params["offset"] = std::to_string(*offset); + + return params; + } +}; + +// ============================================================================ +// Recommendation Parameters +// ============================================================================ + +struct RecommendationParams : public RequestParams { +public: + std::optional> seed_artists; + std::optional> seed_genres; + std::optional> seed_tracks; + std::optional limit = 20; + std::optional market; + + // Tunable attributes + std::optional min_acousticness; + std::optional max_acousticness; + std::optional target_acousticness; + + std::optional min_danceability; + std::optional max_danceability; + std::optional target_danceability; + + std::optional min_duration_ms; + std::optional max_duration_ms; + std::optional target_duration_ms; + + std::optional min_energy; + std::optional max_energy; + std::optional target_energy; + + std::optional min_instrumentalness; + std::optional max_instrumentalness; + std::optional target_instrumentalness; + + std::optional min_key; + std::optional max_key; + std::optional target_key; + + std::optional min_liveness; + std::optional max_liveness; + std::optional target_liveness; + + std::optional min_loudness; + std::optional max_loudness; + std::optional target_loudness; + + std::optional min_mode; + std::optional max_mode; + std::optional target_mode; + + std::optional min_popularity; + std::optional max_popularity; + std::optional target_popularity; + + std::optional min_speechiness; + std::optional max_speechiness; + std::optional target_speechiness; + + std::optional min_tempo; + std::optional max_tempo; + std::optional target_tempo; + + std::optional min_time_signature; + std::optional max_time_signature; + std::optional target_time_signature; + + std::optional min_valence; + std::optional max_valence; + std::optional target_valence; + + auto ToQueryParams() const -> std::map override { + std::map params; + + if (seed_artists && !seed_artists->empty()) { + params["seed_artists"] = std::views::join_with(*seed_artists, ',') | std::ranges::to(); + } + if (seed_genres && !seed_genres->empty()) { + params["seed_genres"] = std::views::join_with(*seed_genres, ',') | std::ranges::to(); + } + if (seed_tracks && !seed_tracks->empty()) { + params["seed_tracks"] = std::views::join_with(*seed_tracks, ',') | std::ranges::to(); + } + + if (limit) params["limit"] = std::to_string(*limit); + if (market) params["market"] = *market; + + // Add all tunable attributes + if (min_acousticness) params["min_acousticness"] = std::to_string(*min_acousticness); + if (max_acousticness) params["max_acousticness"] = std::to_string(*max_acousticness); + if (target_acousticness) params["target_acousticness"] = std::to_string(*target_acousticness); + + if (min_danceability) params["min_danceability"] = std::to_string(*min_danceability); + if (max_danceability) params["max_danceability"] = std::to_string(*max_danceability); + if (target_danceability) params["target_danceability"] = std::to_string(*target_danceability); + + if (min_energy) params["min_energy"] = std::to_string(*min_energy); + if (max_energy) params["max_energy"] = std::to_string(*max_energy); + if (target_energy) params["target_energy"] = std::to_string(*target_energy); + + if (min_popularity) params["min_popularity"] = std::to_string(*min_popularity); + if (max_popularity) params["max_popularity"] = std::to_string(*max_popularity); + if (target_popularity) params["target_popularity"] = std::to_string(*target_popularity); + + // Add remaining attributes as needed... + + return params; + } +}; + +// ============================================================================ +// Create Playlist Parameters +// ============================================================================ + +struct CreatePlaylistParams { + std::string name; + std::optional public_playlist = true; + std::optional collaborative = false; + std::optional description; +}; + +// ============================================================================ +// Update Playlist Parameters +// ============================================================================ + +struct UpdatePlaylistParams { + std::optional name; + std::optional public_playlist; + std::optional collaborative; + std::optional description; +}; + +// ============================================================================ +// Playlist Track Operations +// ============================================================================ + +struct AddTracksToPlaylistParams { + std::vector uris; + std::optional position; +}; + +struct RemoveTracksFromPlaylistParams { + std::vector uris; + std::optional snapshot_id; +}; + +struct ReorderPlaylistParams { + int range_start; + int insert_before; + std::optional range_length = 1; + std::optional snapshot_id; +}; + +struct ReplacePlaylistTracksParams { + std::vector uris; +}; + +// ============================================================================ +// Playback Control Parameters +// ============================================================================ + +struct PlayParams { + std::optional context_uri; + std::optional> uris; + std::optional> offset; + std::optional position_ms; +}; + +struct TransferPlaybackParams { + std::vector device_ids; + std::optional play; +}; + +struct QueueParams { + std::string uri; + std::optional device_id; +}; +struct RequestBody { + std::vector ids; +}; + +// ============================================================================ +// Follow Parameters +// ============================================================================ + struct ErrorResponse { + struct Error { + int status; + std::string message; + } error; + }; +enum class FollowType { + Artist, + User +}; + +inline auto FollowTypeToString(FollowType type) -> std::string { + return type == FollowType::Artist ? "artist" : "user"; +} + +struct FollowParams { + FollowType type; + std::vector ids; +}; + +struct UnfollowParams { + FollowType type; + std::vector ids; +}; + +struct CheckFollowingParams { + FollowType type; + std::vector ids; +}; + +struct FollowPlaylistParams { + std::optional public_playlist = true; +}; + +} // namespace Spotify::Request \ No newline at end of file diff --git a/include/Core/Spotify/Types/Album.hpp b/include/Core/Spotify/Types/Album.hpp new file mode 100644 index 0000000..af64923 --- /dev/null +++ b/include/Core/Spotify/Types/Album.hpp @@ -0,0 +1,178 @@ +#pragma once +#include "Spotify/Types/Common.hpp" +#include "Spotify/Types/Artist.hpp" + +namespace Spotify { + +// ============================================================================ +// Album Group Enum +// ============================================================================ + +enum class AlbumGroup { + Album, + Single, + AppearsOn, + Compilation +}; + +inline auto AlbumGroupToString(AlbumGroup group) -> std::string { + switch (group) { + case AlbumGroup::Album: return "album"; + case AlbumGroup::Single: return "single"; + case AlbumGroup::AppearsOn: return "appears_on"; + case AlbumGroup::Compilation: return "compilation"; + } + return ""; +} + +// ============================================================================ +// Album Base +// ============================================================================ + +class AlbumBase { +public: + std::string album_type; + int total_tracks; + std::vector available_markets; + ExternalUrls external_urls; + std::string href; + std::string id; + std::vector images; + std::string name; + std::string release_date; + std::string release_date_precision; + std::optional restrictions; + std::string type; + std::string uri; + std::vector artists; + bool is_playable; + + virtual ~AlbumBase() = default; + + auto GetId() const -> const std::string& { return id; } + auto GetName() const -> const std::string& { return name; } + auto GetUri() const -> const std::string& { return uri; } + auto GetReleaseDate() const -> const std::string& { return release_date; } + auto GetTotalTracks() const -> int { return total_tracks; } + + auto GetAlbumType() const -> AlbumType { + if (album_type == "album") return AlbumType::Album; + if (album_type == "single") return AlbumType::Single; + return AlbumType::Compilation; + } + + auto GetReleaseDatePrecision() const -> ReleaseDatePrecision { + if (release_date_precision == "year") return ReleaseDatePrecision::Year; + if (release_date_precision == "month") return ReleaseDatePrecision::Month; + return ReleaseDatePrecision::Day; + } +}; + +// ============================================================================ +// Simplified Album +// ============================================================================ + +struct SimplifiedAlbum : AlbumBase { +}; + +// ============================================================================ +// Full Album +// ============================================================================ + +struct Album : AlbumBase { + std::vector copyrights; + ExternalIds external_ids; + std::vector genres; + std::string label; + int popularity; + + auto GetPopularity() const -> int { return popularity; } + auto GetLabel() const -> const std::string& { return label; } + auto GetGenres() const -> const std::vector& { return genres; } +}; + +// ============================================================================ +// Saved Album +// ============================================================================ + +struct SavedAlbum { + std::string added_at; + Album album; + + auto GetAlbum() const -> const Album& { return album; } + auto GetAddedAt() const -> const std::string& { return added_at; } +}; + +struct AlbumsResponse { + std::vector albums; + }; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::SimplifiedAlbum; + static constexpr auto value = object( + "album_type", &T::album_type, + "total_tracks", &T::total_tracks, + "available_markets", &T::available_markets, + "external_urls", &T::external_urls, + "href", &T::href, + "id", &T::id, + "images", &T::images, + "name", &T::name, + "release_date", &T::release_date, + "release_date_precision", &T::release_date_precision, + "restrictions", &T::restrictions, + "type", &T::type, + "uri", &T::uri, + "artists", &T::artists, + "is_playable", &T::is_playable + ); +}; + +template <> +struct glz::meta { + using T = Spotify::AlbumsResponse; + static constexpr auto value = object( + "albums", &T::albums + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Album; + static constexpr auto value = object( + "album_type", &T::album_type, + "total_tracks", &T::total_tracks, + "available_markets", &T::available_markets, + "external_urls", &T::external_urls, + "href", &T::href, + "id", &T::id, + "images", &T::images, + "name", &T::name, + "release_date", &T::release_date, + "release_date_precision", &T::release_date_precision, + "restrictions", &T::restrictions, + "type", &T::type, + "uri", &T::uri, + "artists", &T::artists, + "copyrights", &T::copyrights, + "external_ids", &T::external_ids, + "genres", &T::genres, + "label", &T::label, + "popularity", &T::popularity + ); +}; + +template <> +struct glz::meta { + using T = Spotify::SavedAlbum; + static constexpr auto value = object( + "added_at", &T::added_at, + "album", &T::album + ); +}; diff --git a/include/Core/Spotify/Types/Artist.hpp b/include/Core/Spotify/Types/Artist.hpp new file mode 100644 index 0000000..1c7ca79 --- /dev/null +++ b/include/Core/Spotify/Types/Artist.hpp @@ -0,0 +1,84 @@ +#pragma once +#include "Spotify/Types/Common.hpp" + +namespace Spotify { + +// ============================================================================ +// Artist Base +// ============================================================================ + +class ArtistBase { +public: + ExternalUrls external_urls; + std::string href; + std::string id; + std::string name; + std::string type; + std::string uri; + + virtual ~ArtistBase() = default; + + auto GetId() const -> const std::string& { return id; } + auto GetName() const -> const std::string& { return name; } + auto GetUri() const -> const std::string& { return uri; } +}; + +// ============================================================================ +// Simplified Artist +// ============================================================================ + +struct SimplifiedArtist : ArtistBase { +}; + +// ============================================================================ +// Full Artist +// ============================================================================ + +struct Artist : ArtistBase { + Followers followers; + std::vector genres; + std::vector images; + int popularity; + + auto GetPopularity() const -> int { return popularity; } + auto GetGenres() const -> const std::vector& { return genres; } +}; + +struct ArtistsResponse { + std::vector artists; + }; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::SimplifiedArtist; + static constexpr auto value = object( + "external_urls", &T::external_urls, + "href", &T::href, + "id", &T::id, + "name", &T::name, + "type", &T::type, + "uri", &T::uri + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Artist; + static constexpr auto value = object( + "external_urls", &T::external_urls, + "followers", &T::followers, + "genres", &T::genres, + "href", &T::href, + "id", &T::id, + "images", &T::images, + "name", &T::name, + "popularity", &T::popularity, + "type", &T::type, + "uri", &T::uri + ); +}; diff --git a/include/Core/Spotify/Types/Common.hpp b/include/Core/Spotify/Types/Common.hpp new file mode 100644 index 0000000..8931705 --- /dev/null +++ b/include/Core/Spotify/Types/Common.hpp @@ -0,0 +1,185 @@ +#pragma once +#include +#include +#include +#include + +namespace Spotify { + +// ============================================================================ +// Common Enums +// ============================================================================ + +enum class AlbumType { + Album, + Single, + Compilation +}; + +enum class ReleaseDatePrecision { + Year, + Month, + Day +}; + +enum class CopyrightType { + Copyright, // "C" + Performance // "P" +}; + +enum class RestrictionReason { + Market, + Product, + Explicit +}; + +// ============================================================================ +// Core Structures +// ============================================================================ + +struct Image { + std::string url; + std::optional height; + std::optional width; +}; + +struct ExternalUrls { + std::string spotify; +}; + +struct ExternalIds { + std::optional isrc; + std::optional ean; + std::optional upc; +}; + +struct Followers { + std::optional href; + int total; +}; + +struct Copyright { + std::string text; + std::string type; + + auto GetType() const -> CopyrightType { + return type == "C" ? CopyrightType::Copyright : CopyrightType::Performance; + } +}; + +struct Restrictions { + std::string reason; + + auto GetReason() const -> RestrictionReason { + if (reason == "market") return RestrictionReason::Market; + if (reason == "product") return RestrictionReason::Product; + return RestrictionReason::Explicit; + } +}; + +// ============================================================================ +// Paging Objects +// ============================================================================ + +template +struct PagingObject { + std::string href; + int limit; + std::optional next; + int offset; + std::optional previous; + int total; + std::vector items; +}; + +template +struct CursorPagingObject { + std::string href; + int limit; + std::optional next; + std::optional cursors; + int total; + std::vector items; +}; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata for Common Types +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::Image; + static constexpr auto value = object( + "url", &T::url, + "height", &T::height, + "width", &T::width + ); +}; + +template <> +struct glz::meta { + using T = Spotify::ExternalUrls; + static constexpr auto value = object("spotify", &T::spotify); +}; + +template <> +struct glz::meta { + using T = Spotify::ExternalIds; + static constexpr auto value = object( + "isrc", &T::isrc, + "ean", &T::ean, + "upc", &T::upc + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Followers; + static constexpr auto value = object( + "href", &T::href, + "total", &T::total + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Copyright; + static constexpr auto value = object( + "text", &T::text, + "type", &T::type + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Restrictions; + static constexpr auto value = object("reason", &T::reason); +}; + +template +struct glz::meta> { + using Type = Spotify::PagingObject; + static constexpr auto value = object( + "href", &Type::href, + "limit", &Type::limit, + "next", &Type::next, + "offset", &Type::offset, + "previous", &Type::previous, + "total", &Type::total, + "items", &Type::items + ); +}; + +template +struct glz::meta> { + using Type = Spotify::CursorPagingObject; + static constexpr auto value = object( + "href", &Type::href, + "limit", &Type::limit, + "next", &Type::next, + "cursors", &Type::cursors, + "total", &Type::total, + "items", &Type::items + ); +}; diff --git a/include/Core/Spotify/Types/Other.hpp b/include/Core/Spotify/Types/Other.hpp new file mode 100644 index 0000000..6346a7f --- /dev/null +++ b/include/Core/Spotify/Types/Other.hpp @@ -0,0 +1,133 @@ +#pragma once +#include "Spotify/Types/Common.hpp" +#include "Spotify/Types/Track.hpp" +#include "Spotify/Types/Artist.hpp" +#include "Spotify/Types/Album.hpp" +#include "Spotify/Types/Playlist.hpp" +#include +#include +#include + +namespace Spotify { + +// ============================================================================ +// Category +// ============================================================================ + +struct Category { + std::string href; + std::vector icons; + std::string id; + std::string name; + + auto GetId() const -> const std::string& { return id; } + auto GetName() const -> const std::string& { return name; } +}; + +// ============================================================================ +// Recommendation Seed +// ============================================================================ + +enum class SeedType { + Artist, + Track, + Genre +}; + +inline auto StringToSeedType(const std::string& str) -> SeedType { + if (str == "ARTIST") return SeedType::Artist; + if (str == "TRACK") return SeedType::Track; + return SeedType::Genre; +} + +struct RecommendationSeed { + int afterFilteringSize; + int afterRelinkingSize; + std::optional href; + std::string id; + int initialPoolSize; + std::string type; + + auto GetId() const -> const std::string& { return id; } + auto GetSeedType() const -> SeedType { + return StringToSeedType(type); + } +}; + +// ============================================================================ +// Recommendations Response +// ============================================================================ + +struct Recommendations { + std::vector seeds; + std::vector tracks; + + auto GetTracks() const -> const std::vector& { return tracks; } + auto GetSeeds() const -> const std::vector& { return seeds; } +}; + +// ============================================================================ +// Search Results +// ============================================================================ + +struct SearchResults { + std::optional> tracks; + std::optional> artists; + std::optional> albums; + std::optional> playlists; + + auto GetTracks() const -> const std::optional>& { return tracks; } + auto GetArtists() const -> const std::optional>& { return artists; } + auto GetAlbums() const -> const std::optional>& { return albums; } + auto GetPlaylists() const -> const std::optional>& { return playlists; } +}; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::Category; + static constexpr auto value = object( + "href", &T::href, + "icons", &T::icons, + "id", &T::id, + "name", &T::name + ); +}; + +template <> +struct glz::meta { + using T = Spotify::RecommendationSeed; + static constexpr auto value = object( + "afterFilteringSize", &T::afterFilteringSize, + "afterRelinkingSize", &T::afterRelinkingSize, + "href", &T::href, + "id", &T::id, + "initialPoolSize", &T::initialPoolSize, + "type", &T::type + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Recommendations; + static constexpr auto value = object( + "seeds", &T::seeds, + "tracks", &T::tracks + ); +}; + +template <> +struct glz::meta { + using T = Spotify::SearchResults; + static constexpr auto value = object( + "tracks", &T::tracks, + "artists", &T::artists, + "albums", &T::albums, + "playlists", &T::playlists + ); +}; + diff --git a/include/Core/Spotify/Types/Player.hpp b/include/Core/Spotify/Types/Player.hpp new file mode 100644 index 0000000..668adb9 --- /dev/null +++ b/include/Core/Spotify/Types/Player.hpp @@ -0,0 +1,218 @@ +#pragma once +#include "Spotify/Types/Common.hpp" +#include "Spotify/Types/Track.hpp" + +namespace Spotify { + +// ============================================================================ +// Device Type Enum +// ============================================================================ + +enum class DeviceType { + Computer, + Smartphone, + Speaker, + TV, + AVR, + STB, + AudioDongle, + GameConsole, + CastVideo, + CastAudio, + Automobile, + Unknown +}; + +inline auto StringToDeviceType(const std::string& str) -> DeviceType { + if (str == "Computer") return DeviceType::Computer; + if (str == "Smartphone") return DeviceType::Smartphone; + if (str == "Speaker") return DeviceType::Speaker; + if (str == "TV") return DeviceType::TV; + if (str == "AVR") return DeviceType::AVR; + if (str == "STB") return DeviceType::STB; + if (str == "AudioDongle") return DeviceType::AudioDongle; + if (str == "GameConsole") return DeviceType::GameConsole; + if (str == "CastVideo") return DeviceType::CastVideo; + if (str == "CastAudio") return DeviceType::CastAudio; + if (str == "Automobile") return DeviceType::Automobile; + return DeviceType::Unknown; +} + +// ============================================================================ +// Repeat Mode Enum +// ============================================================================ + +enum class RepeatMode { + Off, + Track, + Context +}; + +inline auto RepeatModeToString(RepeatMode mode) -> std::string { + switch (mode) { + case RepeatMode::Off: return "off"; + case RepeatMode::Track: return "track"; + case RepeatMode::Context: return "context"; + } + return "off"; +} + +inline auto StringToRepeatMode(const std::string& str) -> RepeatMode { + if (str == "track") return RepeatMode::Track; + if (str == "context") return RepeatMode::Context; + return RepeatMode::Off; +} + +// ============================================================================ +// Context Type Enum +// ============================================================================ + +enum class ContextType { + Artist, + Playlist, + Album, + Show, + Collection +}; + +inline auto StringToContextType(const std::string& str) -> ContextType { + if (str == "artist") return ContextType::Artist; + if (str == "playlist") return ContextType::Playlist; + if (str == "album") return ContextType::Album; + if (str == "show") return ContextType::Show; + return ContextType::Collection; +} + +// ============================================================================ +// Currently Playing Type Enum +// ============================================================================ + +enum class CurrentlyPlayingType { + Track, + Episode, + Ad, + Unknown +}; + +inline auto StringToCurrentlyPlayingType(const std::string& str) -> CurrentlyPlayingType { + if (str == "track") return CurrentlyPlayingType::Track; + if (str == "episode") return CurrentlyPlayingType::Episode; + if (str == "ad") return CurrentlyPlayingType::Ad; + return CurrentlyPlayingType::Unknown; +} + +// ============================================================================ +// Device +// ============================================================================ + +struct Device { + std::optional id; + bool is_active; + bool is_private_session; + bool is_restricted; + std::string name; + std::string type; + int volume_percent; + + auto GetId() const -> const std::optional& { return id; } + auto GetName() const -> const std::string& { return name; } + auto IsActive() const -> bool { return is_active; } + auto GetVolume() const -> int { return volume_percent; } + + auto GetDeviceType() const -> DeviceType { + return StringToDeviceType(type); + } +}; + +// ============================================================================ +// Context +// ============================================================================ + +struct Context { + std::string type; + std::string href; + ExternalUrls external_urls; + std::string uri; + + auto GetUri() const -> const std::string& { return uri; } + + auto GetContextType() const -> ContextType { + return StringToContextType(type); + } +}; + +// ============================================================================ +// Playback State +// ============================================================================ + +struct PlaybackState { + Device device; + std::string repeat_state; + bool shuffle_state; + std::optional context; + int timestamp; + int progress_ms; + bool is_playing; + std::optional item; + std::string currently_playing_type; + + auto GetDevice() const -> const Device& { return device; } + auto IsPlaying() const -> bool { return is_playing; } + auto IsShuffled() const -> bool { return shuffle_state; } + auto GetProgressMs() const -> int { return progress_ms; } + auto GetCurrentTrack() const -> const std::optional& { return item; } + + auto GetRepeatMode() const -> RepeatMode { + return StringToRepeatMode(repeat_state); + } + + auto GetCurrentlyPlayingType() const -> CurrentlyPlayingType { + return StringToCurrentlyPlayingType(currently_playing_type); + } +}; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::Device; + static constexpr auto value = object( + "id", &T::id, + "is_active", &T::is_active, + "is_private_session", &T::is_private_session, + "is_restricted", &T::is_restricted, + "name", &T::name, + "type", &T::type, + "volume_percent", &T::volume_percent + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Context; + static constexpr auto value = object( + "type", &T::type, + "href", &T::href, + "external_urls", &T::external_urls, + "uri", &T::uri + ); +}; + +template <> +struct glz::meta { + using T = Spotify::PlaybackState; + static constexpr auto value = object( + "device", &T::device, + "repeat_state", &T::repeat_state, + "shuffle_state", &T::shuffle_state, + "context", &T::context, + "timestamp", &T::timestamp, + "progress_ms", &T::progress_ms, + "is_playing", &T::is_playing, + "item", &T::item, + "currently_playing_type", &T::currently_playing_type + ); +}; diff --git a/include/Core/Spotify/Types/Playlist.hpp b/include/Core/Spotify/Types/Playlist.hpp new file mode 100644 index 0000000..83743f0 --- /dev/null +++ b/include/Core/Spotify/Types/Playlist.hpp @@ -0,0 +1,139 @@ +#pragma once +#include "Spotify/Types/Common.hpp" +#include "Spotify/Types/Artist.hpp" +#include "Spotify/Types/Track.hpp" + +namespace Spotify { + +// ============================================================================ +// Playlist Track +// ============================================================================ + +struct PlaylistTrack { + std::optional added_at; + std::optional added_by; + bool is_local; + Track track; + + auto GetTrack() const -> const Track& { return track; } + auto GetAddedAt() const -> const std::optional& { return added_at; } + auto IsLocal() const -> bool { return is_local; } +}; + +// ============================================================================ +// Playlist Base +// ============================================================================ + +class PlaylistBase { +public: + bool collaborative; + std::optional description; + ExternalUrls external_urls; + std::string href; + std::string id; + std::vector images; + std::string name; + SimplifiedArtist owner; + bool public_playlist; + std::optional snapshot_id; + std::string type; + std::string uri; + + virtual ~PlaylistBase() = default; + + auto GetId() const -> const std::string& { return id; } + auto GetName() const -> const std::string& { return name; } + auto GetUri() const -> const std::string& { return uri; } + auto GetOwner() const -> const SimplifiedArtist& { return owner; } + auto IsPublic() const -> bool { return public_playlist; } + auto IsCollaborative() const -> bool { return collaborative; } + auto GetSnapshotId() const -> const std::optional& { return snapshot_id; } +}; + +// ============================================================================ +// Simplified Playlist +// ============================================================================ + +struct SimplifiedPlaylist : PlaylistBase { + struct TracksInfo { + std::string href; + int total; + } tracks; + + auto GetTotalTracks() const -> int { return tracks.total; } +}; + +// ============================================================================ +// Full Playlist +// ============================================================================ + +struct Playlist : PlaylistBase { + Followers followers; + + auto GetFollowers() const -> const Followers& { return followers; } +}; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::PlaylistTrack; + static constexpr auto value = object( + "added_at", &T::added_at, + "added_by", &T::added_by, + "is_local", &T::is_local, + "track", &T::track + ); +}; + +template <> +struct glz::meta { + using T = Spotify::SimplifiedPlaylist::TracksInfo; + static constexpr auto value = object( + "href", &T::href, + "total", &T::total + ); +}; + +template <> +struct glz::meta { + using T = Spotify::SimplifiedPlaylist; + static constexpr auto value = object( + "collaborative", &T::collaborative, + "description", &T::description, + "external_urls", &T::external_urls, + "href", &T::href, + "id", &T::id, + "images", &T::images, + "name", &T::name, + "owner", &T::owner, + "public", &T::public_playlist, + "snapshot_id", &T::snapshot_id, + "tracks", &T::tracks, + "type", &T::type, + "uri", &T::uri + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Playlist; + static constexpr auto value = object( + "collaborative", &T::collaborative, + "description", &T::description, + "external_urls", &T::external_urls, + "followers", &T::followers, + "href", &T::href, + "id", &T::id, + "images", &T::images, + "name", &T::name, + "owner", &T::owner, + "public", &T::public_playlist, + "snapshot_id", &T::snapshot_id, + "type", &T::type, + "uri", &T::uri + ); +}; diff --git a/include/Core/Spotify/Types/Track.hpp b/include/Core/Spotify/Types/Track.hpp new file mode 100644 index 0000000..ea7ac2d --- /dev/null +++ b/include/Core/Spotify/Types/Track.hpp @@ -0,0 +1,318 @@ +#pragma once +#include "Spotify/Types/Common.hpp" +#include "Spotify/Types/Artist.hpp" +#include "Spotify/Types/Album.hpp" + +namespace Spotify { + +// ============================================================================ +// Track Base +// ============================================================================ + +class TrackBase { +public: + std::vector artists; + std::vector available_markets; + int disc_number; + int duration_ms; + bool explicit_content; + ExternalUrls external_urls; + std::string href; + std::string id; + bool is_playable; + std::optional linked_from; + std::optional restrictions; + std::string name; + std::optional preview_url; + int track_number; + std::string type; + std::string uri; + bool is_local; + + virtual ~TrackBase() = default; + + auto GetId() const -> const std::string& { return id; } + auto GetName() const -> const std::string& { return name; } + auto GetUri() const -> const std::string& { return uri; } + auto GetDurationMs() const -> int { return duration_ms; } + auto GetTrackNumber() const -> int { return track_number; } + auto IsExplicit() const -> bool { return explicit_content; } + auto IsLocal() const -> bool { return is_local; } + auto GetArtists() const -> const std::vector& { return artists; } +}; + +// ============================================================================ +// Simplified Track +// ============================================================================ + +struct SimplifiedTrack : TrackBase { +}; + +// ============================================================================ +// Full Track +// ============================================================================ + +struct Track : TrackBase { + SimplifiedAlbum album; + ExternalIds external_ids; + int popularity; + + auto GetAlbum() const -> const SimplifiedAlbum& { return album; } + auto GetPopularity() const -> int { return popularity; } +}; + +// ============================================================================ +// Saved Track +// ============================================================================ + +struct SavedTrack { + std::string added_at; + Track track; + + auto GetTrack() const -> const Track& { return track; } + auto GetAddedAt() const -> const std::string& { return added_at; } +}; + +// ============================================================================ +// Audio Features +// ============================================================================ + +enum class MusicalKey { + C = 0, CSharp = 1, D = 2, DSharp = 3, + E = 4, F = 5, FSharp = 6, G = 7, + GSharp = 8, A = 9, ASharp = 10, B = 11 +}; + +enum class MusicalMode { + Minor = 0, + Major = 1 +}; + +struct AudioFeatures { + float acousticness; + std::string analysis_url; + float danceability; + int duration_ms; + float energy; + std::string id; + float instrumentalness; + int key; + float liveness; + float loudness; + int mode; + float speechiness; + float tempo; + int time_signature; + std::string track_href; + std::string type; + std::string uri; + float valence; + + auto GetKey() const -> MusicalKey { return static_cast(key); } + auto GetMode() const -> MusicalMode { return static_cast(mode); } + auto GetAcousticness() const -> float { return acousticness; } + auto GetDanceability() const -> float { return danceability; } + auto GetEnergy() const -> float { return energy; } + auto GetValence() const -> float { return valence; } + auto GetTempo() const -> float { return tempo; } +}; + +// ============================================================================ +// Audio Analysis +// ============================================================================ + +struct TimeInterval { + float start; + float duration; + float confidence; +}; + +struct Section { + float start; + float duration; + float confidence; + float loudness; + float tempo; + float tempo_confidence; + int key; + float key_confidence; + int mode; + float mode_confidence; + int time_signature; + float time_signature_confidence; +}; + +struct Segment { + float start; + float duration; + float confidence; + float loudness_start; + float loudness_max; + float loudness_max_time; + float loudness_end; + std::vector pitches; + std::vector timbre; +}; + +struct AudioAnalysis { + std::vector bars; + std::vector beats; + std::vector
sections; + std::vector segments; + std::vector tatums; + + auto GetBars() const -> const std::vector& { return bars; } + auto GetBeats() const -> const std::vector& { return beats; } + auto GetSections() const -> const std::vector
& { return sections; } +}; + + struct TracksResponse { + std::vector tracks; + }; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::SimplifiedTrack; + static constexpr auto value = object( + "artists", &T::artists, + "available_markets", &T::available_markets, + "disc_number", &T::disc_number, + "duration_ms", &T::duration_ms, + "explicit", &T::explicit_content, + "external_urls", &T::external_urls, + "href", &T::href, + "id", &T::id, + "is_playable", &T::is_playable, + "linked_from", &T::linked_from, + "restrictions", &T::restrictions, + "name", &T::name, + "preview_url", &T::preview_url, + "track_number", &T::track_number, + "type", &T::type, + "uri", &T::uri, + "is_local", &T::is_local + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Track; + static constexpr auto value = object( + "album", &T::album, + "artists", &T::artists, + "available_markets", &T::available_markets, + "disc_number", &T::disc_number, + "duration_ms", &T::duration_ms, + "explicit", &T::explicit_content, + "external_ids", &T::external_ids, + "external_urls", &T::external_urls, + "href", &T::href, + "id", &T::id, + "is_playable", &T::is_playable, + "linked_from", &T::linked_from, + "restrictions", &T::restrictions, + "name", &T::name, + "popularity", &T::popularity, + "preview_url", &T::preview_url, + "track_number", &T::track_number, + "type", &T::type, + "uri", &T::uri, + "is_local", &T::is_local + ); +}; + +template <> +struct glz::meta { + using T = Spotify::SavedTrack; + static constexpr auto value = object( + "added_at", &T::added_at, + "track", &T::track + ); +}; + +template <> +struct glz::meta { + using T = Spotify::AudioFeatures; + static constexpr auto value = object( + "acousticness", &T::acousticness, + "analysis_url", &T::analysis_url, + "danceability", &T::danceability, + "duration_ms", &T::duration_ms, + "energy", &T::energy, + "id", &T::id, + "instrumentalness", &T::instrumentalness, + "key", &T::key, + "liveness", &T::liveness, + "loudness", &T::loudness, + "mode", &T::mode, + "speechiness", &T::speechiness, + "tempo", &T::tempo, + "time_signature", &T::time_signature, + "track_href", &T::track_href, + "type", &T::type, + "uri", &T::uri, + "valence", &T::valence + ); +}; + +template <> +struct glz::meta { + using T = Spotify::TimeInterval; + static constexpr auto value = object( + "start", &T::start, + "duration", &T::duration, + "confidence", &T::confidence + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Section; + static constexpr auto value = object( + "start", &T::start, + "duration", &T::duration, + "confidence", &T::confidence, + "loudness", &T::loudness, + "tempo", &T::tempo, + "tempo_confidence", &T::tempo_confidence, + "key", &T::key, + "key_confidence", &T::key_confidence, + "mode", &T::mode, + "mode_confidence", &T::mode_confidence, + "time_signature", &T::time_signature, + "time_signature_confidence", &T::time_signature_confidence + ); +}; + +template <> +struct glz::meta { + using T = Spotify::Segment; + static constexpr auto value = object( + "start", &T::start, + "duration", &T::duration, + "confidence", &T::confidence, + "loudness_start", &T::loudness_start, + "loudness_max", &T::loudness_max, + "loudness_max_time", &T::loudness_max_time, + "loudness_end", &T::loudness_end, + "pitches", &T::pitches, + "timbre", &T::timbre + ); +}; + +template <> +struct glz::meta { + using T = Spotify::AudioAnalysis; + static constexpr auto value = object( + "bars", &T::bars, + "beats", &T::beats, + "sections", &T::sections, + "segments", &T::segments, + "tatums", &T::tatums + ); +}; diff --git a/include/Core/Spotify/Types/User.hpp b/include/Core/Spotify/Types/User.hpp new file mode 100644 index 0000000..a88d839 --- /dev/null +++ b/include/Core/Spotify/Types/User.hpp @@ -0,0 +1,77 @@ +#pragma once +#include "Spotify/Types/Common.hpp" + +namespace Spotify { + +// ============================================================================ +// User Product Type +// ============================================================================ + +enum class Product { + Premium, + Free, + Open, + Unknown +}; + +inline auto StringToProductType(const std::string& str) -> Product { + if (str == "premium") return Product::Premium; + if (str == "free") return Product::Free; + if (str == "open") return Product::Open; + return Product::Unknown; +} + +// ============================================================================ +// User +// ============================================================================ + +struct User { + std::optional country; + std::optional display_name; + std::optional email; + std::optional external_urls; + std::optional followers; + std::string href; + std::string id; + std::optional> images; + std::optional product; + std::string type; + std::string uri; + + auto GetId() const -> const std::string& { return id; } + auto GetDisplayName() const -> const std::optional& { return display_name; } + auto GetEmail() const -> const std::optional& { return email; } + auto GetUri() const -> const std::string& { return uri; } + + auto GetProductType() const -> Product { + if (!product) return Product::Unknown; + return StringToProductType(*product); + } + + auto IsPremium() const -> bool { + return GetProductType() == Product::Premium; + } +}; +} // namespace Spotify + +// ============================================================================ +// Glaze Metadata +// ============================================================================ + +template <> +struct glz::meta { + using T = Spotify::User; + static constexpr auto value = object( + "country", &T::country, + "display_name", &T::display_name, + "email", &T::email, + "external_urls", &T::external_urls, + "followers", &T::followers, + "href", &T::href, + "id", &T::id, + "images", &T::images, + "product", &T::product, + "type", &T::type, + "uri", &T::uri + ); +}; diff --git a/include/Core/Youtube/Client.hpp b/include/Core/Youtube/Client.hpp new file mode 100644 index 0000000..4033eee --- /dev/null +++ b/include/Core/Youtube/Client.hpp @@ -0,0 +1,274 @@ +#pragma once +// Standard Library +#include +#include +#include +#include +#include +#include + +// Third Party +#include "cpr/cprtypes.h" +#include "cpr/parameters.h" +#include +#include // Assumed available per your reference +#include +// Project (Assuming similar structure to your Spotify bot) +#include + +#include + +namespace YouTube { + +// ============================================================================ +// Data Types (Simplified for immediate usage) +// ============================================================================ + +struct Thumbnail { + std::string url; + int width; + int height; +}; + +struct Snippet { + std::string publishedAt; + std::string channelId; + std::string title; + std::string description; + std::string channelTitle; + std::map thumbnails; + std::string liveBroadcastContent; + std::string publishTime; +}; + +struct ResourceId { + std::string kind; + std::string videoId; + std::string channelId; + std::string playlistId; +}; + +// Search results use a wrapper for ID, Videos use a string ID +struct SearchResultId { + std::string kind; + std::string videoId; + std::string channelId; + std::string playlistId; +}; + +struct VideoContentDetails { + std::string duration; + std::string dimension; + std::string definition; +}; + +struct VideoStatistics { + std::string viewCount; + std::string likeCount; + std::string commentCount; +}; + +// Main Resource Types +struct Video { + std::string kind; + std::string id; + Snippet snippet; + VideoContentDetails contentDetails; + VideoStatistics statistics; +}; + +struct SearchResult { + std::string kind; + std::string etag; + SearchResultId id; + Snippet snippet; +}; + +// API Response Wrappers +template struct PageResult { + std::string kind; + std::string etag; + std::string nextPageToken; + std::string prevPageToken; + std::string regionCode; + struct PageInfo { + int totalResults; + int resultsPerPage; + } pageInfo; + std::vector items; +}; +// ============================================================================ +// InnerTube (Player) Data Types +// ============================================================================ + +struct AudioFormat { + int itag; + std::string url; // Direct URL (if unencrypted) + std::string signatureCipher; // Encrypted signature (if present, url is empty) + std::string mimeType; + int bitrate; + std::string qualityLabel; +}; + +struct StreamingData { + std::string expiresInSeconds; + std::vector formats; // Mixed video+audio + std::vector + adaptiveFormats; // Separate streams (we want audio from here) +}; + +struct PlayerResponse { + StreamingData streamingData; + // ... other fields like playabilityStatus ignored for brevity +}; +// ============================================================================ +// Error Handling +// ============================================================================ + +struct ApiError { + int status; + std::string message; + std::string reason; +}; +struct GoogleError { + struct Inner { + int code; + std::string message; + } error; +}; +template using Result = std::expected; +// ============================================================================ +// Request Parameters +// ============================================================================ + +struct SearchParams { + std::string q; + std::vector type = {"video"}; // video, channel, playlist + std::string part = "snippet"; + int maxResults = 5; + std::string order = "relevance"; + std::string pageToken = ""; + std::string videoDuration = "any"; // any, long, medium, short + bool rawQuery = false; // Set to true to preserve -, |, etc. in query +}; + +// ============================================================================ +// Main YouTube Client +// ============================================================================ + +struct CurlDeleter { + void operator()(CURL *ptr) const { + if (ptr) + curl_easy_cleanup(ptr); + } +}; + +enum class HttpMethod { GET, POST, PUT, DELETE }; + +class Client { +public: + // YouTube typically uses API Keys for public data, OAuth for user data. + // Pass "" as accessToken if only using API Key. + Client(std::string apiKey, std::string accessToken = ""); + ~Client(); + auto GetBestStreams(const std::string &videoId) + -> Result<::definitions::Streams>; // Configuration + void SetVerbose(bool verbose) { m_Verbose = verbose; } + void SetProxy(ProxyConfig config) { m_Proxy = std::move(config); } + void SetAccessToken(std::string token) { m_AccessToken = std::move(token); } + void SetApiKey(std::string key) { m_ApiKey = std::move(key); } + + // ======================================================================== + // Search API + // ======================================================================== + + // https://developers.google.com/youtube/v3/docs/search/list + auto Search(const SearchParams ¶ms) -> Result>; + + // ======================================================================== + // Videos API + // ======================================================================== + + // https://developers.google.com/youtube/v3/docs/videos/list + auto GetVideo(const std::string &id, + const std::string &part = "snippet,contentDetails,statistics") + -> Result