]> git.sur5r.net Git - minitube/blob - src/http/src/throttledhttp.cpp
1438a3a738ac708f00e11f4b7f22716911f9f69f
[minitube] / src / http / src / throttledhttp.cpp
1 #include "throttledhttp.h"
2
3 namespace {
4
5 QElapsedTimer initElapsedTimer() {
6     QElapsedTimer timer;
7     timer.start();
8     return timer;
9 }
10 }
11
12 ThrottledHttp::ThrottledHttp(Http &http) : http(http), elapsedTimer(initElapsedTimer()) {}
13
14 QObject *ThrottledHttp::request(const HttpRequest &req) {
15     return new ThrottledHttpReply(http, req, milliseconds, elapsedTimer);
16 }
17
18 ThrottledHttpReply::ThrottledHttpReply(Http &http,
19                                        const HttpRequest &req,
20                                        int milliseconds,
21                                        QElapsedTimer &elapsedTimer)
22     : http(http), req(req), milliseconds(milliseconds), elapsedTimer(elapsedTimer), timer(0) {
23     checkElapsed();
24 }
25
26 void ThrottledHttpReply::checkElapsed() {
27     /*
28     static QMutex mutex;
29     QMutexLocker locker(&mutex);
30     */
31
32     const qint64 elapsedSinceLastRequest = elapsedTimer.elapsed();
33     if (elapsedSinceLastRequest < milliseconds) {
34         if (!timer) {
35             timer = new QTimer(this);
36             timer->setSingleShot(true);
37             timer->setTimerType(Qt::PreciseTimer);
38             connect(timer, SIGNAL(timeout()), SLOT(checkElapsed()));
39         }
40         qDebug() << "Throttling" << req.url
41                  << QString("%1ms").arg(milliseconds - elapsedSinceLastRequest);
42         timer->setInterval(milliseconds - elapsedSinceLastRequest);
43         timer->start();
44         return;
45     }
46     elapsedTimer.start();
47     doRequest();
48 }
49
50 void ThrottledHttpReply::doRequest() {
51     QObject *reply = http.request(req);
52     connect(reply, SIGNAL(data(QByteArray)), SIGNAL(data(QByteArray)));
53     connect(reply, SIGNAL(error(QString)), SIGNAL(error(QString)));
54     connect(reply, SIGNAL(finished(HttpReply)), SIGNAL(finished(HttpReply)));
55
56     // this will cause the deletion of this object once the request is finished
57     setParent(reply);
58 }