1/*
2 *  Copyright 2011 The WebRTC Project Authors. All rights reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/libjingle/xmpp/iqtask.h"
12
13#include "webrtc/libjingle/xmpp/constants.h"
14#include "webrtc/libjingle/xmpp/xmppclient.h"
15
16namespace buzz {
17
18static const int kDefaultIqTimeoutSecs = 15;
19
20IqTask::IqTask(XmppTaskParentInterface* parent,
21               const std::string& verb,
22               const buzz::Jid& to,
23               buzz::XmlElement* el)
24    : buzz::XmppTask(parent, buzz::XmppEngine::HL_SINGLE),
25      to_(to),
26      stanza_(MakeIq(verb, to_, task_id())) {
27  stanza_->AddElement(el);
28  set_timeout_seconds(kDefaultIqTimeoutSecs);
29}
30
31int IqTask::ProcessStart() {
32  buzz::XmppReturnStatus ret = SendStanza(stanza_.get());
33  // TODO: HandleError(NULL) if SendStanza fails?
34  return (ret == buzz::XMPP_RETURN_OK) ? STATE_RESPONSE : STATE_ERROR;
35}
36
37bool IqTask::HandleStanza(const buzz::XmlElement* stanza) {
38  if (!MatchResponseIq(stanza, to_, task_id()))
39    return false;
40
41  if (stanza->Attr(buzz::QN_TYPE) != buzz::STR_RESULT &&
42      stanza->Attr(buzz::QN_TYPE) != buzz::STR_ERROR) {
43    return false;
44  }
45
46  QueueStanza(stanza);
47  return true;
48}
49
50int IqTask::ProcessResponse() {
51  const buzz::XmlElement* stanza = NextStanza();
52  if (stanza == NULL)
53    return STATE_BLOCKED;
54
55  bool success = (stanza->Attr(buzz::QN_TYPE) == buzz::STR_RESULT);
56  if (success) {
57    HandleResult(stanza);
58  } else {
59    SignalError(this, stanza->FirstNamed(QN_ERROR));
60  }
61  return STATE_DONE;
62}
63
64int IqTask::OnTimeout() {
65  SignalError(this, NULL);
66  return XmppTask::OnTimeout();
67}
68
69}  // namespace buzz
70