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 cachedHttp->setIgnoreHostname(true);
36 cachedHttp->getValidators().insert("application/javascript", [](const auto &reply) -> bool {
37 return !reply.body().isEmpty();
45 YTJS::YTJS(QObject *parent) : QObject(parent), engine(nullptr) {
49 bool YTJS::checkError(const QJSValue &value) {
50 if (value.isError()) {
51 qWarning() << "Error" << value.toString();
52 qDebug() << value.property("stack").toString().splitRef('\n');
58 bool YTJS::isInitialized() {
59 if (ready) return true;
64 void YTJS::initialize() {
65 if (initializing) return;
68 if (engine) engine->deleteLater();
69 engine = new QQmlEngine(this);
70 engine->setNetworkAccessManagerFactory(new YTJSNAMFactory);
72 engine->globalObject().setProperty("global", engine->globalObject());
74 QJSValue timer = engine->newQObject(new JsTimer(engine));
75 engine->globalObject().setProperty("clearTimeout", timer.property("clearTimeout"));
76 engine->globalObject().setProperty("setTimeout", timer.property("setTimeout"));
78 connect(cachedHttp().get(ytJs), &HttpReply::finished, this, [this](auto &reply) {
79 if (!reply.isSuccessful()) {
80 emit initFailed("Cannot load " + ytJs);
83 evaluate(reply.body());
90 QJSValue YTJS::evaluate(const QString &js) {
91 auto value = engine->evaluate(js);