cast_message_handler.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/cast_channel/cast_message_handler.h"
  5. #include <tuple>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/bind.h"
  9. #include "base/containers/cxx20_erase.h"
  10. #include "base/observer_list.h"
  11. #include "base/rand_util.h"
  12. #include "base/strings/stringprintf.h"
  13. #include "base/time/default_tick_clock.h"
  14. #include "components/cast_channel/cast_message_util.h"
  15. #include "components/cast_channel/cast_socket_service.h"
  16. namespace cast_channel {
  17. namespace {
  18. // The max launch timeout amount for session launch requests.
  19. constexpr base::TimeDelta kLaunchMaxTimeout = base::Minutes(2);
  20. // The max size of Cast Message is 64KB.
  21. constexpr int kMaxCastMessagePayload = 64 * 1024;
  22. void ReportParseError(const std::string& error) {
  23. DVLOG(1) << "Error parsing JSON message: " << error;
  24. }
  25. } // namespace
  26. GetAppAvailabilityRequest::GetAppAvailabilityRequest(
  27. int request_id,
  28. GetAppAvailabilityCallback callback,
  29. const base::TickClock* clock,
  30. const std::string& app_id)
  31. : PendingRequest(request_id, std::move(callback), clock), app_id(app_id) {}
  32. GetAppAvailabilityRequest::~GetAppAvailabilityRequest() = default;
  33. VirtualConnection::VirtualConnection(int channel_id,
  34. const std::string& source_id,
  35. const std::string& destination_id)
  36. : channel_id(channel_id),
  37. source_id(source_id),
  38. destination_id(destination_id) {}
  39. VirtualConnection::~VirtualConnection() = default;
  40. bool VirtualConnection::operator<(const VirtualConnection& other) const {
  41. return std::tie(channel_id, source_id, destination_id) <
  42. std::tie(other.channel_id, other.source_id, other.destination_id);
  43. }
  44. InternalMessage::InternalMessage(CastMessageType type,
  45. const std::string& message_namespace,
  46. base::Value::Dict message)
  47. : type(type),
  48. message_namespace(message_namespace),
  49. message(std::move(message)) {}
  50. InternalMessage::~InternalMessage() = default;
  51. CastMessageHandler::CastMessageHandler(CastSocketService* socket_service,
  52. ParseJsonCallback parse_json,
  53. const std::string& user_agent,
  54. const std::string& browser_version,
  55. const std::string& locale)
  56. : sender_id_(base::StringPrintf("sender-%d", base::RandInt(0, 1000000))),
  57. parse_json_(std::move(parse_json)),
  58. user_agent_(user_agent),
  59. browser_version_(browser_version),
  60. locale_(locale),
  61. socket_service_(socket_service),
  62. clock_(base::DefaultTickClock::GetInstance()) {
  63. DETACH_FROM_SEQUENCE(sequence_checker_);
  64. socket_service_->task_runner()->PostTask(
  65. FROM_HERE, base::BindOnce(&CastSocketService::AddObserver,
  66. base::Unretained(socket_service_),
  67. base::Unretained(this)));
  68. }
  69. CastMessageHandler::~CastMessageHandler() {
  70. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  71. socket_service_->RemoveObserver(this);
  72. }
  73. void CastMessageHandler::EnsureConnection(
  74. int channel_id,
  75. const std::string& source_id,
  76. const std::string& destination_id,
  77. VirtualConnectionType connection_type) {
  78. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  79. CastSocket* socket = socket_service_->GetSocket(channel_id);
  80. if (!socket) {
  81. DVLOG(2) << "Socket not found: " << channel_id;
  82. return;
  83. }
  84. DoEnsureConnection(socket, source_id, destination_id, connection_type);
  85. }
  86. void CastMessageHandler::CloseConnection(int channel_id,
  87. const std::string& source_id,
  88. const std::string& destination_id) {
  89. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  90. CastSocket* socket = socket_service_->GetSocket(channel_id);
  91. if (!socket) {
  92. return;
  93. }
  94. VirtualConnection connection(socket->id(), source_id, destination_id);
  95. if (virtual_connections_.find(connection) == virtual_connections_.end())
  96. return;
  97. VLOG(1) << "Closing VC for channel: " << connection.channel_id
  98. << ", source: " << connection.source_id
  99. << ", dest: " << connection.destination_id;
  100. socket->transport()->SendMessage(
  101. CreateVirtualConnectionClose(connection.source_id,
  102. connection.destination_id),
  103. base::BindOnce(&CastMessageHandler::OnMessageSent,
  104. weak_ptr_factory_.GetWeakPtr()));
  105. // Assume the virtual connection close will succeed. Eventually the receiver
  106. // will remove the connection even if it doesn't.
  107. virtual_connections_.erase(connection);
  108. }
  109. CastMessageHandler::PendingRequests*
  110. CastMessageHandler::GetOrCreatePendingRequests(int channel_id) {
  111. CastMessageHandler::PendingRequests* requests = nullptr;
  112. auto pending_it = pending_requests_.find(channel_id);
  113. if (pending_it != pending_requests_.end()) {
  114. return pending_it->second.get();
  115. }
  116. auto new_requests = std::make_unique<CastMessageHandler::PendingRequests>();
  117. requests = new_requests.get();
  118. pending_requests_.emplace(channel_id, std::move(new_requests));
  119. return requests;
  120. }
  121. void CastMessageHandler::RequestAppAvailability(
  122. CastSocket* socket,
  123. const std::string& app_id,
  124. GetAppAvailabilityCallback callback) {
  125. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  126. int channel_id = socket->id();
  127. auto* requests = GetOrCreatePendingRequests(channel_id);
  128. int request_id = NextRequestId();
  129. DVLOG(2) << __func__ << ", channel_id: " << channel_id
  130. << ", app_id: " << app_id << ", request_id: " << request_id;
  131. if (requests->AddAppAvailabilityRequest(
  132. std::make_unique<GetAppAvailabilityRequest>(
  133. request_id, std::move(callback), clock_, app_id))) {
  134. SendCastMessageToSocket(socket, CreateGetAppAvailabilityRequest(
  135. sender_id_, request_id, app_id));
  136. }
  137. }
  138. void CastMessageHandler::RequestReceiverStatus(int channel_id) {
  139. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  140. CastSocket* socket = socket_service_->GetSocket(channel_id);
  141. if (!socket) {
  142. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  143. return;
  144. }
  145. int request_id = NextRequestId();
  146. SendCastMessageToSocket(socket,
  147. CreateReceiverStatusRequest(sender_id_, request_id));
  148. }
  149. Result CastMessageHandler::SendBroadcastMessage(
  150. int channel_id,
  151. const std::vector<std::string>& app_ids,
  152. const BroadcastRequest& request) {
  153. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  154. CastSocket* socket = socket_service_->GetSocket(channel_id);
  155. if (!socket) {
  156. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  157. return Result::kFailed;
  158. }
  159. int request_id = NextRequestId();
  160. DVLOG(2) << __func__ << ", channel_id: " << channel_id
  161. << ", request_id: " << request_id;
  162. // Note: Even though the message is formatted like a request, we don't care
  163. // about the response, as broadcasts are fire-and-forget.
  164. CastMessage message =
  165. CreateBroadcastRequest(sender_id_, request_id, app_ids, request);
  166. if (message.ByteSizeLong() > kMaxCastMessagePayload) {
  167. return Result::kFailed;
  168. }
  169. SendCastMessageToSocket(socket, message);
  170. return Result::kOk;
  171. }
  172. void CastMessageHandler::LaunchSession(
  173. int channel_id,
  174. const std::string& app_id,
  175. base::TimeDelta launch_timeout,
  176. const std::vector<std::string>& supported_app_types,
  177. const absl::optional<base::Value>& app_params,
  178. LaunchSessionCallback callback) {
  179. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  180. CastSocket* socket = socket_service_->GetSocket(channel_id);
  181. if (!socket) {
  182. std::move(callback).Run(GetLaunchSessionResponseError(
  183. base::StringPrintf("Socket not found: %d.", channel_id)));
  184. return;
  185. }
  186. auto* requests = GetOrCreatePendingRequests(channel_id);
  187. int request_id = NextRequestId();
  188. // Cap the max launch timeout to avoid long-living pending requests.
  189. launch_timeout = std::min(launch_timeout, kLaunchMaxTimeout);
  190. DVLOG(2) << __func__ << ", channel_id: " << channel_id
  191. << ", request_id: " << request_id;
  192. CastMessage message = CreateLaunchRequest(
  193. sender_id_, request_id, app_id, locale_, supported_app_types, app_params);
  194. if (message.ByteSizeLong() > kMaxCastMessagePayload) {
  195. std::move(callback).Run(GetLaunchSessionResponseError(
  196. "Message size exceeds maximum cast channel message payload."));
  197. return;
  198. }
  199. if (requests->AddLaunchRequest(std::make_unique<LaunchSessionRequest>(
  200. request_id, std::move(callback), clock_),
  201. launch_timeout)) {
  202. SendCastMessageToSocket(socket, message);
  203. }
  204. }
  205. void CastMessageHandler::StopSession(
  206. int channel_id,
  207. const std::string& session_id,
  208. const absl::optional<std::string>& client_id,
  209. ResultCallback callback) {
  210. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  211. CastSocket* socket = socket_service_->GetSocket(channel_id);
  212. if (!socket) {
  213. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  214. std::move(callback).Run(cast_channel::Result::kFailed);
  215. return;
  216. }
  217. auto* requests = GetOrCreatePendingRequests(channel_id);
  218. int request_id = NextRequestId();
  219. DVLOG(2) << __func__ << ", channel_id: " << channel_id
  220. << ", request_id: " << request_id;
  221. if (requests->AddStopRequest(std::make_unique<StopSessionRequest>(
  222. request_id, std::move(callback), clock_))) {
  223. SendCastMessageToSocket(
  224. socket, CreateStopRequest(client_id.value_or(sender_id_), request_id,
  225. session_id));
  226. }
  227. }
  228. Result CastMessageHandler::SendCastMessage(int channel_id,
  229. const CastMessage& message) {
  230. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  231. CastSocket* socket = socket_service_->GetSocket(channel_id);
  232. if (!socket) {
  233. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  234. return Result::kFailed;
  235. }
  236. SendCastMessageToSocket(socket, message);
  237. return Result::kOk;
  238. }
  239. Result CastMessageHandler::SendAppMessage(int channel_id,
  240. const CastMessage& message) {
  241. DCHECK(!IsCastReservedNamespace(message.namespace_()))
  242. << ": unexpected app message namespace: " << message.namespace_();
  243. if (message.ByteSizeLong() > kMaxCastMessagePayload) {
  244. return Result::kFailed;
  245. }
  246. return SendCastMessage(channel_id, message);
  247. }
  248. absl::optional<int> CastMessageHandler::SendMediaRequest(
  249. int channel_id,
  250. const base::Value& body,
  251. const std::string& source_id,
  252. const std::string& destination_id) {
  253. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  254. CastSocket* socket = socket_service_->GetSocket(channel_id);
  255. if (!socket) {
  256. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  257. return absl::nullopt;
  258. }
  259. int request_id = NextRequestId();
  260. SendCastMessageToSocket(
  261. socket, CreateMediaRequest(body, request_id, source_id, destination_id));
  262. return request_id;
  263. }
  264. void CastMessageHandler::SendSetVolumeRequest(int channel_id,
  265. const base::Value& body,
  266. const std::string& source_id,
  267. ResultCallback callback) {
  268. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  269. CastSocket* socket = socket_service_->GetSocket(channel_id);
  270. if (!socket) {
  271. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  272. std::move(callback).Run(Result::kFailed);
  273. return;
  274. }
  275. auto* requests = GetOrCreatePendingRequests(channel_id);
  276. int request_id = NextRequestId();
  277. requests->AddVolumeRequest(std::make_unique<SetVolumeRequest>(
  278. request_id, std::move(callback), clock_));
  279. SendCastMessageToSocket(socket,
  280. CreateSetVolumeRequest(body, request_id, source_id));
  281. }
  282. void CastMessageHandler::AddObserver(Observer* observer) {
  283. observers_.AddObserver(observer);
  284. }
  285. void CastMessageHandler::RemoveObserver(Observer* observer) {
  286. observers_.RemoveObserver(observer);
  287. }
  288. void CastMessageHandler::OnError(const CastSocket& socket,
  289. ChannelError error_state) {
  290. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  291. int channel_id = socket.id();
  292. base::EraseIf(virtual_connections_,
  293. [&channel_id](const VirtualConnection& connection) {
  294. return connection.channel_id == channel_id;
  295. });
  296. pending_requests_.erase(channel_id);
  297. }
  298. void CastMessageHandler::OnMessage(const CastSocket& socket,
  299. const CastMessage& message) {
  300. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  301. // TODO(crbug.com/1291736): Splitting internal messages into a separate code
  302. // path with a separate data type is pretty questionable, because it causes
  303. // duplicated code paths in the downstream logic (manifested as separate
  304. // OnAppMessage and OnInternalMessage methods).
  305. if (IsCastReservedNamespace(message.namespace_())) {
  306. if (message.payload_type() ==
  307. cast::channel::CastMessage_PayloadType_STRING) {
  308. VLOG(1) << __func__ << ": channel_id: " << socket.id()
  309. << ", message: " << message;
  310. parse_json_.Run(
  311. message.payload_utf8(),
  312. base::BindOnce(&CastMessageHandler::HandleCastInternalMessage,
  313. weak_ptr_factory_.GetWeakPtr(), socket.id(),
  314. message.source_id(), message.destination_id(),
  315. message.namespace_()));
  316. } else {
  317. DLOG(ERROR) << "Dropping internal message with binary payload: "
  318. << message.namespace_();
  319. }
  320. } else {
  321. DVLOG(2) << "Got app message from cast channel with namespace: "
  322. << message.namespace_();
  323. for (auto& observer : observers_)
  324. observer.OnAppMessage(socket.id(), message);
  325. }
  326. }
  327. void CastMessageHandler::OnReadyStateChanged(const CastSocket& socket) {
  328. if (socket.ready_state() == ReadyState::CLOSED)
  329. pending_requests_.erase(socket.id());
  330. }
  331. void CastMessageHandler::HandleCastInternalMessage(
  332. int channel_id,
  333. const std::string& source_id,
  334. const std::string& destination_id,
  335. const std::string& namespace_,
  336. data_decoder::DataDecoder::ValueOrError parse_result) {
  337. if (!parse_result.has_value()) {
  338. ReportParseError(parse_result.error());
  339. return;
  340. }
  341. base::Value::Dict* payload = parse_result->GetIfDict();
  342. if (!payload) {
  343. ReportParseError("Parsed message not a dictionary");
  344. return;
  345. }
  346. // Check if the socket still exists as it might have been removed during
  347. // message parsing.
  348. if (!socket_service_->GetSocket(channel_id)) {
  349. DVLOG(2) << __func__ << ": socket not found: " << channel_id;
  350. return;
  351. }
  352. absl::optional<int> request_id = GetRequestIdFromResponse(*payload);
  353. if (request_id) {
  354. auto requests_it = pending_requests_.find(channel_id);
  355. if (requests_it != pending_requests_.end())
  356. // You might think this method should return in this case, but there is at
  357. // least one message type (RECEIVER_STATUS), that has a request ID but
  358. // also needs to be handled by the registered observers.
  359. requests_it->second->HandlePendingRequest(*request_id, *payload);
  360. }
  361. CastMessageType type = ParseMessageTypeFromPayload(*payload);
  362. if (type == CastMessageType::kOther) {
  363. DVLOG(2) << "Unknown type in message: " << payload;
  364. return;
  365. }
  366. if (type == CastMessageType::kCloseConnection) {
  367. // Source / destination is flipped.
  368. virtual_connections_.erase(
  369. VirtualConnection(channel_id, destination_id, source_id));
  370. return;
  371. }
  372. InternalMessage internal_message(type, namespace_, std::move(*payload));
  373. for (auto& observer : observers_)
  374. observer.OnInternalMessage(channel_id, internal_message);
  375. }
  376. void CastMessageHandler::SendCastMessageToSocket(CastSocket* socket,
  377. const CastMessage& message) {
  378. // A virtual connection must be opened to the receiver before other messages
  379. // can be sent.
  380. DoEnsureConnection(socket, message.source_id(), message.destination_id(),
  381. GetConnectionType(message.destination_id()));
  382. VLOG(1) << __func__ << ": channel_id: " << socket->id()
  383. << ", message: " << message;
  384. socket->transport()->SendMessage(
  385. message, base::BindOnce(&CastMessageHandler::OnMessageSent,
  386. weak_ptr_factory_.GetWeakPtr()));
  387. }
  388. void CastMessageHandler::DoEnsureConnection(
  389. CastSocket* socket,
  390. const std::string& source_id,
  391. const std::string& destination_id,
  392. VirtualConnectionType connection_type) {
  393. VirtualConnection connection(socket->id(), source_id, destination_id);
  394. // If there is already a connection, there is nothing to do.
  395. if (virtual_connections_.find(connection) != virtual_connections_.end())
  396. return;
  397. VLOG(1) << "Creating VC for channel: " << connection.channel_id
  398. << ", source: " << connection.source_id
  399. << ", dest: " << connection.destination_id;
  400. CastMessage virtual_connection_request = CreateVirtualConnectionRequest(
  401. connection.source_id, connection.destination_id, connection_type,
  402. user_agent_, browser_version_);
  403. socket->transport()->SendMessage(
  404. virtual_connection_request,
  405. base::BindOnce(&CastMessageHandler::OnMessageSent,
  406. weak_ptr_factory_.GetWeakPtr()));
  407. // We assume the virtual connection request will succeed; otherwise this
  408. // will eventually self-correct.
  409. virtual_connections_.insert(connection);
  410. }
  411. void CastMessageHandler::OnMessageSent(int result) {
  412. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  413. DVLOG_IF(2, result < 0) << "SendMessage failed with code: " << result;
  414. }
  415. CastMessageHandler::PendingRequests::PendingRequests() = default;
  416. CastMessageHandler::PendingRequests::~PendingRequests() {
  417. for (auto& request : pending_app_availability_requests_) {
  418. std::move(request->callback)
  419. .Run(request->app_id, GetAppAvailabilityResult::kUnknown);
  420. }
  421. if (pending_launch_session_request_) {
  422. LaunchSessionResponse response;
  423. response.result = LaunchSessionResponse::kError;
  424. std::move(pending_launch_session_request_->callback)
  425. .Run(std::move(response));
  426. }
  427. if (pending_stop_session_request_)
  428. std::move(pending_stop_session_request_->callback).Run(Result::kFailed);
  429. for (auto& request : pending_volume_requests_by_id_)
  430. std::move(request.second->callback).Run(Result::kFailed);
  431. }
  432. bool CastMessageHandler::PendingRequests::AddAppAvailabilityRequest(
  433. std::unique_ptr<GetAppAvailabilityRequest> request) {
  434. const std::string& app_id = request->app_id;
  435. int request_id = request->request_id;
  436. request->timeout_timer.Start(
  437. FROM_HERE, kRequestTimeout,
  438. base::BindOnce(
  439. &CastMessageHandler::PendingRequests::AppAvailabilityTimedOut,
  440. base::Unretained(this), request_id));
  441. // Look for a request with the given app ID.
  442. bool found = std::find_if(pending_app_availability_requests_.begin(),
  443. pending_app_availability_requests_.end(),
  444. [&app_id](const auto& old_request) {
  445. return old_request->app_id == app_id;
  446. }) != pending_app_availability_requests_.end();
  447. pending_app_availability_requests_.emplace_back(std::move(request));
  448. return !found;
  449. }
  450. bool CastMessageHandler::PendingRequests::AddLaunchRequest(
  451. std::unique_ptr<LaunchSessionRequest> request,
  452. base::TimeDelta timeout) {
  453. if (pending_launch_session_request_) {
  454. std::move(request->callback)
  455. .Run(cast_channel::GetLaunchSessionResponseError(
  456. "There already exists a launch request for the channel"));
  457. return false;
  458. }
  459. int request_id = request->request_id;
  460. request->timeout_timer.Start(
  461. FROM_HERE, timeout,
  462. base::BindOnce(
  463. &CastMessageHandler::PendingRequests::LaunchSessionTimedOut,
  464. base::Unretained(this), request_id));
  465. pending_launch_session_request_ = std::move(request);
  466. return true;
  467. }
  468. bool CastMessageHandler::PendingRequests::AddStopRequest(
  469. std::unique_ptr<StopSessionRequest> request) {
  470. if (pending_stop_session_request_) {
  471. std::move(request->callback).Run(cast_channel::Result::kFailed);
  472. return false;
  473. }
  474. int request_id = request->request_id;
  475. request->timeout_timer.Start(
  476. FROM_HERE, kRequestTimeout,
  477. base::BindOnce(&CastMessageHandler::PendingRequests::StopSessionTimedOut,
  478. base::Unretained(this), request_id));
  479. pending_stop_session_request_ = std::move(request);
  480. return true;
  481. }
  482. void CastMessageHandler::PendingRequests::AddVolumeRequest(
  483. std::unique_ptr<SetVolumeRequest> request) {
  484. int request_id = request->request_id;
  485. request->timeout_timer.Start(
  486. FROM_HERE, kRequestTimeout,
  487. base::BindOnce(&CastMessageHandler::PendingRequests::SetVolumeTimedOut,
  488. base::Unretained(this), request_id));
  489. pending_volume_requests_by_id_.emplace(request_id, std::move(request));
  490. }
  491. void CastMessageHandler::PendingRequests::HandlePendingRequest(
  492. int request_id,
  493. const base::Value::Dict& response) {
  494. // Look up an app availability request by its |request_id|.
  495. auto app_availability_it =
  496. std::find_if(pending_app_availability_requests_.begin(),
  497. pending_app_availability_requests_.end(),
  498. [request_id](const auto& request_ptr) {
  499. return request_ptr->request_id == request_id;
  500. });
  501. // If we found a request, process and remove all requests with the same
  502. // |app_id|, which will of course include the one we just found.
  503. if (app_availability_it != pending_app_availability_requests_.end()) {
  504. std::string app_id = (*app_availability_it)->app_id;
  505. GetAppAvailabilityResult result =
  506. GetAppAvailabilityResultFromResponse(response, app_id);
  507. base::EraseIf(pending_app_availability_requests_,
  508. [&app_id, result](const auto& request_ptr) {
  509. if (request_ptr->app_id == app_id) {
  510. std::move(request_ptr->callback).Run(app_id, result);
  511. return true;
  512. }
  513. return false;
  514. });
  515. return;
  516. }
  517. if (pending_launch_session_request_ &&
  518. pending_launch_session_request_->request_id == request_id) {
  519. std::move(pending_launch_session_request_->callback)
  520. .Run(GetLaunchSessionResponse(response));
  521. pending_launch_session_request_.reset();
  522. return;
  523. }
  524. if (pending_stop_session_request_ &&
  525. pending_stop_session_request_->request_id == request_id) {
  526. std::move(pending_stop_session_request_->callback).Run(Result::kOk);
  527. pending_stop_session_request_.reset();
  528. return;
  529. }
  530. auto volume_it = pending_volume_requests_by_id_.find(request_id);
  531. if (volume_it != pending_volume_requests_by_id_.end()) {
  532. std::move(volume_it->second->callback).Run(Result::kOk);
  533. pending_volume_requests_by_id_.erase(volume_it);
  534. return;
  535. }
  536. }
  537. void CastMessageHandler::PendingRequests::AppAvailabilityTimedOut(
  538. int request_id) {
  539. DVLOG(1) << __func__ << ", request_id: " << request_id;
  540. auto it = std::find_if(pending_app_availability_requests_.begin(),
  541. pending_app_availability_requests_.end(),
  542. [&request_id](const auto& request) {
  543. return request->request_id == request_id;
  544. });
  545. CHECK(it != pending_app_availability_requests_.end());
  546. std::move((*it)->callback)
  547. .Run((*it)->app_id, GetAppAvailabilityResult::kUnknown);
  548. pending_app_availability_requests_.erase(it);
  549. }
  550. void CastMessageHandler::PendingRequests::LaunchSessionTimedOut(
  551. int request_id) {
  552. DVLOG(1) << __func__ << ", request_id: " << request_id;
  553. CHECK(pending_launch_session_request_);
  554. CHECK(pending_launch_session_request_->request_id == request_id);
  555. LaunchSessionResponse response;
  556. response.result = LaunchSessionResponse::kTimedOut;
  557. std::move(pending_launch_session_request_->callback).Run(std::move(response));
  558. pending_launch_session_request_.reset();
  559. }
  560. void CastMessageHandler::PendingRequests::StopSessionTimedOut(int request_id) {
  561. DVLOG(1) << __func__ << ", request_id: " << request_id;
  562. CHECK(pending_stop_session_request_);
  563. CHECK(pending_stop_session_request_->request_id == request_id);
  564. std::move(pending_stop_session_request_->callback).Run(Result::kFailed);
  565. pending_stop_session_request_.reset();
  566. }
  567. void CastMessageHandler::PendingRequests::SetVolumeTimedOut(int request_id) {
  568. DVLOG(1) << __func__ << ", request_id: " << request_id;
  569. auto it = pending_volume_requests_by_id_.find(request_id);
  570. DCHECK(it != pending_volume_requests_by_id_.end());
  571. std::move(it->second->callback).Run(Result::kFailed);
  572. pending_volume_requests_by_id_.erase(it);
  573. }
  574. } // namespace cast_channel