1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "av_trans_message.h"
17
18 #include "av_trans_constants.h"
19
20 namespace OHOS {
21 namespace DistributedHardware {
22 const std::string KEY_TYPE = "type";
23 const std::string KEY_CONTENT = "content";
24 const std::string KEY_DST_DEVID = "dstDevId";
25
AVTransMessage()26 AVTransMessage::AVTransMessage()
27 {
28 type_ = 0;
29 }
30
AVTransMessage(uint32_t type,std::string content,std::string dstDevId)31 AVTransMessage::AVTransMessage(uint32_t type, std::string content, std::string dstDevId)
32 : type_(type), content_(content), dstDevId_(dstDevId)
33 {
34 }
35
~AVTransMessage()36 AVTransMessage::~AVTransMessage()
37 {
38 }
39
MarshalMessage()40 std::string AVTransMessage::MarshalMessage()
41 {
42 nlohmann::json msgJson;
43 msgJson[KEY_TYPE] = type_;
44 msgJson[KEY_CONTENT] = content_;
45 msgJson[KEY_DST_DEVID] = dstDevId_;
46 return msgJson.dump();
47 }
48
UnmarshalMessage(const std::string & jsonStr,const std::string & peerDevId)49 bool AVTransMessage::UnmarshalMessage(const std::string& jsonStr, const std::string &peerDevId)
50 {
51 nlohmann::json msgJson = nlohmann::json::parse(jsonStr, nullptr, false);
52 if (msgJson.is_discarded()) {
53 return false;
54 }
55 if (!IsUInt32(msgJson, KEY_TYPE) || !IsString(msgJson, KEY_CONTENT)) {
56 return false;
57 }
58 type_ = msgJson[KEY_TYPE].get<uint32_t>();
59 content_ = msgJson[KEY_CONTENT].get<std::string>();
60 dstDevId_ = peerDevId;
61 return true;
62 }
63
IsUInt32(const nlohmann::json & msgJson,const std::string & key)64 bool AVTransMessage::IsUInt32(const nlohmann::json &msgJson, const std::string &key)
65 {
66 return msgJson.contains(key) && msgJson[key].is_number_unsigned() && msgJson[key] <= UINT32_MAX;
67 }
68
IsString(const nlohmann::json & msgJson,const std::string & key)69 bool AVTransMessage::IsString(const nlohmann::json &msgJson, const std::string &key)
70 {
71 return msgJson.contains(key) && msgJson[key].is_string() && msgJson[key].size() <= MAX_MESSAGES_LEN;
72 }
73 } // namespace DistributedHardware
74 } // namespace OHOS