-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProtocolTypes.cpp
More file actions
56 lines (46 loc) · 1.65 KB
/
Copy pathProtocolTypes.cpp
File metadata and controls
56 lines (46 loc) · 1.65 KB
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
#include "ProtocolTypes.h"
#include "json.hpp"
#include "util/EncodingUtils.h"
#include <string>
using nlohmann::json;
namespace {
bool IsStringField(const json& value, const char* field) {
auto it = value.find(field);
return it != value.end() && it->is_string();
}
}
std::optional<HostInboundMessage> ParseHostInboundMessageJson(const std::wstring& jsonText) {
try {
// WebView2 hands native UTF-16 JSON; nlohmann::json parses UTF-8, so convert at the bridge edge.
const json parsed = json::parse(WideToUtf8(jsonText));
if (!parsed.is_object() || !IsStringField(parsed, "type")) {
return std::nullopt;
}
const std::string type = parsed.at("type").get<std::string>();
if (type == "page_ready") {
return HostInboundMessage{ PageReadyMessage{} };
}
if (type == "question") {
if (!IsStringField(parsed, "id") || !IsStringField(parsed, "text")) {
return std::nullopt;
}
return HostInboundMessage{ QuestionMessage{
Utf8ToWide(parsed.at("id").get<std::string>()),
Utf8ToWide(parsed.at("text").get<std::string>())
} };
}
return std::nullopt;
}
catch (...) {
return std::nullopt;
}
}
std::wstring SerializeAnswerMessageJson(const AnswerMessage& message) {
// Native answers take the reverse path: typed payload -> JSON -> PostWebMessageAsJson(...).
json payload = {
{ "type", "answer" },
{ "id", WideToUtf8(message.id) },
{ "text", WideToUtf8(message.text) }
};
return Utf8ToWide(payload.dump());
}