2 #include <QCoreApplication>
8 #include <QNetworkCookie>
9 #include <QAuthenticator>
10 #include <QTextStream>
11 #include <QNetworkProxy>
12 #include <QMutexLocker>
26 #include "mythversion.h"
34 #define LOC QString("DownloadManager: ")
49 qRegisterMetaType<QNetworkReply::NetworkError>(
"QNetworkReply::NetworkError");
61 QMutexLocker lock(&
m_lock);
67 QMutexLocker lock(&
m_lock);
91 const QHash<QByteArray, QByteArray> *
m_headers {
nullptr};
93 QNetworkReply::NetworkError
m_errorCode {QNetworkReply::NoError};
159 while (!tmpDLM->getQueueThread())
162 tmpDLM->moveToThread(tmpDLM->getQueueThread());
163 tmpDLM->setRunThread();
165 while (!tmpDLM->isRunning())
195 bool downloading =
false;
196 bool itemsInQueue =
false;
197 bool itemsInCancellationQueue =
false;
198 bool waitAnyway =
false;
205 m_manager =
new QNetworkAccessManager(
this);
209 QCoreApplication::applicationName() +
"-" +
219 m_manager->cookieJar()->setParent(
nullptr);
221 QObject::connect(
m_manager, &QNetworkAccessManager::finished,
229 LOG(VB_GENERAL, LOG_DEBUG,
"Updating DLManager's Cookie Jar");
239 if (itemsInCancellationQueue)
244 QCoreApplication::processEvents();
250 if (!itemsInQueue || waitAnyway)
257 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"waiting 200ms"));
262 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"waiting for more items to download"));
294 if (dlInfo->
m_url.startsWith(
"myth://"))
322 const QString &
dest, QByteArray *data,
329 dlInfo->m_request = req;
330 dlInfo->m_outFile =
dest;
331 dlInfo->m_data = data;
332 dlInfo->m_caller = caller;
333 dlInfo->m_requestType = reqType;
334 dlInfo->m_reload = reload;
354 const QString &
dest, QByteArray *data,
358 const QHash<QByteArray, QByteArray> *
headers,
364 dlInfo->m_request = req;
365 dlInfo->m_outFile =
dest;
366 dlInfo->m_data = data;
367 dlInfo->m_requestType = reqType;
368 dlInfo->m_reload = reload;
369 dlInfo->m_syncMode =
true;
370 dlInfo->m_authCallback = authCallbackFn;
371 dlInfo->m_authArg = authArg;
373 dlInfo->m_finalUrl = finalUrl;
383 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"preCache('%1')").arg(url));
384 queueItem(url,
nullptr, QString(),
nullptr,
nullptr);
398 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"queueDownload('%1', '%2', %3)")
399 .arg(url,
dest, QString::number((
long long)caller)));
413 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"queueDownload('%1', '%2', %3)")
414 .arg(req->url().toString()).arg((
long long)data)
415 .arg((
long long)caller));
417 queueItem(req->url().toString(), req, QString(), data, caller,
419 (QNetworkRequest::AlwaysNetwork == req->attribute(
420 QNetworkRequest::CacheLoadControlAttribute,
421 QNetworkRequest::PreferNetwork).toInt()));
443 const bool reload, QString *finalUrl)
447 nullptr,
nullptr,
nullptr, &redirected))
449 if (!redirected.isEmpty() && finalUrl !=
nullptr)
450 *finalUrl = redirected;
464 QNetworkReply *reply =
nullptr;
467 dlInfo->m_reload = reload;
468 dlInfo->m_syncMode =
true;
469 dlInfo->m_processReply =
false;
475 reply = dlInfo->m_reply;
477 dlInfo->m_reply =
nullptr;
497 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"download('%1', '%2')")
498 .arg(req->url().toString()).arg((
long long)data));
499 return processItem(req->url().toString(), req, QString(), data,
501 (QNetworkRequest::AlwaysNetwork == req->attribute(
502 QNetworkRequest::CacheLoadControlAttribute,
503 QNetworkRequest::PreferNetwork).toInt()));
516 const bool reload,
AuthCallback authCallbackFn,
void *authArg,
517 const QHash<QByteArray, QByteArray> *
headers)
533 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"queuePost('%1', '%2')")
534 .arg(url).arg((
long long)data));
538 LOG(VB_GENERAL, LOG_ERR,
LOC +
"queuePost(), data is NULL!");
554 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"queuePost('%1', '%2')")
555 .arg(req->url().toString()).arg((
long long)data));
559 LOG(VB_GENERAL, LOG_ERR,
LOC +
"queuePost(), data is NULL!");
563 queueItem(req->url().toString(), req, QString(), data, caller,
565 (QNetworkRequest::AlwaysNetwork == req->attribute(
566 QNetworkRequest::CacheLoadControlAttribute,
567 QNetworkRequest::PreferNetwork).toInt()));
578 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"post('%1', '%2')")
579 .arg(url).arg((
long long)data));
583 LOG(VB_GENERAL, LOG_ERR,
LOC +
"post(), data is NULL!");
597 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"post('%1', '%2')")
598 .arg(req->url().toString()).arg((
long long)data));
602 LOG(VB_GENERAL, LOG_ERR,
LOC +
"post(), data is NULL!");
606 return processItem(req->url().toString(), req, QString(), data,
608 (QNetworkRequest::AlwaysNetwork == req->attribute(
609 QNetworkRequest::CacheLoadControlAttribute,
610 QNetworkRequest::PreferNetwork).toInt()));
624 const QHash<QByteArray, QByteArray> *
headers)
626 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"postAuth('%1', '%2')")
627 .arg(url).arg((
long long)data));
631 LOG(VB_GENERAL, LOG_ERR,
LOC +
"postAuth(), data is NULL!");
656 static const QString kDateFormat =
"ddd, dd MMM yyyy hh:mm:ss 'GMT'";
657 QUrl qurl(dlInfo->
m_url);
658 QNetworkRequest request;
668 request.setUrl(qurl);
673 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
674 QNetworkRequest::AlwaysNetwork);
685 while (!(redirectLoc =
getHeader(qurl,
"Location")).isNull())
689 LOG(VB_GENERAL, LOG_WARNING, QString(
"Cache Redirection limit "
691 .arg(qurl.toString()));
694 qurl.setUrl(redirectLoc);
698 LOG(VB_NETWORK, LOG_DEBUG, QString(
"Checking cache for %1")
699 .arg(qurl.toString()));
702 QNetworkCacheMetaData urlData =
m_manager->cache()->metaData(qurl);
704 if ((urlData.isValid()) &&
705 ((!urlData.expirationDate().isValid()) ||
706 (urlData.expirationDate().toUTC().secsTo(now) < 10)))
708 QString dateString =
getHeader(urlData,
"Date");
710 if (!dateString.isNull())
714 loadDate.setTimeSpec(Qt::UTC);
715 if (loadDate.secsTo(now) <= 720)
718 LOG(VB_NETWORK, LOG_DEBUG, QString(
"Preferring cache for %1")
719 .arg(qurl.toString()));
726 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
727 QNetworkRequest::PreferCache);
729 if (!request.hasRawHeader(
"User-Agent"))
731 request.setRawHeader(
"User-Agent",
732 QByteArray(
"MythTV v") + MYTH_BINARY_VERSION +
733 " MythDownloadManager");
738 QHash<QByteArray, QByteArray>::const_iterator it =
740 for ( ; it != dlInfo->
m_headers->constEnd(); ++it )
742 if (!it.key().isEmpty() && !it.value().isEmpty())
744 request.setRawHeader(it.key(), it.value());
767 connect(
m_manager, &QNetworkAccessManager::authenticationRequired,
771 connect(dlInfo->
m_reply, &QNetworkReply::errorOccurred,
773 connect(dlInfo->
m_reply, &QNetworkReply::downloadProgress,
782 QAuthenticator *authenticator)
794 LOG(VB_FILE, LOG_DEBUG,
"Calling auth callback");
816 if (dlInfo->
m_url.startsWith(
"http://[fe80::",Qt::CaseInsensitive))
817 return downloadNowLinkLocal(dlInfo, deleteInfo);
829 while ((!dlInfo->
IsDone()) &&
831 (((!dlInfo->
m_url.startsWith(
"myth://")) &&
833 ((dlInfo->
m_url.startsWith(
"myth://")) &&
842 bool done = dlInfo->
IsDone();
844 done && (dlInfo->
m_errorCode == QNetworkReply::NoError);
853 LOG(VB_FILE, LOG_DEBUG,
854 LOC + QString(
"Aborting download - lack of data transfer"));
889 bool MythDownloadManager::downloadNowLinkLocal(
MythDownloadInfo *dlInfo,
bool deleteInfo)
896 LOG(VB_GENERAL, LOG_ERR,
LOC + QString(
"No data buffer provided for %1").arg(dlInfo->
m_url));
903 LOG(VB_GENERAL, LOG_ERR,
LOC + QString(
"Unsupported authentication for %1").arg(dlInfo->
m_url));
909 LOG(VB_GENERAL, LOG_ERR,
LOC + QString(
"Unsupported File output %1 for %2")
918 LOG(VB_GENERAL, LOG_ERR,
LOC + QString(
"Unsupported link-local operation %1")
919 .arg(dlInfo->
m_url));
923 QUrl url(dlInfo->
m_url);
924 QString host(url.host());
925 int port(url.port(80));
939 QByteArray* buffer = dlInfo->
m_data;
940 QHash<QByteArray, QByteArray>
headers;
943 if (!
headers.contains(
"User-Agent"))
944 headers.insert(
"User-Agent", QByteArray(
"MythDownloadManager v") +
945 MYTH_BINARY_VERSION);
946 headers.insert(
"Connection",
"close");
947 headers.insert(
"Accept-Encoding",
"identity");
948 if (!buffer->isEmpty())
949 headers.insert(
"Content-Length", QString::number(buffer->size()).toUtf8());
950 headers.insert(
"Host", (url.host() +
":" + QString::number(port)).toUtf8());
952 QByteArray requestMessage;
953 QString path (url.path());
954 requestMessage.append(
"POST ");
955 requestMessage.append(path.toLatin1());
956 requestMessage.append(
" HTTP/1.1\r\n");
957 QHashIterator<QByteArray, QByteArray> it(
headers);
961 requestMessage.append(it.key());
962 requestMessage.append(
": ");
963 requestMessage.append(it.value());
964 requestMessage.append(
"\r\n");
966 requestMessage.append(
"\r\n");
967 if (!buffer->isEmpty())
968 requestMessage.append(*buffer);
971 socket.connectToHost(host,
static_cast<uint16_t>(port));
973 if (!socket.waitForConnected(5000))
976 ok = socket.write(requestMessage) > 0;
979 ok = socket.waitForDisconnected(5000);
982 *buffer = socket.readAll();
984 QByteArray delim(
"\r\n\r\n");
985 int delimLoc = buffer->indexOf(delim);
987 *buffer = buffer->right(buffer->size() - delimLoc - 4);
1004 LOG(VB_GENERAL, LOG_ERR,
LOC + QString(
"Link Local request failed: %1").arg(url.toString()));
1025 for (
const auto& url : std::as_const(urls))
1028 while (lit.hasNext())
1032 if (dlInfo->
m_url == url)
1055 if (QThread::currentThread() == this->thread())
1078 while (lit.hasNext())
1086 LOG(VB_FILE, LOG_DEBUG,
1087 LOC + QString(
"Aborting download - user request"));
1096 dlInfo->
m_errorCode = QNetworkReply::OperationCanceledError;
1118 dlInfo->
m_data =
nullptr;
1122 QMap <QString, MythDownloadInfo*>::iterator mit =
m_downloadInfos.begin();
1130 dlInfo->
m_data =
nullptr;
1140 auto *reply = qobject_cast<QNetworkReply *>(sender());
1141 if (reply ==
nullptr)
1144 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"downloadError %1 ")
1145 .arg(errorCode) + reply->errorString() );
1150 reply->deleteLater();
1168 const QUrl& oldRedirectUrl)
1170 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"redirectUrl()"));
1173 if(!possibleRedirectUrl.isEmpty() && possibleRedirectUrl != oldRedirectUrl)
1184 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"downloadFinished(%1)")
1185 .arg((
long long)reply));
1190 reply->deleteLater();
1196 if (!dlInfo || !dlInfo->
m_reply)
1210 int statusCode = -1;
1211 static const QString kDateFormat =
"ddd, dd MMM yyyy hh:mm:ss 'GMT'";
1212 QNetworkReply *reply = dlInfo->
m_reply;
1216 QUrl possibleRedirectUrl =
1217 reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
1219 if (!possibleRedirectUrl.isEmpty() &&
1220 possibleRedirectUrl.isValid() &&
1221 possibleRedirectUrl.isRelative())
1222 possibleRedirectUrl = reply->url().resolved(possibleRedirectUrl);
1224 if (!possibleRedirectUrl.isEmpty() && dlInfo->
m_finalUrl !=
nullptr)
1225 *dlInfo->
m_finalUrl = QString(possibleRedirectUrl.toString());
1231 reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
1232 if (status.isValid())
1233 statusCode = status.toInt();
1238 (statusCode == 301 || statusCode == 302 ||
1239 statusCode == 303)))
1241 LOG(VB_FILE, LOG_DEBUG,
LOC +
1242 QString(
"downloadFinished(%1): Redirect: %2 -> %3")
1243 .arg(QString::number((
long long)dlInfo),
1244 reply->url().toString(),
1245 dlInfo->m_redirectedTo.toString()));
1248 dlInfo->m_data->clear();
1250 dlInfo->m_bytesReceived = 0;
1251 dlInfo->m_bytesTotal = 0;
1253 QNetworkRequest request(dlInfo->m_redirectedTo);
1255 if (dlInfo->m_reload)
1257 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
1258 QNetworkRequest::AlwaysNetwork);
1260 else if (dlInfo->m_preferCache)
1262 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
1263 QNetworkRequest::PreferCache);
1266 request.setRawHeader(
"User-Agent",
1267 "MythDownloadManager v" +
1268 QByteArray(MYTH_BINARY_VERSION));
1270 switch (dlInfo->m_requestType)
1273 dlInfo->m_reply =
m_manager->head(request);
1277 dlInfo->m_reply =
m_manager->get(request);
1283 connect(dlInfo->m_reply, &QNetworkReply::errorOccurred,
1285 connect(dlInfo->m_reply, &QNetworkReply::downloadProgress,
1289 reply->deleteLater();
1293 LOG(VB_FILE, LOG_DEBUG, QString(
"downloadFinished(%1): COMPLETE: %2")
1294 .arg((
long long)dlInfo).arg(dlInfo->m_url));
1298 QUrl fileUrl = dlInfo->m_url;
1299 QString redirectLoc;
1301 while (!(redirectLoc =
getHeader(fileUrl,
"Location")).isNull())
1305 LOG(VB_GENERAL, LOG_WARNING, QString(
"Cache Redirection limit "
1307 .arg(fileUrl.toString()));
1310 fileUrl.setUrl(redirectLoc);
1315 QNetworkCacheMetaData urlData =
m_manager->cache()->metaData(fileUrl);
1317 if (
getHeader(urlData,
"Date").isNull())
1319 QNetworkCacheMetaData::RawHeaderList
headers = urlData.rawHeaders();
1320 QNetworkCacheMetaData::RawHeader newheader;
1322 newheader = QNetworkCacheMetaData::RawHeader(
"Date",
1323 now.toString(kDateFormat).toLatin1());
1325 urlData.setRawHeaders(
headers);
1327 m_manager->cache()->updateMetaData(urlData);
1332 dlInfo->m_redirectedTo.clear();
1338 if (reply && dlInfo->m_processReply)
1340 bool append = (!dlInfo->m_syncMode && dlInfo->m_caller);
1341 QByteArray data = reply->readAll();
1342 dataSize = data.size();
1345 dlInfo->m_bytesReceived += dataSize;
1347 dlInfo->m_bytesReceived = dataSize;
1349 dlInfo->m_bytesTotal = dlInfo->m_bytesReceived;
1354 dlInfo->m_data->append(data);
1356 *dlInfo->m_data = data;
1358 else if (!dlInfo->m_outFile.isEmpty())
1360 saveFile(dlInfo->m_outFile, data, append);
1367 (*dlInfo->m_data) = dlInfo->m_privData;
1369 else if (!dlInfo->m_outFile.isEmpty())
1371 saveFile(dlInfo->m_outFile, dlInfo->m_privData);
1373 dlInfo->m_bytesReceived += dataSize;
1374 dlInfo->m_bytesTotal = dlInfo->m_bytesReceived;
1382 LOG(VB_GENERAL, LOG_ERR,
LOC +
1383 QString(
"ERROR download finished but failed to remove url: %1")
1384 .arg(dlInfo->m_url));
1391 dlInfo->SetDone(
true);
1393 if (!dlInfo->m_syncMode)
1395 if (dlInfo->m_caller)
1397 LOG(VB_FILE, LOG_DEBUG, QString(
"downloadFinished(%1): "
1398 "COMPLETE: %2, sending event to caller")
1399 .arg((
long long)dlInfo).arg(dlInfo->m_url));
1402 args << dlInfo->m_url;
1403 args << dlInfo->m_outFile;
1404 args << QString::number(dlInfo->m_bytesTotal);
1406 args << (reply ? reply->errorString() : QString());
1407 args << QString::number((
int)(reply ? reply->error() :
1408 dlInfo->m_errorCode));
1410 QCoreApplication::postEvent(dlInfo->m_caller,
1429 auto *reply = qobject_cast<QNetworkReply *>(sender());
1430 if (reply ==
nullptr)
1433 LOG(VB_FILE, LOG_DEBUG,
LOC +
1434 QString(
"downloadProgress(%1, %2) (for reply %3)")
1435 .arg(bytesReceived).arg(bytesTotal).arg((
long long)reply));
1448 LOG(VB_FILE, LOG_DEBUG,
LOC +
1449 QString(
"downloadProgress: %1 to %2 is at %3 of %4 bytes downloaded")
1451 .arg(bytesReceived).arg(bytesTotal));
1455 LOG(VB_FILE, LOG_DEBUG, QString(
"downloadProgress(%1): "
1456 "sending event to caller")
1457 .arg(reply->url().toString()));
1460 QByteArray data = reply->readAll();
1465 dlInfo->
m_data->append(data);
1473 args << QString::number(bytesReceived);
1474 args << QString::number(bytesTotal);
1476 QCoreApplication::postEvent(dlInfo->
m_caller,
1489 const QByteArray &data,
1492 if (outFile.isEmpty() || data.isEmpty())
1495 QFile
file(outFile);
1496 QFileInfo fileInfo(outFile);
1497 QDir qdir(fileInfo.absolutePath());
1499 if (!qdir.exists() && !qdir.mkpath(fileInfo.absolutePath()))
1501 LOG(VB_GENERAL, LOG_ERR, QString(
"Failed to create: '%1'")
1502 .arg(fileInfo.absolutePath()));
1506 QIODevice::OpenMode mode = QIODevice::Unbuffered|QIODevice::WriteOnly;
1508 mode |= QIODevice::Append;
1510 if (!
file.open(mode))
1512 LOG(VB_GENERAL, LOG_ERR, QString(
"Failed to open: '%1'") .arg(outFile));
1517 size_t remaining = data.size();
1518 uint failure_cnt = 0;
1519 while ((remaining > 0) && (failure_cnt < 5))
1521 ssize_t written =
file.write(data.data() + offset, remaining);
1531 remaining -= written;
1534 return remaining <= 0;
1548 static const QString kDateFormat =
"ddd, dd MMM yyyy hh:mm:ss 'GMT'";
1549 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"GetLastModified('%1')").arg(url));
1554 QUrl cacheUrl = QUrl(url);
1557 QString redirectLoc;
1559 while (!(redirectLoc =
getHeader(cacheUrl,
"Location")).isNull())
1563 LOG(VB_GENERAL, LOG_WARNING, QString(
"Cache Redirection limit "
1565 .arg(cacheUrl.toString()));
1568 cacheUrl.setUrl(redirectLoc);
1573 QNetworkCacheMetaData urlData =
m_manager->cache()->metaData(cacheUrl);
1576 if (urlData.isValid() &&
1577 ((!urlData.expirationDate().isValid()) ||
1578 (urlData.expirationDate().secsTo(now) < 0)))
1580 if (urlData.lastModified().toUTC().secsTo(now) <= 3600)
1582 result = urlData.lastModified().toUTC();
1586 QString date =
getHeader(urlData,
"Date");
1589 QDateTime loadDate =
1591 loadDate.setTimeSpec(Qt::UTC);
1592 if (loadDate.secsTo(now) <= 1200)
1594 result = urlData.lastModified().toUTC();
1600 if (!result.isValid())
1603 dlInfo->
m_url = url;
1614 QNetworkRequest::LastModifiedHeader);
1615 if (lastMod.isValid())
1616 result = lastMod.toDateTime().toUTC();
1625 LOG(VB_FILE, LOG_DEBUG,
LOC + QString(
"GetLastModified('%1'): Result %2")
1626 .arg(url, result.toString()));
1654 auto *jar = qobject_cast<MythCookieJar *>(
m_manager->cookieJar());
1676 auto *inJar = qobject_cast<MythCookieJar *>(
m_manager->cookieJar());
1677 if (inJar ==
nullptr)
1693 auto *inJar = qobject_cast<MythCookieJar *>(jar);
1694 if (inJar ==
nullptr)
1712 if (inJar !=
nullptr)
1729 QNetworkCacheMetaData metadata =
m_manager->cache()->metaData(url);
1741 const QString& header)
1743 auto headers = cacheData.rawHeaders();
1744 for (
const auto& rh : std::as_const(
headers))
1745 if (QString(rh.first) == header)
1756 const QList<QNetworkCookie> cookieList = old.allCookies();
1757 setAllCookies(cookieList);
1765 LOG(VB_GENERAL, LOG_DEBUG, QString(
"MythCookieJar: loading cookies from: %1").arg(
filename));
1768 if (!f.open(QIODevice::ReadOnly))
1770 LOG(VB_GENERAL, LOG_WARNING, QString(
"MythCookieJar::load() failed to open file for reading: %1").arg(
filename));
1774 QList<QNetworkCookie> cookieList;
1775 QTextStream stream(&f);
1776 while (!stream.atEnd())
1778 QString cookie = stream.readLine();
1779 cookieList << QNetworkCookie::parseCookies(cookie.toLocal8Bit());
1782 setAllCookies(cookieList);
1790 LOG(VB_GENERAL, LOG_DEBUG, QString(
"MythCookieJar: saving cookies to: %1").arg(
filename));
1793 if (!f.open(QIODevice::WriteOnly))
1795 LOG(VB_GENERAL, LOG_ERR, QString(
"MythCookieJar::save() failed to open file for writing: %1").arg(
filename));
1799 QList<QNetworkCookie> cookieList = allCookies();
1800 QTextStream stream(&f);
1802 for (
const auto& cookie : std::as_const(cookieList))
1803 stream << cookie.toRawForm() << Qt::endl;