summaryrefslogtreecommitdiffstats
path: root/libraries/ganalytics/src/ganalytics_worker.cpp
blob: 435306a4274f66497ab148b5310cdbd27213c060 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#include "ganalytics.h"
#include "ganalytics_worker.h"
#include "sys.h"

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>

#include <QGuiApplication>
#include <QScreen>

const QLatin1String GAnalyticsWorker::dateTimeFormat("yyyy,MM,dd-hh:mm::ss:zzz");

GAnalyticsWorker::GAnalyticsWorker(GAnalytics *parent)
	: QObject(parent), q(parent), m_logLevel(GAnalytics::Error)
{
	m_appName = QCoreApplication::instance()->applicationName();
	m_appVersion = QCoreApplication::instance()->applicationVersion();
	m_request.setUrl(QUrl("https://www.google-analytics.com/collect"));
	m_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
	m_request.setHeader(QNetworkRequest::UserAgentHeader, getUserAgent());

	m_language = QLocale::system().name().toLower().replace("_", "-");
	m_screenResolution = getScreenResolution();

	m_timer.setInterval(m_timerInterval);
	connect(&m_timer, &QTimer::timeout, this, &GAnalyticsWorker::postMessage);
}

void GAnalyticsWorker::enable(bool state)
{
	// state change to the same is not valid.
	if(m_isEnabled == state)
	{
		return;
	}

	m_isEnabled = state;
	if(m_isEnabled)
	{
		// enable -> start doing things :)
		m_timer.start();
	}
	else
	{
		// disable -> stop the timer
		m_timer.stop();
	}
}

void GAnalyticsWorker::logMessage(GAnalytics::LogLevel level, const QString &message)
{
	if (m_logLevel > level)
	{
		return;
	}

	qDebug() << "[Analytics]" << message;
}

/**
 * Build the POST query. Adds all parameter to the query
 * which are used in every POST.
 * @param type      Type of POST message. The event which is to post.
 * @return query    Most used parameter in a query for a POST.
 */
QUrlQuery GAnalyticsWorker::buildStandardPostQuery(const QString &type)
{
	QUrlQuery query;
	query.addQueryItem("v", "1");
	query.addQueryItem("tid", m_trackingID);
	query.addQueryItem("cid", m_clientID);
	if (!m_userID.isEmpty())
	{
		query.addQueryItem("uid", m_userID);
	}
	query.addQueryItem("t", type);
	query.addQueryItem("ul", m_language);
	query.addQueryItem("vp", m_viewportSize);
	query.addQueryItem("sr", m_screenResolution);
	if(m_anonymizeIPs)
	{
		query.addQueryItem("aip", "1");
	}
	return query;
}

/**
 * Get primary screen resolution.
 * @return      A QString like "800x600".
 */
QString GAnalyticsWorker::getScreenResolution()
{
	QScreen *screen = QGuiApplication::primaryScreen();
	QSize size = screen->size();

	return QString("%1x%2").arg(size.width()).arg(size.height());
}

/**
 * Try to gain information about the system where this application
 * is running. It needs to get the name and version of the operating
 * system, the language and screen resolution.
 * All this information will be send in POST messages.
 * @return agent        A QString with all the information formatted for a POST message.
 */
QString GAnalyticsWorker::getUserAgent()
{
	QString system = Sys::getSystemInfo();

	return QString("%1/%2 (%3)").arg(m_appName).arg(m_appVersion).arg(system);
}

/**
 * The message queue contains a list of QueryBuffer object.
 * QueryBuffer holds a QUrlQuery object and a QDateTime object.
 * These both object are freed from the buffer object and
 * inserted as QString objects in a QList.
 * @return dataList     The list with concartinated queue data.
 */
QList<QString> GAnalyticsWorker::persistMessageQueue()
{
	QList<QString> dataList;
	foreach (QueryBuffer buffer, m_messageQueue)
	{
		dataList << buffer.postQuery.toString();
		dataList << buffer.time.toString(dateTimeFormat);
	}
	return dataList;
}

/**
 * Reads persistent messages from a file.
 * Gets all message data as a QList<QString>.
 * Two lines in the list build a QueryBuffer object.
 */
void GAnalyticsWorker::readMessagesFromFile(const QList<QString> &dataList)
{
	QListIterator<QString> iter(dataList);
	while (iter.hasNext())
	{
		QString queryString = iter.next();
		QString dateString = iter.next();
		QUrlQuery query;
		query.setQuery(queryString);
		QDateTime dateTime = QDateTime::fromString(dateString, dateTimeFormat);
		QueryBuffer buffer;
		buffer.postQuery = query;
		buffer.time = dateTime;
		m_messageQueue.enqueue(buffer);
	}
}

/**
 * Takes a QUrlQuery object and wrapp it together with
 * a QTime object into a QueryBuffer struct. These struct
 * will be stored in the message queue.
 */
void GAnalyticsWorker::enqueQueryWithCurrentTime(const QUrlQuery &query)
{
	QueryBuffer buffer;
	buffer.postQuery = query;
	buffer.time = QDateTime::currentDateTime();

	m_messageQueue.enqueue(buffer);
}

/**
 * This function is called by a timer interval.
 * The function tries to send a messages from the queue.
 * If message was successfully send then this function
 * will be called back to send next message.
 * If message queue contains more than one message then
 * the connection will kept open.
 * The message POST is asyncroniously when the server
 * answered a signal will be emitted.
 */
void GAnalyticsWorker::postMessage()
{
	if (m_messageQueue.isEmpty())
	{
		// queue empty -> try sending later
		m_timer.start();
		return;
	}
	else
	{
		// queue has messages -> stop timer and start sending
		m_timer.stop();
	}

	QString connection = "close";
	if (m_messageQueue.count() > 1)
	{
		connection = "keep-alive";
	}

	QueryBuffer buffer = m_messageQueue.head();
	QDateTime sendTime = QDateTime::currentDateTime();
	qint64 timeDiff = buffer.time.msecsTo(sendTime);

	if (timeDiff > fourHours)
	{
		// too old.
		m_messageQueue.dequeue();
		emit postMessage();
		return;
	}

	buffer.postQuery.addQueryItem("qt", QString::number(timeDiff));
	m_request.setRawHeader("Connection", connection.toUtf8());
	m_request.setHeader(QNetworkRequest::ContentLengthHeader, buffer.postQuery.toString().length());

	logMessage(GAnalytics::Debug, "Query string = " + buffer.postQuery.toString());

	// Create a new network access manager if we don't have one yet
	if (networkManager == NULL)
	{
		networkManager = new QNetworkAccessManager(this);
	}

	QNetworkReply *reply = networkManager->post(m_request, buffer.postQuery.query(QUrl::EncodeUnicode).toUtf8());
	connect(reply, SIGNAL(finished()), this, SLOT(postMessageFinished()));
}

/**
 * NetworkAccsessManager has finished to POST a message.
 * If POST message was successfully send then the message
 * query should be removed from queue.
 * SIGNAL "postMessage" will be emitted to send next message
 * if there is any.
 * If message couldn't be send then next try is when the
 * timer emits its signal.
 */
void GAnalyticsWorker::postMessageFinished()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

	int httpStausCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
	if (httpStausCode < 200 || httpStausCode > 299)
	{
		logMessage(GAnalytics::Error, QString("Error posting message: %s").arg(reply->errorString()));

		// An error ocurred. Try sending later.
		m_timer.start();
		return;
	}
	else
	{
		logMessage(GAnalytics::Debug, "Message sent");
	}

	m_messageQueue.dequeue();
	postMessage();
	reply->deleteLater();
}