1 // Copyright 2015 The Weave 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 #ifndef LIBWEAVE_SRC_NOTIFICATION_XMPP_IQ_STANZA_HANDLER_H_ 6 #define LIBWEAVE_SRC_NOTIFICATION_XMPP_IQ_STANZA_HANDLER_H_ 7 8 #include <map> 9 #include <memory> 10 #include <string> 11 12 #include <base/callback_forward.h> 13 #include <base/macros.h> 14 #include <base/memory/weak_ptr.h> 15 #include <base/time/time.h> 16 17 #include "src/notification/xmpp_stream_parser.h" 18 19 namespace weave { 20 21 class XmppChannelInterface; 22 23 namespace provider { 24 class TaskRunner; 25 } 26 27 class IqStanzaHandler { 28 public: 29 using ResponseCallback = base::Callback<void(std::unique_ptr<XmlNode>)>; 30 using TimeoutCallback = base::Closure; 31 32 IqStanzaHandler(XmppChannelInterface* xmpp_channel, 33 provider::TaskRunner* task_runner); 34 35 // Sends <iq> request to the server. 36 // |type| is the IQ stanza type, one of "get", "set", "query". 37 // |to| is the target of the message. If empty string, 'to' is omitted. 38 // |body| the XML snipped to include between <iq>...</iq> 39 // |response_callback| is called with result or error XML stanza received 40 // from the server in response to the request sent. 41 // |timeout_callback| is called when the response to the request hasn't been 42 // received within the time allotted. 43 void SendRequest(const std::string& type, 44 const std::string& from, 45 const std::string& to, 46 const std::string& body, 47 const ResponseCallback& response_callback, 48 const TimeoutCallback& timeout_callback); 49 50 // |timeout| is the custom time interval after which requests should be 51 // considered failed. 52 void SendRequestWithCustomTimeout(const std::string& type, 53 const std::string& from, 54 const std::string& to, 55 const std::string& body, 56 base::TimeDelta timeout, 57 const ResponseCallback& response_callback, 58 const TimeoutCallback& timeout_callback); 59 60 // Processes an <iq> stanza is received from the server. This will match the 61 // stanza's 'id' attribute with pending request ID and if found, will 62 // call the |response_callback|, or if the request is not found, an error 63 // stanza fill be sent back to the server. 64 // Returns false if some unexpected condition occurred and the stream should 65 // be restarted. 66 bool HandleIqStanza(std::unique_ptr<XmlNode> stanza); 67 68 private: 69 using RequestId = int; 70 void OnTimeOut(RequestId id, const TimeoutCallback& timeout_callback); 71 72 XmppChannelInterface* xmpp_channel_; 73 provider::TaskRunner* task_runner_{nullptr}; 74 std::map<RequestId, ResponseCallback> requests_; 75 RequestId last_request_id_{0}; 76 77 base::WeakPtrFactory<IqStanzaHandler> weak_ptr_factory_{this}; 78 DISALLOW_COPY_AND_ASSIGN(IqStanzaHandler); 79 }; 80 81 } // namespace weave 82 83 #endif // LIBWEAVE_SRC_NOTIFICATION_XMPP_IQ_STANZA_HANDLER_H_ 84