blob: 1fdd9173c43d0094ccc9c65cbb0ce3e547e5e037 [file] [log] [blame]
Alex Vakulenkoeedf3be2015-05-13 17:52:02 -07001// Copyright 2015 The Chromium OS 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 BUFFET_NOTIFICATION_XMPP_CHANNEL_H_
6#define BUFFET_NOTIFICATION_XMPP_CHANNEL_H_
7
8#include <memory>
9#include <string>
10#include <vector>
11
12#include <base/callback_forward.h>
13#include <base/macros.h>
14#include <base/memory/weak_ptr.h>
15#include <base/task_runner.h>
16#include <chromeos/backoff_entry.h>
17#include <chromeos/streams/stream.h>
18
19#include "buffet/notification/notification_channel.h"
20
21namespace buffet {
22
23class XmppChannel : public NotificationChannel {
24 public:
25 // |account| is the robot account for buffet and |access_token|
26 // it the OAuth token. Note that the OAuth token expires fairly frequently
27 // so you will need to reset the XmppClient every time this happens.
28 XmppChannel(const std::string& account,
29 const std::string& access_token,
30 const scoped_refptr<base::TaskRunner>& task_runner);
31 virtual ~XmppChannel() = default;
32
33 // Overrides from NotificationChannel.
34 std::string GetName() const override;
35 void AddChannelParameters(base::DictionaryValue* channel_json) override;
36 void Start(NotificationDelegate* delegate) override;
37 void Stop() override;
38
39 // Internal states for the XMPP stream.
40 enum class XmppState {
41 kNotStarted,
42 kStarted,
43 kAuthenticationStarted,
44 kAuthenticationFailed,
45 kStreamRestartedPostAuthentication,
46 kBindSent,
47 kSessionStarted,
48 kSubscribeStarted,
49 kSubscribed,
50 };
51
52 protected:
53 virtual void Connect(const std::string& host, uint16_t port,
54 const base::Closure& callback);
55
56 XmppState state_{XmppState::kNotStarted};
57
58 // The connection socket stream to the XMPP server.
59 chromeos::Stream* stream_{nullptr};
60
61 private:
62 void SendMessage(const std::string& message);
63 void WaitForMessage();
64
65 void OnConnected();
66 void OnMessageRead(size_t size);
67 void OnMessageSent();
68 void OnError(const chromeos::Error* error);
69
70 // Robot account name for the device.
71 std::string account_;
72
73 // OAuth access token for the account. Expires fairly frequently.
74 std::string access_token_;
75
76 chromeos::StreamPtr raw_socket_;
77
78 // Read buffer for incoming message packets.
79 std::vector<char> read_socket_data_;
80 // Write buffer for outgoing message packets.
81 std::string write_socket_data_;
82
83 chromeos::BackoffEntry backoff_entry_;
84 NotificationDelegate* delegate_{nullptr};
85 scoped_refptr<base::TaskRunner> task_runner_;
86
87 base::WeakPtrFactory<XmppChannel> weak_ptr_factory_{this};
88 DISALLOW_COPY_AND_ASSIGN(XmppChannel);
89};
90
91} // namespace buffet
92
93#endif // BUFFET_NOTIFICATION_XMPP_CHANNEL_H_
94