Initial commit
This commit is contained in:
commit
f6c5bcca39
52 files changed
+55449
No files matched your search
@@ -0,0 +1,3 @@
|
||||
*build*
|
||||
.cache
|
||||
.idea
|
||||
+110
@@ -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"
|
||||
)
|
||||
@@ -0,0 +1,458 @@
|
||||
# SPDX-FileCopyrightText: 2024 L. E. Segovia <amy@centricular.com>
|
||||
# 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
|
||||
)
|
||||
@@ -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": ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
#pragma once
|
||||
#include "PluginInterface.hpp"
|
||||
// #include "Youtube/Client.hpp"
|
||||
#include "ts6bot/AudioDecoder.hpp"
|
||||
#include <memory>
|
||||
#include <quill/Backend.h>
|
||||
#include <quill/Frontend.h>
|
||||
#include <quill/LogMacros.h>
|
||||
#include <quill/Logger.h>
|
||||
#include <quill/core/SinkManager.h>
|
||||
#include <singleton_atomic.hpp>
|
||||
#include "ts6bot/Config.hpp"
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
#include "quill/sinks/FileSink.h"
|
||||
#include "quill/sinks/ConsoleSink.h"
|
||||
#include <ts6bot/Proxy.hpp>
|
||||
|
||||
#include "PluginDefinitions.hpp"
|
||||
#include "ts6bot/MusicManager.hpp"
|
||||
|
||||
class EchoionCore : public IEchoionPlugin {
|
||||
// Dependencies
|
||||
quill::Logger *m_logger = nullptr;
|
||||
std::shared_ptr<TS3Functions> m_ts3;
|
||||
std::unique_ptr<MusicManager> m_musicManager;
|
||||
|
||||
public:
|
||||
explicit EchoionCore(std::shared_ptr<TS3Functions> 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<TS3Functions>(*funcs));
|
||||
}
|
||||
|
||||
void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <teamspeak/public_definitions.h>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <glaze/core/common.hpp>
|
||||
|
||||
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> streams;
|
||||
|
||||
QueueItem() = default;
|
||||
|
||||
QueueItem(std::string name, std::string videoId, std::string requested_by, const std::optional<Streams> & 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<QueueItem> queue;
|
||||
std::vector<anyID> onlineSubscribers;
|
||||
std::vector<anyID> offlineSubscribers;
|
||||
std::uint64_t serverConnection;
|
||||
bool wasPlaying = false;
|
||||
};
|
||||
}
|
||||
|
||||
template <> struct glz::meta<definitions::StreamInfo> {
|
||||
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<definitions::Streams> {
|
||||
using T = definitions::Streams;
|
||||
static constexpr auto value =
|
||||
object("audio", &T::audio, "video", &T::video);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<definitions::QueueItem> {
|
||||
using T = definitions::QueueItem;
|
||||
static constexpr auto value =
|
||||
object("name", &T::name, "videoId", &T::videoId, "requester", &T::requester,
|
||||
"streams", &T::streams);
|
||||
};
|
||||
@@ -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 <curl/curl.h>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
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 <typename T> using Result = std::expected<T, ApiError>;
|
||||
|
||||
// ============================================================================
|
||||
// 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<std::string> market = {})
|
||||
-> Result<Album>;
|
||||
|
||||
auto GetAlbums(const std::vector<std::string> &ids,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<std::vector<Album>>;
|
||||
|
||||
auto GetAlbumTracks(const std::string &id,
|
||||
const Request::AlbumTracksParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedTrack>>;
|
||||
|
||||
auto GetSavedAlbums(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SavedAlbum>>;
|
||||
|
||||
auto SaveAlbums(const std::vector<std::string> &ids) -> Result<void>;
|
||||
|
||||
auto RemoveSavedAlbums(const std::vector<std::string> &ids) -> Result<void>;
|
||||
|
||||
auto CheckSavedAlbums(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
auto GetNewReleases(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
|
||||
// ========================================================================
|
||||
// Artists API
|
||||
// ========================================================================
|
||||
|
||||
auto GetArtist(const std::string &id) -> Result<Artist>;
|
||||
|
||||
auto GetArtists(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<Artist>>;
|
||||
|
||||
auto GetArtistAlbums(const std::string &id,
|
||||
const Request::ArtistAlbumsParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
|
||||
auto GetArtistTopTracks(const std::string &id, const std::string &market)
|
||||
-> Result<std::vector<Track>>;
|
||||
|
||||
auto GetArtistRelatedArtists(const std::string &id)
|
||||
-> Result<std::vector<Artist>>;
|
||||
|
||||
// ========================================================================
|
||||
// Tracks API
|
||||
// ========================================================================
|
||||
|
||||
auto GetTrack(const std::string &id, std::optional<std::string> market = {})
|
||||
-> Result<Track>;
|
||||
|
||||
auto GetTracks(const std::vector<std::string> &ids,
|
||||
std::optional<std::string> market = {})
|
||||
-> Result<std::vector<Track>>;
|
||||
|
||||
auto GetSavedTracks(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SavedTrack>>;
|
||||
|
||||
auto SaveTracks(const std::vector<std::string> &ids) -> Result<void>;
|
||||
|
||||
auto RemoveSavedTracks(const std::vector<std::string> &ids) -> Result<void>;
|
||||
|
||||
auto CheckSavedTracks(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
auto GetAudioFeatures(const std::string &id) -> Result<AudioFeatures>;
|
||||
|
||||
auto GetAudioFeaturesForTracks(const std::vector<std::string> &ids)
|
||||
-> Result<std::vector<AudioFeatures>>;
|
||||
|
||||
auto GetAudioAnalysis(const std::string &id) -> Result<AudioAnalysis>;
|
||||
|
||||
auto GetRecommendations(const Request::RecommendationParams ¶ms)
|
||||
-> Result<Recommendations>;
|
||||
|
||||
// ========================================================================
|
||||
// Search API
|
||||
// ========================================================================
|
||||
|
||||
auto Search(const Request::SearchParams ¶ms) -> Result<SearchResults>;
|
||||
|
||||
auto SearchTracks(const Request::TrackSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Track>>;
|
||||
|
||||
auto SearchAlbums(const Request::AlbumSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedAlbum>>;
|
||||
|
||||
auto SearchArtists(const Request::ArtistSearchFilters &filters,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Artist>>;
|
||||
|
||||
// ========================================================================
|
||||
// Playlists API
|
||||
// ========================================================================
|
||||
|
||||
auto GetPlaylist(const std::string &id,
|
||||
std::optional<std::string> market = {}) -> Result<Playlist>;
|
||||
|
||||
auto GetPlaylistTracks(const std::string &id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<PlaylistTrack>>;
|
||||
|
||||
auto CreatePlaylist(const std::string &user_id,
|
||||
const Request::CreatePlaylistParams ¶ms)
|
||||
-> Result<Playlist>;
|
||||
|
||||
auto UpdatePlaylist(const std::string &id,
|
||||
const Request::UpdatePlaylistParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto AddTracksToPlaylist(const std::string &id,
|
||||
const Request::AddTracksToPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
|
||||
auto RemoveTracksFromPlaylist(
|
||||
const std::string &id,
|
||||
const Request::RemoveTracksFromPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
|
||||
auto ReorderPlaylistTracks(const std::string &id,
|
||||
const Request::ReorderPlaylistParams ¶ms)
|
||||
-> Result<std::string>;
|
||||
|
||||
auto ReplacePlaylistTracks(const std::string &id,
|
||||
const Request::ReplacePlaylistTracksParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto GetCurrentUserPlaylists(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
auto GetUserPlaylists(const std::string &user_id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
auto GetFeaturedPlaylists(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
auto GetCategoryPlaylists(const std::string &category_id,
|
||||
const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<SimplifiedPlaylist>>;
|
||||
|
||||
// ========================================================================
|
||||
// User API
|
||||
// ========================================================================
|
||||
|
||||
auto GetCurrentUser() -> Result<User>;
|
||||
|
||||
auto GetUser(const std::string &user_id) -> Result<User>;
|
||||
|
||||
auto GetTopArtists(const Request::TopItemsParams ¶ms = {})
|
||||
-> Result<PagingObject<Artist>>;
|
||||
|
||||
auto GetTopTracks(const Request::TopItemsParams ¶ms = {})
|
||||
-> Result<PagingObject<Track>>;
|
||||
|
||||
// ========================================================================
|
||||
// Follow API
|
||||
// ========================================================================
|
||||
|
||||
auto FollowArtistsOrUsers(const Request::FollowParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto UnfollowArtistsOrUsers(const Request::UnfollowParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto CheckFollowingArtistsOrUsers(const Request::CheckFollowingParams ¶ms)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
auto GetFollowedArtists(std::optional<int> limit = {},
|
||||
std::optional<std::string> after = {})
|
||||
-> Result<CursorPagingObject<Artist>>;
|
||||
|
||||
auto FollowPlaylist(const std::string &playlist_id,
|
||||
const Request::FollowPlaylistParams ¶ms = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto UnfollowPlaylist(const std::string &playlist_id) -> Result<void>;
|
||||
|
||||
auto CheckFollowingPlaylist(const std::string &playlist_id,
|
||||
const std::vector<std::string> &user_ids)
|
||||
-> Result<std::vector<bool>>;
|
||||
|
||||
// ========================================================================
|
||||
// Player API
|
||||
// ========================================================================
|
||||
|
||||
auto GetPlaybackState(std::optional<std::string> market = {})
|
||||
-> Result<PlaybackState>;
|
||||
|
||||
auto GetAvailableDevices() -> Result<std::vector<Device>>;
|
||||
|
||||
auto GetCurrentlyPlayingTrack(std::optional<std::string> market = {})
|
||||
-> Result<PlaybackState>;
|
||||
|
||||
auto StartOrResumePlayback(const Request::PlayParams ¶ms,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto PausePlayback(std::optional<std::string> device_id = {}) -> Result<void>;
|
||||
|
||||
auto SkipToNext(std::optional<std::string> device_id = {}) -> Result<void>;
|
||||
|
||||
auto SkipToPrevious(std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SeekToPosition(int position_ms,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SetRepeatMode(RepeatMode mode, std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto SetPlaybackVolume(int volume_percent,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto TogglePlaybackShuffle(bool state,
|
||||
std::optional<std::string> device_id = {})
|
||||
-> Result<void>;
|
||||
|
||||
auto TransferPlayback(const Request::TransferPlaybackParams ¶ms)
|
||||
-> Result<void>;
|
||||
|
||||
auto AddToQueue(const Request::QueueParams ¶ms) -> Result<void>;
|
||||
|
||||
auto GetRecentlyPlayedTracks(std::optional<int> limit = {},
|
||||
std::optional<int64_t> after = {},
|
||||
std::optional<int64_t> before = {})
|
||||
-> Result<CursorPagingObject<PlaylistTrack>>;
|
||||
|
||||
// ========================================================================
|
||||
// Browse API
|
||||
// ========================================================================
|
||||
|
||||
auto GetCategories(const Request::PaginationParams ¶ms = {})
|
||||
-> Result<PagingObject<Category>>;
|
||||
|
||||
auto GetCategory(const std::string &category_id,
|
||||
std::optional<std::string> locale = {}) -> Result<Category>;
|
||||
|
||||
auto GetAvailableGenreSeeds() -> Result<std::vector<std::string>>;
|
||||
|
||||
auto GetAvailableMarkets() -> Result<std::vector<std::string>>;
|
||||
|
||||
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<std::string> &extra_headers = {})
|
||||
-> Result<std::string>;
|
||||
|
||||
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<std::string, std::string> ¶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
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
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<CallbackResult> WaitForCallback(std::chrono::milliseconds timeout);
|
||||
|
||||
private:
|
||||
std::string m_Host;
|
||||
uint16_t m_Port;
|
||||
std::string m_Path;
|
||||
};
|
||||
|
||||
} // namespace ts6bot
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <Spotify/Client.hpp> // 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<std::string>& 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<TokenSet> Load() const;
|
||||
|
||||
static std::int64_t NowUnixSeconds();
|
||||
friend TokenSet;
|
||||
};
|
||||
|
||||
} // namespace ts6bot
|
||||
@@ -0,0 +1,496 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <map>
|
||||
#include <format>
|
||||
#include <ranges>
|
||||
#include <algorithm>
|
||||
|
||||
namespace Spotify::Request {
|
||||
|
||||
// ============================================================================
|
||||
// Base Request Parameter Class
|
||||
// ============================================================================
|
||||
|
||||
class RequestParams {
|
||||
public:
|
||||
virtual ~RequestParams() = default;
|
||||
virtual auto ToQueryParams() const -> std::map<std::string, std::string> = 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<int> limit = 20;
|
||||
std::optional<int> offset = 0;
|
||||
std::optional<std::string> market;
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
std::map<std::string, std::string> 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<SearchType> types;
|
||||
std::optional<std::string> market;
|
||||
std::optional<int> limit = 20;
|
||||
std::optional<int> offset = 0;
|
||||
std::optional<bool> include_external;
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
std::map<std::string, std::string> params;
|
||||
params["q"] = query;
|
||||
|
||||
std::vector<std::string> type_strings;
|
||||
for (const auto& type : types) {
|
||||
type_strings.push_back(SearchTypeToString(type));
|
||||
}
|
||||
params["type"] = std::views::join_with(type_strings, ',') | std::ranges::to<std::string>();
|
||||
|
||||
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<std::string> track;
|
||||
std::optional<std::string> artist;
|
||||
std::optional<std::string> album;
|
||||
std::optional<int> year;
|
||||
std::optional<std::string> genre;
|
||||
std::optional<std::string> isrc;
|
||||
std::optional<std::string> upc;
|
||||
std::optional<bool> is_new;
|
||||
std::optional<bool> hipster;
|
||||
|
||||
auto ToQueryString() const -> std::string {
|
||||
std::vector<std::string> 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<std::string>();
|
||||
}
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Album Search Filters
|
||||
// ============================================================================
|
||||
|
||||
struct AlbumSearchFilters : public RequestParams {
|
||||
public:
|
||||
std::optional<std::string> album;
|
||||
std::optional<std::string> artist;
|
||||
std::optional<int> year;
|
||||
std::optional<std::string> genre;
|
||||
std::optional<std::string> upc;
|
||||
|
||||
auto ToQueryString() const -> std::string {
|
||||
std::vector<std::string> 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<std::string>();
|
||||
}
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Artist Search Filters
|
||||
// ============================================================================
|
||||
|
||||
struct ArtistSearchFilters : public RequestParams {
|
||||
public:
|
||||
std::optional<std::string> artist;
|
||||
std::optional<std::string> genre;
|
||||
|
||||
auto ToQueryString() const -> std::string {
|
||||
std::vector<std::string> 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<std::string>();
|
||||
}
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Album Tracks Parameters
|
||||
// ============================================================================
|
||||
|
||||
struct AlbumTracksParams : public RequestParams {
|
||||
public:
|
||||
std::optional<int> limit = 20;
|
||||
std::optional<int> offset = 0;
|
||||
std::optional<std::string> market;
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
std::map<std::string, std::string> 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<std::vector<std::string>> include_groups;
|
||||
std::optional<std::string> market;
|
||||
std::optional<int> limit = 20;
|
||||
std::optional<int> offset = 0;
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
std::map<std::string, std::string> params;
|
||||
|
||||
if (include_groups && !include_groups->empty()) {
|
||||
params["include_groups"] = std::views::join_with(*include_groups, ',') | std::ranges::to<std::string>();
|
||||
}
|
||||
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<TimeRange> time_range = TimeRange::MediumTerm;
|
||||
std::optional<int> limit = 20;
|
||||
std::optional<int> offset = 0;
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
std::map<std::string, std::string> 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<std::vector<std::string>> seed_artists;
|
||||
std::optional<std::vector<std::string>> seed_genres;
|
||||
std::optional<std::vector<std::string>> seed_tracks;
|
||||
std::optional<int> limit = 20;
|
||||
std::optional<std::string> market;
|
||||
|
||||
// Tunable attributes
|
||||
std::optional<float> min_acousticness;
|
||||
std::optional<float> max_acousticness;
|
||||
std::optional<float> target_acousticness;
|
||||
|
||||
std::optional<float> min_danceability;
|
||||
std::optional<float> max_danceability;
|
||||
std::optional<float> target_danceability;
|
||||
|
||||
std::optional<int> min_duration_ms;
|
||||
std::optional<int> max_duration_ms;
|
||||
std::optional<int> target_duration_ms;
|
||||
|
||||
std::optional<float> min_energy;
|
||||
std::optional<float> max_energy;
|
||||
std::optional<float> target_energy;
|
||||
|
||||
std::optional<float> min_instrumentalness;
|
||||
std::optional<float> max_instrumentalness;
|
||||
std::optional<float> target_instrumentalness;
|
||||
|
||||
std::optional<int> min_key;
|
||||
std::optional<int> max_key;
|
||||
std::optional<int> target_key;
|
||||
|
||||
std::optional<float> min_liveness;
|
||||
std::optional<float> max_liveness;
|
||||
std::optional<float> target_liveness;
|
||||
|
||||
std::optional<float> min_loudness;
|
||||
std::optional<float> max_loudness;
|
||||
std::optional<float> target_loudness;
|
||||
|
||||
std::optional<int> min_mode;
|
||||
std::optional<int> max_mode;
|
||||
std::optional<int> target_mode;
|
||||
|
||||
std::optional<int> min_popularity;
|
||||
std::optional<int> max_popularity;
|
||||
std::optional<int> target_popularity;
|
||||
|
||||
std::optional<float> min_speechiness;
|
||||
std::optional<float> max_speechiness;
|
||||
std::optional<float> target_speechiness;
|
||||
|
||||
std::optional<float> min_tempo;
|
||||
std::optional<float> max_tempo;
|
||||
std::optional<float> target_tempo;
|
||||
|
||||
std::optional<int> min_time_signature;
|
||||
std::optional<int> max_time_signature;
|
||||
std::optional<int> target_time_signature;
|
||||
|
||||
std::optional<float> min_valence;
|
||||
std::optional<float> max_valence;
|
||||
std::optional<float> target_valence;
|
||||
|
||||
auto ToQueryParams() const -> std::map<std::string, std::string> override {
|
||||
std::map<std::string, std::string> params;
|
||||
|
||||
if (seed_artists && !seed_artists->empty()) {
|
||||
params["seed_artists"] = std::views::join_with(*seed_artists, ',') | std::ranges::to<std::string>();
|
||||
}
|
||||
if (seed_genres && !seed_genres->empty()) {
|
||||
params["seed_genres"] = std::views::join_with(*seed_genres, ',') | std::ranges::to<std::string>();
|
||||
}
|
||||
if (seed_tracks && !seed_tracks->empty()) {
|
||||
params["seed_tracks"] = std::views::join_with(*seed_tracks, ',') | std::ranges::to<std::string>();
|
||||
}
|
||||
|
||||
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<bool> public_playlist = true;
|
||||
std::optional<bool> collaborative = false;
|
||||
std::optional<std::string> description;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Update Playlist Parameters
|
||||
// ============================================================================
|
||||
|
||||
struct UpdatePlaylistParams {
|
||||
std::optional<std::string> name;
|
||||
std::optional<bool> public_playlist;
|
||||
std::optional<bool> collaborative;
|
||||
std::optional<std::string> description;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Playlist Track Operations
|
||||
// ============================================================================
|
||||
|
||||
struct AddTracksToPlaylistParams {
|
||||
std::vector<std::string> uris;
|
||||
std::optional<int> position;
|
||||
};
|
||||
|
||||
struct RemoveTracksFromPlaylistParams {
|
||||
std::vector<std::string> uris;
|
||||
std::optional<std::string> snapshot_id;
|
||||
};
|
||||
|
||||
struct ReorderPlaylistParams {
|
||||
int range_start;
|
||||
int insert_before;
|
||||
std::optional<int> range_length = 1;
|
||||
std::optional<std::string> snapshot_id;
|
||||
};
|
||||
|
||||
struct ReplacePlaylistTracksParams {
|
||||
std::vector<std::string> uris;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Playback Control Parameters
|
||||
// ============================================================================
|
||||
|
||||
struct PlayParams {
|
||||
std::optional<std::string> context_uri;
|
||||
std::optional<std::vector<std::string>> uris;
|
||||
std::optional<std::map<std::string, int>> offset;
|
||||
std::optional<int> position_ms;
|
||||
};
|
||||
|
||||
struct TransferPlaybackParams {
|
||||
std::vector<std::string> device_ids;
|
||||
std::optional<bool> play;
|
||||
};
|
||||
|
||||
struct QueueParams {
|
||||
std::string uri;
|
||||
std::optional<std::string> device_id;
|
||||
};
|
||||
struct RequestBody {
|
||||
std::vector<std::string> 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<std::string> ids;
|
||||
};
|
||||
|
||||
struct UnfollowParams {
|
||||
FollowType type;
|
||||
std::vector<std::string> ids;
|
||||
};
|
||||
|
||||
struct CheckFollowingParams {
|
||||
FollowType type;
|
||||
std::vector<std::string> ids;
|
||||
};
|
||||
|
||||
struct FollowPlaylistParams {
|
||||
std::optional<bool> public_playlist = true;
|
||||
};
|
||||
|
||||
} // namespace Spotify::Request
|
||||
@@ -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<std::string> available_markets;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::vector<Image> images;
|
||||
std::string name;
|
||||
std::string release_date;
|
||||
std::string release_date_precision;
|
||||
std::optional<Restrictions> restrictions;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
std::vector<SimplifiedArtist> 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<Copyright> copyrights;
|
||||
ExternalIds external_ids;
|
||||
std::vector<std::string> 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<std::string>& { 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<Album> albums;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedAlbum> {
|
||||
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<Spotify::AlbumsResponse> {
|
||||
using T = Spotify::AlbumsResponse;
|
||||
static constexpr auto value = object(
|
||||
"albums", &T::albums
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Album> {
|
||||
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<Spotify::SavedAlbum> {
|
||||
using T = Spotify::SavedAlbum;
|
||||
static constexpr auto value = object(
|
||||
"added_at", &T::added_at,
|
||||
"album", &T::album
|
||||
);
|
||||
};
|
||||
@@ -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<std::string> genres;
|
||||
std::vector<Image> images;
|
||||
int popularity;
|
||||
|
||||
auto GetPopularity() const -> int { return popularity; }
|
||||
auto GetGenres() const -> const std::vector<std::string>& { return genres; }
|
||||
};
|
||||
|
||||
struct ArtistsResponse {
|
||||
std::vector<Artist> artists;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedArtist> {
|
||||
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<Spotify::Artist> {
|
||||
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
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <glaze/glaze.hpp>
|
||||
|
||||
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<int> height;
|
||||
std::optional<int> width;
|
||||
};
|
||||
|
||||
struct ExternalUrls {
|
||||
std::string spotify;
|
||||
};
|
||||
|
||||
struct ExternalIds {
|
||||
std::optional<std::string> isrc;
|
||||
std::optional<std::string> ean;
|
||||
std::optional<std::string> upc;
|
||||
};
|
||||
|
||||
struct Followers {
|
||||
std::optional<std::string> 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<typename T>
|
||||
struct PagingObject {
|
||||
std::string href;
|
||||
int limit;
|
||||
std::optional<std::string> next;
|
||||
int offset;
|
||||
std::optional<std::string> previous;
|
||||
int total;
|
||||
std::vector<T> items;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct CursorPagingObject {
|
||||
std::string href;
|
||||
int limit;
|
||||
std::optional<std::string> next;
|
||||
std::optional<std::string> cursors;
|
||||
int total;
|
||||
std::vector<T> items;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata for Common Types
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Image> {
|
||||
using T = Spotify::Image;
|
||||
static constexpr auto value = object(
|
||||
"url", &T::url,
|
||||
"height", &T::height,
|
||||
"width", &T::width
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::ExternalUrls> {
|
||||
using T = Spotify::ExternalUrls;
|
||||
static constexpr auto value = object("spotify", &T::spotify);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::ExternalIds> {
|
||||
using T = Spotify::ExternalIds;
|
||||
static constexpr auto value = object(
|
||||
"isrc", &T::isrc,
|
||||
"ean", &T::ean,
|
||||
"upc", &T::upc
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Followers> {
|
||||
using T = Spotify::Followers;
|
||||
static constexpr auto value = object(
|
||||
"href", &T::href,
|
||||
"total", &T::total
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Copyright> {
|
||||
using T = Spotify::Copyright;
|
||||
static constexpr auto value = object(
|
||||
"text", &T::text,
|
||||
"type", &T::type
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Restrictions> {
|
||||
using T = Spotify::Restrictions;
|
||||
static constexpr auto value = object("reason", &T::reason);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct glz::meta<Spotify::PagingObject<T>> {
|
||||
using Type = Spotify::PagingObject<T>;
|
||||
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 <typename T>
|
||||
struct glz::meta<Spotify::CursorPagingObject<T>> {
|
||||
using Type = Spotify::CursorPagingObject<T>;
|
||||
static constexpr auto value = object(
|
||||
"href", &Type::href,
|
||||
"limit", &Type::limit,
|
||||
"next", &Type::next,
|
||||
"cursors", &Type::cursors,
|
||||
"total", &Type::total,
|
||||
"items", &Type::items
|
||||
);
|
||||
};
|
||||
@@ -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 <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Spotify {
|
||||
|
||||
// ============================================================================
|
||||
// Category
|
||||
// ============================================================================
|
||||
|
||||
struct Category {
|
||||
std::string href;
|
||||
std::vector<Image> 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<std::string> 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<RecommendationSeed> seeds;
|
||||
std::vector<Track> tracks;
|
||||
|
||||
auto GetTracks() const -> const std::vector<Track>& { return tracks; }
|
||||
auto GetSeeds() const -> const std::vector<RecommendationSeed>& { return seeds; }
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Search Results
|
||||
// ============================================================================
|
||||
|
||||
struct SearchResults {
|
||||
std::optional<PagingObject<Track>> tracks;
|
||||
std::optional<PagingObject<Artist>> artists;
|
||||
std::optional<PagingObject<SimplifiedAlbum>> albums;
|
||||
std::optional<PagingObject<SimplifiedPlaylist>> playlists;
|
||||
|
||||
auto GetTracks() const -> const std::optional<PagingObject<Track>>& { return tracks; }
|
||||
auto GetArtists() const -> const std::optional<PagingObject<Artist>>& { return artists; }
|
||||
auto GetAlbums() const -> const std::optional<PagingObject<SimplifiedAlbum>>& { return albums; }
|
||||
auto GetPlaylists() const -> const std::optional<PagingObject<SimplifiedPlaylist>>& { return playlists; }
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Category> {
|
||||
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<Spotify::RecommendationSeed> {
|
||||
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<Spotify::Recommendations> {
|
||||
using T = Spotify::Recommendations;
|
||||
static constexpr auto value = object(
|
||||
"seeds", &T::seeds,
|
||||
"tracks", &T::tracks
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SearchResults> {
|
||||
using T = Spotify::SearchResults;
|
||||
static constexpr auto value = object(
|
||||
"tracks", &T::tracks,
|
||||
"artists", &T::artists,
|
||||
"albums", &T::albums,
|
||||
"playlists", &T::playlists
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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<std::string> 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<std::string>& { 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> context;
|
||||
int timestamp;
|
||||
int progress_ms;
|
||||
bool is_playing;
|
||||
std::optional<Track> 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<Track>& { 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<Spotify::Device> {
|
||||
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<Spotify::Context> {
|
||||
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<Spotify::PlaybackState> {
|
||||
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
|
||||
);
|
||||
};
|
||||
@@ -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<std::string> added_at;
|
||||
std::optional<SimplifiedArtist> added_by;
|
||||
bool is_local;
|
||||
Track track;
|
||||
|
||||
auto GetTrack() const -> const Track& { return track; }
|
||||
auto GetAddedAt() const -> const std::optional<std::string>& { return added_at; }
|
||||
auto IsLocal() const -> bool { return is_local; }
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Playlist Base
|
||||
// ============================================================================
|
||||
|
||||
class PlaylistBase {
|
||||
public:
|
||||
bool collaborative;
|
||||
std::optional<std::string> description;
|
||||
ExternalUrls external_urls;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::vector<Image> images;
|
||||
std::string name;
|
||||
SimplifiedArtist owner;
|
||||
bool public_playlist;
|
||||
std::optional<std::string> 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<std::string>& { 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<Spotify::PlaylistTrack> {
|
||||
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<Spotify::SimplifiedPlaylist::TracksInfo> {
|
||||
using T = Spotify::SimplifiedPlaylist::TracksInfo;
|
||||
static constexpr auto value = object(
|
||||
"href", &T::href,
|
||||
"total", &T::total
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedPlaylist> {
|
||||
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<Spotify::Playlist> {
|
||||
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
|
||||
);
|
||||
};
|
||||
@@ -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<SimplifiedArtist> artists;
|
||||
std::vector<std::string> 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<std::string> linked_from;
|
||||
std::optional<Restrictions> restrictions;
|
||||
std::string name;
|
||||
std::optional<std::string> 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<SimplifiedArtist>& { 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<MusicalKey>(key); }
|
||||
auto GetMode() const -> MusicalMode { return static_cast<MusicalMode>(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<float> pitches;
|
||||
std::vector<float> timbre;
|
||||
};
|
||||
|
||||
struct AudioAnalysis {
|
||||
std::vector<TimeInterval> bars;
|
||||
std::vector<TimeInterval> beats;
|
||||
std::vector<Section> sections;
|
||||
std::vector<Segment> segments;
|
||||
std::vector<TimeInterval> tatums;
|
||||
|
||||
auto GetBars() const -> const std::vector<TimeInterval>& { return bars; }
|
||||
auto GetBeats() const -> const std::vector<TimeInterval>& { return beats; }
|
||||
auto GetSections() const -> const std::vector<Section>& { return sections; }
|
||||
};
|
||||
|
||||
struct TracksResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
} // namespace Spotify
|
||||
|
||||
// ============================================================================
|
||||
// Glaze Metadata
|
||||
// ============================================================================
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::SimplifiedTrack> {
|
||||
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<Spotify::Track> {
|
||||
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<Spotify::SavedTrack> {
|
||||
using T = Spotify::SavedTrack;
|
||||
static constexpr auto value = object(
|
||||
"added_at", &T::added_at,
|
||||
"track", &T::track
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::AudioFeatures> {
|
||||
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<Spotify::TimeInterval> {
|
||||
using T = Spotify::TimeInterval;
|
||||
static constexpr auto value = object(
|
||||
"start", &T::start,
|
||||
"duration", &T::duration,
|
||||
"confidence", &T::confidence
|
||||
);
|
||||
};
|
||||
|
||||
template <>
|
||||
struct glz::meta<Spotify::Section> {
|
||||
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<Spotify::Segment> {
|
||||
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<Spotify::AudioAnalysis> {
|
||||
using T = Spotify::AudioAnalysis;
|
||||
static constexpr auto value = object(
|
||||
"bars", &T::bars,
|
||||
"beats", &T::beats,
|
||||
"sections", &T::sections,
|
||||
"segments", &T::segments,
|
||||
"tatums", &T::tatums
|
||||
);
|
||||
};
|
||||
@@ -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<std::string> country;
|
||||
std::optional<std::string> display_name;
|
||||
std::optional<std::string> email;
|
||||
std::optional<ExternalUrls> external_urls;
|
||||
std::optional<Followers> followers;
|
||||
std::string href;
|
||||
std::string id;
|
||||
std::optional<std::vector<Image>> images;
|
||||
std::optional<std::string> product;
|
||||
std::string type;
|
||||
std::string uri;
|
||||
|
||||
auto GetId() const -> const std::string& { return id; }
|
||||
auto GetDisplayName() const -> const std::optional<std::string>& { return display_name; }
|
||||
auto GetEmail() const -> const std::optional<std::string>& { 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<Spotify::User> {
|
||||
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
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
#pragma once
|
||||
// Standard Library
|
||||
#include <expected>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Third Party
|
||||
#include "cpr/cprtypes.h"
|
||||
#include "cpr/parameters.h"
|
||||
#include <curl/curl.h>
|
||||
#include <glaze/glaze.hpp> // Assumed available per your reference
|
||||
#include <quickjs.h>
|
||||
// Project (Assuming similar structure to your Spotify bot)
|
||||
#include <ts6bot/Proxy.hpp>
|
||||
|
||||
#include <PluginDefinitions.hpp>
|
||||
|
||||
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<std::string, Thumbnail> 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 <typename T> 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<T> 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<AudioFormat> formats; // Mixed video+audio
|
||||
std::vector<AudioFormat>
|
||||
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 <typename T> using Result = std::expected<T, ApiError>;
|
||||
// ============================================================================
|
||||
// Request Parameters
|
||||
// ============================================================================
|
||||
|
||||
struct SearchParams {
|
||||
std::string q;
|
||||
std::vector<std::string> 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<PageResult<SearchResult>>;
|
||||
|
||||
// ========================================================================
|
||||
// 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<Video>;
|
||||
|
||||
auto GetVideos(const std::vector<std::string> &ids,
|
||||
const std::string &part = "snippet,contentDetails,statistics")
|
||||
-> Result<std::vector<Video>>;
|
||||
|
||||
// ========================================================================
|
||||
// Channels API
|
||||
// ========================================================================
|
||||
|
||||
// https://developers.google.com/youtube/v3/docs/channels/list
|
||||
auto GetChannel(const std::string &id,
|
||||
const std::string &part = "snippet,statistics")
|
||||
-> Result<std::string>; // Returns raw JSON for brevity in this example
|
||||
|
||||
// ========================================================================
|
||||
// Playlists API
|
||||
// ========================================================================
|
||||
|
||||
// https://developers.google.com/youtube/v3/docs/playlistItems/list
|
||||
auto GetPlaylistItems(const std::string &playlistId,
|
||||
const std::string &pageToken = "")
|
||||
-> Result<PageResult<SearchResult>>; // Reusing SearchResult as structure
|
||||
// is similar enough for snippet
|
||||
// ========================================================================
|
||||
// Player API (The "Extraction" Logic)
|
||||
// ========================================================================
|
||||
|
||||
// Returns a raw https://googlevideo.com/... URL for the audio stream.
|
||||
// Returns error if the video is region locked or requires signature
|
||||
// deciphering.
|
||||
auto GetAudioStreamUrl(const std::string &videoId) -> Result<std::string>;
|
||||
|
||||
auto ExtractVideoId(std::string_view url) const -> std::optional<std::string>;
|
||||
|
||||
private:
|
||||
std::string m_ApiKey;
|
||||
std::string m_AccessToken;
|
||||
ProxyConfig m_Proxy;
|
||||
bool m_Verbose = false;
|
||||
const std::string m_BaseUrl = "https://www.googleapis.com/youtube/v3";
|
||||
JSRuntime *m_rt;
|
||||
JSContext *m_ctx;
|
||||
std::string m_preprocessedPlayer;
|
||||
|
||||
// Helper methods for the solver logic
|
||||
void InitSolver();
|
||||
void SetPlayerJs(const std::string &js);
|
||||
std::string SolveChallenge(const std::string &challenge,
|
||||
const std::string &type);
|
||||
auto PerformRequest(
|
||||
const std::string &purl, const std::string &endpoint,
|
||||
const cpr::Parameters ¶ms = {},
|
||||
const cpr::Header &headers =
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
|
||||
HttpMethod method = HttpMethod::GET, const std::string &body = "")
|
||||
-> Result<std::string>;
|
||||
|
||||
auto PerformRequest(
|
||||
const std::string &endpoint, const cpr::Parameters ¶ms = {},
|
||||
const cpr::Header &headers =
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
|
||||
HttpMethod method = HttpMethod::GET, const std::string &body = "")
|
||||
-> Result<std::string>;
|
||||
// Helper specifically for the internal YouTube API (different Base URL)
|
||||
auto PerformInternalRequest(const std::string &endpoint,
|
||||
const std::string &jsonBody)
|
||||
-> Result<std::string>;
|
||||
static auto WriteCallback(void *contents, size_t size, size_t nmemb,
|
||||
std::string *out) -> size_t;
|
||||
auto UrlEncode(std::string_view value) const -> std::string;
|
||||
auto UrlEncodePreservingOperators(std::string_view query) const
|
||||
-> std::string;
|
||||
};
|
||||
|
||||
} // namespace YouTube
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
}
|
||||
enum class DecodeStatus { Idle, Processing, Completed, Failed, Cancelled };
|
||||
class AudioDecoder {
|
||||
public:
|
||||
struct AudioData {
|
||||
std::vector<short> buffer;
|
||||
int samples = 0;
|
||||
int channels = 0;
|
||||
int sampleRate = 0;
|
||||
};
|
||||
std::deque<std::vector<short>> m_chunkQueue;
|
||||
std::mutex m_queueMtx;
|
||||
std::condition_variable m_cv;
|
||||
std::atomic<bool> m_isDecodingFinished{false};
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
void StartDecode(const std::string &url, int targetSampleRate);
|
||||
void Cancel() { m_cancelRequested = true; }
|
||||
DecodeStatus GetStatus() const { return m_status; }
|
||||
AudioData GetResult() { return std::move(m_result); }
|
||||
bool GetNextChunk(std::vector<short> &outChunk, bool blocking = false);
|
||||
bool IsFinished() const { return m_finished.load(); }
|
||||
|
||||
private:
|
||||
void Log(const std::string &msg) {
|
||||
std::lock_guard<std::mutex> lock(m_logMtx);
|
||||
std::cout << "[AudioDecoder] " << msg << std::endl;
|
||||
}
|
||||
void Cleanup();
|
||||
void InternalDecode(std::string url, int targetSampleRate);
|
||||
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
|
||||
std::atomic<bool> m_cancelRequested{false};
|
||||
std::jthread m_thread;
|
||||
std::mutex m_logMtx;
|
||||
AudioData m_result;
|
||||
std::atomic<bool> m_finished{false};
|
||||
AVFormatContext *m_formatCtx = nullptr;
|
||||
AVCodecContext *m_codecCtx = nullptr;
|
||||
SwrContext *m_swrCtx = nullptr;
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <singleton_atomic.hpp>
|
||||
#include <string>
|
||||
#include <ts6bot/Proxy.hpp>
|
||||
|
||||
#include <glaze/glaze.hpp>
|
||||
|
||||
namespace ts6bot {
|
||||
|
||||
enum class LogLevel { Critical, Error, Warning, Info, Trace };
|
||||
|
||||
struct ServerQueryConfig {
|
||||
std::string host{"127.0.0.1"};
|
||||
uint16_t port{
|
||||
10022}; // ServerQuery SSH default :contentReference[oaicite:6]{index=6}
|
||||
std::string username{"serveradmin"};
|
||||
std::string password{};
|
||||
int virtual_server_id{1};
|
||||
std::string nickname{"ts6bot"};
|
||||
};
|
||||
|
||||
struct AfkConfig {
|
||||
bool enabled{true};
|
||||
int idle_seconds{600};
|
||||
std::uint64_t afk_channel_id{0};
|
||||
int poll_interval_ms{5000};
|
||||
};
|
||||
|
||||
struct MusicConfig {
|
||||
bool enabled{true};
|
||||
std::string youtubeApiToken;
|
||||
};
|
||||
|
||||
struct ProxyConfiguration : public ProxyConfig {
|
||||
bool enabled{false};
|
||||
};
|
||||
|
||||
struct Config {
|
||||
std::string nickname;
|
||||
std::string host;
|
||||
std::string channel;
|
||||
std::string password;
|
||||
LogLevel loggingLevel;
|
||||
AfkConfig afk{};
|
||||
MusicConfig music{};
|
||||
ProxyConfiguration proxy{};
|
||||
};
|
||||
|
||||
class Configuration : public SingletonAtomic<Configuration> {
|
||||
public:
|
||||
const Config getConfig() const noexcept { return m_config; }
|
||||
|
||||
Configuration(std::string path) {
|
||||
auto config = Config();
|
||||
std::string buffer;
|
||||
auto ec = glz::read_file_json(config, path, buffer);
|
||||
if (ec) {
|
||||
std::string descriptive_error = glz::format_error(ec, buffer);
|
||||
std::cerr << "Not found configuration in " << path << " using default"
|
||||
<< std::endl;
|
||||
std::cerr << descriptive_error << std::endl;
|
||||
std::cerr << ec.ec << std::endl;
|
||||
m_config = Config();
|
||||
}
|
||||
this->m_config = config;
|
||||
}
|
||||
|
||||
Config m_config{};
|
||||
};
|
||||
|
||||
// Glaze meta (explicit, stable)
|
||||
|
||||
} // namespace ts6bot
|
||||
template <> struct glz::meta<ProxyType> {
|
||||
using enum ProxyType;
|
||||
static constexpr auto value = enumerate(HTTP, SOCKS5, SOCKS5_HOSTNAME);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::LogLevel> {
|
||||
using enum ts6bot::LogLevel;
|
||||
static constexpr auto value =
|
||||
enumerate(Critical, Error, Warning, Info, Trace);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::ServerQueryConfig> {
|
||||
using T = ts6bot::ServerQueryConfig;
|
||||
static constexpr auto value =
|
||||
object("host", &T::host, "port", &T::port, "username", &T::username,
|
||||
"password", &T::password, "virtual_server_id",
|
||||
&T::virtual_server_id, "nickname", &T::nickname);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<ts6bot::AfkConfig> {
|
||||
using T = ts6bot::AfkConfig;
|
||||
static constexpr auto value =
|
||||
object("enabled", &T::enabled, "idle_seconds", &T::idle_seconds,
|
||||
"afk_channel_id", &T::afk_channel_id, "poll_interval_ms",
|
||||
&T::poll_interval_ms);
|
||||
};
|
||||
|
||||
template <> struct glz::meta<ts6bot::MusicConfig> {
|
||||
using T = ts6bot::MusicConfig;
|
||||
static constexpr auto value =
|
||||
object("enabled", &T::enabled, "youtubeApiToken", &T::youtubeApiToken);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::ProxyConfiguration> {
|
||||
using T = ts6bot::ProxyConfiguration;
|
||||
static constexpr auto value =
|
||||
object("url", &T::url, "username", &T::username, "password", &T::password,
|
||||
"type", &T::type, "enabled", &T::enabled);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::Config> {
|
||||
using T = ts6bot::Config;
|
||||
static constexpr auto value =
|
||||
object("nickname", &T::nickname, "host", &T::host, "channel", &T::channel,
|
||||
"password", &T::password, "loggingLevel", &T::loggingLevel, "afk",
|
||||
&T::afk, "music", &T::music, "proxy", &T::proxy);
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ts6bot::crypto {
|
||||
|
||||
// RFC 7636: length 43..128, chars [A-Z a-z 0-9 - . _ ~]
|
||||
std::string GenerateCodeVerifier(std::size_t length = 64);
|
||||
|
||||
// Random state value (base64url, no padding).
|
||||
std::string GenerateState(std::size_t bytes = 16);
|
||||
|
||||
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data);
|
||||
std::vector<std::uint8_t> Sha256(std::span<const char> data);
|
||||
|
||||
// Base64url encode without padding.
|
||||
std::string Base64UrlEncode(std::span<const std::uint8_t> data);
|
||||
|
||||
} // namespace ts6bot::crypto
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include <string_view>
|
||||
|
||||
#include "quill/Backend.h"
|
||||
#include "quill/Frontend.h"
|
||||
#include "quill/LogMacros.h"
|
||||
#include "quill/Logger.h"
|
||||
#include "quill/sinks/FileSink.h"
|
||||
#include "quill/sinks/ConsoleSink.h"
|
||||
|
||||
namespace ts6bot {
|
||||
|
||||
class Log {
|
||||
public:
|
||||
static void init(std::string_view file_path);
|
||||
static quill::Logger* logger();
|
||||
|
||||
private:
|
||||
static quill::Logger* g_logger;
|
||||
};
|
||||
|
||||
} // namespace ts6bot
|
||||
@@ -0,0 +1,100 @@
|
||||
#include <optional>
|
||||
|
||||
#include "PluginDefinitions.hpp"
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Youtube/Client.hpp"
|
||||
#include <atomic>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <singleton_atomic.hpp>
|
||||
#include <string>
|
||||
#include <teamspeak/public_definitions.h>
|
||||
#include <thread>
|
||||
#include <ts3_functions.h>
|
||||
#include <ts6bot/AudioDecoder.hpp>
|
||||
#include <quill/Logger.h>
|
||||
#include <quill/LogMacros.h>
|
||||
#include <vector>
|
||||
class MusicManager {
|
||||
public:
|
||||
explicit MusicManager(std::shared_ptr<TS3Functions> functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID = 0);
|
||||
~MusicManager();
|
||||
|
||||
struct Music {
|
||||
std::string name;
|
||||
std::string videoId;
|
||||
std::string requestedBy;
|
||||
YouTube::Result<definitions::Streams> streams;
|
||||
};
|
||||
|
||||
// Playback Control
|
||||
void stop();
|
||||
void skip();
|
||||
void forceSkip();
|
||||
void setStopAfterCurrent(bool val) { m_stopAfterCurrent = val; }
|
||||
bool isIdle() const { return m_isIdle; }
|
||||
std::uint64_t getServerConnectionHandlerID() const
|
||||
{return m_serverConnectionHandlerID; }
|
||||
void setServerConnectionHandlerID(std::uint64_t id) { m_serverConnectionHandlerID = id; }
|
||||
// Subscription (Whisper) Management
|
||||
void subscribe(anyID id);
|
||||
void moveSubscriberToOffline(anyID id);
|
||||
void moveSubscriberToOnline(anyID id);
|
||||
void addSubscriberToOnline(anyID id);
|
||||
void addSubscriberToOffline(anyID id);
|
||||
void unSubscribe(anyID id);
|
||||
std::set<uint64_t> getOnlineSubscribers() const;
|
||||
std::set<uint64_t> getOfflineSubscribers() const;
|
||||
// Queue Management
|
||||
std::vector<Music> getQueue() const;
|
||||
std::optional<Music> getCurrent() const { return m_current; }
|
||||
void removeFromQueue(std::size_t index);
|
||||
void removeFromQueue(const std::string &name);
|
||||
void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& req, std::optional<definitions::Streams> streams);
|
||||
void checkQueueAndPlay();
|
||||
|
||||
// Youtube / Search
|
||||
std::vector<definitions::SearchResultItem> search(std::string name, int maxResults = 5) const;
|
||||
void playUrl(std::string url, const std::string &requester = "");
|
||||
|
||||
// Selection Logic
|
||||
// Stores the results for a specific user to select later
|
||||
void storePendingSearch(anyID clientId,
|
||||
const std::vector<definitions::SearchResultItem> &results);
|
||||
bool selectSearchResult(anyID clientId, int index, const std::string& requesterName);
|
||||
|
||||
private:
|
||||
void loop(std::stop_token st);
|
||||
static std::string formatDuration(const std::string &isoDuration);
|
||||
void updateWhisperList();
|
||||
|
||||
quill::Logger* m_logger;
|
||||
std::shared_ptr<TS3Functions> m_functions{nullptr};
|
||||
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
|
||||
std::unique_ptr<YouTube::Client> m_client{nullptr};
|
||||
|
||||
|
||||
std::atomic<bool> m_stopAfterCurrent{false};
|
||||
std::atomic<bool> m_isIdle{true};
|
||||
|
||||
std::deque<Music> m_queue{};
|
||||
mutable std::mutex m_queueMtx;
|
||||
std::condition_variable m_cv;
|
||||
|
||||
std::set<anyID> m_onlineSubscribers;
|
||||
std::set<anyID> m_offlineSubscribers;
|
||||
// Playback Control
|
||||
std::atomic_bool m_skipRequested{false};
|
||||
|
||||
std::atomic<float> m_volume{0.5f}; // Default 50%
|
||||
std::uint64_t m_serverConnectionHandlerID = 0;
|
||||
std::optional<Music> m_current;
|
||||
std::mutex m_subMtx;
|
||||
std::map<anyID, std::vector<definitions::SearchResultItem>> m_pendingSearches;
|
||||
std::mutex m_pendingMtx;
|
||||
std::jthread m_worker;
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
enum class ProxyType {
|
||||
HTTP,
|
||||
SOCKS5,
|
||||
SOCKS5_HOSTNAME // Use this to let the proxy resolve the DNS
|
||||
};
|
||||
struct ProxyConfig {
|
||||
std::string url;
|
||||
ProxyType type = ProxyType::SOCKS5_HOSTNAME;
|
||||
std::string username = "";
|
||||
std::string password = "";
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
|
||||
class SignalShutdown {
|
||||
public:
|
||||
explicit SignalShutdown(std::function<void()> onShutdown);
|
||||
~SignalShutdown();
|
||||
|
||||
SignalShutdown(const SignalShutdown&) = delete;
|
||||
SignalShutdown& operator=(const SignalShutdown&) = delete;
|
||||
|
||||
private:
|
||||
std::function<void()> m_OnShutdown;
|
||||
std::thread m_Thread;
|
||||
bool m_Running = true;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace ts6bot::url {
|
||||
|
||||
// Percent-encode a string for use as a query parameter value.
|
||||
std::string EncodeComponent(const std::string& s);
|
||||
|
||||
struct HttpUrl {
|
||||
std::string host;
|
||||
uint16_t port{};
|
||||
std::string path; // begins with '/'
|
||||
};
|
||||
|
||||
// Minimal parser for redirect URIs.
|
||||
// Supports: http://<host>:<port>/<path>
|
||||
// Throws std::runtime_error on invalid input.
|
||||
HttpUrl ParseHttpUrl(const std::string& httpUrl);
|
||||
|
||||
} // namespace ts6bot::url
|
||||
@@ -0,0 +1,114 @@
|
||||
#pragma once
|
||||
|
||||
#include "Spotify/Client.hpp"
|
||||
#include <gst/gst.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <print>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
struct GstObjectDeleter {
|
||||
void operator()(gpointer ptr) const noexcept {
|
||||
if (ptr)
|
||||
gst_object_unref(ptr);
|
||||
}
|
||||
};
|
||||
|
||||
struct GstMessageDeleter {
|
||||
void operator()(GstMessage *msg) const noexcept {
|
||||
if (msg)
|
||||
gst_message_unref(msg);
|
||||
}
|
||||
};
|
||||
|
||||
class VirtualMicrophone {
|
||||
public:
|
||||
// micName: what apps will see/select (e.g. "StudioMic")
|
||||
explicit VirtualMicrophone(std::string micName, bool createNew);
|
||||
~VirtualMicrophone() noexcept;
|
||||
|
||||
// Play Spotify track via gstspotify spotifyaudiosrc and route into the
|
||||
// virtual microphone.
|
||||
void PlayUri(const std::string &trackUri, const std::string &token,
|
||||
const ProxyConfig &proxy);
|
||||
void PlayUri(const std::string &trackUri,
|
||||
const std::optional<ProxyConfig> proxy);
|
||||
// Playback control
|
||||
void Pause();
|
||||
void Resume();
|
||||
void StopPlayback(); // stops pipeline (does not destroy devices)
|
||||
void WaitUntilFinished(); // waits EOS or ERROR; throws on ERROR
|
||||
|
||||
// Device control (normally you don't call these directly)
|
||||
void DestroyDevices() noexcept;
|
||||
|
||||
// For debugging / integration
|
||||
[[nodiscard]] const std::string &MicName() const noexcept {
|
||||
return m_MicName;
|
||||
}
|
||||
[[nodiscard]] const std::string &BusSinkName() const noexcept {
|
||||
return m_BusSinkName;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string m_MicName; // virtual mic node name (Audio/Source/Virtual)
|
||||
std::string m_BusSinkName; // bus sink name (Audio/Sink)
|
||||
|
||||
// Pulse/PipeWire module ids
|
||||
uint32_t m_ModBusSink = 0;
|
||||
uint32_t m_ModVirtualMic = 0;
|
||||
|
||||
// pw-link ports we connected (for disconnection)
|
||||
std::optional<std::string> m_LinkOutFL;
|
||||
std::optional<std::string> m_LinkOutFR;
|
||||
std::optional<std::string> m_LinkInFL;
|
||||
std::optional<std::string> m_LinkInFR;
|
||||
|
||||
// GStreamer pipeline
|
||||
std::unique_ptr<GstElement, GstObjectDeleter> m_Pipeline;
|
||||
std::jthread m_BusThread;
|
||||
|
||||
// completion signalling
|
||||
std::mutex m_Mtx;
|
||||
std::condition_variable m_Cv;
|
||||
bool m_Finished = true;
|
||||
bool m_HadError = false;
|
||||
std::string m_LastError;
|
||||
|
||||
private:
|
||||
// startup behavior
|
||||
void CleanupStaleDevicesByName();
|
||||
|
||||
// create routing: bus sink + virtual mic + pw-link
|
||||
void CreateDevices();
|
||||
void CreateLinks();
|
||||
|
||||
// pipeline lifecycle
|
||||
void BuildAndStartPipeline(const std::string &pipelineDesc);
|
||||
void WatchBus(std::stop_token st);
|
||||
|
||||
// utilities
|
||||
static std::string RunCommandCapture(const std::string &cmd);
|
||||
static int RunCommandNoCapture(const std::string &cmd);
|
||||
static uint32_t ParseFirstUint(std::string_view s);
|
||||
|
||||
static std::vector<std::string> SplitLines(const std::string &s);
|
||||
static bool Contains(std::string_view hay, std::string_view needle);
|
||||
|
||||
// pw-link helpers
|
||||
static std::vector<std::string> PwLinkListOutputs();
|
||||
static std::vector<std::string> PwLinkListInputs();
|
||||
static std::optional<std::string>
|
||||
FindPortPrefix(const std::vector<std::string> &list, std::string_view prefix,
|
||||
std::string_view suffix);
|
||||
};
|
||||
@@ -0,0 +1,360 @@
|
||||
#pragma once
|
||||
#include "teamspeak/public_definitions.h"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <string>
|
||||
#include <ts3_functions.h>
|
||||
#include <vector>
|
||||
|
||||
// --- STATE STRUCTURES (Serialized by Glaze) ---
|
||||
// --- THE INTERFACE ---
|
||||
|
||||
class IEchoionPlugin {
|
||||
public:
|
||||
virtual ~IEchoionPlugin() = default;
|
||||
|
||||
// Lifecycle
|
||||
virtual void Initialize(bool start = true) = 0;
|
||||
virtual void Shutdown() = 0;
|
||||
|
||||
// Hot Reload State
|
||||
virtual std::string SerializeState() = 0;
|
||||
virtual void DeserializeState(const std::string &jsonState) = 0;
|
||||
|
||||
// Graceful Update
|
||||
virtual void RequestGracefulStop() = 0; // "Finish current track then stop"
|
||||
virtual bool IsStopped() = 0; // "I am idle, threads joined, safe to unload"
|
||||
|
||||
// Events
|
||||
virtual void onConnectStatusChangeEvent(uint64 serverConnectionHandlerID,
|
||||
int newStatus,
|
||||
unsigned int errorNumber) = 0;
|
||||
virtual void onNewChannelEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, uint64 channelParentID) = 0;
|
||||
virtual void
|
||||
onNewChannelCreatedEvent(uint64 serverConnectionHandlerID, uint64 channelID,
|
||||
uint64 channelParentID, anyID invokerID,
|
||||
const char *invokerName,
|
||||
const char *invokerUniqueIdentifier) = 0;
|
||||
virtual void onDelChannelEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, anyID invokerID,
|
||||
const char *invokerName,
|
||||
const char *invokerUniqueIdentifier) = 0;
|
||||
virtual void onChannelMoveEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, uint64 newChannelParentID,
|
||||
anyID invokerID, const char *invokerName,
|
||||
const char *invokerUniqueIdentifier) = 0;
|
||||
virtual void onUpdateChannelEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID) = 0;
|
||||
virtual void
|
||||
onUpdateChannelEditedEvent(uint64 serverConnectionHandlerID, uint64 channelID,
|
||||
anyID invokerID, const char *invokerName,
|
||||
const char *invokerUniqueIdentifier) = 0;
|
||||
virtual void onUpdateClientEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, anyID invokerID,
|
||||
const char *invokerName,
|
||||
const char *invokerUniqueIdentifier) = 0;
|
||||
virtual void onClientMoveEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, uint64 oldChannelID,
|
||||
uint64 newChannelID, int visibility,
|
||||
const char *moveMessage) = 0;
|
||||
virtual void onClientMoveSubscriptionEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID,
|
||||
uint64 oldChannelID,
|
||||
uint64 newChannelID,
|
||||
int visibility) = 0;
|
||||
virtual void onClientMoveTimeoutEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, uint64 oldChannelID,
|
||||
uint64 newChannelID, int visibility,
|
||||
const char *timeoutMessage) = 0;
|
||||
virtual void onClientMoveMovedEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, uint64 oldChannelID,
|
||||
uint64 newChannelID, int visibility,
|
||||
anyID moverID, const char *moverName,
|
||||
const char *moverUniqueIdentifier,
|
||||
const char *moveMessage) = 0;
|
||||
virtual void onClientKickFromChannelEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, uint64 oldChannelID,
|
||||
uint64 newChannelID, int visibility,
|
||||
anyID kickerID,
|
||||
const char *kickerName,
|
||||
const char *kickerUniqueIdentifier,
|
||||
const char *kickMessage) = 0;
|
||||
virtual void onClientKickFromServerEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, uint64 oldChannelID,
|
||||
uint64 newChannelID, int visibility,
|
||||
anyID kickerID,
|
||||
const char *kickerName,
|
||||
const char *kickerUniqueIdentifier,
|
||||
const char *kickMessage) = 0;
|
||||
virtual void onClientIDsEvent(uint64 serverConnectionHandlerID,
|
||||
const char *uniqueClientIdentifier,
|
||||
anyID clientID, const char *clientName) = 0;
|
||||
virtual void onClientIDsFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onServerEditedEvent(uint64 serverConnectionHandlerID,
|
||||
anyID editerID, const char *editerName,
|
||||
const char *editerUniqueIdentifier) = 0;
|
||||
virtual void onServerUpdatedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual int onServerErrorEvent(uint64 serverConnectionHandlerID,
|
||||
const char *errorMessage, unsigned int error,
|
||||
const char *returnCode,
|
||||
const char *extraMessage) = 0;
|
||||
virtual void onServerStopEvent(uint64 serverConnectionHandlerID,
|
||||
const char *shutdownMessage) = 0;
|
||||
virtual int onTextMessageEvent(uint64 serverConnectionHandlerID,
|
||||
anyID targetMode, anyID toID, anyID fromID,
|
||||
const char *fromName,
|
||||
const char *fromUniqueIdentifier,
|
||||
const char *message, int ffIgnored) = 0;
|
||||
virtual void onTalkStatusChangeEvent(uint64 serverConnectionHandlerID,
|
||||
int status, int isReceivedWhisper,
|
||||
anyID clientID) = 0;
|
||||
virtual void onConnectionInfoEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID) = 0;
|
||||
virtual void
|
||||
onServerConnectionInfoEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onChannelSubscribeEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID) = 0;
|
||||
virtual void
|
||||
onChannelSubscribeFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onChannelUnsubscribeEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID) = 0;
|
||||
virtual void
|
||||
onChannelUnsubscribeFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onChannelDescriptionUpdateEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID) = 0;
|
||||
virtual void onChannelPasswordChangedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID) = 0;
|
||||
virtual void
|
||||
onPlaybackShutdownCompleteEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onSoundDeviceListChangedEvent(const char *modeID,
|
||||
int playOrCap) = 0;
|
||||
virtual void onEditPlaybackVoiceDataEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, short *samples,
|
||||
int sampleCount, int channels) = 0;
|
||||
virtual void onEditPostProcessVoiceDataEvent(
|
||||
uint64 serverConnectionHandlerID, anyID clientID, short *samples,
|
||||
int sampleCount, int channels, const unsigned int *channelSpeakerArray,
|
||||
unsigned int *channelFillMask) = 0;
|
||||
virtual void onEditMixedPlaybackVoiceDataEvent(
|
||||
uint64 serverConnectionHandlerID, short *samples, int sampleCount,
|
||||
int channels, const unsigned int *channelSpeakerArray,
|
||||
unsigned int *channelFillMask) = 0;
|
||||
virtual void onEditCapturedVoiceDataEvent(uint64 serverConnectionHandlerID,
|
||||
short *samples, int sampleCount,
|
||||
int channels, int *edited) = 0;
|
||||
virtual void
|
||||
onCustom3dRolloffCalculationClientEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, float distance,
|
||||
float *volume) = 0;
|
||||
virtual void
|
||||
onCustom3dRolloffCalculationWaveEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 waveHandle, float distance,
|
||||
float *volume) = 0;
|
||||
virtual void onUserLoggingMessageEvent(const char *logMessage, int logLevel,
|
||||
const char *logChannel, uint64 logID,
|
||||
const char *logTime,
|
||||
const char *completeLogString) = 0;
|
||||
|
||||
/* Clientlib rare */
|
||||
virtual 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) = 0;
|
||||
virtual int onClientPokeEvent(uint64 serverConnectionHandlerID,
|
||||
anyID fromClientID, const char *pokerName,
|
||||
const char *pokerUniqueIdentity,
|
||||
const char *message, int ffIgnored) = 0;
|
||||
virtual void onClientSelfVariableUpdateEvent(uint64 serverConnectionHandlerID,
|
||||
int flag, const char *oldValue,
|
||||
const char *newValue) = 0;
|
||||
virtual void onFileListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, const char *path,
|
||||
const char *name, uint64 size, uint64 datetime,
|
||||
int type, uint64 incompletesize,
|
||||
const char *returnCode) = 0;
|
||||
virtual void onFileListFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, const char *path) = 0;
|
||||
virtual void onFileInfoEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, const char *name, uint64 size,
|
||||
uint64 datetime) = 0;
|
||||
virtual void onServerGroupListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 serverGroupID, const char *name,
|
||||
int type, int iconID, int saveDB) = 0;
|
||||
virtual void
|
||||
onServerGroupListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onServerGroupByClientIDEvent(uint64 serverConnectionHandlerID,
|
||||
const char *name,
|
||||
uint64 serverGroupList,
|
||||
uint64 clientDatabaseID) = 0;
|
||||
virtual void onServerGroupPermListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 serverGroupID,
|
||||
unsigned int permissionID,
|
||||
int permissionValue,
|
||||
int permissionNegated,
|
||||
int permissionSkip) = 0;
|
||||
virtual void
|
||||
onServerGroupPermListFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 serverGroupID) = 0;
|
||||
virtual void onServerGroupClientListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 serverGroupID,
|
||||
uint64 clientDatabaseID,
|
||||
const char *clientNameIdentifier,
|
||||
const char *clientUniqueID) = 0;
|
||||
virtual void onChannelGroupListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelGroupID, const char *name,
|
||||
int type, int iconID, int saveDB) = 0;
|
||||
virtual void
|
||||
onChannelGroupListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onChannelGroupPermListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelGroupID,
|
||||
unsigned int permissionID,
|
||||
int permissionValue,
|
||||
int permissionNegated,
|
||||
int permissionSkip) = 0;
|
||||
virtual void
|
||||
onChannelGroupPermListFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelGroupID) = 0;
|
||||
virtual void
|
||||
onChannelPermListEvent(uint64 serverConnectionHandlerID, uint64 channelID,
|
||||
unsigned int permissionID, int permissionValue,
|
||||
int permissionNegated, int permissionSkip) = 0;
|
||||
virtual void onChannelPermListFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID) = 0;
|
||||
virtual void onClientPermListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 clientDatabaseID,
|
||||
unsigned int permissionID,
|
||||
int permissionValue, int permissionNegated,
|
||||
int permissionSkip) = 0;
|
||||
virtual void onClientPermListFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 clientDatabaseID) = 0;
|
||||
virtual void
|
||||
onChannelClientPermListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID, uint64 clientDatabaseID,
|
||||
unsigned int permissionID, int permissionValue,
|
||||
int permissionNegated, int permissionSkip) = 0;
|
||||
virtual void
|
||||
onChannelClientPermListFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 channelID,
|
||||
uint64 clientDatabaseID) = 0;
|
||||
virtual void onClientChannelGroupChangedEvent(
|
||||
uint64 serverConnectionHandlerID, uint64 channelGroupID, uint64 channelID,
|
||||
anyID clientID, anyID invokerClientID, const char *invokerName,
|
||||
const char *invokerUniqueIdentity) = 0;
|
||||
virtual int onServerPermissionErrorEvent(uint64 serverConnectionHandlerID,
|
||||
const char *errorMessage,
|
||||
unsigned int error,
|
||||
const char *returnCode,
|
||||
unsigned int failedPermissionID) = 0;
|
||||
virtual void onPermissionListGroupEndIDEvent(uint64 serverConnectionHandlerID,
|
||||
unsigned int groupEndID) = 0;
|
||||
virtual void onPermissionListEvent(uint64 serverConnectionHandlerID,
|
||||
unsigned int permissionID,
|
||||
const char *permissionName,
|
||||
const char *permissionDescription) = 0;
|
||||
virtual void
|
||||
onPermissionListFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onPermissionOverviewEvent(
|
||||
uint64 serverConnectionHandlerID, uint64 clientDatabaseID,
|
||||
uint64 channelID, int overviewType, uint64 overviewID1,
|
||||
uint64 overviewID2, unsigned int permissionID, int permissionValue,
|
||||
int permissionNegated, int permissionSkip) = 0;
|
||||
virtual void
|
||||
onPermissionOverviewFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onServerGroupClientAddedEvent(
|
||||
uint64 serverConnectionHandlerID, anyID clientID, const char *clientName,
|
||||
const char *clientUniqueIdentity, uint64 serverGroupID,
|
||||
anyID invokerClientID, const char *invokerName,
|
||||
const char *invokerUniqueIdentity) = 0;
|
||||
virtual void onServerGroupClientDeletedEvent(
|
||||
uint64 serverConnectionHandlerID, anyID clientID, const char *clientName,
|
||||
const char *clientUniqueIdentity, uint64 serverGroupID,
|
||||
anyID invokerClientID, const char *invokerName,
|
||||
const char *invokerUniqueIdentity) = 0;
|
||||
virtual void onClientNeededPermissionsEvent(uint64 serverConnectionHandlerID,
|
||||
unsigned int permissionID,
|
||||
int permissionValue) = 0;
|
||||
virtual void
|
||||
onClientNeededPermissionsFinishedEvent(uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onFileTransferStatusEvent(anyID transferID, unsigned int status,
|
||||
const char *statusMessage,
|
||||
uint64 remotefileSize,
|
||||
uint64 serverConnectionHandlerID) = 0;
|
||||
virtual void onClientChatClosedEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID,
|
||||
const char *clientUniqueIdentity) = 0;
|
||||
virtual void onClientChatComposingEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID,
|
||||
const char *clientUniqueIdentity) = 0;
|
||||
virtual void onServerLogEvent(uint64 serverConnectionHandlerID,
|
||||
const char *logMsg) = 0;
|
||||
virtual void onServerLogFinishedEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 lastPos, uint64 fileSize) = 0;
|
||||
virtual void onMessageListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 messageID,
|
||||
const char *fromClientUniqueIdentity,
|
||||
const char *subject, uint64 timestamp,
|
||||
int flagRead) = 0;
|
||||
virtual void onMessageGetEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 messageID,
|
||||
const char *fromClientUniqueIdentity,
|
||||
const char *subject, const char *message,
|
||||
uint64 timestamp) = 0;
|
||||
virtual void onClientDBIDfromUIDEvent(uint64 serverConnectionHandlerID,
|
||||
const char *uniqueClientIdentifier,
|
||||
uint64 clientDatabaseID) = 0;
|
||||
virtual void onClientNamefromUIDEvent(uint64 serverConnectionHandlerID,
|
||||
const char *uniqueClientIdentifier,
|
||||
uint64 clientDatabaseID,
|
||||
const char *clientNickName) = 0;
|
||||
virtual void onClientNamefromDBIDEvent(uint64 serverConnectionHandlerID,
|
||||
const char *uniqueClientIdentifier,
|
||||
uint64 clientDatabaseID,
|
||||
const char *clientNickName) = 0;
|
||||
virtual void onComplainListEvent(uint64 serverConnectionHandlerID,
|
||||
uint64 targetClientDatabaseID,
|
||||
const char *targetClientNickName,
|
||||
uint64 fromClientDatabaseID,
|
||||
const char *fromClientNickName,
|
||||
const char *complainReason,
|
||||
uint64 timestamp) = 0;
|
||||
virtual 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) = 0;
|
||||
virtual void
|
||||
onClientServerQueryLoginPasswordEvent(uint64 serverConnectionHandlerID,
|
||||
const char *loginPassword) = 0;
|
||||
virtual void onPluginCommandEvent(uint64 serverConnectionHandlerID,
|
||||
const char *pluginName,
|
||||
const char *pluginCommand,
|
||||
anyID invokerClientID,
|
||||
const char *invokerName,
|
||||
const char *invokerUniqueIdentity) = 0;
|
||||
virtual void onIncomingClientQueryEvent(uint64 serverConnectionHandlerID,
|
||||
const char *commandText) = 0;
|
||||
virtual 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) = 0;
|
||||
|
||||
/* Client UI callbacks */
|
||||
virtual void onAvatarUpdated(uint64 serverConnectionHandlerID, anyID clientID,
|
||||
const char *avatarPath) = 0;
|
||||
virtual void onMenuItemEvent(uint64 serverConnectionHandlerID,
|
||||
enum PluginMenuType type, int menuItemID,
|
||||
uint64 selectedItemID) = 0;
|
||||
virtual void onHotkeyEvent(const char *keyword) = 0;
|
||||
virtual void onHotkeyRecordedEvent(const char *keyword, const char *key) = 0;
|
||||
virtual void
|
||||
onClientDisplayNameChanged(uint64 serverConnectionHandlerID, anyID clientID,
|
||||
const char *displayName,
|
||||
const char *uniqueClientIdentifier) = 0;
|
||||
};
|
||||
|
||||
typedef IEchoionPlugin *(*CreatePluginFunc)(const TS3Functions* funcs);
|
||||
typedef void (*DestroyPluginFunc)(const IEchoionPlugin *);
|
||||
@@ -0,0 +1,53 @@
|
||||
#ifndef PLUGIN_DEFINITIONS
|
||||
#define PLUGIN_DEFINITIONS
|
||||
|
||||
/* Return values for ts3plugin_offersConfigure */
|
||||
enum PluginConfigureOffer {
|
||||
PLUGIN_OFFERS_NO_CONFIGURE = 0, /* Plugin does not implement ts3plugin_configure */
|
||||
PLUGIN_OFFERS_CONFIGURE_NEW_THREAD, /* Plugin does implement ts3plugin_configure and requests to run this function in an own thread */
|
||||
PLUGIN_OFFERS_CONFIGURE_QT_THREAD /* Plugin does implement ts3plugin_configure and requests to run this function in the Qt GUI thread */
|
||||
};
|
||||
|
||||
enum PluginMessageTarget { PLUGIN_MESSAGE_TARGET_SERVER = 0, PLUGIN_MESSAGE_TARGET_CHANNEL };
|
||||
|
||||
enum PluginItemType { PLUGIN_SERVER = 0, PLUGIN_CHANNEL, PLUGIN_CLIENT };
|
||||
|
||||
enum PluginMenuType { PLUGIN_MENU_TYPE_GLOBAL = 0, PLUGIN_MENU_TYPE_CHANNEL, PLUGIN_MENU_TYPE_CLIENT };
|
||||
|
||||
#define PLUGIN_MENU_BUFSZ 128
|
||||
|
||||
struct PluginMenuItem {
|
||||
enum PluginMenuType type;
|
||||
int id;
|
||||
char text[PLUGIN_MENU_BUFSZ];
|
||||
char icon[PLUGIN_MENU_BUFSZ];
|
||||
};
|
||||
|
||||
#define PLUGIN_HOTKEY_BUFSZ 128
|
||||
|
||||
struct PluginHotkey {
|
||||
char keyword[PLUGIN_HOTKEY_BUFSZ];
|
||||
char description[PLUGIN_HOTKEY_BUFSZ];
|
||||
};
|
||||
|
||||
struct PluginBookmarkList;
|
||||
struct PluginBookmarkItem {
|
||||
char* name;
|
||||
unsigned char isFolder;
|
||||
unsigned char reserved[3];
|
||||
union {
|
||||
char* uuid;
|
||||
struct PluginBookmarkList* folder;
|
||||
};
|
||||
};
|
||||
|
||||
struct PluginBookmarkList {
|
||||
int itemcount;
|
||||
struct PluginBookmarkItem items[1]; //should be 0 but compiler complains
|
||||
};
|
||||
|
||||
enum PluginGuiProfile { PLUGIN_GUI_SOUND_CAPTURE = 0, PLUGIN_GUI_SOUND_PLAYBACK, PLUGIN_GUI_HOTKEY, PLUGIN_GUI_SOUNDPACK, PLUGIN_GUI_IDENTITY };
|
||||
|
||||
enum PluginConnectTab { PLUGIN_CONNECT_TAB_NEW = 0, PLUGIN_CONNECT_TAB_CURRENT, PLUGIN_CONNECT_TAB_NEW_IF_CURRENT_CONNECTED };
|
||||
|
||||
#endif
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#ifndef TEAMLOG_LOGTYPES_H
|
||||
#define TEAMLOG_LOGTYPES_H
|
||||
|
||||
enum LogTypes {
|
||||
LogType_NONE = 0x0000, ///< Logging is disabled
|
||||
LogType_FILE = 0x0001, ///< Log to regular log file
|
||||
LogType_CONSOLE = 0x0002, ///< Log to standard output / error
|
||||
LogType_USERLOGGING = 0x0004, ///< User defined logging. Will call the \ref ServerLibFunctions.onUserLoggingMessageEvent callback for every message to be logged
|
||||
LogType_NO_NETLOGGING = 0x0008, ///< Not used
|
||||
LogType_DATABASE = 0x0010, ///< Log to database (deprecated, server only, no effect in SDK)
|
||||
LogType_SYSLOG = 0x0020, ///< Log to syslog (only available on Linux)
|
||||
};
|
||||
|
||||
enum LogLevel {
|
||||
LogLevel_CRITICAL = 0, ///< these messages stop the program
|
||||
LogLevel_ERROR, ///< everything that is really bad, but not so bad we need to shut down
|
||||
LogLevel_WARNING, ///< everything that *might* be bad
|
||||
LogLevel_DEBUG, ///< output that might help find a problem
|
||||
LogLevel_INFO, ///< informational output, like "starting database version x.y.z"
|
||||
LogLevel_DEVEL ///< developer only output (will not be displayed in release mode)
|
||||
};
|
||||
|
||||
#endif //TEAMLOG_LOGTYPES_H
|
||||
@@ -0,0 +1,579 @@
|
||||
#ifndef PUBLIC_DEFINITIONS_H
|
||||
#define PUBLIC_DEFINITIONS_H
|
||||
|
||||
#include "teamlog/logtypes.h"
|
||||
|
||||
#define TS3_MAX_SIZE_CHANNEL_NAME 40 // channel name maximum length in characters
|
||||
#define TS3_MAX_SIZE_VIRTUALSERVER_NAME 64 // virtual server name maximum length in characters
|
||||
#define TS3_MAX_SIZE_CLIENT_NICKNAME 64 // client display name length limit in characters
|
||||
#define TS3_MIN_SIZE_CLIENT_NICKNAME 3 // client display name minimum length in characters
|
||||
#define TS3_MAX_SIZE_REASON_MESSAGE 80 // length limit in characters for kick, move, etc reasons
|
||||
|
||||
#define TS3_MAX_SIZE_TEXTMESSAGE 8192 // text message length limit, measured in bytes (utf8 encoded)
|
||||
#define TS3_MAX_SIZE_CHANNEL_TOPIC 255 // channel topic lengt limith, measured in bytes (utf8 encoded)
|
||||
#define TS3_MAX_SIZE_CHANNEL_DESCRIPTION 8192 // channel description length limit, measured in bytes (utf8 encoded)
|
||||
// server welcome message length limit measured in bytes (utf8 encoded)
|
||||
#define TS3_MAX_SIZE_VIRTUALSERVER_WELCOMEMESSAGE 1024
|
||||
#define TS3_SIZE_MYTSID 44
|
||||
// minimum amount of seconds before a clientID that was in use can be assigned to a new client
|
||||
#define TS3_MIN_SECONDS_CLIENTID_REUSE 300
|
||||
|
||||
#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32)
|
||||
typedef unsigned __int16 anyID;
|
||||
typedef unsigned __int64 uint64;
|
||||
#ifndef EXPORTDLL
|
||||
#ifdef BUILDING_DLL
|
||||
#define EXPORTDLL __declspec(dllexport)
|
||||
#else
|
||||
#define EXPORTDLL
|
||||
#endif
|
||||
#endif
|
||||
#else
|
||||
#include <stdint.h>
|
||||
typedef uint16_t anyID;
|
||||
typedef uint64_t uint64;
|
||||
#ifndef EXPORTDLL
|
||||
#ifdef BUILDING_DLL
|
||||
#define EXPORTDLL __attribute__((visibility("default")))
|
||||
#else
|
||||
#define EXPORTDLL
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
enum Visibility {
|
||||
ENTER_VISIBILITY = 0, ///< Client joined from an unsubscribed channel, or joined the server.
|
||||
RETAIN_VISIBILITY, ///< Client switched from one subscribed channel to a different subscribed channel.
|
||||
LEAVE_VISIBILITY ///< Client switches to an unsubscribed channel, or disconnected from server.
|
||||
};
|
||||
|
||||
enum ConnectStatus {
|
||||
STATUS_DISCONNECTED = 0, ///< There is no activity to the server, this is the default value
|
||||
STATUS_CONNECTING, ///< We are trying to connect, we haven't got a client id yet, we haven't been accepted by the server
|
||||
STATUS_CONNECTED, ///< The server has accepted us, we can talk and hear and we have a client id, but we don't
|
||||
///< have the channels and clients yet, we can get server infos (welcome msg etc.)
|
||||
STATUS_CONNECTION_ESTABLISHING, ///< we are connected and we are visible
|
||||
STATUS_CONNECTION_ESTABLISHED, ///< we are connected and we have the client and channels available
|
||||
};
|
||||
|
||||
enum LocalTestMode { TEST_MODE_OFF = 0, TEST_MODE_VOICE_LOCAL_ONLY, TEST_MODE_VOICE_LOCAL_AND_REMOTE, TEST_MODE_TALK_STATUS_CHANGES_ONLY };
|
||||
|
||||
enum TalkStatus {
|
||||
STATUS_NOT_TALKING = 0, ///< client is not talking
|
||||
STATUS_TALKING = 1, ///< client is talking
|
||||
STATUS_TALKING_WHILE_DISABLED = 2, ///< client is talking while the microphone is muted (only valid for own client)
|
||||
};
|
||||
|
||||
enum CodecType {
|
||||
CODEC_SPEEX_NARROWBAND = 0, ///< (deprecated) mono, 16bit, 8kHz, bitrate dependent on the quality setting
|
||||
CODEC_SPEEX_WIDEBAND, ///< (deprecated) mono, 16bit, 16kHz, bitrate dependent on the quality setting
|
||||
CODEC_SPEEX_ULTRAWIDEBAND, ///< (deprecated) mono, 16bit, 32kHz, bitrate dependent on the quality setting
|
||||
CODEC_CELT_MONO, ///< (deprecated) mono, 16bit, 48kHz, bitrate dependent on the quality setting
|
||||
CODEC_OPUS_VOICE, ///< mono, 16bit, 48khz, bitrate dependent on the quality setting, optimized for voice
|
||||
CODEC_OPUS_MUSIC, ///< stereo, 16bit, 48khz, bitrate dependent on the quality setting, optimized for music
|
||||
};
|
||||
|
||||
enum CodecEncryptionMode {
|
||||
CODEC_ENCRYPTION_PER_CHANNEL = 0, ///< voice data encryption decided per channel
|
||||
CODEC_ENCRYPTION_FORCED_OFF, ///< voice data encryption disabled
|
||||
CODEC_ENCRYPTION_FORCED_ON, ///< voice data encryption enabled
|
||||
};
|
||||
|
||||
enum TextMessageTargetMode {
|
||||
TextMessageTarget_CLIENT = 1, ///< Message is a private message to another client
|
||||
TextMessageTarget_CHANNEL, ///< Message is sent to a channel, received by all clients in that channel at the time
|
||||
TextMessageTarget_SERVER, ///< Message is sent to every client on the server
|
||||
TextMessageTarget_MAX
|
||||
};
|
||||
|
||||
enum MuteInputStatus {
|
||||
MUTEINPUT_NONE = 0, ///< Microphone is not muted, audio is sent to the server
|
||||
MUTEINPUT_MUTED, ///< Microphone is muted, no audio is transmitted to the server
|
||||
};
|
||||
|
||||
enum MuteOutputStatus {
|
||||
MUTEOUTPUT_NONE = 0, ///< Speaker is active, server is sending us audio
|
||||
MUTEOUTPUT_MUTED, ///< Speaker is muted, server is not sending audio to us
|
||||
};
|
||||
|
||||
enum HardwareInputStatus {
|
||||
HARDWAREINPUT_DISABLED = 0, ///< no capture device opened
|
||||
HARDWAREINPUT_ENABLED, ///< capture device open
|
||||
};
|
||||
|
||||
enum HardwareOutputStatus {
|
||||
HARDWAREOUTPUT_DISABLED = 0, ///< no playback device opened
|
||||
HARDWAREOUTPUT_ENABLED, ///< playback device open
|
||||
};
|
||||
|
||||
enum InputDeactivationStatus {
|
||||
INPUT_ACTIVE = 0, ///< Audio is captured from the capture device.
|
||||
INPUT_DEACTIVATED = 1, ///< No audio is captured from the capture device.
|
||||
};
|
||||
|
||||
enum ReasonIdentifier {
|
||||
REASON_NONE = 0, ///< no reason data
|
||||
REASON_MOVED = 1, ///< client was moved
|
||||
REASON_SUBSCRIPTION = 2, // no reason data
|
||||
REASON_LOST_CONNECTION = 3, // reasonmsg=reason
|
||||
REASON_KICK_CHANNEL = 4, //{SectionInvoker} reasonmsg=reason //{SectionInvoker} is only added server->client
|
||||
REASON_KICK_SERVER = 5, //{SectionInvoker} reasonmsg=reason //{SectionInvoker} is only added server->client
|
||||
REASON_KICK_SERVER_BAN = 6, //{SectionInvoker} reasonmsg=reason bantime=time //{SectionInvoker} is only added server->client
|
||||
REASON_SERVERSTOP = 7, // reasonmsg=reason
|
||||
REASON_CLIENTDISCONNECT = 8, // reasonmsg=reason
|
||||
REASON_CHANNELUPDATE = 9, // no reason data
|
||||
REASON_CHANNELEDIT = 10, //{SectionInvoker}
|
||||
REASON_CLIENTDISCONNECT_SERVER_SHUTDOWN = 11, // reasonmsg=reason
|
||||
};
|
||||
|
||||
enum Protocol_Encryption_Cipher { AES_128 = 0, AES_256, PROTOCOL_ENCRYPTION_CIPHER_END_MARKER };
|
||||
|
||||
enum ChannelProperties {
|
||||
CHANNEL_NAME = 0, ///< String. Read/Write. Name of the channel. Always available.
|
||||
CHANNEL_TOPIC, ///< String. Read/Write. Short single line text describing what the channel is about. Always available.
|
||||
CHANNEL_DESCRIPTION, ///< String. Read/Write. Arbitrary text (up to 8k bytes) with information about the channel.
|
||||
///< Must be requested (\ref ts3client_requestChannelDescription)
|
||||
CHANNEL_PASSWORD, ///< String. Read/Write. Password of the channel. Read access is limited to the server. Clients
|
||||
///< will only ever see the last password they attempted to use when joining the channel. Always available.
|
||||
CHANNEL_CODEC, ///< Integer. Read/Write. The codec this channel is using. One of the values from the \ref CodecType
|
||||
///< enum. Always available.
|
||||
CHANNEL_CODEC_QUALITY, ///< Integer. Read/Write. The quality setting of the channel. Valid values are 0 to 10 inclusive.
|
||||
///< Higher value means better voice quality but also more bandwidth usage. Always available.
|
||||
CHANNEL_MAXCLIENTS, ///< Integer. Read/Write. The number of clients that can be in the channel simultaneously.
|
||||
///< Always available.
|
||||
CHANNEL_MAXFAMILYCLIENTS, ///< Integer. Read/Write. The total number of clients that can be in this channel and all
|
||||
///< sub channels of this channel. Always available.
|
||||
CHANNEL_ORDER, ///< UInt64. Read/Write. The ID of the channel below which this channel should be displayed. If 0
|
||||
///< the channel is sorted at the top of the current level. Always available.
|
||||
CHANNEL_FLAG_PERMANENT, ///< Integer. Read/Write. Boolean (1/0) indicating whether the channel remains when empty.
|
||||
///< Permanent channels are stored to the database and available after server restart. SDK
|
||||
///< users will need to take care of restoring channel at server start on their own.
|
||||
///< Mutually exclusive with \ref CHANNEL_FLAG_SEMI_PERMANENT. Always available.
|
||||
CHANNEL_FLAG_SEMI_PERMANENT, ///< Integer. Read/Write. Boolean (1/0) indicating whether the channel remains when
|
||||
///< empty. Semi permanent channels are not stored to disk and gone after server
|
||||
///< restart but remain while empty. Mutually exclusive with \ref
|
||||
///< CHANNEL_FLAG_PERMANENT. Always available.
|
||||
CHANNEL_FLAG_DEFAULT, ///< Integer. Read/Write. Boolean (1/0). The default channel is the channel that all clients
|
||||
///< are located in when they join the server, unless the client explicitly specified a
|
||||
///< different channel when connecting and is allowed to join their preferred channel. Only
|
||||
///< one channel on the server can have this flag set. The default channel must have \ref
|
||||
///< CHANNEL_FLAG_PERMANENT set. Always available.
|
||||
CHANNEL_FLAG_PASSWORD, ///< Integer. Read/Write. Boolean (1/0) indicating whether this channel is password protected.
|
||||
///< When removing or setting \ref CHANNEL_PASSWORD you also need to adjust this flag.
|
||||
CHANNEL_CODEC_LATENCY_FACTOR, ///< (deprecated) Integer. Read/Write. Allows to increase packet size, reducing
|
||||
///< bandwith at the cost of higher latency of voice transmission. Valid values are
|
||||
///< 1-10 inclusive. 1 is the default and offers the lowest latency. Always available.
|
||||
CHANNEL_CODEC_IS_UNENCRYPTED, ///< Integer. Read/Write. Boolean (1/0). If 0 voice data is encrypted, if 1 the voice
|
||||
///< data is not encrypted. Only used if the server \ref
|
||||
///< VIRTUALSERVER_CODEC_ENCRYPTION_MODE is set to \ref CODEC_ENCRYPTION_PER_CHANNEL.
|
||||
///< Always available.
|
||||
CHANNEL_SECURITY_SALT, ///< String. Read/Write. SDK Only, not used by TeamSpeak. This channels security hash. When
|
||||
///< a client joins their \ref CLIENT_SECURITY_HASH is compared to this value, to allow or
|
||||
///< deny the client access to the channel. Used to enforce clients joining the server with
|
||||
///< specific identity and \ref CLIENT_META_DATA. See SDK Documentation about this feature
|
||||
///< for further details. Always available.
|
||||
CHANNEL_DELETE_DELAY, ///< UInt64. Read/Write. Number of seconds deletion of temporary channels is delayed after
|
||||
///< the last client leaves the channel. Channel is only deleted if empty when the delete
|
||||
///< delay expired. Always available.
|
||||
CHANNEL_UNIQUE_IDENTIFIER, ///< String. Read only. An identifier that uniquely identifies a channel. Available in
|
||||
///< Server >= 3.10.0
|
||||
CHANNEL_ENDMARKER,
|
||||
};
|
||||
|
||||
enum ClientProperties {
|
||||
CLIENT_UNIQUE_IDENTIFIER = 0, ///< String. Read only. Public Identity, can be used to identify a client
|
||||
///< installation. Remains identical as long as the client keeps using the same
|
||||
///< identity. Available for visible clients.
|
||||
CLIENT_NICKNAME, ///< String. Read/Write. Display name of the client. Available for visible clients.
|
||||
CLIENT_VERSION, ///< String. Read only. Version String of the client used. For clients other than ourself this
|
||||
///< needs to be requested (\ref ts3client_requestClientVariables).
|
||||
CLIENT_PLATFORM, ///< String. Read only. Operating system used by the client. For other clients other than ourself
|
||||
///< this needs to be requested (\ref ts3client_requestClientVariables).
|
||||
CLIENT_FLAG_TALKING, ///< Integer. Read only. Whether the client is talking. Available on clients that are either
|
||||
///< whispering to us, or in our channel.
|
||||
CLIENT_INPUT_MUTED, ///< Integer. Read/Write. Microphone mute status. Available for visible clients. One of the
|
||||
///< values from the \ref MuteInputStatus enum.
|
||||
CLIENT_OUTPUT_MUTED, ///< Integer. Read only. Speaker mute status. Speaker mute implies microphone mute. Available
|
||||
///< for visible clients. One of the values from the \ref MuteOutputStatus enum.
|
||||
CLIENT_OUTPUTONLY_MUTED, ///< Integer. Read only. Speaker mute status. Microphone may be active. Available for
|
||||
///< visible clients. One of the values from the \ref MuteOutputStatus enum.
|
||||
CLIENT_INPUT_HARDWARE, ///< Integer. Read only. Indicates whether a capture device is open. Available for visible
|
||||
///< clients. One of the values from the \ref HardwareInputStatus enum.
|
||||
CLIENT_OUTPUT_HARDWARE, ///< Integer. Read only. Indicates whether a playback device is open. Available for visible
|
||||
///< clients. One of the values from the \ref HardwareOutputStatus enum.
|
||||
CLIENT_INPUT_DEACTIVATED, ///< Integer. Read/Write. Not available server side. Local microphone mute status.
|
||||
///< Available only for own client. Used to implement Push To Talk. One of the values from
|
||||
///< the \ref InputDeactivationStatus enum.
|
||||
CLIENT_IDLE_TIME, ///< UInt64. Read only. Seconds since last activity. Available only for own client.
|
||||
CLIENT_DEFAULT_CHANNEL, ///< String. Read only. User specified channel they joined when connecting to the server.
|
||||
///< Available only for own client.
|
||||
CLIENT_DEFAULT_CHANNEL_PASSWORD, ///< String. Read only. User specified channel password for the channel they
|
||||
///< attempted to join when connecting to the server. Available only for own
|
||||
///< client.
|
||||
CLIENT_SERVER_PASSWORD, ///< String. Read only. User specified server password. Available only for own client.
|
||||
CLIENT_META_DATA, ///< String. Read/Write. Can be used to store up to 4096 bytes of information on clients. Not
|
||||
///< used by TeamSpeak. Available for visible clients.
|
||||
CLIENT_IS_MUTED, ///< Integer. Read only. Not available server side. Indicates whether we have muted the client
|
||||
///< using \ref ts3client_requestMuteClients. Available for visible clients other than ourselves.
|
||||
CLIENT_IS_RECORDING, ///< Integer. Read only. Indicates whether the client is recording incoming audio. Available
|
||||
///< for visible clients.
|
||||
CLIENT_VOLUME_MODIFICATOR, ///< Integer. Read only. Volume adjustment for this client as set by \ref
|
||||
///< ts3client_setClientVolumeModifier. Available for visible clients.
|
||||
CLIENT_VERSION_SIGN, ///< String. Read only. TeamSpeak internal signature.
|
||||
CLIENT_SECURITY_HASH, ///< String. Read/Write. This clients security hash. Not used by TeamSpeak, SDK only. Hash is
|
||||
///< provided by an outside source. A channel will use the security salt + other client data
|
||||
///< to calculate a hash, which must be the same as the one provided here. See SDK
|
||||
///< documentation about Client / Channel Security Hashes for more details.
|
||||
CLIENT_ENCRYPTION_CIPHERS, ///< String. Read only. SDK only. List of available ciphers this client can use.
|
||||
CLIENT_ENDMARKER,
|
||||
};
|
||||
|
||||
enum VirtualServerProperties {
|
||||
VIRTUALSERVER_UNIQUE_IDENTIFIER = 0, ///< String. Read only. Unique identifier for a virtual server, does not
|
||||
///< change on server restart. Available if \ref ts3client_getConnectionStatus
|
||||
///< is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_NAME, ///< String. Read/Write. The virtual server display name. Available if \ref
|
||||
///< ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_WELCOMEMESSAGE, ///< String. Read/Write. The welcome message displayed to clients on connect.
|
||||
///< Available if \ref ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED. Not
|
||||
///< updated automatically when changed, updates need to be requested (\ref
|
||||
///< ts3client_requestServerVariables).
|
||||
VIRTUALSERVER_PLATFORM, ///< String. Read only. The operating system the server is running on. Available if \ref
|
||||
///< ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_VERSION, ///< String. Read only. The server software version string. Available if \ref
|
||||
///< ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_MAXCLIENTS, ///< UInt64. Read/Write. The maximum number of clients that can be connected
|
||||
///< simultaneously. Only available on request (\ref ts3client_requestServerVariables).
|
||||
VIRTUALSERVER_PASSWORD, ///< String. Read/Write. The server password. Read access is limited to the server. Clients
|
||||
///< will only get the password they supplied when connecting. Available if \ref
|
||||
///< ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_CLIENTS_ONLINE, ///< UInt64. Read only. The current number of clients connected to the server,
|
||||
///< including query connections. Only available on request (\ref
|
||||
///< ts3client_requestServerVariables).
|
||||
VIRTUALSERVER_CHANNELS_ONLINE, ///< UInt64. Read only. The current number of channels on the server. Only
|
||||
///< available on request (\ref ts3client_requestServerVariables).
|
||||
VIRTUALSERVER_CREATED, ///< Integer. Read only. The time this virtual server was created as unix timestamp.
|
||||
///< Available if \ref ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_UPTIME, ///< UInt64. Read only. Number of seconds that have passed since the virtual server was
|
||||
///< started. Only available on request (\ref ts3client_requestServerVariables).
|
||||
VIRTUALSERVER_CODEC_ENCRYPTION_MODE, ///< Integer. Read/Write. Boolean (1/0) that specifies if voice data is encrypted
|
||||
///< during transfer. One of the values from the \ref CodecEncryptionMode enum.
|
||||
///< Available if \ref ts3client_getConnectionStatus is >= \ref STATUS_CONNECTED.
|
||||
VIRTUALSERVER_ENCRYPTION_CIPHERS, ///< String. Read/Write. Comma separated list of available ciphers to encrypt the
|
||||
///< connection. The server will use the first cipher in the list that is also
|
||||
///< listed in the \ref CLIENT_ENCRYPTION_CIPHERS of the connecting client.
|
||||
///< Clients will fail to connect if no match is found. Always available.
|
||||
VIRTUALSERVER_ENDMARKER,
|
||||
VIRTUALSERVER_FILEBASE = 24, ///< String. Read only. The path to the base directory used to store files
|
||||
///< transferred using file transfer. Available only on the server. Is set by \ref
|
||||
///< ts3server_enableFileManager
|
||||
VIRTUALSERVER_MAX_DOWNLOAD_TOTAL_BANDWIDTH = 29, ///< UInt64. Read/Write. Maximum traffic in bytes the server can
|
||||
///< use for file transfer downloads. Only available on request
|
||||
///< (\ref ts3client_requestServerVariables).
|
||||
VIRTUALSERVER_MAX_UPLOAD_TOTAL_BANDWIDTH = 30, ///< UInt64. Read/Write. Maximum traffic in bytes the server can use
|
||||
///< for file transfer uploads. Only available on request (=>
|
||||
///< requestServerVariables)
|
||||
VIRTUALSERVER_LOG_FILETRANSFER = 64 ///< Integer. Read/Write. Boolean (1/0) indicating whether to include file
|
||||
///< transfer activities (uploading or downloading of files) in the server log.
|
||||
///< Always available.
|
||||
};
|
||||
|
||||
/**
|
||||
* Various connection properties.
|
||||
* These are all read only, and except for your own client must be requested using \ref ts3client_requestConnectionInfo
|
||||
*/
|
||||
enum ConnectionProperties {
|
||||
CONNECTION_PING = 0, ///< UInt64. Round trip latency for the connection based on the last 5 seconds. On the server
|
||||
///< this is the average across all connected clients for the last 5 seconds.
|
||||
CONNECTION_PING_DEVIATION, ///< Double. Standard deviation for the round trip latency in \ref CONNECTION_PING
|
||||
CONNECTION_CONNECTED_TIME, ///< UInt64. Seconds the client has been connected.
|
||||
CONNECTION_IDLE_TIME, ///< UInt64. Time in seconds since the last activity (voice transmission, switching channels,
|
||||
///< changing mic / speaker mute status) of the client.
|
||||
CONNECTION_CLIENT_IP, ///< String. IP of this client (as seen from the server side)
|
||||
CONNECTION_CLIENT_PORT, ///< UInt64. Client side port of this client (as seen from the server side)
|
||||
CONNECTION_SERVER_IP, ///< String. The IP or hostname used to connect to the server. Only available on yourself.
|
||||
CONNECTION_SERVER_PORT, ///< UInt64. The server port connected to. Only available on yourself.
|
||||
CONNECTION_PACKETS_SENT_SPEECH, ///< UInt64. The number of voice packets transmitted by the client.
|
||||
CONNECTION_PACKETS_SENT_KEEPALIVE, ///< UInt64. The number of keep alive packets transmitted by the client.
|
||||
CONNECTION_PACKETS_SENT_CONTROL, ///< UInt64. The number of command & control packets transmitted by the client.
|
||||
CONNECTION_PACKETS_SENT_TOTAL, ///< UInt64. Total number of packets transmitted by the client. Equal to the sum of
|
||||
///< \ref CONNECTION_PACKETS_SENT_SPEECH, \ref CONNECTION_PACKETS_SENT_KEEPALIVE and
|
||||
///< \ref CONNECTION_PACKETS_SENT_CONTROL
|
||||
CONNECTION_BYTES_SENT_SPEECH, ///< UInt64. Outgoing traffic used for voice data by the client.
|
||||
CONNECTION_BYTES_SENT_KEEPALIVE, ///< UInt64. Outgoing traffic used for keeping the connection alive by the client.
|
||||
CONNECTION_BYTES_SENT_CONTROL, ///< UInt64. Outgoing traffic used for command & control data by the client.
|
||||
CONNECTION_BYTES_SENT_TOTAL, ///< UInt64. Total outgoing traffic to the server by this client. Equal to the sum of
|
||||
///< \ref CONNECTION_BYTES_SENT_SPEECH, \ref CONNECTION_BYTES_SENT_KEEPALIVE and \ref
|
||||
///< CONNECTION_BYTES_SENT_CONTROL
|
||||
CONNECTION_PACKETS_RECEIVED_SPEECH, ///< UInt64. Number of voice packets received by the client.
|
||||
CONNECTION_PACKETS_RECEIVED_KEEPALIVE, ///< UInt64. Number of keep alive packets received by the client.
|
||||
CONNECTION_PACKETS_RECEIVED_CONTROL, ///< UInt64. Number of command & control packets received by the client.
|
||||
CONNECTION_PACKETS_RECEIVED_TOTAL, ///< UInt64. Total number of packets received by the client. Equal to the sum of
|
||||
///< \ref CONNECTION_PACKETS_RECEIVED_SPEECH, \ref
|
||||
///< CONNECTION_PACKETS_RECEIVED_KEEPALIVE and \ref
|
||||
///< CONNECTION_PACKETS_RECEIVED_CONTROL
|
||||
CONNECTION_BYTES_RECEIVED_SPEECH, ///< UInt64. Incoming traffic used by the client for voice data.
|
||||
CONNECTION_BYTES_RECEIVED_KEEPALIVE, ///< UInt64. Incoming traffic used by the client to keep the connection alive.
|
||||
CONNECTION_BYTES_RECEIVED_CONTROL, ///< UInt64. Incoming traffic used by the client for command & control data.
|
||||
CONNECTION_BYTES_RECEIVED_TOTAL, ///< UInt64. Total incoming traffic used by the client. Equal to the sum of \ref
|
||||
///< CONNECTION_BYTES_RECEIVED_SPEECH, \ref CONNECTION_BYTES_RECEIVED_KEEPALIVE and
|
||||
///< \ref CONNECTION_BYTES_RECEIVED_CONTROL
|
||||
CONNECTION_PACKETLOSS_SPEECH, ///< Double. Percentage points of voice packets for the client that did not arrive at
|
||||
///< the client or server averaged across the last 5 seconds.
|
||||
CONNECTION_PACKETLOSS_KEEPALIVE, ///< Double. Percentage points of keep alive packets for the client that did not
|
||||
///< arrive at the client or server averaged across the last 5 seconds.
|
||||
CONNECTION_PACKETLOSS_CONTROL, ///< Double. Percentage points of command & control packets for the client that did
|
||||
///< not arrive at the client or server averaged across the last 5 seconds.
|
||||
CONNECTION_PACKETLOSS_TOTAL, ///< Double. Cumulative chance in percentage points with which a packet round trip
|
||||
///< failed because a packet was lost
|
||||
CONNECTION_SERVER2CLIENT_PACKETLOSS_SPEECH, ///< Double. Probability with which a voice packet sent by the server
|
||||
///< was not received by the client.
|
||||
CONNECTION_SERVER2CLIENT_PACKETLOSS_KEEPALIVE, ///< Double. Probability with which a keepalive packet sent by the
|
||||
///< server was not received by the client.
|
||||
CONNECTION_SERVER2CLIENT_PACKETLOSS_CONTROL, ///< Double. Probability with which a control packet sent by the server
|
||||
///< was not received by the client.
|
||||
CONNECTION_SERVER2CLIENT_PACKETLOSS_TOTAL, ///< Double. Probability with which a packet sent by the server was not
|
||||
///< received by the client.
|
||||
CONNECTION_CLIENT2SERVER_PACKETLOSS_SPEECH, ///< Double. Probability with which a speech packet sent by the client
|
||||
///< was not received by the server.
|
||||
CONNECTION_CLIENT2SERVER_PACKETLOSS_KEEPALIVE, ///< Double. Probability with which a keepalive packet sent by the
|
||||
///< client was not received by the server.
|
||||
CONNECTION_CLIENT2SERVER_PACKETLOSS_CONTROL, ///< Double. Probability with which a control packet sent by the client
|
||||
///< was not received by the server.
|
||||
CONNECTION_CLIENT2SERVER_PACKETLOSS_TOTAL, ///< Double. Probability with which a packet sent by the client was not
|
||||
///< received by the server.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_SECOND_SPEECH, ///< UInt64. Number of bytes sent for speech data in the last second.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_SECOND_KEEPALIVE, ///< UInt64. Number of bytes sent for keepalive data in the last second.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_SECOND_CONTROL, ///< UInt64. Number of bytes sent for control data in the last second.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_SECOND_TOTAL, ///< UInt64. Number of bytes sent in the last second.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_MINUTE_SPEECH, ///< UInt64. Bytes per second sent for speech data, averaged over the
|
||||
///< last minute.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_MINUTE_KEEPALIVE, ///< UInt64. Bytes per second sent for keepalive data, averaged
|
||||
///< over the last minute.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_MINUTE_CONTROL, ///< UInt64. Bytes per second sent for control data, averaged over
|
||||
///< the last minute.
|
||||
CONNECTION_BANDWIDTH_SENT_LAST_MINUTE_TOTAL, ///< UInt64. Bytes per second sent, averaged over the last minute.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_SPEECH, ///< UInt64. Number of bytes received for speech data in the last second.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_KEEPALIVE, ///< UInt64. Number of bytes received for keepalive data in the
|
||||
///< last second.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_CONTROL, ///< UInt64. Number of bytes received for control data in the
|
||||
///< last second.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_TOTAL, ///< UInt64. Number of bytes received in the last second.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_MINUTE_SPEECH, ///< UInt64. Bytes per second received for speech data, averaged
|
||||
///< over the last minute.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_MINUTE_KEEPALIVE, ///< UInt64. Bytes per second received for keepalive data,
|
||||
///< averaged over the last minute.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_MINUTE_CONTROL, ///< UInt64. Bytes per second received for control data, averaged
|
||||
///< over the last minute.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_MINUTE_TOTAL, ///< UInt64. Bytes per second received, averaged over the last minute.
|
||||
CONNECTION_DUMMY_0,
|
||||
CONNECTION_DUMMY_1,
|
||||
CONNECTION_DUMMY_2,
|
||||
CONNECTION_DUMMY_3,
|
||||
CONNECTION_DUMMY_4,
|
||||
CONNECTION_DUMMY_5,
|
||||
CONNECTION_DUMMY_6,
|
||||
CONNECTION_DUMMY_7,
|
||||
CONNECTION_DUMMY_8,
|
||||
CONNECTION_DUMMY_9,
|
||||
CONNECTION_FILETRANSFER_BANDWIDTH_SENT, ///< UInt64. Current file transfer upstream activity in bytes per second.
|
||||
///< Only available on request (\ref ts3client_requestServerConnectionInfo).
|
||||
CONNECTION_FILETRANSFER_BANDWIDTH_RECEIVED, ///< UInt64. Current file transfer downstream activity in bytes per
|
||||
///< second. Only available on request (\ref
|
||||
///< ts3client_requestServerConnectionInfo).
|
||||
CONNECTION_FILETRANSFER_BYTES_RECEIVED_TOTAL, ///< UInt64. Total downstream traffic, in bytes, used for file
|
||||
///< transfer since the server was started. Only available on request
|
||||
///< (\ref ts3client_requestServerConnectionInfo).
|
||||
CONNECTION_FILETRANSFER_BYTES_SENT_TOTAL, ///< UInt64. Total upstream traffic, in bytes, used for file transfer
|
||||
///< since the server was started. Only available on request (\ref
|
||||
///< ts3client_requestServerConnectionInfo).
|
||||
CONNECTION_ENDMARKER
|
||||
};
|
||||
|
||||
/**
|
||||
* Describes a client position in 3 dimensional space, used for 3D Sound.
|
||||
*/
|
||||
typedef struct {
|
||||
float x; ///< X co-ordinate in 3D space.
|
||||
float y; ///< Y co-ordinate in 3D space.
|
||||
float z; ///< Z co-ordinate in 3D space.
|
||||
} TS3_VECTOR;
|
||||
|
||||
enum GroupWhisperType {
|
||||
GROUPWHISPERTYPE_SERVERGROUP = 0, ///< Whisper list consists of server groups
|
||||
GROUPWHISPERTYPE_CHANNELGROUP = 1, ///< Whisper list consists of channel groups
|
||||
GROUPWHISPERTYPE_CHANNELCOMMANDER = 2, ///< whisper to channel commanders
|
||||
GROUPWHISPERTYPE_ALLCLIENTS = 3, ///< whisper to all clients
|
||||
GROUPWHISPERTYPE_ENDMARKER,
|
||||
};
|
||||
|
||||
enum GroupWhisperTargetMode {
|
||||
GROUPWHISPERTARGETMODE_ALL = 0,
|
||||
GROUPWHISPERTARGETMODE_CURRENTCHANNEL = 1, ///< Whisper the current channel of the client
|
||||
GROUPWHISPERTARGETMODE_PARENTCHANNEL = 2, ///< Whisper the parent channel of whatever channel the client is currently in
|
||||
GROUPWHISPERTARGETMODE_ALLPARENTCHANNELS = 3, ///< Whipser to the parent channel and all their parent channels as well
|
||||
GROUPWHISPERTARGETMODE_CHANNELFAMILY = 4, ///< Whisper to the current channel and all its sub channels
|
||||
GROUPWHISPERTARGETMODE_ANCESTORCHANNELFAMILY = 5, ///< Whisper to the current channel, all its parent and sub channels.
|
||||
GROUPWHISPERTARGETMODE_SUBCHANNELS = 6, ///< Whisper to all sub channels of the current channel of the client
|
||||
GROUPWHISPERTARGETMODE_ENDMARKER,
|
||||
};
|
||||
|
||||
enum MonoSoundDestination {
|
||||
MONO_SOUND_DESTINATION_ALL = 0, ///< Send mono sound to all available speakers
|
||||
MONO_SOUND_DESTINATION_FRONT_CENTER = 1, ///< Send mono sound to front center speaker if available
|
||||
MONO_SOUND_DESTINATION_FRONT_LEFT_AND_RIGHT = 2 ///< Send mono sound to front left/right speakers if available
|
||||
};
|
||||
|
||||
enum SecuritySaltOptions {
|
||||
SECURITY_SALT_CHECK_NICKNAME = 1, ///< put nickname into security hash
|
||||
SECURITY_SALT_CHECK_META_DATA = 2 ///< put meta data into security hash
|
||||
};
|
||||
|
||||
/*this enum is used to disable client commands on the server*/
|
||||
enum ClientCommand {
|
||||
CLIENT_COMMAND_requestConnectionInfo = 0, ///< disable client connection info request (client bandwidth usage, ip,
|
||||
///< port, ping)
|
||||
CLIENT_COMMAND_requestClientMove = 1, ///< disable moving clients
|
||||
CLIENT_COMMAND_requestXXMuteClients = 2, ///< disable muting other clients
|
||||
CLIENT_COMMAND_requestClientKickFromXXX = 3, ///< disable kicking clients
|
||||
CLIENT_COMMAND_flushChannelCreation = 4, ///< disable creating channels
|
||||
CLIENT_COMMAND_flushChannelUpdates = 5, ///< disable editing channels
|
||||
CLIENT_COMMAND_requestChannelMove = 6, ///< disable moving channels
|
||||
CLIENT_COMMAND_requestChannelDelete = 7, ///< disable deleting channels
|
||||
CLIENT_COMMAND_requestChannelDescription = 8, ///< disable channel descriptions
|
||||
CLIENT_COMMAND_requestChannelXXSubscribeXXX = 9, ///< disable being able to see clients in channels other than the
|
||||
///< current channel the client is in
|
||||
CLIENT_COMMAND_requestServerConnectionInfo = 10, ///< disable server connection info request (server bandwidth
|
||||
///< usage, ip, port, ping)
|
||||
CLIENT_COMMAND_requestSendXXXTextMsg = 11, ///< disable text messaging
|
||||
CLIENT_COMMAND_filetransfers = 12, ///< disable file transfer
|
||||
CLIENT_COMMAND_ENDMARKER
|
||||
};
|
||||
|
||||
/* Access Control List*/
|
||||
enum ACLType { ACL_NONE = 0, ACL_WHITE_LIST = 1, ACL_BLACK_LIST = 2 };
|
||||
|
||||
/* file transfer actions*/
|
||||
enum FTAction {
|
||||
FT_INIT_SERVER = 0, ///< The virtual server is created. result->channelPath can be changed to create a different
|
||||
///< directory than the default 'virtualserver_x' where x is the virtual server.
|
||||
FT_INIT_CHANNEL = 1, ///< A channel is created. result->channelPath can be changed to create a different directory
|
||||
///< then the default 'channel_x' where x is the channel id.
|
||||
FT_UPLOAD = 2, ///< A file is being uploaded. All values in the result struct can be modified.
|
||||
FT_DOWNLOAD = 3, ///< A file is being downloaded. All values in the result struct can be modified.
|
||||
FT_DELETE = 4, ///< A file is being deleted. All values in the result struct can be modified.
|
||||
FT_CREATEDIR = 5, ///< A directory is being created in a channel. All values in the result struct can be modified.
|
||||
FT_RENAME = 6, ///< A file or folder is being renamed. The callback will be called twice! Once for the old and then
|
||||
///< for the new name. All values in the result struct can be modified.
|
||||
FT_FILELIST = 7, ///< A directory listing is requested. All values in the result struct can be modified.
|
||||
FT_FILEINFO = 8 ///< Information of a file is requested. All values in the result struct can be modified.
|
||||
};
|
||||
|
||||
/* file transfer status */
|
||||
enum FileTransferState {
|
||||
FILETRANSFER_INITIALISING = 0, ///< File transfer is establishing connection.
|
||||
FILETRANSFER_ACTIVE, ///< File transfer is in progress
|
||||
FILETRANSFER_FINISHED, ///< File transfer has finished
|
||||
};
|
||||
|
||||
/* file transfer types */
|
||||
enum FileTransferType {
|
||||
FileListType_Directory = 0, ///< The file entry is a directory
|
||||
FileListType_File, ///< The file entry is a regular file
|
||||
};
|
||||
|
||||
/* some structs to handle variables in callbacks */
|
||||
#define MAX_VARIABLES_EXPORT_COUNT 64
|
||||
struct VariablesExportItem {
|
||||
unsigned char itemIsValid; ///< Whether or not there is any data in this item. Ignore this item if this is 0.
|
||||
unsigned char proposedIsSet; ///< The value in proposed is set. If 0 ignore proposed
|
||||
const char* current; ///< current value (stored in memory)
|
||||
const char* proposed; ///< New value to change to (const, so no updates please)
|
||||
};
|
||||
|
||||
struct VariablesExport {
|
||||
struct VariablesExportItem items[MAX_VARIABLES_EXPORT_COUNT];
|
||||
};
|
||||
|
||||
struct ClientMiniExport {
|
||||
anyID ID; ///< id of the client
|
||||
uint64 channel; ///< the channel the client is in
|
||||
const char* ident; ///< client public identity
|
||||
const char* nickname; ///< client display name
|
||||
};
|
||||
|
||||
/**
|
||||
* Structure used to describe a file transfer in the \ref ServerLibFunctions.onTransformFilePath callback.
|
||||
* This describes the original values, and also contains hints for length limitations of the result parameter
|
||||
* of the callback.
|
||||
* \verbatim embed:rst
|
||||
.. important::
|
||||
Which values of the struct can be modified is defined by the action value of the original parameter.
|
||||
\endverbatim
|
||||
*/
|
||||
struct TransformFilePathExport {
|
||||
uint64 channel; ///< The channel id of the file. 0 if action is \ref FT_INIT_SERVER
|
||||
const char* filename; ///< utf8 encoded c string containing the original file name as intended by the client.
|
||||
int action; ///< The action to be performed. One of the values from the \ref FTAction enum. Defines which values of
|
||||
///< the result struct can be modified.
|
||||
int transformedFileNameMaxSize; ///< The maximum length the file name can be rewritten to.
|
||||
int channelPathMaxSize; ///< The maximum length the path can be rewritten to.
|
||||
};
|
||||
|
||||
/**
|
||||
* Structure to rewrite the file transfer file name and path in the \ref ServerLibFunctions.onTransformFilePath callback.
|
||||
* The lengths are limited as described in the original parameter.
|
||||
* \verbatim embed:rst
|
||||
.. important::
|
||||
Which values of the struct can be modified is defined by the action value of the original parameter.
|
||||
\endverbatim
|
||||
*/
|
||||
struct TransformFilePathExportReturns {
|
||||
char* transformedFileName; ///< pointer to target file name. Fill the memory pointed to with an utf8 encoded c string
|
||||
///< containing the new file name. Limited to original->transformedFileNameMaxSize bytes.
|
||||
char* channelPath; ///< pointer to memory for new path. Fill the memory pointed to with an utf8 encoded c string
|
||||
///< containing the new path. Limited to original->channelPathMaxSize bytes.
|
||||
int logFileAction; ///< boolean (1/0). Whether to log this file transfer to the log. Action is not logged regardless
|
||||
///< of this value if the servers \ref VIRTUALSERVER_LOG_FILETRANSFER property is 0.
|
||||
};
|
||||
|
||||
struct FileTransferCallbackExport {
|
||||
anyID clientID; ///< the client who started the file transfer
|
||||
anyID transferID; ///< local identifier of the transfer that has completed
|
||||
anyID remoteTransferID; ///< remote identifier of the transfer that has completed
|
||||
unsigned int status; ///< status of the transfer. One of the values from the \ref FileTransferState enum
|
||||
const char* statusMessage; ///< utf8 encoded c string containing a human readable description of the status
|
||||
uint64 remotefileSize; ///< size in bytes of the complete file to be transferred
|
||||
uint64 bytes; ///< number of bytes transferred. Same as remotefileSize when the transfer completed entirely.
|
||||
int isSender; ///< boolean. 1 if the server is sending the file. 0 if the server is receiving the file.
|
||||
};
|
||||
|
||||
/*define for file transfer bandwith limits*/
|
||||
#define BANDWIDTH_LIMIT_UNLIMITED 0xFFFFFFFFFFFFFFFFll
|
||||
|
||||
/*defines for speaker locations used by some sound callbacks*/
|
||||
#ifndef SPEAKER_FRONT_LEFT
|
||||
#define SPEAKER_FRONT_LEFT 0x1
|
||||
#define SPEAKER_FRONT_RIGHT 0x2
|
||||
#define SPEAKER_FRONT_CENTER 0x4
|
||||
#define SPEAKER_LOW_FREQUENCY 0x8
|
||||
#define SPEAKER_BACK_LEFT 0x10
|
||||
#define SPEAKER_BACK_RIGHT 0x20
|
||||
#define SPEAKER_FRONT_LEFT_OF_CENTER 0x40
|
||||
#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80
|
||||
#define SPEAKER_BACK_CENTER 0x100
|
||||
#define SPEAKER_SIDE_LEFT 0x200
|
||||
#define SPEAKER_SIDE_RIGHT 0x400
|
||||
#define SPEAKER_TOP_CENTER 0x800
|
||||
#define SPEAKER_TOP_FRONT_LEFT 0x1000
|
||||
#define SPEAKER_TOP_FRONT_CENTER 0x2000
|
||||
#define SPEAKER_TOP_FRONT_RIGHT 0x4000
|
||||
#define SPEAKER_TOP_BACK_LEFT 0x8000
|
||||
#define SPEAKER_TOP_BACK_CENTER 0x10000
|
||||
#define SPEAKER_TOP_BACK_RIGHT 0x20000
|
||||
#endif
|
||||
#define SPEAKER_HEADPHONES_LEFT 0x10000000
|
||||
#define SPEAKER_HEADPHONES_RIGHT 0x20000000
|
||||
#define SPEAKER_MONO 0x40000000
|
||||
|
||||
#endif /*PUBLIC_DEFINITIONS_H*/
|
||||
@@ -0,0 +1,200 @@
|
||||
#ifndef PUBLIC_ERRORS_H
|
||||
#define PUBLIC_ERRORS_H
|
||||
|
||||
//The idea here is: the values are 2 bytes wide, the first byte identifies the group, the second the count within that group
|
||||
|
||||
enum Ts3ErrorType {
|
||||
//general
|
||||
ERROR_ok = 0x0000, ///< Indicates success.
|
||||
ERROR_undefined = 0x0001,
|
||||
ERROR_not_implemented = 0x0002, ///< The attempted operation is not available in this context
|
||||
ERROR_ok_no_update = 0x0003, ///< Indicates success, but no change occurred. Returned for example upon flushing (e.g. using \ref ts3client_flushChannelUpdates) when all indicated changes already matched the current state.
|
||||
ERROR_dont_notify = 0x0004,
|
||||
ERROR_lib_time_limit_reached = 0x0005,
|
||||
ERROR_out_of_memory = 0x0006, ///< Not enough system memory to perform operation
|
||||
ERROR_canceled = 0x0007,
|
||||
|
||||
//dunno
|
||||
ERROR_command_not_found = 0x0100,
|
||||
ERROR_unable_to_bind_network_port = 0x0101, ///< Unspecified failure to create a listening port
|
||||
ERROR_no_network_port_available = 0x0102, ///< Failure to initialize a listening port for FileTransfer
|
||||
ERROR_port_already_in_use = 0x0103, ///< Specified port is already in use by a different application
|
||||
|
||||
//client
|
||||
ERROR_client_invalid_id = 0x0200, ///< Client no longer connected
|
||||
ERROR_client_nickname_inuse = 0x0201, ///< Client name is already in use. Client names must be unique
|
||||
ERROR_client_protocol_limit_reached = 0x0203, ///< Too many clients on the server
|
||||
ERROR_client_invalid_type = 0x0204, ///< Function called for normal clients that is only available for query clients or vice versa
|
||||
ERROR_client_already_subscribed = 0x0205, ///< Attempting to subscribe to a channel already subscribed to
|
||||
ERROR_client_not_logged_in = 0x0206,
|
||||
ERROR_client_could_not_validate_identity = 0x0207, ///< Identity not valid or insufficient security level
|
||||
ERROR_client_invalid_password = 0x0208,
|
||||
ERROR_client_version_outdated = 0x020a, ///< Server requires newer client version as determined by the min_client_version properties
|
||||
ERROR_client_is_flooding = 0x020c, ///< Triggered flood protection. Further information is supplied in the extra message if applicable.
|
||||
ERROR_client_hacked = 0x020d,
|
||||
ERROR_client_cannot_verify_now = 0x020e,
|
||||
ERROR_client_login_not_permitted = 0x020f,
|
||||
ERROR_client_not_subscribed = 0x0210, ///< Action is only available on subscribed channels
|
||||
|
||||
//channel
|
||||
ERROR_channel_invalid_id = 0x0300, ///< Channel does not exist on the server (any longer)
|
||||
ERROR_channel_protocol_limit_reached = 0x0301, ///< Too many channels on the server
|
||||
ERROR_channel_already_in = 0x0302, ///< Attempting to move a client or channel to its current channel
|
||||
ERROR_channel_name_inuse = 0x0303, ///< Channel name is already taken by another channel. Channel names must be unique
|
||||
ERROR_channel_not_empty = 0x0304, ///< Attempting to delete a channel with clients or sub channels in it
|
||||
ERROR_channel_can_not_delete_default = 0x0305, ///< Default channel cannot be deleted. Set a new default channel first (see \ref ts3client_setChannelVariableAsInt or \ref ts3server_setChannelVariableAsInt )
|
||||
ERROR_channel_default_require_permanent = 0x0306, ///< Attempt to set a non permanent channel as default channel. Set channel to permanent first (see \ref ts3client_setChannelVariableAsInt or \ref ts3server_setChannelVariableAsInt )
|
||||
ERROR_channel_invalid_flags = 0x0307, ///< Invalid combination of \ref ChannelProperties, trying to remove \ref CHANNEL_FLAG_DEFAULT or set a password on the default channel
|
||||
ERROR_channel_parent_not_permanent = 0x0308, ///< Attempt to move a permanent channel into a non-permanent one, or set a channel to be permanent that is a sub channel of a non-permanent one
|
||||
ERROR_channel_maxclients_reached = 0x0309, ///< Channel is full as determined by its \ref CHANNEL_MAXCLIENTS setting
|
||||
ERROR_channel_maxfamily_reached = 0x030a, ///< Channel tree is full as determined by its \ref CHANNEL_MAXFAMILYCLIENTS setting
|
||||
ERROR_channel_invalid_order = 0x030b, ///< Invalid value for the \ref CHANNEL_ORDER property. The specified channel must exist on the server and be on the same level.
|
||||
ERROR_channel_no_filetransfer_supported = 0x030c, ///< Invalid \ref CHANNEL_FILEPATH set for the channel
|
||||
ERROR_channel_invalid_password = 0x030d, ///< Channel has a password not matching the password supplied in the call
|
||||
// used in public_rare_errors = 0x030e,
|
||||
ERROR_channel_invalid_security_hash = 0x030f,
|
||||
|
||||
//server
|
||||
ERROR_server_invalid_id = 0x0400, ///< Chosen virtual server does not exist or is offline
|
||||
ERROR_server_running = 0x0401, ///< attempting to delete a server that is running. Stop the server before deleting it.
|
||||
ERROR_server_is_shutting_down = 0x0402, ///< Client disconnected because the server is going offline
|
||||
ERROR_server_maxclients_reached = 0x0403, ///< Given in the onConnectStatusChange event when the server has reached its maximum number of clients as defined by the \ref VIRTUALSERVER_MAXCLIENTS property
|
||||
ERROR_server_invalid_password = 0x0404, ///< Specified server password is wrong. Provide the correct password in the \ref ts3client_startConnection / \ref ts3client_startConnectionWithChannelID call.
|
||||
ERROR_server_is_virtual = 0x0407, ///< Server is in virtual status. The attempted action is not possible in this state. Start the virtual server first.
|
||||
ERROR_server_is_not_running = 0x0409, ///< Attempting to stop a server that is not online.
|
||||
ERROR_server_is_booting = 0x040a, // Not used
|
||||
ERROR_server_status_invalid = 0x040b,
|
||||
ERROR_server_version_outdated = 0x040d, ///< Attempt to connect to an outdated server version. The server needs to be updated.
|
||||
ERROR_server_duplicate_running = 0x040e, ///< This server is already running within the instance. Each virtual server may only exist once.
|
||||
|
||||
//parameter
|
||||
ERROR_parameter_quote = 0x0600, // Not used
|
||||
ERROR_parameter_invalid_count = 0x0601, ///< Attempt to flush changes without previously calling set*VariableAs* since the last flush
|
||||
ERROR_parameter_invalid = 0x0602, ///< At least one of the supplied parameters did not meet the criteria for that parameter
|
||||
ERROR_parameter_not_found = 0x0603, ///< Failure to supply all the necessary parameters
|
||||
ERROR_parameter_convert = 0x0604, ///< Invalid type supplied for a parameter, such as passing a string (ie. "five") that expects a number.
|
||||
ERROR_parameter_invalid_size = 0x0605, ///< Value out of allowed range. Such as strings are too long/short or numeric values outside allowed range
|
||||
ERROR_parameter_missing = 0x0606, ///< Neglecting to specify a required parameter
|
||||
ERROR_parameter_checksum = 0x0607, ///< Attempting to deploy a modified snapshot
|
||||
|
||||
//unsorted, need further investigation
|
||||
ERROR_vs_critical = 0x0700, ///< Failure to create default channel
|
||||
ERROR_connection_lost = 0x0701, ///< Generic error with the connection.
|
||||
ERROR_not_connected = 0x0702, ///< Attempting to call functions with a serverConnectionHandler that is not connected. You can use \ref ts3client_getConnectionStatus to check whether the connection handler is connected to a server
|
||||
ERROR_no_cached_connection_info = 0x0703, ///< Attempting to query connection information (bandwidth usage, ping, etc) without requesting them first using \ref ts3client_requestConnectionInfo
|
||||
ERROR_currently_not_possible = 0x0704, ///< Requested information is not currently available. You may have to call \ref ts3client_requestClientVariables or \ref ts3client_requestServerVariables
|
||||
ERROR_failed_connection_initialisation = 0x0705, ///< No TeamSpeak server running on the specified IP address and port
|
||||
ERROR_could_not_resolve_hostname = 0x0706, ///< Failure to resolve the specified hostname to an IP address
|
||||
ERROR_invalid_server_connection_handler_id = 0x0707, ///< Attempting to perform actions on a non-existent server connection handler
|
||||
ERROR_could_not_initialise_input_manager = 0x0708, // Not used
|
||||
ERROR_clientlibrary_not_initialised = 0x0709, ///< Calling client library functions without successfully calling \ref ts3client_initClientLib before
|
||||
ERROR_serverlibrary_not_initialised = 0x070a, ///< Calling server library functions without successfully calling \ref ts3server_initServerLib before
|
||||
ERROR_whisper_too_many_targets = 0x070b, ///< Using a whisper list that contain more clients than the servers \ref VIRTUALSERVER_MIN_CLIENTS_IN_CHANNEL_BEFORE_FORCED_SILENCE property
|
||||
ERROR_whisper_no_targets = 0x070c, ///< The active whisper list is empty or no clients matched the whisper list (e.g. all channels in the list are empty)
|
||||
ERROR_connection_ip_protocol_missing = 0x070d, ///< Invalid or unsupported protocol (e.g. attempting an IPv6 connection on an IPv4 only machine)
|
||||
ERROR_handshake_failed = 0x070e,
|
||||
ERROR_illegal_server_license = 0x070f,
|
||||
|
||||
//file transfer
|
||||
ERROR_file_invalid_name = 0x0800, ///< Invalid UTF8 string or not a valid file
|
||||
ERROR_file_invalid_permissions = 0x0801, ///< Permissions prevent opening the file
|
||||
ERROR_file_already_exists = 0x0802, ///< Target path already exists as a directory
|
||||
ERROR_file_not_found = 0x0803, ///< Attempt to access or move non existing file
|
||||
ERROR_file_io_error = 0x0804, ///< Generic file input / output error
|
||||
ERROR_file_invalid_transfer_id = 0x0805, ///< Attempt to get information about a file transfer after it has already been cleaned up. File transfer information is not available indefinitely after the transfer completed
|
||||
ERROR_file_invalid_path = 0x0806, ///< specified path contains invalid characters or does not start with "/"
|
||||
ERROR_file_no_files_available = 0x0807, // Not used
|
||||
ERROR_file_overwrite_excludes_resume = 0x0808, ///< File overwrite and resume are mutually exclusive. Only one or neither can be 1.
|
||||
ERROR_file_invalid_size = 0x0809, ///< Attempt to write more bytes than claimed file size.
|
||||
ERROR_file_already_in_use = 0x080a, ///< File is currently not available, try again later.
|
||||
ERROR_file_could_not_open_connection = 0x080b, ///< Generic failure in file transfer connection / other party did not conform to file transfer protocol
|
||||
ERROR_file_no_space_left_on_device = 0x080c, ///< Operating system reports hard disk is full. May be caused by quota limitations.
|
||||
ERROR_file_exceeds_file_system_maximum_size = 0x080d, ///< File is too large for the file system of the target device.
|
||||
ERROR_file_transfer_connection_timeout = 0x080e, // Not used
|
||||
ERROR_file_connection_lost = 0x080f, ///< File input / output timeout or connection failure
|
||||
ERROR_file_exceeds_supplied_size = 0x0810, // Not used
|
||||
ERROR_file_transfer_complete = 0x0811, ///< Indicates successful completion
|
||||
ERROR_file_transfer_canceled = 0x0812, ///< Transfer was cancelled through @ref ts3client_haltTransfer
|
||||
ERROR_file_transfer_interrupted = 0x0813, ///< Transfer failed because the server is shutting down, or network connection issues
|
||||
ERROR_file_transfer_server_quota_exceeded = 0x0814, ///< Transfer terminated due to server bandwidth quota being exceeded. No client can transfer files.
|
||||
ERROR_file_transfer_client_quota_exceeded = 0x0815, ///< Attempt to transfer more data than allowed by this clients' bandwidth quota. Other clients may continue to transfer files.
|
||||
ERROR_file_transfer_reset = 0x0816, // Not used
|
||||
ERROR_file_transfer_limit_reached = 0x0817, ///< Too many file transfers are in progress. Try again later
|
||||
ERROR_file_invalid_storage_class = 0x0818, // TODO: Invalid storage class for HTTP FileTransfer (what is a storage class?)
|
||||
ERROR_file_invalid_dimension = 0x0819, ///< Avatar image exceeds maximum width or height accepted by the server.
|
||||
ERROR_file_transfer_channel_quota_exceeded = 0x081a, ///< Transfer failed because the channel quota was exceeded. Uploading to this channel is not possible, but other channels may be fine.
|
||||
|
||||
//sound
|
||||
ERROR_sound_preprocessor_disabled = 0x0900, ///< Cannot set or query pre processor variables with preprocessing disabled
|
||||
ERROR_sound_internal_preprocessor = 0x0901,
|
||||
ERROR_sound_internal_encoder = 0x0902,
|
||||
ERROR_sound_internal_playback = 0x0903,
|
||||
ERROR_sound_no_capture_device_available = 0x0904, ///< No audio capture devices are available
|
||||
ERROR_sound_no_playback_device_available = 0x0905, ///< No audio playback devices are available
|
||||
ERROR_sound_could_not_open_capture_device = 0x0906, ///< Error accessing audio device, or audio device does not support the requested mode
|
||||
ERROR_sound_could_not_open_playback_device = 0x0907, ///< Error accessing audio device, or audio device does not support the requested mode
|
||||
ERROR_sound_handler_has_device = 0x0908, ///< Attempt to open a sound device on a connection handler which already has an open device. Close the already open device first using \ref ts3client_closeCaptureDevice or \ref ts3client_closePlaybackDevice
|
||||
ERROR_sound_invalid_capture_device = 0x0909, ///< Attempt to use a device for capture that does not support capturing audio
|
||||
ERROR_sound_invalid_playback_device = 0x090a, ///< Attempt to use a device for playback that does not support playback of audio
|
||||
ERROR_sound_invalid_wave = 0x090b, ///< Attempt to use a non WAV file in \ref ts3client_playWaveFile or \ref ts3client_playWaveFileHandle
|
||||
ERROR_sound_unsupported_wave = 0x090c, ///< Unsupported wave file used in \ref ts3client_playWaveFile or \ref ts3client_playWaveFileHandle.
|
||||
ERROR_sound_open_wave = 0x090d, ///< Failure to open the specified sound file
|
||||
ERROR_sound_internal_capture = 0x090e,
|
||||
ERROR_sound_device_in_use = 0x090f, ///< Attempt to unregister a custom device that is being used. Close the device first using \ref ts3client_closeCaptureDevice or \ref ts3client_closePlaybackDevice
|
||||
ERROR_sound_device_already_registerred = 0x0910, ///< Attempt to register a custom device with a device id that has already been used in a previous call. Device ids must be unique.
|
||||
ERROR_sound_unknown_device = 0x0911, ///< Attempt to open, close, unregister or use a device which is not known. Custom devices must be registered before being used (see \ref ts3client_registerCustomDevice)
|
||||
ERROR_sound_unsupported_frequency = 0x0912,
|
||||
ERROR_sound_invalid_channel_count = 0x0913, ///< Invalid device audio channel count, must be > 0
|
||||
ERROR_sound_read_wave = 0x0914, ///< Failure to read sound samples from an opened wave file. Is this a valid wave file?
|
||||
ERROR_sound_need_more_data = 0x0915, // for internal purposes only
|
||||
ERROR_sound_device_busy = 0x0916, // for internal purposes only
|
||||
ERROR_sound_no_data = 0x0917, ///< Indicates there is currently no data for playback, e.g. nobody is speaking right now.
|
||||
ERROR_sound_channel_mask_mismatch = 0x0918, ///< Opening a device with an unsupported channel count
|
||||
|
||||
//permissions
|
||||
ERROR_permissions_client_insufficient = 0x0a08, ///< Not enough permissions to perform the requested activity
|
||||
ERROR_permissions = 0x0a0c, ///< Permissions to use sound device not granted by operating system, e.g. Windows denied microphone access.
|
||||
|
||||
//accounting
|
||||
ERROR_accounting_virtualserver_limit_reached = 0x0b00, ///< Attempt to use more virtual servers than allowed by the license
|
||||
ERROR_accounting_slot_limit_reached = 0x0b01, ///< Attempt to set more slots than allowed by the license
|
||||
ERROR_accounting_license_file_not_found = 0x0b02, // Not used
|
||||
ERROR_accounting_license_date_not_ok = 0x0b03, ///< License expired or not valid yet
|
||||
ERROR_accounting_unable_to_connect_to_server = 0x0b04, ///< Failure to communicate with accounting backend
|
||||
ERROR_accounting_unknown_error = 0x0b05, ///< Failure to write update license file
|
||||
ERROR_accounting_server_error = 0x0b06, // Not used
|
||||
ERROR_accounting_instance_limit_reached = 0x0b07, ///< More than one process of the server is running
|
||||
ERROR_accounting_instance_check_error = 0x0b08, ///< Shared memory access failure.
|
||||
ERROR_accounting_license_file_invalid = 0x0b09, ///< License is not a TeamSpeak license
|
||||
ERROR_accounting_running_elsewhere = 0x0b0a, ///< A copy of this server is already running in another instance. Each server may only exist once.
|
||||
ERROR_accounting_instance_duplicated = 0x0b0b, ///< A copy of this server is running already in this process. Each server may only exist once.
|
||||
ERROR_accounting_already_started = 0x0b0c, ///< Attempt to start a server that is already running
|
||||
ERROR_accounting_not_started = 0x0b0d,
|
||||
ERROR_accounting_to_many_starts = 0x0b0e, ///< Starting instance / virtual servers too often in too short a time period
|
||||
|
||||
//provisioning server
|
||||
/// @cond HAS_PROVISIONING
|
||||
ERROR_provisioning_invalid_password = 0x1100,
|
||||
ERROR_provisioning_invalid_request = 0x1101,
|
||||
ERROR_provisioning_no_slots_available = 0x1102,
|
||||
ERROR_provisioning_pool_missing = 0x1103,
|
||||
ERROR_provisioning_pool_unknown = 0x1104,
|
||||
ERROR_provisioning_unknown_ip_location = 0x1105,
|
||||
ERROR_provisioning_internal_tries_exceeded = 0x1106,
|
||||
ERROR_provisioning_too_many_slots_requested = 0x1107,
|
||||
ERROR_provisioning_too_many_reserved = 0x1108,
|
||||
ERROR_provisioning_could_not_connect = 0x1109,
|
||||
ERROR_provisioning_auth_server_not_connected = 0x1110,
|
||||
ERROR_provisioning_auth_data_too_large = 0x1111,
|
||||
ERROR_provisioning_already_initialized = 0x1112,
|
||||
ERROR_provisioning_not_initialized = 0x1113,
|
||||
ERROR_provisioning_connecting = 0x1114,
|
||||
ERROR_provisioning_already_connected = 0x1115,
|
||||
ERROR_provisioning_not_connected = 0x1116,
|
||||
ERROR_provisioning_io_error = 0x1117,
|
||||
ERROR_provisioning_invalid_timeout = 0x1118,
|
||||
ERROR_provisioning_ts3server_not_found = 0x1119,
|
||||
ERROR_provisioning_no_permission = 0x111A,
|
||||
/// @endcond
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,108 @@
|
||||
#ifndef PUBLIC_ERRORS__RARE_H
|
||||
#define PUBLIC_ERRORS__RARE_H
|
||||
|
||||
//The idea here is: the values are 2 bytes wide, the first byte identifies the group, the second the count within that group
|
||||
|
||||
enum Ts3RareErrorType {
|
||||
//client
|
||||
ERROR_client_too_many_clones_connected = 0x0209,
|
||||
ERROR_client_is_online = 0x020b,
|
||||
|
||||
//channel
|
||||
ERROR_channel_is_private_channel = 0x030e,
|
||||
//note 0x030f is defined in public_errors;
|
||||
|
||||
//database
|
||||
ERROR_database = 0x0500,
|
||||
ERROR_database_empty_result = 0x0501,
|
||||
ERROR_database_duplicate_entry = 0x0502,
|
||||
ERROR_database_no_modifications = 0x0503,
|
||||
ERROR_database_constraint = 0x0504,
|
||||
ERROR_database_reinvoke = 0x0505,
|
||||
|
||||
//permissions
|
||||
ERROR_permission_invalid_group_id = 0x0a00,
|
||||
ERROR_permission_duplicate_entry = 0x0a01,
|
||||
ERROR_permission_invalid_perm_id = 0x0a02,
|
||||
ERROR_permission_empty_result = 0x0a03,
|
||||
ERROR_permission_default_group_forbidden = 0x0a04,
|
||||
ERROR_permission_invalid_size = 0x0a05,
|
||||
ERROR_permission_invalid_value = 0x0a06,
|
||||
ERROR_permissions_group_not_empty = 0x0a07,
|
||||
ERROR_permissions_insufficient_group_power = 0x0a09,
|
||||
ERROR_permissions_insufficient_permission_power = 0x0a0a,
|
||||
ERROR_permission_template_group_is_used = 0x0a0b,
|
||||
//0x0a0c is in public_errors.h
|
||||
ERROR_permission_used_by_integration = 0x0a0d,
|
||||
|
||||
//server
|
||||
ERROR_server_deployment_active = 0x0405,
|
||||
ERROR_server_unable_to_stop_own_server = 0x0406,
|
||||
ERROR_server_wrong_machineid = 0x0408,
|
||||
ERROR_server_modal_quit = 0x040c,
|
||||
ERROR_server_time_difference_too_large = 0x040f,
|
||||
ERROR_server_blacklisted = 0x0410,
|
||||
ERROR_server_shutdown = 0x0411,
|
||||
|
||||
//messages
|
||||
ERROR_message_invalid_id = 0x0c00,
|
||||
|
||||
//ban
|
||||
ERROR_ban_invalid_id = 0x0d00,
|
||||
ERROR_connect_failed_banned = 0x0d01,
|
||||
ERROR_rename_failed_banned = 0x0d02,
|
||||
ERROR_ban_flooding = 0x0d03,
|
||||
|
||||
//tts
|
||||
ERROR_tts_unable_to_initialize = 0x0e00,
|
||||
|
||||
//privilege key
|
||||
ERROR_privilege_key_invalid = 0x0f00,
|
||||
|
||||
//voip
|
||||
ERROR_voip_pjsua = 0x1000,
|
||||
ERROR_voip_already_initialized = 0x1001,
|
||||
ERROR_voip_too_many_accounts = 0x1002,
|
||||
ERROR_voip_invalid_account = 0x1003,
|
||||
ERROR_voip_internal_error = 0x1004,
|
||||
ERROR_voip_invalid_connectionId = 0x1005,
|
||||
ERROR_voip_cannot_answer_initiated_call = 0x1006,
|
||||
ERROR_voip_not_initialized = 0x1007,
|
||||
|
||||
//mytsid - client
|
||||
ERROR_invalid_mytsid_data = 0x1200,
|
||||
ERROR_invalid_integration = 0x1201,
|
||||
ERROR_mytsid_needed = 0x1202,
|
||||
|
||||
//ed25519
|
||||
ERROR_ed25519_rng_fail = 0x1300,
|
||||
ERROR_ed25519_signature_invalid = 0x1301,
|
||||
ERROR_ed25519_invalid_key = 0x1302,
|
||||
ERROR_ed25519_unable_to_create_valid_key = 0x1303,
|
||||
ERROR_ed25519_out_of_memory = 0x1304,
|
||||
ERROR_ed25519_exists = 0x1305,
|
||||
ERROR_ed25519_read_beyond_eof = 0x1306,
|
||||
ERROR_ed25519_write_beyond_eof = 0x1307,
|
||||
ERROR_ed25519_version = 0x1308,
|
||||
ERROR_ed25519_invalid = 0x1309,
|
||||
ERROR_ed25519_invalid_date = 0x130A,
|
||||
ERROR_ed25519_unauthorized = 0x130B,
|
||||
ERROR_ed25519_invalid_type = 0x130C,
|
||||
ERROR_ed25519_address_nomatch = 0x130D,
|
||||
ERROR_ed25519_not_valid_yet = 0x130E,
|
||||
ERROR_ed25519_expired = 0x130F,
|
||||
ERROR_ed25519_index_out_of_range = 0x1310,
|
||||
ERROR_ed25519_invalid_size = 0x1311,
|
||||
|
||||
//api key
|
||||
ERROR_apikey_outofscope = 0x1400,
|
||||
ERROR_apikey_crypto_error = 0x1401,
|
||||
ERROR_apikey_invalid = 0x1402,
|
||||
ERROR_apikey_invalid_id = 0x1403,
|
||||
ERROR_apikey_missing = 0x1404,
|
||||
|
||||
//homebase
|
||||
ERROR_homebase_no_slots_available = 0x1500,
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,368 @@
|
||||
#ifndef PUBLIC_RARE_DEFINITIONS_H
|
||||
#define PUBLIC_RARE_DEFINITIONS_H
|
||||
|
||||
#include "public_definitions.h"
|
||||
|
||||
//limited length, measured in characters
|
||||
#define TS3_MAX_SIZE_CLIENT_NICKNAME_NONSDK 30
|
||||
#define TS3_MIN_SIZE_CLIENT_NICKNAME_NONSDK 3
|
||||
#define TS3_MAX_SIZE_AWAY_MESSAGE 80
|
||||
#define TS3_MAX_SIZE_GROUP_NAME 30
|
||||
#define TS3_MAX_SIZE_TALK_REQUEST_MESSAGE 50
|
||||
#define TS3_MAX_SIZE_COMPLAIN_MESSAGE 200
|
||||
#define TS3_MAX_SIZE_CLIENT_DESCRIPTION 200
|
||||
#define TS3_MAX_SIZE_HOST_MESSAGE 200
|
||||
#define TS3_MAX_SIZE_HOSTBUTTON_TOOLTIP 50
|
||||
#define TS3_MAX_SIZE_POKE_MESSAGE 100
|
||||
#define TS3_MAX_SIZE_OFFLINE_MESSAGE 4096
|
||||
#define TS3_MAX_SIZE_OFFLINE_MESSAGE_SUBJECT 200
|
||||
#define TS3_MAX_SIZE_USER_TAG 100
|
||||
|
||||
//limited length, measured in bytes (utf8 encoded)
|
||||
#define TS3_MAX_SIZE_PLUGIN_COMMAND 1024 * 8
|
||||
#define TS3_MAX_SIZE_VIRTUALSERVER_HOSTBANNER_GFX_URL 2000
|
||||
|
||||
enum GroupShowNameTreeMode {
|
||||
GroupShowNameTreeMode_NONE = 0, //dont group show name
|
||||
GroupShowNameTreeMode_BEFORE, //show group name before client name
|
||||
GroupShowNameTreeMode_BEHIND //show group name behind client name
|
||||
};
|
||||
|
||||
enum PluginTargetMode {
|
||||
PluginCommandTarget_CURRENT_CHANNEL = 0, //send plugincmd to all clients in current channel
|
||||
PluginCommandTarget_SERVER, //send plugincmd to all clients on server
|
||||
PluginCommandTarget_CLIENT, //send plugincmd to all given client ids
|
||||
PluginCommandTarget_CURRENT_CHANNEL_SUBSCRIBED_CLIENTS, //send plugincmd to all subscribed clients in current channel
|
||||
PluginCommandTarget_MAX
|
||||
};
|
||||
|
||||
enum {
|
||||
SERVER_BINDING_VIRTUALSERVER = 0,
|
||||
SERVER_BINDING_SERVERQUERY = 1,
|
||||
SERVER_BINDING_FILETRANSFER = 2,
|
||||
};
|
||||
|
||||
enum HostMessageMode {
|
||||
HostMessageMode_NONE = 0, //dont display anything
|
||||
HostMessageMode_LOG, //display message inside log
|
||||
HostMessageMode_MODAL, //display message inside a modal dialog
|
||||
HostMessageMode_MODALQUIT //display message inside a modal dialog and quit/close server/connection
|
||||
};
|
||||
|
||||
enum HostBannerMode {
|
||||
HostBannerMode_NO_ADJUST = 0, //Do not adjust
|
||||
HostBannerMode_ADJUST_IGNORE_ASPECT, //Adjust but ignore aspect ratio
|
||||
HostBannerMode_ADJUST_KEEP_ASPECT, //Adjust and keep aspect ratio
|
||||
};
|
||||
|
||||
enum ClientType {
|
||||
ClientType_NORMAL = 0,
|
||||
ClientType_SERVERQUERY,
|
||||
};
|
||||
|
||||
enum AwayStatus {
|
||||
AWAY_NONE = 0,
|
||||
AWAY_ZZZ,
|
||||
};
|
||||
|
||||
enum CommandLinePropertiesRare {
|
||||
#ifdef SERVER
|
||||
COMMANDLINE_CREATE_DEFAULT_VIRTUALSERVER = 0, //create default virtualserver
|
||||
COMMANDLINE_MACHINE_ID, //machine id (starts only virtualserver with given machineID
|
||||
COMMANDLINE_DEFAULT_VOICE_PORT,
|
||||
COMMANDLINE_VOICE_IP,
|
||||
COMMANDLINE_THREADS_VOICE_UDP,
|
||||
COMMANDLINE_LICENSEPATH,
|
||||
COMMANDLINE_YAMLFILE,
|
||||
#ifndef TEAMSPEAK_SDK
|
||||
COMMANDLINE_FILETRANSFER_PORT,
|
||||
COMMANDLINE_FILETRANSFER_IP,
|
||||
COMMANDLINE_QUERY_PORT,
|
||||
COMMANDLINE_QUERY_IP,
|
||||
COMMANDLINE_QUERY_IP_ALLOWLIST,
|
||||
COMMANDLINE_QUERY_IP_DENYLIST,
|
||||
COMMANDLINE_CLEAR_DATABASE,
|
||||
COMMANDLINE_SERVERADMIN_PASSWORD,
|
||||
COMMANDLINE_DBPLUGIN,
|
||||
COMMANDLINE_DBPLUGINPARAMETER,
|
||||
COMMANDLINE_DBSQLPATH,
|
||||
COMMANDLINE_DBSQLCREATEPATH,
|
||||
COMMANDLINE_DBCONNECTIONS,
|
||||
COMMANDLINE_LOGPATH,
|
||||
COMMANDLINE_CREATEINIFILE,
|
||||
COMMANDLINE_INIFILE,
|
||||
COMMANDLINE_LOGQUERYCOMMANDS,
|
||||
COMMANDLINE_DBCLIENTKEEPDAYS,
|
||||
COMMANDLINE_NO_PERMISSION_UPDATE,
|
||||
COMMANDLINE_OPEN_WIN_CONSOLE,
|
||||
COMMANDLINE_NO_PASSWORD_DIALOG,
|
||||
COMMANDLINE_LOGAPPEND,
|
||||
COMMANDLINE_QUERY_SKIPBRUTEFORCECHECK,
|
||||
COMMANDLINE_QUERY_BUFFER_MB,
|
||||
#endif
|
||||
COMMANDLINE_HTTP_PROXY,
|
||||
#ifndef TEAMSPEAK_SDK
|
||||
COMMANDLINE_LICENSE_ACCEPTED,
|
||||
COMMANDLINE_SERVERQUERYDOCS_PATH,
|
||||
COMMANDLINE_QUERY_SSH_IP,
|
||||
COMMANDLINE_QUERY_SSH_PORT,
|
||||
COMMANDLINE_QUERY_PROTOCOLS,
|
||||
COMMANDLINE_QUERY_SSH_RSA_HOST_KEY,
|
||||
COMMANDLINE_QUERY_TIMEOUT,
|
||||
COMMANDLINE_VERSION,
|
||||
COMMANDLINE_CRASHDUMPSPATH,
|
||||
COMMANDLINE_DAEMON,
|
||||
COMMANDLINE_PID_FILE,
|
||||
COMMANDLINE_HINTS_ENABLED,
|
||||
COMMANDLINE_QUERY_HTTP_IP,
|
||||
COMMANDLINE_QUERY_HTTP_PORT,
|
||||
COMMANDLINE_QUERY_HTTPS_IP,
|
||||
COMMANDLINE_QUERY_HTTPS_PORT,
|
||||
COMMANDLINE_QUERY_HTTPS_CERTIFICATE_FILE,
|
||||
COMMANDLINE_QUERY_HTTPS_PRIVATE_KEY_FILE,
|
||||
COMMANDLINE_QUERY_POOL_SIZE,
|
||||
COMMANDLINE_MMDBPATH,
|
||||
COMMANDLINE_LOGQUERYTIMINGINTERVAL,
|
||||
COMMANDLINE_EVENT_TO_DB_LOGGING,
|
||||
COMMANDLINE_ADMINISTRATIVE_DOMAIN,
|
||||
#endif
|
||||
COMMANDLINE_WEBRTC_SERVER_ENABLED,
|
||||
#else
|
||||
COMMANDLINE_NOTHING = 0,
|
||||
#endif
|
||||
COMMANDLINE_ENDMARKER_RARE,
|
||||
};
|
||||
|
||||
enum ServerInstancePropertiesRare {
|
||||
SERVERINSTANCE_DATABASE_VERSION = 0,
|
||||
SERVERINSTANCE_FILETRANSFER_PORT,
|
||||
SERVERINSTANCE_SERVER_ENTROPY,
|
||||
SERVERINSTANCE_MONTHLY_TIMESTAMP,
|
||||
SERVERINSTANCE_MAX_DOWNLOAD_TOTAL_BANDWIDTH,
|
||||
SERVERINSTANCE_MAX_UPLOAD_TOTAL_BANDWIDTH,
|
||||
SERVERINSTANCE_GUEST_SERVERQUERY_GROUP,
|
||||
SERVERINSTANCE_SERVERQUERY_FLOOD_COMMANDS, //how many commands we can issue while in the SERVERINSTANCE_SERVERQUERY_FLOOD_TIME window
|
||||
SERVERINSTANCE_SERVERQUERY_FLOOD_TIME, //time window in seconds for max command execution check
|
||||
SERVERINSTANCE_SERVERQUERY_BAN_TIME, //how many seconds someone get banned if he floods
|
||||
SERVERINSTANCE_TEMPLATE_SERVERADMIN_GROUP,
|
||||
SERVERINSTANCE_TEMPLATE_SERVERDEFAULT_GROUP,
|
||||
SERVERINSTANCE_TEMPLATE_CHANNELADMIN_GROUP,
|
||||
SERVERINSTANCE_TEMPLATE_CHANNELDEFAULT_GROUP,
|
||||
SERVERINSTANCE_PERMISSIONS_VERSION,
|
||||
SERVERINSTANCE_PENDING_CONNECTIONS_PER_IP,
|
||||
SERVERINSTANCE_SERVERQUERY_MAX_CONNECTIONS_PER_IP,
|
||||
SERVERINSTANCE_MAX_HOMEBASES, //How many matrix homebase users this instance can have. -1 for no limit
|
||||
SERVERINSTANCE_ENDMARKER_RARE,
|
||||
};
|
||||
|
||||
enum VirtualServerPropertiesRare {
|
||||
VIRTUALSERVER_DUMMY_1 = VIRTUALSERVER_ENDMARKER,
|
||||
VIRTUALSERVER_DUMMY_2,
|
||||
VIRTUALSERVER_DUMMY_3,
|
||||
VIRTUALSERVER_DUMMY_4,
|
||||
VIRTUALSERVER_DUMMY_5,
|
||||
VIRTUALSERVER_DUMMY_6,
|
||||
VIRTUALSERVER_DUMMY_7,
|
||||
VIRTUALSERVER_DUMMY_8,
|
||||
VIRTUALSERVER_KEYPAIR, //internal use
|
||||
VIRTUALSERVER_HOSTMESSAGE, //available when connected, not updated while connected
|
||||
VIRTUALSERVER_HOSTMESSAGE_MODE, //available when connected, not updated while connected
|
||||
// VIRTUALSERVER_FILEBASE, // Moved to VirtualServerProperties due to SDK usage
|
||||
VIRTUALSERVER_DEFAULT_SERVER_GROUP = 25, //the client permissions server group that a new client gets assigned
|
||||
VIRTUALSERVER_DEFAULT_CHANNEL_GROUP, //the channel permissions group that a new client gets assigned when joining a channel
|
||||
VIRTUALSERVER_FLAG_PASSWORD, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_DEFAULT_CHANNEL_ADMIN_GROUP, //the channel permissions group that a client gets assigned when creating a channel
|
||||
// VIRTUALSERVER_MAX_DOWNLOAD_TOTAL_BANDWIDTH, // Moved to VirtualServerProperties due to SDK usage
|
||||
// VIRTUALSERVER_MAX_UPLOAD_TOTAL_BANDWIDTH, // Moved to VirtualServerProperties due to SDK usage
|
||||
VIRTUALSERVER_HOSTBANNER_URL = 31, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_HOSTBANNER_GFX_URL, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_HOSTBANNER_GFX_INTERVAL, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_COMPLAIN_AUTOBAN_COUNT, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_COMPLAIN_AUTOBAN_TIME, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_COMPLAIN_REMOVE_TIME, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_MIN_CLIENTS_IN_CHANNEL_BEFORE_FORCED_SILENCE, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_PRIORITY_SPEAKER_DIMM_MODIFICATOR, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_ID, //available when connected
|
||||
VIRTUALSERVER_ANTIFLOOD_POINTS_TICK_REDUCE, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_COMMAND_BLOCK, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_IP_BLOCK, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_CLIENT_CONNECTIONS, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_QUERY_CLIENT_CONNECTIONS, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_HOSTBUTTON_TOOLTIP, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_HOSTBUTTON_URL, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_HOSTBUTTON_GFX_URL, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_QUERYCLIENTS_ONLINE, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_DOWNLOAD_QUOTA, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_UPLOAD_QUOTA, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_MONTH_BYTES_DOWNLOADED, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_MONTH_BYTES_UPLOADED, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_TOTAL_BYTES_DOWNLOADED, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_TOTAL_BYTES_UPLOADED, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_PORT, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_AUTOSTART, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_MACHINE_ID, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_NEEDED_IDENTITY_SECURITY_LEVEL, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_LOG_CLIENT, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_LOG_QUERY, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_LOG_CHANNEL, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_LOG_PERMISSIONS, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_LOG_SERVER, //only available on request (=> requestServerVariables)
|
||||
// VIRTUALSERVER_LOG_FILETRANSFER, // Moved to VirtualServerProperties due to SDK usage
|
||||
VIRTUALSERVER_MIN_CLIENT_VERSION = 65, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_NAME_PHONETIC, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_ICON_ID, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_RESERVED_SLOTS, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_TOTAL_PACKETLOSS_SPEECH, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_TOTAL_PACKETLOSS_KEEPALIVE, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_TOTAL_PACKETLOSS_CONTROL, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_TOTAL_PACKETLOSS_TOTAL, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_TOTAL_PING, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_IP, //internal use | contains comma separated ip list
|
||||
VIRTUALSERVER_WEBLIST_ENABLED, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_AUTOGENERATED_PRIVILEGEKEY, //internal use
|
||||
VIRTUALSERVER_ASK_FOR_PRIVILEGEKEY, //available when connected
|
||||
VIRTUALSERVER_HOSTBANNER_MODE, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_CHANNEL_TEMP_DELETE_DELAY_DEFAULT, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_MIN_ANDROID_VERSION, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_MIN_IOS_VERSION, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_MIN_WINPHONE_VERSION, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_NICKNAME, //available when connected, always up-to-date
|
||||
VIRTUALSERVER_ACCOUNTING_TOKEN, //internal use | contains base64 encoded token data
|
||||
VIRTUALSERVER_PROTOCOL_VERIFY_KEYPAIR, //internal use
|
||||
VIRTUALSERVER_ANTIFLOOD_POINTS_NEEDED_PLUGIN_BLOCK, //only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_CAPABILITY_EXTENSIONS, //available when connected, not updated while connected
|
||||
VIRTUALSERVER_STORAGE_QUOTA, // Allowed filetransfer storage on this server (including chat attachments) in megabytes
|
||||
VIRTUALSERVER_WEBRTC_CERTIFICATE, //internal use
|
||||
VIRTUALSERVER_WEBRTC_PRIVATE_KEY, //internal use
|
||||
VIRTUALSERVER_UUID, //the uuid of the server (uuid v5 of VIRTUALSERVER_UNIQUE_IDENTIFIER)
|
||||
VIRTUALSERVER_ADMINISTRATIVE_DOMAIN, //The domain which is responsible for this teamspeak server (which hosts its .well-known file)
|
||||
VIRTUALSERVER_CANONICAL_NAME, //The canonical name under which the server is reachable
|
||||
VIRTUALSERVER_MYTSID_CONNECT_ONLY, //Only clients that have a valid mytsid can connect
|
||||
VIRTUALSERVER_MAX_HOMEBASES, //How many matrix homebases this virtual server supports. -1 = no limit
|
||||
VIRTUALSERVER_HOMEBASE_STORAGE_QUOTA, // Allowed filetransfer storage for homebase attachments in megabytes
|
||||
VIRTUALSERVER_ENDMARKER_RARE
|
||||
};
|
||||
|
||||
enum ChannelPropertiesRare {
|
||||
CHANNEL_DUMMY_3 = CHANNEL_ENDMARKER,
|
||||
CHANNEL_DUMMY_4,
|
||||
CHANNEL_DUMMY_5,
|
||||
CHANNEL_DUMMY_6,
|
||||
CHANNEL_DUMMY_7,
|
||||
CHANNEL_FLAG_MAXCLIENTS_UNLIMITED, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_FLAG_MAXFAMILYCLIENTS_UNLIMITED, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_FLAG_MAXFAMILYCLIENTS_INHERITED, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_FLAG_ARE_SUBSCRIBED, //Only available client side, stores whether we are subscribed to this channel
|
||||
CHANNEL_FILEPATH, //not available client side, the folder used for file-transfers for this channel
|
||||
CHANNEL_NEEDED_TALK_POWER, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_FORCED_SILENCE, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_NAME_PHONETIC, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_ICON_ID, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_BANNER_GFX_URL, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_BANNER_MODE, //Available for all channels that are "in view", always up-to-date
|
||||
CHANNEL_PERMISSION_HINTS,
|
||||
CHANNEL_STORAGE_QUOTA, // Storage space that is allowed to be used by this channels files (in MiB)
|
||||
CHANNEL_ENDMARKER_RARE,
|
||||
CHANNEL_DELETE_DELAY_DEADLINE = 127 //(for clientlibv2) expected delete time in monotonic clock seconds or 0 if nothing is expected
|
||||
};
|
||||
|
||||
enum ClientPropertiesRare {
|
||||
CLIENT_DUMMY_4 = CLIENT_ENDMARKER,
|
||||
CLIENT_DUMMY_5,
|
||||
CLIENT_DUMMY_6,
|
||||
CLIENT_DUMMY_7,
|
||||
CLIENT_DUMMY_8,
|
||||
CLIENT_DUMMY_9,
|
||||
CLIENT_KEY_OFFSET, //internal use
|
||||
CLIENT_LAST_VAR_REQUEST, //internal use
|
||||
CLIENT_LOGIN_NAME, //used for serverquery clients, makes no sense on normal clients currently
|
||||
CLIENT_LOGIN_PASSWORD, //used for serverquery clients, makes no sense on normal clients currently
|
||||
CLIENT_DATABASE_ID, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds database client id
|
||||
CLIENT_CHANNEL_GROUP_ID, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds database client id
|
||||
CLIENT_SERVERGROUPS, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds all servergroups client belongs too
|
||||
CLIENT_CREATED, //this needs to be requested (=> requestClientVariables), first time this client connected to this server
|
||||
CLIENT_LASTCONNECTED, //this needs to be requested (=> requestClientVariables), last time this client connected to this server
|
||||
CLIENT_TOTALCONNECTIONS, //this needs to be requested (=> requestClientVariables), how many times this client connected to this server
|
||||
CLIENT_AWAY, //automatically up-to-date for any client "in view", this clients away status
|
||||
CLIENT_AWAY_MESSAGE, //automatically up-to-date for any client "in view", this clients away message
|
||||
CLIENT_TYPE, //automatically up-to-date for any client "in view", determines if this is a real client or a server-query connection
|
||||
CLIENT_FLAG_AVATAR, //automatically up-to-date for any client "in view", this client got an avatar
|
||||
CLIENT_TALK_POWER, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds database client id
|
||||
CLIENT_TALK_REQUEST, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds timestamp where client requested to talk
|
||||
CLIENT_TALK_REQUEST_MSG, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, holds matter for the request
|
||||
CLIENT_DESCRIPTION, //automatically up-to-date for any client "in view"
|
||||
CLIENT_IS_TALKER, //automatically up-to-date for any client "in view"
|
||||
CLIENT_MONTH_BYTES_UPLOADED, //this needs to be requested (=> requestClientVariables)
|
||||
CLIENT_MONTH_BYTES_DOWNLOADED, //this needs to be requested (=> requestClientVariables)
|
||||
CLIENT_TOTAL_BYTES_UPLOADED, //this needs to be requested (=> requestClientVariables)
|
||||
CLIENT_TOTAL_BYTES_DOWNLOADED, //this needs to be requested (=> requestClientVariables)
|
||||
CLIENT_IS_PRIORITY_SPEAKER, //automatically up-to-date for any client "in view"
|
||||
CLIENT_UNREAD_MESSAGES, //automatically up-to-date for any client "in view"
|
||||
CLIENT_NICKNAME_PHONETIC, //automatically up-to-date for any client "in view"
|
||||
CLIENT_NEEDED_SERVERQUERY_VIEW_POWER, //automatically up-to-date for any client "in view"
|
||||
CLIENT_DEFAULT_TOKEN, //only usable for ourself, the default token we used to connect on our last connection attempt
|
||||
CLIENT_ICON_ID, //automatically up-to-date for any client "in view"
|
||||
CLIENT_IS_CHANNEL_COMMANDER, //automatically up-to-date for any client "in view"
|
||||
CLIENT_COUNTRY, //automatically up-to-date for any client "in view"
|
||||
CLIENT_CHANNEL_GROUP_INHERITED_CHANNEL_ID, //automatically up-to-date for any client "in view", only valid with PERMISSION feature, contains channel_id where the channel_group_id is set from
|
||||
CLIENT_BADGES, //automatically up-to-date for any client "in view", stores icons for partner badges
|
||||
CLIENT_MYTEAMSPEAK_ID, //automatically up-to-date for any client "in view", stores myteamspeak id
|
||||
CLIENT_INTEGRATIONS, //automatically up-to-date for any client "in view", stores integrations
|
||||
CLIENT_ACTIVE_INTEGRATIONS_INFO, //stores info from the myts server and contains the subscription info
|
||||
CLIENT_MYTS_AVATAR,
|
||||
CLIENT_SIGNED_BADGES,
|
||||
CLIENT_PERMISSION_HINTS,
|
||||
CLIENT_USER_TAG, //automatically up-to-date for any client "in view", stores public chat user tag
|
||||
CLIENT_ENDMARKER_RARE,
|
||||
CLIENT_HW_ID = 127 //(for clientlibv2) unique hardware id
|
||||
};
|
||||
|
||||
enum BBCodeTags {
|
||||
BBCodeTag_B = 0x00000001,
|
||||
BBCodeTag_I = 0x00000002,
|
||||
BBCodeTag_U = 0x00000004,
|
||||
BBCodeTag_S = 0x00000008,
|
||||
BBCodeTag_SUP = 0x00000010,
|
||||
BBCodeTag_SUB = 0x00000020,
|
||||
BBCodeTag_COLOR = 0x00000040,
|
||||
BBCodeTag_SIZE = 0x00000080,
|
||||
BBCodeTag_group_text = 0x000000FF,
|
||||
|
||||
BBCodeTag_LEFT = 0x00001000,
|
||||
BBCodeTag_RIGHT = 0x00002000,
|
||||
BBCodeTag_CENTER = 0x00004000,
|
||||
BBCodeTag_group_align = 0x00007000,
|
||||
|
||||
BBCodeTag_URL = 0x00010000,
|
||||
BBCodeTag_IMAGE = 0x00020000,
|
||||
BBCodeTag_HR = 0x00040000,
|
||||
|
||||
BBCodeTag_LIST = 0x00100000,
|
||||
BBCodeTag_LISTITEM = 0x00200000,
|
||||
BBCodeTag_group_list = 0x00300000,
|
||||
|
||||
BBCodeTag_TABLE = 0x00400000,
|
||||
BBCodeTag_TR = 0x00800000,
|
||||
BBCodeTag_TH = 0x01000000,
|
||||
BBCodeTag_TD = 0x02000000,
|
||||
BBCodeTag_group_table = 0x03C00000,
|
||||
|
||||
BBCodeTag_def_simple = BBCodeTag_B | BBCodeTag_I | BBCodeTag_U | BBCodeTag_S | BBCodeTag_SUP | BBCodeTag_SUB | BBCodeTag_COLOR | BBCodeTag_URL,
|
||||
BBCodeTag_def_simple_Img = BBCodeTag_def_simple | BBCodeTag_IMAGE,
|
||||
BBCodeTag_def_extended = BBCodeTag_group_text | BBCodeTag_group_align | BBCodeTag_URL | BBCodeTag_IMAGE | BBCodeTag_HR | BBCodeTag_group_list | BBCodeTag_group_table,
|
||||
};
|
||||
|
||||
enum LicenseIssue { Blacklisted = 0, Greylisted };
|
||||
|
||||
enum MytsDataUnsetFlags {
|
||||
MytsDataUnsetFlag_None = 0,
|
||||
MytsDataUnsetFlag_Badges = 1,
|
||||
MytsDataUnsetFlag_Avatar = 1 << 1,
|
||||
|
||||
MytsDataUnsetFlag_All = MytsDataUnsetFlag_Badges | MytsDataUnsetFlag_Avatar // make sure "all" really contains all flags
|
||||
};
|
||||
|
||||
typedef int (*ExtraBBCodeValidator)(void* userparam, const char* tag, const char* paramValue, int paramValueSize, const char* childValue, int childValueSize);
|
||||
typedef const char* (*ExtraBBCodeParamTransform)(void* userparam, const char* tag, const char* paramValue);
|
||||
|
||||
#endif //PUBLIC_RARE_DEFINITIONS_H
|
||||
@@ -0,0 +1,312 @@
|
||||
#ifndef TS3_FUNCTIONS_H
|
||||
#define TS3_FUNCTIONS_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include "plugin_definitions.h"
|
||||
#include "teamspeak/public_definitions.h"
|
||||
|
||||
/* Functions exported to plugin from main binary */
|
||||
struct TS3Functions {
|
||||
unsigned int (*getClientLibVersion)(char** result);
|
||||
unsigned int (*getClientLibVersionNumber)(uint64* result);
|
||||
unsigned int (*spawnNewServerConnectionHandler)(int port, uint64* result);
|
||||
unsigned int (*destroyServerConnectionHandler)(uint64 serverConnectionHandlerID);
|
||||
|
||||
/* Error handling */
|
||||
unsigned int (*getErrorMessage)(unsigned int errorCode, char** error);
|
||||
|
||||
/* Memory management */
|
||||
unsigned int (*freeMemory)(void* pointer);
|
||||
|
||||
/* Logging */
|
||||
unsigned int (*logMessage)(const char* logMessage, enum LogLevel severity, const char* channel, uint64 logID);
|
||||
|
||||
/* Sound */
|
||||
unsigned int (*getPlaybackDeviceList)(const char* modeID, char**** result);
|
||||
unsigned int (*getPlaybackModeList)(char*** result);
|
||||
unsigned int (*getCaptureDeviceList)(const char* modeID, char**** result);
|
||||
unsigned int (*getCaptureModeList)(char*** result);
|
||||
unsigned int (*getDefaultPlaybackDevice)(const char* modeID, char*** result);
|
||||
unsigned int (*getDefaultPlayBackMode)(char** result);
|
||||
unsigned int (*getDefaultCaptureDevice)(const char* modeID, char*** result);
|
||||
unsigned int (*getDefaultCaptureMode)(char** result);
|
||||
unsigned int (*openPlaybackDevice)(uint64 serverConnectionHandlerID, const char* modeID, const char* playbackDevice);
|
||||
unsigned int (*openCaptureDevice)(uint64 serverConnectionHandlerID, const char* modeID, const char* captureDevice);
|
||||
unsigned int (*getCurrentPlaybackDeviceName)(uint64 serverConnectionHandlerID, char** result, int* isDefault);
|
||||
unsigned int (*getCurrentPlayBackMode)(uint64 serverConnectionHandlerID, char** result);
|
||||
unsigned int (*getCurrentCaptureDeviceName)(uint64 serverConnectionHandlerID, char** result, int* isDefault);
|
||||
unsigned int (*getCurrentCaptureMode)(uint64 serverConnectionHandlerID, char** result);
|
||||
unsigned int (*initiateGracefulPlaybackShutdown)(uint64 serverConnectionHandlerID);
|
||||
unsigned int (*closePlaybackDevice)(uint64 serverConnectionHandlerID);
|
||||
unsigned int (*closeCaptureDevice)(uint64 serverConnectionHandlerID);
|
||||
unsigned int (*activateCaptureDevice)(uint64 serverConnectionHandlerID);
|
||||
unsigned int (*playWaveFileHandle)(uint64 serverConnectionHandlerID, const char* path, int loop, uint64* waveHandle);
|
||||
unsigned int (*pauseWaveFileHandle)(uint64 serverConnectionHandlerID, uint64 waveHandle, int pause);
|
||||
unsigned int (*closeWaveFileHandle)(uint64 serverConnectionHandlerID, uint64 waveHandle);
|
||||
unsigned int (*playWaveFile)(uint64 serverConnectionHandlerID, const char* path);
|
||||
unsigned int (*registerCustomDevice)(const char* deviceID, const char* deviceDisplayName, int capFrequency, int capChannels, int playFrequency, int playChannels);
|
||||
unsigned int (*unregisterCustomDevice)(const char* deviceID);
|
||||
unsigned int (*processCustomCaptureData)(const char* deviceName, const short* buffer, int samples);
|
||||
unsigned int (*acquireCustomPlaybackData)(const char* deviceName, short* buffer, int samples);
|
||||
|
||||
/* Preprocessor */
|
||||
unsigned int (*getPreProcessorInfoValueFloat)(uint64 serverConnectionHandlerID, const char* ident, float* result);
|
||||
unsigned int (*getPreProcessorConfigValue)(uint64 serverConnectionHandlerID, const char* ident, char** result);
|
||||
unsigned int (*setPreProcessorConfigValue)(uint64 serverConnectionHandlerID, const char* ident, const char* value);
|
||||
|
||||
/* Encoder */
|
||||
unsigned int (*getEncodeConfigValue)(uint64 serverConnectionHandlerID, const char* ident, char** result);
|
||||
|
||||
/* Playback */
|
||||
unsigned int (*getPlaybackConfigValueAsFloat)(uint64 serverConnectionHandlerID, const char* ident, float* result);
|
||||
unsigned int (*setPlaybackConfigValue)(uint64 serverConnectionHandlerID, const char* ident, const char* value);
|
||||
unsigned int (*setClientVolumeModifier)(uint64 serverConnectionHandlerID, anyID clientID, float value);
|
||||
|
||||
/* Recording status */
|
||||
unsigned int (*startVoiceRecording)(uint64 serverConnectionHandlerID);
|
||||
unsigned int (*stopVoiceRecording)(uint64 serverConnectionHandlerID);
|
||||
|
||||
/* 3d sound positioning */
|
||||
unsigned int (*systemset3DListenerAttributes)(uint64 serverConnectionHandlerID, const TS3_VECTOR* position, const TS3_VECTOR* forward, const TS3_VECTOR* up);
|
||||
unsigned int (*set3DWaveAttributes)(uint64 serverConnectionHandlerID, uint64 waveHandle, const TS3_VECTOR* position);
|
||||
unsigned int (*systemset3DSettings)(uint64 serverConnectionHandlerID, float distanceFactor, float rolloffScale);
|
||||
unsigned int (*channelset3DAttributes)(uint64 serverConnectionHandlerID, anyID clientID, const TS3_VECTOR* position);
|
||||
|
||||
/* Interaction with the server */
|
||||
unsigned int (*startConnection)(uint64 serverConnectionHandlerID, const char* identity, const char* ip, unsigned int port, const char* nickname, const char** defaultChannelArray, const char* defaultChannelPassword, const char* serverPassword);
|
||||
unsigned int (*stopConnection)(uint64 serverConnectionHandlerID, const char* quitMessage);
|
||||
unsigned int (*requestClientMove)(uint64 serverConnectionHandlerID, anyID clientID, uint64 newChannelID, const char* password, const char* returnCode);
|
||||
unsigned int (*requestClientVariables)(uint64 serverConnectionHandlerID, anyID clientID, const char* returnCode);
|
||||
unsigned int (*requestClientKickFromChannel)(uint64 serverConnectionHandlerID, anyID clientID, const char* kickReason, const char* returnCode);
|
||||
unsigned int (*requestClientKickFromServer)(uint64 serverConnectionHandlerID, anyID clientID, const char* kickReason, const char* returnCode);
|
||||
unsigned int (*requestChannelDelete)(uint64 serverConnectionHandlerID, uint64 channelID, int force, const char* returnCode);
|
||||
unsigned int (*requestChannelMove)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 newChannelParentID, uint64 newChannelOrder, const char* returnCode);
|
||||
unsigned int (*requestSendPrivateTextMsg)(uint64 serverConnectionHandlerID, const char* message, anyID targetClientID, const char* returnCode);
|
||||
unsigned int (*requestSendChannelTextMsg)(uint64 serverConnectionHandlerID, const char* message, uint64 targetChannelID, const char* returnCode);
|
||||
unsigned int (*requestSendServerTextMsg)(uint64 serverConnectionHandlerID, const char* message, const char* returnCode);
|
||||
unsigned int (*requestConnectionInfo)(uint64 serverConnectionHandlerID, anyID clientID, const char* returnCode);
|
||||
unsigned int (*requestClientSetWhisperList)(uint64 serverConnectionHandlerID, anyID clientID, const uint64* targetChannelIDArray, const anyID* targetClientIDArray, const char* returnCode);
|
||||
unsigned int (*requestChannelSubscribe)(uint64 serverConnectionHandlerID, const uint64* channelIDArray, const char* returnCode);
|
||||
unsigned int (*requestChannelSubscribeAll)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*requestChannelUnsubscribe)(uint64 serverConnectionHandlerID, const uint64* channelIDArray, const char* returnCode);
|
||||
unsigned int (*requestChannelUnsubscribeAll)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*requestChannelDescription)(uint64 serverConnectionHandlerID, uint64 channelID, const char* returnCode);
|
||||
unsigned int (*requestMuteClients)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
|
||||
unsigned int (*requestUnmuteClients)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
|
||||
unsigned int (*requestClientPoke)(uint64 serverConnectionHandlerID, anyID clientID, const char* message, const char* returnCode);
|
||||
unsigned int (*requestClientIDs)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, const char* returnCode);
|
||||
unsigned int (*clientChatClosed)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, anyID clientID, const char* returnCode);
|
||||
unsigned int (*clientChatComposing)(uint64 serverConnectionHandlerID, anyID clientID, const char* returnCode);
|
||||
unsigned int (*requestServerTemporaryPasswordAdd)(uint64 serverConnectionHandlerID, const char* password, const char* description, uint64 duration, uint64 targetChannelID, const char* targetChannelPW, const char* returnCode);
|
||||
unsigned int (*requestServerTemporaryPasswordDel)(uint64 serverConnectionHandlerID, const char* password, const char* returnCode);
|
||||
unsigned int (*requestServerTemporaryPasswordList)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
|
||||
/* Access clientlib information */
|
||||
|
||||
/* Query own client ID */
|
||||
unsigned int (*getClientID)(uint64 serverConnectionHandlerID, anyID* result);
|
||||
|
||||
/* Client info */
|
||||
unsigned int (*getClientSelfVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int* result);
|
||||
unsigned int (*getClientSelfVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, char** result);
|
||||
unsigned int (*setClientSelfVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int value);
|
||||
unsigned int (*setClientSelfVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, const char* value);
|
||||
unsigned int (*flushClientSelfUpdates)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*getClientVariableAsInt)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, int* result);
|
||||
unsigned int (*getClientVariableAsUInt64)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, uint64* result);
|
||||
unsigned int (*getClientVariableAsString)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, char** result);
|
||||
unsigned int (*getClientList)(uint64 serverConnectionHandlerID, anyID** result);
|
||||
unsigned int (*getChannelOfClient)(uint64 serverConnectionHandlerID, anyID clientID, uint64* result);
|
||||
|
||||
/* Channel info */
|
||||
unsigned int (*getChannelVariableAsInt)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, int* result);
|
||||
unsigned int (*getChannelVariableAsUInt64)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, uint64* result);
|
||||
unsigned int (*getChannelVariableAsString)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, char** result);
|
||||
unsigned int (*getChannelIDFromChannelNames)(uint64 serverConnectionHandlerID, char** channelNameArray, uint64* result);
|
||||
unsigned int (*setChannelVariableAsInt)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, int value);
|
||||
unsigned int (*setChannelVariableAsUInt64)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, uint64 value);
|
||||
unsigned int (*setChannelVariableAsString)(uint64 serverConnectionHandlerID, uint64 channelID, size_t flag, const char* value);
|
||||
unsigned int (*flushChannelUpdates)(uint64 serverConnectionHandlerID, uint64 channelID, const char* returnCode);
|
||||
unsigned int (*flushChannelCreation)(uint64 serverConnectionHandlerID, uint64 channelParentID, const char* returnCode);
|
||||
unsigned int (*getChannelList)(uint64 serverConnectionHandlerID, uint64** result);
|
||||
unsigned int (*getChannelClientList)(uint64 serverConnectionHandlerID, uint64 channelID, anyID** result);
|
||||
unsigned int (*getParentChannelOfChannel)(uint64 serverConnectionHandlerID, uint64 channelID, uint64* result);
|
||||
|
||||
/* Server info */
|
||||
unsigned int (*getServerConnectionHandlerList)(uint64** result);
|
||||
unsigned int (*getServerVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int* result);
|
||||
unsigned int (*getServerVariableAsUInt64)(uint64 serverConnectionHandlerID, size_t flag, uint64* result);
|
||||
unsigned int (*getServerVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, char** result);
|
||||
unsigned int (*requestServerVariables)(uint64 serverConnectionHandlerID);
|
||||
|
||||
/* Connection info */
|
||||
unsigned int (*getConnectionStatus)(uint64 serverConnectionHandlerID, int* result);
|
||||
unsigned int (*getConnectionVariableAsUInt64)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, uint64* result);
|
||||
unsigned int (*getConnectionVariableAsDouble)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, double* result);
|
||||
unsigned int (*getConnectionVariableAsString)(uint64 serverConnectionHandlerID, anyID clientID, size_t flag, char** result);
|
||||
unsigned int (*cleanUpConnectionInfo)(uint64 serverConnectionHandlerID, anyID clientID);
|
||||
|
||||
/* Client related */
|
||||
unsigned int (*requestClientDBIDfromUID)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, const char* returnCode);
|
||||
unsigned int (*requestClientNamefromUID)(uint64 serverConnectionHandlerID, const char* clientUniqueIdentifier, const char* returnCode);
|
||||
unsigned int (*requestClientNamefromDBID)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestClientEditDescription)(uint64 serverConnectionHandlerID, anyID clientID, const char* clientDescription, const char* returnCode);
|
||||
unsigned int (*requestClientSetIsTalker)(uint64 serverConnectionHandlerID, anyID clientID, int isTalker, const char* returnCode);
|
||||
unsigned int (*requestIsTalker)(uint64 serverConnectionHandlerID, int isTalkerRequest, const char* isTalkerRequestMessage, const char* returnCode);
|
||||
|
||||
/* Plugin related */
|
||||
unsigned int (*requestSendClientQueryCommand)(uint64 serverConnectionHandlerID, const char* command, const char* returnCode);
|
||||
|
||||
/* Filetransfer */
|
||||
unsigned int (*getTransferFileName)(anyID transferID, char** result);
|
||||
unsigned int (*getTransferFilePath)(anyID transferID, char** result);
|
||||
unsigned int (*getTransferFileSize)(anyID transferID, uint64* result);
|
||||
unsigned int (*getTransferFileSizeDone)(anyID transferID, uint64* result);
|
||||
unsigned int (*isTransferSender)(anyID transferID, int* result); /* 1 == upload, 0 == download */
|
||||
unsigned int (*getTransferStatus)(anyID transferID, int* result);
|
||||
unsigned int (*getCurrentTransferSpeed)(anyID transferID, float* result);
|
||||
unsigned int (*getAverageTransferSpeed)(anyID transferID, float* result);
|
||||
unsigned int (*getTransferRunTime)(anyID transferID, uint64* result);
|
||||
unsigned int (*sendFile)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* file, int overwrite, int resume, const char* sourceDirectory, anyID* result, const char* returnCode);
|
||||
unsigned int (*requestFile)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* file, int overwrite, int resume, const char* destinationDirectory, anyID* result, const char* returnCode);
|
||||
unsigned int (*haltTransfer)(uint64 serverConnectionHandlerID, anyID transferID, int deleteUnfinishedFile, const char* returnCode);
|
||||
unsigned int (*requestFileList)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* path, const char* returnCode);
|
||||
unsigned int (*requestFileInfo)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* file, const char* returnCode);
|
||||
unsigned int (*requestDeleteFile)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char** file, const char* returnCode);
|
||||
unsigned int (*requestCreateDirectory)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPW, const char* directoryPath, const char* returnCode);
|
||||
unsigned int (*requestRenameFile)(uint64 serverConnectionHandlerID, uint64 fromChannelID, const char* channelPW, uint64 toChannelID, const char* toChannelPW, const char* oldFile, const char* newFile, const char* returnCode);
|
||||
|
||||
/* Offline message management */
|
||||
unsigned int (*requestMessageAdd)(uint64 serverConnectionHandlerID, const char* toClientUID, const char* subject, const char* message, const char* returnCode);
|
||||
unsigned int (*requestMessageDel)(uint64 serverConnectionHandlerID, uint64 messageID, const char* returnCode);
|
||||
unsigned int (*requestMessageGet)(uint64 serverConnectionHandlerID, uint64 messageID, const char* returnCode);
|
||||
unsigned int (*requestMessageList)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*requestMessageUpdateFlag)(uint64 serverConnectionHandlerID, uint64 messageID, int flag, const char* returnCode);
|
||||
|
||||
/* Interacting with the server - confirming passwords */
|
||||
unsigned int (*verifyServerPassword)(uint64 serverConnectionHandlerID, const char* serverPassword, const char* returnCode);
|
||||
unsigned int (*verifyChannelPassword)(uint64 serverConnectionHandlerID, uint64 channelID, const char* channelPassword, const char* returnCode);
|
||||
|
||||
/* Interacting with the server - banning */
|
||||
unsigned int (*banclient)(uint64 serverConnectionHandlerID, anyID clientID, uint64 timeInSeconds, const char* banReason, const char* returnCode);
|
||||
unsigned int (*banadd)(uint64 serverConnectionHandlerID, const char* ipRegExp, const char* nameRegexp, const char* uniqueIdentity, const char* mytsID, uint64 timeInSeconds, const char* banReason, const char* returnCode);
|
||||
unsigned int (*banclientdbid)(uint64 serverConnectionHandlerID, uint64 clientDBID, uint64 timeInSeconds, const char* banReason, const char* returnCode);
|
||||
unsigned int (*bandel)(uint64 serverConnectionHandlerID, uint64 banID, const char* returnCode);
|
||||
unsigned int (*bandelall)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*requestBanList)(uint64 serverConnectionHandlerID, uint64 start, unsigned int duration, const char* returnCode);
|
||||
|
||||
/* Interacting with the server - complain */
|
||||
unsigned int (*requestComplainAdd)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, const char* complainReason, const char* returnCode);
|
||||
unsigned int (*requestComplainDel)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, uint64 fromClientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestComplainDelAll)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestComplainList)(uint64 serverConnectionHandlerID, uint64 targetClientDatabaseID, const char* returnCode);
|
||||
|
||||
/* Permissions */
|
||||
unsigned int (*requestServerGroupList)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*requestServerGroupAdd)(uint64 serverConnectionHandlerID, const char* groupName, int groupType, const char* returnCode);
|
||||
unsigned int (*requestServerGroupDel)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int force, const char* returnCode);
|
||||
unsigned int (*requestServerGroupAddClient)(uint64 serverConnectionHandlerID, uint64 serverGroupID, uint64 clientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestServerGroupDelClient)(uint64 serverConnectionHandlerID, uint64 serverGroupID, uint64 clientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestServerGroupsByClientID)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestServerGroupAddPerm)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int continueonerror, const unsigned int* permissionIDArray, const int* permissionValueArray, const int* permissionNegatedArray,
|
||||
const int* permissionSkipArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestServerGroupDelPerm)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int continueOnError, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestServerGroupPermList)(uint64 serverConnectionHandlerID, uint64 serverGroupID, const char* returnCode);
|
||||
unsigned int (*requestServerGroupClientList)(uint64 serverConnectionHandlerID, uint64 serverGroupID, int withNames, const char* returnCode);
|
||||
unsigned int (*requestChannelGroupList)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
unsigned int (*requestChannelGroupAdd)(uint64 serverConnectionHandlerID, const char* groupName, int groupType, const char* returnCode);
|
||||
unsigned int (*requestChannelGroupDel)(uint64 serverConnectionHandlerID, uint64 channelGroupID, int force, const char* returnCode);
|
||||
unsigned int (*requestChannelGroupAddPerm)(uint64 serverConnectionHandlerID, uint64 channelGroupID, int continueonerror, const unsigned int* permissionIDArray, const int* permissionValueArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelGroupDelPerm)(uint64 serverConnectionHandlerID, uint64 channelGroupID, int continueOnError, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelGroupPermList)(uint64 serverConnectionHandlerID, uint64 channelGroupID, const char* returnCode);
|
||||
unsigned int (*requestSetClientChannelGroup)(uint64 serverConnectionHandlerID, const uint64* channelGroupIDArray, const uint64* channelIDArray, const uint64* clientDatabaseIDArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelAddPerm)(uint64 serverConnectionHandlerID, uint64 channelID, const unsigned int* permissionIDArray, const int* permissionValueArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelDelPerm)(uint64 serverConnectionHandlerID, uint64 channelID, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelPermList)(uint64 serverConnectionHandlerID, uint64 channelID, const char* returnCode);
|
||||
unsigned int (*requestClientAddPerm)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, const int* permissionValueArray, const int* permissionSkipArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestClientDelPerm)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestClientPermList)(uint64 serverConnectionHandlerID, uint64 clientDatabaseID, const char* returnCode);
|
||||
unsigned int (*requestChannelClientAddPerm)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, const int* permissionValueArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelClientDelPerm)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, const unsigned int* permissionIDArray, int arraySize, const char* returnCode);
|
||||
unsigned int (*requestChannelClientPermList)(uint64 serverConnectionHandlerID, uint64 channelID, uint64 clientDatabaseID, const char* returnCode);
|
||||
unsigned int (*privilegeKeyUse)(uint64 serverConnectionHandler, const char* tokenKey, const char* returnCode);
|
||||
unsigned int (*requestPermissionList)(uint64 serverConnectionHandler, const char* returnCode);
|
||||
unsigned int (*requestPermissionOverview)(uint64 serverConnectionHandler, uint64 clientDBID, uint64 channelID, const char* returnCode);
|
||||
|
||||
/* Helper Functions */
|
||||
unsigned int (*clientPropertyStringToFlag)(const char* clientPropertyString, size_t* resultFlag);
|
||||
unsigned int (*channelPropertyStringToFlag)(const char* channelPropertyString, size_t* resultFlag);
|
||||
unsigned int (*serverPropertyStringToFlag)(const char* serverPropertyString, size_t* resultFlag);
|
||||
|
||||
/* Client functions */
|
||||
void (*getAppPath)(char* path, size_t maxLen);
|
||||
void (*getResourcesPath)(char* path, size_t maxLen);
|
||||
void (*getConfigPath)(char* path, size_t maxLen);
|
||||
void (*getPluginPath)(char* path, size_t maxLen, const char* pluginID);
|
||||
uint64 (*getCurrentServerConnectionHandlerID)(void);
|
||||
void (*printMessage)(uint64 serverConnectionHandlerID, const char* message, enum PluginMessageTarget messageTarget);
|
||||
void (*printMessageToCurrentTab)(const char* message);
|
||||
void (*urlsToBB)(const char* text, char* result, size_t maxLen);
|
||||
void (*sendPluginCommand)(uint64 serverConnectionHandlerID, const char* pluginID, const char* command, int targetMode, const anyID* targetIDs, const char* returnCode);
|
||||
void (*getDirectories)(const char* path, char* result, size_t maxLen);
|
||||
unsigned int (*getServerConnectInfo)(uint64 scHandlerID, char* host, unsigned short* port, char* password, size_t maxLen);
|
||||
unsigned int (*getChannelConnectInfo)(uint64 scHandlerID, uint64 channelID, char* path, char* password, size_t maxLen);
|
||||
void (*createReturnCode)(const char* pluginID, char* returnCode, size_t maxLen);
|
||||
unsigned int (*requestInfoUpdate)(uint64 scHandlerID, enum PluginItemType itemType, uint64 itemID);
|
||||
uint64 (*getServerVersion)(uint64 scHandlerID);
|
||||
unsigned int (*isWhispering)(uint64 scHandlerID, anyID clientID, int* result);
|
||||
unsigned int (*isReceivingWhisper)(uint64 scHandlerID, anyID clientID, int* result);
|
||||
unsigned int (*getAvatar)(uint64 scHandlerID, anyID clientID, char* result, size_t maxLen);
|
||||
void (*setPluginMenuEnabled)(const char* pluginID, int menuID, int enabled);
|
||||
void (*showHotkeySetup)(void);
|
||||
void (*requestHotkeyInputDialog)(const char* pluginID, const char* keyword, int isDown, void* qParentWindow);
|
||||
unsigned int (*getHotkeyFromKeyword)(const char* pluginID, const char** keywords, char** hotkeys, size_t arrayLen, size_t hotkeyBufSize);
|
||||
unsigned int (*getClientDisplayName)(uint64 scHandlerID, anyID clientID, char* result, size_t maxLen);
|
||||
unsigned int (*getBookmarkList)(struct PluginBookmarkList** list);
|
||||
unsigned int (*getProfileList)(enum PluginGuiProfile profile, int* defaultProfileIdx, char*** result);
|
||||
unsigned int (*guiConnect)(enum PluginConnectTab connectTab, const char* serverLabel, const char* serverAddress, const char* serverPassword, const char* nickname, const char* channel, const char* channelPassword, const char* captureProfile,
|
||||
const char* playbackProfile, const char* hotkeyProfile, const char* soundProfile, const char* userIdentity, const char* oneTimeKey, const char* phoneticName, uint64* scHandlerID);
|
||||
unsigned int (*guiConnectBookmark)(enum PluginConnectTab connectTab, const char* bookmarkuuid, uint64* scHandlerID);
|
||||
unsigned int (*createBookmark)(const char* bookmarkuuid, const char* serverLabel, const char* serverAddress, const char* serverPassword, const char* nickname, const char* channel, const char* channelPassword, const char* captureProfile,
|
||||
const char* playbackProfile, const char* hotkeyProfile, const char* soundProfile, const char* uniqueUserId, const char* oneTimeKey, const char* phoneticName);
|
||||
unsigned int (*getPermissionIDByName)(uint64 serverConnectionHandlerID, const char* permissionName, unsigned int* result);
|
||||
unsigned int (*getClientNeededPermission)(uint64 serverConnectionHandlerID, const char* permissionName, int* result);
|
||||
void (*notifyKeyEvent)(const char* pluginID, const char* keyIdentifier, int up_down);
|
||||
|
||||
/* Single-Track/Multi-Track recording */
|
||||
unsigned int (*startRecording)(uint64 serverConnectionHandlerID, int multitrack, int noFileSelector, const char* path);
|
||||
unsigned int (*stopRecording)(uint64 serverConnectionHandlerID);
|
||||
|
||||
/* Convenience functions */
|
||||
unsigned int (*requestClientsMove)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, uint64 newChannelID, const char* password, const char* returnCode);
|
||||
unsigned int (*requestClientsKickFromChannel)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* kickReason, const char* returnCode);
|
||||
unsigned int (*requestClientsKickFromServer)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* kickReason, const char* returnCode);
|
||||
unsigned int (*requestMuteClientsTemporary)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
|
||||
unsigned int (*requestUnmuteClientsTemporary)(uint64 serverConnectionHandlerID, const anyID* clientIDArray, const char* returnCode);
|
||||
unsigned int (*getPermissionNameByID)(uint64 scHandlerID, unsigned int permissionID, char* result, size_t max_len);
|
||||
unsigned int (*clientPropertyFlagToString)(size_t clientPropertyFlag, char** resultString);
|
||||
unsigned int (*channelPropertyFlagToString)(size_t channelPropertyFlag, char** resultString);
|
||||
unsigned int (*serverPropertyFlagToString)(size_t serverPropertyFlag, char** resultString);
|
||||
|
||||
/* Server editing */
|
||||
unsigned int (*setServerVariableAsInt)(uint64 serverConnectionHandlerID, size_t flag, int value);
|
||||
unsigned int (*setServerVariableAsUInt64)(uint64 serverConnectionHandlerID, size_t flag, uint64 value);
|
||||
unsigned int (*setServerVariableAsDouble)(uint64 serverConnectionHandlerID, size_t flag, double value);
|
||||
unsigned int (*setServerVariableAsString)(uint64 serverConnectionHandlerID, size_t flag, const char* value);
|
||||
unsigned int (*flushServerUpdates)(uint64 serverConnectionHandlerID, const char* returnCode);
|
||||
|
||||
/* Server/Channel group helper functions */
|
||||
unsigned int (*getServerGroupIDByName)(uint64 serverConnectionHandlerID, const char* groupName, unsigned int* result);
|
||||
unsigned int (*getServerGroupNameByID)(uint64 scHandlerID, unsigned int groupID, char* result, size_t max_len);
|
||||
unsigned int (*getChannelGroupIDByName)(uint64 serverConnectionHandlerID, const char* groupName, unsigned int* result);
|
||||
unsigned int (*getChannelGroupNameByID)(uint64 scHandlerID, unsigned int groupID, char* result, size_t max_len);
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,225 @@
|
||||
#include "ts6bot/AudioDecoder.hpp"
|
||||
#include "ts6bot/Config.hpp"
|
||||
#include <iostream>
|
||||
#include <libavutil/log.h>
|
||||
#include <print>
|
||||
|
||||
AudioDecoder::AudioDecoder() { av_log_set_level(AV_LOG_WARNING); }
|
||||
|
||||
AudioDecoder::~AudioDecoder() {
|
||||
Cancel();
|
||||
if (m_thread.joinable())
|
||||
m_thread.join();
|
||||
Cleanup();
|
||||
}
|
||||
|
||||
void AudioDecoder::Cleanup() {
|
||||
if (m_swrCtx) {
|
||||
swr_free(&m_swrCtx);
|
||||
m_swrCtx = nullptr;
|
||||
}
|
||||
if (m_codecCtx) {
|
||||
avcodec_free_context(&m_codecCtx);
|
||||
m_codecCtx = nullptr;
|
||||
}
|
||||
if (m_formatCtx) {
|
||||
avformat_close_input(&m_formatCtx);
|
||||
m_formatCtx = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool AudioDecoder::GetNextChunk(std::vector<short> &outChunk, bool blocking) {
|
||||
std::unique_lock lock(m_queueMtx);
|
||||
|
||||
if (blocking) {
|
||||
m_cv.wait(lock, [&] { return !m_chunkQueue.empty() || m_finished.load(); });
|
||||
}
|
||||
|
||||
if (m_chunkQueue.empty())
|
||||
return false;
|
||||
|
||||
outChunk = std::move(m_chunkQueue.front());
|
||||
m_chunkQueue.pop_front();
|
||||
return true;
|
||||
}
|
||||
|
||||
void AudioDecoder::StartDecode(const std::string &url, int targetSampleRate) {
|
||||
Cancel();
|
||||
if (m_thread.joinable()) {
|
||||
m_thread.join();
|
||||
}
|
||||
// Clear previous data
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_queueMtx);
|
||||
m_chunkQueue.clear();
|
||||
}
|
||||
|
||||
m_isDecodingFinished = false;
|
||||
m_finished = false; // <--- ADD THIS LINE
|
||||
m_status = DecodeStatus::Processing;
|
||||
m_cancelRequested = false;
|
||||
m_thread =
|
||||
std::jthread(&AudioDecoder::InternalDecode, this, url, targetSampleRate);
|
||||
}
|
||||
void AudioDecoder::InternalDecode(std::string url, int targetSampleRate) {
|
||||
|
||||
auto config = ts6bot::Configuration::GetInstance()->getConfig();
|
||||
AVPacket *pkt = nullptr;
|
||||
AVFrame *frame = nullptr;
|
||||
uint8_t *outputBuffer = nullptr;
|
||||
|
||||
AVDictionary *formatOpts = nullptr;
|
||||
|
||||
try {
|
||||
// Example: SOCKS5 without authentication
|
||||
av_dict_set(&formatOpts, "proxy",
|
||||
std::format("socks5h://{}:{}@{}", config.proxy.username,
|
||||
config.proxy.password, config.proxy.url)
|
||||
.c_str(),
|
||||
0);
|
||||
av_dict_set(&formatOpts, "protocol_whitelist",
|
||||
"file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5", 0);
|
||||
|
||||
// Strongly recommended for YouTube
|
||||
av_dict_set(&formatOpts, "user_agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/120.0.0.0 Safari/537.36",
|
||||
0);
|
||||
// Optional but recommended for network streams
|
||||
av_dict_set(&formatOpts, "timeout", "15000000",
|
||||
0); // 5 seconds (microseconds)
|
||||
av_dict_set(&formatOpts, "reconnect", "1", 0);
|
||||
av_dict_set(&formatOpts, "reconnect_streamed", "1", 0);
|
||||
av_dict_set(&formatOpts, "reconnect_delay_max", "5", 0);
|
||||
av_dict_set(&formatOpts, "analyzeduration", "20000000", 0); // 20 seconds
|
||||
av_dict_set(&formatOpts, "probesize", "10240000", 0); // 10 MB buffer for header probing
|
||||
// Reset state flags
|
||||
m_isDecodingFinished = false;
|
||||
// 1. Open Input & Find Stream
|
||||
|
||||
if (avformat_open_input(&m_formatCtx, url.c_str(), nullptr, &formatOpts) <
|
||||
0) {
|
||||
av_dict_free(&formatOpts);
|
||||
throw std::runtime_error("Failed to open input stream: " + url);
|
||||
}
|
||||
if (avformat_find_stream_info(m_formatCtx, nullptr) < 0)
|
||||
throw std::runtime_error("Failed to find stream info");
|
||||
|
||||
const AVCodec *decoder = nullptr;
|
||||
int streamIdx = av_find_best_stream(m_formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1,
|
||||
&decoder, 0);
|
||||
if (streamIdx < 0)
|
||||
throw std::runtime_error("No audio stream found");
|
||||
|
||||
// 2. Setup Multithreaded Decoder
|
||||
m_codecCtx = avcodec_alloc_context3(decoder);
|
||||
avcodec_parameters_to_context(m_codecCtx,
|
||||
m_formatCtx->streams[streamIdx]->codecpar);
|
||||
|
||||
m_codecCtx->thread_count = 0; // Auto-detect CPU cores
|
||||
m_codecCtx->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
|
||||
|
||||
if (avcodec_open2(m_codecCtx, decoder, nullptr) < 0)
|
||||
throw std::runtime_error("Failed to open codec");
|
||||
|
||||
// 3. Setup Resampler (Stereo S16 PCM)
|
||||
AVChannelLayout outLayout;
|
||||
av_channel_layout_default(&outLayout, 2);
|
||||
|
||||
swr_alloc_set_opts2(&m_swrCtx, &outLayout, AV_SAMPLE_FMT_S16,
|
||||
targetSampleRate, &m_codecCtx->ch_layout,
|
||||
m_codecCtx->sample_fmt, m_codecCtx->sample_rate, 0,
|
||||
nullptr);
|
||||
if (m_codecCtx->sample_rate != targetSampleRate) {
|
||||
av_opt_set_int(m_swrCtx, "linear_interp", 1, 0);
|
||||
av_opt_set_int(m_swrCtx, "filter_size", 256, 0);
|
||||
}
|
||||
swr_init(m_swrCtx);
|
||||
|
||||
// 4. Allocate Resources
|
||||
pkt = av_packet_alloc();
|
||||
frame = av_frame_alloc();
|
||||
int maxSamples = 4096;
|
||||
av_samples_alloc(&outputBuffer, nullptr, 2, maxSamples, AV_SAMPLE_FMT_S16,
|
||||
0);
|
||||
|
||||
Log("Decoder initialized. Starting stream...");
|
||||
while (!m_cancelRequested) {
|
||||
int readRet = av_read_frame(m_formatCtx, pkt);
|
||||
if (readRet == AVERROR_EOF)
|
||||
break;
|
||||
if (readRet < 0)
|
||||
throw std::runtime_error("read error");
|
||||
|
||||
if (pkt->stream_index == streamIdx) {
|
||||
avcodec_send_packet(m_codecCtx, pkt);
|
||||
|
||||
while (!m_cancelRequested) {
|
||||
int ret = avcodec_receive_frame(m_codecCtx, frame);
|
||||
if (ret == AVERROR(EAGAIN))
|
||||
break;
|
||||
if (ret < 0)
|
||||
continue;
|
||||
|
||||
int outSamples =
|
||||
swr_convert(m_swrCtx, &outputBuffer, maxSamples,
|
||||
(const uint8_t **)frame->data, frame->nb_samples);
|
||||
|
||||
if (outSamples > 0) {
|
||||
std::vector<short> chunk(outSamples * 2);
|
||||
memcpy(chunk.data(), outputBuffer, outSamples * 2 * sizeof(short));
|
||||
|
||||
{
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
m_chunkQueue.push_back(std::move(chunk));
|
||||
}
|
||||
m_cv.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
av_packet_unref(pkt);
|
||||
}
|
||||
/* ---------- FINAL FLUSH (CRITICAL FIX) ---------- */
|
||||
|
||||
avcodec_send_packet(m_codecCtx, nullptr);
|
||||
while (!m_cancelRequested) {
|
||||
int ret = avcodec_receive_frame(m_codecCtx, frame);
|
||||
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
|
||||
break;
|
||||
if (ret < 0)
|
||||
throw std::runtime_error("flush decode error");
|
||||
|
||||
int outSamples =
|
||||
swr_convert(m_swrCtx, &outputBuffer, maxSamples,
|
||||
(const uint8_t **)frame->data, frame->nb_samples);
|
||||
|
||||
if (outSamples > 0) {
|
||||
std::vector<short> chunk(outSamples * 2);
|
||||
memcpy(chunk.data(), outputBuffer, outSamples * 2 * sizeof(short));
|
||||
|
||||
{
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
m_chunkQueue.push_back(std::move(chunk));
|
||||
}
|
||||
m_cv.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
m_status =
|
||||
m_cancelRequested ? DecodeStatus::Cancelled : DecodeStatus::Completed;
|
||||
|
||||
} catch (...) {
|
||||
m_status = DecodeStatus::Failed;
|
||||
}
|
||||
|
||||
Cleanup();
|
||||
|
||||
m_finished = true;
|
||||
m_cv.notify_all();
|
||||
|
||||
av_freep(&outputBuffer);
|
||||
av_frame_free(&frame);
|
||||
av_packet_free(&pkt);
|
||||
Log("Internal thread exited.");
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#include <ts6bot/Crypto.hpp>
|
||||
|
||||
#include <openssl/rand.h>
|
||||
#include <openssl/sha.h>
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace ts6bot::crypto {
|
||||
|
||||
static void rand_bytes(std::span<std::uint8_t> out) {
|
||||
if (out.empty()) return;
|
||||
if (RAND_bytes(out.data(), static_cast<int>(out.size())) != 1) {
|
||||
throw std::runtime_error("RAND_bytes failed");
|
||||
}
|
||||
}
|
||||
|
||||
std::string GenerateCodeVerifier(std::size_t length) {
|
||||
if (length < 43 || length > 128) {
|
||||
throw std::runtime_error("code_verifier length must be 43..128");
|
||||
}
|
||||
|
||||
static constexpr char kAlphabet[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"abcdefghijklmnopqrstuvwxyz"
|
||||
"0123456789"
|
||||
"-._~";
|
||||
|
||||
std::vector<std::uint8_t> rnd(length);
|
||||
rand_bytes(rnd);
|
||||
|
||||
std::string out;
|
||||
out.reserve(length);
|
||||
for (std::uint8_t b : rnd) {
|
||||
out.push_back(kAlphabet[b % (sizeof(kAlphabet) - 1)]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Base64UrlEncode(std::span<const std::uint8_t> data) {
|
||||
static constexpr char tbl[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
std::string out;
|
||||
out.reserve(((data.size() + 2) / 3) * 4);
|
||||
|
||||
std::size_t i = 0;
|
||||
while (i + 3 <= data.size()) {
|
||||
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16) |
|
||||
(static_cast<std::uint32_t>(data[i + 1]) << 8) |
|
||||
(static_cast<std::uint32_t>(data[i + 2]));
|
||||
out.push_back(tbl[(n >> 18) & 63]);
|
||||
out.push_back(tbl[(n >> 12) & 63]);
|
||||
out.push_back(tbl[(n >> 6) & 63]);
|
||||
out.push_back(tbl[n & 63]);
|
||||
i += 3;
|
||||
}
|
||||
|
||||
std::size_t rem = data.size() - i;
|
||||
if (rem == 1) {
|
||||
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16);
|
||||
out.push_back(tbl[(n >> 18) & 63]);
|
||||
out.push_back(tbl[(n >> 12) & 63]);
|
||||
out.push_back('=');
|
||||
out.push_back('=');
|
||||
} else if (rem == 2) {
|
||||
std::uint32_t n = (static_cast<std::uint32_t>(data[i]) << 16) |
|
||||
(static_cast<std::uint32_t>(data[i + 1]) << 8);
|
||||
out.push_back(tbl[(n >> 18) & 63]);
|
||||
out.push_back(tbl[(n >> 12) & 63]);
|
||||
out.push_back(tbl[(n >> 6) & 63]);
|
||||
out.push_back('=');
|
||||
}
|
||||
|
||||
// base64url + no padding
|
||||
for (char& c : out) {
|
||||
if (c == '+') c = '-';
|
||||
else if (c == '/') c = '_';
|
||||
}
|
||||
while (!out.empty() && out.back() == '=') out.pop_back();
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string GenerateState(std::size_t bytes) {
|
||||
std::vector<std::uint8_t> rnd(bytes);
|
||||
rand_bytes(rnd);
|
||||
return Base64UrlEncode(rnd);
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> Sha256(std::span<const std::uint8_t> data) {
|
||||
std::vector<std::uint8_t> out(SHA256_DIGEST_LENGTH);
|
||||
SHA256_CTX ctx;
|
||||
if (SHA256_Init(&ctx) != 1) throw std::runtime_error("SHA256_Init failed");
|
||||
if (!data.empty() && SHA256_Update(&ctx, data.data(), data.size()) != 1) {
|
||||
throw std::runtime_error("SHA256_Update failed");
|
||||
}
|
||||
if (SHA256_Final(out.data(), &ctx) != 1) throw std::runtime_error("SHA256_Final failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> Sha256(std::span<const char> data) {
|
||||
auto* ptr = reinterpret_cast<const std::uint8_t*>(data.data());
|
||||
return Sha256(std::span{ptr, data.size()});
|
||||
}
|
||||
|
||||
} // namespace ts6bot::crypto
|
||||
@@ -0,0 +1,453 @@
|
||||
#include "ts6bot/MusicManager.hpp"
|
||||
#include "Youtube/Client.hpp"
|
||||
#include "teamspeak/public_errors.h"
|
||||
#include "ts6bot/Config.hpp"
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <glaze/json/read.hpp>
|
||||
#include <optional>
|
||||
#include <print>
|
||||
#include <ranges>
|
||||
#include <regex>
|
||||
#include <utility>
|
||||
#include <quill/Frontend.h>
|
||||
|
||||
MusicManager::MusicManager(std::shared_ptr<TS3Functions> functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID)
|
||||
: m_logger(logger), m_functions(std::move(functions)), m_serverConnectionHandlerID(serverConnectionHandlerID) {
|
||||
auto config = ts6bot::Configuration::GetInstance()->getConfig();
|
||||
m_client = std::make_unique<YouTube::Client>(config.music.youtubeApiToken);
|
||||
m_client->SetProxy(static_cast<ProxyConfig>(config.proxy));
|
||||
|
||||
if (const auto err = m_functions->registerCustomDevice("custom", "custom", 192000, 2,
|
||||
192000, 2);
|
||||
err != ERROR_ok) {
|
||||
char *errorMsg = nullptr;
|
||||
m_functions->getErrorMessage(err, &errorMsg);
|
||||
LOG_ERROR(m_logger, "Unable to register custom device: {}", errorMsg);
|
||||
m_functions->freeMemory(errorMsg);
|
||||
}
|
||||
|
||||
m_worker = std::jthread([this](const std::stop_token &st) { this->loop(st); });
|
||||
}
|
||||
|
||||
MusicManager::~MusicManager() {
|
||||
{
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
m_worker.request_stop();
|
||||
}
|
||||
m_cv.notify_all(); // Wake up the thread so it can see the stop request
|
||||
|
||||
if (m_worker.joinable()) {
|
||||
m_worker.join(); // Explicitly wait for it to finish before deleting members
|
||||
}
|
||||
|
||||
if (m_microphone) {
|
||||
m_microphone->Cancel();
|
||||
}
|
||||
}
|
||||
// ============================================================================
|
||||
// Search Implementation
|
||||
// ============================================================================
|
||||
|
||||
std::string MusicManager::formatDuration(const std::string &isoDuration) {
|
||||
// Regex for ISO 8601 Duration (e.g., PT1H2M10S, PT4M, PT30S)
|
||||
std::regex re(R"(PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)");
|
||||
std::smatch match;
|
||||
if (std::regex_match(isoDuration, match, re)) {
|
||||
int hours = match[1].length() ? std::stoi(match[1]) : 0;
|
||||
int minutes = match[2].length() ? std::stoi(match[2]) : 0;
|
||||
int seconds = match[3].length() ? std::stoi(match[3]) : 0;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{}:{:02}", hours, minutes, seconds);
|
||||
} else {
|
||||
return std::format("{}:{:02}", minutes, seconds);
|
||||
}
|
||||
}
|
||||
return isoDuration; // Fallback
|
||||
}
|
||||
|
||||
std::vector<definitions::SearchResultItem> MusicManager::search(std::string name,
|
||||
int maxResults) const {
|
||||
YouTube::SearchParams params;
|
||||
params.q = std::move(name);
|
||||
params.maxResults = maxResults;
|
||||
params.type = {"video"};
|
||||
|
||||
auto searchRes = m_client->Search(params);
|
||||
if (!searchRes) {
|
||||
LOG_ERROR(m_logger, "Search failed: {} - {}", searchRes.error().status, searchRes.error().message);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<std::string> videoIds;
|
||||
for (const auto &item : searchRes->items) {
|
||||
videoIds.push_back(item.id.videoId);
|
||||
}
|
||||
|
||||
if (videoIds.empty())
|
||||
return {};
|
||||
|
||||
auto videosRes = m_client->GetVideos(videoIds);
|
||||
std::vector<definitions::SearchResultItem> resultItems;
|
||||
|
||||
if (!videosRes) {
|
||||
LOG_WARNING(m_logger, "Failed to fetch video details, using snippets.");
|
||||
for (const auto &item : searchRes->items) {
|
||||
resultItems.push_back(
|
||||
{.name = item.snippet.title,
|
||||
.length = "??:??",
|
||||
.thumbnail = item.snippet.thumbnails.empty() ? "" : item.snippet.thumbnails.begin()->second.url,
|
||||
.viewCount = "N/A",
|
||||
.url = "https://youtube.com/watch?v=" + item.id.videoId,
|
||||
.videoId = item.id.videoId});
|
||||
}
|
||||
return resultItems;
|
||||
}
|
||||
|
||||
for (const auto &video : *videosRes) {
|
||||
std::string thumbUrl;
|
||||
if (!video.snippet.thumbnails.empty()) {
|
||||
if (video.snippet.thumbnails.contains("high"))
|
||||
thumbUrl = video.snippet.thumbnails.at("high").url;
|
||||
else
|
||||
thumbUrl = video.snippet.thumbnails.begin()->second.url;
|
||||
}
|
||||
|
||||
resultItems.push_back(
|
||||
{.name = video.snippet.title,
|
||||
.length = formatDuration(video.contentDetails.duration),
|
||||
.thumbnail = thumbUrl,
|
||||
.viewCount = video.statistics.viewCount,
|
||||
.url = "https://youtube.com/watch?v=" + video.id,
|
||||
.videoId = video.id});
|
||||
}
|
||||
|
||||
return resultItems;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Playback & Queue
|
||||
// ============================================================================
|
||||
|
||||
void MusicManager::playUrl(std::string url, const std::string &requester) {
|
||||
const auto videoIdOpt = m_client->ExtractVideoId(url);
|
||||
if (!videoIdOpt) {
|
||||
LOG_WARNING(m_logger, "Invalid YouTube URI: {}", url);
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string& vid = *videoIdOpt;
|
||||
std::string title = "Unknown Title";
|
||||
|
||||
if (const auto videoInfo = m_client->GetVideo(vid, "snippet")) {
|
||||
title = videoInfo->snippet.title;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
// Fetch streams immediately (Note: This might be blocking, consider doing it in the loop if UI hangs)
|
||||
m_queue.push_back({.name = title,
|
||||
.videoId = vid,
|
||||
.requestedBy = requester,
|
||||
.streams = m_client->GetBestStreams(vid)});
|
||||
}
|
||||
LOG_INFO(m_logger, "Added to queue: {}", title);
|
||||
m_cv.notify_one(); // Wake up loop
|
||||
}
|
||||
|
||||
void MusicManager::addToQueueDirect(const std::string& vid, const std::string& title,
|
||||
const std::string& req, std::optional<definitions::Streams> streams) {
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
Music m;
|
||||
m.name = title;
|
||||
m.videoId = vid;
|
||||
m.requestedBy = req;
|
||||
if(streams) {
|
||||
m.streams = YouTube::Result<definitions::Streams>(streams.value());
|
||||
}
|
||||
m_queue.push_back(std::move(m));
|
||||
}
|
||||
void MusicManager::skip() {
|
||||
m_skipRequested = true;
|
||||
if (m_microphone) {
|
||||
m_microphone->Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
void MusicManager::forceSkip() {
|
||||
{
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
m_queue.clear();
|
||||
}
|
||||
skip();
|
||||
}
|
||||
|
||||
void MusicManager::stop() {
|
||||
// If we want to stop completely (not just clear queue)
|
||||
forceSkip();
|
||||
}
|
||||
|
||||
std::vector<MusicManager::Music> MusicManager::getQueue() const {
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
return {m_queue.begin(), m_queue.end()};
|
||||
}
|
||||
|
||||
void MusicManager::checkQueueAndPlay() {
|
||||
m_cv.notify_one();
|
||||
}
|
||||
|
||||
void MusicManager::removeFromQueue(const std::size_t index) {
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
if (index < m_queue.size()) {
|
||||
m_queue.erase(m_queue.begin() + index);
|
||||
}
|
||||
}
|
||||
|
||||
void MusicManager::removeFromQueue(const std::string &name) {
|
||||
std::lock_guard lock(m_queueMtx);
|
||||
std::erase_if(m_queue, [&](const Music &m) { return m.name == name; });
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Loop
|
||||
// ============================================================================
|
||||
void MusicManager::loop(std::stop_token st) {
|
||||
// Initial setup delay
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
|
||||
auto config = ts6bot::Configuration::GetInstance()->getConfig();
|
||||
if (m_serverConnectionHandlerID == 0) {
|
||||
// Connect GUI Tab
|
||||
if (auto err = m_functions->guiConnect(
|
||||
PLUGIN_CONNECT_TAB_CURRENT, "current", config.host.c_str(),
|
||||
config.password.c_str(), config.nickname.c_str(),
|
||||
config.channel.c_str(), "", "", "", "", "", "", "", "",
|
||||
&m_serverConnectionHandlerID);
|
||||
err != ERROR_ok) {
|
||||
char* msg; m_functions->getErrorMessage(err, &msg);
|
||||
LOG_ERROR(m_logger, "GUI Connect failed: {}", msg);
|
||||
m_functions->freeMemory(msg);
|
||||
}
|
||||
}
|
||||
// Setup Devices
|
||||
m_functions->closeCaptureDevice(m_serverConnectionHandlerID);
|
||||
m_functions->closePlaybackDevice(m_serverConnectionHandlerID);
|
||||
|
||||
if(m_functions->openCaptureDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok)
|
||||
LOG_ERROR(m_logger, "Failed to open Capture Device");
|
||||
|
||||
if(m_functions->openPlaybackDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok)
|
||||
LOG_ERROR(m_logger, "Failed to open Playback Device");
|
||||
m_microphone = std::make_unique<AudioDecoder>();
|
||||
|
||||
constexpr int SAMPLE_RATE = 192000;
|
||||
constexpr int CHANNEL_COUNT = 2;
|
||||
constexpr int CHUNK_MS = 20;
|
||||
constexpr size_t SHORTS_PER_CHUNK = (SAMPLE_RATE * CHANNEL_COUNT * CHUNK_MS) / 1000;
|
||||
constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50;
|
||||
|
||||
while (!st.stop_requested()) {
|
||||
m_isIdle = true;
|
||||
|
||||
// 1. Wait for Track
|
||||
{
|
||||
std::unique_lock lock(m_queueMtx);
|
||||
m_cv.wait(lock, [&] { return !m_queue.empty() || st.stop_requested(); });
|
||||
|
||||
if (st.stop_requested()) break;
|
||||
|
||||
m_current = m_queue.front();
|
||||
m_queue.pop_front();
|
||||
}
|
||||
m_isIdle = false;
|
||||
// 2. Resolve Streams if needed (Hot reload might have provided them, new search might not)
|
||||
if (!m_current->streams || m_current->streams->audio.url.empty()) {
|
||||
LOG_INFO(m_logger, "Resolving streams for {}", m_current->name);
|
||||
m_current->streams = m_client->GetBestStreams(m_current->videoId);
|
||||
}
|
||||
|
||||
if (!m_current->streams || m_current->streams->audio.url.empty()) {
|
||||
LOG_ERROR(m_logger, "Failed to get stream for {}", m_current->name);
|
||||
m_current = std::nullopt;
|
||||
continue;
|
||||
}
|
||||
|
||||
LOG_INFO(m_logger, "Now Playing: {}", m_current->name);
|
||||
|
||||
// 3. Start Decoding
|
||||
m_microphone->StartDecode(m_current->streams->audio.url, SAMPLE_RATE);
|
||||
|
||||
std::vector<short> localAudioBuffer;
|
||||
auto next = std::chrono::steady_clock::now();
|
||||
m_skipRequested = false;
|
||||
|
||||
// 4. Playback Loop
|
||||
while (!st.stop_requested() && !m_skipRequested) {
|
||||
|
||||
// Pull Data
|
||||
if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) {
|
||||
std::vector<short> incomingChunk;
|
||||
if (m_microphone->GetNextChunk(incomingChunk)) {
|
||||
localAudioBuffer.insert(localAudioBuffer.end(), incomingChunk.begin(), incomingChunk.end());
|
||||
}
|
||||
}
|
||||
|
||||
// Check Subscribers (Pause if none)
|
||||
bool hasSubscribers = false;
|
||||
{
|
||||
std::lock_guard lock(m_subMtx);
|
||||
hasSubscribers = !m_onlineSubscribers.empty();
|
||||
}
|
||||
|
||||
if (!hasSubscribers) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
next = std::chrono::steady_clock::now(); // Reset timing so we don't fast-forward
|
||||
continue;
|
||||
}
|
||||
|
||||
// Send Audio
|
||||
if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) {
|
||||
float volMult = std::pow(m_volume.load(), 3.0f);
|
||||
short chunkToSend[SHORTS_PER_CHUNK];
|
||||
|
||||
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
|
||||
int val = static_cast<int>(localAudioBuffer[i] * volMult);
|
||||
chunkToSend[i] = static_cast<short>(std::clamp(val, -32768, 32767));
|
||||
}
|
||||
|
||||
localAudioBuffer.erase(localAudioBuffer.begin(), localAudioBuffer.begin() + SHORTS_PER_CHUNK);
|
||||
|
||||
if (m_functions->processCustomCaptureData("custom", chunkToSend, (int)(SHORTS_PER_CHUNK / CHANNEL_COUNT)) != ERROR_ok) {
|
||||
// Device error handling?
|
||||
}
|
||||
|
||||
// Precision Timing
|
||||
next += std::chrono::milliseconds(CHUNK_MS);
|
||||
std::this_thread::sleep_until(next);
|
||||
} else {
|
||||
// Buffer Underrun or End of Stream?
|
||||
std::vector<short> incoming;
|
||||
if (m_microphone->GetNextChunk(incoming, true)) { // Blocking wait
|
||||
localAudioBuffer.insert(localAudioBuffer.end(), incoming.begin(), incoming.end());
|
||||
continue;
|
||||
}
|
||||
|
||||
bool decoderEmpty;
|
||||
{
|
||||
std::lock_guard lock(m_microphone->m_queueMtx);
|
||||
decoderEmpty = m_microphone->m_chunkQueue.empty();
|
||||
}
|
||||
|
||||
if (m_microphone->IsFinished() && decoderEmpty) {
|
||||
// Drain remaining
|
||||
if (!localAudioBuffer.empty()) {
|
||||
localAudioBuffer.resize(SHORTS_PER_CHUNK, 0); // Pad silence
|
||||
continue; // Send padded chunk
|
||||
}
|
||||
break; // Done
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m_microphone->Cancel();
|
||||
LOG_INFO(m_logger, "Finished track: {}", m_current->name);
|
||||
m_current = std::nullopt;
|
||||
|
||||
// Check for Graceful Stop (Update)
|
||||
if (m_stopAfterCurrent) {
|
||||
LOG_INFO(m_logger, "Graceful stop requested. Stopping main loop.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
m_isIdle = true;
|
||||
}
|
||||
// Stubs for Subscription (Logic not fully defined in prompt, basic stub
|
||||
// provided)
|
||||
// ============================================================================
|
||||
|
||||
void MusicManager::subscribe(const anyID id) {
|
||||
addSubscriberToOnline(id);
|
||||
}
|
||||
|
||||
void MusicManager::addSubscriberToOnline(anyID id) {
|
||||
std::lock_guard lock(m_subMtx);
|
||||
m_offlineSubscribers.erase(id);
|
||||
m_onlineSubscribers.insert(id);
|
||||
updateWhisperList();
|
||||
LOG_INFO(m_logger, "User {} added to Online Subscribers", id);
|
||||
}
|
||||
|
||||
void MusicManager::addSubscriberToOffline(const anyID id) {
|
||||
std::lock_guard lock(m_subMtx);
|
||||
m_onlineSubscribers.erase(id);
|
||||
m_offlineSubscribers.insert(id);
|
||||
updateWhisperList();
|
||||
LOG_INFO(m_logger, "User {} added to Offline Subscribers", id);
|
||||
|
||||
}
|
||||
|
||||
void MusicManager::moveSubscriberToOffline(const anyID id) {
|
||||
if (m_onlineSubscribers.contains(id)) {
|
||||
addSubscriberToOffline(id);
|
||||
}
|
||||
}
|
||||
|
||||
void MusicManager::moveSubscriberToOnline(const anyID id) {
|
||||
if (m_offlineSubscribers.contains(id)) {
|
||||
addSubscriberToOnline(id);
|
||||
}
|
||||
}
|
||||
void MusicManager::unSubscribe(anyID id) {
|
||||
std::lock_guard lock(m_subMtx);
|
||||
m_onlineSubscribers.erase(id);
|
||||
m_offlineSubscribers.erase(id);
|
||||
updateWhisperList();
|
||||
LOG_INFO(m_logger, "User {} Unsubscribed", id);
|
||||
}
|
||||
std::set<uint64_t> MusicManager::getOnlineSubscribers() const {
|
||||
std::lock_guard lock(const_cast<std::mutex&>(m_subMtx));
|
||||
return {m_onlineSubscribers.begin(), m_onlineSubscribers.end()};
|
||||
}
|
||||
|
||||
std::set<uint64_t> MusicManager::getOfflineSubscribers() const {
|
||||
std::lock_guard lock(const_cast<std::mutex&>(m_subMtx));
|
||||
return {m_offlineSubscribers.begin(), m_offlineSubscribers.end()};
|
||||
}
|
||||
|
||||
void MusicManager::updateWhisperList() {
|
||||
if (!m_functions || m_serverConnectionHandlerID == 0)
|
||||
return;
|
||||
|
||||
// We only whisper to ONLINE subscribers
|
||||
std::vector<anyID> clientList(m_onlineSubscribers.begin(), m_onlineSubscribers.end());
|
||||
clientList.push_back(0);
|
||||
|
||||
anyID myID = 0;
|
||||
if (m_functions->getClientID(m_serverConnectionHandlerID, &myID) != ERROR_ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_functions->requestClientSetWhisperList(m_serverConnectionHandlerID, myID,
|
||||
nullptr, clientList.data(), "");
|
||||
}
|
||||
|
||||
void MusicManager::storePendingSearch(const anyID clientId, const std::vector<definitions::SearchResultItem> &results) {
|
||||
std::lock_guard lock(m_pendingMtx);
|
||||
m_pendingSearches[clientId] = results;
|
||||
}
|
||||
|
||||
bool MusicManager::selectSearchResult(const anyID clientId, const int index, const std::string& requesterName) {
|
||||
std::lock_guard lock(m_pendingMtx);
|
||||
const auto it = m_pendingSearches.find(clientId);
|
||||
if (it == m_pendingSearches.end())
|
||||
return false;
|
||||
|
||||
if (int vecIndex = index - 1; vecIndex >= 0 && vecIndex < static_cast<int>(it->second.size())) {
|
||||
playUrl(it->second[vecIndex].url, requesterName);
|
||||
m_pendingSearches.erase(it);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
#include <Plugin.hpp>
|
||||
|
||||
|
||||
void EchoionCore::Initialize(bool start) {
|
||||
// Init Logger
|
||||
try {
|
||||
quill::BackendOptions backend_options;
|
||||
backend_options.check_printable_char = {};
|
||||
quill::Backend::start(backend_options);
|
||||
// m_logger = quill::getor("Core", quill::file_handler("echoion.log", "w"));
|
||||
auto console_sink = quill::Frontend::create_or_get_sink<quill::ConsoleSink>("console");
|
||||
auto file_sink = quill::Frontend::create_or_get_sink<quill::FileSink>(
|
||||
"logs/echoion.log",
|
||||
[]()
|
||||
{
|
||||
quill::FileSinkConfig cfg {};
|
||||
cfg.set_open_mode('w');
|
||||
cfg.set_filename_append_option(quill::FilenameAppendOption::StartDateTime);
|
||||
return cfg;
|
||||
}(),
|
||||
quill::FileEventNotifier{});
|
||||
quill::PatternFormatterOptions pfo;
|
||||
pfo.format_pattern =
|
||||
"%(time) [%(thread_id)] %(source_location:<28) "
|
||||
"%(log_level:<9) %(message)";
|
||||
pfo.timestamp_pattern = ("%H:%M:%S.%Qns");
|
||||
pfo.timestamp_timezone = quill::Timezone::GmtTime;
|
||||
|
||||
m_logger = quill::Frontend::create_or_get_logger("root", {std::move(file_sink),std::move(console_sink)}, pfo);
|
||||
m_logger->set_log_level(quill::LogLevel::TraceL1);
|
||||
LOG_INFO(m_logger, "Core Initializing...");
|
||||
|
||||
// Config
|
||||
char path[512];
|
||||
m_ts3->getConfigPath(path, 512);
|
||||
ts6bot::Configuration::Construct(std::string(path) + "bot.json");
|
||||
// Services
|
||||
auto cfg = ts6bot::Configuration::GetInstance()->getConfig();
|
||||
|
||||
if (start) {
|
||||
m_musicManager = std::make_unique<MusicManager>(m_ts3, m_logger);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
} // Ignore if already active
|
||||
}
|
||||
|
||||
void EchoionCore::Shutdown() {
|
||||
if (m_musicManager) {
|
||||
m_musicManager->stop();
|
||||
m_musicManager.reset();
|
||||
}
|
||||
quill::Backend::stop();
|
||||
}
|
||||
|
||||
// --- HOT RELOAD ---
|
||||
void EchoionCore::RequestGracefulStop() {
|
||||
if (m_musicManager)
|
||||
m_musicManager->setStopAfterCurrent(true);
|
||||
}
|
||||
|
||||
bool EchoionCore::IsStopped() {
|
||||
return !m_musicManager || m_musicManager->isIdle();
|
||||
}
|
||||
|
||||
std::string EchoionCore::SerializeState() {
|
||||
if (!m_musicManager)
|
||||
return "{}";
|
||||
|
||||
definitions::PluginState state;
|
||||
auto q = m_musicManager->getQueue();
|
||||
for (const auto &i : q) {
|
||||
std::optional<definitions::Streams> streams = (i.streams.has_value() ? std::optional(i.streams.value()) : std::nullopt);
|
||||
auto temp = definitions::QueueItem(i.name, i.videoId, i.requestedBy, streams);
|
||||
state.queue.push_back(temp);
|
||||
}
|
||||
auto subs = m_musicManager->getOnlineSubscribers();
|
||||
auto offsubs = m_musicManager->getOfflineSubscribers();
|
||||
state.onlineSubscribers.assign(subs.begin(), subs.end());
|
||||
state.offlineSubscribers.assign(offsubs.begin(), offsubs.end());
|
||||
state.serverConnection = m_musicManager->getServerConnectionHandlerID();
|
||||
|
||||
std::string buf;
|
||||
glz::write_json(state, buf);
|
||||
return buf;
|
||||
}
|
||||
|
||||
void EchoionCore::DeserializeState(const std::string &jsonState) {
|
||||
definitions::PluginState state;
|
||||
if (auto err = glz::read_json(state, jsonState); !err) {
|
||||
if (m_musicManager)
|
||||
m_musicManager = std::make_unique<MusicManager>(m_ts3, m_logger, state.serverConnection);
|
||||
for (auto s : state.onlineSubscribers)
|
||||
m_musicManager->addSubscriberToOnline(s);
|
||||
for (auto s : state.offlineSubscribers)
|
||||
m_musicManager->addSubscriberToOffline(s);
|
||||
for (const auto &item : state.queue) {
|
||||
m_musicManager->addToQueueDirect(item.videoId, item.name,
|
||||
item.requester, item.streams);
|
||||
}
|
||||
m_musicManager->setServerConnectionHandlerID(state.serverConnection);
|
||||
m_musicManager->checkQueueAndPlay();
|
||||
}
|
||||
}
|
||||
|
||||
int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targetMode, anyID toID, anyID fromID,
|
||||
const char *fromName, const char *fromUniqueIdentifier, const char *message,
|
||||
int ffIgnored) {
|
||||
auto reply = [this](const uint64 sc, const anyID toId, const std::string &text) {
|
||||
const char* returnCode = nullptr;
|
||||
this->m_ts3->requestSendPrivateTextMsg(sc, text.c_str(), toId,returnCode);
|
||||
};
|
||||
// 1. Only react to Direct Messages (Private Chats)
|
||||
if (targetMode != TextMessageTarget_CLIENT) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 2. Ignore own messages
|
||||
anyID myID;
|
||||
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
|
||||
if (fromID == myID)
|
||||
return 0;
|
||||
|
||||
std::string msgStr = message;
|
||||
if (msgStr.empty() || msgStr[0] != '.')
|
||||
return 0;
|
||||
|
||||
std::stringstream ss(msgStr);
|
||||
std::string command;
|
||||
ss >> command;
|
||||
|
||||
std::string args;
|
||||
std::getline(ss, args);
|
||||
if (!args.empty() && args[0] == ' ')
|
||||
args.erase(0, 1);
|
||||
|
||||
if (command == ".play") {
|
||||
if (args.find("http") == 0) {
|
||||
this->m_musicManager->playUrl(args, fromName);
|
||||
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Added URL to queue.", fromID,
|
||||
nullptr);
|
||||
} else {
|
||||
auto results = this->m_musicManager->search(args, 5);
|
||||
if (results.empty()) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "No results found.", fromID,
|
||||
nullptr);
|
||||
} else if (results.size() == 1) {
|
||||
this->m_musicManager->playUrl(results[0].url, fromName);
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, ("Playing: " + results[0].name).c_str(), fromID, nullptr);
|
||||
} else {
|
||||
this->m_musicManager->storePendingSearch(fromID, results);
|
||||
std::string list = "Multiple results found. Use .select <number>:\n";
|
||||
for (size_t i = 0; i < results.size(); ++i) {
|
||||
list += std::format("{}. {} [{}]\n",(i+1), results[i].name, results[i].length);
|
||||
}
|
||||
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, list.c_str(), fromID, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (command == ".select") {
|
||||
try {
|
||||
int idx = std::stoi(args);
|
||||
if (this->m_musicManager->selectSearchResult(fromID, idx, fromName)) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Selected song added to queue.",
|
||||
fromID, nullptr);
|
||||
} else {
|
||||
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Invalid selection.", fromID,
|
||||
nullptr);
|
||||
}
|
||||
} catch (...) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Please provide a valid number.",
|
||||
fromID, nullptr);
|
||||
}
|
||||
} else if (command == ".stop") {
|
||||
this->m_musicManager->stop();
|
||||
reply(serverConnectionHandlerID, fromID, "Playback stopped and queue cleared.");
|
||||
} else if (command == ".skip" || command == ".next") {
|
||||
this->m_musicManager->skip();
|
||||
reply(serverConnectionHandlerID, fromID, "Skipped current track.");
|
||||
} else if (command == ".queue" || command == ".list") {
|
||||
auto q = this->m_musicManager->getQueue();
|
||||
auto current = this->m_musicManager->getCurrent();
|
||||
std::string str =
|
||||
current ? std::format("Now playing: {}\n\n", current.value().name)
|
||||
:
|
||||
"";
|
||||
if (q.empty() && str.empty())
|
||||
reply(serverConnectionHandlerID, fromID, "Queue is empty");
|
||||
|
||||
for (auto i = 0; i < q.size(); i++) {
|
||||
str += std::format("{}. {}\n", i, q.at(i).name);
|
||||
}
|
||||
reply(serverConnectionHandlerID, fromID, str);
|
||||
} else if (command == ".sub") {
|
||||
this->m_musicManager->subscribe(fromID);
|
||||
reply(serverConnectionHandlerID, fromID, "You are now subscribed to the music bot.");
|
||||
} else if (command == ".unsub") {
|
||||
this->m_musicManager->unSubscribe(fromID);
|
||||
reply(serverConnectionHandlerID, fromID, "Unsubscribed.");
|
||||
} else if (command == ".help") {
|
||||
reply(serverConnectionHandlerID, fromID,
|
||||
".play <ссылка или название>\n.select "
|
||||
"<#>\n.stop\n.skip\\next\n.queue\\list\n.sub\n"
|
||||
".unsub");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID,
|
||||
int visibility, const char *moveMessage) {
|
||||
|
||||
anyID myID;
|
||||
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
|
||||
if (clientID == myID)
|
||||
return;
|
||||
|
||||
if (newChannelID == 0) {
|
||||
if (m_musicManager) {
|
||||
m_musicManager->moveSubscriberToOffline(clientID);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (oldChannelID == 0) {
|
||||
if (m_musicManager) {
|
||||
m_musicManager->moveSubscriberToOnline(clientID);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
#include "ts6bot/SignalShutdown.hpp"
|
||||
#include <csignal>
|
||||
#include <pthread.h>
|
||||
|
||||
SignalShutdown::SignalShutdown(std::function<void()> onShutdown)
|
||||
: m_OnShutdown(std::move(onShutdown))
|
||||
{
|
||||
// Block signals in this thread (and thus in subsequently created threads)
|
||||
sigset_t set;
|
||||
sigemptyset(&set);
|
||||
sigaddset(&set, SIGINT);
|
||||
sigaddset(&set, SIGTERM);
|
||||
sigaddset(&set, SIGHUP);
|
||||
sigaddset(&set, SIGQUIT);
|
||||
pthread_sigmask(SIG_BLOCK, &set, nullptr);
|
||||
|
||||
m_Thread = std::thread([this, set]() mutable {
|
||||
while (m_Running) {
|
||||
int sig = 0;
|
||||
if (sigwait(&set, &sig) == 0) {
|
||||
if (!m_Running) break;
|
||||
if (m_OnShutdown) m_OnShutdown();
|
||||
// After requesting shutdown once, allow main to exit
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
SignalShutdown::~SignalShutdown() {
|
||||
m_Running = false;
|
||||
// Send a signal to unblock sigwait if desired; easiest is detach-safe join
|
||||
if (m_Thread.joinable()) {
|
||||
// If main exits without signals, thread may still be blocked in sigwait.
|
||||
// In that case, process teardown ends it anyway; but we prefer not to hang.
|
||||
// So we simply detach.
|
||||
m_Thread.detach();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
#include "Spotify/Client.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <print>
|
||||
#include <format>
|
||||
#include <ranges>
|
||||
#include <algorithm>
|
||||
|
||||
namespace Spotify {
|
||||
|
||||
// ============================================================================
|
||||
// Constructor
|
||||
// ============================================================================
|
||||
|
||||
Client::Client(std::string accessToken)
|
||||
: m_AccessToken(std::move(accessToken)) {}
|
||||
|
||||
// ============================================================================
|
||||
// HTTP Request Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::PerformRequest(
|
||||
const std::string& url,
|
||||
HttpMethod method,
|
||||
const std::string& body,
|
||||
const std::vector<std::string>& extra_headers
|
||||
) -> Result<std::string> {
|
||||
std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
|
||||
if (!curl) {
|
||||
return std::unexpected(ApiError{0, "Failed to initialize CURL", ""});
|
||||
}
|
||||
|
||||
std::string response;
|
||||
|
||||
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &response);
|
||||
|
||||
if (!m_Proxy.url.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXY, m_Proxy.url.c_str());
|
||||
|
||||
long curlProxyType = (m_Proxy.type == ProxyType::SOCKS5_HOSTNAME) ?
|
||||
CURLPROXY_SOCKS5_HOSTNAME : CURLPROXY_SOCKS5;
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXYTYPE, curlProxyType);
|
||||
|
||||
if (!m_Proxy.username.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_SOCKS5_AUTH, (long)CURLAUTH_BASIC);
|
||||
auto authStr = std::format("{}:{}", m_Proxy.username, m_Proxy.password);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXYUSERPWD, authStr.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
switch (method) {
|
||||
case HttpMethod::POST:
|
||||
curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
|
||||
break;
|
||||
case HttpMethod::PUT:
|
||||
curl_easy_setopt(curl.get(), CURLOPT_CUSTOMREQUEST, "PUT");
|
||||
break;
|
||||
case HttpMethod::DELETE:
|
||||
curl_easy_setopt(curl.get(), CURLOPT_CUSTOMREQUEST, "DELETE");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
struct curl_slist* headers = nullptr;
|
||||
headers = curl_slist_append(headers, std::format("Authorization: Bearer {}", m_AccessToken).c_str());
|
||||
headers = curl_slist_append(headers, "Content-Type: application/json");
|
||||
|
||||
for (const auto& header : extra_headers) {
|
||||
headers = curl_slist_append(headers, header.c_str());
|
||||
}
|
||||
|
||||
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers);
|
||||
|
||||
if (!body.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, body.c_str());
|
||||
}
|
||||
|
||||
if (m_Verbose) {
|
||||
std::println("Request: {} {}",
|
||||
method == HttpMethod::GET ? "GET" :
|
||||
method == HttpMethod::POST ? "POST" :
|
||||
method == HttpMethod::PUT ? "PUT" : "DELETE",
|
||||
url);
|
||||
if (!body.empty()) {
|
||||
std::println("Body: {}", body);
|
||||
}
|
||||
}
|
||||
|
||||
CURLcode res = curl_easy_perform(curl.get());
|
||||
curl_slist_free_all(headers);
|
||||
|
||||
if (res != CURLE_OK) {
|
||||
return std::unexpected(ApiError{
|
||||
static_cast<int>(res),
|
||||
curl_easy_strerror(res),
|
||||
m_Proxy.url.empty() ? "None" : m_Proxy.url
|
||||
});
|
||||
}
|
||||
|
||||
long http_code = 0;
|
||||
curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
|
||||
|
||||
if (m_Verbose) {
|
||||
std::println("Response Code: {}", http_code);
|
||||
std::println("Response: {}", response);
|
||||
}
|
||||
|
||||
if (http_code >= 400) {
|
||||
Request::ErrorResponse err;
|
||||
auto parse_result = glz::read_json(err, response);
|
||||
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{
|
||||
err.error.status,
|
||||
err.error.message,
|
||||
"API Error"
|
||||
});
|
||||
}
|
||||
|
||||
return std::unexpected(ApiError{
|
||||
static_cast<int>(http_code),
|
||||
response,
|
||||
"HTTP Error"
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
auto Client::WriteCallback(void* c, size_t s, size_t n, std::string* o) -> size_t {
|
||||
o->append(static_cast<char*>(c), s * n);
|
||||
return s * n;
|
||||
}
|
||||
|
||||
auto Client::BuildUrl(const std::string& endpoint, const std::map<std::string, std::string>& params) const -> std::string {
|
||||
std::string url = "https://api.spotify.com/v1" + endpoint;
|
||||
|
||||
if (!params.empty()) {
|
||||
url += "?";
|
||||
bool first = true;
|
||||
for (const auto& [key, value] : params) {
|
||||
if (!first) url += "&";
|
||||
url += key + "=" + UrlEncode(value);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
auto Client::BuildUrl(const std::string& endpoint, const Request::RequestParams& params) const -> std::string {
|
||||
return BuildUrl(endpoint, params.ToQueryParams());
|
||||
}
|
||||
|
||||
auto Client::UrlEncode(const std::string& value) const -> std::string {
|
||||
std::string encoded;
|
||||
for (char c : value) {
|
||||
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
|
||||
encoded += c;
|
||||
} else if (c == ' ') {
|
||||
encoded += "%20";
|
||||
} else {
|
||||
char* escaped = curl_easy_escape(nullptr, &c, 1);
|
||||
encoded += escaped;
|
||||
curl_free(escaped);
|
||||
}
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Albums API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetAlbum(const std::string& id, std::optional<std::string> market) -> Result<Album> {
|
||||
std::map<std::string, std::string> params;
|
||||
if (market) params["market"] = *market;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/albums/" + id, params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
Album album;
|
||||
auto parse_result = glz::read_json(album, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return album;
|
||||
}
|
||||
|
||||
auto Client::GetAlbums(const std::vector<std::string>& ids, std::optional<std::string> market) -> Result<std::vector<Album>> {
|
||||
std::map<std::string, std::string> params;
|
||||
params["ids"] = std::views::join_with(ids, ',') | std::ranges::to<std::string>();
|
||||
if (market) params["market"] = *market;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/albums", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
|
||||
|
||||
AlbumsResponse albums_response;
|
||||
auto parse_result = glz::read_json(albums_response, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return albums_response.albums;
|
||||
}
|
||||
|
||||
auto Client::GetAlbumTracks(const std::string& id, const Request::AlbumTracksParams& params) -> Result<PagingObject<SimplifiedTrack>> {
|
||||
auto response = PerformRequest(BuildUrl("/albums/" + id + "/tracks", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
PagingObject<SimplifiedTrack> result;
|
||||
auto parse_result = glz::read_json(result, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
auto Client::SaveAlbums(const std::vector<std::string>& ids) -> Result<void> {
|
||||
Request::RequestBody body{ids};
|
||||
std::string json;
|
||||
glz::write_json(body, json);
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/albums"), HttpMethod::PUT, json);
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Client::RemoveSavedAlbums(const std::vector<std::string>& ids) -> Result<void> {
|
||||
std::map<std::string, std::string> params;
|
||||
params["ids"] = std::views::join_with(ids, ',') | std::ranges::to<std::string>();
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/albums", params), HttpMethod::DELETE);
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Client::CheckSavedAlbums(const std::vector<std::string>& ids) -> Result<std::vector<bool>> {
|
||||
std::map<std::string, std::string> params;
|
||||
params["ids"] = std::views::join_with(ids, ',') | std::ranges::to<std::string>();
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/albums/contains", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
std::vector<bool> result;
|
||||
auto parse_result = glz::read_json(result, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Artists API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetArtist(const std::string& id) -> Result<Artist> {
|
||||
auto response = PerformRequest(BuildUrl("/artists/" + id));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
Artist artist;
|
||||
auto parse_result = glz::read_json(artist, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return artist;
|
||||
}
|
||||
|
||||
auto Client::GetArtists(const std::vector<std::string>& ids) -> Result<std::vector<Artist>> {
|
||||
std::map<std::string, std::string> params;
|
||||
params["ids"] = std::views::join_with(ids, ',') | std::ranges::to<std::string>();
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/artists", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
ArtistsResponse artists_response;
|
||||
auto parse_result = glz::read_json(artists_response, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return artists_response.artists;
|
||||
}
|
||||
|
||||
auto Client::GetArtistAlbums(const std::string& id, const Request::ArtistAlbumsParams& params) -> Result<PagingObject<SimplifiedAlbum>> {
|
||||
auto response = PerformRequest(BuildUrl("/artists/" + id + "/albums", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
PagingObject<SimplifiedAlbum> result;
|
||||
auto parse_result = glz::read_json(result, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
auto Client::GetArtistTopTracks(const std::string& id, const std::string& market) -> Result<std::vector<Track>> {
|
||||
std::map<std::string, std::string> params;
|
||||
params["market"] = market;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/artists/" + id + "/top-tracks", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
TracksResponse tracks_response;
|
||||
auto parse_result = glz::read_json(tracks_response, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return tracks_response.tracks;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Tracks API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetTrack(const std::string& id, std::optional<std::string> market) -> Result<Track> {
|
||||
std::map<std::string, std::string> params;
|
||||
if (market) params["market"] = *market;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/tracks/" + id, params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
Track track;
|
||||
auto parse_result = glz::read_json(track, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return track;
|
||||
}
|
||||
|
||||
auto Client::SaveTracks(const std::vector<std::string>& ids) -> Result<void> {
|
||||
Request::RequestBody body{ids};
|
||||
std::string json;
|
||||
glz::write_json(body, json);
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/tracks"), HttpMethod::PUT, json);
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Client::GetAudioFeatures(const std::string& id) -> Result<AudioFeatures> {
|
||||
auto response = PerformRequest(BuildUrl("/audio-features/" + id));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
AudioFeatures features;
|
||||
auto parse_result = glz::read_json(features, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return features;
|
||||
}
|
||||
|
||||
auto Client::GetRecommendations(const Request::RecommendationParams& params) -> Result<Recommendations> {
|
||||
auto response = PerformRequest(BuildUrl("/recommendations", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
Recommendations recommendations;
|
||||
auto parse_result = glz::read_json(recommendations, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return recommendations;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Search API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::Search(const Request::SearchParams& params) -> Result<SearchResults> {
|
||||
auto response = PerformRequest(BuildUrl("/search", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
SearchResults results;
|
||||
auto parse_result = glz::read_json(results, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
auto Client::SearchTracks(const Request::TrackSearchFilters& filters, const Request::PaginationParams& params) -> Result<PagingObject<Track>> {
|
||||
Request::SearchParams search_params;
|
||||
search_params.query = filters.ToQueryString();
|
||||
search_params.types = {Request::SearchType::Track};
|
||||
search_params.market = params.market;
|
||||
search_params.limit = params.limit;
|
||||
search_params.offset = params.offset;
|
||||
|
||||
auto result = Search(search_params);
|
||||
if (!result) return std::unexpected(result.error());
|
||||
|
||||
if (!result->tracks) {
|
||||
return std::unexpected(ApiError{0, "No tracks in search results", ""});
|
||||
}
|
||||
|
||||
return *result->tracks;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// User API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetCurrentUser() -> Result<User> {
|
||||
auto response = PerformRequest(BuildUrl("/me"));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
User user;
|
||||
auto parse_result = glz::read_json(user, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
auto Client::GetTopArtists(const Request::TopItemsParams& params) -> Result<PagingObject<Artist>> {
|
||||
auto response = PerformRequest(BuildUrl("/me/top/artists", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
PagingObject<Artist> result;
|
||||
auto parse_result = glz::read_json(result, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Player API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetPlaybackState(std::optional<std::string> market) -> Result<PlaybackState> {
|
||||
std::map<std::string, std::string> params;
|
||||
if (market) params["market"] = *market;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/player", params));
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
PlaybackState state;
|
||||
auto parse_result = glz::read_json(state, *response);
|
||||
if (parse_result) {
|
||||
return std::unexpected(ApiError{0, "JSON parse error", glz::format_error(parse_result, *response)});
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
auto Client::PausePlayback(std::optional<std::string> device_id) -> Result<void> {
|
||||
std::map<std::string, std::string> params;
|
||||
if (device_id) params["device_id"] = *device_id;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/player/pause", params), HttpMethod::PUT);
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Client::SkipToNext(std::optional<std::string> device_id) -> Result<void> {
|
||||
std::map<std::string, std::string> params;
|
||||
if (device_id) params["device_id"] = *device_id;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/player/next", params), HttpMethod::POST);
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Client::SetRepeatMode(RepeatMode mode, std::optional<std::string> device_id) -> Result<void> {
|
||||
std::map<std::string, std::string> params;
|
||||
params["state"] = RepeatModeToString(mode);
|
||||
if (device_id) params["device_id"] = *device_id;
|
||||
|
||||
auto response = PerformRequest(BuildUrl("/me/player/repeat", params), HttpMethod::PUT);
|
||||
if (!response) return std::unexpected(response.error());
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace Spotify
|
||||
@@ -0,0 +1,156 @@
|
||||
#include <Spotify/HttpCallbackServer.hpp>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Spotify {
|
||||
|
||||
HttpCallbackServer::HttpCallbackServer(std::string host, uint16_t port, std::string path)
|
||||
: m_Host(std::move(host)), m_Port(port), m_Path(std::move(path)) {
|
||||
if (m_Path.empty() || m_Path[0] != '/') m_Path = "/" + m_Path;
|
||||
}
|
||||
|
||||
static std::unordered_map<std::string, std::string> parse_query(std::string_view q) {
|
||||
std::unordered_map<std::string, std::string> out;
|
||||
while (!q.empty()) {
|
||||
auto amp = q.find('&');
|
||||
auto part = q.substr(0, amp);
|
||||
if (amp == std::string_view::npos) q = {};
|
||||
else q = q.substr(amp + 1);
|
||||
|
||||
if (part.empty()) continue;
|
||||
auto eq = part.find('=');
|
||||
std::string k = (eq == std::string_view::npos) ? std::string(part) : std::string(part.substr(0, eq));
|
||||
std::string v = (eq == std::string_view::npos) ? std::string() : std::string(part.substr(eq + 1));
|
||||
// NOTE: not percent-decoding (Spotify returns base64url-ish values).
|
||||
out.emplace(std::move(k), std::move(v));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static void write_all(int fd, std::string_view s) {
|
||||
while (!s.empty()) {
|
||||
ssize_t n = ::send(fd, s.data(), s.size(), 0);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
break;
|
||||
}
|
||||
s.remove_prefix(static_cast<std::size_t>(n));
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<CallbackResult> HttpCallbackServer::WaitForCallback(std::chrono::milliseconds timeout) {
|
||||
int listenFd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (listenFd < 0) throw std::runtime_error("socket() failed");
|
||||
|
||||
int one = 1;
|
||||
::setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(m_Port);
|
||||
|
||||
if (m_Host == "localhost") {
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
} else {
|
||||
if (::inet_pton(AF_INET, m_Host.c_str(), &addr.sin_addr) != 1) {
|
||||
::close(listenFd);
|
||||
throw std::runtime_error("Only IPv4 hosts supported for redirect_uri (use 127.0.0.1)");
|
||||
}
|
||||
}
|
||||
|
||||
if (::bind(listenFd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
|
||||
int e = errno;
|
||||
::close(listenFd);
|
||||
throw std::runtime_error(std::string("bind() failed: ") + std::strerror(e));
|
||||
}
|
||||
if (::listen(listenFd, 1) != 0) {
|
||||
int e = errno;
|
||||
::close(listenFd);
|
||||
throw std::runtime_error(std::string("listen() failed: ") + std::strerror(e));
|
||||
}
|
||||
|
||||
pollfd pfd{listenFd, POLLIN, 0};
|
||||
int pr = ::poll(&pfd, 1, static_cast<int>(timeout.count()));
|
||||
if (pr <= 0) {
|
||||
::close(listenFd);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
int clientFd = ::accept(listenFd, nullptr, nullptr);
|
||||
::close(listenFd);
|
||||
if (clientFd < 0) return std::nullopt;
|
||||
|
||||
std::string req;
|
||||
req.reserve(2048);
|
||||
char buf[2048];
|
||||
while (true) {
|
||||
ssize_t n = ::recv(clientFd, buf, sizeof(buf), 0);
|
||||
if (n <= 0) break;
|
||||
req.append(buf, buf + n);
|
||||
if (req.find("\r\n\r\n") != std::string::npos) break;
|
||||
if (req.size() > 8192) break;
|
||||
}
|
||||
|
||||
CallbackResult res;
|
||||
|
||||
// Parse request line: GET /path?query HTTP/1.1
|
||||
std::string_view sv{req};
|
||||
auto lineEnd = sv.find("\r\n");
|
||||
if (lineEnd != std::string_view::npos) {
|
||||
auto line = sv.substr(0, lineEnd);
|
||||
if (line.starts_with("GET ")) {
|
||||
line.remove_prefix(4);
|
||||
auto sp = line.find(' ');
|
||||
auto target = line.substr(0, sp);
|
||||
|
||||
auto qm = target.find('?');
|
||||
std::string_view path = (qm == std::string_view::npos) ? target : target.substr(0, qm);
|
||||
std::string_view query = (qm == std::string_view::npos) ? std::string_view{} : target.substr(qm + 1);
|
||||
|
||||
if (path == m_Path) {
|
||||
auto kv = parse_query(query);
|
||||
if (auto it = kv.find("code"); it != kv.end()) res.code = it->second;
|
||||
if (auto it = kv.find("state"); it != kv.end()) res.state = it->second;
|
||||
if (auto it = kv.find("error"); it != kv.end()) res.error = it->second;
|
||||
} else {
|
||||
res.error = "invalid_path";
|
||||
}
|
||||
} else {
|
||||
res.error = "unsupported_method";
|
||||
}
|
||||
} else {
|
||||
res.error = "malformed_request";
|
||||
}
|
||||
|
||||
std::string body;
|
||||
if (!res.error.empty()) {
|
||||
body = "<html><body><h2>Authorization failed</h2><p>" + res.error + "</p></body></html>";
|
||||
} else {
|
||||
body = "<html><body><h2>Authorization received</h2><p>You can close this window.</p></body></html>";
|
||||
}
|
||||
|
||||
std::string hdr =
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: text/html; charset=utf-8\r\n"
|
||||
"Connection: close\r\n"
|
||||
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n";
|
||||
|
||||
write_all(clientFd, hdr);
|
||||
write_all(clientFd, body);
|
||||
::shutdown(clientFd, SHUT_RDWR);
|
||||
::close(clientFd);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace ts6bot
|
||||
@@ -0,0 +1,244 @@
|
||||
#include <Spotify/PkceAuth.hpp>
|
||||
|
||||
#include <ts6bot/Crypto.hpp>
|
||||
#include <Spotify/HttpCallbackServer.hpp>
|
||||
#include <ts6bot/Url.hpp>
|
||||
|
||||
#include <curl/curl.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <print>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Spotify {
|
||||
|
||||
static size_t write_cb(void* contents, size_t size, size_t nmemb, void* userp) {
|
||||
auto* s = reinterpret_cast<std::string*>(userp);
|
||||
s->append(reinterpret_cast<const char*>(contents), size * nmemb);
|
||||
return size * nmemb;
|
||||
}
|
||||
|
||||
static std::string http_request(const std::string& url,
|
||||
const std::string& header,
|
||||
const std::string& postBody,
|
||||
const ProxyConfig& proxy) {
|
||||
std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
|
||||
if (!curl) throw std::runtime_error("curl_easy_init failed");
|
||||
|
||||
std::string response;
|
||||
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_cb);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &response);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
|
||||
|
||||
if (!proxy.url.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXY, proxy.url.c_str());
|
||||
long curlProxyType = (proxy.type == ProxyType::SOCKS5_HOSTNAME) ? CURLPROXY_SOCKS5_HOSTNAME : CURLPROXY_SOCKS5;
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXYTYPE, curlProxyType);
|
||||
|
||||
if (!proxy.username.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_SOCKS5_AUTH, (long)CURLAUTH_BASIC);
|
||||
std::string authStr = proxy.username + ":" + proxy.password;
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXYUSERPWD, authStr.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
struct curl_slist* headers = nullptr;
|
||||
if (!header.empty()) {
|
||||
headers = curl_slist_append(headers, header.c_str());
|
||||
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers);
|
||||
}
|
||||
|
||||
if (!postBody.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postBody.c_str());
|
||||
}
|
||||
|
||||
CURLcode res = curl_easy_perform(curl.get());
|
||||
if (headers) curl_slist_free_all(headers);
|
||||
|
||||
if (res != CURLE_OK) {
|
||||
throw std::runtime_error(std::string("curl error: ") + curl_easy_strerror(res));
|
||||
}
|
||||
|
||||
long httpCode = 0;
|
||||
curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &httpCode);
|
||||
if (httpCode < 200 || httpCode >= 300) {
|
||||
std::ostringstream oss;
|
||||
oss << "HTTP " << httpCode << " from " << url << "\n" << response;
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
bool TokenSet::IsExpired(std::chrono::seconds skew) const {
|
||||
const auto now = std::chrono::seconds{PkceAuth::NowUnixSeconds()};
|
||||
const auto exp = std::chrono::seconds{expires_at_utc};
|
||||
return now + skew >= exp;
|
||||
}
|
||||
|
||||
std::int64_t PkceAuth::NowUnixSeconds() {
|
||||
using namespace std::chrono;
|
||||
return duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
PkceAuth::PkceAuth(std::string clientId, std::string redirectUri, std::filesystem::path tokenCachePath)
|
||||
: m_ClientId(std::move(clientId)), m_RedirectUri(std::move(redirectUri)), m_TokenCachePath(std::move(tokenCachePath)) {}
|
||||
|
||||
void PkceAuth::AuthorizeAndStore(const std::vector<std::string>& scopes, std::chrono::milliseconds timeout) {
|
||||
auto redir = ts6bot::url::ParseHttpUrl(m_RedirectUri);
|
||||
|
||||
const std::string codeVerifier = ts6bot::crypto::GenerateCodeVerifier(64);
|
||||
const auto hashed = ts6bot::crypto::Sha256(std::span{codeVerifier.data(), codeVerifier.size()});
|
||||
const std::string codeChallenge = ts6bot::crypto::Base64UrlEncode(hashed);
|
||||
const std::string state = ts6bot::crypto::GenerateState(16);
|
||||
|
||||
std::string scopeStr;
|
||||
for (std::size_t i = 0; i < scopes.size(); ++i) {
|
||||
if (i) scopeStr += ' ';
|
||||
scopeStr += scopes[i];
|
||||
}
|
||||
|
||||
std::string authUrl = "https://accounts.spotify.com/authorize";
|
||||
authUrl += "?response_type=code";
|
||||
authUrl += "&client_id=" + ts6bot::url::EncodeComponent(m_ClientId);
|
||||
authUrl += "&redirect_uri=" + ts6bot::url::EncodeComponent(m_RedirectUri);
|
||||
authUrl += "&state=" + ts6bot::url::EncodeComponent(state);
|
||||
if (!scopeStr.empty()) {
|
||||
authUrl += "&scope=" + ts6bot::url::EncodeComponent(scopeStr);
|
||||
}
|
||||
authUrl += "&code_challenge_method=S256";
|
||||
authUrl += "&code_challenge=" + ts6bot::url::EncodeComponent(codeChallenge);
|
||||
|
||||
std::println("\nOpen this URL and approve access:\n{}\n", authUrl);
|
||||
std::println("Waiting for callback on {}:{}{} (timeout: {}s)...",
|
||||
redir.host, redir.port, redir.path, timeout.count() / 1000);
|
||||
|
||||
HttpCallbackServer srv(redir.host, redir.port, redir.path);
|
||||
auto cb = srv.WaitForCallback(timeout);
|
||||
if (!cb) throw std::runtime_error("Timed out waiting for OAuth redirect");
|
||||
|
||||
if (!cb->error.empty()) throw std::runtime_error("Spotify authorization failed: " + cb->error);
|
||||
if (cb->state != state) throw std::runtime_error("OAuth state mismatch");
|
||||
if (cb->code.empty()) throw std::runtime_error("No authorization code in callback");
|
||||
|
||||
auto tokens = ExchangeCodeForToken(cb->code, codeVerifier);
|
||||
Save(tokens);
|
||||
|
||||
if (m_Verbose) {
|
||||
std::println("Saved token cache: {}", m_TokenCachePath.string());
|
||||
std::println("Access expires_at_utc: {}", tokens.expires_at_utc);
|
||||
}
|
||||
}
|
||||
|
||||
TokenSet PkceAuth::ExchangeCodeForToken(const std::string& code, const std::string& codeVerifier) {
|
||||
const std::string tokenUrl = "https://accounts.spotify.com/api/token";
|
||||
|
||||
std::string body;
|
||||
body += "client_id=" + ts6bot::url::EncodeComponent(m_ClientId);
|
||||
body += "&grant_type=authorization_code";
|
||||
body += "&code=" + ts6bot::url::EncodeComponent(code);
|
||||
body += "&redirect_uri=" + ts6bot::url::EncodeComponent(m_RedirectUri);
|
||||
body += "&code_verifier=" + ts6bot::url::EncodeComponent(codeVerifier);
|
||||
|
||||
auto resp = http_request(tokenUrl, "Content-Type: application/x-www-form-urlencoded", body, m_Proxy);
|
||||
auto j = nlohmann::json::parse(resp);
|
||||
|
||||
TokenSet out;
|
||||
out.access_token = j.value("access_token", "");
|
||||
out.token_type = j.value("token_type", "Bearer");
|
||||
out.scope = j.value("scope", "");
|
||||
out.refresh_token = j.value("refresh_token", "");
|
||||
int expiresIn = j.value("expires_in", 0);
|
||||
|
||||
if (out.access_token.empty() || expiresIn <= 0) {
|
||||
throw std::runtime_error("Token exchange returned no access_token/expires_in\n" + resp);
|
||||
}
|
||||
|
||||
out.expires_at_utc = NowUnixSeconds() + expiresIn;
|
||||
return out;
|
||||
}
|
||||
|
||||
TokenSet PkceAuth::RefreshAccessToken(const TokenSet& current) {
|
||||
if (current.refresh_token.empty()) throw std::runtime_error("No refresh_token; run auth-init");
|
||||
|
||||
const std::string tokenUrl = "https://accounts.spotify.com/api/token";
|
||||
std::string body;
|
||||
body += "grant_type=refresh_token";
|
||||
body += "&refresh_token=" + ts6bot::url::EncodeComponent(current.refresh_token);
|
||||
body += "&client_id=" + ts6bot::url::EncodeComponent(m_ClientId); // required for PKCE refresh
|
||||
|
||||
auto resp = http_request(tokenUrl, "Content-Type: application/x-www-form-urlencoded", body, m_Proxy);
|
||||
auto j = nlohmann::json::parse(resp);
|
||||
|
||||
TokenSet out = current;
|
||||
out.access_token = j.value("access_token", "");
|
||||
out.token_type = j.value("token_type", out.token_type);
|
||||
out.scope = j.value("scope", out.scope);
|
||||
int expiresIn = j.value("expires_in", 0);
|
||||
|
||||
// Spotify may omit refresh_token on refresh; keep old one
|
||||
if (auto rt = j.value("refresh_token", ""); !rt.empty()) out.refresh_token = rt;
|
||||
|
||||
if (out.access_token.empty() || expiresIn <= 0) {
|
||||
throw std::runtime_error("Refresh returned no access_token/expires_in\n" + resp);
|
||||
}
|
||||
|
||||
out.expires_at_utc = NowUnixSeconds() + expiresIn;
|
||||
return out;
|
||||
}
|
||||
|
||||
void PkceAuth::Save(const TokenSet& t) const {
|
||||
std::filesystem::create_directories(m_TokenCachePath.parent_path());
|
||||
|
||||
nlohmann::json j;
|
||||
j["access_token"] = t.access_token;
|
||||
j["token_type"] = t.token_type;
|
||||
j["scope"] = t.scope;
|
||||
j["refresh_token"] = t.refresh_token;
|
||||
j["expires_at_utc"] = t.expires_at_utc;
|
||||
|
||||
auto tmp = m_TokenCachePath;
|
||||
tmp += ".tmp";
|
||||
|
||||
{
|
||||
std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
|
||||
if (!f) throw std::runtime_error("Failed to write token cache: " + tmp.string());
|
||||
f << j.dump(2);
|
||||
}
|
||||
std::filesystem::rename(tmp, m_TokenCachePath);
|
||||
}
|
||||
|
||||
std::optional<TokenSet> PkceAuth::Load() const {
|
||||
std::ifstream f(m_TokenCachePath, std::ios::binary);
|
||||
if (!f) return std::nullopt;
|
||||
|
||||
nlohmann::json j;
|
||||
f >> j;
|
||||
|
||||
TokenSet t;
|
||||
t.access_token = j.value("access_token", "");
|
||||
t.token_type = j.value("token_type", "Bearer");
|
||||
t.scope = j.value("scope", "");
|
||||
t.refresh_token = j.value("refresh_token", "");
|
||||
t.expires_at_utc = j.value("expires_at_utc", 0LL);
|
||||
|
||||
if (t.access_token.empty() || t.expires_at_utc <= 0) return std::nullopt;
|
||||
return t;
|
||||
}
|
||||
|
||||
TokenSet PkceAuth::LoadOrRefresh() {
|
||||
auto loaded = Load();
|
||||
if (!loaded) throw std::runtime_error("No token cache found; run auth-init");
|
||||
|
||||
if (!loaded->IsExpired()) return *loaded;
|
||||
|
||||
if (m_Verbose) std::println("Access token expired; refreshing...");
|
||||
auto refreshed = RefreshAccessToken(*loaded);
|
||||
Save(refreshed);
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
} // namespace ts6bot
|
||||
@@ -0,0 +1,64 @@
|
||||
#include <ts6bot/Url.hpp>
|
||||
|
||||
#include <curl/curl.h>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
|
||||
namespace ts6bot::url {
|
||||
|
||||
std::string EncodeComponent(const std::string& s) {
|
||||
CURL* h = curl_easy_init();
|
||||
if (!h) throw std::runtime_error("curl_easy_init failed");
|
||||
|
||||
char* esc = curl_easy_escape(h, s.c_str(), static_cast<int>(s.size()));
|
||||
curl_easy_cleanup(h);
|
||||
|
||||
if (!esc) throw std::runtime_error("curl_easy_escape failed");
|
||||
|
||||
std::string out{esc};
|
||||
curl_free(esc);
|
||||
return out;
|
||||
}
|
||||
|
||||
static bool starts_with(std::string_view s, std::string_view p) {
|
||||
return s.size() >= p.size() && s.substr(0, p.size()) == p;
|
||||
}
|
||||
|
||||
HttpUrl ParseHttpUrl(const std::string& httpUrl) {
|
||||
std::string_view s{httpUrl};
|
||||
if (!starts_with(s, "http://")) {
|
||||
throw std::runtime_error("redirect_uri must start with http://");
|
||||
}
|
||||
s.remove_prefix(7);
|
||||
|
||||
// host[:port][/path]
|
||||
auto slash = s.find('/');
|
||||
std::string_view hostPort = (slash == std::string_view::npos) ? s : s.substr(0, slash);
|
||||
std::string_view path = (slash == std::string_view::npos) ? std::string_view{"/"} : s.substr(slash);
|
||||
|
||||
auto colon = hostPort.rfind(':');
|
||||
if (colon == std::string_view::npos) {
|
||||
throw std::runtime_error("redirect_uri must include explicit :port");
|
||||
}
|
||||
|
||||
HttpUrl out;
|
||||
out.host = std::string(hostPort.substr(0, colon));
|
||||
if (out.host.empty()) throw std::runtime_error("redirect_uri host empty");
|
||||
|
||||
auto portSv = hostPort.substr(colon + 1);
|
||||
if (portSv.empty()) throw std::runtime_error("redirect_uri port empty");
|
||||
|
||||
unsigned long port = 0;
|
||||
for (char c : portSv) {
|
||||
if (c < '0' || c > '9') throw std::runtime_error("redirect_uri port not numeric");
|
||||
port = port * 10 + static_cast<unsigned long>(c - '0');
|
||||
if (port > 65535) throw std::runtime_error("redirect_uri port out of range");
|
||||
}
|
||||
|
||||
out.port = static_cast<uint16_t>(port);
|
||||
out.path = std::string(path);
|
||||
if (out.path.empty() || out.path[0] != '/') out.path = "/" + out.path;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace ts6bot::url
|
||||
@@ -0,0 +1,660 @@
|
||||
#include "Youtube/Client.hpp"
|
||||
#include "Youtube/SolverCore.hpp"
|
||||
#include "Youtube/SolverLib.hpp"
|
||||
#include "cpr/cprtypes.h"
|
||||
#include "cpr/parameters.h"
|
||||
#include "cpr/proxies.h"
|
||||
#include "cpr/proxyauth.h"
|
||||
#include "cpr/response.h"
|
||||
#include "cpr/session.h"
|
||||
#include <algorithm>
|
||||
#include <curl/curl.h>
|
||||
#include <curl/easy.h>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <print>
|
||||
#include <ranges>
|
||||
#include <regex>
|
||||
using json = nlohmann::json;
|
||||
namespace YouTube {
|
||||
|
||||
// ============================================================================
|
||||
// Constructor
|
||||
// ============================================================================
|
||||
|
||||
Client::Client(std::string apiKey, std::string accessToken)
|
||||
: m_ApiKey(std::move(apiKey)), m_AccessToken(std::move(accessToken)) {
|
||||
|
||||
// Initialize QuickJS
|
||||
m_rt = JS_NewRuntime();
|
||||
JS_SetMemoryLimit(m_rt, 64 * 1024 * 1024);
|
||||
m_ctx = JS_NewContext(m_rt);
|
||||
InitSolver();
|
||||
}
|
||||
|
||||
Client::~Client() {
|
||||
JS_FreeContext(m_ctx);
|
||||
JS_FreeRuntime(m_rt);
|
||||
} // ============================================================================
|
||||
// HTTP Request Implementation
|
||||
// ============================================================================
|
||||
void Client::InitSolver() {
|
||||
JS_FreeValue(m_ctx,
|
||||
JS_Eval(m_ctx, (char *)yt_solver_core_js, yt_solver_core_js_len,
|
||||
"core.js", JS_EVAL_TYPE_GLOBAL));
|
||||
// Create the Bridge
|
||||
const char *bridge = "var meriyah=lib.meriyah; var astring=lib.astring;";
|
||||
JS_FreeValue(m_ctx, JS_Eval(m_ctx, bridge, strlen(bridge), "bridge",
|
||||
JS_EVAL_TYPE_GLOBAL));
|
||||
|
||||
// Load Core
|
||||
JS_FreeValue(m_ctx,
|
||||
JS_Eval(m_ctx, (char *)yt_solver_lib_js, yt_solver_lib_js_len,
|
||||
"lib.js", JS_EVAL_TYPE_GLOBAL));
|
||||
}
|
||||
|
||||
void Client::SetPlayerJs(const std::string &js) {
|
||||
json in = {{"type", "player"},
|
||||
{"player", js},
|
||||
{"output_preprocessed", true},
|
||||
{"requests", json::array()}};
|
||||
JSValue global = JS_GetGlobalObject(m_ctx);
|
||||
JSValue jsc = JS_GetPropertyStr(m_ctx, global, "jsc");
|
||||
|
||||
std::string in_s = in.dump();
|
||||
JSValue input_val = JS_ParseJSON(m_ctx, in_s.c_str(), in_s.size(), "in");
|
||||
JSValue args[] = {input_val};
|
||||
JSValue res = JS_Call(m_ctx, jsc, global, 1, args);
|
||||
|
||||
if (!JS_IsException(res)) {
|
||||
const char *ptr = JS_ToCString(m_ctx, res);
|
||||
m_preprocessedPlayer = json::parse(ptr)["preprocessed_player"];
|
||||
JS_FreeCString(m_ctx, ptr);
|
||||
}
|
||||
|
||||
JS_FreeValue(m_ctx, res);
|
||||
JS_FreeValue(m_ctx, input_val);
|
||||
JS_FreeValue(m_ctx, jsc);
|
||||
JS_FreeValue(m_ctx, global);
|
||||
}
|
||||
|
||||
std::string Client::SolveChallenge(const std::string &challenge,
|
||||
const std::string &type) {
|
||||
if (m_preprocessedPlayer.empty() || challenge.empty())
|
||||
return "";
|
||||
|
||||
json in = {{"type", "preprocessed"},
|
||||
{"preprocessed_player", m_preprocessedPlayer},
|
||||
{"requests", {{{"type", type}, {"challenges", {challenge}}}}}};
|
||||
|
||||
JSValue global = JS_GetGlobalObject(m_ctx);
|
||||
JSValue jsc = JS_GetPropertyStr(m_ctx, global, "jsc");
|
||||
std::string s_in = in.dump();
|
||||
JSValue input_val = JS_ParseJSON(m_ctx, s_in.c_str(), s_in.size(), "in");
|
||||
JSValue args[] = {input_val};
|
||||
JSValue res = JS_Call(m_ctx, jsc, global, 1, args);
|
||||
|
||||
std::string out = "";
|
||||
if (!JS_IsException(res)) {
|
||||
const char *ptr = JS_ToCString(m_ctx, res);
|
||||
auto j_res = json::parse(ptr);
|
||||
if (j_res["responses"][0]["type"] == "result")
|
||||
out = j_res["responses"][0]["data"][challenge].get<std::string>();
|
||||
JS_FreeCString(m_ctx, ptr);
|
||||
}
|
||||
|
||||
JS_FreeValue(m_ctx, res);
|
||||
JS_FreeValue(m_ctx, input_val);
|
||||
JS_FreeValue(m_ctx, jsc);
|
||||
JS_FreeValue(m_ctx, global);
|
||||
return out;
|
||||
}
|
||||
|
||||
auto Client::GetBestStreams(const std::string &videoId) -> Result<definitions::Streams> {
|
||||
// 1. Get base.js and signatureTimestamp via Watch Page
|
||||
auto watchPage = PerformRequest(
|
||||
"https://www.youtube.com", "/watch", {{"v", videoId}},
|
||||
{{"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
|
||||
HttpMethod::GET); // Adjust to your base YouTube URL if needed
|
||||
if (!watchPage)
|
||||
return std::unexpected(watchPage.error());
|
||||
|
||||
std::regex js_re("/s/player/[a-f0-9]+/player_ias\\.vflset/[^/]+/base\\.js");
|
||||
std::smatch js_m;
|
||||
if (!std::regex_search(*watchPage, js_m, js_re))
|
||||
return std::unexpected(ApiError{0, "Failed to find player JS", ""});
|
||||
|
||||
std::string base_url = "https://www.youtube.com" + js_m.str();
|
||||
std::cout << js_m.str() << std::endl;
|
||||
// Fetch player JS (using simple CURL/CPR or your PerformRequest)
|
||||
auto playerJs = PerformRequest(
|
||||
"https://www.youtube.com", js_m.str(), {},
|
||||
{{"User-Agent",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}},
|
||||
HttpMethod::GET); // Use direct URL here
|
||||
if (!playerJs)
|
||||
return std::unexpected(playerJs.error());
|
||||
|
||||
SetPlayerJs(*playerJs);
|
||||
|
||||
std::regex sts_re("signatureTimestamp:(\\d+)");
|
||||
std::smatch sts_m;
|
||||
int sts = std::regex_search(*playerJs, sts_m, sts_re)
|
||||
? std::stoi(sts_m[1].str())
|
||||
: 0;
|
||||
|
||||
// 2. Call Player API using ANDROID client for best stream access
|
||||
json payload = {
|
||||
{"context",
|
||||
{{"client",
|
||||
{{"clientName", "ANDROID"},
|
||||
{"clientVersion", "20.10.38"},
|
||||
{"osName", "Android"},
|
||||
{"osVersion", "11"},
|
||||
{"hl", "en"},
|
||||
{"timeZone", "UTC"}}}}},
|
||||
{"videoId", videoId},
|
||||
{"playbackContext",
|
||||
{{"contentPlaybackContext", {{"signatureTimestamp", sts}}}}}};
|
||||
|
||||
auto response = PerformRequest(
|
||||
"https://www.youtube.com", "/youtubei/v1/player", {},
|
||||
{{"Content-Type", "application/json"},
|
||||
{"User-Agent",
|
||||
"com.google.android.youtube/20.10.38 (Linux; U; Android 11) gzip"},
|
||||
{"X-Youtube-Client-Name", "3"},
|
||||
{"X-Youtube-Client-Version", "20.10.38"}},
|
||||
HttpMethod::POST, payload.dump());
|
||||
if (!response)
|
||||
return std::unexpected(response.error());
|
||||
|
||||
json data = json::parse(*response);
|
||||
definitions::Streams best;
|
||||
|
||||
auto parse_query = [](std::string query) {
|
||||
std::map<std::string, std::string> m;
|
||||
std::regex re("([^&=]+)=([^&]*)");
|
||||
for (std::sregex_iterator it(query.begin(), query.end(), re), end;
|
||||
it != end; ++it)
|
||||
m[(*it)[1].str()] = (*it)[2].str();
|
||||
return m;
|
||||
};
|
||||
|
||||
if (data.contains("streamingData") &&
|
||||
data["streamingData"].contains("adaptiveFormats")) {
|
||||
for (auto &f : data["streamingData"]["adaptiveFormats"]) {
|
||||
definitions::StreamInfo info;
|
||||
info.itag = f["itag"].get<int>();
|
||||
info.mimeType = f["mimeType"].get<std::string>();
|
||||
info.bitrate = f["bitrate"].get<int>();
|
||||
|
||||
// Decrypt URL
|
||||
if (f.contains("url")) {
|
||||
info.url = f["url"].get<std::string>();
|
||||
} else if (f.contains("signatureCipher")) {
|
||||
auto c = parse_query(f["signatureCipher"].get<std::string>());
|
||||
// The query parts are URL encoded in the cipher string
|
||||
std::string sig = SolveChallenge(c["s"], "sig");
|
||||
// Construct URL (handle sp parameter which is usually 'sig' or 'lsig')
|
||||
info.url =
|
||||
c["url"] + "&" + (c.count("sp") ? c["sp"] : "sig") + "=" + sig;
|
||||
}
|
||||
|
||||
// Handle 'n' parameter
|
||||
std::regex n_re("([&?])n=([^&]*)");
|
||||
std::smatch n_m;
|
||||
if (std::regex_search(info.url, n_m, n_re)) {
|
||||
std::string n_solved = SolveChallenge(n_m[2].str(), "n");
|
||||
info.url = std::regex_replace(info.url, n_re, "$1n=" + n_solved);
|
||||
}
|
||||
|
||||
// Selection Logic
|
||||
if (info.mimeType.find("audio/") != std::string::npos) {
|
||||
if (info.bitrate > best.audio.bitrate)
|
||||
best.audio = info;
|
||||
} else if (info.mimeType.find("video/") != std::string::npos) {
|
||||
info.width = f.value("width", 0);
|
||||
info.height = f.value("height", 0);
|
||||
// Prefer higher resolution, then higher bitrate
|
||||
if (info.height > best.video.height ||
|
||||
(info.height == best.video.height &&
|
||||
info.bitrate > best.video.bitrate)) {
|
||||
best.video = info;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
auto Client::PerformRequest(const std::string &purl,
|
||||
const std::string &endpoint,
|
||||
const cpr::Parameters ¶ms,
|
||||
const cpr::Header &headers, HttpMethod method,
|
||||
const std::string &body) -> Result<std::string> {
|
||||
cpr::Session session;
|
||||
// 1. Build Query String
|
||||
auto urlStr = purl + endpoint;
|
||||
auto url = cpr::Url(urlStr);
|
||||
session.SetUrl(url);
|
||||
// Always append API Key if we don't have a Bearer token, or if we just want
|
||||
// to be safe. YouTube allows 'key' param for almost all requests.
|
||||
cpr::Parameters final_params = params;
|
||||
if (!m_ApiKey.empty() && urlStr.contains("googleapis")) {
|
||||
final_params.Add({"key", m_ApiKey});
|
||||
}
|
||||
session.SetParameters(final_params);
|
||||
|
||||
cpr::Header head = headers;
|
||||
if (!m_AccessToken.empty()) {
|
||||
head["Authorization"] = std::format("Bearer {}", m_AccessToken);
|
||||
}
|
||||
session.SetHeader(head);
|
||||
|
||||
if (!m_Proxy.url.empty()) {
|
||||
auto proxy = cpr::Proxies(
|
||||
{std::make_pair("http", std::format("socks5://{}", m_Proxy.url)),
|
||||
std::make_pair("https", std::format("socks5://{}", m_Proxy.url))});
|
||||
auto encodedAuth =
|
||||
cpr::EncodedAuthentication(m_Proxy.username, m_Proxy.password);
|
||||
auto auth =
|
||||
cpr::ProxyAuthentication({std::make_pair("socks5", encodedAuth),
|
||||
std::make_pair("http", encodedAuth),
|
||||
std::make_pair("https", encodedAuth)});
|
||||
session.SetProxies(proxy);
|
||||
session.SetProxyAuth(auth);
|
||||
}
|
||||
|
||||
if (!body.empty()) {
|
||||
session.SetBody(cpr::Body{body});
|
||||
}
|
||||
std::cout << session.GetFullRequestUrl() << std::endl;
|
||||
// Headers
|
||||
// struct curl_slist *headers = nullptr;
|
||||
// headers = curl_slist_append(headers, "Accept: application/json");
|
||||
// headers = curl_slist_append(headers, "Content-Type: application/json");
|
||||
|
||||
// Add Authorization header ONLY if Access Token is provided
|
||||
// if (!m_AccessToken.empty()) {
|
||||
// headers = curl_slist_append(
|
||||
// headers,
|
||||
// std::format("Authorization: Bearer {}", m_AccessToken).c_str());
|
||||
// }
|
||||
cpr::Response response;
|
||||
if (m_Verbose) {
|
||||
std::println("Request: {} {}", method == HttpMethod::GET ? "GET" : "POST",
|
||||
url.str());
|
||||
}
|
||||
|
||||
// Method Selection
|
||||
switch (method) {
|
||||
case HttpMethod::POST:
|
||||
response = session.Post();
|
||||
break;
|
||||
case HttpMethod::PUT:
|
||||
response = session.Put();
|
||||
break;
|
||||
case HttpMethod::DELETE:
|
||||
response = session.Delete();
|
||||
break;
|
||||
default:
|
||||
response = session.Get();
|
||||
break;
|
||||
}
|
||||
|
||||
// Verbose Logging
|
||||
if (response.status_code != 200) {
|
||||
return std::unexpected(ApiError{static_cast<int>(response.status_code),
|
||||
response.text, response.error.message});
|
||||
}
|
||||
|
||||
std::println("Response Code: {}", response.status_code);
|
||||
|
||||
// 4. Handle Errors (HTTP 4xx/5xx)
|
||||
|
||||
return response.text;
|
||||
}
|
||||
|
||||
auto Client::PerformRequest(const std::string &endpoint,
|
||||
const cpr::Parameters ¶ms,
|
||||
const cpr::Header &headers, HttpMethod method,
|
||||
const std::string &body) -> Result<std::string> {
|
||||
return this->PerformRequest(m_BaseUrl, endpoint, params, headers, method,
|
||||
body);
|
||||
}
|
||||
|
||||
auto Client::WriteCallback(void *c, size_t s, size_t n, std::string *o)
|
||||
-> size_t {
|
||||
o->append(static_cast<char *>(c), s * n);
|
||||
return s * n;
|
||||
}
|
||||
|
||||
auto Client::UrlEncode(std::string_view value) const -> std::string {
|
||||
std::unique_ptr<char, decltype(&curl_free)> escaped(
|
||||
curl_easy_escape(nullptr, value.data(), static_cast<int>(value.length())),
|
||||
curl_free);
|
||||
|
||||
if (!escaped) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return std::string(escaped.get());
|
||||
}
|
||||
// ... (Inside namespace YouTube)
|
||||
|
||||
// ============================================================================
|
||||
// Player API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::PerformInternalRequest(const std::string &endpoint,
|
||||
const std::string &jsonBody)
|
||||
-> Result<std::string> {
|
||||
// This uses the internal YouTube domain, not googleapis
|
||||
std::string fullUrl = "https://www.youtube.com" + endpoint;
|
||||
|
||||
std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
|
||||
std::string response;
|
||||
|
||||
if (!curl)
|
||||
return std::unexpected(ApiError{0, "CURL init failed", ""});
|
||||
|
||||
struct curl_slist *headers = nullptr;
|
||||
headers = curl_slist_append(headers, "Content-Type: application/json");
|
||||
// User-Agent is critical here. We must look like the Android app.
|
||||
headers = curl_slist_append(
|
||||
headers,
|
||||
"User-Agent: com.google.android.youtube/19.29.35 (Linux; U; Android 11)");
|
||||
|
||||
curl_easy_setopt(curl.get(), CURLOPT_URL, fullUrl.c_str());
|
||||
curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, jsonBody.c_str());
|
||||
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &response);
|
||||
if (!m_Proxy.url.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXY, m_Proxy.url.c_str());
|
||||
long curlProxyType = (m_Proxy.type == ProxyType::SOCKS5_HOSTNAME)
|
||||
? CURLPROXY_SOCKS5_HOSTNAME
|
||||
: CURLPROXY_SOCKS5;
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXYTYPE, curlProxyType);
|
||||
|
||||
if (!m_Proxy.username.empty()) {
|
||||
curl_easy_setopt(curl.get(), CURLOPT_SOCKS5_AUTH, (long)CURLAUTH_BASIC);
|
||||
auto authStr = std::format("{}:{}", m_Proxy.username, m_Proxy.password);
|
||||
curl_easy_setopt(curl.get(), CURLOPT_PROXYUSERPWD, authStr.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (m_Verbose) {
|
||||
std::println("Internal Request: POST {}", fullUrl);
|
||||
}
|
||||
|
||||
CURLcode res = curl_easy_perform(curl.get());
|
||||
curl_slist_free_all(headers);
|
||||
|
||||
if (res != CURLE_OK) {
|
||||
return std::unexpected(ApiError{
|
||||
static_cast<int>(res), curl_easy_strerror(res), "CURL Internal Error"});
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
auto Client::ExtractVideoId(std::string_view url) const
|
||||
-> std::optional<std::string> {
|
||||
// Pattern 1: Standard youtube.com watch URL
|
||||
// https://www.youtube.com/watch?v=VIDEO_ID or
|
||||
// https://youtube.com/watch?v=VIDEO_ID
|
||||
static const std::regex watch_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/watch\?.*v=([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
// Pattern 2: Shortened youtu.be URL
|
||||
// https://youtu.be/VIDEO_ID
|
||||
static const std::regex short_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
// Pattern 3: Embedded URL
|
||||
// https://www.youtube.com/embed/VIDEO_ID
|
||||
static const std::regex embed_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
// Pattern 4: YouTube shorts
|
||||
// https://www.youtube.com/shorts/VIDEO_ID
|
||||
static const std::regex shorts_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
std::cmatch match;
|
||||
std::string url_str(url);
|
||||
|
||||
// Try each pattern
|
||||
if (std::regex_search(url_str.c_str(), match, watch_pattern) ||
|
||||
std::regex_search(url_str.c_str(), match, short_pattern) ||
|
||||
std::regex_search(url_str.c_str(), match, embed_pattern) ||
|
||||
std::regex_search(url_str.c_str(), match, shorts_pattern)) {
|
||||
return match[1].str();
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto Client::GetAudioStreamUrl(const std::string &videoId)
|
||||
-> Result<std::string> {
|
||||
// 1. Construct the "Android" Payload
|
||||
// This specific context structure is known to bypass some signature
|
||||
// requirements
|
||||
std::string payload = std::format(R"({{
|
||||
"videoId": "{}",
|
||||
"context": {{
|
||||
"client": {{
|
||||
"clientName": "ANDROID",
|
||||
"clientVersion": "19.29.35",
|
||||
"androidSdkVersion": 30,
|
||||
"hl": "en",
|
||||
"gl": "US",
|
||||
"utcOffsetMinutes": 0
|
||||
}}
|
||||
}}
|
||||
}})",
|
||||
videoId);
|
||||
|
||||
// 2. Perform Request to /youtubei/v1/player
|
||||
auto response = PerformInternalRequest("/youtubei/v1/player", payload);
|
||||
if (!response)
|
||||
return std::unexpected(response.error());
|
||||
// 3. Parse Response
|
||||
PlayerResponse playerResp;
|
||||
// Note: You need to configure glz to ignore unknown fields to avoid errors
|
||||
// or ensure your struct definition is robust.
|
||||
auto parse_err = glz::read<glz::opts{.error_on_unknown_keys = false}>(
|
||||
playerResp, *response);
|
||||
|
||||
if (parse_err) {
|
||||
// If parsing fails, the structure might have changed or video is restricted
|
||||
return std::unexpected(ApiError{0, "Failed to parse player response",
|
||||
glz::format_error(parse_err, *response)});
|
||||
}
|
||||
|
||||
// 4. Find Best Audio Stream
|
||||
std::string bestUrl = "";
|
||||
int maxBitrate = 0;
|
||||
|
||||
// adaptiveFormats contains separate audio and video streams
|
||||
for (const auto &format : playerResp.streamingData.formats) {
|
||||
// We only want audio
|
||||
// CHECK: If URL is empty, it uses "signatureCipher" which we cannot handle
|
||||
// easily in C++
|
||||
if (format.url.empty()) {
|
||||
// If you find *only* ciphered streams, this method will fail (typical for
|
||||
// VEVO music videos)
|
||||
continue;
|
||||
}
|
||||
|
||||
// Simple quality selection (highest bitrate)
|
||||
// You could also parse format.bitrate which is a string in JSON
|
||||
// but often convertible to int. Assuming safe access:
|
||||
try {
|
||||
// Note: In real production code, parse the "bitrate" string safely
|
||||
// For now we just take the first valid one or implement simple logic
|
||||
bestUrl = format.url;
|
||||
break; // Taking the first valid audio stream is usually sufficient (often
|
||||
// decent quality m4a)
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
|
||||
if (bestUrl.empty()) {
|
||||
return std::unexpected(
|
||||
ApiError{403, "No direct audio URL found (Video likely encrypted/VEVO)",
|
||||
videoId});
|
||||
}
|
||||
|
||||
return bestUrl;
|
||||
}
|
||||
// ============================================================================
|
||||
// Search API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::Search(const SearchParams ¶ms)
|
||||
-> Result<PageResult<SearchResult>> {
|
||||
cpr::Parameters query;
|
||||
query.Add({"part", params.part});
|
||||
|
||||
query.Add({"q", params.q});
|
||||
|
||||
query.Add({"maxResults", std::to_string(params.maxResults)});
|
||||
query.Add({"order", params.order});
|
||||
query.Add({"videoDuration", params.videoDuration});
|
||||
|
||||
// Modern ranges approach for joining types
|
||||
query.Add({"type", params.type | std::views::join_with(',') |
|
||||
std::ranges::to<std::string>()});
|
||||
|
||||
if (!params.pageToken.empty()) {
|
||||
query.Add({"pageToken", params.pageToken});
|
||||
}
|
||||
|
||||
auto response = PerformRequest("/search", query);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
|
||||
if (m_Verbose) {
|
||||
std::println("Search response: {}", response.value());
|
||||
}
|
||||
|
||||
PageResult<SearchResult> results;
|
||||
auto parse_err =
|
||||
glz::read<glz::opts{.error_on_unknown_keys = false}>(results, *response);
|
||||
|
||||
if (parse_err) {
|
||||
return std::unexpected(ApiError{0, "JSON Parse Error",
|
||||
glz::format_error(parse_err, *response)});
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
auto Client::UrlEncodePreservingOperators(std::string_view query) const
|
||||
-> std::string {
|
||||
std::string result;
|
||||
result.reserve(query.length() * 2); // Reserve space for potential encoding
|
||||
|
||||
for (char ch : query) {
|
||||
switch (ch) {
|
||||
case '-': // NOT operator
|
||||
case '|': // OR operator (will be encoded to %7C in PerformRequest)
|
||||
case ' ': // Space between terms
|
||||
result += ch;
|
||||
break;
|
||||
default:
|
||||
// Encode everything else
|
||||
if (std::isalnum(static_cast<unsigned char>(ch))) {
|
||||
result += ch;
|
||||
} else {
|
||||
// Manual percent encoding for special chars
|
||||
result += std::format("%{:02X}", static_cast<unsigned char>(ch));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
// ============================================================================
|
||||
// Videos API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetVideo(const std::string &id, const std::string &part)
|
||||
-> Result<Video> {
|
||||
auto res = GetVideos({id}, part);
|
||||
if (!res)
|
||||
return std::unexpected(res.error());
|
||||
if (res->empty())
|
||||
return std::unexpected(ApiError{404, "Video not found", ""});
|
||||
return res->at(0);
|
||||
}
|
||||
|
||||
auto Client::GetVideos(const std::vector<std::string> &ids,
|
||||
const std::string &part) -> Result<std::vector<Video>> {
|
||||
cpr::Parameters query;
|
||||
query.Add({"part", part});
|
||||
query.Add(
|
||||
{"id", std::views::join_with(ids, ',') | std::ranges::to<std::string>()});
|
||||
|
||||
auto response = PerformRequest("/videos", query);
|
||||
if (!response)
|
||||
return std::unexpected(response.error());
|
||||
|
||||
PageResult<Video> page;
|
||||
auto parse_err =
|
||||
glz::read<glz::opts{.error_on_unknown_keys = false}>(page, *response);
|
||||
|
||||
if (parse_err) {
|
||||
return std::unexpected(ApiError{0, "JSON Parse Error",
|
||||
glz::format_error(parse_err, *response)});
|
||||
}
|
||||
|
||||
return page.items;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Playlists API Implementation
|
||||
// ============================================================================
|
||||
|
||||
auto Client::GetPlaylistItems(const std::string &playlistId,
|
||||
const std::string &pageToken)
|
||||
-> Result<PageResult<SearchResult>> {
|
||||
cpr::Parameters query;
|
||||
query.Add({"part", "snippet"});
|
||||
query.Add({"playlistId", playlistId});
|
||||
query.Add({"maxResults", "50"});
|
||||
if (!pageToken.empty())
|
||||
query.Add({"pageToken", pageToken});
|
||||
|
||||
auto response = PerformRequest("/playlistItems", query);
|
||||
if (!response)
|
||||
return std::unexpected(response.error());
|
||||
|
||||
// Note: PlaylistItems resource structure is slightly different from
|
||||
// SearchResult, but often close enough for basic snippet extraction. In
|
||||
// strict production, define a separate PlaylistItems struct.
|
||||
PageResult<SearchResult> page;
|
||||
auto parse_err =
|
||||
glz::read<glz::opts{.error_on_unknown_keys = false}>(page, *response);
|
||||
|
||||
(page, *response);
|
||||
|
||||
if (parse_err) {
|
||||
return std::unexpected(ApiError{0, "JSON Parse Error",
|
||||
glz::format_error(parse_err, *response)});
|
||||
}
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
} // namespace YouTube
|
||||
@@ -0,0 +1 @@
|
||||
MusicManager
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,420 @@
|
||||
#include "ts6bot/VirtualMicrophone.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
|
||||
VirtualMicrophone::VirtualMicrophone(std::string micName, bool createNew)
|
||||
: m_MicName(std::move(micName)) {
|
||||
gst_init(nullptr, nullptr);
|
||||
|
||||
// Keep bus sink distinct from mic name
|
||||
m_BusSinkName = m_MicName + "_bus";
|
||||
if (createNew) {
|
||||
// 1) Clear any stale modules with same names (covers crashes / SIGKILL)
|
||||
CleanupStaleDevicesByName();
|
||||
// 2) Create devices for this run
|
||||
CreateDevices();
|
||||
// 3) Wire bus.monitor -> virtual mic ports
|
||||
CreateLinks();
|
||||
}
|
||||
std::println("Virtual mic created: {}", m_MicName);
|
||||
std::println("Bus sink created: {}", m_BusSinkName);
|
||||
}
|
||||
|
||||
VirtualMicrophone::~VirtualMicrophone() noexcept {
|
||||
try {
|
||||
StopPlayback();
|
||||
DestroyDevices();
|
||||
} catch (...) {
|
||||
// never throw from destructor
|
||||
}
|
||||
}
|
||||
|
||||
void VirtualMicrophone::CleanupStaleDevicesByName() {
|
||||
// pactl list short modules is tabular and intended for scripting
|
||||
// :contentReference[oaicite:4]{index=4}
|
||||
const std::string out = RunCommandCapture("pactl list modules short");
|
||||
for (const auto &line : SplitLines(out)) {
|
||||
// Format is tabular; commonly: <id>\t<name>\t<args>
|
||||
// We'll parse first token as id, then search args for our sink_name
|
||||
// occurrences.
|
||||
std::string_view sv(line);
|
||||
|
||||
// parse id
|
||||
uint32_t id = ParseFirstUint(sv);
|
||||
if (!id)
|
||||
continue;
|
||||
|
||||
// quick filter: only unload modules that mention our names
|
||||
if (!Contains(sv, "sink_name=") && !Contains(sv, "source_name="))
|
||||
continue;
|
||||
|
||||
const bool mentionsBus =
|
||||
Contains(sv, std::string("sink_name=" + m_BusSinkName));
|
||||
const bool mentionsMic =
|
||||
Contains(sv, std::string("sink_name=" + m_MicName)) ||
|
||||
Contains(sv, std::string("source_name=" + m_MicName));
|
||||
|
||||
if (mentionsBus || mentionsMic) {
|
||||
// Unload by numeric id :contentReference[oaicite:5]{index=5}
|
||||
RunCommandNoCapture(std::format("pactl unload-module {}", id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void VirtualMicrophone::CreateDevices() {
|
||||
// PipeWire-Pulse modules support sink_name/source_name style properties
|
||||
// :contentReference[oaicite:6]{index=6} Create BUS SINK (Audio/Sink)
|
||||
{
|
||||
const std::string cmd =
|
||||
std::format("pactl load-module module-null-sink "
|
||||
"media.class=Audio/Sink "
|
||||
"sink_name={} "
|
||||
"channel_map=stereo "
|
||||
"sink_properties=\\\"device.description='{} (bus)'\\\"",
|
||||
m_BusSinkName, m_MicName);
|
||||
m_ModBusSink = ParseFirstUint(RunCommandCapture(cmd));
|
||||
if (!m_ModBusSink) {
|
||||
throw std::runtime_error(
|
||||
"Failed to create bus sink via module-null-sink");
|
||||
}
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
// Create VIRTUAL MIC (Audio/Source/Virtual) – apps select this as microphone
|
||||
// This approach is widely used on PipeWire setups: module-null-sink with
|
||||
// media.class=Audio/Source/Virtual :contentReference[oaicite:7]{index=7}
|
||||
{
|
||||
const std::string cmd =
|
||||
std::format("pactl load-module module-null-sink "
|
||||
"media.class=Audio/Source/Virtual "
|
||||
"sink_name={} "
|
||||
"channel_map=front-left,front-right "
|
||||
"sink_properties=\\\"device.description='{}'\\\"",
|
||||
m_MicName, m_MicName);
|
||||
m_ModVirtualMic = ParseFirstUint(RunCommandCapture(cmd));
|
||||
if (!m_ModVirtualMic) {
|
||||
// rollback bus sink
|
||||
RunCommandNoCapture(std::format("pactl unload-module {}", m_ModBusSink));
|
||||
m_ModBusSink = 0;
|
||||
throw std::runtime_error("Failed to create virtual microphone device");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void VirtualMicrophone::CreateLinks() {
|
||||
// pw-link is the canonical CLI to link/disconnect ports
|
||||
// :contentReference[oaicite:8]{index=8}
|
||||
const auto outs = PwLinkListOutputs();
|
||||
const auto ins = PwLinkListInputs();
|
||||
|
||||
// On PipeWire, bus sink monitor ports commonly look like:
|
||||
// <bus>:monitor_FL / monitor_FR
|
||||
// Virtual mic commonly exposes inputs like:
|
||||
// <mic>:input_FL / input_FR (sometimes playback_FL/FR; we handle both)
|
||||
m_LinkOutFL =
|
||||
FindPortPrefix(outs, std::string(m_BusSinkName + ":monitor_"), "FL");
|
||||
m_LinkOutFR =
|
||||
FindPortPrefix(outs, std::string(m_BusSinkName + ":monitor_"), "FR");
|
||||
|
||||
m_LinkInFL = FindPortPrefix(ins, std::string(m_MicName + ":"), "FL");
|
||||
m_LinkInFR = FindPortPrefix(ins, std::string(m_MicName + ":"), "FR");
|
||||
|
||||
// If input ports are ambiguous, prefer typical names.
|
||||
if (!m_LinkInFL) {
|
||||
for (auto cand : {std::string(m_MicName + ":input_FL"),
|
||||
std::string(m_MicName + ":playback_FL")}) {
|
||||
if (std::find(ins.begin(), ins.end(), cand) != ins.end()) {
|
||||
m_LinkInFL = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!m_LinkInFR) {
|
||||
for (auto cand : {std::string(m_MicName + ":input_FR"),
|
||||
std::string(m_MicName + ":playback_FR")}) {
|
||||
if (std::find(ins.begin(), ins.end(), cand) != ins.end()) {
|
||||
m_LinkInFR = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_LinkOutFL || !m_LinkOutFR || !m_LinkInFL || !m_LinkInFR) {
|
||||
throw std::runtime_error("Could not locate PipeWire ports for linking. "
|
||||
"Run: pw-link -o ; pw-link -i ; and verify port "
|
||||
"names for the created nodes.");
|
||||
}
|
||||
|
||||
// Link and linger is default behavior :contentReference[oaicite:9]{index=9}
|
||||
RunCommandNoCapture(
|
||||
std::format("pw-link '{}' '{}'", *m_LinkOutFL, *m_LinkInFL));
|
||||
RunCommandNoCapture(
|
||||
std::format("pw-link '{}' '{}'", *m_LinkOutFR, *m_LinkInFR));
|
||||
}
|
||||
|
||||
void VirtualMicrophone::PlayUri(const std::string &trackUri,
|
||||
const std::string &token,
|
||||
const ProxyConfig &proxy) {
|
||||
if (!proxy.url.empty()) {
|
||||
const std::string proxyStr = std::format(
|
||||
"socks5://{}:{}@{}", proxy.username, proxy.password, proxy.url);
|
||||
setenv("all_proxy", proxyStr.c_str(), 1);
|
||||
setenv("https_proxy", proxyStr.c_str(), 1);
|
||||
setenv("socks5_proxy", proxyStr.c_str(), 1);
|
||||
}
|
||||
|
||||
// Route playback into BUS sink; the bus is linked into the virtual mic.
|
||||
const std::string pipeline =
|
||||
std::format("spotifyaudiosrc track=\"{}\" access-token=\"{}\" ! "
|
||||
"oggdemux ! vorbisdec ! audioconvert ! audioresample ! "
|
||||
"pulsesink device=\"{}\"",
|
||||
trackUri, token, m_BusSinkName);
|
||||
|
||||
BuildAndStartPipeline(pipeline);
|
||||
}
|
||||
|
||||
void VirtualMicrophone::PlayUri(const std::string &trackUri,
|
||||
const std::optional<ProxyConfig> proxy) {
|
||||
if (proxy) {
|
||||
const std::string proxyStr =
|
||||
std::format("socks5://{}:{}@{}", proxy.value().username,
|
||||
proxy.value().password, proxy.value().url);
|
||||
setenv("all_proxy", proxyStr.c_str(), 1);
|
||||
setenv("https_proxy", proxyStr.c_str(), 1);
|
||||
setenv("socks5_proxy", proxyStr.c_str(), 1);
|
||||
}
|
||||
|
||||
// Route playback into BUS sink; the bus is linked into the virtual mic.
|
||||
const std::string pipeline =
|
||||
std::format("uridecodebin uri=\"{}\" ! audioconvert ! audioresample ! "
|
||||
"pulsesink device=\"{}\"",
|
||||
trackUri, m_BusSinkName);
|
||||
|
||||
BuildAndStartPipeline(pipeline);
|
||||
}
|
||||
|
||||
void VirtualMicrophone::Pause() {
|
||||
if (!m_Pipeline)
|
||||
return;
|
||||
gst_element_set_state(
|
||||
m_Pipeline.get(),
|
||||
GST_STATE_PAUSED); // GStreamer states include PAUSED/PLAYING
|
||||
// :contentReference[oaicite:10]{index=10}
|
||||
}
|
||||
|
||||
void VirtualMicrophone::Resume() {
|
||||
if (!m_Pipeline)
|
||||
return;
|
||||
gst_element_set_state(m_Pipeline.get(), GST_STATE_PLAYING);
|
||||
}
|
||||
|
||||
void VirtualMicrophone::StopPlayback() {
|
||||
if (m_BusThread.joinable()) {
|
||||
m_BusThread.request_stop();
|
||||
m_BusThread.join();
|
||||
}
|
||||
if (m_Pipeline) {
|
||||
gst_element_set_state(m_Pipeline.get(), GST_STATE_NULL);
|
||||
m_Pipeline.reset();
|
||||
}
|
||||
{
|
||||
std::lock_guard lk(m_Mtx);
|
||||
m_Finished = true;
|
||||
m_HadError = false;
|
||||
m_LastError.clear();
|
||||
}
|
||||
m_Cv.notify_all();
|
||||
}
|
||||
|
||||
void VirtualMicrophone::WaitUntilFinished() {
|
||||
std::unique_lock lk(m_Mtx);
|
||||
m_Cv.wait(lk, [this] { return m_Finished; });
|
||||
if (m_HadError) {
|
||||
throw std::runtime_error(m_LastError.empty() ? "GStreamer ERROR"
|
||||
: m_LastError);
|
||||
}
|
||||
}
|
||||
|
||||
void VirtualMicrophone::DestroyDevices() noexcept {
|
||||
// Disconnect links first (optional, but clean). pw-link supports disconnect
|
||||
// :contentReference[oaicite:11]{index=11}
|
||||
if (m_LinkOutFL && m_LinkInFL)
|
||||
RunCommandNoCapture(
|
||||
std::format("pw-link -d '{}' '{}'", *m_LinkOutFL, *m_LinkInFL));
|
||||
if (m_LinkOutFR && m_LinkInFR)
|
||||
RunCommandNoCapture(
|
||||
std::format("pw-link -d '{}' '{}'", *m_LinkOutFR, *m_LinkInFR));
|
||||
m_LinkOutFL.reset();
|
||||
m_LinkOutFR.reset();
|
||||
m_LinkInFL.reset();
|
||||
m_LinkInFR.reset();
|
||||
|
||||
// Unload modules by id :contentReference[oaicite:12]{index=12}
|
||||
if (m_ModVirtualMic) {
|
||||
RunCommandNoCapture(std::format("pactl unload-module {}", m_ModVirtualMic));
|
||||
m_ModVirtualMic = 0;
|
||||
}
|
||||
if (m_ModBusSink) {
|
||||
RunCommandNoCapture(std::format("pactl unload-module {}", m_ModBusSink));
|
||||
m_ModBusSink = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void VirtualMicrophone::BuildAndStartPipeline(const std::string &pipelineDesc) {
|
||||
StopPlayback();
|
||||
|
||||
{
|
||||
std::lock_guard lk(m_Mtx);
|
||||
m_Finished = false;
|
||||
m_HadError = false;
|
||||
m_LastError.clear();
|
||||
}
|
||||
|
||||
GError *error = nullptr;
|
||||
m_Pipeline.reset(gst_parse_launch(pipelineDesc.c_str(), &error));
|
||||
if (error) {
|
||||
const std::string msg =
|
||||
error->message ? error->message : "unknown gst_parse_launch error";
|
||||
g_error_free(error);
|
||||
throw std::runtime_error("GStreamer parse error: " + msg);
|
||||
}
|
||||
|
||||
gst_element_set_state(m_Pipeline.get(), GST_STATE_PLAYING);
|
||||
|
||||
m_BusThread = std::jthread([this](std::stop_token st) { WatchBus(st); });
|
||||
}
|
||||
|
||||
void VirtualMicrophone::WatchBus(std::stop_token st) {
|
||||
if (!m_Pipeline)
|
||||
return;
|
||||
std::unique_ptr<GstBus, GstObjectDeleter> bus(
|
||||
gst_element_get_bus(m_Pipeline.get()));
|
||||
|
||||
while (!st.stop_requested()) {
|
||||
std::unique_ptr<GstMessage, GstMessageDeleter> msg(
|
||||
gst_bus_timed_pop_filtered(
|
||||
bus.get(), 500 * GST_MSECOND,
|
||||
static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_EOS)));
|
||||
|
||||
if (!msg)
|
||||
continue;
|
||||
|
||||
if (GST_MESSAGE_TYPE(msg.get()) == GST_MESSAGE_EOS) {
|
||||
// waiting for EOS is standard pattern
|
||||
// :contentReference[oaicite:13]{index=13}
|
||||
std::lock_guard lk(m_Mtx);
|
||||
m_Finished = true;
|
||||
m_HadError = false;
|
||||
m_Cv.notify_all();
|
||||
return;
|
||||
}
|
||||
|
||||
if (GST_MESSAGE_TYPE(msg.get()) == GST_MESSAGE_ERROR) {
|
||||
GError *err = nullptr;
|
||||
gchar *dbg = nullptr;
|
||||
gst_message_parse_error(msg.get(), &err, &dbg);
|
||||
|
||||
std::string text = "GStreamer ERROR";
|
||||
if (err && err->message)
|
||||
text += std::string(": ") + err->message;
|
||||
if (dbg)
|
||||
text += std::string(" | Debug: ") + dbg;
|
||||
|
||||
if (err)
|
||||
g_error_free(err);
|
||||
if (dbg)
|
||||
g_free(dbg);
|
||||
|
||||
{
|
||||
std::lock_guard lk(m_Mtx);
|
||||
m_Finished = true;
|
||||
m_HadError = true;
|
||||
m_LastError = std::move(text);
|
||||
}
|
||||
m_Cv.notify_all();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string VirtualMicrophone::RunCommandCapture(const std::string &cmd) {
|
||||
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"),
|
||||
pclose);
|
||||
if (!pipe)
|
||||
return {};
|
||||
std::array<char, 256> buf{};
|
||||
std::string out;
|
||||
while (fgets(buf.data(), buf.size(), pipe.get()))
|
||||
out += buf.data();
|
||||
return out;
|
||||
}
|
||||
|
||||
int VirtualMicrophone::RunCommandNoCapture(const std::string &cmd) {
|
||||
return std::system(cmd.c_str());
|
||||
}
|
||||
|
||||
uint32_t VirtualMicrophone::ParseFirstUint(std::string_view s) {
|
||||
size_t i = 0;
|
||||
while (i < s.size() &&
|
||||
(s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r'))
|
||||
++i;
|
||||
uint64_t v = 0;
|
||||
bool any = false;
|
||||
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
|
||||
any = true;
|
||||
v = v * 10 + static_cast<uint64_t>(s[i] - '0');
|
||||
if (v > 0xFFFFFFFFull)
|
||||
return 0;
|
||||
++i;
|
||||
}
|
||||
return any ? static_cast<uint32_t>(v) : 0;
|
||||
}
|
||||
|
||||
std::vector<std::string> VirtualMicrophone::SplitLines(const std::string &s) {
|
||||
std::vector<std::string> lines;
|
||||
std::string cur;
|
||||
for (char c : s) {
|
||||
if (c == '\n') {
|
||||
if (!cur.empty() && cur.back() == '\r')
|
||||
cur.pop_back();
|
||||
lines.push_back(cur);
|
||||
cur.clear();
|
||||
} else {
|
||||
cur.push_back(c);
|
||||
}
|
||||
}
|
||||
if (!cur.empty())
|
||||
lines.push_back(cur);
|
||||
return lines;
|
||||
}
|
||||
|
||||
bool VirtualMicrophone::Contains(std::string_view hay,
|
||||
std::string_view needle) {
|
||||
return hay.find(needle) != std::string_view::npos;
|
||||
}
|
||||
|
||||
std::vector<std::string> VirtualMicrophone::PwLinkListOutputs() {
|
||||
return SplitLines(RunCommandCapture("pw-link -o"));
|
||||
}
|
||||
|
||||
std::vector<std::string> VirtualMicrophone::PwLinkListInputs() {
|
||||
return SplitLines(RunCommandCapture("pw-link -i"));
|
||||
}
|
||||
|
||||
std::optional<std::string>
|
||||
VirtualMicrophone::FindPortPrefix(const std::vector<std::string> &list,
|
||||
std::string_view prefix,
|
||||
std::string_view suffix) {
|
||||
// Find first exact-ish match that contains prefix and ends with suffix, e.g.
|
||||
// prefix: "StudioMic_bus:monitor_" suffix: "FL"
|
||||
for (const auto &s : list) {
|
||||
std::string_view v(s);
|
||||
if (v.find(prefix) != std::string_view::npos && v.size() >= suffix.size() &&
|
||||
v.substr(v.size() - suffix.size()) == suffix) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
Reference in new issue
Block a user