1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
| #include <windows.h>
#include <winhttp.h>
#include <stdexcept>
#include <string>
#pragma comment(lib, "winhttp.lib")
class WinHttpHandle {
public:
explicit WinHttpHandle(HINTERNET handle) : handle_(handle) {
if (!handle_) throw std::runtime_error("WinHTTP handle creation failed: " + std::to_string(GetLastError()));
}
~WinHttpHandle() { if (handle_) WinHttpCloseHandle(handle_); }
WinHttpHandle(const WinHttpHandle&) = delete;
WinHttpHandle& operator=(const WinHttpHandle&) = delete;
HINTERNET get() const { return handle_; }
private:
HINTERNET handle_;
};
void CheckWinHttp(BOOL ok) {
if (!ok) throw std::runtime_error("WinHTTP request failed: " + std::to_string(GetLastError()));
}
std::string EscapeJsonString(const std::string& utf8) {
static const char hex[] = "0123456789abcdef";
std::string out;
for (unsigned char ch : utf8) {
switch (ch) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (ch < 0x20) {
out += "\\u00";
out += hex[ch >> 4];
out += hex[ch & 0x0f];
} else {
out += static_cast<char>(ch);
}
}
}
return out;
}
void PostToTeamsChat(const std::wstring& delegatedAccessToken,
const std::wstring& chatId,
const std::string& messageUtf8) {
WinHttpHandle session(WinHttpOpenW(L"TeamsPoster/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0));
WinHttpHandle connection(WinHttpConnectW(session.get(), L"graph.microsoft.com",
INTERNET_DEFAULT_HTTPS_PORT, 0));
const std::wstring path = L"/v1.0/chats/" + chatId + L"/messages";
WinHttpHandle request(WinHttpOpenRequestW(connection.get(), L"POST", path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE));
const std::string json = "{\"body\":{\"content\":\"" + EscapeJsonString(messageUtf8) + "\"}}";
const std::wstring headers = L"Authorization: Bearer " + delegatedAccessToken +
L"\r\nContent-Type: application/json; charset=utf-8\r\n";
const DWORD bodyBytes = static_cast<DWORD>(json.size());
CheckWinHttp(WinHttpSendRequestW(request.get(), headers.c_str(), static_cast<DWORD>(-1L),
const_cast<char*>(json.data()), bodyBytes, bodyBytes, 0));
CheckWinHttp(WinHttpReceiveResponse(request.get(), nullptr));
DWORD status = 0;
DWORD statusBytes = sizeof(status);
CheckWinHttp(WinHttpQueryHeadersW(request.get(),
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusBytes, WINHTTP_NO_HEADER_INDEX));
if (status != 201) {
throw std::runtime_error("Microsoft Graph returned HTTP " + std::to_string(status));
}
}
|