diff --git a/.clang-format b/.clang-format index 87c95de..a3d2b94 100644 --- a/.clang-format +++ b/.clang-format @@ -1,5 +1,5 @@ # A complete list of style options can be found at: -# http://clang.llvm.org/docs/ClangFormatStyleOptions.html +# https://clang.llvm.org/docs/ClangFormatStyleOptions.html # # Google C++ Style Guide # https://google.github.io/styleguide/cppguide.html @@ -13,11 +13,19 @@ # void formatted_code_again; # +Language: Cpp + +# Basic indentation and spacing rules: +IndentWidth: 4 +ContinuationIndentWidth: 4 +UseCRLF: false +Standard: c++20 +UseTab: Never +MaxEmptyLinesToKeep: 1 + AccessModifierOffset: -4 -ConstructorInitializerIndentWidth: 4 AlignAfterOpenBracket: AlwaysBreak AlignConsecutiveAssignments: true -#AlignConsecutiveBitFields: true AlignConsecutiveDeclarations: false AlignConsecutiveMacros: true AlignEscapedNewlinesLeft: true @@ -26,7 +34,7 @@ AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortFunctionsOnASingleLine: Empty AllowShortBlocksOnASingleLine: true -AllowShortIfStatementsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AllowShortLambdasOnASingleLine: Empty AllowShortCaseLabelsOnASingleLine: false @@ -59,10 +67,8 @@ ColumnLimit: 120 CompactNamespaces: true ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DeriveLineEnding: true -DerivePointerAlignment: false ExperimentalAutoDetectBinPacking: true FixNamespaceComments: true IncludeBlocks: Preserve @@ -70,8 +76,6 @@ IndentCaseLabels: false IndentGotoLabels: false IndentPPDirectives: None IndentFunctionDeclarationAfterType: false -IndentWidth: 4 -MaxEmptyLinesToKeep: 1 NamespaceIndentation: All ObjCSpaceBeforeProtocolList: false PenaltyBreakBeforeFirstCallParameter: 10 @@ -80,8 +84,6 @@ PenaltyBreakFirstLessLess: 20 PenaltyBreakString: 1000 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 200 -PointerAlignment: Right -PointerBindsToType: true SortIncludes: false SpaceAfterControlStatementKeyword: true SpaceBeforeParens: ControlStatements @@ -97,6 +99,12 @@ SpacesInConditionalStatement: false SpacesInContainerLiterals: false SpacesInParentheses: false SpacesInSquareBrackets: false -Standard: c++20 -TabWidth: 4 -UseTab: Never \ No newline at end of file + +# int* value instead of int *value +DerivePointerAlignment: false +PointerAlignment: Left +PointerBindsToType: true +SpaceAroundPointerQualifiers: After + +# Prefer "east const", placing `const` after the type: int const instead of const int +QualifierAlignment: Right diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..9c575ad --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,26 @@ +# Clang Tidy - Config +--- +Checks: '-* + bugprone-*, + -bugprone-easily-swappable-parameters + cert-*, + -cert-err33-c + cppcoreguidelines-*, + -cppcoreguidelines-pro-bounds-pointer-arithmetic + -cppcoreguidelines-pro-type-vararg + -cppcoreguidelines-avoid-c-arrays + -cppcoreguidelines-no-malloc + -cppcoreguidelines-owning-memory + -cppcoreguidelines-pro-bounds-array-to-pointer-decay + misc-*, + -misc-include-cleaner + modernize-*, + -modernize-use-trailing-return-type + performance-*, + readability-*, + -readability-identifier-length + -readability-function-cognitive-complexity + -readability-static-accessed-through-instance + ' + +WarningsAsErrors: '*' diff --git a/.github/workflows/cpp-quality.yml b/.github/workflows/cpp-quality.yml new file mode 100644 index 0000000..6c02c08 --- /dev/null +++ b/.github/workflows/cpp-quality.yml @@ -0,0 +1,81 @@ +# +# .github/workflows/cpp-quality.yml +# +# Copyright 2024 Jens A. Koch. +# SPDX-License-Identifier: MIT +# This file is part of jakoch/wikifolio_universe_converter. +# + +name: "C++ Quality" + +on: + - push + - pull_request + # You can manually run this workflow. + - workflow_dispatch + +# improve CI concurrency by automatically cancelling outdated jobs +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + +# --------------------------------------------------------------------------------------- + + clang-format: + +# --------------------------------------------------------------------------------------- + + runs-on: ubuntu-latest + + steps: + + - name: 🤘 Checkout Code + uses: actions/checkout@v4 # https://github.com/actions/checkout + + - name: 🔽 Install dos2unix + run: sudo apt-get install -y dos2unix + + - name: 🔽 Install clang-format-18 + run: | + wget https://apt.llvm.org/llvm.sh + chmod +x ./llvm.sh + sudo ./llvm.sh 18 + sudo apt-get install -y clang-format-18 + + - name: Check formatting + run: ./format.sh && git diff --exit-code + env: + CLANG_FORMAT: clang-format-18 + +# --------------------------------------------------------------------------------------- + + cpplint: + +# --------------------------------------------------------------------------------------- + + runs-on: ubuntu-latest + + steps: + + - name: 🤘 Checkout Code + uses: actions/checkout@v4 # https://github.com/actions/checkout + + - name: Setup Python + run: sudo apt-get -y install python3 python3-pip python3-venv + + - name: Setup Python Virtual Env + run: | + export VIRTUAL_ENV=/opt/venv + python3 -m venv $VIRTUAL_ENV + export PATH="$VIRTUAL_ENV/bin:$PATH" + + - name: Install cpplint + run: pip install --prefer-binary --no-cache-dir cpplint + + - name: Run lint + run: cpplint --recursive src --exclude=src/steamapi/* diff --git a/src/DataObject.cpp b/src/DataObject.cpp index a60d709..0f6cc45 100644 --- a/src/DataObject.cpp +++ b/src/DataObject.cpp @@ -1,11 +1,20 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "DataObject.h" std::string DataObject::getPlayerRank(int rank_type_id) { int rank_id; - if (rank_type_id == 6) { rank_id = rankings.at(0).id; } - if (rank_type_id == 7) { rank_id = rankings.at(1).id; } - if (rank_type_id == 10) { rank_id = rankings.at(2).id; } + if (rank_type_id == 6) { + rank_id = rankings.at(0).id; + } + if (rank_type_id == 7) { + rank_id = rankings.at(1).id; + } + if (rank_type_id == 10) { + rank_id = rankings.at(2).id; + } int rank = (rank_id < 0) ? rank_id - 1 : rank_id; @@ -19,7 +28,7 @@ std::string DataObject::getPlayerLevel() return getLevelName(level); } -const int DataObject::calcPlayerXpBase() const +int const DataObject::calcPlayerXpBase() const { return player_cur_xp - 327680000; // xp minus base value, gives normalized player xp } @@ -29,9 +38,9 @@ std::string DataObject::getPlayerXp() return std::to_string(calcPlayerXpBase()); } -const float DataObject::getPlayerXpPercentage() +float const DataObject::getPlayerXpPercentage() { - return ((float)calcPlayerXpBase() / 5000) * 100; + return (static_cast(calcPlayerXpBase()) / 5000) * 100; } std::string DataObject::getVacStatus() @@ -51,9 +60,15 @@ std::string DataObject::getRankName(int i) std::string DataObject::getRankType(int i) { - if (i == 6) { return "MatchMaking"; } - if (i == 7) { return "Wingman"; } - if (i == 10) { return "DangerZone"; } + if (i == 6) { + return "MatchMaking"; + } + if (i == 7) { + return "Wingman"; + } + if (i == 10) { + return "DangerZone"; + } return "Unknown RankType"; } @@ -74,11 +89,15 @@ std::string DataObject::getSteamProfileUrl() std::string DataObject::getCanDoOverwatch() { RankingInfo matchmaking_rank = rankings.at(0); - int rank_id = matchmaking_rank.id; - int rank_wins = matchmaking_rank.wins; - - if (rank_id < 7) { return "Your rank is too low. " + getRankName(7) + " required."; } - if (rank_wins < 150) { return "You don't have enough wins: 150 required."; } + int rank_id = matchmaking_rank.id; + int rank_wins = matchmaking_rank.wins; + + if (rank_id < 7) { + return "Your rank is too low. " + getRankName(7) + " required."; + } + if (rank_wins < 150) { + return "You don't have enough wins: 150 required."; + } return "Qualified to request replays."; } std::string DataObject::getAverageSearchTime() diff --git a/src/DataObject.h b/src/DataObject.h index 5af9877..ffd866b 100644 --- a/src/DataObject.h +++ b/src/DataObject.h @@ -1,18 +1,22 @@ -#ifndef DataObject_H -#define DataObject_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_DATAOBJECT_H_ +#define SRC_DATAOBJECT_H_ #include "DateTimeUtils.h" #include "csgo/CSGOMatchData.h" // for vector matches #include "cstrike15_gcmessages.pb.h" #include +#include #include #include class DataObject { private: - const std::vector ranks = { + std::vector const ranks = { "Not Ranked", "Silver 1", "Silver 2", @@ -34,7 +38,7 @@ class DataObject "Global Elite", // big globe }; - const std::vector levels = { + std::vector const levels = { "Not Recruited", "Recruit", "Private I", "Private II", "Private III", "Corporal I", "Corporal II", "Corporal III", "Corporal IV", "Sergeant I", "Sergeant II", "Sergeant III", @@ -47,7 +51,7 @@ class DataObject "Brigadier General", "Major General", "Lieutenant General", "General", "Global General"}; - const std::vector dangerzone_ranks = { + std::vector const dangerzone_ranks = { "Hidden", "Lab Rat I", "Lab Rat II", @@ -65,7 +69,7 @@ class DataObject "Wildfire Wolf", "The Howling Alpha"}; - const std::vector penalty_reasons_long = { + std::vector const penalty_reasons_long = { "Temporary Matchmaking Cooldown (No reason)", "You have been kicked from your last matchmaking game.", "You killed too many teammates.", @@ -87,7 +91,7 @@ class DataObject "Your account is under skill placement calibration.", "A server using your game server token has been banned."}; - const std::vector penalty_reasons_short = { + std::vector const penalty_reasons_short = { "CooldownNone" "Kicked" "KilledMate" @@ -109,12 +113,12 @@ class DataObject "NewbieCooldown" "GameServerBanned"}; - const std::string steam_profile_url_base = "https://steamcommunity.com/profiles/"; + std::string const steam_profile_url_base = "https://steamcommunity.com/profiles/"; - // TODO - const std::string tpl_url_wingman_replays = "https://steamcommunity.com/id/{}/gcpd/730/?tab=matchhistorywingman"; + // TODO(jakoch): add wingman. + std::string const tpl_url_wingman_replays = "https://steamcommunity.com/id/{}/gcpd/730/?tab=matchhistorywingman"; - const int calcPlayerXpBase() const; + int const calcPlayerXpBase() const; public: std::string getSteamId(); @@ -122,7 +126,7 @@ class DataObject std::string getPlayerLevel(); std::string getPlayerRank(int rank_type_id); std::string getPlayerXp(); - const float getPlayerXpPercentage(); + float const getPlayerXpPercentage(); std::string getVacStatus(); std::string getLevelName(int i); std::string getRankName(int i); @@ -160,9 +164,9 @@ class DataObject uint32 cmd_leader = 0; // player level - int32 player_level = 0; - int32 player_cur_xp = 0; // starts at 327680000 (level % = (player_cur_xp - 327680000) / 5000) - int32 player_xp_bonus_flags = 0; // TODO + int32 player_level = 0; + int32 player_cur_xp = 0; // starts at 327680000 (level % = (player_cur_xp - 327680000) / 5000) + int32 player_xp_bonus_flags = 0; // TODO(jakoch): add bonus flag. // medals uint32 medals_arms = 0; @@ -200,4 +204,4 @@ class DataObject }; GlobalStats global_stats; }; -#endif +#endif // SRC_DATAOBJECT_H_ diff --git a/src/DateTimeUtils.cpp b/src/DateTimeUtils.cpp index 44813ea..e1e7c9c 100644 --- a/src/DateTimeUtils.cpp +++ b/src/DateTimeUtils.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "DateTimeUtils.h" std::string getYear() @@ -10,17 +13,17 @@ std::string getYear() return ss.str(); } -std::string getDateTime(const time_t &time, const char *time_format) +std::string getDateTime(time_t const & time, char const * time_format) { std::stringstream ss; - ss << std::put_time(localtime(&time), time_format); + ss << std::put_time(localtime_r(&time), time_format); return ss.str(); } std::string format_duration_get_minutes(int msecs) { - using namespace std::chrono; - auto ms = milliseconds(msecs); + using std::chrono; + auto ms = milliseconds(msecs); auto secs = duration_cast(ms); ms -= duration_cast(secs); auto mins = duration_cast(secs); diff --git a/src/DateTimeUtils.h b/src/DateTimeUtils.h index e75dea0..e2a1bed 100644 --- a/src/DateTimeUtils.h +++ b/src/DateTimeUtils.h @@ -1,13 +1,17 @@ -#ifndef DATETIMEUTILS_H -#define DATETIMEUTILS_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_DATETIMEUTILS_H_ +#define SRC_DATETIMEUTILS_H_ #include #include #include #include +#include std::string getYear(); -std::string getDateTime(const time_t &time, const char *time_format = "%Y-%m-%d %H:%M:%S"); +std::string getDateTime(time_t const & time, char const * time_format = "%Y-%m-%d %H:%M:%S"); std::string format_duration_get_minutes(int milliseconds); -#endif \ No newline at end of file +#endif // SRC_DATETIMEUTILS_H_ \ No newline at end of file diff --git a/src/ErrorHandler.h b/src/ErrorHandler.h index 39214cc..07eed20 100644 --- a/src/ErrorHandler.h +++ b/src/ErrorHandler.h @@ -1,12 +1,15 @@ -#ifndef ERRORHANDLER_H -#define ERRORHANDLER_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_ERRORHANDLER_H_ +#define SRC_ERRORHANDLER_H_ #include #include -static inline void printError(const char *title, const char *text) +static inline void printError(char const * title, char const * text) { fprintf(stdout, "\x1B[91m%s:\033[0m %s\n", title, text); } -#endif \ No newline at end of file +#endif // SRC_ERRORHANDLER_H_ \ No newline at end of file diff --git a/src/ExceptionHandler.cpp b/src/ExceptionHandler.cpp index c44a8d1..40028e2 100644 --- a/src/ExceptionHandler.cpp +++ b/src/ExceptionHandler.cpp @@ -1,8 +1,11 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "ExceptionHandler.h" -ExceptionHandler::ExceptionHandler(const std::string &what) : m_what(what) { } +ExceptionHandler::ExceptionHandler(std::string const & what) : m_what(what) { } -const char *ExceptionHandler::what() const throw() +char const * ExceptionHandler::what() const throw() { return m_what.c_str(); } diff --git a/src/ExceptionHandler.h b/src/ExceptionHandler.h index de69ec0..a78939b 100644 --- a/src/ExceptionHandler.h +++ b/src/ExceptionHandler.h @@ -1,5 +1,8 @@ -#ifndef ExceptionHandler_H -#define ExceptionHandler_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_EXCEPTIONHANDLER_H_ +#define SRC_EXCEPTIONHANDLER_H_ #include #include @@ -7,11 +10,11 @@ class ExceptionHandler : public std::exception { public: - ExceptionHandler(const std::string &what); - virtual const char *what() const throw(); + explicit ExceptionHandler(std::string const & what); + virtual char const * what() const throw(); private: std::string m_what; }; -#endif +#endif // SRC_EXCEPTIONHANDLER_H_ diff --git a/src/ShareCode.cpp b/src/ShareCode.cpp index f6d988e..553394c 100644 --- a/src/ShareCode.cpp +++ b/src/ShareCode.cpp @@ -1,13 +1,16 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "ShareCode.h" -void quotientAndRemainder(uint64_t &a0, uint64_t &a1, uint16_t &a2, uint16_t m, uint16_t &r) +void quotientAndRemainder(uint64_t& a0, uint64_t& a1, uint16_t& a2, uint16_t m, uint16_t& r) { r = 0; uint64_t q0 = 0; uint64_t q1 = 0; uint16_t q2 = 0; - const unsigned int ull_bitnum = sizeof(uint64_t) * 8; - const unsigned int us_bitnum = sizeof(uint16_t) * 8; + unsigned int const ull_bitnum = sizeof(uint64_t) * 8; + unsigned int const us_bitnum = sizeof(uint16_t) * 8; for (int i = 2 * ull_bitnum + us_bitnum - 1; i >= 0; --i) { r <<= 1; @@ -61,12 +64,12 @@ void quotientAndRemainder(uint64_t &a0, uint64_t &a1, uint16_t &a2, uint16_t m, std::string getShareCode(uint64_t matchid, uint64_t reservationid, uint32_t tvport) { // charset for base57 - const std::string dictionary = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789"; + std::string const dictionary = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789"; std::string code; uint64_t matchid_reversed = _byteswap_uint64(matchid); uint64_t reservationid_reversed = _byteswap_uint64(reservationid); - uint16_t tvport_reversed = _byteswap_ushort(*(uint16_t *)(&tvport)); + uint16_t tvport_reversed = _byteswap_ushort(*reinterpret_cast(&tvport)); uint16_t r = 0; uint16_t dl = dictionary.length(); @@ -79,8 +82,9 @@ std::string getShareCode(uint64_t matchid, uint64_t reservationid, uint32_t tvpo // example: "CSGO-GADqf-jjyJ8-cSP2r-smZRo-TO2xK" char shareCode[35]; - sprintf( + snprintf( shareCode, + sizeof(shareCode), "CSGO-%s-%s-%s-%s-%s", code.substr(0, 5).c_str(), code.substr(5, 5).c_str(), diff --git a/src/ShareCode.h b/src/ShareCode.h index d8be149..0426e7a 100644 --- a/src/ShareCode.h +++ b/src/ShareCode.h @@ -1,12 +1,16 @@ -#ifndef ShareCode_H -#define ShareCode_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_SHARECODE_H_ +#define SRC_SHARECODE_H_ #include #include #include #include +#include -void quotientAndRemainder(uint64_t &a0, uint64_t &a1, uint16_t &a2, uint16_t m, uint16_t &r); +void quotientAndRemainder(uint64_t& a0, uint64_t& a1, uint16_t& a2, uint16_t m, uint16_t& r); /** * Generate a demo share code from its object data and return its string representation. @@ -36,4 +40,4 @@ std::string getShareCode(uint64_t matchid, uint64_t reservationid, uint32_t tvpo std::string fromDemoShareCode(std::string sharecode); */ -#endif \ No newline at end of file +#endif // SRC_SHARECODE_H_ \ No newline at end of file diff --git a/src/SteamId.cpp b/src/SteamId.cpp index dfade86..6959fe2 100644 --- a/src/SteamId.cpp +++ b/src/SteamId.cpp @@ -1,9 +1,12 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "SteamId.h" // 76561197960493477 -> 113874 uint32 calcSteamID32(uint64 steamID64) { - const uint64 steamID64Base = 76561197960265728; + uint64 const steamID64Base = 76561197960265728; uint32 iSteamID32 = (steamID64 - steamID64Base); return iSteamID32; } diff --git a/src/SteamId.h b/src/SteamId.h index 690c22c..bed99e1 100644 --- a/src/SteamId.h +++ b/src/SteamId.h @@ -1,9 +1,14 @@ -#ifndef SteamID_H -#define SteamID_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef SRC_STEAMID_H_ +#define SRC_STEAMID_H_ + +#include +#include #include #include -#include + // 76561197960493477 -> 113874 uint32 calcSteamID32(uint64 steamID64); @@ -14,4 +19,4 @@ std::string toSteamID32(uint64 steamID64); // steamID32: STEAM_0:1:113874 std::string toSteamIDClassic(uint64 steamID64); -#endif \ No newline at end of file +#endif // SRC_STEAMID_H_ \ No newline at end of file diff --git a/src/VersionAndConstants.h b/src/VersionAndConstants.h index 7b9023c..28ee4c5 100644 --- a/src/VersionAndConstants.h +++ b/src/VersionAndConstants.h @@ -1,5 +1,8 @@ -#ifndef VersionAndConstants_H -#define VersionAndConstants_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_VERSIONANDCONSTANTS_H_ +#define SRC_VERSIONANDCONSTANTS_H_ // Application Name #define CSGO_CLI_BINARYNAME "csgo_cli" @@ -25,4 +28,4 @@ struct CSGO_CLI_TimeoutException { }; -#endif +#endif // SRC_VERSIONANDCONSTANTS_H_ diff --git a/src/VersionAndConstants.h.in b/src/VersionAndConstants.h.in index ab86e2e..70dce7d 100644 --- a/src/VersionAndConstants.h.in +++ b/src/VersionAndConstants.h.in @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #ifndef VersionAndConstants_H #define VersionAndConstants_H diff --git a/src/commands/cmd.globalstats.cpp b/src/commands/cmd.globalstats.cpp index aa16d93..6d3fa89 100644 --- a/src/commands/cmd.globalstats.cpp +++ b/src/commands/cmd.globalstats.cpp @@ -1,6 +1,9 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "cmd.globalstats.h" -bool requestGlobalStats(DataObject &data, bool &verbose) +bool requestGlobalStats(DataObject& data, bool& verbose) { if (verbose) { @@ -15,13 +18,17 @@ bool requestGlobalStats(DataObject &data, bool &verbose) std::this_thread::sleep_for(std::chrono::milliseconds(CSGO_CLI_STEAM_HELLO_DELAY)); CSGOMMHello mmhello; - if (verbose) spdlog::info(" Requesting: Hello"); + if (verbose) + spdlog::info(" Requesting: Hello"); mmhello.RefreshWait(); - if (verbose) spdlog::info(" Got Hello"); + if (verbose) + spdlog::info(" Got Hello"); result = true; - if (verbose) { spdlog::debug("mmhello.data.DebugString {}", mmhello.data.DebugString()); } + if (verbose) { + spdlog::debug("mmhello.data.DebugString {}", mmhello.data.DebugString()); + } data.global_stats.ongoing_matches = mmhello.data.global_stats().ongoing_matches(); data.global_stats.players_online = mmhello.data.global_stats().players_online(); @@ -31,16 +38,17 @@ bool requestGlobalStats(DataObject &data, bool &verbose) data.global_stats.search_time_avg = mmhello.data.global_stats().search_time_avg(); // Detailed Search Statistics (players searching per game_type) - //data.global_stats. mmhello.data.global_stats().search_statistics(); + // data.global_stats. mmhello.data.global_stats().search_statistics(); } catch (CSGO_CLI_TimeoutException) { printError("Warning", "Timeout on receiving UserInfo."); result = false; - } catch (ExceptionHandler &e) { + } catch (ExceptionHandler& e) { printError("Fatal error", e.what()); result = false; } - if (verbose) spdlog::info("[ End ] [ Thread ] getUserInfo"); + if (verbose) + spdlog::info("[ End ] [ Thread ] getUserInfo"); return 0; }); @@ -49,13 +57,13 @@ bool requestGlobalStats(DataObject &data, bool &verbose) return result; } -void printGlobalStats(DataObject &data) +void printGlobalStats(DataObject& data) { // ---------- Format Output Strings // ---------- Output Table - const auto printAligned{[=](const std::string &a, const std::string &b = "") { + auto const printAligned{[=](std::string const & a, std::string const & b = "") { return fmt::print(" {0:<23} {1}\n", a, b); }}; diff --git a/src/commands/cmd.globalstats.h b/src/commands/cmd.globalstats.h index d23e731..5df4cf5 100644 --- a/src/commands/cmd.globalstats.h +++ b/src/commands/cmd.globalstats.h @@ -1,13 +1,17 @@ -#ifndef CMD_GLOBALSTATS_H -#define CMD_GLOBALSTATS_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef SRC_COMMANDS_CMD_GLOBALSTATS_H_ +#define SRC_COMMANDS_CMD_GLOBALSTATS_H_ + +#include "../csgo/CSGOMMHello.h" #include "../DataObject.h" #include "../ErrorHandler.h" #include "../ExceptionHandler.h" #include "../VersionAndConstants.h" -#include "../csgo/CSGOMMHello.h" +#include -bool requestGlobalStats(DataObject &data, bool &verbose); -void printGlobalStats(DataObject &data); +bool requestGlobalStats(DataObject& data, bool& verbose); +void printGlobalStats(DataObject& data); -#endif \ No newline at end of file +#endif // SRC_COMMANDS_CMD_GLOBALSTATS_H_ \ No newline at end of file diff --git a/src/commands/cmd.help.cpp b/src/commands/cmd.help.cpp index c2697f5..62bb1c4 100644 --- a/src/commands/cmd.help.cpp +++ b/src/commands/cmd.help.cpp @@ -1,9 +1,12 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "cmd.help.h" void printHelp() { - const std::string binary = WinCliColors::formatLightGreen(CSGO_CLI_BINARYNAME); - const std::string version = WinCliColors::formatYellow(CSGO_CLI_VERSION); + std::string const binary = WinCliColors::formatLightGreen(CSGO_CLI_BINARYNAME); + std::string const version = WinCliColors::formatYellow(CSGO_CLI_VERSION); fmt::print("{} v{}, {}\n", binary, version, CSGO_CLI_WEBSITE); fmt::print("Copyright (c) 2018-{} Jens A. Koch.\n", getYear()); diff --git a/src/commands/cmd.help.h b/src/commands/cmd.help.h index c46bae7..2882c28 100644 --- a/src/commands/cmd.help.h +++ b/src/commands/cmd.help.h @@ -1,12 +1,16 @@ -#ifndef CMD_HELP_H -#define CMD_HELP_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_COMMANDS_CMD_HELP_H_ +#define SRC_COMMANDS_CMD_HELP_H_ #include "../DateTimeUtils.h" -#include "../VersionAndConstants.h" #include "../platform/windows/WinCliColors.h" +#include "../VersionAndConstants.h" #include +#include void printHelp(); -#endif \ No newline at end of file +#endif // SRC_COMMANDS_CMD_HELP_H_ \ No newline at end of file diff --git a/src/commands/cmd.matches.cpp b/src/commands/cmd.matches.cpp index a1a5bed..6cbc345 100644 --- a/src/commands/cmd.matches.cpp +++ b/src/commands/cmd.matches.cpp @@ -1,10 +1,15 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "cmd.matches.h" #include "spdlog/common.h" #include "spdlog/spdlog.h" -bool requestRecentMatches(DataObject &data, bool &verbose) +bool requestRecentMatches(DataObject& data, bool& verbose) { - if (verbose) { spdlog::info("[ Start ] [ Thread ] MatchList"); } + if (verbose) { + spdlog::info("[ Start ] [ Thread ] MatchList"); + } bool result = false; @@ -15,13 +20,19 @@ bool requestRecentMatches(DataObject &data, bool &verbose) // refresh match list CSGOMatchList matchList; - if (verbose) { spdlog::info(" -> requesting MatchList"); } + if (verbose) { + spdlog::info(" -> requesting MatchList"); + } matchList.RefreshWait(); - if (verbose) { spdlog::info(" -> got MatchList"); } + if (verbose) { + spdlog::info(" -> got MatchList"); + } result = true; - if (verbose) { spdlog::info("[ Start ] processing MatchList"); } + if (verbose) { + spdlog::info("[ Start ] processing MatchList"); + } // empty match history if (matchList.Matches().size() == 0) { @@ -32,9 +43,11 @@ bool requestRecentMatches(DataObject &data, bool &verbose) int matches_num = 1; - for (auto &match : matchList.Matches()) { + for (auto& match : matchList.Matches()) { - if (verbose) { spdlog::info("[ Start ] processing Match #{}", matches_num); } + if (verbose) { + spdlog::info("[ Start ] processing Match #{}", matches_num); + } CSGOMatchData parsedMatch; parsedMatch.matchid = match.matchid(); @@ -48,7 +61,9 @@ bool requestRecentMatches(DataObject &data, bool &verbose) parsedMatch.mapgroup = match.watchablematchinfo().game_mapgroup(); parsedMatch.game_type = match.watchablematchinfo().game_type(); // this is nowadays 0 - if (verbose) { spdlog::info("{}", match.DebugString()); } + if (verbose) { + spdlog::info("{}", match.DebugString()); + } // iterate roundstats CMsgGCCStrike15_v2_MatchmakingServerRoundStats roundStats; @@ -66,7 +81,7 @@ bool requestRecentMatches(DataObject &data, bool &verbose) } // ROUNDSTATS per player - for (auto &account_id : roundStats.reservation().account_ids()) { + for (auto& account_id : roundStats.reservation().account_ids()) { CSGOMatchPlayerScore player; player.index = matchList.getPlayerIndex(account_id, roundStats); @@ -82,7 +97,9 @@ bool requestRecentMatches(DataObject &data, bool &verbose) parsedMatch.scoreboard.push_back(player); - if (verbose) { spdlog::info("[ End ] Match-Player"); } + if (verbose) { + spdlog::info("[ End ] Match-Player"); + } } if (verbose) { @@ -112,20 +129,26 @@ bool requestRecentMatches(DataObject &data, bool &verbose) data.matches.push_back(parsedMatch); - if (verbose) { spdlog::info("[ End ] processing Match #{}", matches_num); } + if (verbose) { + spdlog::info("[ End ] processing Match #{}", matches_num); + } matches_num++; } } - if (verbose) { spdlog::info("[ End ] processing MatchList"); } + if (verbose) { + spdlog::info("[ End ] processing MatchList"); + } } catch (CSGO_CLI_TimeoutException) { printError("Warning", "Timeout on receiving MatchList."); result = false; - } catch (ExceptionHandler &e) { + } catch (ExceptionHandler& e) { printError("Fatal Error", e.what()); result = false; } - if (verbose) { spdlog::info("[ End ] [ Thread ] MatchList"); } + if (verbose) { + spdlog::info("[ End ] [ Thread ] MatchList"); + } return 0; }); @@ -135,7 +158,7 @@ bool requestRecentMatches(DataObject &data, bool &verbose) return result; } -void printMatches(DataObject &data) +void printMatches(DataObject& data) { fmt::print("\n Hello {}!\n\n", data.playername); @@ -150,19 +173,19 @@ void printMatches(DataObject &data) fmt::print(" Here are your {} latest matches:\n\n", data.num_matches_played); } - const auto printRow{[=](const std::string &s1, - const std::string &s2, - const std::string &s3, - const std::string &s4, - const std::string &s5, - const std::string &s6) { + auto const printRow{[=](std::string const & s1, + std::string const & s2, + std::string const & s3, + std::string const & s4, + std::string const & s5, + std::string const & s6) { return fmt::print("{0:^3} {1:<20} {2:^8} {3:^13} {4:^8} {5:^6} \n", s1, s2, s3, s4, s5, s6); }}; printRow("#", "Match Played", "Duration", "Map", "Score", "Result\n"); int i = 1; - for (const auto &match : data.matches) { + for (auto const & match : data.matches) { printRow( std::to_string(i), match.matchtime_str, diff --git a/src/commands/cmd.matches.h b/src/commands/cmd.matches.h index e527aab..0e6d729 100644 --- a/src/commands/cmd.matches.h +++ b/src/commands/cmd.matches.h @@ -1,17 +1,21 @@ -#ifndef CMD_MATCHES_H -#define CMD_MATCHES_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef SRC_COMMANDS_CMD_MATCHES_H_ +#define SRC_COMMANDS_CMD_MATCHES_H_ + +#include "../csgo/CSGOMatchList.h" #include "../DataObject.h" #include "../DateTimeUtils.h" #include "../ErrorHandler.h" #include "../ExceptionHandler.h" #include "../ShareCode.h" #include "../VersionAndConstants.h" -#include "../csgo/CSGOMatchList.h" +#include #include -bool requestRecentMatches(DataObject &data, bool &verbose); -void printMatches(DataObject &data); +bool requestRecentMatches(DataObject& data, bool& verbose); +void printMatches(DataObject& data); -#endif \ No newline at end of file +#endif // SRC_COMMANDS_CMD_MATCHES_H_ \ No newline at end of file diff --git a/src/commands/cmd.scoreboard.cpp b/src/commands/cmd.scoreboard.cpp index 80e439f..2f3152b 100644 --- a/src/commands/cmd.scoreboard.cpp +++ b/src/commands/cmd.scoreboard.cpp @@ -1,6 +1,9 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "cmd.scoreboard.h" -void printScoreboard(DataObject &data) +void printScoreboard(DataObject& data) { if (!data.has_matches_played) { fmt::print("\n Your CS:GO match history is empty.\n"); @@ -11,17 +14,17 @@ void printScoreboard(DataObject &data) //{0:^3} {1:<20} {2:^8} {3:^5} {4:<9} {5:<7} - const auto printRow{[=](const std::string &s1, - const std::string &s2, - const std::string &s3, - const std::string &s4, - const std::string &s5, - const std::string &s6, - const std::string &s7, - const std::string &s8, - const std::string &s9, - const std::string &s10, - const std::string &s11) { + auto const printRow{[=](std::string const & s1, + std::string const & s2, + std::string const & s3, + std::string const & s4, + std::string const & s5, + std::string const & s6, + std::string const & s7, + std::string const & s8, + std::string const & s9, + std::string const & s10, + std::string const & s11) { return fmt::print( " {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} \n", s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11); }}; @@ -31,8 +34,8 @@ void printScoreboard(DataObject &data) printRow("Match Played", "Result", "Score", "K", "A", "D", "HS(%)", "K/D", "Rating", "MVP", "Score"); - for (const auto &match : data.matches) { - for (const auto &player : match.scoreboard) { + for (auto const & match : data.matches) { + for (auto const & player : match.scoreboard) { if (player.account_id == data.account_id) { fmt::print("{}\n", match.matchtime_str); /*printRow( diff --git a/src/commands/cmd.scoreboard.h b/src/commands/cmd.scoreboard.h index 2c6a503..4f77d56 100644 --- a/src/commands/cmd.scoreboard.h +++ b/src/commands/cmd.scoreboard.h @@ -1,9 +1,13 @@ -#ifndef CMD_SCOREBOARD_H -#define CMD_SCOREBOARD_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_COMMANDS_CMD_SCOREBOARD_H_ +#define SRC_COMMANDS_CMD_SCOREBOARD_H_ #include "../DataObject.h" #include +#include -void printScoreboard(DataObject &data); +void printScoreboard(DataObject& data); -#endif \ No newline at end of file +#endif // SRC_COMMANDS_CMD_SCOREBOARD_H_ \ No newline at end of file diff --git a/src/commands/cmd.upload.cpp b/src/commands/cmd.upload.cpp index fc58e37..11144d8 100644 --- a/src/commands/cmd.upload.cpp +++ b/src/commands/cmd.upload.cpp @@ -1,6 +1,9 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "cmd.upload.h" -static inline void uploadShareCode(std::string &sharecode, ShareCodeCache *matchCache, ShareCodeUpload *codeUpload) +static inline void uploadShareCode(std::string& sharecode, ShareCodeCache* matchCache, ShareCodeUpload* codeUpload) { if (matchCache->find(sharecode)) { auto msg1 = fmt::format(fmt::fg(fmt::color::indian_red), "Skipped."); @@ -27,7 +30,7 @@ static inline void uploadShareCode(std::string &sharecode, ShareCodeCache *match } } -void uploadReplayShareCodes(DataObject &data, bool &verbose) +void uploadReplayShareCodes(DataObject& data, bool& verbose) { if (!data.has_matches_played) { printRed(" No replay sharecodes to upload.\n"); @@ -37,20 +40,20 @@ void uploadReplayShareCodes(DataObject &data, bool &verbose) fmt::print( "\n Uploading Replay ShareCode{} to https://csgostats.gg/: \n\n", (data.num_matches_played == 1) ? "" : "s"); - ShareCodeCache *matchCache = new ShareCodeCache(verbose); - ShareCodeUpload *codeUpload = new ShareCodeUpload(verbose); + ShareCodeCache* matchCache = new ShareCodeCache(verbose); + ShareCodeUpload* codeUpload = new ShareCodeUpload(verbose); - for (auto &match : data.matches) { + for (auto& match : data.matches) { uploadShareCode(match.sharecode, matchCache, codeUpload); } } -void uploadSingleShareCode(std::string &sharecode, bool &verbose) +void uploadSingleShareCode(std::string& sharecode, bool& verbose) { printTerminalYellow("\n Uploading Single Replay ShareCode to https://csgostats.gg/: \n\n"); - ShareCodeCache *matchCache = new ShareCodeCache(verbose); - ShareCodeUpload *codeUpload = new ShareCodeUpload(verbose); + ShareCodeCache* matchCache = new ShareCodeCache(verbose); + ShareCodeUpload* codeUpload = new ShareCodeUpload(verbose); uploadShareCode(sharecode, matchCache, codeUpload); } \ No newline at end of file diff --git a/src/commands/cmd.upload.h b/src/commands/cmd.upload.h index 9d3300e..22b9323 100644 --- a/src/commands/cmd.upload.h +++ b/src/commands/cmd.upload.h @@ -1,14 +1,19 @@ -#ifndef CMD_UPLOAD_H -#define CMD_UPLOAD_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_COMMANDS_CMD_UPLOAD_H_ +#define SRC_COMMANDS_CMD_UPLOAD_H_ -#include "../DataObject.h" -#include "../ErrorHandler.h" #include "../csgostats/ShareCodeCache.h" #include "../csgostats/ShareCodeUpload.h" +#include "../DataObject.h" +#include "../ErrorHandler.h" + +#include -static inline void uploadShareCode(std::string &sharecode, ShareCodeCache *matchCache, ShareCodeUpload *codeUpload); +static inline void uploadShareCode(std::string& sharecode, ShareCodeCache* matchCache, ShareCodeUpload* codeUpload); -void uploadReplayShareCodes(DataObject &data, bool &verbose); -void uploadSingleShareCode(std::string &sharecode, bool &verbose); +void uploadReplayShareCodes(DataObject& data, bool& verbose); +void uploadSingleShareCode(std::string& sharecode, bool& verbose); -#endif +#endif // SRC_COMMANDS_CMD_UPLOAD_H_ diff --git a/src/commands/cmd.user.cpp b/src/commands/cmd.user.cpp index 0934ad9..518a8b1 100644 --- a/src/commands/cmd.user.cpp +++ b/src/commands/cmd.user.cpp @@ -1,9 +1,13 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "cmd.user.h" #include "cstrike15_gcmessages.pb.h" -bool requestPlayersProfile(DataObject &data, bool &verbose) +bool requestPlayersProfile(DataObject& data, bool& verbose) { - if (verbose) spdlog::info("[ Start ] [ Thread ] getUserInfo"); + if (verbose) + spdlog::info("[ Start ] [ Thread ] getUserInfo"); bool result = false; @@ -12,13 +16,17 @@ bool requestPlayersProfile(DataObject &data, bool &verbose) std::this_thread::sleep_for(std::chrono::milliseconds(CSGO_CLI_STEAM_HELLO_DELAY)); CSGOMMHello mmhello; - if (verbose) spdlog::info(" Requesting: Hello"); + if (verbose) + spdlog::info(" Requesting: Hello"); mmhello.RefreshWait(); - if (verbose) spdlog::info(" Got Hello"); + if (verbose) + spdlog::info(" Got Hello"); result = true; - if (verbose) { spdlog::debug("mmhello.data.DebugString {}", mmhello.data.DebugString()); } + if (verbose) { + spdlog::debug("mmhello.data.DebugString {}", mmhello.data.DebugString()); + } // player level data.player_level = mmhello.data.player_level(); @@ -57,11 +65,12 @@ bool requestPlayersProfile(DataObject &data, bool &verbose) } catch (CSGO_CLI_TimeoutException) { printError("Warning", "Timeout on receiving UserInfo."); result = false; - } catch (ExceptionHandler &e) { + } catch (ExceptionHandler& e) { printError("Fatal error", e.what()); result = false; } - if (verbose) spdlog::info("[ End ] [ Thread ] getUserInfo"); + if (verbose) + spdlog::info("[ End ] [ Thread ] getUserInfo"); return 0; }); @@ -70,9 +79,10 @@ bool requestPlayersProfile(DataObject &data, bool &verbose) return result; } -bool requestPlayersRankInfo(DataObject &data, bool &verbose) +bool requestPlayersRankInfo(DataObject& data, bool& verbose) { - if (verbose) spdlog::info("[ Start ] [ Thread ] requestPlayersRankInfo"); + if (verbose) + spdlog::info("[ Start ] [ Thread ] requestPlayersRankInfo"); bool result = false; @@ -82,15 +92,19 @@ bool requestPlayersRankInfo(DataObject &data, bool &verbose) CSGORankUpdate rankUpdate; - if (verbose) spdlog::info(" Requesting: rankUpdate for Wingman"); + if (verbose) + spdlog::info(" Requesting: rankUpdate for Wingman"); rankUpdate.RefreshWaitWingmanRank(); - if (verbose) spdlog::info(" Got rankUpdate for Wingman"); + if (verbose) + spdlog::info(" Got rankUpdate for Wingman"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - if (verbose) spdlog::info(" Requesting: rankUpdate for DangerZone"); + if (verbose) + spdlog::info(" Requesting: rankUpdate for DangerZone"); rankUpdate.RefreshWaitDangerZoneRank(); - if (verbose) spdlog::info(" Got rankUpdate for DangerZone"); + if (verbose) + spdlog::info(" Got rankUpdate for DangerZone"); result = true; @@ -122,11 +136,12 @@ bool requestPlayersRankInfo(DataObject &data, bool &verbose) } catch (CSGO_CLI_TimeoutException) { printError("Warning", "Timeout on receiving RankUpdate."); result = false; - } catch (ExceptionHandler &e) { + } catch (ExceptionHandler& e) { printError("Fatal error", e.what()); result = false; } - if (verbose) spdlog::info("[ End ] [ Thread ] rankUpdate"); + if (verbose) + spdlog::info("[ End ] [ Thread ] rankUpdate"); return 0; }); @@ -135,7 +150,7 @@ bool requestPlayersRankInfo(DataObject &data, bool &verbose) return result; } -void printPlayersProfile(DataObject &data) +void printPlayersProfile(DataObject& data) { // ---------- Format Output Strings @@ -168,13 +183,13 @@ void printPlayersProfile(DataObject &data) std::string dangerzone_rank = fmt::format("{} ({}/18) ({} wins)", dz_rank_name, dz_ranks.id, dz_ranks.wins); - // TODO how to access medals data? + // @todo(jakoch): how to access medals data? // auto medals = fmt::format("{} x arms, {} x combat, {} x global, {} x team, {} x weapon", // data.medals_arms, data.medals_combat, data.medals_global, data.medals_team, data.medals_weapon); // ---------- Output Table - const auto printAligned{[=](const std::string &a, const std::string &b = "") { + auto const printAligned{[=](std::string const & a, std::string const & b = "") { return fmt::print(" {0:<18} {1}\n", a, b); }}; diff --git a/src/commands/cmd.user.h b/src/commands/cmd.user.h index 7d1cb25..cd870fc 100644 --- a/src/commands/cmd.user.h +++ b/src/commands/cmd.user.h @@ -1,16 +1,21 @@ -#ifndef CMD_USER_H -#define CMD_USER_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef SRC_COMMANDS_CMD_USER_H_ +#define SRC_COMMANDS_CMD_USER_H_ + +#include "../csgo/CSGOMMHello.h" +#include "../csgo/CSGORankUpdate.h" #include "../DataObject.h" #include "../ErrorHandler.h" #include "../ExceptionHandler.h" #include "../SteamId.h" #include "../VersionAndConstants.h" -#include "../csgo/CSGOMMHello.h" -#include "../csgo/CSGORankUpdate.h" -bool requestPlayersProfile(DataObject &data, bool &verbose); -bool requestPlayersRankInfo(DataObject &data, bool &verbose); -void printPlayersProfile(DataObject &data); +#include + +bool requestPlayersProfile(DataObject& data, bool& verbose); +bool requestPlayersRankInfo(DataObject& data, bool& verbose); +void printPlayersProfile(DataObject& data); -#endif \ No newline at end of file +#endif // SRC_COMMANDS_CMD_USER_H_ \ No newline at end of file diff --git a/src/csgo/CSGOClient.cpp b/src/csgo/CSGOClient.cpp index c3c344b..d0ec096 100644 --- a/src/csgo/CSGOClient.cpp +++ b/src/csgo/CSGOClient.cpp @@ -1,15 +1,18 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "CSGOClient.h" -static const uint32_t ProtobufFlag = (1 << 31); -CSGOClient *CSGOClient::m_instance = nullptr; +static uint32_t const ProtobufFlag = (1 << 31); +CSGOClient* CSGOClient::m_instance = nullptr; CSGOClient::CSGOClient() : m_welcomeHandler(this, &CSGOClient::OnClientWelcome), m_availableCb(this, &CSGOClient::OnMessageAvailable), m_failedCb(this, &CSGOClient::OnMessageFailed) { - m_gameCoordinator = (ISteamGameCoordinator *)SteamClient()->GetISteamGenericInterface( - SteamAPI_GetHSteamUser(), SteamAPI_GetHSteamPipe(), STEAMGAMECOORDINATOR_INTERFACE_VERSION); + m_gameCoordinator = reinterpret_cast(SteamClient()->GetISteamGenericInterface( + SteamAPI_GetHSteamUser(), SteamAPI_GetHSteamPipe(), STEAMGAMECOORDINATOR_INTERFACE_VERSION)); RegisterHandler(k_EMsgGCClientWelcome, &m_welcomeHandler); @@ -21,7 +24,7 @@ CSGOClient::CSGOClient() : } } -EGCResults CSGOClient::SendGCMessage(uint32_t uMsgType, google::protobuf::Message *msg) +EGCResults CSGOClient::SendGCMessage(uint32_t uMsgType, google::protobuf::Message* msg) { std::lock_guard lock(m_sendMutex); @@ -33,24 +36,28 @@ EGCResults CSGOClient::SendGCMessage(uint32_t uMsgType, google::protobuf::Messag auto size = body_size + 2 * sizeof(uint32_t); - if (m_msgBuffer.size() < size) { m_msgBuffer.resize(size); } + if (m_msgBuffer.size() < size) { + m_msgBuffer.resize(size); + } uMsgType |= ProtobufFlag; - ((uint32_t *)m_msgBuffer.data())[0] = uMsgType; - ((uint32_t *)m_msgBuffer.data())[1] = 0; + reinterpret_cast(m_msgBuffer.data())[0] = uMsgType; + reinterpret_cast(m_msgBuffer.data())[1] = 0; msg->SerializeToArray(m_msgBuffer.data() + 2 * sizeof(uint32_t), m_msgBuffer.size() - 2 * sizeof(uint32_t)); return m_gameCoordinator->SendMessage(uMsgType, m_msgBuffer.data(), size); } -void CSGOClient::OnMessageAvailable(GCMessageAvailable_t *msg) +void CSGOClient::OnMessageAvailable(GCMessageAvailable_t* msg) { std::lock_guard lock(m_recvMutex); std::lock_guard lock2(m_handlerMutex); - if (m_recvBuffer.size() < msg->m_nMessageSize) { m_recvBuffer.resize(msg->m_nMessageSize); } + if (m_recvBuffer.size() < msg->m_nMessageSize) { + m_recvBuffer.resize(msg->m_nMessageSize); + } uint32_t msgType; uint32_t msgSize; @@ -68,18 +75,18 @@ void CSGOClient::OnMessageAvailable(GCMessageAvailable_t *msg) } } -void CSGOClient::OnMessageFailed(GCMessageFailed_t *msg) +void CSGOClient::OnMessageFailed(GCMessageFailed_t* msg) { throw ExceptionHandler("Failed to deliver GC message"); } -void CSGOClient::RegisterHandler(uint32 msgId, IGCMsgHandler *handler) +void CSGOClient::RegisterHandler(uint32 msgId, IGCMsgHandler* handler) { std::lock_guard lock(m_handlerMutex); m_msgHandler.insert({msgId, handler}); } -void CSGOClient::RemoveHandler(uint32 msgId, IGCMsgHandler *handler) +void CSGOClient::RemoveHandler(uint32 msgId, IGCMsgHandler* handler) { std::lock_guard lock(m_handlerMutex); @@ -93,9 +100,11 @@ void CSGOClient::RemoveHandler(uint32 msgId, IGCMsgHandler *handler) } } -CSGOClient *CSGOClient::GetInstance() +CSGOClient* CSGOClient::GetInstance() { - if (!m_instance) { m_instance = new CSGOClient(); } + if (!m_instance) { + m_instance = new CSGOClient(); + } return m_instance; } @@ -108,7 +117,9 @@ void CSGOClient::Destroy() void CSGOClient::WaitForGameClientConnect() { - if (m_connectedToGameClient) { return; } + if (m_connectedToGameClient) { + return; + } std::unique_lock lock(m_connectedMutex); // if this takes longer than 10 seconds we are already connected to the gc @@ -116,7 +127,7 @@ void CSGOClient::WaitForGameClientConnect() m_connectedToGameClient = true; } -void CSGOClient::OnClientWelcome(const CMsgClientWelcome &msg) +void CSGOClient::OnClientWelcome(CMsgClientWelcome const & msg) { // printf("Received welcome CS:GO Game Coordinator version %s (Connected to %s).", // std::to_string(msg.version()).c_str(), msg.location().country().c_str()); diff --git a/src/csgo/CSGOClient.h b/src/csgo/CSGOClient.h index 5bc238f..5561a99 100644 --- a/src/csgo/CSGOClient.h +++ b/src/csgo/CSGOClient.h @@ -1,5 +1,8 @@ -#ifndef CSGOClient_H -#define CSGOClient_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_CSGOCLIENT_H_ +#define SRC_CSGO_CSGOCLIENT_H_ // Steamworks SDK #pragma warning(disable : 4996) @@ -31,7 +34,7 @@ class CSGOClient /** * Retrieves the instance to the current csgo client or creates a new one */ - static CSGOClient *GetInstance(); + static CSGOClient* GetInstance(); /** * Destroys the csgo client @@ -41,17 +44,17 @@ class CSGOClient /** * Sends a gc protobuf message */ - EGCResults SendGCMessage(uint32 uMsgType, google::protobuf::Message *msg); + EGCResults SendGCMessage(uint32 uMsgType, google::protobuf::Message* msg); /** * Registers a gc protobuf msg handler */ - void RegisterHandler(uint32 msgId, IGCMsgHandler *handler); + void RegisterHandler(uint32 msgId, IGCMsgHandler* handler); /** * Removes a gc protobuf msg handler */ - void RemoveHandler(uint32 msgId, IGCMsgHandler *handler); + void RemoveHandler(uint32 msgId, IGCMsgHandler* handler); /** * Blocks until we are connected to the GameClient @@ -63,32 +66,32 @@ class CSGOClient * Sends client mm hello */ CSGOClient(); - CSGOClient(const CSGOClient &) = delete; + CSGOClient(CSGOClient const &) = delete; /** * Steam callback for gc messages */ - void OnMessageAvailable(GCMessageAvailable_t *msg); + void OnMessageAvailable(GCMessageAvailable_t* msg); /** * Steam callback for failed gc messages */ - void OnMessageFailed(GCMessageFailed_t *msg); + void OnMessageFailed(GCMessageFailed_t* msg); /** * Handles the gc welcome msg */ - void OnClientWelcome(const CMsgClientWelcome &msg); + void OnClientWelcome(CMsgClientWelcome const & msg); private: - static CSGOClient *m_instance; + static CSGOClient* m_instance; GCMsgHandler m_welcomeHandler; std::condition_variable m_connectedCV; std::mutex m_connectedMutex; bool m_connectedToGameClient = false; - ISteamGameCoordinator *m_gameCoordinator; + ISteamGameCoordinator* m_gameCoordinator; CCallback m_availableCb; CCallback m_failedCb; @@ -97,7 +100,7 @@ class CSGOClient std::mutex m_sendMutex; std::mutex m_recvMutex; std::mutex m_handlerMutex; - std::multimap m_msgHandler; + std::multimap m_msgHandler; }; -#endif +#endif // SRC_CSGO_CSGOCLIENT_H_ diff --git a/src/csgo/CSGOMMHello.cpp b/src/csgo/CSGOMMHello.cpp index 5902944..fead236 100644 --- a/src/csgo/CSGOMMHello.cpp +++ b/src/csgo/CSGOMMHello.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "CSGOMMHello.h" #include "../ExceptionHandler.h" #include "../VersionAndConstants.h" @@ -14,7 +17,7 @@ CSGOMMHello::~CSGOMMHello() CSGOClient::GetInstance()->RemoveHandler(k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello, &m_mmhelloHandler); } -void CSGOMMHello::OnMMHello(const CMsgGCCStrike15_v2_MatchmakingGC2ClientHello &msg) +void CSGOMMHello::OnMMHello(CMsgGCCStrike15_v2_MatchmakingGC2ClientHello const & msg) { std::unique_lock lock(m_mmhelloMutex); data = msg; @@ -40,5 +43,7 @@ void CSGOMMHello::RefreshWait() m_updateCv.wait_for(lock, std::chrono::milliseconds(CSGO_CLI_STEAM_CMSG_TIMEOUT)); - if (!m_updateComplete) { throw CSGO_CLI_TimeoutException(); } + if (!m_updateComplete) { + throw CSGO_CLI_TimeoutException(); + } } diff --git a/src/csgo/CSGOMMHello.h b/src/csgo/CSGOMMHello.h index ceba485..9f3f1d8 100644 --- a/src/csgo/CSGOMMHello.h +++ b/src/csgo/CSGOMMHello.h @@ -1,5 +1,8 @@ -#ifndef CSGOMMHello_H -#define CSGOMMHello_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_CSGOMMHELLO_H_ +#define SRC_CSGO_CSGOMMHELLO_H_ #include "CSGOClient.h" @@ -17,7 +20,7 @@ class CSGOMMHello CMsgGCCStrike15_v2_MatchmakingGC2ClientHello data; private: - void OnMMHello(const CMsgGCCStrike15_v2_MatchmakingGC2ClientHello &msg); + void OnMMHello(CMsgGCCStrike15_v2_MatchmakingGC2ClientHello const & msg); private: bool m_updateComplete = false; @@ -26,4 +29,4 @@ class CSGOMMHello GCMsgHandler m_mmhelloHandler; }; -#endif +#endif // SRC_CSGO_CSGOMMHELLO_H_ diff --git a/src/csgo/CSGOMatchData.h b/src/csgo/CSGOMatchData.h index 3bfb10e..96654f0 100644 --- a/src/csgo/CSGOMatchData.h +++ b/src/csgo/CSGOMatchData.h @@ -1,5 +1,8 @@ -#ifndef CSGOMatchData_H -#define CSGOMatchData_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_CSGOMATCHDATA_H_ +#define SRC_CSGO_CSGOMATCHDATA_H_ #include #include @@ -13,7 +16,7 @@ struct CSGOMatchData { private: - // TODO find out, if this is correct? + // TODO(jakoch): find out, if this is correct? // the idea is that "lastRound.reservation.game_type" is the "map_name" enum GameTypes { @@ -59,7 +62,7 @@ struct CSGOMatchData case GameTypes::de_workout: return "de_workout"; // omit default case to trigger compiler warning for missing cases - }; + } return std::to_string(static_cast(game_type)); }; @@ -98,7 +101,7 @@ struct CSGOMatchData return fmt::format("{:02} : {:02}", score_ally, score_enemy); } - // TODO how to get mapname? + // @todo(jakoch): how to get mapname? std::string getMapname() const { return (map.empty() ? "? " : map); @@ -121,4 +124,4 @@ struct CSGOMatchData } }; -#endif +#endif // SRC_CSGO_CSGOMATCHDATA_H_ diff --git a/src/csgo/CSGOMatchList.cpp b/src/csgo/CSGOMatchList.cpp index 6978346..aeb47aa 100644 --- a/src/csgo/CSGOMatchList.cpp +++ b/src/csgo/CSGOMatchList.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "CSGOMatchList.h" #include "../ExceptionHandler.h" #include "../VersionAndConstants.h" @@ -20,14 +23,14 @@ CSGOMatchList::~CSGOMatchList() { CMsgGCCStrike15_v2_MatchList matchlist; - for (auto &m : m_matches) { + for (auto& m : m_matches) { matchlist.add_matches()->CopyFrom(m); } CSGOClient::GetInstance()->RemoveHandler(k_EMsgGCCStrike15_v2_MatchList, &m_matchListHandler); } -void CSGOMatchList::OnMatchList(const CMsgGCCStrike15_v2_MatchList &msg) +void CSGOMatchList::OnMatchList(CMsgGCCStrike15_v2_MatchList const & msg) { std::unique_lock lock(m_matchMutex); @@ -42,7 +45,7 @@ void CSGOMatchList::OnMatchList(const CMsgGCCStrike15_v2_MatchList &msg) void CSGOMatchList::Refresh() { - const uint32 accountId = SteamUser()->GetSteamID().GetAccountID(); + uint32 const accountId = SteamUser()->GetSteamID().GetAccountID(); CMsgGCCStrike15_v2_MatchListRequestRecentUserGames request; request.set_accountid(accountId); @@ -61,47 +64,55 @@ void CSGOMatchList::RefreshWait() m_updateCv.wait_for(lock, std::chrono::milliseconds(CSGO_CLI_STEAM_CMSG_TIMEOUT)); - if (!m_updateComplete) { throw CSGO_CLI_TimeoutException(); } + if (!m_updateComplete) { + throw CSGO_CLI_TimeoutException(); + } } -const std::vector &CSGOMatchList::Matches() const +std::vector const & CSGOMatchList::Matches() const { std::lock_guard lock(m_matchMutex); return m_matches; } -int CSGOMatchList::getOwnIndex(const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const +int CSGOMatchList::getOwnIndex(CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const { - const uint32 accountId = SteamUser()->GetSteamID().GetAccountID(); + uint32 const accountId = SteamUser()->GetSteamID().GetAccountID(); for (int i = 0; i < roundStats.reservation().account_ids().size(); ++i) { - if (roundStats.reservation().account_ids(i) == accountId) { return i; } + if (roundStats.reservation().account_ids(i) == accountId) { + return i; + } } throw ExceptionHandler("Unable to find own AccountID in matchinfo."); } int CSGOMatchList::getPlayerIndex( - uint32 accountId, const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const + uint32 accountId, CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const { for (int i = 0; i < roundStats.reservation().account_ids().size(); ++i) { - if (roundStats.reservation().account_ids(i) == accountId) { return i; } + if (roundStats.reservation().account_ids(i) == accountId) { + return i; + } } throw ExceptionHandler("Unable to find specified AccountID in matchinfo."); } -std::string CSGOMatchList::getMatchResult(const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const +std::string CSGOMatchList::getMatchResult(CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const { - const int num = getMatchResultNum(roundStats); - if (num == 0) return "TIE"; - if (num == 1) return "WIN"; + int const num = getMatchResultNum(roundStats); + if (num == 0) + return "TIE"; + if (num == 1) + return "WIN"; return "LOSS"; } -int CSGOMatchList::getMatchResultNum(const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const +int CSGOMatchList::getMatchResultNum(CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const { - const auto ownIndex = getOwnIndex(roundStats); + auto const ownIndex = getOwnIndex(roundStats); if (roundStats.match_result() == 0) { return 0; // tie } diff --git a/src/csgo/CSGOMatchList.h b/src/csgo/CSGOMatchList.h index 4f215d6..04e43aa 100644 --- a/src/csgo/CSGOMatchList.h +++ b/src/csgo/CSGOMatchList.h @@ -1,9 +1,14 @@ -#ifndef CSGOMatchList_H -#define CSGOMatchList_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_CSGOMATCHLIST_H_ +#define SRC_CSGO_CSGOMATCHLIST_H_ #include "CSGOClient.h" #include +#include +#include /** * utility class to store and update the match list @@ -17,17 +22,17 @@ class CSGOMatchList void Refresh(); void RefreshWait(); - const std::vector &Matches() const; + std::vector const & Matches() const; - int getOwnIndex(const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const; - int getPlayerIndex(uint32 accountId, const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const; - std::string getMatchResult(const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const; - int getMatchResultNum(const CMsgGCCStrike15_v2_MatchmakingServerRoundStats &roundStats) const; + int getOwnIndex(CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const; + int getPlayerIndex(uint32 accountId, CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const; + std::string getMatchResult(CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const; + int getMatchResultNum(CMsgGCCStrike15_v2_MatchmakingServerRoundStats const & roundStats) const; CMsgGCCStrike15_v2_MatchList matchList; private: - void OnMatchList(const CMsgGCCStrike15_v2_MatchList &msg); + void OnMatchList(CMsgGCCStrike15_v2_MatchList const & msg); private: bool m_updateComplete = false; @@ -37,4 +42,4 @@ class CSGOMatchList GCMsgHandler m_matchListHandler; }; -#endif +#endif // SRC_CSGO_CSGOMATCHLIST_H_ diff --git a/src/csgo/CSGOMatchPlayerScore.cpp b/src/csgo/CSGOMatchPlayerScore.cpp index db04978..2a4975a 100644 --- a/src/csgo/CSGOMatchPlayerScore.cpp +++ b/src/csgo/CSGOMatchPlayerScore.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "CSGOMatchPlayerScore.h" std::string CSGOMatchPlayerScore::getKillDeathRatio() const diff --git a/src/csgo/CSGOMatchPlayerScore.h b/src/csgo/CSGOMatchPlayerScore.h index 9f2831e..74ee772 100644 --- a/src/csgo/CSGOMatchPlayerScore.h +++ b/src/csgo/CSGOMatchPlayerScore.h @@ -1,8 +1,12 @@ -#ifndef CSGOMatchPlayerScore_H -#define CSGOMatchPlayerScore_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_CSGOMATCHPLAYERSCORE_H_ +#define SRC_CSGO_CSGOMATCHPLAYERSCORE_H_ #include "CSGOClient.h" #include +#include /** * This struct represents the PlayerScoreboard. @@ -31,4 +35,4 @@ struct CSGOMatchPlayerScore std::string getScore() const; }; -#endif +#endif // SRC_CSGO_CSGOMATCHPLAYERSCORE_H_ diff --git a/src/csgo/CSGORankUpdate.cpp b/src/csgo/CSGORankUpdate.cpp index 9cae9e4..617ac0e 100644 --- a/src/csgo/CSGORankUpdate.cpp +++ b/src/csgo/CSGORankUpdate.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "CSGORankUpdate.h" #include "../ExceptionHandler.h" #include "../VersionAndConstants.h" @@ -14,7 +17,7 @@ CSGORankUpdate::~CSGORankUpdate() CSGOClient::GetInstance()->RemoveHandler(k_EMsgGCCStrike15_v2_ClientGCRankUpdate, &m_rankUpdateHandler); } -void CSGORankUpdate::OnRankUpdate(const CMsgGCCStrike15_v2_ClientGCRankUpdate &msg) +void CSGORankUpdate::OnRankUpdate(CMsgGCCStrike15_v2_ClientGCRankUpdate const & msg) { std::unique_lock lock(m_rankUpdateMutex); data.push_back(msg); @@ -51,7 +54,9 @@ void CSGORankUpdate::RefreshWaitWingmanRank() m_updateCv.wait_for(lock, std::chrono::milliseconds(CSGO_CLI_STEAM_CMSG_TIMEOUT + 10000)); - if (!m_updateComplete) { throw CSGO_CLI_TimeoutException(); } + if (!m_updateComplete) { + throw CSGO_CLI_TimeoutException(); + } } void CSGORankUpdate::RefreshWaitDangerZoneRank() @@ -62,5 +67,7 @@ void CSGORankUpdate::RefreshWaitDangerZoneRank() m_updateCv.wait_for(lock, std::chrono::milliseconds(CSGO_CLI_STEAM_CMSG_TIMEOUT + 10000)); - if (!m_updateComplete) { throw CSGO_CLI_TimeoutException(); } + if (!m_updateComplete) { + throw CSGO_CLI_TimeoutException(); + } } diff --git a/src/csgo/CSGORankUpdate.h b/src/csgo/CSGORankUpdate.h index 2f51ef0..21d3d8e 100644 --- a/src/csgo/CSGORankUpdate.h +++ b/src/csgo/CSGORankUpdate.h @@ -1,9 +1,13 @@ -#ifndef CSGORankUpdate_H -#define CSGORankUpdate_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_CSGORANKUPDATE_H_ +#define SRC_CSGO_CSGORANKUPDATE_H_ #include "CSGOClient.h" #include +#include class CSGORankUpdate { @@ -20,7 +24,7 @@ class CSGORankUpdate std::vector data; private: - void OnRankUpdate(const CMsgGCCStrike15_v2_ClientGCRankUpdate &msg); + void OnRankUpdate(CMsgGCCStrike15_v2_ClientGCRankUpdate const & msg); private: bool m_updateComplete = false; @@ -29,4 +33,4 @@ class CSGORankUpdate GCMsgHandler m_rankUpdateHandler; }; -#endif \ No newline at end of file +#endif // SRC_CSGO_CSGORANKUPDATE_H_ \ No newline at end of file diff --git a/src/csgo/GCMsgHandler.h b/src/csgo/GCMsgHandler.h index 5eaf131..f810ce5 100644 --- a/src/csgo/GCMsgHandler.h +++ b/src/csgo/GCMsgHandler.h @@ -1,11 +1,14 @@ -#ifndef GCMsgHandler_H -#define GCMsgHandler_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGO_GCMSGHANDLER_H_ +#define SRC_CSGO_GCMSGHANDLER_H_ #include struct IGCMsgHandler { - virtual void Handle(void *buf, size_t len) const = 0; + virtual void Handle(void* buf, size_t len) const = 0; }; template @@ -15,13 +18,13 @@ template class GCMsgHandler : public IGCMsgHandler { public: - using CallbackThread = std::function; + using CallbackThread = std::function; template /** * Construct from class handler */ - GCMsgHandler(C *instance, void (C::*handler)(const M &)) + GCMsgHandler(C* instance, void (C::*handler)(M const &)) { m_handler = std::bind(std::mem_fn(handler), instance, std::placeholders::_1); } @@ -30,14 +33,14 @@ class GCMsgHandler : public IGCMsgHandler /** * Construct from functor */ - GCMsgHandler(const F &handler) : m_handler(handler) + explicit GCMsgHandler(F const & handler) : m_handler(handler) { } /** * Try parsing msg from buffer and call handler */ - virtual void Handle(void *buf, size_t len) const final + /*virtual*/ void Handle(void* buf, size_t len) const final { M msg; msg.ParseFromArray(buf, len); @@ -48,4 +51,4 @@ class GCMsgHandler : public IGCMsgHandler CallbackThread m_handler; }; -#endif +#endif // SRC_CSGO_GCMSGHANDLER_H_ diff --git a/src/csgostats/ShareCodeCache.cpp b/src/csgostats/ShareCodeCache.cpp index 96fc8ec..cdbe9b5 100644 --- a/src/csgostats/ShareCodeCache.cpp +++ b/src/csgostats/ShareCodeCache.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "ShareCodeCache.h" ShareCodeCache::ShareCodeCache(bool verboseMode) @@ -15,7 +18,7 @@ ShareCodeCache::ShareCodeCache(bool verboseMode) if (verboseMode) { // debug print sharecode cache printf(" Cached Sharecodes: %zd \n", sharecodeCache.size()); - for (auto const &sharecode : sharecodeCache) { + for (auto const & sharecode : sharecodeCache) { printf(" \"%s\" \n", sharecode.c_str()); } printf("\n"); @@ -30,8 +33,10 @@ ShareCodeCache::ShareCodeCache(bool verboseMode) bool ShareCodeCache::find(std::string sharecode) { - for (auto const &sharecodeFromCache : sharecodeCache) { - if (sharecode.compare(sharecodeFromCache.c_str()) == 0) { return true; } + for (auto const & sharecodeFromCache : sharecodeCache) { + if (sharecode.compare(sharecodeFromCache.c_str()) == 0) { + return true; + } } return false; } @@ -47,7 +52,7 @@ bool ShareCodeCache::insert(std::string sharecode) return false; } -std::vector ShareCodeCache::read(std::istream &is) +std::vector ShareCodeCache::read(std::istream& is) { std::vector tokens; std::string token; diff --git a/src/csgostats/ShareCodeCache.h b/src/csgostats/ShareCodeCache.h index 27f5e2f..ddc334a 100644 --- a/src/csgostats/ShareCodeCache.h +++ b/src/csgostats/ShareCodeCache.h @@ -1,5 +1,8 @@ -#ifndef ShareCodeCache_H -#define ShareCodeCache_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGOSTATS_SHARECODECACHE_H_ +#define SRC_CSGOSTATS_SHARECODECACHE_H_ #include #include @@ -11,19 +14,19 @@ class ShareCodeCache { public: - ShareCodeCache(bool verboseMode); + explicit ShareCodeCache(bool verboseMode); ~ShareCodeCache(); bool find(std::string sharecode); bool insert(std::string sharecode); private: - const std::string csvFile = "sharecode.db"; + std::string const csvFile = "sharecode.db"; std::fstream matchDbFile; std::vector sharecodeCache; - std::vector read(std::istream &input); + std::vector read(std::istream& input); }; -#endif \ No newline at end of file +#endif // SRC_CSGOSTATS_SHARECODECACHE_H_ \ No newline at end of file diff --git a/src/csgostats/ShareCodeUpload.cpp b/src/csgostats/ShareCodeUpload.cpp index a2cdb20..679ab71 100644 --- a/src/csgostats/ShareCodeUpload.cpp +++ b/src/csgostats/ShareCodeUpload.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "ShareCodeUpload.h" #include "../VersionAndConstants.h" @@ -21,21 +24,21 @@ ShareCodeUpload::~ShareCodeUpload() curl_easy_cleanup(curl); } -size_t CurlWrite_CallbackFunc_StdString(void *contents, size_t size, size_t nmemb, std::string *s) +size_t CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::string* s) { size_t newLength = size * nmemb; size_t oldLength = s->size(); try { s->resize(oldLength + newLength); - } catch (std::bad_alloc &e) { + } catch (std::bad_alloc& e) { // cast to void (formerly self-assign) to avoid unused/unreferenced variable e static_cast(e); // handle memory problem return 0; } - std::copy((char *)contents, (char *)contents + newLength, s->begin() + oldLength); + std::copy(reinterpret_cast(contents), reinterpret_cast(contents) + newLength, s->begin() + oldLength); return size * nmemb; } @@ -43,7 +46,7 @@ size_t CurlWrite_CallbackFunc_StdString(void *contents, size_t size, size_t nmem /* POST the CSGO Demo Sharecode to csgostats.gg */ -int ShareCodeUpload::uploadShareCode(std::string shareCode, std::string &responseContent) +int ShareCodeUpload::uploadShareCode(std::string shareCode, std::string& responseContent) { CURLcode res; @@ -66,16 +69,17 @@ int ShareCodeUpload::uploadShareCode(std::string shareCode, std::string &respons postData.append("&index=0"); // 3. set data to POST - const char *data = postData.c_str(); - curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(data)); + char const * data = postData.c_str(); + //curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(data)); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast(strlen(data))); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); // prepare user-agent identifier char ua_ident[100]; - sprintf(ua_ident, "User-Agent: Mozilla/5.0 (compatible; %s)", CSGO_CLI_USERAGENT_ID); + snprintf(ua_ident, "User-Agent: Mozilla/5.0 (compatible; %s)", CSGO_CLI_USERAGENT_ID); // 4. set headers - struct curl_slist *headers = NULL; + struct curl_slist* headers = NULL; headers = curl_slist_append(headers, "Accept: application/json, text/javascript, */*; q=0.01"); headers = curl_slist_append(headers, "Accept-Language: en-US;q=0.8,en;q=0.7"); headers = curl_slist_append(headers, ua_ident); @@ -96,7 +100,9 @@ int ShareCodeUpload::uploadShareCode(std::string shareCode, std::string &respons curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseContent); // 8. enable verbose mode - if (verbose) { curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); } + if (verbose) { + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + } // perform the request res = curl_easy_perform(curl); @@ -144,7 +150,7 @@ int ShareCodeUpload::uploadShareCode(std::string shareCode, std::string &respons * 4. Server-Side: Match queued / processing demo file * 5. Server-Side: complete */ -int ShareCodeUpload::processJsonResponse(std::string &jsonResponse) +int ShareCodeUpload::processJsonResponse(std::string& jsonResponse) { // response empty? if (jsonResponse.empty()) { @@ -167,8 +173,8 @@ int ShareCodeUpload::processJsonResponse(std::string &jsonResponse) nlohmann::json json; try { json = nlohmann::json::parse(jsonResponse); - } catch (nlohmann::json::parse_error &e) { - const auto msg = fmt::format( + } catch (nlohmann::json::parse_error& e) { + auto const msg = fmt::format( "Message: {}\n Exception Id: {}\n Byte position of parsing error: {}\n", e.what(), e.id, e.byte); printError("JsonParsingError", msg.c_str()); return 2; @@ -180,49 +186,49 @@ int ShareCodeUpload::processJsonResponse(std::string &jsonResponse) printError("Error", "Json Response does not contain the keys \"status\" and \"data\"."); return 2; } - const auto status = json["status"].get(); - const auto data = json["data"]; + auto const status = json["status"].get(); + auto const data = json["data"]; /* csgostats.gg has 4 json responses to a sharecode POST request: error, queued, retrying, complete. */ if (status == "error") { - const std::string msg = data["msg"].get(); + std::string const msg = data["msg"].get(); - const auto result = fmt::format(" Result: {} -> {}. \n", status, msg); + auto const result = fmt::format(" Result: {} -> {}. \n", status, msg); printRed(result); return 3; } if (status == "queued" || status == "retrying") { - const std::string msg = data["msg"].get(); + std::string const msg = data["msg"].get(); // msg contains HTML crap, let's cut that out std::string msgHtml = msg; std::string newMsg(" "); // get the "in queue #X" part (start of value (char 0) to char "<"span) - const std::string queuedString = msgHtml.substr(0, msgHtml.find("<")); + std::string const queuedString = msgHtml.substr(0, msgHtml.find("<")); newMsg.append(queuedString); // get the "time remaining part (start of value (char "~" + 1) to end) - const std::string timeString = msgHtml.substr(msgHtml.find("~") + 1, -1); + std::string const timeString = msgHtml.substr(msgHtml.find("~") + 1, -1); newMsg.append(timeString); - const std::string url = data["url"].get(); + std::string const url = data["url"].get(); - const auto result = fmt::format(" Result: {} -> {} | {} \n", status, url, newMsg); + auto const result = fmt::format(" Result: {} -> {} | {} \n", status, url, newMsg); printDarkOrange(result); return 4; } if (status == "complete") { - const std::string url = data["url"].get(); + std::string const url = data["url"].get(); - const auto result = fmt::format(" Result: {} -> {} \n", status, url); + auto const result = fmt::format(" Result: {} -> {} \n", status, url); printGreen(result); return 5; diff --git a/src/csgostats/ShareCodeUpload.h b/src/csgostats/ShareCodeUpload.h index 36b1e59..b47a8fe 100644 --- a/src/csgostats/ShareCodeUpload.h +++ b/src/csgostats/ShareCodeUpload.h @@ -1,5 +1,8 @@ -#ifndef ShareCodeUpload_H -#define ShareCodeUpload_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_CSGOSTATS_SHARECODEUPLOAD_H_ +#define SRC_CSGOSTATS_SHARECODEUPLOAD_H_ #include #include @@ -8,31 +11,33 @@ #include "../ErrorHandler.h" #include "../platform/windows/WinCliColors.h" +#include #include #include +#include #include #include -using namespace WinCliColors; +using WinCliColors; class ShareCodeUpload { public: - ShareCodeUpload(bool verboseMode); + explicit ShareCodeUpload(bool verboseMode); ~ShareCodeUpload(); - int uploadShareCode(std::string shareCode, std::string &responseContent); - int processJsonResponse(std::string &jsonResponse); + int uploadShareCode(std::string shareCode, std::string& responseContent); + int processJsonResponse(std::string& jsonResponse); // int testProcessJsonResponse(); private: - CURL *curl = nullptr; + CURL* curl = nullptr; bool verbose = false; - struct curl_slist *host = NULL; + struct curl_slist* host = NULL; - CURL *initCurlConnection(); + CURL* initCurlConnection(); }; -#endif +#endif // SRC_CSGOSTATS_SHARECODEUPLOAD_H_ diff --git a/src/main/main.cpp b/src/main/main.cpp index ecae7bb..304026c 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include #include #include @@ -5,15 +8,15 @@ #include "../ErrorHandler.h" #include "../ExceptionHandler.h" -#include "../VersionAndConstants.h" #include "../platform/windows/WinCliColors.h" +#include "../VersionAndConstants.h" +#include "../commands/cmd.globalstats.h" #include "../commands/cmd.help.h" #include "../commands/cmd.matches.h" #include "../commands/cmd.scoreboard.h" #include "../commands/cmd.upload.h" #include "../commands/cmd.user.h" -#include "../commands/cmd.globalstats.h" #ifdef _WIN32 #include @@ -28,13 +31,16 @@ // Includes needed for _setmode() (+io.h) #include -using namespace WinCliColors; +using WinCliColors; -void initSteamAPI(bool &verbose) +void initSteamAPI(bool& verbose) { - if (verbose) spdlog::info("[ Start ] STEAM_INIT"); + if (verbose) + spdlog::info("[ Start ] STEAM_INIT"); - if (SteamAPI_RestartAppIfNecessary(k_uAppIdInvalid)) { exit(1); } + if (SteamAPI_RestartAppIfNecessary(k_uAppIdInvalid)) { + exit(1); + } #ifdef _WIN32 int savedStderr; @@ -63,55 +69,66 @@ void initSteamAPI(bool &verbose) exit(1); } - // TODO - // setPersonaState(Invisible) 7 + // TODO(my_username): setPersonaState(Invisible) 7 - if (verbose) { spdlog::info("[ End ] STEAM_INIT"); } + if (verbose) { + spdlog::info("[ End ] STEAM_INIT"); + } } -std::thread createCallbackThread(bool &running, bool &verbose) +std::thread createCallbackThread(bool& running, bool& verbose) { - if (verbose) { spdlog::info("[ Start ] CallbackThread & Steam_RunCallbacks"); } + if (verbose) { + spdlog::info("[ Start ] CallbackThread & Steam_RunCallbacks"); + } auto CallbackThread = std::thread([&running]() { while (running) { try { std::this_thread::sleep_for(std::chrono::milliseconds(CSGO_CLI_STEAM_CALLBACK_INTERVAL)); SteamAPI_RunCallbacks(); - } catch (ExceptionHandler &e) { + } catch (ExceptionHandler& e) { printError("Fatal Error", e.what()); exit(1); } - }; + } }); - if (verbose) { spdlog::info("[ End ] CallbackThread & Steam_RunCallbacks"); } + if (verbose) { + spdlog::info("[ End ] CallbackThread & Steam_RunCallbacks"); + } return CallbackThread; } -void initGameClientConnection(DataObject &data, bool &verbose) +void initGameClientConnection(DataObject& data, bool& verbose) { - if (verbose) { spdlog::info("[ Start ] Trying to establish a GameClient Connection"); } + if (verbose) { + spdlog::info("[ Start ] Trying to establish a GameClient Connection"); + } bool result = false; try { // make sure we are connected to the GameClient - if (verbose) { spdlog::info(" -> Requesting: GameClient Connection"); } + if (verbose) { + spdlog::info(" -> Requesting: GameClient Connection"); + } CSGOClient::GetInstance()->WaitForGameClientConnect(); - if (verbose) { spdlog::info(" -> Successful: GameClient connected!"); } + if (verbose) { + spdlog::info(" -> Successful: GameClient connected!"); + } result = true; data.account_id = SteamUser()->GetSteamID().GetAccountID(); data.steam_id = SteamUser()->GetSteamID().ConvertToUint64(); data.steam_player_level = SteamUser()->GetPlayerSteamLevel(); // this is a "const char*" UTF data narrowing to std::string - data.playername = reinterpret_cast(SteamFriends()->GetPersonaName()); + data.playername = reinterpret_cast(SteamFriends()->GetPersonaName()); CSteamID clan_id = SteamFriends()->GetClanByIndex(0); data.clan_name = SteamFriends()->GetClanName(clan_id); data.clan_tag = SteamFriends()->GetClanTag(clan_id); - } catch (ExceptionHandler &e) { + } catch (ExceptionHandler& e) { printError("Fatal error", e.what()); result = false; } @@ -121,7 +138,9 @@ void initGameClientConnection(DataObject &data, bool &verbose) exit(1); } - if (verbose) { spdlog::info("[ End ] Trying to establish a GameClient Connection"); } + if (verbose) { + spdlog::info("[ End ] Trying to establish a GameClient Connection"); + } } void exitIfGameIsRunning() @@ -135,7 +154,7 @@ void exitIfGameIsRunning() #endif } -int main(int argc, char **argv) +int main(int argc, char** argv) { SetConsoleOutputCP(CP_UTF8); WinCliColors::enableConsoleColor(true); @@ -190,8 +209,8 @@ int main(int argc, char **argv) } } - if (paramVerbose && !paramPrintUser && !paramPrintGlobalStats && !paramPrintMatches && !paramPrintScoreboard && !paramUploadShareCode && - !paramUploadShareCodes) { + if (paramVerbose && !paramPrintUser && !paramPrintGlobalStats && !paramPrintMatches && !paramPrintScoreboard && + !paramUploadShareCode && !paramUploadShareCodes) { printError("ERROR", "You are using (-v|-verbose) without any other command."); fmt::print("Please check: '{} -help'\n", CSGO_CLI_BINARYNAME); return 1; @@ -247,15 +266,25 @@ int main(int argc, char **argv) // OUTPUT - if (paramPrintUser) { printPlayersProfile(data); } + if (paramPrintUser) { + printPlayersProfile(data); + } - if (paramPrintGlobalStats) { printGlobalStats(data); } + if (paramPrintGlobalStats) { + printGlobalStats(data); + } - if (paramPrintMatches) { printMatches(data); } + if (paramPrintMatches) { + printMatches(data); + } - if (paramPrintScoreboard) { printScoreboard(data); } + if (paramPrintScoreboard) { + printScoreboard(data); + } - if (paramUploadShareCodes) { uploadReplayShareCodes(data, paramVerbose); } + if (paramUploadShareCodes) { + uploadReplayShareCodes(data, paramVerbose); + } // SHUTDOWN diff --git a/src/platform/windows/WinCliColors.cpp b/src/platform/windows/WinCliColors.cpp index 9372f2f..dbbe1f1 100644 --- a/src/platform/windows/WinCliColors.cpp +++ b/src/platform/windows/WinCliColors.cpp @@ -1,7 +1,10 @@ +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + #include "WinCliColors.h" // console color heck by mlocati: https://gist.github.com/mlocati/21a9233ac83f7d3d7837535bc109b3b7 -typedef NTSTATUS(WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); +typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); namespace WinCliColors { @@ -11,16 +14,22 @@ namespace WinCliColors HMODULE hMod = GetModuleHandle(TEXT("ntdll.dll")); - if (!hMod) { return false; } + if (!hMod) { + return false; + } RtlGetVersionPtr rlGetVersion = (RtlGetVersionPtr)GetProcAddress(hMod, "RtlGetVersion"); - if (rlGetVersion == NULL) { return false; } + if (rlGetVersion == NULL) { + return false; + } RTL_OSVERSIONINFOW version_info = {0}; version_info.dwOSVersionInfoSize = sizeof(version_info); - if (rlGetVersion(&version_info) != 0) { return false; } + if (rlGetVersion(&version_info) != 0) { + return false; + } if (version_info.dwMajorVersion > MINV_MAJOR || (version_info.dwMajorVersion == MINV_MAJOR && @@ -34,17 +43,25 @@ namespace WinCliColors bool enableConsoleColor(bool enabled) { - if (!consoleHasColorSupport()) { return false; } + if (!consoleHasColorSupport()) { + return false; + } HANDLE hStdOut; hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); - if (INVALID_HANDLE_VALUE == hStdOut) { return false; } + if (INVALID_HANDLE_VALUE == hStdOut) { + return false; + } DWORD mode; - if (!GetConsoleMode(hStdOut, &mode)) { return false; } + if (!GetConsoleMode(hStdOut, &mode)) { + return false; + } - if (((mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) ? 1 : 0) == (enabled ? 1 : 0)) { return true; } + if (((mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) ? 1 : 0) == (enabled ? 1 : 0)) { + return true; + } if (enabled) { mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; @@ -52,7 +69,9 @@ namespace WinCliColors mode &= ~ENABLE_VIRTUAL_TERMINAL_PROCESSING; } - if (SetConsoleMode(hStdOut, mode)) { return true; } + if (SetConsoleMode(hStdOut, mode)) { + return true; + } return false; } diff --git a/src/platform/windows/WinCliColors.h b/src/platform/windows/WinCliColors.h index 30c2b12..d70355f 100644 --- a/src/platform/windows/WinCliColors.h +++ b/src/platform/windows/WinCliColors.h @@ -1,11 +1,16 @@ -#ifndef WinCliColors_H -#define WinCliColors_H +// SPDX-FileCopyrightText: Copyright © 2018-present Jens A. Koch +// SPDX-License-Identifier: GPL-3.0-or-later + +#ifndef SRC_PLATFORM_WINDOWS_WINCLICOLORS_H_ +#define SRC_PLATFORM_WINDOWS_WINCLICOLORS_H_ #include #include #include "Windows.h" +#include + namespace WinCliColors { bool consoleHasColorSupport(); @@ -26,4 +31,4 @@ namespace WinCliColors } // namespace WinCliColors -#endif \ No newline at end of file +#endif // SRC_PLATFORM_WINDOWS_WINCLICOLORS_H_ \ No newline at end of file