Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

[e8cdcd]: plugins / internetradio / icy_http_handler.cpp Maximize Restore History

Download this file

icy_http_handler.cpp    448 lines (377 with data), 16.9 kB

  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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/***************************************************************************
icy_http_handler.cpp
-------------------
begin : Sun Jan 22 2012
copyright : (C) 2012 by Martin Witte
email : emw-kradio@nocabal.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kio/global.h>
#include <klocale.h>
#include <kio/slaveconfig.h>
#include <QtCore/QTextCodec>
#include <math.h>
#include "icy_http_handler.h"
#include "errorlog_interfaces.h"
#include <internetradiostation.h>
// avoid ever-growing metadata buffers
#define METADATA_MAX_SIZE (1024 * 1024)
IcyHttpHandler::IcyHttpHandler()
: m_httpHeaderAnalyzed (false),
m_ICYMetaInt (0),
m_dataRest (0),
m_metaRest (0),
m_streamJob (NULL),
m_metaDataEncoding ("auto"),
m_metaDataEncodingCodec (NULL)
#ifdef DEBUG_DUMP_ICY_STREAMS
, m_debugFullStream (NULL)
, m_debugMetaStream (NULL)
, m_debugDataStream (NULL)
, m_debugDecodingLog(NULL)
, m_debugFullPos (0)
, m_debugDataPos (0)
, m_debugMetaPos (0)
#endif
{
}
IcyHttpHandler::~IcyHttpHandler()
{
stopStreamDownload();
}
void IcyHttpHandler::setupStreamJob(const KUrl &url, const QString &metaDataEncoding)
{
// stop old job if present
stopStreamDownload();
m_metaDataEncoding = metaDataEncoding;
m_metaDataEncodingCodec = QTextCodec::codecForName(m_metaDataEncoding.toLocal8Bit());
// start download job
m_streamUrl = url;
IErrorLogClient::staticLogDebug(i18n("Internet Radio Plugin (ICY http handler): opening stream %1", m_streamUrl.pathOrUrl()));
emit sigUrlChanged(m_streamUrl);
m_streamJob = KIO::get(m_streamUrl, KIO::NoReload, KIO::HideProgressInfo);
if (m_streamJob) {
m_streamJob->addMetaData("customHTTPHeader", "Icy-MetaData:1");
m_streamJob->addMetaData("accept", "*/*");
m_streamJob->addMetaData("Encodings", "*");
m_streamJob->addMetaData("Charsets", "*");
m_streamJob->addMetaData("Languages", "*");
m_streamJob->addMetaData("UserAgent", QString("KRadio Internet Radio Plugin, Version %1").arg(KRADIO_VERSION));
m_streamJob->addMetaData("PropagateHttpHeader", "true");
QObject::connect(m_streamJob, SIGNAL(data (KIO::Job *, const QByteArray &)), this, SLOT(slotStreamData(KIO::Job *, const QByteArray &)));
QObject::connect(m_streamJob, SIGNAL(result(KJob *)), this, SLOT(slotStreamDone(KJob *)));
} else {
IErrorLogClient::staticLogError(i18n("Internet Radio Plugin (ICY http handler): Failed to start stream download of %1: KIO::get returned NULL pointer", m_streamUrl.pathOrUrl()));
stopStreamDownload(false);
emit sigError(m_streamUrl);
}
}
void IcyHttpHandler::startStreamJob()
{
m_httpHeaderAnalyzed = false;
m_ICYMetaInt = 0;
m_dataRest = 0;
m_metaRest = 0;
// m_inputBuffer->resetBuffer();
m_streamJob->start();
emit sigStarted(m_streamUrl);
if (m_streamJob->error()) {
IErrorLogClient::staticLogError(i18n("Internet Radio Plugin (ICY http handler): Failed to start stream download of %1: %2", m_streamUrl.pathOrUrl(), m_streamJob->errorString()));
stopStreamDownload(false);
emit sigError(m_streamUrl);
}
}
void IcyHttpHandler::startStreamDownload(KUrl url, const QString &metaDataEncoding)
{
// just in case, stop current downloads
stopStreamDownload();
m_streamUrl = url;
setupStreamJob(m_streamUrl, metaDataEncoding);
startStreamJob();
#ifdef DEBUG_DUMP_ICY_STREAMS
m_debugFullStream = fopen("/tmp/kradio-debug-icy-full-stream", "w");
m_debugMetaStream = fopen("/tmp/kradio-debug-icy-meta-stream", "w");
m_debugDataStream = fopen("/tmp/kradio-debug-icy-data-stream", "w");
m_debugDecodingLog = fopen("/tmp/kradio-debug-icy-decoding-log", "w");
m_debugFullPos = 0;
m_debugDataPos = 0;
m_debugMetaPos = 0;
#endif
}
void IcyHttpHandler::stopStreamDownload(bool emitSigFinished)
{
if (m_streamJob) {
QObject::disconnect(m_streamJob, SIGNAL(data (KIO::Job *, const QByteArray &)), this, SLOT(slotStreamData(KIO::Job *, const QByteArray &)));
QObject::disconnect(m_streamJob, SIGNAL(result(KJob *)), this, SLOT(slotStreamDone(KJob *)));
m_streamJob->kill(); // stop and delete
m_streamJob = NULL;
if (emitSigFinished) {
emit sigFinished(m_streamUrl);
}
}
#ifdef DEBUG_DUMP_ICY_STREAMS
if (m_debugFullStream) fclose(m_debugFullStream); m_debugFullStream = NULL;
if (m_debugMetaStream) fclose(m_debugMetaStream); m_debugMetaStream = NULL;
if (m_debugDataStream) fclose(m_debugDataStream); m_debugDataStream = NULL;
if (m_debugDecodingLog) fclose(m_debugDecodingLog); m_debugDecodingLog = NULL;
#endif
}
QMap<QString, QString> IcyHttpHandler::splitExtractHttpHeaderKeys(QString httpHeader)
{
// urg... QHttpResponseHeader is deprecated and does not parse ICY headers correctly.
// let's do it ourselves
QStringList lines = httpHeader.split(QRegExp("\\r?\\n"));
// fix HTTP header line continuations
QStringList consolidatedLines;
foreach(QString line, lines) {
if (line.startsWith(" ")) {
consolidatedLines.last() += line;
} else {
consolidatedLines.append(line);
}
}
// extract keys form header lines
QMap<QString, QString> headerMap;
foreach(QString line, consolidatedLines) {
QRegExp colonRegExp("\\s*:\\s*");
int colonIdx = colonRegExp.indexIn(line);
if (colonRegExp.matchedLength() > 0 && colonIdx > 0 && colonIdx < line.length()) {
QString key = line.left(colonIdx);
QString val = line.mid (colonIdx + colonRegExp.matchedLength());
headerMap.insert(key, val);
}
}
return headerMap;
}
void IcyHttpHandler::analyzeHttpHeader(QString httpHeader, KIO::MetaData &metaData)
{
QMap<QString, QString> headerMap = splitExtractHttpHeaderKeys(httpHeader);
QString icyMetaIntKey = "icy-metaint";
QString contentTypeKey = "content-type";
foreach(QString key, headerMap.keys()) {
if (key.toLower() == icyMetaIntKey) {
m_ICYMetaInt = headerMap.value(key).toInt();
m_dataRest = m_ICYMetaInt;
IErrorLogClient::staticLogDebug(QString("Internet Radio Plugin (ICY http handler): found metaint: %1").arg(m_ICYMetaInt));
}
if (key.toLower() == contentTypeKey) {
emit sigContentType(headerMap.value(key));
}
}
foreach(QString key, headerMap.keys()) {
metaData.insert(key, headerMap.value(key));
}
}
// returns packet minus header
QByteArray IcyHttpHandler::analyzeICYHeader(QByteArray packet)
{
m_httpHeaderAnalyzed = true;
QString headerStr = packet;
int headerLen = headerStr.indexOf("\r\n\r\n");
QByteArray remainingData = packet.mid(headerLen + 4);
m_connectionMetaData.clear();
analyzeHttpHeader(headerStr.left(headerLen + 4), m_connectionMetaData);
emit sigConnectionEstablished(m_streamUrl, m_connectionMetaData);
return remainingData;
}
void IcyHttpHandler::analyzeHttpHeader(KIO::Job *job)
{
m_httpHeaderAnalyzed = true;
m_connectionMetaData = job->metaData();
foreach(QString k, m_connectionMetaData.keys()) {
QString v = m_connectionMetaData[k];
IErrorLogClient::staticLogDebug(QString("Internet Radio Plugin (ICY http handler): %1 = %2").arg(k).arg(v));
if (k == "HTTP-Headers") {
analyzeHttpHeader(v, m_connectionMetaData);
}
else if (k == "content-type") {
emit sigContentType(m_connectionMetaData[k]);
}
}
emit sigConnectionEstablished(m_streamUrl, m_connectionMetaData);
}
void IcyHttpHandler::handleStreamData(const QByteArray &data)
{
// logDebug(QString("stream data: %1 bytes").arg(data.size()));
#ifdef DEBUG_DUMP_ICY_STREAMS
fwrite(data.constData(), data.size(), 1, m_debugDataStream); fflush(m_debugDataStream);
fprintf(m_debugDecodingLog, " data received: size = %zi @ pos %zi\n", (size_t)data.size(), m_debugDataPos); fflush(m_debugDecodingLog);
m_debugDataPos += data.size();
#endif
emit sigStreamData(data);
}
void IcyHttpHandler::handleMetaData(const QByteArray &data, bool complete)
{
// avoid that the buffer grows too large in case the transmission is broken by whatever
if (m_metaData.size() + data.size() > METADATA_MAX_SIZE) {
m_metaData.clear();
}
m_metaData.append(QByteArray(data.data(), data.size()));
#ifdef DEBUG_DUMP_ICY_STREAMS
fwrite(data.constData(), data.size(), 1, m_debugMetaStream); fflush(m_debugMetaStream);
fprintf(m_debugDecodingLog, " meta data received: size = %zi @ pos %zi\n", (size_t)data.size(), m_debugMetaPos); fflush(m_debugDecodingLog);
m_debugMetaPos += data.size();
#endif
if (complete) {
if (m_metaData.size()) {
// truncate tailing zeros, seems that the codecs also translate zero chars
int zpos = m_metaData.indexOf('\000');
if (zpos >= 0) {
m_metaData = m_metaData.left(zpos);
}
QString tmpString;
if (m_metaDataEncoding == "auto" || !m_metaDataEncodingCodec) {
m_metaDataEncodingProber.feed(m_metaData);
// printf ("confidence = %f\n", prober.confidence());
if (m_metaDataEncodingProber.confidence() > 0.8) {
tmpString = QTextCodec::codecForName(m_metaDataEncodingProber.encoding())->toUnicode(m_metaData);
} else {
tmpString = QString::fromUtf8(m_metaData.data());
}
} else {
tmpString = m_metaDataEncodingCodec->toUnicode(m_metaData);
}
// enforce deep copy
QString metaString(tmpString.constData(), tmpString.size());
QString charcode = "";
for (int i = 0; i < metaString.length(); ++i) {
charcode += QString::number(metaString[i].toAscii(), 16) + " ";
}
IErrorLogClient::staticLogDebug(QString("Internet Radio Plugin (ICY http handler): meta: %1 (len %2), %3").arg(metaString).arg(metaString.length()).arg(charcode));
// parse meta data
QMap<QString, QString> metaData;
while (metaString.size()) {
int eqIdx = metaString.indexOf('=');
if (eqIdx < 0) {
break;
}
QString key = metaString.left(eqIdx).trimmed();
// IErrorLogClient::staticLogDebug(QString("Metadata Key: %1").arg(key));
metaString = metaString.mid(eqIdx + 1).trimmed();
bool useQuotes = metaString.startsWith("'");
metaString.remove(0,useQuotes);
int curIdx = 0;
QString escapeRegExp = "\\\\.|''";
QString termRegExp = useQuotes ? "'\\s*;" : ";";
QRegExp findRegExp("(" + escapeRegExp + "|" + termRegExp + ")");
// step by step replace escapes and generate variable value
QString value;
while (curIdx < metaString.size()) {
int findIdx = findRegExp.indexIn(metaString, curIdx);
int matchLen = findRegExp.matchedLength();
if (findIdx >= 0) {
QString tmp = metaString.mid(findIdx, matchLen);
if (QRegExp(escapeRegExp).exactMatch(tmp)) {
curIdx += matchLen;
} else {
value = metaString.left(findIdx);
metaString = metaString.mid(findIdx + matchLen).trimmed();
break;
}
} else {
value = metaString;
metaString = QString::null;
break;
}
}
metaData.insert(key, value);
#ifdef DEBUG
IErrorLogClient::staticLogDebug(QString("Internet Radio Plugin (ICY http handler): Metadata Key: %1 = %2").arg(key).arg(value));
#endif
}
emit sigMetaDataUpdate(metaData);
}
// free buffer for next meta data transmission
m_metaData.clear();
}
}
void IcyHttpHandler::slotStreamData(KIO::Job *job, QByteArray data)
{
if (m_streamJob == job) {
if (!m_httpHeaderAnalyzed) {
QRegExp ICYHeaderRegExp("^ICY\\s+\\d+\\s+\\w+[\r\n]");
if (QString(data).indexOf(ICYHeaderRegExp) == 0) {
data = analyzeICYHeader(data);
} else {
analyzeHttpHeader(job);
}
}
#ifdef DEBUG_DUMP_ICY_STREAMS
fwrite(data.constData(), data.size(), 1, m_debugFullStream); fflush(m_debugFullStream);
fprintf(m_debugDecodingLog, "full stream data received: size = %zi @ pos %zi\n", (size_t)data.size(), m_debugFullPos); fflush(m_debugDecodingLog);
m_debugFullPos += data.size();
#endif
// printf ("received packet: %i bytes\n", data.size());
while (data.size()) {
// is it stream data?
if (m_ICYMetaInt <= 0 || m_dataRest > 0) {
size_t chunk = m_ICYMetaInt > 0 ? qMin(m_dataRest, (size_t)data.size()) : data.size();
// printf (" stream chunk: %zi bytes\n", chunk);
handleStreamData(data.left(chunk));
data = data.mid(chunk);
m_dataRest -= chunk;
}
// or is it meta data
else {
if (m_metaRest <= 0) {
m_metaRest = data[0] * 16;
data = data.mid(1);
}
size_t chunk = qMin(m_metaRest, (size_t)data.size());
// printf (" meta chunk: %zi + 1 bytes\n", chunk);
QByteArray mdata(data.constData(), chunk);
m_metaRest -= chunk;
bool metaComplete = m_metaRest <= 0;
data = data.mid(chunk);
if (metaComplete) {
m_dataRest = m_ICYMetaInt;
}
handleMetaData(mdata, metaComplete);
}
}
}
}
void IcyHttpHandler::slotStreamContinue()
{
if (m_streamJob) {
m_streamJob->resume();
// printf ("stream CONTINUED\n");
}
}
void IcyHttpHandler::slotStreamPause()
{
if (m_streamJob) {
m_streamJob->suspend();
// printf ("stream PAUSED\n");
}
}
void IcyHttpHandler::slotStreamDone(KJob *job)
{
if (m_streamJob == job) {
bool local_err = false;
if (m_streamJob->error()) {
IErrorLogClient::staticLogError(i18n("Internet Radio Plugin (ICY http handler): Failed to load stream data for %1: %2", m_streamUrl.pathOrUrl(), m_streamJob->errorString()));
local_err = true;
}
KIO::MetaData md = m_streamJob->metaData();
if (md.contains("HTTP-Headers") && md.contains("responsecode")) {
int http_response_code = md["responsecode"].toInt();
if ((http_response_code < 200 || http_response_code >= 300) && http_response_code != 304) { // skip 304 NOT MODIFIED http response codes
IErrorLogClient::staticLogError(i18n("Internet Radio Plugin (ICY http handler): HTTP error %1 for stream %2", http_response_code, m_streamUrl.pathOrUrl()));
local_err = true;
}
}
stopStreamDownload(!local_err);
if (local_err) {
emit sigError(m_streamUrl);
}
}
job->deleteLater();
}