3 #include "ytjsnamfactory.h"
5 #include "cachedhttp.h"
11 QString wsBase = "https://flavio.tordini.org/minitube-ws/ytjs/";
12 QString ytJs = wsBase + "yt.js";
16 YTJS &YTJS::instance() {
23 Http *http = new Http;
24 http->addRequestHeader("User-Agent", HttpUtils::userAgent());
30 Http &YTJS::cachedHttp() {
32 CachedHttp *cachedHttp = new CachedHttp(http(), "ytjs");
33 cachedHttp->setMaxSeconds(3600 * 6);
34 // Avoid expiring the cached js
35 cachedHttp->setMaxSize(0);
36 cachedHttp->setIgnoreHostname(true);
38 cachedHttp->getValidators().insert("application/javascript", [](const auto &reply) -> bool {
39 return !reply.body().isEmpty();
47 YTJS::YTJS(QObject *parent) : QObject(parent), engine(nullptr) {
51 bool YTJS::checkError(const QJSValue &value) {
52 if (value.isError()) {
53 qWarning() << "Error" << value.toString();
54 qDebug() << value.property("stack").toString().splitRef('\n');
60 bool YTJS::isInitialized() {
61 if (ready) return true;
66 void YTJS::initialize() {
67 if (initializing) return;
70 if (engine) engine->deleteLater();
71 engine = new QQmlEngine(this);
72 engine->setNetworkAccessManagerFactory(new YTJSNAMFactory);
74 engine->globalObject().setProperty("global", engine->globalObject());
76 QJSValue timer = engine->newQObject(new JsTimer(engine));
77 engine->globalObject().setProperty("clearTimeout", timer.property("clearTimeout"));
78 engine->globalObject().setProperty("setTimeout", timer.property("setTimeout"));
80 connect(cachedHttp().get(ytJs), &HttpReply::finished, this, [this](auto &reply) {
81 if (!reply.isSuccessful()) {
82 emit initFailed("Cannot load JS");
83 qDebug() << "Cannot load JS";
86 evaluate(reply.body());
89 qDebug() << "Initialized";
94 QJSValue YTJS::evaluate(const QString &js) {
95 auto value = engine->evaluate(js);