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