summaryrefslogtreecommitdiff
path: root/src/components/application_manager/rpc_plugins/rc_rpc_plugin/src/commands/mobile/get_interior_vehicle_data_consent_request.cc
blob: 8e58f33fad0cd51dce26eeaa0739bc3e237f54f7 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
 * Copyright (c) 2019, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <algorithm>
#include <ctime>
#include <numeric>
#include <vector>

#include "rc_rpc_plugin/commands/mobile/get_interior_vehicle_data_consent_request.h"
#include "rc_rpc_plugin/rc_helpers.h"
#include "rc_rpc_plugin/rc_module_constants.h"
#include "rc_rpc_plugin/rc_rpc_types.h"
#include "smart_objects/enum_schema_item.h"

namespace rc_rpc_plugin {
namespace app_mngr = application_manager;
namespace commands {

GetInteriorVehicleDataConsentRequest::GetInteriorVehicleDataConsentRequest(
    const application_manager::commands::MessageSharedPtr& message,
    const RCCommandParams& params)
    : RCCommandRequest(message, params) {}

void GetInteriorVehicleDataConsentRequest::Execute() {
  LOG4CXX_AUTO_TRACE(logger_);

  auto& msg_params = (*message_)[app_mngr::strings::msg_params];

  const bool module_ids_exists =
      msg_params.keyExists(message_params::kModuleIds);
  if (!module_ids_exists) {
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "ModuleIds collection is absent in request message");
    return;
  }

  if (msg_params[message_params::kModuleIds].empty()) {
    LOG4CXX_DEBUG(logger_,
                  "ModuleIds collection is empty. Will be add default "
                  "module_id from capabilities");

    const auto module_id =
        rc_capabilities_manager_.GetDefaultModuleIdFromCapabilities(
            ModuleType());

    msg_params[message_params::kModuleIds][0] = module_id;
  }

  const std::string module_type = ModuleType();
  for (const auto module_id :
       *(msg_params[message_params::kModuleIds].asArray())) {
    const ModuleUid module(module_type, module_id.asString());
    if (!rc_capabilities_manager_.CheckIfModuleExistsInCapabilities(module)) {
      LOG4CXX_WARN(logger_,
                   "Accessing not supported module: " << module_type << " "
                                                      << module_id.asString());
      SetResourceState(module_type, ResourceState::FREE);
      SendResponse(false,
                   mobile_apis::Result::UNSUPPORTED_RESOURCE,
                   "Accessing not supported module data");
      return;
    }
  }

  smart_objects::SmartObject location_consents;
  GetLocationConsents(location_consents);

  smart_objects::SmartObject response_params;
  if (GetCalculatedVehicleDataConsent(location_consents, response_params)) {
    LOG4CXX_DEBUG(
        logger_,
        "No need to send request to HMI. Sending cached consents to mobile");
    SendResponse(true, mobile_apis::Result::SUCCESS, nullptr, &response_params);
    return;
  }

  (*message_)[application_manager::strings::msg_params]
             [application_manager::strings::app_id] = connection_key();

  LOG4CXX_DEBUG(logger_,
                "Filtering out module ids with serviceArea which does not "
                "cover userLocation");

  smart_objects::SmartObject hmi_msg_params(msg_params);
  auto module_ids_for_consent =
      hmi_msg_params[message_params::kModuleIds].asArray();
  module_ids_for_consent->clear();

  auto module_ids = msg_params[message_params::kModuleIds].asArray();
  for (uint32_t i = 0; i < module_ids->size(); i++) {
    // Only add modules whose serviceArea covers the userLocation
    if (location_consents[i].asBool()) {
      module_ids_for_consent->push_back((*module_ids)[i]);
    }
  }

  SendHMIRequest(hmi_apis::FunctionID::RC_GetInteriorVehicleDataConsent,
                 (&hmi_msg_params),
                 true);
}

void GetInteriorVehicleDataConsentRequest::on_event(
    const app_mngr::event_engine::Event& event) {
  LOG4CXX_AUTO_TRACE(logger_);

  if (event.id() != hmi_apis::FunctionID::RC_GetInteriorVehicleDataConsent) {
    LOG4CXX_ERROR(logger_, "Received wrong event. FunctionID: " << event.id());
    return;
  }

  auto temp_response = event.smart_object();

  auto result_code =
      GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
          temp_response[app_mngr::strings::params][app_mngr::hmi_response::code]
              .asUInt()));

  const bool success_result =
      helpers::Compare<mobile_apis::Result::eType, helpers::EQ, helpers::ONE>(
          result_code,
          mobile_apis::Result::SUCCESS,
          mobile_apis::Result::WARNINGS);

  if (!success_result) {
    std::string info;
    GetInfo(temp_response, info);
    SendResponse(false, result_code, info.c_str(), nullptr);
    return;
  }

  if (!temp_response[app_mngr::strings::msg_params].keyExists(
          message_params::kAllowed) ||
      temp_response[app_mngr::strings::msg_params][message_params::kAllowed]
          .empty()) {
    std::string info_out =
        "Collection of consents is absent in HMI response or empty";
    LOG4CXX_ERROR(logger_, info_out);
    SendResponse(false, mobile_apis::Result::GENERIC_ERROR, info_out.c_str());
    return;
  }

  LOG4CXX_DEBUG(logger_,
                "Adding back filtered out module ids for response to mobile");

  smart_objects::SmartObject all_consents;
  GetLocationConsents(all_consents);
  uint32_t number_of_expected_response_consents = std::accumulate(
      all_consents.asArray()->begin(),
      all_consents.asArray()->end(),
      uint32_t(0),
      [](uint32_t num_consents, smart_objects::SmartObject& consent) {
        // Only module ids with valid location consents were sent to the hmi
        return (consent.asBool()) ? num_consents + 1 : num_consents;
      });

  const auto response_consents =
      temp_response[app_mngr::strings::msg_params][message_params::kAllowed]
          .asArray();

  if (number_of_expected_response_consents != response_consents->size()) {
    std::string info_out =
        "HMI response has incorrect number of consents expected: " +
        std::to_string(number_of_expected_response_consents) +
        ", actual: " + std::to_string(response_consents->size());
    LOG4CXX_ERROR(logger_, info_out);
    SendResponse(false, mobile_apis::Result::GENERIC_ERROR, info_out.c_str());
    return;
  }
  uint32_t response_consents_counter = 0;

  for (auto& consent : *(all_consents.asArray())) {
    // Only modify consent for moduleIds allowed by location constraints
    if (consent.asBool()) {
      consent = (*response_consents)[response_consents_counter];
      response_consents_counter++;
    }
  }

  temp_response[app_mngr::strings::msg_params][message_params::kAllowed] =
      all_consents;

  const auto hmi_response = temp_response;
  std::string response_info;
  const bool result_of_saving = SaveModuleIdConsents(
      response_info, hmi_response[app_mngr::strings::msg_params]);

  if (!result_of_saving) {
    LOG4CXX_DEBUG(logger_, "Consent saving failed");
    SendResponse(
        false, mobile_apis::Result::GENERIC_ERROR, response_info.c_str());
    return;
  }

  smart_objects::SmartObject response_params =
      hmi_response[app_mngr::strings::msg_params];
  std::string info;
  GetInfo(hmi_response, info);
  SendResponse(success_result,
               result_code,
               info.c_str(),
               success_result ? &response_params : nullptr);
}

std::string GetInteriorVehicleDataConsentRequest::ModuleType() const {
  mobile_apis::ModuleType::eType module_type =
      static_cast<mobile_apis::ModuleType::eType>(
          (*message_)[app_mngr::strings::msg_params]
                     [message_params::kModuleType]
                         .asUInt());

  const char* str;
  const bool ok = smart_objects::EnumConversionHelper<
      mobile_apis::ModuleType::eType>::EnumToCString(module_type, &str);
  return ok ? str : "unknown";
}

std::string GetInteriorVehicleDataConsentRequest::ModuleId() const {
  return std::string();
}

GetInteriorVehicleDataConsentRequest::~GetInteriorVehicleDataConsentRequest() {}

void GetInteriorVehicleDataConsentRequest::GetLocationConsents(
    smart_objects::SmartObject& location_consents) {
  location_consents =
      smart_objects::SmartObject(smart_objects::SmartType::SmartType_Array);

  auto modules_consent_array = location_consents.asArray();
  const auto module_ids =
      (*message_)[app_mngr::strings::msg_params][message_params::kModuleIds]
          .asArray();
  const std::string module_type = ModuleType();

  auto is_user_location_valid = [this](ModuleUid& module) {
    const auto app_ptr = application_manager_.application(connection_key());
    const auto extension = RCHelpers::GetRCExtension(*app_ptr);
    const auto user_location = extension->GetUserLocation();
    const auto module_service_area =
        rc_capabilities_manager_.GetModuleServiceArea(module);
    const auto driver =
        rc_capabilities_manager_.GetDriverLocationFromSeatLocationCapability();
    const bool is_driver = user_location == driver;
    if (is_driver || user_location.IntersectionExists(module_service_area)) {
      return true;
    }
    return false;
  };

  for (auto& module_id : (*module_ids)) {
    bool consent = true;
    if (rc_capabilities_manager_.IsSeatLocationCapabilityProvided()) {
      ModuleUid module(module_type, module_id.asString());
      consent = is_user_location_valid(module);
    }
    modules_consent_array->push_back(smart_objects::SmartObject(consent));
  }
}

bool GetInteriorVehicleDataConsentRequest::GetCalculatedVehicleDataConsent(
    const smart_objects::SmartObject& location_consents,
    smart_objects::SmartObject& out_response) const {
  LOG4CXX_AUTO_TRACE(logger_);

  out_response =
      smart_objects::SmartObject(smart_objects::SmartType::SmartType_Map);
  out_response[message_params::kAllowed] =
      smart_objects::SmartObject(smart_objects::SmartType::SmartType_Array);

  auto modules_consent_array = out_response[message_params::kAllowed].asArray();
  const auto module_ids =
      (*message_)[app_mngr::strings::msg_params][message_params::kModuleIds]
          .asArray();
  const std::string module_type = ModuleType();

  auto get_disallowed_multiple_access_consent =
      [this](const ModuleUid& module_uid) {
        auto app = application_manager_.application(connection_key());
        const uint32_t app_id = app->app_id();
        const bool is_resource_available =
            (resource_allocation_manager_.AcquireResource(
                 module_uid.first, module_uid.second, app_id) ==
             AcquireResult::ALLOWED);
        return (is_resource_available)
                   ? rc_rpc_types::ModuleConsent::CONSENTED
                   : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
      };

  auto get_auto_allow_consent = [](const ModuleUid& module_uid) {
    return rc_rpc_types::ModuleConsent::CONSENTED;
  };

  auto get_auto_deny_consent = [this](const ModuleUid& module_uid) {
    auto app = application_manager_.application(connection_key());
    const uint32_t app_id = app->app_id();
    const bool is_resource_available =
        (resource_allocation_manager_.AcquireResource(
             module_uid.first, module_uid.second, app_id) ==
         AcquireResult::ALLOWED);
    return (is_resource_available) ? rc_rpc_types::ModuleConsent::CONSENTED
                                   : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
  };

  auto get_ask_driver_consent = [this](const ModuleUid& module_uid) {
    auto app = application_manager_.application(connection_key());
    const std::string policy_app_id = app->policy_app_id();
    const std::string mac_address = app->mac_address();

    auto consent = rc_consent_manager_.GetModuleConsent(
        policy_app_id, mac_address, module_uid);

    if (rc_rpc_types::ModuleConsent::NOT_EXISTS == consent) {
      auto acquire_result = resource_allocation_manager_.AcquireResource(
          module_uid.first, module_uid.second, app->app_id());
      const bool is_resource_available =
          (acquire_result == AcquireResult::ALLOWED);
      const bool is_resource_rejected =
          (acquire_result == AcquireResult::REJECTED);

      if (!is_resource_available && !is_resource_rejected) {
        return rc_rpc_types::ModuleConsent::NOT_EXISTS;
      }

      return (is_resource_available)
                 ? rc_rpc_types::ModuleConsent::CONSENTED
                 : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
    }

    const bool is_consent_allowed =
        (rc_rpc_types::ModuleConsent::CONSENTED == consent);
    return (is_consent_allowed) ? rc_rpc_types::ModuleConsent::CONSENTED
                                : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
  };

  for (uint32_t i = 0; i < module_ids->size(); ++i) {
    const ModuleUid module_uid(module_type, (*module_ids)[i].asString());
    if (!location_consents[i].asBool()) {
      LOG4CXX_DEBUG(logger_,
                    "User is outside the serviceArea for module("
                        << module_uid.first << ", " << module_uid.second
                        << ")");
      modules_consent_array->push_back(smart_objects::SmartObject(false));
      continue;
    }

    rc_rpc_types::ModuleConsent module_consent;

    const bool is_multiple_access_allowed =
        rc_capabilities_manager_.IsMultipleAccessAllowed(module_uid);

    if (!is_multiple_access_allowed) {
      module_consent = get_disallowed_multiple_access_consent(module_uid);
      modules_consent_array->push_back(smart_objects::SmartObject(
          module_consent == rc_rpc_types::ModuleConsent::CONSENTED));
      continue;
    }

    const auto access_mode = resource_allocation_manager_.GetAccessMode();
    switch (access_mode) {
      case hmi_apis::Common_RCAccessMode::AUTO_ALLOW: {
        module_consent = get_auto_allow_consent(module_uid);
        modules_consent_array->push_back(smart_objects::SmartObject(
            module_consent == rc_rpc_types::ModuleConsent::CONSENTED));
        break;
      }
      case hmi_apis::Common_RCAccessMode::AUTO_DENY: {
        module_consent = get_auto_deny_consent(module_uid);
        modules_consent_array->push_back(smart_objects::SmartObject(
            module_consent == rc_rpc_types::ModuleConsent::CONSENTED));
        break;
      }
      case hmi_apis::Common_RCAccessMode::ASK_DRIVER: {
        module_consent = get_ask_driver_consent(module_uid);
        if (module_consent == rc_rpc_types::ModuleConsent::NOT_EXISTS) {
          LOG4CXX_DEBUG(
              logger_,
              "Can't provide calculated consents - should send request to HMI");
          modules_consent_array->clear();
          return false;
        }
        modules_consent_array->push_back(smart_objects::SmartObject(
            module_consent == rc_rpc_types::ModuleConsent::CONSENTED));
        break;
      }
      default: { break; }
    }
  }

  return true;
}

bool GetInteriorVehicleDataConsentRequest::SaveModuleIdConsents(
    std::string& info_out, const smart_objects::SmartObject& msg_params) {
  LOG4CXX_AUTO_TRACE(logger_);

  const auto& allowed = msg_params[message_params::kAllowed];
  const auto& moduleIds =
      (*message_)[app_mngr::strings::msg_params][message_params::kModuleIds];

  if (allowed.length() != moduleIds.length()) {
    info_out =
        "The received module_id collection from mobile and received consent "
        "collection from HMI are not equal by size.";
    LOG4CXX_ERROR(logger_, info_out);
    return false;
  }
  std::string module_type = ModuleType();
  auto module_ids = RCHelpers::RetrieveModuleIds(moduleIds);
  auto module_allowed = RCHelpers::RetrieveModuleConsents(allowed);

  auto module_consents =
      RCHelpers::FillModuleConsents(module_type, module_ids, module_allowed);

  auto application = application_manager_.application(connection_key());
  if (!application) {
    LOG4CXX_ERROR(logger_,
                  "Application with connection key:" << connection_key()
                                                     << " isn't registered");
    return false;
  }
  std::string policy_app_id = application->policy_app_id();
  const auto mac_address = application->mac_address();
  rc_consent_manager_.SaveModuleConsents(
      policy_app_id, mac_address, module_consents);
  return true;
}

}  // namespace commands
}  // namespace rc_rpc_plugin