extracted album handling

This commit is contained in:
emeric
2023-10-01 16:04:28 +02:00
parent 0f1a5efffe
commit 0da12bec0f
9 changed files with 541 additions and 428 deletions
+3
View File
@@ -1,5 +1,7 @@
add_library(lmssubsonic SHARED add_library(lmssubsonic SHARED
impl/responses/Album.cpp
impl/responses/Artist.cpp
impl/ProtocolVersion.cpp impl/ProtocolVersion.cpp
impl/Scan.cpp impl/Scan.cpp
impl/Stream.cpp impl/Stream.cpp
@@ -13,6 +15,7 @@ target_include_directories(lmssubsonic INTERFACE
) )
target_include_directories(lmssubsonic PRIVATE target_include_directories(lmssubsonic PRIVATE
impl
include include
) )
+13 -106
View File
@@ -21,7 +21,6 @@
#include <atomic> #include <atomic>
#include <ctime> #include <ctime>
#include <iomanip>
#include <map> #include <map>
#include <unordered_map> #include <unordered_map>
@@ -55,6 +54,9 @@
#include "SubsonicId.hpp" #include "SubsonicId.hpp"
#include "SubsonicResponse.hpp" #include "SubsonicResponse.hpp"
#include "responses/Artist.hpp"
#include "responses/Album.hpp"
using namespace Database; using namespace Database;
static const std::string_view genreClusterName {"GENRE"}; static const std::string_view genreClusterName {"GENRE"};
@@ -183,25 +185,6 @@ checkUserTypeIsAllowed(RequestContext& context, EnumSet<Database::UserType> allo
throw UserNotAuthorizedError {}; throw UserNotAuthorizedError {};
} }
static
std::string
getArtistNames(const std::vector<Artist::pointer>& artists)
{
if (artists.size() == 1)
return artists.front()->getName();
std::vector<std::string> names;
names.resize(artists.size());
std::transform(std::cbegin(artists), std::cend(artists), std::begin(names),
[](const Artist::pointer& artist)
{
return artist->getName();
});
return StringUtils::joinStrings(names, ", ");
}
static static
std::string std::string
getTrackPath(const Track::pointer& track) getTrackPath(const Track::pointer& track)
@@ -254,17 +237,6 @@ formatToSuffix(AudioFormat format)
return ""; return "";
} }
static
std::string
dateTimeToCreatedString(const Wt::WDateTime& dateTime)
{
const std::time_t t {dateTime.toTime_t()};
std::tm gmTime;
std::ostringstream oss;
oss << std::put_time(::gmtime_r(&t, &gmTime), "%FT%T");
return oss.str();
}
static static
Response::Node Response::Node
trackToResponseNode(const Track::pointer& track, Session& dbSession, const User::pointer& user) trackToResponseNode(const Track::pointer& track, Session& dbSession, const User::pointer& user)
@@ -303,7 +275,7 @@ trackToResponseNode(const Track::pointer& track, Session& dbSession, const User:
const std::vector<Artist::pointer>& artists {track->getArtists({TrackArtistLinkType::Artist})}; const std::vector<Artist::pointer>& artists {track->getArtists({TrackArtistLinkType::Artist})};
if (!artists.empty()) if (!artists.empty())
{ {
trackResponse.setAttribute("artist", getArtistNames(artists)); trackResponse.setAttribute("artist", utils::joinArtistNames(artists));
if (artists.size() == 1) if (artists.size() == 1)
trackResponse.setAttribute("artistId", idToString(artists.front()->getId())); trackResponse.setAttribute("artistId", idToString(artists.front()->getId()));
@@ -318,7 +290,7 @@ trackToResponseNode(const Track::pointer& track, Session& dbSession, const User:
trackResponse.setAttribute("duration", std::chrono::duration_cast<std::chrono::seconds>(track->getDuration()).count()); trackResponse.setAttribute("duration", std::chrono::duration_cast<std::chrono::seconds>(track->getDuration()).count());
trackResponse.setAttribute("type", "music"); trackResponse.setAttribute("type", "music");
trackResponse.setAttribute("created", dateTimeToCreatedString(track->getLastWritten())); trackResponse.setAttribute("created", StringUtils::toISO8601String(track->getLastWritten()));
if (Service<Scrobbling::IScrobblingService>::get()->isStarred(user->getId(), track->getId())) if (Service<Scrobbling::IScrobblingService>::get()->isStarred(user->getId(), track->getId()))
trackResponse.setAttribute("starred", reportedStarredDate); trackResponse.setAttribute("starred", reportedStarredDate);
@@ -351,71 +323,6 @@ trackBookmarkToResponseNode(const TrackBookmark::pointer& trackBookmark)
return trackBookmarkNode; return trackBookmarkNode;
} }
static
Response::Node
releaseToResponseNode(const Release::pointer& release, Session& dbSession, const User::pointer& user, bool id3)
{
Response::Node albumNode;
if (id3)
{
albumNode.setAttribute("name", release->getName());
albumNode.setAttribute("songCount", release->getTracksCount());
albumNode.setAttribute("duration", std::chrono::duration_cast<std::chrono::seconds>(release->getDuration()).count());
}
else
{
albumNode.setAttribute("title", release->getName());
albumNode.setAttribute("isDir", true);
}
albumNode.setAttribute("created", dateTimeToCreatedString(release->getLastWritten()));
albumNode.setAttribute("id", idToString(release->getId()));
albumNode.setAttribute("coverArt", idToString(release->getId()));
if (const Wt::WDate releaseDate {release->getReleaseDate()}; releaseDate.isValid())
albumNode.setAttribute("year", releaseDate.year());
auto artists {release->getReleaseArtists()};
if (artists.empty())
artists = release->getArtists();
if (artists.empty() && !id3)
{
albumNode.setAttribute("parent", idToString(RootId {}));
}
else if (!artists.empty())
{
albumNode.setAttribute("artist", getArtistNames(artists));
if (artists.size() == 1)
{
albumNode.setAttribute(id3 ? "artistId" : "parent", idToString(artists.front()->getId()));
}
else
{
if (!id3)
albumNode.setAttribute("parent", idToString(RootId {}));
}
}
if (id3)
{
// Report the first GENRE for this track
ClusterType::pointer clusterType{ClusterType::find(dbSession, genreClusterName)};
if (clusterType)
{
auto clusters{release->getClusterGroups({clusterType}, 1)};
if (!clusters.empty() && !clusters.front().empty())
albumNode.setAttribute("genre", clusters.front().front()->getName());
}
}
if (Service<Scrobbling::IScrobblingService>::get()->isStarred(user->getId(), release->getId()))
albumNode.setAttribute("starred", reportedStarredDate);
return albumNode;
}
static static
Response::Node Response::Node
artistToResponseNode(const Artist::pointer& artist, Session& session, const User::pointer& user, bool id3) artistToResponseNode(const Artist::pointer& artist, Session& session, const User::pointer& user, bool id3)
@@ -816,7 +723,7 @@ handleGetAlbumListRequestCommon(const RequestContext& context, bool id3)
for (const ReleaseId releaseId : releases.results) for (const ReleaseId releaseId : releases.results)
{ {
const Release::pointer release {Release::find(context.dbSession, releaseId)}; const Release::pointer release {Release::find(context.dbSession, releaseId)};
albumListNode.addArrayChild("album", releaseToResponseNode(release, context.dbSession, user, id3)); albumListNode.addArrayChild("album", createAlbumNode(release, context.dbSession, user, id3));
} }
return response; return response;
@@ -854,16 +761,16 @@ handleGetAlbumRequest(RequestContext& context)
throw UserNotAuthorizedError {}; throw UserNotAuthorizedError {};
Response response {Response::createOkResponse(context.serverProtocolVersion)}; Response response {Response::createOkResponse(context.serverProtocolVersion)};
Response::Node releaseNode {releaseToResponseNode(release, context.dbSession, user, true /* id3 */)}; Response::Node albumNode {createAlbumNode(release, context.dbSession, user, true /* id3 */)};
const auto tracks {Track::find(context.dbSession, Track::FindParameters {}.setRelease(id).setSortMethod(TrackSortMethod::Release))}; const auto tracks {Track::find(context.dbSession, Track::FindParameters {}.setRelease(id).setSortMethod(TrackSortMethod::Release))};
for (const TrackId trackId : tracks.results) for (const TrackId trackId : tracks.results)
{ {
const Track::pointer track {Track::find(context.dbSession, trackId)}; const Track::pointer track {Track::find(context.dbSession, trackId)};
releaseNode.addArrayChild("song", trackToResponseNode(track, context.dbSession, user)); albumNode.addArrayChild("song", trackToResponseNode(track, context.dbSession, user));
} }
response.addNode("album", std::move(releaseNode)); response.addNode("album", std::move(albumNode));
return response; return response;
} }
@@ -915,7 +822,7 @@ handleGetArtistRequest(RequestContext& context)
for (const ReleaseId releaseId : releases.results) for (const ReleaseId releaseId : releases.results)
{ {
const Release::pointer release {Release::find(context.dbSession, releaseId)}; const Release::pointer release {Release::find(context.dbSession, releaseId)};
artistNode.addArrayChild("album", releaseToResponseNode(release, context.dbSession, user, true /* id3 */)); artistNode.addArrayChild("album", createAlbumNode(release, context.dbSession, user, true /* id3 */));
} }
response.addNode("artist", std::move(artistNode)); response.addNode("artist", std::move(artistNode));
@@ -1029,7 +936,7 @@ handleGetMusicDirectoryRequest(RequestContext& context)
for (const ReleaseId artistReleaseId : artistReleases.results) for (const ReleaseId artistReleaseId : artistReleases.results)
{ {
const Release::pointer release {Release::find(context.dbSession, artistReleaseId)}; const Release::pointer release {Release::find(context.dbSession, artistReleaseId)};
directoryNode.addArrayChild("child", releaseToResponseNode(release, context.dbSession, user, false /* no id3 */)); directoryNode.addArrayChild("child", createAlbumNode(release, context.dbSession, user, false /* no id3 */));
} }
} }
else if (releaseId) else if (releaseId)
@@ -1311,7 +1218,7 @@ handleGetStarredRequestCommon(RequestContext& context, bool id3)
for (const ReleaseId releaseId : scrobbling.getStarredReleases(context.userId, {} /* clusters */, Range {}).results) for (const ReleaseId releaseId : scrobbling.getStarredReleases(context.userId, {} /* clusters */, Range {}).results)
{ {
if (auto release {Release::find(context.dbSession, releaseId)}) if (auto release {Release::find(context.dbSession, releaseId)})
starredNode.addArrayChild("album", releaseToResponseNode(release, context.dbSession, user, id3)); starredNode.addArrayChild("album", createAlbumNode(release, context.dbSession, user, id3));
} }
for (const TrackId trackId : scrobbling.getStarredTracks(context.userId, {} /* clusters */, Range {}).results) for (const TrackId trackId : scrobbling.getStarredTracks(context.userId, {} /* clusters */, Range {}).results)
@@ -1547,7 +1454,7 @@ handleSearchRequestCommon(RequestContext& context, bool id3)
for (const ReleaseId releaseId : releaseIds.results) for (const ReleaseId releaseId : releaseIds.results)
{ {
const auto release {Release::find(context.dbSession, releaseId)}; const auto release {Release::find(context.dbSession, releaseId)};
searchResult2Node.addArrayChild("album", releaseToResponseNode(release, context.dbSession, user, id3)); searchResult2Node.addArrayChild("album", createAlbumNode(release, context.dbSession, user, id3));
} }
} }
+102
View File
@@ -0,0 +1,102 @@
/*
* Copyright (C) 2023 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "services/database/Cluster.hpp"
#include "services/database/Artist.hpp"
#include "services/database/Release.hpp"
#include "services/database/User.hpp"
#include "services/scrobbling/IScrobblingService.hpp"
#include "utils/Service.hpp"
#include "utils/String.hpp"
#include "responses/Album.hpp"
#include "responses/Artist.hpp"
#include "SubsonicId.hpp"
namespace API::Subsonic
{
static const std::string_view reportedDummyStarredDate {"2000-01-01T00:00:00"};
using namespace Database;
Response::Node createAlbumNode(const Release::pointer& release, Session& dbSession, const User::pointer& user, bool id3)
{
Response::Node albumNode;
if (id3) {
albumNode.setAttribute("name", release->getName());
albumNode.setAttribute("songCount", release->getTracksCount());
albumNode.setAttribute(
"duration", std::chrono::duration_cast<std::chrono::seconds>(
release->getDuration())
.count());
}
else
{
albumNode.setAttribute("title", release->getName());
albumNode.setAttribute("isDir", true);
}
albumNode.setAttribute("created", StringUtils::toISO8601String(release->getLastWritten()));
albumNode.setAttribute("id", idToString(release->getId()));
albumNode.setAttribute("coverArt", idToString(release->getId()));
if (const Wt::WDate releaseDate{ release->getReleaseDate() }; releaseDate.isValid())
albumNode.setAttribute("year", releaseDate.year());
auto artists{ release->getReleaseArtists() };
if (artists.empty())
artists = release->getArtists();
if (artists.empty() && !id3)
{
albumNode.setAttribute("parent", idToString(RootId{}));
}
else if (!artists.empty())
{
albumNode.setAttribute("artist", utils::joinArtistNames(artists));
if (artists.size() == 1)
{
albumNode.setAttribute(id3 ? "artistId" : "parent", idToString(artists.front()->getId()));
}
else
{
if (!id3)
albumNode.setAttribute("parent", idToString(RootId{}));
}
}
if (id3)
{
// Report the first GENRE for this track
ClusterType::pointer clusterType{ ClusterType::find(dbSession, "GENRE") };
if (clusterType)
{
auto clusters{ release->getClusterGroups({clusterType}, 1) };
if (!clusters.empty() && !clusters.front().empty())
albumNode.setAttribute("genre", clusters.front().front()->getName());
}
}
if (Service<Scrobbling::IScrobblingService>::get()->isStarred(user->getId(), release->getId()))
albumNode.setAttribute("starred", reportedDummyStarredDate); // TODO report correct date/time
return albumNode;
}
}
@@ -0,0 +1,34 @@
/*
* Copyright (C) 2023 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "services/database/Object.hpp"
#include "SubsonicResponse.hpp"
namespace Database
{
class Release;
class User;
}
namespace API::Subsonic
{
Response::Node createAlbumNode(const Database::ObjectPtr<Database::Release>& release, Database::Session& dbSession, const Database::ObjectPtr<Database::User>& user, bool id3);
}
@@ -0,0 +1,46 @@
/*
* Copyright (C) 2023 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "responses/Artist.hpp"
#include "services/database/Artist.hpp"
namespace API::Subsonic
{
using namespace Database;
namespace utils
{
std::string joinArtistNames(const std::vector<Artist::pointer>& artists)
{
if (artists.size() == 1)
return artists.front()->getName();
std::vector<std::string> names;
names.resize(artists.size());
std::transform(std::cbegin(artists), std::cend(artists), std::begin(names),
[](const Artist::pointer& artist)
{
return artist->getName();
});
return StringUtils::joinStrings(names, ", ");
}
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2023 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <vector>
#include "services/database/Object.hpp"
#include "SubsonicResponse.hpp"
namespace Database
{
class Artist;
class User;
}
namespace API::Subsonic
{
namespace utils
{
std::string joinArtistNames(const std::vector<Database::ObjectPtr<Database::Artist>>& artists);
}
}
+88 -94
View File
@@ -27,11 +27,14 @@
#include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
namespace StringUtils { #include <Wt/WDateTime.h>
#include <Wt/WDate.h>
bool namespace StringUtils
readList(const std::string& str, const std::string& separators, std::list<std::string>& results)
{ {
bool readList(const std::string& str, const std::string& separators, std::list<std::string>& results)
{
std::string curStr; std::string curStr;
for (char c : str) for (char c : str)
@@ -54,55 +57,50 @@ readList(const std::string& str, const std::string& separators, std::list<std::s
results.push_back(curStr); results.push_back(curStr);
return !str.empty(); return !str.empty();
} }
template<> template<>
std::optional<std::string> std::optional<std::string> readAs(std::string_view str)
readAs(std::string_view str) {
{ return std::string{ str };
return std::string {str}; }
}
template<> template<>
std::optional<std::string_view> std::optional<std::string_view> readAs(std::string_view str)
readAs(std::string_view str) {
{
return str; return str;
} }
template<> template<>
std::optional<bool> std::optional<bool> readAs(std::string_view str)
readAs(std::string_view str) {
{
if (str == "1" || str == "true") if (str == "1" || str == "true")
return true; return true;
else if (str == "0" || str == "false") else if (str == "0" || str == "false")
return false; return false;
return std::nullopt; return std::nullopt;
} }
std::vector<std::string> std::vector<std::string> splitStringCopy(std::string_view string, std::string_view separators)
splitStringCopy(std::string_view string, std::string_view separators) {
{ std::string str{ stringTrim(string, separators) };
std::string str {stringTrim(string, separators)};
std::vector<std::string> res; std::vector<std::string> res;
boost::algorithm::split(res, str, boost::is_any_of(separators), boost::token_compress_on); boost::algorithm::split(res, str, boost::is_any_of(separators), boost::token_compress_on);
return res; return res;
} }
std::vector<std::string_view> std::vector<std::string_view> splitString(std::string_view str, std::string_view separators)
splitString(std::string_view str, std::string_view separators) {
{
std::vector<std::string_view> res; std::vector<std::string_view> res;
std::string_view::size_type strBegin {}; std::string_view::size_type strBegin{};
while ((strBegin = str.find_first_not_of(separators, strBegin)) != std::string_view::npos) while ((strBegin = str.find_first_not_of(separators, strBegin)) != std::string_view::npos)
{ {
auto strEnd {str.find_first_of(separators, strBegin + 1)}; auto strEnd{ str.find_first_of(separators, strBegin + 1) };
if (strEnd == std::string_view::npos) if (strEnd == std::string_view::npos)
{ {
res.push_back(str.substr(strBegin, str.size() - strBegin)); res.push_back(str.substr(strBegin, str.size() - strBegin));
@@ -114,68 +112,61 @@ splitString(std::string_view str, std::string_view separators)
} }
return res; return res;
} }
std::string std::string joinStrings(const std::vector<std::string>& strings, const std::string& delimiter)
joinStrings(const std::vector<std::string>& strings, const std::string& delimiter) {
{
return boost::algorithm::join(strings, delimiter); return boost::algorithm::join(strings, delimiter);
} }
std::string_view std::string_view stringTrim(std::string_view str, std::string_view whitespaces)
stringTrim(std::string_view str, std::string_view whitespaces) {
{
std::string_view res; std::string_view res;
const auto strBegin = str.find_first_not_of(whitespaces); const auto strBegin = str.find_first_not_of(whitespaces);
if (strBegin != std::string_view::npos) if (strBegin != std::string_view::npos)
{ {
const auto strEnd {str.find_last_not_of(whitespaces)}; const auto strEnd{ str.find_last_not_of(whitespaces) };
const auto strRange {strEnd - strBegin + 1}; const auto strRange{ strEnd - strBegin + 1 };
res = str.substr(strBegin, strRange); res = str.substr(strBegin, strRange);
} }
return res; return res;
} }
std::string_view std::string_view stringTrimEnd(std::string_view str, std::string_view whitespaces)
stringTrimEnd(std::string_view str, std::string_view whitespaces) {
{
return str.substr(0, str.find_last_not_of(whitespaces) + 1); return str.substr(0, str.find_last_not_of(whitespaces) + 1);
} }
std::string std::string stringToLower(std::string_view str)
stringToLower(std::string_view str) {
{
std::string res; std::string res;
res.reserve(str.size()); res.reserve(str.size());
std::transform(std::cbegin(str), std::cend(str), std::back_inserter(res), [](unsigned char c) { return std::tolower(c);}); std::transform(std::cbegin(str), std::cend(str), std::back_inserter(res), [](unsigned char c) { return std::tolower(c);});
return res; return res;
} }
void void stringToLower(std::string& str)
stringToLower(std::string& str) {
{
std::transform(std::cbegin(str), std::cend(str), std::begin(str), [](unsigned char c) { return std::tolower(c);}); std::transform(std::cbegin(str), std::cend(str), std::begin(str), [](unsigned char c) { return std::tolower(c);});
} }
std::string std::string stringToUpper(const std::string& str)
stringToUpper(const std::string& str) {
{
std::string res; std::string res;
res.reserve(str.size()); res.reserve(str.size());
std::transform(std::cbegin(str), std::cend(str), std::back_inserter(res), [](char c) { return std::toupper(c);}); std::transform(std::cbegin(str), std::cend(str), std::back_inserter(res), [](char c) { return std::toupper(c);});
return res; return res;
} }
std::string std::string bufferToString(const std::vector<unsigned char>& data)
bufferToString(const std::vector<unsigned char>& data) {
{
std::ostringstream oss; std::ostringstream oss;
for (unsigned char c : data) for (unsigned char c : data)
@@ -184,12 +175,11 @@ bufferToString(const std::vector<unsigned char>& data)
} }
return oss.str(); return oss.str();
} }
void void capitalize(std::string& str)
capitalize(std::string& str) {
{ for (auto it{ std::begin(str) }; it != std::end(str); ++it)
for (auto it {std::begin(str)}; it != std::end(str); ++it)
{ {
if (std::isspace(*it)) if (std::isspace(*it))
continue; continue;
@@ -199,12 +189,11 @@ capitalize(std::string& str)
break; break;
} }
} }
std::string std::string replaceInString(std::string_view str, const std::string& from, const std::string& to)
replaceInString(std::string_view str, const std::string& from, const std::string& to) {
{ std::string res{ str };
std::string res {str};
size_t pos = 0; size_t pos = 0;
while ((pos = res.find(from, pos)) != std::string::npos) while ((pos = res.find(from, pos)) != std::string::npos)
@@ -214,11 +203,10 @@ replaceInString(std::string_view str, const std::string& from, const std::string
} }
return res; return res;
} }
std::string std::string jsEscape(const std::string& str)
jsEscape(const std::string& str) {
{
static const std::unordered_map<char, std::string_view> escapeMap static const std::unordered_map<char, std::string_view> escapeMap
{ {
{ '\\', "\\\\" }, { '\\', "\\\\" },
@@ -234,7 +222,7 @@ jsEscape(const std::string& str)
for (const char c : str) for (const char c : str)
{ {
auto it {escapeMap.find(c)}; auto it{ escapeMap.find(c) };
if (it == std::cend(escapeMap)) if (it == std::cend(escapeMap))
{ {
escaped += c; escaped += c;
@@ -245,11 +233,10 @@ jsEscape(const std::string& str)
} }
return escaped; return escaped;
} }
std::string std::string escapeString(std::string_view str, std::string_view charsToEscape, char escapeChar)
escapeString(std::string_view str, std::string_view charsToEscape, char escapeChar) {
{
std::string res; std::string res;
res.reserve(str.size()); res.reserve(str.size());
@@ -262,18 +249,16 @@ escapeString(std::string_view str, std::string_view charsToEscape, char escapeCh
} }
return res; return res;
} }
bool bool stringEndsWith(const std::string& str, const std::string& ending)
stringEndsWith(const std::string& str, const std::string& ending) {
{
return boost::algorithm::ends_with(str, ending); return boost::algorithm::ends_with(str, ending);
} }
std::optional<std::string> std::optional<std::string> stringFromHex(const std::string& str)
stringFromHex(const std::string& str) {
{ static const char lut[]{ "0123456789ABCDEF" };
static const char lut[] {"0123456789ABCDEF"};
if (str.length() % 2 != 0) if (str.length() % 2 != 0)
return std::nullopt; return std::nullopt;
@@ -281,25 +266,34 @@ stringFromHex(const std::string& str)
std::string res; std::string res;
res.reserve(str.length() / 2); res.reserve(str.length() / 2);
auto it {std::cbegin(str)}; auto it{ std::cbegin(str) };
while (it != std::cend(str)) while (it != std::cend(str))
{ {
unsigned val {}; unsigned val{};
auto itHigh {std::lower_bound(std::cbegin(lut), std::cend(lut), std::toupper(*(it++)))}; auto itHigh{ std::lower_bound(std::cbegin(lut), std::cend(lut), std::toupper(*(it++))) };
auto itLow {std::lower_bound(std::cbegin(lut), std::cend(lut), std::toupper(*(it++)))}; auto itLow{ std::lower_bound(std::cbegin(lut), std::cend(lut), std::toupper(*(it++))) };
if (itHigh == std::cend(lut) || itLow == std::cend(lut)) if (itHigh == std::cend(lut) || itLow == std::cend(lut))
return {}; return {};
val = std::distance(std::cbegin(lut), itHigh) << 4; val = std::distance(std::cbegin(lut), itHigh) << 4;
val += std::distance(std::cbegin(lut), itLow ); val += std::distance(std::cbegin(lut), itLow);
res.push_back(static_cast<char>(val)); res.push_back(static_cast<char>(val));
} }
return res; return res;
} }
std::string toISO8601String(const Wt::WDateTime& dateTime)
{
return dateTime.toString("yyyy-MM-ddThh:mm:ss.zzz", false).toUTF8();
}
std::string toISO8601String(const Wt::WDate& date)
{
return date.toString("yyyy-MM-dd").toUTF8();
}
} // StringUtils } // StringUtils
+35 -62
View File
@@ -29,94 +29,67 @@
#define QUOTEME(x) QUOTEME_1(x) #define QUOTEME(x) QUOTEME_1(x)
#define QUOTEME_1(x) #x #define QUOTEME_1(x) #x
namespace Wt
{
class WDate;
class WDateTime;
}
namespace StringUtils { namespace StringUtils {
[[nodiscard]] [[nodiscard]] std::vector<std::string> splitStringCopy(std::string_view string, std::string_view separators);
std::vector<std::string>
splitStringCopy(std::string_view string, std::string_view separators);
[[nodiscard]] [[nodiscard]] std::vector<std::string_view> splitString(std::string_view string, std::string_view separators);
std::vector<std::string_view>
splitString(std::string_view string, std::string_view separators);
[[nodiscard]] [[nodiscard]] std::string joinStrings(const std::vector<std::string>& strings, const std::string& delimiter);
std::string
joinStrings(const std::vector<std::string>& strings, const std::string& delimiter);
[[nodiscard]] [[nodiscard]] std::string_view stringTrim(std::string_view str, std::string_view whitespaces = " \t");
std::string_view
stringTrim(std::string_view str, std::string_view whitespaces = " \t");
[[nodiscard]] [[nodiscard]] std::string_view stringTrimEnd(std::string_view str, std::string_view whitespaces = " \t");
std::string_view
stringTrimEnd(std::string_view str, std::string_view whitespaces = " \t");
[[nodiscard]] [[nodiscard]] std::string stringToLower(std::string_view str);
std::string
stringToLower(std::string_view str);
void void stringToLower(std::string& str);
stringToLower(std::string& str);
[[nodiscard]] [[nodiscard]] std::string stringToUpper(const std::string& str);
std::string
stringToUpper(const std::string& str);
[[nodiscard]] [[nodiscard]] std::string bufferToString(const std::vector<unsigned char>& data);
std::string
bufferToString(const std::vector<unsigned char>& data);
void void capitalize(std::string& str);
capitalize(std::string& str);
template<typename T> template<typename T>
[[nodiscard]] [[nodiscard]] std::optional<T> readAs(std::string_view str)
std::optional<T> readAs(std::string_view str) {
{
T res; T res;
std::istringstream iss {std::string {str}}; std::istringstream iss{ std::string {str} };
iss >> res; iss >> res;
if (iss.fail()) if (iss.fail())
return std::nullopt; return std::nullopt;
return res; return res;
} }
template<> template<>
[[nodiscard]] [[nodiscard]] std::optional<std::string> readAs(std::string_view str);
std::optional<std::string>
readAs(std::string_view str);
template<> template<>
[[nodiscard]] [[nodiscard]] std::optional<std::string_view> readAs(std::string_view str);
std::optional<std::string_view>
readAs(std::string_view str);
template<> template<>
[[nodiscard]] [[nodiscard]] std::optional<bool> readAs(std::string_view str);
std::optional<bool>
readAs(std::string_view str);
[[nodiscard]] [[nodiscard]] std::string replaceInString(std::string_view str, const std::string& from, const std::string& to);
std::string
replaceInString(std::string_view str, const std::string& from, const std::string& to);
[[nodiscard]] [[nodiscard]] std::string jsEscape(const std::string& str);
std::string
jsEscape(const std::string& str);
[[nodiscard]] [[nodiscard]] std::string escapeString(std::string_view str, std::string_view charsToEscape, char escapeChar);
std::string
escapeString(std::string_view str, std::string_view charsToEscape, char escapeChar);
[[nodiscard]] [[nodiscard]] bool stringEndsWith(const std::string& str, const std::string& ending);
bool
stringEndsWith(const std::string& str, const std::string& ending);
[[nodiscard]] [[nodiscard]] std::optional<std::string> stringFromHex(const std::string& str);
std::optional<std::string>
stringFromHex(const std::string& str); [[nodiscard]] std::string toISO8601String(const Wt::WDateTime& dateTime);
[[nodiscard]] std::string toISO8601String(const Wt::WDate& date);
} // StringUtils } // StringUtils
+15
View File
@@ -19,6 +19,9 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <Wt/WDateTime.h>
#include <Wt/WDate.h>
#include <Wt/WTime.h>
#include "utils/String.hpp" #include "utils/String.hpp"
TEST(StringUtils, splitString) TEST(StringUtils, splitString)
@@ -147,3 +150,15 @@ TEST(StringUtils, capitalize)
EXPECT_EQ(str, test.expectedOutput) << " str was '" << test.input << "'"; EXPECT_EQ(str, test.expectedOutput) << " str was '" << test.input << "'";
} }
} }
TEST(Stringutils, date)
{
const Wt::WDate date{ 2020, 01, 03 };
EXPECT_EQ(StringUtils::toISO8601String(date), "2020-01-03");
}
TEST(Stringutils, dateTime)
{
const Wt::WDateTime dateTime{ Wt::WDate {2020, 01, 03 }, Wt::WTime{9, 8, 11, 75} };
EXPECT_EQ(StringUtils::toISO8601String(dateTime), "2020-01-03T09:08:11.075");
}