Add .clang-format and reformat all sources.

This commit is contained in:
Kirill Kirilenko 2020-11-30 15:14:05 +03:00
parent 0c71edab8b
commit b1f0b94ba3
26 changed files with 400 additions and 281 deletions

110
.clang-format Normal file
View file

@ -0,0 +1,110 @@
---
BasedOnStyle: WebKit
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveBitFields: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: DontAlign
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: InlineOnly
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: Inline
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: true
BinPackParameters: false
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: Always
AfterEnum: true
AfterFunction: true
AfterNamespace: false
AfterStruct: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
ColumnLimit: 100
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
FixNamespaceComments: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^".*"'
Priority: 1
- Regex: '^<telebotxx/.*>'
Priority: 2
- Regex: '^<.*([.]h|[.]hpp)>'
Priority: 3
- Regex: '^<.*>'
Priority: 4
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExternBlock: NoIndent
IndentGotoLabels: false
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
Language: Cpp
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
PenaltyExcessCharacter: 10
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++14
StatementMacros: ['Q_UNUSED']
TabWidth: 4
UseCRLF: false
UseTab: ForIndentation
...

View file

@ -1,11 +1,11 @@
#ifndef TELEBOTXX_ATTACHMENT_HPP #ifndef TELEBOTXX_ATTACHMENT_HPP
#define TELEBOTXX_ATTACHMENT_HPP #define TELEBOTXX_ATTACHMENT_HPP
#include <string>
#include <vector>
#include <memory> #include <memory>
#include <variant>
#include <optional> #include <optional>
#include <string>
#include <variant>
#include <vector>
namespace telebotxx { namespace telebotxx {
@ -161,6 +161,6 @@ private:
std::variant<PhotoSizeArray, Audio, Document, Sticker> value_; std::variant<PhotoSizeArray, Audio, Document, Sticker> value_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_ATTACHMENT_HPP #endif // TELEBOTXX_ATTACHMENT_HPP

View file

@ -1,14 +1,14 @@
#ifndef TELEBOTXX_BOTAPI_HPP #ifndef TELEBOTXX_BOTAPI_HPP
#define TELEBOTXX_BOTAPI_HPP #define TELEBOTXX_BOTAPI_HPP
#include "User.hpp"
#include "Message.hpp" #include "Message.hpp"
#include "Update.hpp"
#include "SendMessageRequest.hpp" #include "SendMessageRequest.hpp"
#include "SendPhotoRequest.hpp" #include "SendPhotoRequest.hpp"
#include "Update.hpp"
#include "User.hpp"
#include <string>
#include <memory> #include <memory>
#include <string>
namespace telebotxx { namespace telebotxx {
@ -28,7 +28,6 @@ void setRequestOption(RequestType& request, T&& t, Ts&&... ts)
class BotApi class BotApi
{ {
public: public:
/// \param [in] token bot's secret token /// \param [in] token bot's secret token
BotApi(const std::string& token); BotApi(const std::string& token);
@ -52,7 +51,8 @@ public:
template <typename... Ts> template <typename... Ts>
Message sendMessage(ChatId&& chatId, Text&& text, Ts&&... args) Message sendMessage(ChatId&& chatId, Text&& text, Ts&&... args)
{ {
SendMessageRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId), std::forward<Text>(text)); SendMessageRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId),
std::forward<Text>(text));
setRequestOption(request, std::forward<Ts>(args)...); setRequestOption(request, std::forward<Ts>(args)...);
return request.execute(); return request.execute();
} }
@ -71,7 +71,8 @@ public:
template <typename... Ts> template <typename... Ts>
Message sendPhoto(ChatId&& chatId, Photo&& photo, Ts&&... args) Message sendPhoto(ChatId&& chatId, Photo&& photo, Ts&&... args)
{ {
SendPhotoRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId), std::forward<Photo>(photo)); SendPhotoRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId),
std::forward<Photo>(photo));
setRequestOption(request, std::forward<Ts>(args)...); setRequestOption(request, std::forward<Ts>(args)...);
return request.execute(); return request.execute();
} }
@ -91,6 +92,6 @@ private:
std::unique_ptr<Impl> impl_; std::unique_ptr<Impl> impl_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_BOTAPI_HPP #endif // TELEBOTXX_BOTAPI_HPP

View file

@ -1,10 +1,10 @@
#ifndef TELEBOTXX_CHAT_HPP #ifndef TELEBOTXX_CHAT_HPP
#define TELEBOTXX_CHAT_HPP #define TELEBOTXX_CHAT_HPP
#include <string>
#include <memory>
#include <cstdint> #include <cstdint>
#include <memory>
#include <optional> #include <optional>
#include <string>
namespace telebotxx { namespace telebotxx {
@ -54,6 +54,6 @@ private:
Chat::Type chatTypeFromString(const std::string& str); Chat::Type chatTypeFromString(const std::string& str);
} } // namespace telebotxx
#endif // TELEBOTXX_CHAT_HPP #endif // TELEBOTXX_CHAT_HPP

View file

@ -8,29 +8,20 @@ namespace telebotxx {
class ParseError : public std::invalid_argument class ParseError : public std::invalid_argument
{ {
public: public:
ParseError(const std::string& message) ParseError(const std::string& message) : std::invalid_argument(message) {}
: std::invalid_argument(message)
{
}
}; };
class ApiError : public std::runtime_error class ApiError : public std::runtime_error
{ {
public: public:
ApiError(int code, std::string message) ApiError(int code, std::string message) : std::runtime_error(std::move(message)), code_(code) {}
: std::runtime_error(std::move(message)), code_(code)
{
}
int getCode() const int getCode() const { return code_; }
{
return code_;
}
protected: protected:
int code_; int code_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_EXCEPTION_HPP #endif // TELEBOTXX_EXCEPTION_HPP

View file

@ -8,6 +8,6 @@ extern bool debugMode;
/// \brief Enable/disable debug output /// \brief Enable/disable debug output
void setDebugMode(bool enabled); void setDebugMode(bool enabled);
} } // namespace telebotxx
#endif // TELEBOTXX_LOGGING_HPP #endif // TELEBOTXX_LOGGING_HPP

View file

@ -1,14 +1,14 @@
#ifndef TELEBOTXX_MESSAGE_HPP #ifndef TELEBOTXX_MESSAGE_HPP
#define TELEBOTXX_MESSAGE_HPP #define TELEBOTXX_MESSAGE_HPP
#include "User.hpp"
#include "Chat.hpp"
#include "Attachment.hpp" #include "Attachment.hpp"
#include "Chat.hpp"
#include "User.hpp"
#include <vector>
#include <ctime> #include <ctime>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <vector>
namespace telebotxx { namespace telebotxx {
@ -167,6 +167,6 @@ private:
MessagePtr pinnedMessage_; MessagePtr pinnedMessage_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_MESSAGE_HPP #endif // TELEBOTXX_MESSAGE_HPP

View file

@ -2,23 +2,27 @@
#define TELEBOTXX_REQUEST_OPTIONS_HPP #define TELEBOTXX_REQUEST_OPTIONS_HPP
#include <string> #include <string>
#include <vector>
#include <variant> #include <variant>
#include <vector>
#define TELEBOTXX_DECLARE_BOOL_PARAM_CLASS(Name, DEFAULT) class Name \ #define TELEBOTXX_DECLARE_BOOL_PARAM_CLASS(Name, DEFAULT) \
class Name \
{ \ { \
public: \ public: \
explicit Name(bool value = DEFAULT); \ explicit Name(bool value = DEFAULT); \
bool getValue() const; \ bool getValue() const; \
\
private: \ private: \
bool value_; \ bool value_; \
}; };
#define TELEBOTXX_DECLARE_STRING_PARAM_CLASS(Name) class Name \ #define TELEBOTXX_DECLARE_STRING_PARAM_CLASS(Name) \
class Name \
{ \ { \
public: \ public: \
explicit Name(const std::string& value); \ explicit Name(const std::string& value); \
const std::string& getValue() const; \ const std::string& getValue() const; \
\
private: \ private: \
std::string value_; \ std::string value_; \
}; };
@ -31,10 +35,15 @@ public:
ChatId(int); ChatId(int);
ChatId(const std::string&); ChatId(const std::string&);
enum class Type { Id, Username }; enum class Type
{
Id,
Username
};
Type getType() const; Type getType() const;
const int getId() const; const int getId() const;
const std::string getUsername() const; const std::string getUsername() const;
private: private:
Type type_; Type type_;
std::variant<int, std::string> value_; std::variant<int, std::string> value_;
@ -59,6 +68,7 @@ class ReplyTo
public: public:
explicit ReplyTo(int id); explicit ReplyTo(int id);
int value() const; int value() const;
private: private:
int id_; int id_;
}; };
@ -71,6 +81,7 @@ public:
const char* data() const; const char* data() const;
const std::size_t size() const; const std::size_t size() const;
const std::string filename() const; const std::string filename() const;
private: private:
const char* data_; const char* data_;
std::size_t size_; std::size_t size_;
@ -89,7 +100,13 @@ public:
explicit Photo(const File&); explicit Photo(const File&);
explicit Photo(const Url&); explicit Photo(const Url&);
enum class Type { Id, Buffer, File, Url }; enum class Type
{
Id,
Buffer,
File,
Url
};
Type getType() const; Type getType() const;
int getId() const; int getId() const;
@ -102,6 +119,6 @@ private:
std::variant<int, Buffer, File, Url> value_; std::variant<int, Buffer, File, Url> value_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_REQUEST_OPTIONS_HPP #endif // TELEBOTXX_REQUEST_OPTIONS_HPP

View file

@ -1,11 +1,11 @@
#ifndef TELEBOTXX_SEND_MESSAGE_REQUEST_HPP #ifndef TELEBOTXX_SEND_MESSAGE_REQUEST_HPP
#define TELEBOTXX_SEND_MESSAGE_REQUEST_HPP #define TELEBOTXX_SEND_MESSAGE_REQUEST_HPP
#include <telebotxx/RequestOptions.hpp> #include "Message.hpp"
#include <telebotxx/Message.hpp> #include "RequestOptions.hpp"
#include <string>
#include <memory> #include <memory>
#include <string>
namespace telebotxx { namespace telebotxx {
@ -32,6 +32,6 @@ private:
std::unique_ptr<Impl> impl_; std::unique_ptr<Impl> impl_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_SEND_MESSAGE_REQUEST_HPP #endif // TELEBOTXX_SEND_MESSAGE_REQUEST_HPP

View file

@ -1,11 +1,11 @@
#ifndef TELEBOTXX_SEND_PHOTO_REQUEST_HPP #ifndef TELEBOTXX_SEND_PHOTO_REQUEST_HPP
#define TELEBOTXX_SEND_PHOTO_REQUEST_HPP #define TELEBOTXX_SEND_PHOTO_REQUEST_HPP
#include <telebotxx/RequestOptions.hpp> #include "Message.hpp"
#include <telebotxx/Message.hpp> #include "RequestOptions.hpp"
#include <string>
#include <memory> #include <memory>
#include <string>
namespace telebotxx { namespace telebotxx {
@ -30,6 +30,6 @@ private:
std::unique_ptr<Impl> impl_; std::unique_ptr<Impl> impl_;
}; };
} } // namespace telebotxx
#endif // TELEBOTXX_SEND_PHOTO_REQUEST_HPP #endif // TELEBOTXX_SEND_PHOTO_REQUEST_HPP

View file

@ -3,9 +3,9 @@
#include "Message.hpp" #include "Message.hpp"
#include <vector>
#include <memory> #include <memory>
#include <variant> #include <variant>
#include <vector>
namespace telebotxx { namespace telebotxx {
@ -37,6 +37,6 @@ private:
using Updates = std::vector<Update>; using Updates = std::vector<Update>;
} } // namespace telebotxx
#endif // TELEBOTXX_UPDATE_HPP #endif // TELEBOTXX_UPDATE_HPP

View file

@ -1,9 +1,9 @@
#ifndef TELEBOTXX_USER_H #ifndef TELEBOTXX_USER_H
#define TELEBOTXX_USER_H #define TELEBOTXX_USER_H
#include <string>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <string>
namespace telebotxx { namespace telebotxx {
@ -48,6 +48,6 @@ private:
std::ostream& operator<<(std::ostream& os, const User& user); std::ostream& operator<<(std::ostream& os, const User& user);
} } // namespace telebotxx
#endif // TELEBOTXX_USER_H #endif // TELEBOTXX_USER_H

View file

@ -2,10 +2,7 @@
namespace telebotxx { namespace telebotxx {
PhotoSize::PhotoSize() PhotoSize::PhotoSize() : width_(-1), height_(-1), fileSize_(-1)
: width_(-1),
height_(-1),
fileSize_(-1)
{ {
} }
@ -51,9 +48,7 @@ void PhotoSize::setFileSize(std::optional<int> fileSize)
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
Audio::Audio() Audio::Audio() : duration_(-1), fileSize_(-1)
: duration_(-1),
fileSize_(-1)
{ {
} }
@ -119,8 +114,7 @@ void Audio::setFileSize(std::optional<int> fileSize)
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
Document::Document() Document::Document() : fileSize_(-1)
: fileSize_(-1)
{ {
} }
@ -176,8 +170,7 @@ void Document::setFileSize(std::optional<int> fileSize)
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
Sticker::Sticker() Sticker::Sticker() : fileSize_(-1)
: fileSize_(-1)
{ {
} }
@ -248,18 +241,15 @@ Attachment::Attachment(PhotoSizeArray photos)
{ {
} }
Attachment::Attachment(Audio audio) Attachment::Attachment(Audio audio) : type_(Type::Audio), value_(std::move(audio))
: type_(Type::Audio), value_(std::move(audio))
{ {
} }
Attachment::Attachment(Document document) Attachment::Attachment(Document document) : type_(Type::Document), value_(std::move(document))
: type_(Type::Document), value_(std::move(document))
{ {
} }
Attachment::Attachment(Sticker sticker) Attachment::Attachment(Sticker sticker) : type_(Type::Sticker), value_(std::move(sticker))
: type_(Type::Sticker), value_(std::move(sticker))
{ {
} }
@ -275,7 +265,8 @@ const PhotoSizeArray& Attachment::getPhotoSizeArray() const
const Audio& Attachment::getAudio() const const Audio& Attachment::getAudio() const
{ {
return std::get<Audio>(value_);; return std::get<Audio>(value_);
;
} }
const Document& Attachment::getDocument() const const Document& Attachment::getDocument() const
@ -285,7 +276,8 @@ const Document& Attachment::getDocument() const
const Sticker& Attachment::getSticker() const const Sticker& Attachment::getSticker() const
{ {
return std::get<Sticker>(value_);; return std::get<Sticker>(value_);
;
} }
} } // namespace telebotxx

View file

@ -1,22 +1,21 @@
#include <telebotxx/BotApi.hpp> #include "BotApi.hpp"
#include <telebotxx/Exception.hpp>
#include <telebotxx/Logging.hpp> #include "Exception.hpp"
#include "JsonObjects.hpp" #include "JsonObjects.hpp"
#include "Logging.hpp"
#include <cpr/cpr.h>
#include <rapidjson/writer.h>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <rapidjson/writer.h>
#include <cpr/cpr.h>
namespace telebotxx { namespace telebotxx {
class BotApi::Impl class BotApi::Impl
{ {
public: public:
Impl(const std::string& token) Impl(const std::string& token) : token_(token)
: token_(token)
{ {
telegramMainUrl_ = "https://api.telegram.org/bot" + token_; telegramMainUrl_ = "https://api.telegram.org/bot" + token_;
botUser_ = getMe(); botUser_ = getMe();
@ -37,14 +36,12 @@ public:
return require<User>(doc, "result"); return require<User>(doc, "result");
} }
inline Message sendPhoto(const std::string& chat, const std::string& filename, const std::string& caption) inline Message
sendPhoto(const std::string& chat, const std::string& filename, const std::string& caption)
{ {
auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/sendPhoto"}, auto r = cpr::Post(
cpr::Multipart{{"chat_id", chat}, cpr::Url{telegramMainUrl_ + "/sendPhoto"},
{"photo", cpr::File{filename}}, cpr::Multipart{{"chat_id", chat}, {"photo", cpr::File{filename}}, {"caption", caption}});
{"caption", caption}
}
);
auto& response = r.text; auto& response = r.text;
if (debugMode) if (debugMode)
@ -58,7 +55,8 @@ public:
return *parseMessage(doc, "result", REQUIRED); return *parseMessage(doc, "result", REQUIRED);
} }
inline Message sendPhotoUrl(const std::string& chat, const std::string& url, const std::string& caption) inline Message
sendPhotoUrl(const std::string& chat, const std::string& url, const std::string& caption)
{ {
// Construct JSON body // Construct JSON body
using namespace rapidjson; using namespace rapidjson;
@ -77,9 +75,7 @@ public:
std::string request = s.GetString(); std::string request = s.GetString();
auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/sendPhoto"}, auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/sendPhoto"},
cpr::Header{{"Content-Type", "application/json"}}, cpr::Header{{"Content-Type", "application/json"}}, cpr::Body{request});
cpr::Body{request}
);
auto& response = r.text; auto& response = r.text;
if (debugMode) if (debugMode)
@ -121,9 +117,7 @@ public:
std::string request = s.GetString(); std::string request = s.GetString();
auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/getUpdates"}, auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/getUpdates"},
cpr::Header{{"Content-Type", "application/json"}}, cpr::Header{{"Content-Type", "application/json"}}, cpr::Body{request});
cpr::Body{request}
);
auto& response = r.text; auto& response = r.text;
if (debugMode) if (debugMode)
@ -136,20 +130,15 @@ public:
return parseUpdates(doc, "result"); return parseUpdates(doc, "result");
} }
std::string getTelegramMainUrl() const std::string getTelegramMainUrl() const { return telegramMainUrl_; }
{
return telegramMainUrl_;
}
private: private:
std::string token_; std::string token_;
std::string telegramMainUrl_; std::string telegramMainUrl_;
User botUser_; User botUser_;
}; };
BotApi::BotApi(const std::string& token) BotApi::BotApi(const std::string& token) : impl_(std::make_unique<Impl>(token))
: impl_(std::make_unique<Impl>(token))
{ {
} }
@ -162,13 +151,15 @@ User BotApi::getMe()
Message BotApi::sendMessage(ChatId&& chatId, Text&& text) Message BotApi::sendMessage(ChatId&& chatId, Text&& text)
{ {
SendMessageRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId), std::forward<Text>(text)); SendMessageRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId),
std::forward<Text>(text));
return request.execute(); return request.execute();
} }
Message BotApi::sendPhoto(ChatId&& chatId, Photo&& photo) Message BotApi::sendPhoto(ChatId&& chatId, Photo&& photo)
{ {
SendPhotoRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId), std::forward<Photo>(photo)); SendPhotoRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId),
std::forward<Photo>(photo));
return request.execute(); return request.execute();
} }
@ -182,4 +173,4 @@ std::string BotApi::getTelegramMainUrl() const
return impl_->getTelegramMainUrl(); return impl_->getTelegramMainUrl();
} }
} } // namespace telebotxx

View file

@ -18,6 +18,7 @@ set(SOURCE_FILES Attachment.cpp
add_library(telebotxx ${SOURCE_FILES}) add_library(telebotxx ${SOURCE_FILES})
target_include_directories(telebotxx PUBLIC ${telebotxx_SOURCE_DIR}/include) target_include_directories(telebotxx PUBLIC ${telebotxx_SOURCE_DIR}/include)
target_include_directories(telebotxx PRIVATE ${telebotxx_SOURCE_DIR}/include/telebotxx)
target_link_libraries(telebotxx target_link_libraries(telebotxx
PRIVATE PRIVATE
${CPR_LIBRARIES} ${CPR_LIBRARIES}

View file

@ -1,12 +1,10 @@
#include <telebotxx/Chat.hpp> #include "Chat.hpp"
#include <stdexcept> #include <stdexcept>
namespace telebotxx { namespace telebotxx {
Chat::Chat() Chat::Chat() : id_(-1), type_(Type::Private), allAdmins_(false)
: id_(-1),
type_(Type::Private),
allAdmins_(false)
{ {
} }
@ -94,4 +92,4 @@ Chat::Type chatTypeFromString(const std::string& str)
throw std::invalid_argument("Unknown chat type"); throw std::invalid_argument("Unknown chat type");
} }
} } // namespace telebotxx

View file

@ -4,17 +4,49 @@
namespace telebotxx { namespace telebotxx {
namespace impl { namespace impl {
template<> bool is<int>(const rapidjson::Value& obj) { return obj.IsInt(); } template <>
template<> bool is<std::int64_t>(const rapidjson::Value& obj) { return obj.IsInt64(); } bool is<int>(const rapidjson::Value& obj)
template<> bool is<bool>(const rapidjson::Value& obj) { return obj.IsBool(); } {
template<> bool is<std::string>(const rapidjson::Value& obj) { return obj.IsString(); } return obj.IsInt();
template<> const int get(const rapidjson::Value& obj) { return obj.GetInt(); }
template<> const std::int64_t get(const rapidjson::Value& obj) { return obj.GetInt64(); }
template<> const bool get(const rapidjson::Value& obj) { return obj.GetBool(); }
template<> const std::string get(const rapidjson::Value& obj) { return obj.GetString(); }
} }
template <>
bool is<std::int64_t>(const rapidjson::Value& obj)
{
return obj.IsInt64();
}
template <>
bool is<bool>(const rapidjson::Value& obj)
{
return obj.IsBool();
}
template <>
bool is<std::string>(const rapidjson::Value& obj)
{
return obj.IsString();
}
template <>
const int get(const rapidjson::Value& obj)
{
return obj.GetInt();
}
template <>
const std::int64_t get(const rapidjson::Value& obj)
{
return obj.GetInt64();
}
template <>
const bool get(const rapidjson::Value& obj)
{
return obj.GetBool();
}
template <>
const std::string get(const rapidjson::Value& obj)
{
return obj.GetString();
}
} // namespace impl
bool check(const rapidjson::Value& obj, const char* name) bool check(const rapidjson::Value& obj, const char* name)
{ {
@ -24,7 +56,8 @@ bool check(const rapidjson::Value& obj, const char* name)
return false; return false;
} }
const rapidjson::Value& parseObject(const rapidjson::Value& parent, const char* name, bool required, bool& found) const rapidjson::Value&
parseObject(const rapidjson::Value& parent, const char* name, bool required, bool& found)
{ {
if (parent.HasMember(name)) if (parent.HasMember(name))
{ {
@ -45,7 +78,8 @@ const rapidjson::Value& parseObject(const rapidjson::Value& parent, const char*
} }
} }
const rapidjson::Value& parseArray(const rapidjson::Value& parent, const char* name, bool required, bool& found) const rapidjson::Value&
parseArray(const rapidjson::Value& parent, const char* name, bool required, bool& found)
{ {
if (parent.HasMember(name)) if (parent.HasMember(name))
{ {
@ -113,7 +147,8 @@ PhotoSize parsePhotoSize(const rapidjson::Value& obj)
} }
template <> template <>
std::optional<PhotoSize> parse<PhotoSize>(const rapidjson::Value& parent, const char* name, bool required) std::optional<PhotoSize>
parse<PhotoSize>(const rapidjson::Value& parent, const char* name, bool required)
{ {
std::optional<PhotoSize> photo; std::optional<PhotoSize> photo;
bool found; bool found;
@ -126,7 +161,8 @@ std::optional<PhotoSize> parse<PhotoSize>(const rapidjson::Value& parent, const
} }
template <> template <>
std::optional<PhotoSizeArray> parse<PhotoSizeArray>(const rapidjson::Value& parent, const char* name, bool required) std::optional<PhotoSizeArray>
parse<PhotoSizeArray>(const rapidjson::Value& parent, const char* name, bool required)
{ {
std::optional<PhotoSizeArray> photos; std::optional<PhotoSizeArray> photos;
bool found; bool found;
@ -197,7 +233,8 @@ std::optional<Sticker> parse<Sticker>(const rapidjson::Value& parent, const char
} }
template <> template <>
std::optional<Attachment> parse<Attachment>(const rapidjson::Value& parent, const char* name, bool required) std::optional<Attachment>
parse<Attachment>(const rapidjson::Value& parent, const char* name, bool required)
{ {
std::optional<Attachment> attachment; std::optional<Attachment> attachment;
if (auto photo = allow<PhotoSizeArray>(parent, "photo")) if (auto photo = allow<PhotoSizeArray>(parent, "photo"))
@ -295,4 +332,4 @@ void checkResponse(const rapidjson::Document& doc)
} }
} }
} } // namespace telebotxx

View file

@ -1,11 +1,11 @@
#ifndef TELEBOTXX_JSON_OBJECTS_HPP #ifndef TELEBOTXX_JSON_OBJECTS_HPP
#define TELEBOTXX_JSON_OBJECTS_HPP #define TELEBOTXX_JSON_OBJECTS_HPP
#include <telebotxx/Attachment.hpp> #include "Attachment.hpp"
#include <telebotxx/Message.hpp> #include "Exception.hpp"
#include <telebotxx/Update.hpp> #include "Message.hpp"
#include <telebotxx/User.hpp> #include "Update.hpp"
#include <telebotxx/Exception.hpp> #include "User.hpp"
#include <rapidjson/document.h> #include <rapidjson/document.h>
@ -19,19 +19,29 @@ const bool OPTIONAL = false;
namespace impl { namespace impl {
template<typename T> bool is(const rapidjson::Value& obj); template <typename T>
template<> bool is<int>(const rapidjson::Value& obj); bool is(const rapidjson::Value& obj);
template<> bool is<std::int64_t>(const rapidjson::Value& obj); template <>
template<> bool is<bool>(const rapidjson::Value& obj); bool is<int>(const rapidjson::Value& obj);
template<> bool is<std::string>(const rapidjson::Value& obj); template <>
bool is<std::int64_t>(const rapidjson::Value& obj);
template <>
bool is<bool>(const rapidjson::Value& obj);
template <>
bool is<std::string>(const rapidjson::Value& obj);
template<typename T> const T get(const rapidjson::Value& obj); template <typename T>
template<> const int get(const rapidjson::Value& obj); const T get(const rapidjson::Value& obj);
template<> const std::int64_t get(const rapidjson::Value& obj); template <>
template<> const bool get(const rapidjson::Value& obj); const int get(const rapidjson::Value& obj);
template<> const std::string get(const rapidjson::Value& obj); template <>
const std::int64_t get(const rapidjson::Value& obj);
template <>
const bool get(const rapidjson::Value& obj);
template <>
const std::string get(const rapidjson::Value& obj);
} } // namespace impl
template <typename T> template <typename T>
std::optional<T> parse(const rapidjson::Value& obj, const char* name, bool required) std::optional<T> parse(const rapidjson::Value& obj, const char* name, bool required)
@ -68,7 +78,8 @@ bool check(const rapidjson::Value& obj, const char* name);
/// \param name field with Document object /// \param name field with Document object
/// \param required REQUIRED or OPTIONAL /// \param required REQUIRED or OPTIONAL
/// \return pointer to User /// \return pointer to User
template<> std::optional<User> parse<User>(const rapidjson::Value& parent, const char* name, bool required); template <>
std::optional<User> parse<User>(const rapidjson::Value& parent, const char* name, bool required);
/// \brief Parse JSON object to Message /// \brief Parse JSON object to Message
/// \param parent reference to parent JSON object /// \param parent reference to parent JSON object
@ -89,6 +100,6 @@ Updates parseUpdates(const rapidjson::Value& parent, const char* name);
/// \param doc reference to JSON document /// \param doc reference to JSON document
void checkResponse(const rapidjson::Document& doc); void checkResponse(const rapidjson::Document& doc);
} } // namespace telebotxx
#endif // TELEBOTXX_JSON_OBJECTS_HPP #endif // TELEBOTXX_JSON_OBJECTS_HPP

View file

@ -1,4 +1,4 @@
#include <telebotxx/Logging.hpp> #include "Logging.hpp"
namespace telebotxx { namespace telebotxx {
@ -9,4 +9,4 @@ void setDebugMode(bool enabled)
debugMode = enabled; debugMode = enabled;
} }
} } // namespace telebotxx

View file

@ -1,13 +1,10 @@
#include <telebotxx/Message.hpp> #include "Message.hpp"
#include <stdexcept> #include <stdexcept>
namespace telebotxx { namespace telebotxx {
MessageEntity::MessageEntity() MessageEntity::MessageEntity() : type_(Type::Mention), offset_(-1), length_(0)
: type_(Type::Mention),
offset_(-1),
length_(0)
{ {
} }
@ -340,4 +337,4 @@ void Message::setPinnedMessage(MessagePtr pinnedMessage)
pinnedMessage_ = pinnedMessage; pinnedMessage_ = pinnedMessage;
} }
} } // namespace telebotxx

View file

@ -1,20 +1,20 @@
#include <telebotxx/RequestOptions.hpp> #include "RequestOptions.hpp"
#define TELEBOTXX_DEFINE_BOOL_PARAM_CLASS(Name) Name::Name(bool value) : value_(value) { } \ #define TELEBOTXX_DEFINE_BOOL_PARAM_CLASS(Name) \
Name::Name(bool value) : value_(value) {} \
bool Name::getValue() const { return value_; } bool Name::getValue() const { return value_; }
#define TELEBOTXX_DEFINE_STRING_PARAM_CLASS(Name) Name::Name(const std::string& value) : value_(value) { } \ #define TELEBOTXX_DEFINE_STRING_PARAM_CLASS(Name) \
Name::Name(const std::string& value) : value_(value) {} \
const std::string& Name::getValue() const { return value_; } const std::string& Name::getValue() const { return value_; }
namespace telebotxx { namespace telebotxx {
ChatId::ChatId(int id) ChatId::ChatId(int id) : type_(Type::Id), value_(id)
: type_(Type::Id), value_(id)
{ {
} }
ChatId::ChatId(const std::string& str) ChatId::ChatId(const std::string& str) : type_(Type::Username), value_(str)
: type_(Type::Username), value_(str)
{ {
} }
@ -51,8 +51,7 @@ TELEBOTXX_DEFINE_BOOL_PARAM_CLASS(DisableNotification)
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
ReplyTo::ReplyTo(int id) ReplyTo::ReplyTo(int id) : id_(id)
: id_(id)
{ {
} }
@ -98,23 +97,19 @@ TELEBOTXX_DEFINE_STRING_PARAM_CLASS(Url)
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
Photo::Photo(int id) Photo::Photo(int id) : type_(Type::Id), value_(id)
: type_(Type::Id), value_(id)
{ {
} }
Photo::Photo(const Buffer& buffer) Photo::Photo(const Buffer& buffer) : type_(Type::Buffer), value_(buffer)
: type_(Type::Buffer), value_(buffer)
{ {
} }
Photo::Photo(const File& file) Photo::Photo(const File& file) : type_(Type::File), value_(file)
: type_(Type::File), value_(file)
{ {
} }
Photo::Photo(const Url& url) Photo::Photo(const Url& url) : type_(Type::Url), value_(url)
: type_(Type::Url), value_(url)
{ {
} }
@ -143,4 +138,4 @@ const Url& Photo::getUrl() const
return std::get<Url>(value_); return std::get<Url>(value_);
} }
} } // namespace telebotxx

View file

@ -1,6 +1,7 @@
#include <telebotxx/SendMessageRequest.hpp> #include "SendMessageRequest.hpp"
#include <telebotxx/Logging.hpp>
#include "JsonObjects.hpp" #include "JsonObjects.hpp"
#include "Logging.hpp"
#include <cpr/cpr.h> #include <cpr/cpr.h>
#include <rapidjson/document.h> #include <rapidjson/document.h>
@ -19,10 +20,7 @@ public:
{ {
} }
void setParseMode(ParseMode mode) void setParseMode(ParseMode mode) { parseMode_ = mode; }
{
parseMode_ = mode;
}
void setDisableWebPagePreview(const DisableWebPagePreview& disableWebPagePreview) void setDisableWebPagePreview(const DisableWebPagePreview& disableWebPagePreview)
{ {
@ -62,8 +60,9 @@ public:
if (parseMode_) if (parseMode_)
{ {
writer.String("parse_mode"); writer.String("parse_mode");
writer.String( writer.String((parseMode_ == ParseMode::Markdown) ? "Markdown"
(parseMode_ == ParseMode::Markdown) ? "Markdown" : (parseMode_ == ParseMode::Html) ? "HTML" : "Plain"); : (parseMode_ == ParseMode::Html) ? "HTML"
: "Plain");
} }
// Add disable_web_page_preview // Add disable_web_page_preview
@ -96,9 +95,7 @@ public:
if (debugMode) if (debugMode)
std::cout << "Request: " << request << std::endl; std::cout << "Request: " << request << std::endl;
auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/sendMessage"}, auto r = cpr::Post(cpr::Url{telegramMainUrl_ + "/sendMessage"},
cpr::Header{{"Content-Type", "application/json"}}, cpr::Header{{"Content-Type", "application/json"}}, cpr::Body{request});
cpr::Body{request}
);
auto& response = r.text; auto& response = r.text;
if (debugMode) if (debugMode)
@ -122,7 +119,9 @@ private:
std::optional<ReplyTo> replyToMessageId_; std::optional<ReplyTo> replyToMessageId_;
}; };
SendMessageRequest::SendMessageRequest(const std::string& telegramMainUrl, const ChatId& chat, const Text& text) SendMessageRequest::SendMessageRequest(const std::string& telegramMainUrl,
const ChatId& chat,
const Text& text)
: impl_(std::make_unique<Impl>(telegramMainUrl, chat, text)) : impl_(std::make_unique<Impl>(telegramMainUrl, chat, text))
{ {
} }
@ -176,4 +175,4 @@ Message SendMessageRequest::execute()
return impl_->execute(); return impl_->execute();
} }
} } // namespace telebotxx

View file

@ -1,6 +1,7 @@
#include <telebotxx/SendPhotoRequest.hpp> #include "SendPhotoRequest.hpp"
#include <telebotxx/Logging.hpp>
#include "JsonObjects.hpp" #include "JsonObjects.hpp"
#include "Logging.hpp"
#include <cpr/cpr.h> #include <cpr/cpr.h>
#include <rapidjson/document.h> #include <rapidjson/document.h>
@ -19,10 +20,7 @@ public:
{ {
} }
void setCaption(const Caption& caption) void setCaption(const Caption& caption) { caption_ = caption; }
{
caption_ = caption;
}
void setDisableNotification(const DisableNotification& disableNotification) void setDisableNotification(const DisableNotification& disableNotification)
{ {
@ -94,7 +92,9 @@ private:
std::optional<ReplyTo> replyToMessageId_; std::optional<ReplyTo> replyToMessageId_;
}; };
SendPhotoRequest::SendPhotoRequest(const std::string& telegramMainUrl, const ChatId& chat, const Photo& photo) SendPhotoRequest::SendPhotoRequest(const std::string& telegramMainUrl,
const ChatId& chat,
const Photo& photo)
: impl_(std::make_unique<Impl>(telegramMainUrl, chat, photo)) : impl_(std::make_unique<Impl>(telegramMainUrl, chat, photo))
{ {
} }
@ -138,4 +138,4 @@ Message SendPhotoRequest::execute()
return impl_->execute(); return impl_->execute();
} }
} } // namespace telebotxx

View file

@ -1,11 +1,9 @@
#include <telebotxx/Update.hpp> #include "Update.hpp"
namespace telebotxx { namespace telebotxx {
Update::Update(int id, Type type, std::unique_ptr<Message> message) Update::Update(int id, Type type, std::unique_ptr<Message> message)
: id_(id), : id_(id), type_(type), value_(std::move(message))
type_(type),
value_(std::move(message))
{ {
} }
@ -24,4 +22,4 @@ MessagePtr Update::getMessage() const
return std::get<MessagePtr>(value_); return std::get<MessagePtr>(value_);
} }
} } // namespace telebotxx

View file

@ -1,10 +1,10 @@
#include <telebotxx/User.hpp> #include "User.hpp"
#include <sstream> #include <sstream>
namespace telebotxx { namespace telebotxx {
User::User() User::User() : id_(-1)
: id_(-1)
{ {
} }
@ -65,4 +65,4 @@ std::ostream& operator<<(std::ostream& os, const User& user)
return os; return os;
} }
} } // namespace telebotxx

View file

@ -1,15 +1,13 @@
#include <catch2/catch_all.hpp>
#include <telebotxx/BotApi.hpp> #include <telebotxx/BotApi.hpp>
#include <telebotxx/Logging.hpp> #include <telebotxx/Logging.hpp>
#include <memory> #include <catch2/catch_all.hpp>
#include <fstream>
#include <rapidjson/document.h> #include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h> #include <rapidjson/istreamwrapper.h>
#include <fstream>
#include <iostream> #include <iostream>
#include <memory>
const char* CONFIG_FILE_NAME = "config.json"; const char* CONFIG_FILE_NAME = "config.json";
@ -107,36 +105,29 @@ TEST_CASE("Send message with markdown", "[API]")
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat}, REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat},
Text{"[Sample text in markdown](http://google.com/)"}, Text{"[Sample text in markdown](http://google.com/)"},
ParseMode::Markdown ParseMode::Markdown));
));
} }
TEST_CASE("Send message with HTML", "[API]") TEST_CASE("Send message with HTML", "[API]")
{ {
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat}, REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat},
Text{ Text{"<a href=\"http://google.com/\">Sample text in HTML</a>"},
"<a href=\"http://google.com/\">Sample text in HTML</a>"}, ParseMode::Html));
ParseMode::Html
));
} }
TEST_CASE("Send message without preview", "[API]") TEST_CASE("Send message without preview", "[API]")
{ {
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat}, REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat}, Text{"http://google.com/"},
Text{"http://google.com/"}, DisableWebPagePreview()));
DisableWebPagePreview()
));
} }
TEST_CASE("Send message without notification", "[API]") TEST_CASE("Send message without notification", "[API]")
{ {
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat}, REQUIRE_NOTHROW(bot->sendMessage(ChatId{config->chat}, Text{"Message without notification"},
Text{"Message without notification"}, DisableNotification()));
DisableNotification()
));
} }
TEST_CASE("Send photo from file", "[API]") TEST_CASE("Send photo from file", "[API]")
@ -147,12 +138,9 @@ TEST_CASE("Send photo from file", "[API]")
TEST_CASE("Send photo from file with caption", "[API]") TEST_CASE("Send photo from file with caption", "[API]")
{ {
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendPhoto(config->chat, REQUIRE_NOTHROW(bot->sendPhoto(config->chat, Photo{File{config->photoFile}},
Photo{File{config->photoFile}}, Caption{"Photo with caption"}));
Caption{"Photo with caption"}
));
} }
TEST_CASE("Send photo from memory", "[API]") TEST_CASE("Send photo from memory", "[API]")
@ -163,29 +151,22 @@ TEST_CASE("Send photo from memory", "[API]")
file.seekg(0, std::ios::beg); file.seekg(0, std::ios::beg);
std::vector<char> buffer(size); std::vector<char> buffer(size);
REQUIRE(file.read(buffer.data(), size)); REQUIRE(file.read(buffer.data(), size));
REQUIRE_NOTHROW(bot->sendPhoto(config->chat, REQUIRE_NOTHROW(bot->sendPhoto(config->chat, Photo{Buffer{buffer.data(), size, config->photoFile}},
Photo{Buffer{buffer.data(), size, config->photoFile}}, Caption{"Photo sent in-memory"}));
Caption{"Photo sent in-memory"}
));
} }
TEST_CASE("Send photo by URL", "[API]") TEST_CASE("Send photo by URL", "[API]")
{ {
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendPhoto(config->chat, REQUIRE_NOTHROW(
Photo{Url{config->photoUrl}}, bot->sendPhoto(config->chat, Photo{Url{config->photoUrl}}, Caption{"Photo sent by URL"}));
Caption{"Photo sent by URL"}
));
} }
TEST_CASE("Send photo without notification", "[API]") TEST_CASE("Send photo without notification", "[API]")
{ {
REQUIRE(bot); REQUIRE(bot);
REQUIRE_NOTHROW(bot->sendPhoto(config->chat, REQUIRE_NOTHROW(bot->sendPhoto(config->chat, Photo{File{config->photoFile}},
Photo{File{config->photoFile}}, Caption{"Photo without notification"}, DisableNotification()));
Caption{"Photo without notification"},
DisableNotification()
));
} }
TEST_CASE("Get updates", "[API]") TEST_CASE("Get updates", "[API]")