19 Commits

Author SHA1 Message Date
Kun Deng 9420ee97b4 Merge pull request #9 from kdeng00/support_new_upload_endpoint
Support new upload endpoint
2022-01-09 18:07:50 -05:00
Kun Deng c46f386d70 Merge branch 'master' into support_new_upload_endpoint 2022-01-09 18:07:44 -05:00
kdeng00 d9962749c8 Ready for release 2022-01-09 18:06:43 -05:00
kdeng00 c8e8c1a460 Changed cmake version 2022-01-09 02:16:51 -05:00
kdeng00 dcfa9951d9 Updated Readme 2022-01-09 02:04:56 -05:00
kdeng00 e90278995a Saving changes 2022-01-09 00:31:43 -05:00
kdeng00 7c8e77f233 Formatting 2022-01-08 23:52:46 -05:00
Kun Deng a1b2e5f64a Merge branch 'master' into support_new_upload_endpoint 2022-01-08 23:46:43 -05:00
kdeng00 25e8774968 Visual Studio support 2022-01-08 21:12:55 -05:00
kdeng00 10ed33d412 Formatting 2022-01-08 21:09:40 -05:00
kdeng00 1ef40bcbfb Got functionality working 2022-01-01 00:39:35 -05:00
kdeng00 3e25dd77b5 Updates
Updating required flags for uploading a song with metadata
2021-12-31 22:15:17 -05:00
kdeng00 14d3c9acc6 Made progress 2021-12-31 19:09:31 -05:00
kdeng00 9930aab985 Updated Readme 2021-12-31 16:00:45 -05:00
kdeng00 0839731ee8 upload-meta command 2021-12-29 15:58:14 -05:00
Kun Deng 7a04b802f0 Merge pull request #8 from kdeng00/package_manager-switch
Package manager switch
2021-12-29 15:50:28 -05:00
kdeng00 63d6022d16 Updated Readme
Added link to conan repo
2021-12-29 15:47:21 -05:00
kdeng00 db1a6302ad Updated Readme 2021-12-29 15:45:12 -05:00
kdeng00 bd819f0332 package manager switch
Moving from Hunter to conan
2021-12-29 15:38:28 -05:00
45 changed files with 2111 additions and 1874 deletions
+41 -43
View File
@@ -1,27 +1,37 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.14)
include("cmake/HunterGate.cmake")
HunterGate(
URL "https://github.com/ruslo/hunter/archive/v0.23.184.tar.gz"
SHA1 "fe3fb05d51c21499c7eebbe7d0e102742a54a9cd"
)
project(IcarusDownloadManager) project(IcarusDownloadManager)
if(NOT ${CMAKE_VERSION} LESS 3.2) message(STATUS "Checking compiler flags for C++17 support.")
set(CMAKE_CXX_STANDARD 11) # Set C++17 support flags for various compilers
include(CheckCXXCompilerFlag)
if(WIN32)
message("Windows")
set(vs_ver 19.29.30138)
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL ${vs_ver})
message("Visual Studio version is at least ${vs_ver}")
set(CMAKE_CXX_STANDARD_COMPILE_OPTION "-std:c++latest")
set(CMAKE_CXX_EXTENSION_COMPILE_OPTION "-std:c++latest")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
else() else()
message(STATUS "Checking compiler flags for C++17 support.")
# Set C++17 support flags for various compilers
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-std=c++17" COMPILER_SUPPORTS_CXX17) check_cxx_compiler_flag("-std=c++17" COMPILER_SUPPORTS_CXX17)
check_cxx_compiler_flag("-std=c++0x" COMPILER_SUPPORTS_CXX0X) check_cxx_compiler_flag("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX17) if(COMPILER_SUPPORTS_CXX17)
message(STATUS "C++17 is supported.") message(STATUS "C++17 is supported.")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++")
else() else()
@@ -47,6 +57,7 @@ set(SOURCES
src/Managers/FileManager.cpp src/Managers/FileManager.cpp
src/Managers/TokenManager.cpp src/Managers/TokenManager.cpp
src/Managers/UserManager.cpp src/Managers/UserManager.cpp
src/Models/Song.cpp
src/Parsers/APIParser.cpp src/Parsers/APIParser.cpp
src/Syncers/Delete.cpp src/Syncers/Delete.cpp
src/Syncers/Download.cpp src/Syncers/Download.cpp
@@ -54,36 +65,23 @@ set(SOURCES
src/Syncers/Upload.cpp src/Syncers/Upload.cpp
src/Utilities/Conversions.cpp src/Utilities/Conversions.cpp
) )
set(HEADERS
include/Managers/ActionManager.h set(IDM_INCLUDE_DIR
include/Managers/CommitManager.h "${CMAKE_CURRENT_SOURCE_DIR}/include")
include/Managers/FileManager.h
include/Managers/TokenManager.h # conan
include/Managers/UserManager.h set(CONAN_BUILDINFO
include/Models/API.h ${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
include/Models/Flags.h
include/Models/IcarusAction.h message("conan build info ${CONAN_BUILDINFO}")
include/Models/Song.h include(${CONAN_BUILDINFO})
include/Models/Token.h conan_basic_setup()
include/Models/UploadForm.h
include/Models/User.h include_directories(${CPR_INCLUDE_DIRS} ${IDM_INCLUDE_DIR})
include/Parsers/APIParser.h
include/Syncers/Delete.h set(USE_SYSTEM_CURL OFF)
include/Syncers/Download.h set(BUILD_CPR_TESTS OFF)
include/Syncers/RetrieveRecords.h
include/Syncers/SyncerBase.h
include/Syncers/Upload.h
include/Utilities/Conversions.h
)
hunter_add_package(nlohmann_json) add_executable(icd ${SOURCES})
find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(icd PUBLIC ${CONAN_LIBS})
hunter_add_package(cpr)
find_package(cpr CONFIG REQUIRED)
add_executable(icd ${SOURCES} ${HEADERS})
target_link_libraries(icd PUBLIC nlohmann_json::nlohmann_json cpr::cpr)
include_directories(include/)
+49 -18
View File
@@ -1,17 +1,18 @@
# IcarusDownloadManager # IcarusDownloadManager
IcarusDownloadManager is a Linux CLI software client application that has the feature of uploading and downloading songs from the [Icarus](https://github.com/amazing-username/Icarus) Music Server. IcarusDownloadManager is a Linux CLI software client application that has the feature of uploading and downloading songs from the [Icarus](https://github.com/kdeng00/Icarus) Music Server.
## Built With ## Built With
* C++ * C++ with C++17 features
* CMake * CMake
* GCC * GCC >= 9 or Visual Studio >= 16 [2019]
* [Hunter](https://github.com/ruslo/hunter) * [conan](https://github.com/conan-io/conan)
* libCurl
* [json](https://github.com/nlohmann/json) * [json](https://github.com/nlohmann/json)
* [cpr](http://whoshuu.github.io/cpr/) * [openssl](https://github.com/openssl/openssl)
* [curl](https://github.com/curl/curl)
* [cpr](https://github.com/libcpr/cpr)
### Getting Started ### Getting Started
@@ -19,27 +20,56 @@ IcarusDownloadManager is a Linux CLI software client application that has the fe
Build the project: Build the project:
``` ```
export HUNTER_ROOT=/path/to/download/hunter/files/for/dependencies git clone --recursive https://github.com/kdeng00/IcarusDownloadManager
mkdir _build
cd _build
cmake -H. -B_builds -DHUNTER_STATUS_DEBUG=ON -DCMAKE_BUILD_TYPE=DEBUG mkdir build
cmake --build _builds --config Debug cd build
make
conan install .. --build
cmake ..
cmake --build . --config release -j
``` ```
The program has been built and can be executed by the binary file *icd*. For information on how to use icd, merely execute the program without any command line arguments. The program has been built and can be executed by the binary file *icd*. For information on how to use icd, merely execute the program without any command line arguments.
### Downloading Song ### Downloading Song
``icd download -u spacecadet -p stellar40 -h https://icarus.com -b 15``
```BASH
icd download -u spacecadet -p stellar40 -h https://icarus.com -b 15
```
### Uploading Song ### Uploading Song
``icd upload -u spacecadet -p stellar40 -h https://icarus.com -s /path/of/song.mp3``
```BASH
icd upload -u spacecadet -p stellar40 -h https://icarus.com -s /path/of/song.mp3
```
### Uploading Song with metadata
```BASH
icd upload-meta -u spacecadet -p stellar40 -h https://icarus.com -s /path/of/song.mp3 -t 1 -m /path/to/metadata/config/collection.json -ca /path/to/cover/art/image.png
```
### Uploading Song with metadata from directory
```BASH
icd upload-meta -u spacecadet -p stellar40 -h https://icarus.com -smca /path/where/songs/and/metadata/exists/
```
### Retrieving Song in json ### Retrieving Song in json
``icd retrieve -u spacecadet -p stellar40 -h https://icarus.com -rt songs``
```Bash
icd retrieve -u spacecadet -p stellar40 -h https://icarus.com -rt songs
```
### Deleting Song ### Deleting Song
``icd delete -u spacecadet -p stellar40 -h https://icarus.com -D 15``
```BASH
icd delete -u spacecadet -p stellar40 -h https://icarus.com -D 15
```
## Contributing ## Contributing
@@ -48,14 +78,15 @@ Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the code of conduc
## Versioning ## Versioning
[v0.2.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.2.0)
[v0.1.1](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.1.1) [v0.1.1](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.1.1)
[v0.1.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/0.1.0) [v0.1.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/0.1.0)
## Authors ## Authors
* **Kun Deng** - [amazing-username](https://github.com/amazing-username) * **Kun Deng** - [kdeng00](https://github.com/kdeng00)
See also the list of [contributors](https://github.com/amazing-username/Icarus/graphs/contributors) who participated in this project. See also the list of [contributors](https://github.com/kdeng00/Icarus/graphs/contributors) who participated in this project.
## License ## License
-528
View File
@@ -1,528 +0,0 @@
# Copyright (c) 2013-2019, Ruslan Baratov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# This is a gate file to Hunter package manager.
# Include this file using `include` command and add package you need, example:
#
# cmake_minimum_required(VERSION 3.2)
#
# include("cmake/HunterGate.cmake")
# HunterGate(
# URL "https://github.com/path/to/hunter/archive.tar.gz"
# SHA1 "798501e983f14b28b10cda16afa4de69eee1da1d"
# )
#
# project(MyProject)
#
# hunter_add_package(Foo)
# hunter_add_package(Boo COMPONENTS Bar Baz)
#
# Projects:
# * https://github.com/hunter-packages/gate/
# * https://github.com/ruslo/hunter
option(HUNTER_ENABLED "Enable Hunter package manager support" ON)
if(HUNTER_ENABLED)
if(CMAKE_VERSION VERSION_LESS "3.2")
message(
FATAL_ERROR
"At least CMake version 3.2 required for Hunter dependency management."
" Update CMake or set HUNTER_ENABLED to OFF."
)
endif()
endif()
include(CMakeParseArguments) # cmake_parse_arguments
option(HUNTER_STATUS_PRINT "Print working status" ON)
option(HUNTER_STATUS_DEBUG "Print a lot info" OFF)
option(HUNTER_TLS_VERIFY "Enable/disable TLS certificate checking on downloads" ON)
set(HUNTER_ERROR_PAGE "https://docs.hunter.sh/en/latest/reference/errors")
function(hunter_gate_status_print)
if(HUNTER_STATUS_PRINT OR HUNTER_STATUS_DEBUG)
foreach(print_message ${ARGV})
message(STATUS "[hunter] ${print_message}")
endforeach()
endif()
endfunction()
function(hunter_gate_status_debug)
if(HUNTER_STATUS_DEBUG)
foreach(print_message ${ARGV})
string(TIMESTAMP timestamp)
message(STATUS "[hunter *** DEBUG *** ${timestamp}] ${print_message}")
endforeach()
endif()
endfunction()
function(hunter_gate_error_page error_page)
message("------------------------------ ERROR ------------------------------")
message(" ${HUNTER_ERROR_PAGE}/${error_page}.html")
message("-------------------------------------------------------------------")
message("")
message(FATAL_ERROR "")
endfunction()
function(hunter_gate_internal_error)
message("")
foreach(print_message ${ARGV})
message("[hunter ** INTERNAL **] ${print_message}")
endforeach()
message("[hunter ** INTERNAL **] [Directory:${CMAKE_CURRENT_LIST_DIR}]")
message("")
hunter_gate_error_page("error.internal")
endfunction()
function(hunter_gate_fatal_error)
cmake_parse_arguments(hunter "" "ERROR_PAGE" "" "${ARGV}")
if("${hunter_ERROR_PAGE}" STREQUAL "")
hunter_gate_internal_error("Expected ERROR_PAGE")
endif()
message("")
foreach(x ${hunter_UNPARSED_ARGUMENTS})
message("[hunter ** FATAL ERROR **] ${x}")
endforeach()
message("[hunter ** FATAL ERROR **] [Directory:${CMAKE_CURRENT_LIST_DIR}]")
message("")
hunter_gate_error_page("${hunter_ERROR_PAGE}")
endfunction()
function(hunter_gate_user_error)
hunter_gate_fatal_error(${ARGV} ERROR_PAGE "error.incorrect.input.data")
endfunction()
function(hunter_gate_self root version sha1 result)
string(COMPARE EQUAL "${root}" "" is_bad)
if(is_bad)
hunter_gate_internal_error("root is empty")
endif()
string(COMPARE EQUAL "${version}" "" is_bad)
if(is_bad)
hunter_gate_internal_error("version is empty")
endif()
string(COMPARE EQUAL "${sha1}" "" is_bad)
if(is_bad)
hunter_gate_internal_error("sha1 is empty")
endif()
string(SUBSTRING "${sha1}" 0 7 archive_id)
set(
hunter_self
"${root}/_Base/Download/Hunter/${version}/${archive_id}/Unpacked"
)
set("${result}" "${hunter_self}" PARENT_SCOPE)
endfunction()
# Set HUNTER_GATE_ROOT cmake variable to suitable value.
function(hunter_gate_detect_root)
# Check CMake variable
string(COMPARE NOTEQUAL "${HUNTER_ROOT}" "" not_empty)
if(not_empty)
set(HUNTER_GATE_ROOT "${HUNTER_ROOT}" PARENT_SCOPE)
hunter_gate_status_debug("HUNTER_ROOT detected by cmake variable")
return()
endif()
# Check environment variable
string(COMPARE NOTEQUAL "$ENV{HUNTER_ROOT}" "" not_empty)
if(not_empty)
set(HUNTER_GATE_ROOT "$ENV{HUNTER_ROOT}" PARENT_SCOPE)
hunter_gate_status_debug("HUNTER_ROOT detected by environment variable")
return()
endif()
# Check HOME environment variable
string(COMPARE NOTEQUAL "$ENV{HOME}" "" result)
if(result)
set(HUNTER_GATE_ROOT "$ENV{HOME}/.hunter" PARENT_SCOPE)
hunter_gate_status_debug("HUNTER_ROOT set using HOME environment variable")
return()
endif()
# Check SYSTEMDRIVE and USERPROFILE environment variable (windows only)
if(WIN32)
string(COMPARE NOTEQUAL "$ENV{SYSTEMDRIVE}" "" result)
if(result)
set(HUNTER_GATE_ROOT "$ENV{SYSTEMDRIVE}/.hunter" PARENT_SCOPE)
hunter_gate_status_debug(
"HUNTER_ROOT set using SYSTEMDRIVE environment variable"
)
return()
endif()
string(COMPARE NOTEQUAL "$ENV{USERPROFILE}" "" result)
if(result)
set(HUNTER_GATE_ROOT "$ENV{USERPROFILE}/.hunter" PARENT_SCOPE)
hunter_gate_status_debug(
"HUNTER_ROOT set using USERPROFILE environment variable"
)
return()
endif()
endif()
hunter_gate_fatal_error(
"Can't detect HUNTER_ROOT"
ERROR_PAGE "error.detect.hunter.root"
)
endfunction()
function(hunter_gate_download dir)
string(
COMPARE
NOTEQUAL
"$ENV{HUNTER_DISABLE_AUTOINSTALL}"
""
disable_autoinstall
)
if(disable_autoinstall AND NOT HUNTER_RUN_INSTALL)
hunter_gate_fatal_error(
"Hunter not found in '${dir}'"
"Set HUNTER_RUN_INSTALL=ON to auto-install it from '${HUNTER_GATE_URL}'"
"Settings:"
" HUNTER_ROOT: ${HUNTER_GATE_ROOT}"
" HUNTER_SHA1: ${HUNTER_GATE_SHA1}"
ERROR_PAGE "error.run.install"
)
endif()
string(COMPARE EQUAL "${dir}" "" is_bad)
if(is_bad)
hunter_gate_internal_error("Empty 'dir' argument")
endif()
string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" is_bad)
if(is_bad)
hunter_gate_internal_error("HUNTER_GATE_SHA1 empty")
endif()
string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" is_bad)
if(is_bad)
hunter_gate_internal_error("HUNTER_GATE_URL empty")
endif()
set(done_location "${dir}/DONE")
set(sha1_location "${dir}/SHA1")
set(build_dir "${dir}/Build")
set(cmakelists "${dir}/CMakeLists.txt")
hunter_gate_status_debug("Locking directory: ${dir}")
file(LOCK "${dir}" DIRECTORY GUARD FUNCTION)
hunter_gate_status_debug("Lock done")
if(EXISTS "${done_location}")
# while waiting for lock other instance can do all the job
hunter_gate_status_debug("File '${done_location}' found, skip install")
return()
endif()
file(REMOVE_RECURSE "${build_dir}")
file(REMOVE_RECURSE "${cmakelists}")
file(MAKE_DIRECTORY "${build_dir}") # check directory permissions
# Disabling languages speeds up a little bit, reduces noise in the output
# and avoids path too long windows error
file(
WRITE
"${cmakelists}"
"cmake_minimum_required(VERSION 3.2)\n"
"project(HunterDownload LANGUAGES NONE)\n"
"include(ExternalProject)\n"
"ExternalProject_Add(\n"
" Hunter\n"
" URL\n"
" \"${HUNTER_GATE_URL}\"\n"
" URL_HASH\n"
" SHA1=${HUNTER_GATE_SHA1}\n"
" DOWNLOAD_DIR\n"
" \"${dir}\"\n"
" TLS_VERIFY\n"
" ${HUNTER_TLS_VERIFY}\n"
" SOURCE_DIR\n"
" \"${dir}/Unpacked\"\n"
" CONFIGURE_COMMAND\n"
" \"\"\n"
" BUILD_COMMAND\n"
" \"\"\n"
" INSTALL_COMMAND\n"
" \"\"\n"
")\n"
)
if(HUNTER_STATUS_DEBUG)
set(logging_params "")
else()
set(logging_params OUTPUT_QUIET)
endif()
hunter_gate_status_debug("Run generate")
# Need to add toolchain file too.
# Otherwise on Visual Studio + MDD this will fail with error:
# "Could not find an appropriate version of the Windows 10 SDK installed on this machine"
if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
get_filename_component(absolute_CMAKE_TOOLCHAIN_FILE "${CMAKE_TOOLCHAIN_FILE}" ABSOLUTE)
set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=${absolute_CMAKE_TOOLCHAIN_FILE}")
else()
# 'toolchain_arg' can't be empty
set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=")
endif()
string(COMPARE EQUAL "${CMAKE_MAKE_PROGRAM}" "" no_make)
if(no_make)
set(make_arg "")
else()
# Test case: remove Ninja from PATH but set it via CMAKE_MAKE_PROGRAM
set(make_arg "-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}")
endif()
execute_process(
COMMAND
"${CMAKE_COMMAND}"
"-H${dir}"
"-B${build_dir}"
"-G${CMAKE_GENERATOR}"
"${toolchain_arg}"
${make_arg}
WORKING_DIRECTORY "${dir}"
RESULT_VARIABLE download_result
${logging_params}
)
if(NOT download_result EQUAL 0)
hunter_gate_internal_error(
"Configure project failed."
"To reproduce the error run: ${CMAKE_COMMAND} -H${dir} -B${build_dir} -G${CMAKE_GENERATOR} ${toolchain_arg} ${make_arg}"
"In directory ${dir}"
)
endif()
hunter_gate_status_print(
"Initializing Hunter workspace (${HUNTER_GATE_SHA1})"
" ${HUNTER_GATE_URL}"
" -> ${dir}"
)
execute_process(
COMMAND "${CMAKE_COMMAND}" --build "${build_dir}"
WORKING_DIRECTORY "${dir}"
RESULT_VARIABLE download_result
${logging_params}
)
if(NOT download_result EQUAL 0)
hunter_gate_internal_error("Build project failed")
endif()
file(REMOVE_RECURSE "${build_dir}")
file(REMOVE_RECURSE "${cmakelists}")
file(WRITE "${sha1_location}" "${HUNTER_GATE_SHA1}")
file(WRITE "${done_location}" "DONE")
hunter_gate_status_debug("Finished")
endfunction()
# Must be a macro so master file 'cmake/Hunter' can
# apply all variables easily just by 'include' command
# (otherwise PARENT_SCOPE magic needed)
macro(HunterGate)
if(HUNTER_GATE_DONE)
# variable HUNTER_GATE_DONE set explicitly for external project
# (see `hunter_download`)
set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES)
endif()
# First HunterGate command will init Hunter, others will be ignored
get_property(_hunter_gate_done GLOBAL PROPERTY HUNTER_GATE_DONE SET)
if(NOT HUNTER_ENABLED)
# Empty function to avoid error "unknown function"
function(hunter_add_package)
endfunction()
set(
_hunter_gate_disabled_mode_dir
"${CMAKE_CURRENT_LIST_DIR}/cmake/Hunter/disabled-mode"
)
if(EXISTS "${_hunter_gate_disabled_mode_dir}")
hunter_gate_status_debug(
"Adding \"disabled-mode\" modules: ${_hunter_gate_disabled_mode_dir}"
)
list(APPEND CMAKE_PREFIX_PATH "${_hunter_gate_disabled_mode_dir}")
endif()
elseif(_hunter_gate_done)
hunter_gate_status_debug("Secondary HunterGate (use old settings)")
hunter_gate_self(
"${HUNTER_CACHED_ROOT}"
"${HUNTER_VERSION}"
"${HUNTER_SHA1}"
_hunter_self
)
include("${_hunter_self}/cmake/Hunter")
else()
set(HUNTER_GATE_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}")
string(COMPARE NOTEQUAL "${PROJECT_NAME}" "" _have_project_name)
if(_have_project_name)
hunter_gate_fatal_error(
"Please set HunterGate *before* 'project' command. "
"Detected project: ${PROJECT_NAME}"
ERROR_PAGE "error.huntergate.before.project"
)
endif()
cmake_parse_arguments(
HUNTER_GATE "LOCAL" "URL;SHA1;GLOBAL;FILEPATH" "" ${ARGV}
)
string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" _empty_sha1)
string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" _empty_url)
string(
COMPARE
NOTEQUAL
"${HUNTER_GATE_UNPARSED_ARGUMENTS}"
""
_have_unparsed
)
string(COMPARE NOTEQUAL "${HUNTER_GATE_GLOBAL}" "" _have_global)
string(COMPARE NOTEQUAL "${HUNTER_GATE_FILEPATH}" "" _have_filepath)
if(_have_unparsed)
hunter_gate_user_error(
"HunterGate unparsed arguments: ${HUNTER_GATE_UNPARSED_ARGUMENTS}"
)
endif()
if(_empty_sha1)
hunter_gate_user_error("SHA1 suboption of HunterGate is mandatory")
endif()
if(_empty_url)
hunter_gate_user_error("URL suboption of HunterGate is mandatory")
endif()
if(_have_global)
if(HUNTER_GATE_LOCAL)
hunter_gate_user_error("Unexpected LOCAL (already has GLOBAL)")
endif()
if(_have_filepath)
hunter_gate_user_error("Unexpected FILEPATH (already has GLOBAL)")
endif()
endif()
if(HUNTER_GATE_LOCAL)
if(_have_global)
hunter_gate_user_error("Unexpected GLOBAL (already has LOCAL)")
endif()
if(_have_filepath)
hunter_gate_user_error("Unexpected FILEPATH (already has LOCAL)")
endif()
endif()
if(_have_filepath)
if(_have_global)
hunter_gate_user_error("Unexpected GLOBAL (already has FILEPATH)")
endif()
if(HUNTER_GATE_LOCAL)
hunter_gate_user_error("Unexpected LOCAL (already has FILEPATH)")
endif()
endif()
hunter_gate_detect_root() # set HUNTER_GATE_ROOT
# Beautify path, fix probable problems with windows path slashes
get_filename_component(
HUNTER_GATE_ROOT "${HUNTER_GATE_ROOT}" ABSOLUTE
)
hunter_gate_status_debug("HUNTER_ROOT: ${HUNTER_GATE_ROOT}")
if(NOT HUNTER_ALLOW_SPACES_IN_PATH)
string(FIND "${HUNTER_GATE_ROOT}" " " _contain_spaces)
if(NOT _contain_spaces EQUAL -1)
hunter_gate_fatal_error(
"HUNTER_ROOT (${HUNTER_GATE_ROOT}) contains spaces."
"Set HUNTER_ALLOW_SPACES_IN_PATH=ON to skip this error"
"(Use at your own risk!)"
ERROR_PAGE "error.spaces.in.hunter.root"
)
endif()
endif()
string(
REGEX
MATCH
"[0-9]+\\.[0-9]+\\.[0-9]+[-_a-z0-9]*"
HUNTER_GATE_VERSION
"${HUNTER_GATE_URL}"
)
string(COMPARE EQUAL "${HUNTER_GATE_VERSION}" "" _is_empty)
if(_is_empty)
set(HUNTER_GATE_VERSION "unknown")
endif()
hunter_gate_self(
"${HUNTER_GATE_ROOT}"
"${HUNTER_GATE_VERSION}"
"${HUNTER_GATE_SHA1}"
_hunter_self
)
set(_master_location "${_hunter_self}/cmake/Hunter")
get_filename_component(_archive_id_location "${_hunter_self}/.." ABSOLUTE)
set(_done_location "${_archive_id_location}/DONE")
set(_sha1_location "${_archive_id_location}/SHA1")
# Check Hunter already downloaded by HunterGate
if(NOT EXISTS "${_done_location}")
hunter_gate_download("${_archive_id_location}")
endif()
if(NOT EXISTS "${_done_location}")
hunter_gate_internal_error("hunter_gate_download failed")
endif()
if(NOT EXISTS "${_sha1_location}")
hunter_gate_internal_error("${_sha1_location} not found")
endif()
file(READ "${_sha1_location}" _sha1_value)
string(COMPARE EQUAL "${_sha1_value}" "${HUNTER_GATE_SHA1}" _is_equal)
if(NOT _is_equal)
hunter_gate_internal_error(
"Short SHA1 collision:"
" ${_sha1_value} (from ${_sha1_location})"
" ${HUNTER_GATE_SHA1} (HunterGate)"
)
endif()
if(NOT EXISTS "${_master_location}")
hunter_gate_user_error(
"Master file not found:"
" ${_master_location}"
"try to update Hunter/HunterGate"
)
endif()
include("${_master_location}")
set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES)
endif()
endmacro()
+20
View File
@@ -0,0 +1,20 @@
[requires]
nlohmann_json/3.10.4
openssl/1.1.1l
libcurl/7.80.0
cpr/1.7.2
[generators]
cmake
[options]
openssl:shared=False
libcurl:shared=False
cpr:shared=False
libcurl:with_ssl=openssl
libcurl:with_ftp=False
libcurl:with_gopher=False
libcurl:with_imap=False
libcurl:with_pop3=False
libcurl:with_smb=False
libcurl:with_smtp=False
+59 -9
View File
@@ -1,6 +1,7 @@
#ifndef ACTIONMANAGER_H_ #ifndef ACTIONMANAGER_H_
#define ACTIONMANAGER_H_ #define ACTIONMANAGER_H_
#include<algorithm>
#include<string> #include<string>
#include<string_view> #include<string_view>
#include<array> #include<array>
@@ -11,33 +12,82 @@
namespace Managers namespace Managers
{ {
class ActionManager
{
public:
class ActionManager
{
public:
ActionManager(char**, int); ActionManager(char**, int);
Models::IcarusAction retrieveIcarusAction() const; Models::IcarusAction retrieveIcarusAction() const;
private: private:
constexpr std::array<const char*, 12> supportedFlags() noexcept; constexpr std::array<const char*, 16> supportedFlags() noexcept
constexpr std::array<const char*, 4> supportedActions() noexcept; {
constexpr std::array<const char*, 16> allFlags{"-u", "-p", "-t", "-h", "-s",
"-sd", "-sr", "-d", "-D", "-b", "-rt", "-nc",
"-m", "-ca", "-smca", "-t"};
bool isNumber(const std::string_view) noexcept; return allFlags;
}
constexpr std::array<const char*, 4> supportedActions() noexcept;
void initialize(); void initialize();
void validateFlags(); void validateFlags();
// Checks to see if the flag is valid
template<typename Str>
bool isValidFlag(const Str flag)
{
const auto flags = supportedFlags();
const auto i = std::find_if(flags.begin(), flags.end(), [&](const Str &f)
{
return f.compare(flag) == 0 ? true : false;
});
std::vector<std::string> parsedFlags(); auto result = i != flags.end() ? true : false;
return result;
}
template<typename Str>
bool doesFlagHaveValue(const Str flag)
{
const auto flags = parsedFlags();
auto i = std::find_if(flags.begin(), flags.end(), [&](const Str &f)
{
return f.compare(flag) == 0 ? true : false;
});
if (i != flags.end())
{
if (++i != flags.end() && !isValidFlag<Str>(*i))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
void printAction() noexcept; void printAction() noexcept;
void printFlags() noexcept; void printFlags() noexcept;
std::vector<std::string> parsedFlags();
std::string action; std::string action;
std::vector<Models::Flags> flags; std::vector<Models::Flags> flags;
char **params; char **params;
int paramCount; int paramCount;
}; };
} }
#endif #endif
+175 -9
View File
@@ -2,48 +2,214 @@
#define COMMITMANAGER_H_ #define COMMITMANAGER_H_
#include<map> #include<map>
#include<iostream>
#include<string> #include<string>
#include<string_view>
#include"Models/API.h" #include"Models/API.h"
#include"Models/Token.h"
#include"Models/IcarusAction.h" #include"Models/IcarusAction.h"
#include"Models/Song.h"
#include"Models/Token.h"
#include"Utilities/Checks.h"
namespace Managers namespace Managers
{ {
class CommitManager
{ class CommitManager
public: {
public:
CommitManager(Models::IcarusAction&); CommitManager(Models::IcarusAction&);
void commitAction(); void commitAction();
enum class RetrieveTypes enum class RetrieveTypes
{ {
songs songs
}; };
private: // Used for parsing songs from the metadata file
class Album
{
public:
Album() = default;
void printInfo();
std::string album;
std::string albumArtist;
std::string genre;
int year;
int trackCount;
int discCount;
std::vector<Models::Song> songs;
};
private:
enum class ActionValues; enum class ActionValues;
std::map<std::string, ActionValues> mapActions() noexcept; std::map<std::string, ActionValues> mapActions() noexcept;
Models::Token parseToken(Models::API);
void deleteSong(); void deleteSong();
void downloadSong(); void downloadSong();
void retrieveObjects(); void retrieveObjects();
void uploadSong(); void uploadSong();
Models::Token parseToken(Models::API);
// Uploads a single song. The song is constructed from a metadata file that contains
// information about the album the song is from. Also, the cover art of the song must
// be present.
//
// Expects
// * Song - mp3 file path
// * TrackID - track number to chose from when retrieving metadata. "1" and "1:1" are similar
// * Metadata - Source file containing metadata of the song
// * Cover art - path to image cover art
void uploadSongWithMetadata();
// Expects the song path, trackID, metadata file path, and cover path
void singTargetUpload(const std::string &songPath, const std::string &trackID,
const std::string &metaPath, const std::string &coverPath);
// Expects the source directory that contains songs, a metadata file, and cover image
// Disc and Track is retrieved from the filename if the filename conforms to a standard.
// If not, then the disc and track will default to 1
//
// Standards
// * track01.mp3 - Disc 1, Track 1
// * track05d02.mp3 - Disc 2, Track 5
void multiTargetUpload(const std::string &sourcePath);
// Standards
// * track01.mp3 - Disc 1, Track 1
// * track05d02.mp3 - Disc 2, Track 5
template<typename Song, typename Str>
void initializeDiscAndTrack(Song &song)
{
auto disc = 1;
auto track = 1;
// If 1 go with first standard, if 2 go with the second, if 0 then will default to 1 for disc and track
auto mode = 0;
const Str &songPath = song.songPath;
auto trd = song.songPath.find("trackd");
auto tr = song.songPath.find("track");
if (tr != Str::npos)
{
mode = 1;
}
if (trd != Str::npos)
{
mode = 2;
}
auto dl = [](char c, char t){ return c == t; };
auto d = Utilities::Checks::itemIterInContainer<char, Str>(songPath, 'd', dl);
auto k = Utilities::Checks::itemIterInContainer<char, Str>(songPath, 'k', dl);
auto dot = Utilities::Checks::itemIterInContainer<char, Str>(songPath, '.', dl);
switch(mode)
{
case 1:
{
if (k != songPath.end() && dot != songPath.end())
{
auto tStr = std::string(++k, dot);
std::cout << "TStr: " << tStr<<"\n";
if (Utilities::Checks::isNumber(tStr))
{
track = std::atoi(tStr.c_str());
}
}
break;
}
case 2:
{
if (k != songPath.end() && dot != songPath.end() && d != songPath.end())
{
auto tStr = std::string(++k, d);
auto dStr = std::string(++d, dot);
std::cout<<"DStr: "<<dStr<<" TStr: " << tStr<<"\n";
if (Utilities::Checks::isNumber(tStr))
{
track = std::atoi(tStr.c_str());
}
else if (Utilities::Checks::isNumber(dStr))
{
disc = std::atoi(dStr.c_str());
}
}
break;
}
}
song.disc = disc;
song.track = track;
}
template<typename Song, typename Str>
void parseDiscAndTrack(Song &song, const Str &trackID)
{
auto sep = [](char c, char t) { return c == t; };
auto separator = Utilities::Checks::itemIterInContainer<char, Str>(trackID, ':', sep);
if (separator != trackID.end())
{
auto dStr = Str(trackID.begin(), separator);
auto tStr = Str(++separator, trackID.end());
song.disc = std::atoi(dStr.c_str());
song.track = std::atoi(tStr.c_str());
}
else
{
auto isNumber = Utilities::Checks::isNumber(trackID);
if (isNumber)
{
song.track = std::atoi(trackID.c_str());
}
}
}
// Checks for the no confirm flag. Used when uploading songs from a directory
bool checkForNoConfirm()
{
for (const auto &arg: this->icaAction.flags)
{
if (arg.flag.compare("-nc") == 0)
{
return true;
}
}
return false;
}
Album retrieveMetadata(const std::string_view path);
std::string retrieveFileContent(const std::string_view path);
enum class ActionValues enum class ActionValues
{ {
deleteAct, deleteAct,
downloadAct, downloadAct,
retrieveAct, retrieveAct,
uploadAct uploadAct,
UPLOAD_SONG_WITH_METADATA // Uploads the song with metadata, including cover art
}; };
Models::IcarusAction icaAction; Models::IcarusAction icaAction;
};
};
} }
#endif #endif
+7 -5
View File
@@ -5,9 +5,10 @@
namespace Managers namespace Managers
{ {
class FileManager
{ class FileManager
public: {
public:
FileManager(); FileManager();
FileManager(std::string); FileManager(std::string);
@@ -16,14 +17,15 @@ namespace Managers
char* retrieveFileBuffer() const; char* retrieveFileBuffer() const;
int retrieveFileBufferLength() const; int retrieveFileBufferLength() const;
private: private:
void readFile(); void readFile();
std::string filePath; std::string filePath;
char* fileBuffer; char* fileBuffer;
bool fileRead; bool fileRead;
int fileBufferLength; int fileBufferLength;
}; };
} }
#endif #endif
+7 -5
View File
@@ -7,17 +7,19 @@
namespace Managers namespace Managers
{ {
class TokenManager
{ class TokenManager
public: {
public:
TokenManager(const Models::User&); TokenManager(const Models::User&);
TokenManager(const Models::User&, Models::API&); TokenManager(const Models::User&, Models::API&);
Models::Token requestToken(); Models::Token requestToken();
private: private:
Models::API api; Models::API api;
Models::User user; Models::User user;
}; };
} }
#endif #endif
+7 -5
View File
@@ -8,19 +8,21 @@
namespace Managers namespace Managers
{ {
class UserManager
{ class UserManager
public: {
public:
UserManager(Models::User); UserManager(Models::User);
UserManager(const Models::IcarusAction); UserManager(const Models::IcarusAction);
Models::User retrieveUser() const; Models::User retrieveUser() const;
private: private:
void parseUserFromActions(); void parseUserFromActions();
Models::User user; Models::User user;
Models::IcarusAction icaAction; Models::IcarusAction icaAction;
}; };
} }
#endif #endif
+6 -3
View File
@@ -5,12 +5,15 @@
namespace Models namespace Models
{ {
struct API
{ class API
{
public:
std::string url; std::string url;
std::string endpoint; std::string endpoint;
std::string version; std::string version;
}; };
} }
#endif #endif
+6 -3
View File
@@ -5,11 +5,14 @@
namespace Models namespace Models
{ {
struct Flags
{ class Flags
{
public:
std::string flag; std::string flag;
std::string value; std::string value;
}; };
} }
#endif #endif
+37 -2
View File
@@ -2,17 +2,52 @@
#define ICARUSACTION_H_ #define ICARUSACTION_H_
#include<string> #include<string>
#include<algorithm>
#include<string_view>
#include<vector> #include<vector>
#include<iostream>
#include"Flags.h" #include"Flags.h"
namespace Models namespace Models
{ {
struct IcarusAction
class IcarusAction
{
public:
std::string retrieveFlagValue(const std::string_view flag)
{ {
std::string value;
const auto fg = std::find_if(flags.begin(), flags.end(), [&](Flags f)
{
return f.flag.compare(flag) == 0 ? true : false;
});
if (fg != flags.end())
{
value.assign(fg->value);
}
return value;
}
void print_action_and_flags() noexcept
{
std::cout<<"Action: "<<this->action<<"\n";
std::cout<<"Flag count: "<<this->flags.size()<<"\n";
for (const auto &flag : this->flags)
{
std::cout<<"flag "<<flag.flag<<" value "<<flag.value<<"\n";
}
std::cout<<"\n";
}
std::string action; std::string action;
std::vector<Flags> flags; std::vector<Flags> flags;
}; };
} }
#endif #endif
+69 -3
View File
@@ -1,13 +1,66 @@
#ifndef SONG_H_ #ifndef SONG_H_
#define SONG_H_ #define SONG_H_
#include<string> #include <string>
#include <iostream>
#include <sstream>
namespace Models namespace Models
{ {
struct Song
class Song
{
public:
Song() = default;
void printInfo()
{ {
std::cout<<"Title: "<<this->title<<"\n";
std::cout<<"\n";
}
std::string song_path() noexcept
{
std::stringstream buffer;
buffer << this->directory;
const auto count = this->directory.size();
if (this->directory.at(count - 1) != '/' || this->directory.at(count - 1) != '\\')
{
buffer << "/";
}
buffer << this->filename;
return buffer.str();
}
int generate_filename_from_track()
{
auto result = 0;
std::stringstream buffer;
buffer << "track";
// NOTE: Multiple discs in one directory is not being addressed
if (this->track < 10)
{
buffer << "0";
}
buffer << this->track << ".mp3";
this->filename.assign(buffer.str());
return result;
}
std::string toMetadataJson();
int id; int id;
std::string title; std::string title;
std::string artist; std::string artist;
@@ -16,9 +69,22 @@ namespace Models
int year; int year;
int duration; int duration;
int track; int track;
int disc;
std::string data; std::string data;
[[deprecated("Use song_path() function instead")]]
std::string songPath; std::string songPath;
}; std::string filename;
std::string directory;
};
class CoverArt
{
public:
int id;
std::string title;
std::string path;
};
} }
#endif #endif
+5 -3
View File
@@ -5,12 +5,14 @@
namespace Models namespace Models
{ {
struct Token
{ struct Token
{
std::string accessToken; std::string accessToken;
std::string tokenType; std::string tokenType;
int expiration; int expiration;
}; };
} }
#endif #endif
+5 -3
View File
@@ -6,11 +6,13 @@
namespace Models namespace Models
{ {
struct UploadForm
{ struct UploadForm
{
std::string url; std::string url;
std::string filePath; std::string filePath;
}; };
} }
#endif #endif
+5 -3
View File
@@ -5,11 +5,13 @@
namespace Models namespace Models
{ {
struct User
{ struct User
{
std::string username; std::string username;
std::string password; std::string password;
}; };
} }
#endif #endif
+7 -5
View File
@@ -6,18 +6,20 @@
namespace Parsers namespace Parsers
{ {
class APIParser
{ class APIParser
public: {
public:
APIParser(Models::IcarusAction); APIParser(Models::IcarusAction);
Models::API retrieveAPI() const; Models::API retrieveAPI() const;
private: private:
void parseAPI(); void parseAPI();
Models::API api; Models::API api;
Models::IcarusAction icaAct; Models::IcarusAction icaAct;
}; };
} }
#endif #endif
+7 -5
View File
@@ -9,15 +9,17 @@
namespace Syncers namespace Syncers
{ {
class Delete : SyncerBase
{ class Delete : SyncerBase
public: {
public:
Delete(Models::API); Delete(Models::API);
void deleteSong(const Models::Token, Models::Song); void deleteSong(const Models::Token, Models::Song);
private: private:
std::string retrieveUrl(Models::Song); std::string retrieveUrl(Models::Song);
}; };
} }
#endif #endif
+7 -5
View File
@@ -12,20 +12,22 @@
namespace Syncers namespace Syncers
{ {
class Download : SyncerBase
{ class Download : SyncerBase
public: {
public:
Download(); Download();
Download(Models::API); Download(Models::API);
Download(std::string); Download(std::string);
void downloadSong(const Models::Token token, Models::Song); void downloadSong(const Models::Token token, Models::Song);
private: private:
std::string retrieveUrl(Models::Song); std::string retrieveUrl(Models::Song);
std::string downloadFilePath; std::string downloadFilePath;
void saveSong(Models::Song&); void saveSong(Models::Song&);
}; };
} }
#endif #endif
+7 -5
View File
@@ -8,19 +8,21 @@
namespace Syncers namespace Syncers
{ {
class RetrieveRecords: public SyncerBase
{ class RetrieveRecords: public SyncerBase
public: {
public:
RetrieveRecords(); RetrieveRecords();
RetrieveRecords(Models::API, Models::Token); RetrieveRecords(Models::API, Models::Token);
void retrieve(Managers::CommitManager::RetrieveTypes); void retrieve(Managers::CommitManager::RetrieveTypes);
private: private:
void fetchSongs(); void fetchSongs();
Models::API api; Models::API api;
Models::Token token; Models::Token token;
}; };
} }
#endif #endif
+6 -4
View File
@@ -7,9 +7,10 @@
namespace Syncers namespace Syncers
{ {
class SyncerBase
{ class SyncerBase
protected: {
protected:
Models::API api; Models::API api;
const int OK = 200; const int OK = 200;
const int UNAUTHORIZED = 401; const int UNAUTHORIZED = 401;
@@ -21,7 +22,8 @@ namespace Syncers
UNAUTHORIZED = 401, UNAUTHORIZED = 401,
NOTFOUND = 404 NOTFOUND = 404
}; };
}; };
} }
#endif #endif
+26 -19
View File
@@ -1,36 +1,42 @@
#ifndef UPLOAD_H_ #ifndef UPLOAD_H_
#define UPLOAD_H_ #define UPLOAD_H_
#include<filesystem> #include <filesystem>
#include<string> #include <string>
#include<vector> #include <vector>
#include<nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include"Managers/FileManager.h" #include "Managers/CommitManager.h"
#include"Models/API.h" #include "Managers/FileManager.h"
#include"Models/Song.h" #include "Models/API.h"
#include"Models/Token.h" #include "Models/Song.h"
#include"Models/UploadForm.h" #include "Models/Token.h"
#include "Models/UploadForm.h"
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Syncers namespace Syncers
{ {
class Upload
{
public:
Upload();
Upload(Models::API);
Models::Song uploadSong(const Models::Token&, Models::Song&); class Upload
void uploadSongsFromDirectory(const Models::Token&, {
const std::string&, const bool, bool); public:
private: Upload() = default;
Upload(Models::API api, Models::Token token) : m_token(token), api(api)
{
this->api.endpoint = "song/data";
}
Models::Song uploadSong(Models::Song&);
void uploadSongsFromDirectory(const std::string&, const bool, bool);
void uploadSongWithMetadata(Managers::CommitManager::Album&, Models::Song&, Models::CoverArt&);
private:
Managers::FileManager fMgr; Managers::FileManager fMgr;
Models::API api; Models::API api;
Models::Song song; Models::Song song;
Models::Token m_token;
std::vector<Models::Song> retrieveAllSongsFromDirectory(const std::string&, std::vector<Models::Song> retrieveAllSongsFromDirectory(const std::string&,
bool); bool);
@@ -42,7 +48,8 @@ namespace Syncers
void printSongDetails(); void printSongDetails();
void printSongDetails(std::vector<Models::Song>&); void printSongDetails(std::vector<Models::Song>&);
void printJsonData(const nlohmann::json&); void printJsonData(const nlohmann::json&);
}; };
} }
#endif #endif
+8 -6
View File
@@ -13,22 +13,24 @@
namespace UI namespace UI
{ {
class AboutWindow: public QDialog, public CommonWindow
{ class AboutWindow: public QDialog, public CommonWindow
{
Q_OBJECT Q_OBJECT
public: public:
AboutWindow(QWidget* parent=0); AboutWindow(QWidget* parent=0);
~AboutWindow() = default; ~AboutWindow() = default;
private: private:
void connections(); void connections();
void setupWindow(); void setupWindow();
std::unique_ptr<QLabel> appName; std::unique_ptr<QLabel> appName;
private slots: private slots:
void closeWindow(); void closeWindow();
}; };
} }
#endif #endif
+6
View File
@@ -10,6 +10,9 @@
#include<QPushButton> #include<QPushButton>
namespace UI
{
class CommonWindow class CommonWindow
{ {
public: public:
@@ -24,4 +27,7 @@ protected:
std::unique_ptr<QVBoxLayout> subLayoutTwoQt; std::unique_ptr<QVBoxLayout> subLayoutTwoQt;
int windowHeight, windowWidth; int windowHeight, windowWidth;
}; };
}
#endif #endif
+9 -7
View File
@@ -22,13 +22,14 @@
namespace UI namespace UI
{ {
class MainWindow: public QMainWindow, public CommonWindow
{ class MainWindow: public QMainWindow, public CommonWindow
{
Q_OBJECT Q_OBJECT
public: public:
MainWindow(); MainWindow();
~MainWindow() = default; ~MainWindow() = default;
private: private:
void configureDownloadSection(); void configureDownloadSection();
void configureUploadSection(); void configureUploadSection();
void configureWindowDimensions(); void configureWindowDimensions();
@@ -70,13 +71,14 @@ namespace UI
std::unique_ptr<QAction> aboutApplicationQt; std::unique_ptr<QAction> aboutApplicationQt;
std::unique_ptr<AboutWindow> aboutWindow; std::unique_ptr<AboutWindow> aboutWindow;
signals: signals:
private slots: private slots:
void uploadSong(); void uploadSong();
void exitApplication(); void exitApplication();
void displaySoftwareInformation(); void displaySoftwareInformation();
void setCurrentIndex(int); void setCurrentIndex(int);
}; };
} }
#endif #endif
+68
View File
@@ -0,0 +1,68 @@
#ifndef CHECKS_H_
#define CHECKS_H_
#include<algorithm>
#include<cstdlib>
#include<ctype.h>
namespace Utilities
{
class Checks
{
public:
Checks() = delete;
static auto isNumber(const std::string &val)
{
return !val.empty() && std::find_if(val.begin(),
val.end(), [](char c)
{
return !std::isdigit(c);
}) == val.end();
}
// Note: Not implemented
template<typename Item, typename Container, typename Func>
static auto itemInContainer(const Container container, const Item item, Func func)
{
auto result = false;
auto i = std::find_if(container.begin(), container.end(), [&](Item i)
{
return func(item, i);
});
if (i != container.end())
{
result = true;
}
return result;
}
template<typename Item, typename Container, typename Func>
static auto itemIterInContainer(const Container &container, const Item &item, Func func)
{
auto result = false;
// std::cout<<container<<"\n";
auto ii = std::find_if(container.begin(), container.end(), [&](Item i)
{
// std::cout<<"iter "<<i<<" target "<<item<<"\n";
return func(i, item);
});
if (ii == container.end())
{
// std::cout<<item<<" not found in container\n";
ii = container.end();
}
return ii;
}
private:
};
}
#endif
+17 -7
View File
@@ -6,17 +6,27 @@
namespace Utilities namespace Utilities
{ {
class Conversions
{ class Conversions
public: {
public:
Conversions(); Conversions();
static void toLowerChar(char &c)
{
if (std::isalpha(c))
{
c = std::tolower(c);
}
}
void initializeValues(); void initializeValues();
template <typename T> template<typename T>
void printValue(T); void printValue(T val);
private: private:
}; };
} }
#endif #endif
-1
View File
@@ -1 +0,0 @@
cmake -H. -B_builds -DHUNTER_STATUS_DEBUG=ON -DCMAKE_BUILD_TYPE=DEBUG
-1
View File
@@ -1 +0,0 @@
cmake --build _builds --config Debug
-1
View File
@@ -1 +0,0 @@
cmake --build _builds --config Release
+7
View File
@@ -12,6 +12,11 @@ using std::string;
using Managers::ActionManager; using Managers::ActionManager;
using Managers::CommitManager; using Managers::CommitManager;
constexpr static auto IcarusDownloadManager_version()
{
return "v0.2.0";
}
void printHelp() void printHelp()
{ {
cout<<"icd [Action] [flag]\n\n"; cout<<"icd [Action] [flag]\n\n";
@@ -57,6 +62,8 @@ int main(int argc, char** argv)
ActionManager actMgr(argv, argc); ActionManager actMgr(argv, argc);
auto chosenAction = actMgr.retrieveIcarusAction(); auto chosenAction = actMgr.retrieveIcarusAction();
chosenAction.print_action_and_flags();
CommitManager commitMgr(chosenAction); CommitManager commitMgr(chosenAction);
commitMgr.commitAction(); commitMgr.commitAction();
+50 -77
View File
@@ -16,98 +16,70 @@ using Models::IcarusAction;
namespace Managers namespace Managers
{ {
#pragma
ActionManager::ActionManager(char **param, int paramCount) : #pragma region Constructors
ActionManager::ActionManager(char **param, int paramCount) :
params(std::move(param)), paramCount(paramCount) params(std::move(param)), paramCount(paramCount)
{ {
initialize(); initialize();
} }
#pragma Constructors #pragma endregion
#pragma #pragma region Functions
IcarusAction ActionManager::retrieveIcarusAction() const IcarusAction ActionManager::retrieveIcarusAction() const
{ {
IcarusAction icarusAction; IcarusAction icarusAction;
icarusAction.flags = flags; icarusAction.flags = flags;
icarusAction.action = action; icarusAction.action = action;
return icarusAction; return icarusAction;
} }
constexpr std::array<const char*, 12> ActionManager::supportedFlags() noexcept
{
constexpr std::array<const char*, 12> allFlags{"-u", "-p", "-t", "-h", "-s",
"-sd", "-sr", "-d", "-D", "-b", "-rt", "-nc"};
return allFlags; void ActionManager::initialize()
} {
bool ActionManager::isNumber(string_view val) noexcept
{
return !val.empty() && std::find_if(val.begin(),
val.end(), [](char c)
{
return !std::isdigit(c);
}) == val.end();
}
void ActionManager::initialize()
{
validateFlags(); validateFlags();
action = std::move(string{params[1]}); action = std::move(string{params[1]});
transform(action.begin(), action.end(), transform(action.begin(), action.end(),
action.begin(), ::tolower); action.begin(), ::tolower);
}
void ActionManager::validateFlags()
{
cout<<"Validating flags\n";
const auto flagVals = parsedFlags();
for (auto flag = flagVals.begin(); flag != flagVals.end(); ++flag)
{
Flags flg;
cout<<"Value: "<<*flag<<"\n";
if (isValidFlag<string>(*flag) && doesFlagHaveValue<string>(*flag))
{
cout<<"Flag has value\n";
flg.flag = *flag;
flg.value = *(++flag);
} }
void ActionManager::validateFlags() else if (isValidFlag<string>(*flag))
{ {
cout<<"Validating flags"<<endl; cout<<"Flag does not have a value\n";
flg.flag = *flag;
auto flagVals = parsedFlags();
Flags flg{};
auto allSupportedFlags = supportedFlags();
for (auto flag : flagVals)
{
if (flag.compare("-nc") == 0)
{
flg.flag = flag;
flags.push_back(flg);
continue;
}
if (flag.size() > 3 || isNumber(flag))
{
flg.value = flag;
//cout<<"flag value "<<flg.value<<endl;
flags.push_back(flg);
flg = Flags{};
continue;
}
if (std::any_of(allSupportedFlags.begin(), allSupportedFlags.end(),
[&](const char *val)
{
return !flag.compare(val);
}))
{
//cout<<"flag "<<flag<<endl;
flg.flag = flag;
} }
else else
{ {
cout<<"Flag is not valid"<<endl; cout<<"Flag "<<*flag<<" is not valid"<<endl;
exit(1); exit(1);
} }
}
}
vector<string> ActionManager::parsedFlags() flags.emplace_back(std::move(flg));
{ }
}
vector<string> ActionManager::parsedFlags()
{
auto parsed = vector<string>(); auto parsed = vector<string>();
for (auto i = 2; i < paramCount; ++i) for (auto i = 2; i < paramCount; ++i)
@@ -117,11 +89,11 @@ namespace Managers
} }
return parsed; return parsed;
} }
#pragma #pragma region Testing
void ActionManager::printAction() noexcept void ActionManager::printAction() noexcept
{ {
if (action.empty()) if (action.empty())
{ {
printf("Action is empty\n"); printf("Action is empty\n");
@@ -130,16 +102,17 @@ namespace Managers
{ {
cout<<"Action is "<<action<<endl; cout<<"Action is "<<action<<endl;
} }
} }
void ActionManager::printFlags() noexcept void ActionManager::printFlags() noexcept
{ {
cout<<"\nPrinting flags..."<<endl; cout<<"\nPrinting flags..."<<endl;
for (auto flag: flags) for (auto flag: flags)
{ {
cout<<"flag "<<flag.flag<<endl; cout<<"flag "<<flag.flag<<endl;
cout<<"value "<<flag.value<<endl; cout<<"value "<<flag.value<<endl;
} }
} }
#pragma Testing #pragma endregion
#pragma Functions #pragma endregion
} }
+265 -49
View File
@@ -1,18 +1,23 @@
#include"Managers/CommitManager.h" #include"Managers/CommitManager.h"
#include<iostream> #include <iostream>
#include <fstream>
#include <sstream>
#include <filesystem>
#include"Models/API.h" #include "nlohmann/json.hpp"
#include"Models/Song.h"
#include"Models/Token.h"
#include"Parsers/APIParser.h"
#include"Syncers/Delete.h"
#include"Syncers/Download.h"
#include"Syncers/RetrieveRecords.h"
#include"Syncers/Upload.h"
#include"Managers/TokenManager.h" #include "Models/API.h"
#include"Managers/UserManager.h" #include "Models/Song.h"
#include "Models/Token.h"
#include "Parsers/APIParser.h"
#include "Syncers/Delete.h"
#include "Syncers/Download.h"
#include "Syncers/RetrieveRecords.h"
#include "Syncers/Upload.h"
#include "Managers/TokenManager.h"
#include "Managers/UserManager.h"
using std::cout; using std::cout;
using std::endl; using std::endl;
@@ -31,19 +36,23 @@ using Syncers::Download;
using Syncers::RetrieveRecords; using Syncers::RetrieveRecords;
using Syncers::Upload; using Syncers::Upload;
namespace filesystem = std::filesystem;
namespace Managers namespace Managers
{ {
#pragma
CommitManager::CommitManager(IcarusAction& icaAct) : icaAction(std::move(icaAct)) #pragma region Constructors
{ } CommitManager::CommitManager(IcarusAction& icaAct) : icaAction(std::move(icaAct))
#pragma Constructors { }
#pragma endregion
#pragma #pragma region Functions
void CommitManager::commitAction() void CommitManager::commitAction()
{ {
auto action = icaAction.action; auto action = icaAction.action;
cout<<"Commiting "<<action<<" action"<<endl; cout<<"Commiting "<<action<<" action"<<endl;
switch (mapActions()[action]) switch (mapActions()[action])
{ {
case ActionValues::deleteAct: case ActionValues::deleteAct:
@@ -58,41 +67,49 @@ namespace Managers
case ActionValues::uploadAct: case ActionValues::uploadAct:
uploadSong(); uploadSong();
break; break;
case ActionValues::UPLOAD_SONG_WITH_METADATA:
uploadSongWithMetadata();
break;
default: default:
break; break;
} }
} }
enum class ActionValues;
std::map<std::string, CommitManager::ActionValues>
std::map<std::string, CommitManager::ActionValues>
CommitManager::mapActions() noexcept CommitManager::mapActions() noexcept
{ {
const std::map<std::string, ActionValues> actions{ const std::map<std::string, ActionValues> actions{
{"delete", ActionValues::deleteAct}, {"delete", ActionValues::deleteAct},
{"download", ActionValues::downloadAct}, {"download", ActionValues::downloadAct},
{"retrieve", ActionValues::retrieveAct}, {"retrieve", ActionValues::retrieveAct},
{"upload", ActionValues::uploadAct} {"upload", ActionValues::uploadAct},
{"upload-meta", ActionValues::UPLOAD_SONG_WITH_METADATA}
}; };
return actions; return actions;
} }
Token CommitManager::parseToken(API api)
{
cout<<"fetching token"<<endl; Token CommitManager::parseToken(API api)
{
cout<<"fetching token\n";
UserManager usrMgr{icaAction}; UserManager usrMgr{icaAction};
auto user = usrMgr.retrieveUser(); auto user = usrMgr.retrieveUser();
TokenManager tk{user, api}; TokenManager tk{user, api};
return tk.requestToken(); return tk.requestToken();
} }
void CommitManager::deleteSong() void CommitManager::deleteSong()
{ {
APIParser apiPrs{icaAction}; APIParser apiPrs{icaAction};
auto api = apiPrs.retrieveAPI(); auto api = apiPrs.retrieveAPI();
@@ -114,9 +131,9 @@ namespace Managers
Delete del{api}; Delete del{api};
cout<<"Deleting song..."<<endl; cout<<"Deleting song..."<<endl;
del.deleteSong(token, song); del.deleteSong(token, song);
} }
void CommitManager::downloadSong() void CommitManager::downloadSong()
{ {
cout<<"Starting downloading process..."<<endl; cout<<"Starting downloading process..."<<endl;
APIParser apiPrs{icaAction}; APIParser apiPrs{icaAction};
@@ -144,9 +161,9 @@ namespace Managers
Download dnld{api}; Download dnld{api};
cout<<"downloading song"<<endl; cout<<"downloading song"<<endl;
dnld.downloadSong(token, song); dnld.downloadSong(token, song);
} }
void CommitManager::retrieveObjects() void CommitManager::retrieveObjects()
{ {
cout<<"Starting retrieve process..."<<endl; cout<<"Starting retrieve process..."<<endl;
APIParser apiPrs{icaAction}; APIParser apiPrs{icaAction};
@@ -173,12 +190,13 @@ namespace Managers
RetrieveRecords songs{api, token}; RetrieveRecords songs{api, token};
songs.retrieve(retrieveType); songs.retrieve(retrieveType);
} }
void CommitManager::uploadSong()
{ void CommitManager::uploadSong()
{
auto uploadSingleSong = true; auto uploadSingleSong = true;
auto recursiveDirectory = false; auto recursiveDirectory = false;
auto noConfirm = false; const auto noConfirm = checkForNoConfirm();
string songDirectory; string songDirectory;
APIParser apiPrs{icaAction}; APIParser apiPrs{icaAction};
auto api = apiPrs.retrieveAPI(); auto api = apiPrs.retrieveAPI();
@@ -206,24 +224,222 @@ namespace Managers
songDirectory = value; songDirectory = value;
uploadSingleSong = false; uploadSingleSong = false;
recursiveDirectory = true; recursiveDirectory = true;
}
else if (flag.compare("-nc") == 0)
{
noConfirm = true;
} }
} }
Upload upld{api}; Upload upld{api, token};
if (uploadSingleSong) if (uploadSingleSong)
{ {
cout<<"Uploading song..."<<endl; cout<<"Uploading song..."<<endl;
upld.uploadSong(token, song); upld.uploadSong(song);
} }
else else
{ {
cout<<"Uploading songs from " << songDirectory << endl; cout<<"Uploading songs from " << songDirectory << endl;
upld.uploadSongsFromDirectory(token, songDirectory, noConfirm, recursiveDirectory); upld.uploadSongsFromDirectory(songDirectory, noConfirm, recursiveDirectory);
} }
} }
#pragma Functions
void CommitManager::uploadSongWithMetadata()
{
cout<<"Uploading single song with metadata\n\n";
// Either the set of "-s", "-m", "-ca", "-t" flags or "-smca" must exist with values
// in order to be valid but not both
const auto songPath = this->icaAction.retrieveFlagValue("-s");
const auto metadataPath = this->icaAction.retrieveFlagValue("-m");
const auto coverPath = this->icaAction.retrieveFlagValue("-ca");
const auto trackID = this->icaAction.retrieveFlagValue("-t");
const auto singleTarget = !songPath.empty() && !metadataPath.empty() &&
!coverPath.empty() && !trackID.empty() ? true : false;
const auto uni = this->icaAction.retrieveFlagValue("-smca");
const auto multiTarget = !uni.empty() ? true : false;
if (singleTarget && multiTarget)
{
cout<<"Cannot upload from source and directory\n";
return;
}
cout<<"Song path: "<<songPath<<"\n";
cout<<"TrackID: "<<trackID<<"\n";
cout<<"Metadata path: "<<metadataPath<<"\n";
cout<<"Cover Art path: "<<coverPath<<"\n";
if (singleTarget)
{
singTargetUpload(songPath, trackID, metadataPath, coverPath);
}
else if (multiTarget)
{
multiTargetUpload(uni);
}
}
void CommitManager::singTargetUpload(const std::string &songPath, const std::string &trackID,
const std::string &metaPath, const std::string &coverPath)
{
APIParser apiPrs(icaAction);
auto api = apiPrs.retrieveAPI();
const auto token = parseToken(api);
auto album = retrieveMetadata(metaPath);
album.printInfo();
Song song;
song.track = 1;
song.disc = 1;
cout<<"TrackID: "<<trackID<<"\n";
parseDiscAndTrack<Song, std::string>(song, trackID);
auto c = [](const Song &songA, const Song &songB) { return songA.track == songB.track && songA.disc == songB.disc; };
auto sng = Utilities::Checks::itemIterInContainer<Song, std::vector<Song>>(album.songs, song, c);
if (sng == album.songs.end())
{
cout<<"Not found with disc "<<song.disc<<" track "<<song.track<<"\n";
std::exit(-1);
}
song = *sng;
const auto p = fs::path(songPath);
song.directory = p.parent_path.string();
song.generate_filename_from_track();
Models::CoverArt cover;
cover.title = song.title;
cover.path = coverPath;
Upload up(api, token);
up.uploadSongWithMetadata(album, song, cover);
}
void CommitManager::multiTargetUpload(const std::string &sourcePath)
{
APIParser apiPrs(icaAction);
auto api = apiPrs.retrieveAPI();
const auto token = parseToken(api);
if (!fs::is_directory(sourcePath))
{
cout<<sourcePath<<" is not a directory\n";
std::exit(-1);
}
std::vector<Song> songs;
Models::CoverArt cover;
string metadataPath;
for (auto &p: fs::directory_iterator(sourcePath))
{
const auto &pp = p.path();
const auto stem = pp.stem();
const auto file = pp.filename();
const auto extension = pp.extension();
cout<<"Stem "<<stem<<" Extension "<<extension<<"\n";
if (extension.compare(".mp3") == 0)
{
Song song;
song.songPath = pp.string();
initializeDiscAndTrack<Song, std::string>(song);
songs.emplace_back(std::move(song));
}
else if (extension.compare(".jpg") == 0 || extension.compare(".png") == 0)
{
cover.path.assign(pp.string());
}
else if (extension.compare(".json") == 0)
{
metadataPath.assign(pp.string());
}
}
auto album = retrieveMetadata(metadataPath);
songs.clear();
songs.assign(album.songs.begin(), album.songs.end());
Upload up(api, token);
for (auto &song : songs)
{
up.uploadSongWithMetadata(album, song, cover);
}
}
#pragma region private
CommitManager::Album CommitManager::retrieveMetadata(const std::string_view path)
{
CommitManager::Album album;
const auto fileContent = retrieveFileContent(path);
cout<<"Parsing...\n";
auto serialized = nlohmann::json::parse(fileContent);
cout<<"Parsed\n";
album.album = serialized["album"].get<std::string>();
album.albumArtist = serialized["album_artist"].get<std::string>();
album.genre = serialized["genre"].get<std::string>();
album.year = serialized["year"].get<int>();
album.trackCount = serialized["track_count"].get<int>();
album.discCount = serialized["disc_count"].get<int>();
album.songs.reserve(album.trackCount);
for (auto &j : serialized["tracks"])
{
Song song;
song.title = j["title"].get<std::string>();
song.track = j["track"].get<int>();
song.disc = j["disc"].get<int>();
song.artist = j["artist"].get<std::string>();
song.album = album.album;
song.year = album.year;
song.genre = album.genre;
song.generate_filename_from_track();
const auto p = fs::path(path);
song.directory = p.parent_path().string();
album.songs.push_back(song);
}
return album;
}
string CommitManager::retrieveFileContent(const std::string_view path)
{
string path_str(path);
string value;
std::stringstream buffer;
std::fstream file(path_str, std::ios::in);
buffer<<file.rdbuf();
file.close();
value.assign(buffer.str());
return value;
}
#pragma endregion
void CommitManager::Album::printInfo()
{
std::cout<<"Album: "<<this->album<<"\n";
std::cout<<"Album Artist: "<<this->albumArtist<<"\n";
std::cout<<"Genre: "<<this->genre<<"\n";
std::cout<<"Year: "<<this->year<<"\n";
std::cout<<"Track count: "<<this->trackCount<<"\n";
std::cout<<"Disc count: "<<this->discCount<<"\n";
std::cout<<"\n";
}
#pragma region Functions
} }
+28 -21
View File
@@ -11,26 +11,30 @@ using std::string;
namespace Managers namespace Managers
{ {
FileManager::FileManager() {}
FileManager::FileManager(string filePath) #pragma region Constructors
{ FileManager::FileManager() {}
FileManager::FileManager(string filePath)
{
this->filePath = filePath; this->filePath = filePath;
readFile(); readFile();
} }
#pragma endregion
void FileManager::saveFile(string newFilePath) #pragma region Functions
{ void FileManager::saveFile(string newFilePath)
{
if (!fileRead) if (!fileRead)
readFile(); readFile();
ofstream of{newFilePath, ofstream::binary}; ofstream of{newFilePath, ofstream::binary};
of.write(fileBuffer, fileBufferLength); of.write(fileBuffer, fileBufferLength);
of.close(); of.close();
} }
void FileManager::readFile() void FileManager::readFile()
{ {
ifstream is{filePath, ifstream::binary}; ifstream is{filePath, ifstream::binary};
if (is) if (is)
{ {
@@ -51,16 +55,19 @@ namespace Managers
is.close(); is.close();
fileRead = true; fileRead = true;
} }
} }
void FileManager::modifyFilePath(string filePath) void FileManager::modifyFilePath(string filePath)
{ {
this->filePath = filePath; this->filePath = filePath;
} }
char* FileManager::retrieveFileBuffer() const char* FileManager::retrieveFileBuffer() const
{ {
return fileBuffer; return fileBuffer;
} }
int FileManager::retrieveFileBufferLength() const { return fileBufferLength; } int FileManager::retrieveFileBufferLength() const { return fileBufferLength; }
#pragma endregion
} }
+15 -13
View File
@@ -17,24 +17,25 @@ using Models::User;
namespace Managers namespace Managers
{ {
#pragma
TokenManager::TokenManager(const User& user) #pragma region Constructors
{ TokenManager::TokenManager(const User& user)
{
this->user = user; this->user = user;
} }
TokenManager::TokenManager(const User& user, API& api) TokenManager::TokenManager(const User& user, API& api)
{ {
this->user = user; this->user = user;
this->api = api; this->api = api;
this->api.endpoint = "api/" + api.version this->api.endpoint = "api/" + api.version
+ "/login"; + "/login";
} }
#pragma Constructors #pragma endregion
#pragma #pragma region Functions
Token TokenManager::requestToken() Token TokenManager::requestToken()
{ {
Token token{}; Token token{};
json usrObj; json usrObj;
@@ -55,6 +56,7 @@ namespace Managers
cout<<"status code "<<r.status_code<<endl; cout<<"status code "<<r.status_code<<endl;
return token; return token;
} }
#pragma Functions #pragma endregion
} }
+18 -16
View File
@@ -12,28 +12,29 @@ using Models::User;
namespace Managers namespace Managers
{ {
#pragma
UserManager::UserManager(User user) #pragma region Constructors
{ UserManager::UserManager(User user)
{
this->user = user; this->user = user;
} }
UserManager::UserManager(const IcarusAction icaAct) UserManager::UserManager(const IcarusAction icaAct)
{ {
this->icaAction = icaAct; this->icaAction = icaAct;
this->user = User{}; this->user = User{};
parseUserFromActions(); parseUserFromActions();
} }
#pragma Constructors #pragma endregion
#pragma #pragma region Functions
User UserManager::retrieveUser() const User UserManager::retrieveUser() const
{ {
return user; return user;
} }
void UserManager::parseUserFromActions() void UserManager::parseUserFromActions()
{ {
auto args = icaAction.flags; auto args = icaAction.flags;
for (auto arg : args) for (auto arg : args)
@@ -48,6 +49,7 @@ namespace Managers
user.password = arg.value; user.password = arg.value;
} }
} }
} }
#pragma Functions #pragma endregion
} }
+22
View File
@@ -0,0 +1,22 @@
#include "Models/Song.h"
#include "nlohmann/json.hpp"
using std::string;
namespace Models
{
string Song::toMetadataJson()
{
nlohmann::json s;
s["title"] = this->title;
s["artist"] = this->artist;
s["album"] = this->album;
s["genre"] = this->genre;
s["year"] = this->year;
s["track"] = this->track;
s["disc"] = this->disc;
return s.dump();
}
}
+18 -17
View File
@@ -1,6 +1,6 @@
#include"Parsers/APIParser.h" #include "Parsers/APIParser.h"
#include<iostream> #include <iostream>
using std::cout; using std::cout;
using std::endl; using std::endl;
@@ -10,25 +10,26 @@ using Models::IcarusAction;
namespace Parsers namespace Parsers
{ {
#pragma
APIParser::APIParser(IcarusAction icaAct) : icaAct(icaAct) #pragma region Constructors
{ APIParser::APIParser(IcarusAction icaAct) : icaAct(icaAct)
{
api = API{}; api = API{};
parseAPI(); parseAPI();
} }
#pragma endregion #pragma endregion
#pragma #pragma region Functions
API APIParser::retrieveAPI() const API APIParser::retrieveAPI() const
{ {
return api; return api;
} }
void APIParser::parseAPI() void APIParser::parseAPI()
{ {
auto flags = icaAct.flags; auto flags = icaAct.flags;
cout<<"Parsing api"<<endl; cout << "Parsing api" << endl;
for (auto i =0; i < flags.size(); ++i) for (auto i =0; i < flags.size(); ++i)
{ {
@@ -40,13 +41,13 @@ namespace Parsers
api.url = (value[value.size()-1] == '/') ? value : value + "/"; api.url = (value[value.size()-1] == '/') ? value : value + "/";
break; break;
} }
} }
// TODO: For now I will hard code // TODO: For now I will hard code
// the api version since I am only // the api version since I am only
// on version 1 // on version 1
api.version = "v1"; api.version = "v1";
} }
#pragma functions #pragma endregion
} }
+19 -17
View File
@@ -1,9 +1,9 @@
#include"Syncers/Delete.h" #include "Syncers/Delete.h"
#include<exception> #include <exception>
#include<iostream> #include <iostream>
#include<cpr/cpr.h> #include <cpr/cpr.h>
using std::cout; using std::cout;
using std::endl; using std::endl;
@@ -16,18 +16,19 @@ using Models::Token;
namespace Syncers namespace Syncers
{ {
#pragma
Delete::Delete(API api) #pragma region Constructors
{ Delete::Delete(API api)
{
this->api = api; this->api = api;
this->api.endpoint = "song/data"; this->api.endpoint = "song/data";
} }
#pragma Constructors #pragma endregion
#pragma #pragma region Functions
void Delete::deleteSong(const Token token, Song song) void Delete::deleteSong(const Token token, Song song)
{ {
try try
{ {
auto url = retrieveUrl(song); auto url = retrieveUrl(song);
@@ -46,10 +47,10 @@ namespace Syncers
cout<<msg<<endl; cout<<msg<<endl;
} }
cout<<"Finished"<<endl; cout<<"Finished"<<endl;
} }
string Delete::retrieveUrl(Song song) string Delete::retrieveUrl(Song song)
{ {
string url{api.url + "api/" + api.version + "/" + string url{api.url + "api/" + api.version + "/" +
api.endpoint + "/"}; api.endpoint + "/"};
@@ -57,6 +58,7 @@ namespace Syncers
cout<<"url "<<url<<endl; cout<<"url "<<url<<endl;
return url; return url;
} }
#pragma Functions #pragma endregion
} }
+27 -25
View File
@@ -1,10 +1,10 @@
#include"Syncers/Download.h" #include "Syncers/Download.h"
#include<exception> #include <exception>
#include<iostream> #include <iostream>
#include<fstream> #include <fstream>
#include<cpr/cpr.h> #include <cpr/cpr.h>
using std::cout; using std::cout;
using std::endl; using std::endl;
@@ -18,23 +18,24 @@ using Models::Token;
namespace Syncers namespace Syncers
{ {
#pragma
Download::Download() { } #pragma region Constructors
Download::Download(API api) Download::Download() { }
{ Download::Download(API api)
{
this->api = api; this->api = api;
this->api.endpoint = "song/data"; this->api.endpoint = "song/data";
} }
Download::Download(string filePath) Download::Download(string filePath)
{ {
downloadFilePath = filePath; downloadFilePath = filePath;
} }
#pragma Constructors #pragma endregion
#pragma #pragma region Functions
void Download::downloadSong(const Token token, Song song) void Download::downloadSong(const Token token, Song song)
{ {
try try
{ {
string url = retrieveUrl(song); string url = retrieveUrl(song);
@@ -63,10 +64,10 @@ namespace Syncers
auto msg = e.what(); auto msg = e.what();
cout<<msg<<endl; cout<<msg<<endl;
} }
} }
string Download::retrieveUrl(Song song) string Download::retrieveUrl(Song song)
{ {
string url{api.url + "api/" + api.version + "/" + string url{api.url + "api/" + api.version + "/" +
api.endpoint + "/"}; api.endpoint + "/"};
@@ -74,10 +75,10 @@ namespace Syncers
cout<<"url "<<url<<endl; cout<<"url "<<url<<endl;
return url; return url;
} }
void Download::saveSong(Song& song) void Download::saveSong(Song& song)
{ {
cout<<"\nSaving song to: "<<song.songPath<<endl; cout<<"\nSaving song to: "<<song.songPath<<endl;
int bufferLength = song.data.length(); int bufferLength = song.data.length();
const char *data = song.data.c_str(); const char *data = song.data.c_str();
@@ -86,6 +87,7 @@ namespace Syncers
ofstream saveSong{song.songPath, std::ios::binary}; ofstream saveSong{song.songPath, std::ios::binary};
saveSong.write(data, bufferLength); saveSong.write(data, bufferLength);
saveSong.close(); saveSong.close();
} }
#pragma Functions #pragma endregion
} }
+13 -8
View File
@@ -20,12 +20,15 @@ using Utilities::Conversions;
namespace Syncers namespace Syncers
{ {
RetrieveRecords::RetrieveRecords() { } #pragma region Constructors
RetrieveRecords::RetrieveRecords(API api, Token token) RetrieveRecords::RetrieveRecords() { }
RetrieveRecords::RetrieveRecords(API api, Token token)
: token(token), api(api) { } : token(token), api(api) { }
#pragma endregion
void RetrieveRecords::retrieve(CommitManager::RetrieveTypes type) #pragma region Functions
{ void RetrieveRecords::retrieve(CommitManager::RetrieveTypes type)
{
switch (type) switch (type)
{ {
case CommitManager::RetrieveTypes::songs: case CommitManager::RetrieveTypes::songs:
@@ -34,9 +37,9 @@ namespace Syncers
default: default:
break; break;
} }
} }
void RetrieveRecords::fetchSongs() void RetrieveRecords::fetchSongs()
{ {
cout<<"fetching songs"<<endl; cout<<"fetching songs"<<endl;
auto url = api.url + "api/" + api.version + "/" + "song"; auto url = api.url + "api/" + api.version + "/" + "song";
@@ -58,5 +61,7 @@ namespace Syncers
writeData.open("songs.json"); writeData.open("songs.json");
writeData<<songData.dump(4); writeData<<songData.dump(4);
writeData.close(); writeData.close();
} }
#pragma endregion
} }
+89 -62
View File
@@ -1,11 +1,11 @@
#include<iostream> #include <iostream>
#include<filesystem> #include <filesystem>
#include<exception> #include <exception>
#include<cpr/cpr.h> #include "cpr/cpr.h"
#include<nlohmann/json.hpp>
#include"Syncers/Upload.h" #include "Syncers/Upload.h"
#include "Utilities/Conversions.h"
using std::cout; using std::cout;
using std::cin; using std::cin;
@@ -24,22 +24,21 @@ using namespace cpr;
namespace Syncers namespace Syncers
{ {
Upload::Upload() { }
Upload::Upload(API api) : api(api) #pragma region Constructors
{ #pragma endregion
this->api.endpoint = "song/data";
}
Song Upload::uploadSong(const Models::Token& token, Song& song) #pragma region Functions
{ Song Upload::uploadSong(Song& song)
{
try try
{ {
auto url = retrieveUrl(); auto url = retrieveUrl();
cout<<"url "<<url<<endl; cout<<"url "<<url<<endl;
string auth{token.tokenType}; string auth{this->m_token.tokenType};
auth.append(" " + token.accessToken); auth.append(" " + this->m_token.accessToken);
auto r = cpr::Post(cpr::Url{url}, auto r = cpr::Post(cpr::Url{url},
cpr::Multipart{{"key", "small value"}, cpr::Multipart{{"key", "small value"},
{"file", cpr::File{song.songPath}}}, {"file", cpr::File{song.songPath}}},
@@ -68,12 +67,11 @@ namespace Syncers
} }
return song; return song;
} }
void Upload::uploadSongsFromDirectory(const Models::Token& token, void Upload::uploadSongsFromDirectory(const std::string& directory,
const std::string& directory,
const bool noConfirm, bool recursive = false) const bool noConfirm, bool recursive = false)
{ {
try try
{ {
auto songs = retrieveAllSongsFromDirectory(directory, recursive); auto songs = retrieveAllSongsFromDirectory(directory, recursive);
@@ -84,42 +82,79 @@ namespace Syncers
auto answer = 'a'; auto answer = 'a';
cout << "are you sure you want to upload " << songs.size() << " songs? [y/n]"; cout << "are you sure you want to upload " << songs.size() << " songs? [y/n]";
cin >> answer; cin >> answer;
Utilities::Conversions::toLowerChar(answer);
if (answer == 'y' || answer == 'Y') if (answer == 'y' || answer == 'Y')
{ {
confirmUpload = true; confirmUpload = true;
break; break;
} }
else if (answer == 'n' || answer == 'N')
{
confirmUpload = false;
break;
}
}
if (!confirmUpload)
{
cout << "exiting...\n";
std::exit(-1);
} }
cout << "uploading songs\n"; cout << "uploading songs\n";
for (auto& song: songs) for (auto& song: songs)
{ {
song = uploadSong(token, song); song = uploadSong(song);
} }
} }
catch (exception& e) catch (exception& e)
{ {
cout<<e.what()<<endl; cout<<e.what()<<endl;
} }
} }
std::vector<Song> Upload::retrieveAllSongsFromDirectory(const std::string& directory, void Upload::uploadSongWithMetadata(Managers::CommitManager::Album &album, Models::Song& song, Models::CoverArt &cover)
bool recursive) {
this->api.endpoint.assign("song/data/upload/with/data");
try
{ {
auto url = retrieveUrl();
cout << "url " << url << "\n";
string auth(this->m_token.tokenType);
auth.append(" " + this->m_token.accessToken);
nlohmann::json s;
s["title"] = song.title;
s["album"] = album.album;
s["album_artist"] = album.albumArtist;
s["artist"] = song.artist;
s["year"] = album.year;
s["genre"] = album.genre;
s["disc"] = song.disc;
s["track"] = song.track;
s["disc_count"] = album.discCount;
s["track_count"] = album.trackCount;
const auto meta = s.dump();
cout<<"\n\nMeta:\n"<<meta<<"\n";
cout << "Filepath: " << song.song_path() << "\n";
auto multipart = cpr::Multipart{{"cover", cpr::File{cover.path}},
{"metadata", meta},
{"file", cpr::File{song.song_path()}}};
auto r = cpr::Post(cpr::Url{url}, multipart,
cpr::Header{{"authorization", auth}}
);
cout << "status code: " << r.status_code<< std::endl;
cout << r.text << endl;
}
catch (exception &e)
{
auto msg = e.what();
cout<<"Error: "<<msg<<"\n";
}
}
std::vector<Song> Upload::retrieveAllSongsFromDirectory(const std::string& directory,
bool recursive)
{
std::vector<Song> allSongs; std::vector<Song> allSongs;
if (recursive) if (recursive)
{ {
for (auto p: fs::recursive_directory_iterator(directory)) for (auto p: fs::recursive_directory_iterator(directory))
@@ -140,20 +175,20 @@ namespace Syncers
} }
return allSongs; return allSongs;
} }
string Upload::retrieveUrl() string Upload::retrieveUrl()
{ {
const string url{api.url + "api/" + api.version + "/" + const string url{api.url + "api/" + api.version + "/" +
api.endpoint}; api.endpoint};
return url; return url;
} }
Song Upload::retrieveSongPath(fs::directory_entry& dirEntry) Song Upload::retrieveSongPath(fs::directory_entry& dirEntry)
{ {
constexpr auto mp3Ext = ".mp3"; constexpr auto mp3Ext = ".mp3";
Song song; Song song;
if (fs::is_regular_file(dirEntry.path())) if (fs::is_regular_file(dirEntry.path()))
@@ -167,23 +202,13 @@ namespace Syncers
} }
return song; return song;
} }
#pragma #pragma region Testing
void Upload::printSongDetails()
{ void Upload::printSongDetails(std::vector<Song>& songs)
cout<<"Song details: "<<endl; {
cout<<"Id: "<<song.id<<endl;
cout<<"Title: "<<song.title<<endl;
cout<<"Artist: "<<song.artist<<endl;
cout<<"Album: "<<song.album<<endl;
cout<<"Genre: "<<song.genre<<endl;
cout<<"Year: "<<song.year<<endl;
cout<<"Duration: "<<song.duration<<endl;
}
void Upload::printSongDetails(std::vector<Song>& songs)
{
for (auto& song: songs) for (auto& song: songs)
{ {
cout<<"Song details: "<<endl; cout<<"Song details: "<<endl;
@@ -196,9 +221,10 @@ namespace Syncers
cout<<"Duration: "<<song.duration<<endl; cout<<"Duration: "<<song.duration<<endl;
cout<<"Path: "<<song.songPath<<endl; cout<<"Path: "<<song.songPath<<endl;
} }
} }
void Upload::printJsonData(const json& obj)
{ void Upload::printJsonData(const json& obj)
{
cout<<endl<<endl<<"JSon data: "<<endl; cout<<endl<<endl<<"JSon data: "<<endl;
cout<<"id: "<<obj["id"]<<endl; cout<<"id: "<<obj["id"]<<endl;
cout<<"title: "<<obj["title"]<<endl; cout<<"title: "<<obj["title"]<<endl;
@@ -209,8 +235,9 @@ namespace Syncers
cout<<"duration: "<<obj["duration"]<<endl; cout<<"duration: "<<obj["duration"]<<endl;
cout<<"song_data: "<<obj["song_data"]<<endl; cout<<"song_data: "<<obj["song_data"]<<endl;
cout<<endl<<endl;; cout<<endl<<endl;
} }
#pragma Testing #pragma endregion
#pragma Functions #pragma endregion
} }
+21 -16
View File
@@ -1,17 +1,20 @@
#include"UI/AboutWindow.h" #include "UI/AboutWindow.h"
using std::unique_ptr; using std::unique_ptr;
namespace UI namespace UI
{ {
AboutWindow::AboutWindow(QWidget* parent): QDialog(parent) #pragma region Constructors
{ AboutWindow::AboutWindow(QWidget* parent): QDialog(parent)
{
setupWindow(); setupWindow();
} }
#pragma endregion
void AboutWindow::setupWindow() #pragma region Functions
{ void AboutWindow::setupWindow()
{
windowWidth = 250; windowWidth = 250;
windowHeight = 300; windowHeight = 300;
@@ -32,16 +35,18 @@ namespace UI
setWindowTitle("About"); setWindowTitle("About");
connections(); connections();
} }
void AboutWindow::connections() void AboutWindow::connections()
{ {
QObject::connect(actionButtonQt.get(), SIGNAL(clicked()), this, QObject::connect(actionButtonQt.get(), SIGNAL(clicked()), this,
SLOT(closeWindow())); SLOT(closeWindow()));
} }
void AboutWindow::closeWindow() void AboutWindow::closeWindow()
{ {
this->hide(); this->hide();
} }
#pragma endregion
} }
+54 -48
View File
@@ -1,11 +1,11 @@
#include"UI/MainWindow.h" #include "UI/MainWindow.h"
#include<iostream> #include <iostream>
#include<string> #include <string>
#include"Models/UploadForm.h" #include "Models/UploadForm.h"
#include"Syncers/Upload.h" #include "Syncers/Upload.h"
#include"Utilities/Conversions.h" #include "Utilities/Conversions.h"
using std::cout; using std::cout;
using std::endl; using std::endl;
@@ -17,18 +17,22 @@ using Syncers::Upload;
namespace UI namespace UI
{ {
MainWindow::MainWindow()
{ #pragma region Constructors
MainWindow::MainWindow()
{
setupMainWindow(); setupMainWindow();
aboutWindow = unique_ptr<AboutWindow>{new AboutWindow}; aboutWindow = unique_ptr<AboutWindow>{new AboutWindow};
} }
#pragma endregion
void MainWindow::configureDownloadSection() #pragma region Functions
{ void MainWindow::configureDownloadSection()
} {
void MainWindow::configureUploadSection() }
{ void MainWindow::configureUploadSection()
{
uploadSongQt = unique_ptr<QPushButton>{new QPushButton(tr("Upload"))}; uploadSongQt = unique_ptr<QPushButton>{new QPushButton(tr("Upload"))};
urlQt = unique_ptr<QTextEdit>{new QTextEdit()}; urlQt = unique_ptr<QTextEdit>{new QTextEdit()};
sourceFilePathQt = unique_ptr<QTextEdit>{new QTextEdit()}; sourceFilePathQt = unique_ptr<QTextEdit>{new QTextEdit()};
@@ -49,20 +53,20 @@ namespace UI
subLayoutOneQt.get()->addLayout(urlPortion.get()); subLayoutOneQt.get()->addLayout(urlPortion.get());
subLayoutOneQt->addLayout(songPathPortion.get()); subLayoutOneQt->addLayout(songPathPortion.get());
mainLayoutQt.get()->addLayout(subLayoutOneQt.get()); mainLayoutQt.get()->addLayout(subLayoutOneQt.get());
} }
void MainWindow::configureWindowDimensions() void MainWindow::configureWindowDimensions()
{ {
windowWidth = 450; windowWidth = 450;
windowHeight = 450; windowHeight = 450;
} }
void MainWindow::configureWindowProperties() void MainWindow::configureWindowProperties()
{ {
setWindowTitle("IcarusDownloadManager"); setWindowTitle("IcarusDownloadManager");
setFixedHeight(windowHeight); setFixedHeight(windowHeight);
setFixedWidth(windowWidth); setFixedWidth(windowWidth);
} }
void MainWindow::connections() void MainWindow::connections()
{ {
QObject::connect(uploadSongQt.get(), SIGNAL(clicked()), this, SLOT(uploadSong())); QObject::connect(uploadSongQt.get(), SIGNAL(clicked()), this, SLOT(uploadSong()));
QObject::connect(closeApplicationQt.get(), SIGNAL(triggered()), this, QObject::connect(closeApplicationQt.get(), SIGNAL(triggered()), this,
SLOT(exitApplication())); SLOT(exitApplication()));
@@ -70,9 +74,9 @@ namespace UI
SLOT(displaySoftwareInformation())); SLOT(displaySoftwareInformation()));
QObject::connect(windowComboBox.get(), SIGNAL(activated(int)), QObject::connect(windowComboBox.get(), SIGNAL(activated(int)),
this, SLOT(setCurrentIndex(int))); this, SLOT(setCurrentIndex(int)));
} }
void MainWindow::createMenus() void MainWindow::createMenus()
{ {
fileMenuQt = unique_ptr<QMenu>{menuBar()->addMenu(tr("File"))}; fileMenuQt = unique_ptr<QMenu>{menuBar()->addMenu(tr("File"))};
editMenuQt = unique_ptr<QMenu>{menuBar()->addMenu(tr("Edit"))}; editMenuQt = unique_ptr<QMenu>{menuBar()->addMenu(tr("Edit"))};
helpMenuQt = unique_ptr<QMenu>{menuBar()->addMenu(tr("Help"))}; helpMenuQt = unique_ptr<QMenu>{menuBar()->addMenu(tr("Help"))};
@@ -86,9 +90,9 @@ namespace UI
fileMenuQt->addAction(closeApplicationQt.get()); fileMenuQt->addAction(closeApplicationQt.get());
helpMenuQt->addAction(aboutApplicationQt.get()); helpMenuQt->addAction(aboutApplicationQt.get());
} }
void MainWindow::setupMainWidget() void MainWindow::setupMainWidget()
{ {
mainWidgetQt = unique_ptr<QWidget>{new QWidget}; mainWidgetQt = unique_ptr<QWidget>{new QWidget};
windowComboBox = unique_ptr<QComboBox>{new QComboBox}; windowComboBox = unique_ptr<QComboBox>{new QComboBox};
@@ -104,9 +108,9 @@ namespace UI
stackLayout->addWidget(uploadSongWidgetQt.get()); stackLayout->addWidget(uploadSongWidgetQt.get());
mainWidgetQt->setLayout(stackLayout.get()); mainWidgetQt->setLayout(stackLayout.get());
} }
void MainWindow::setupMainWindow() void MainWindow::setupMainWindow()
{ {
configureWindowDimensions(); configureWindowDimensions();
mainLayoutQt = unique_ptr<QVBoxLayout>{new QVBoxLayout}; mainLayoutQt = unique_ptr<QVBoxLayout>{new QVBoxLayout};
@@ -130,34 +134,34 @@ namespace UI
configureWindowProperties(); configureWindowProperties();
connections(); connections();
} }
void MainWindow::setupWindowLists() void MainWindow::setupWindowLists()
{ {
windowComboBox->addItem(tr("Upload song")); windowComboBox->addItem(tr("Upload song"));
windowComboBox->addItem(tr("Download song")); windowComboBox->addItem(tr("Download song"));
windowComboBox->addItem(tr("Display all songs")); windowComboBox->addItem(tr("Display all songs"));
windowComboBox->addItem(tr("Display songs")); windowComboBox->addItem(tr("Display songs"));
} }
void MainWindow::exitApplication() void MainWindow::exitApplication()
{ {
exit(0); exit(0);
} }
void MainWindow::displaySoftwareInformation() void MainWindow::displaySoftwareInformation()
{ {
aboutWindow->show(); aboutWindow->show();
} }
void MainWindow::setCurrentIndex(int index) void MainWindow::setCurrentIndex(int index)
{ {
cout<<"index "<<index<<endl; cout<<"index "<<index<<endl;
QString qText = windowComboBox->itemText(index); QString qText = windowComboBox->itemText(index);
auto cnvert = Utilities::Conversions(qText); auto cnvert = Utilities::Conversions(qText);
auto convertedStr = cnvert.convertQStringToString(); auto convertedStr = cnvert.convertQStringToString();
cout<<"item text"<<endl; cout<<"item text"<<endl;
} }
void MainWindow::uploadSong() void MainWindow::uploadSong()
{ {
uploadSongQt->setEnabled(false); uploadSongQt->setEnabled(false);
string url = urlQt->toPlainText().toUtf8().constData(); string url = urlQt->toPlainText().toUtf8().constData();
@@ -170,5 +174,7 @@ namespace UI
upld.uploadSong(); upld.uploadSong();
uploadSongQt->setEnabled(true); uploadSongQt->setEnabled(true);
} }
#pragma endregion
} }
+17 -15
View File
@@ -1,24 +1,26 @@
#include"Utilities/Conversions.h" #include "Utilities/Conversions.h"
#include<iostream> #include <iostream>
using std::string; using std::string;
using std::unique_ptr; using std::unique_ptr;
namespace Utilities namespace Utilities
{ {
Conversions::Conversions()
{
initializeValues();
}
void Conversions::initializeValues() Conversions::Conversions()
{ {
} initializeValues();
template <typename T> }
void Conversions::printValue(T val)
{ void Conversions::initializeValues()
std::cout<<"going to print value"<<std::endl; {
std::cout<<val<<std::endl; }
} template <typename T>
void Conversions::printValue(T val)
{
std::cout<<"going to print value\n";
std::cout<<val<< "\n";
}
} }