Merge remote-tracking branch 'origin/5.3' into 5.4
[contrib/qtwebsockets.git] / src / imports / qmlwebsockets / qqmlwebsocket.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL21$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 **
26 ** In addition, as a special exception, Digia gives you certain additional
27 ** rights. These rights are described in the Digia Qt LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 **
30 ** $QT_END_LICENSE$
31 **
32 ****************************************************************************/
33
34 /*!
35     \qmltype WebSocket
36     \instantiates QQmlWebSocket
37
38     \inqmlmodule Qt.WebSockets
39     \ingroup websockets-qml
40     \brief QML interface to QWebSocket.
41
42     WebSockets is a web technology providing full-duplex communications channels over a
43     single TCP connection.
44     The WebSocket protocol was standardized by the IETF as
45     \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
46 */
47
48 /*!
49   \qmlproperty QUrl WebSocket::url
50   Server url to connect to. The url must have one of 2 schemes: \e ws:// or \e wss://.
51   When not supplied, then \e ws:// is used.
52   */
53
54 /*!
55   \qmlproperty Status WebSocket::status
56   Status of the WebSocket.
57
58   The status can have the following values:
59   \list
60   \li WebSockets.Connecting
61   \li WebSockets.Open
62   \li WebSockets.Closing
63   \li WebSockets.Closed
64   \li WebSockets.Error
65   \endlist
66   */
67
68 /*!
69   \qmlproperty QString WebSocket::errorString
70   Contains a description of the last error that occurred. When no error occurrred,
71   this string is empty.
72   */
73
74 /*!
75   \qmlproperty bool WebSocket::active
76   When set to true, a connection is made to the server with the given url.
77   When set to false, the connection is closed.
78   The default value is false.
79   */
80
81 /*!
82   \qmlsignal WebSocket::textMessageReceived(QString message)
83   This signal is emitted when a text message is received.
84   */
85
86 /*!
87   \qmlsignal WebSocket::statusChanged(Status status)
88   This signal is emitted when the status of the WebSocket changes.
89   the \l {WebSocket::status}{status} argument provides the current status.
90
91   \sa WebSocket::status
92   */
93
94 /*!
95   \qmlmethod void WebSocket::sendTextMessage(string message)
96   Sends \c message to the server.
97   */
98
99 #include "qqmlwebsocket.h"
100 #include <QtWebSockets/QWebSocket>
101
102 QT_BEGIN_NAMESPACE
103
104 QQmlWebSocket::QQmlWebSocket(QObject *parent) :
105     QObject(parent),
106     m_webSocket(),
107     m_status(Closed),
108     m_url(),
109     m_isActive(false),
110     m_componentCompleted(true),
111     m_errorString()
112 {
113 }
114
115 QQmlWebSocket::QQmlWebSocket(QWebSocket *socket, QObject *parent) :
116     QObject(parent),
117     m_status(Closed),
118     m_url(socket->requestUrl()),
119     m_isActive(true),
120     m_componentCompleted(true),
121     m_errorString(socket->errorString())
122 {
123     setSocket(socket);
124     onStateChanged(socket->state());
125 }
126
127 QQmlWebSocket::~QQmlWebSocket()
128 {
129 }
130
131 qint64 QQmlWebSocket::sendTextMessage(const QString &message)
132 {
133     if (m_status != Open) {
134         setErrorString(tr("Messages can only be sent when the socket is open."));
135         setStatus(Error);
136         return 0;
137     }
138     return m_webSocket->sendTextMessage(message);
139 }
140
141 QUrl QQmlWebSocket::url() const
142 {
143     return m_url;
144 }
145
146 void QQmlWebSocket::setUrl(const QUrl &url)
147 {
148     if (m_url == url) {
149         return;
150     }
151     if (m_webSocket && (m_status == Open)) {
152         m_webSocket->close();
153     }
154     m_url = url;
155     Q_EMIT urlChanged();
156     if (m_webSocket) {
157         m_webSocket->open(m_url);
158     }
159 }
160
161 QQmlWebSocket::Status QQmlWebSocket::status() const
162 {
163     return m_status;
164 }
165
166 QString QQmlWebSocket::errorString() const
167 {
168     return m_errorString;
169 }
170
171 void QQmlWebSocket::classBegin()
172 {
173     m_componentCompleted = false;
174     m_errorString = tr("QQmlWebSocket is not ready.");
175     m_status = Closed;
176 }
177
178 void QQmlWebSocket::componentComplete()
179 {
180     setSocket(new QWebSocket);
181
182     m_componentCompleted = true;
183
184     open();
185 }
186
187 void QQmlWebSocket::setSocket(QWebSocket *socket)
188 {
189     m_webSocket.reset(socket);
190     if (m_webSocket) {
191         // explicit ownership via QScopedPointer
192         m_webSocket->setParent(Q_NULLPTR);
193         connect(m_webSocket.data(), &QWebSocket::textMessageReceived,
194                 this, &QQmlWebSocket::textMessageReceived);
195         typedef void (QWebSocket::* ErrorSignal)(QAbstractSocket::SocketError);
196         connect(m_webSocket.data(), static_cast<ErrorSignal>(&QWebSocket::error),
197                 this, &QQmlWebSocket::onError);
198         connect(m_webSocket.data(), &QWebSocket::stateChanged,
199                 this, &QQmlWebSocket::onStateChanged);
200     }
201 }
202
203 void QQmlWebSocket::onError(QAbstractSocket::SocketError error)
204 {
205     Q_UNUSED(error)
206     setErrorString(m_webSocket->errorString());
207     setStatus(Error);
208 }
209
210 void QQmlWebSocket::onStateChanged(QAbstractSocket::SocketState state)
211 {
212     switch (state)
213     {
214         case QAbstractSocket::ConnectingState:
215         case QAbstractSocket::BoundState:
216         case QAbstractSocket::HostLookupState:
217         {
218             setStatus(Connecting);
219             break;
220         }
221         case QAbstractSocket::UnconnectedState:
222         {
223             setStatus(Closed);
224             break;
225         }
226         case QAbstractSocket::ConnectedState:
227         {
228             setStatus(Open);
229             break;
230         }
231         case QAbstractSocket::ClosingState:
232         {
233             setStatus(Closing);
234             break;
235         }
236         default:
237         {
238             setStatus(Connecting);
239             break;
240         }
241     }
242 }
243
244 void QQmlWebSocket::setStatus(QQmlWebSocket::Status status)
245 {
246     if (m_status == status) {
247         return;
248     }
249     m_status = status;
250     if (status != Error) {
251         setErrorString();
252     }
253     Q_EMIT statusChanged(m_status);
254 }
255
256 void QQmlWebSocket::setActive(bool active)
257 {
258     if (m_isActive == active) {
259         return;
260     }
261     m_isActive = active;
262     Q_EMIT activeChanged(m_isActive);
263     if (!m_componentCompleted) {
264         return;
265     }
266     if (m_isActive) {
267         open();
268     } else {
269         close();
270     }
271 }
272
273 bool QQmlWebSocket::isActive() const
274 {
275     return m_isActive;
276 }
277
278 void QQmlWebSocket::open()
279 {
280     if (m_componentCompleted && m_isActive && m_url.isValid() && Q_LIKELY(m_webSocket)) {
281         m_webSocket->open(m_url);
282     }
283 }
284
285 void QQmlWebSocket::close()
286 {
287     if (m_componentCompleted && Q_LIKELY(m_webSocket)) {
288         m_webSocket->close();
289     }
290 }
291
292 void QQmlWebSocket::setErrorString(QString errorString)
293 {
294     if (m_errorString == errorString) {
295         return;
296     }
297     m_errorString = errorString;
298     Q_EMIT errorStringChanged(m_errorString);
299 }
300
301 QT_END_NAMESPACE