copresence_manager_impl.cc revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
1// Copyright 2014 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
5#include "components/copresence/copresence_manager_impl.h"
6
7#include "base/bind.h"
8#include "components/copresence/public/copresence_delegate.h"
9#include "components/copresence/public/whispernet_client.h"
10#include "components/copresence/rpc/rpc_handler.h"
11
12namespace copresence {
13
14PendingRequest::PendingRequest(const copresence::ReportRequest& report,
15                               const std::string app_id,
16                               const StatusCallback& callback)
17    : report(report), app_id(app_id), callback(callback) {
18}
19
20PendingRequest::~PendingRequest() {
21}
22
23// Public methods
24
25CopresenceManagerImpl::~CopresenceManagerImpl() {}
26
27// Returns false if any operations were malformed.
28void CopresenceManagerImpl::ExecuteReportRequest(
29    ReportRequest request,
30    const std::string& app_id,
31    const StatusCallback& callback) {
32  // Don't take on any more requests. We can't execute them since init failed.
33  if (init_failed_) {
34    callback.Run(FAIL);
35    return;
36  }
37
38  DCHECK(rpc_handler_.get());
39  if (pending_init_operations_) {
40    pending_requests_queue_.push_back(
41        PendingRequest(request, app_id, callback));
42  } else {
43    rpc_handler_->SendReportRequest(
44        make_scoped_ptr(new copresence::ReportRequest(request)),
45        app_id,
46        callback);
47  }
48}
49
50// Private methods
51
52CopresenceManagerImpl::CopresenceManagerImpl(CopresenceDelegate* delegate)
53    : init_failed_(false),
54      pending_init_operations_(0),
55      delegate_(delegate) {
56  DCHECK(delegate);
57}
58
59void CopresenceManagerImpl::CompleteInitialization() {
60  if (pending_init_operations_)
61    return;
62
63  DCHECK(rpc_handler_.get());
64  if (!init_failed_)
65    rpc_handler_->ConnectToWhispernet();
66
67  for (std::vector<PendingRequest>::iterator request =
68           pending_requests_queue_.begin();
69       request != pending_requests_queue_.end();
70       ++request) {
71    if (init_failed_) {
72      request->callback.Run(FAIL);
73    } else {
74      rpc_handler_->SendReportRequest(
75          make_scoped_ptr(new copresence::ReportRequest(request->report)),
76          request->app_id,
77          request->callback);
78    }
79  }
80  pending_requests_queue_.clear();
81}
82
83void CopresenceManagerImpl::InitStepComplete(
84    const std::string& step, bool success) {
85  if (!success) {
86    LOG(ERROR) << step << " failed!";
87    init_failed_ = true;
88  }
89
90  DVLOG(3) << "Init step: " << step << " complete.";
91  pending_init_operations_--;
92  CompleteInitialization();
93}
94
95}  // namespace copresence
96