Showing the changes to libraries/script-engine/src/ScriptCache.cpp (1 of 6 files). Show all
Unified · Split
| @@ -81,4 +81,51 @@ void ScriptCache::scriptDownloaded() { · 80 unmodified lines | ||
| 81 | 81 | req->deleteLater(); |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | +void ScriptCache::getScriptContents(const QString& scriptOrURL, contentAvailableCallback contentAvailable, bool forceDownload) { | |
| 85 | + QUrl unnormalizedURL(scriptOrURL); | |
| 86 | + QUrl url = ResourceManager::normalizeURL(unnormalizedURL); | |
| 87 | + | |
| 88 | + // attempt to determine if this is a URL to a script, or if this is actually a script itself (which is valid in the entityScript use case) | |
| 89 | + if (url.scheme().isEmpty() && scriptOrURL.simplified().replace(" ", "").contains("(function(){")) { | |
| 90 | + contentAvailable(scriptOrURL, scriptOrURL, false, true); | |
| 91 | + return; | |
| 92 | + } | |
| 93 | + | |
| 94 | + if (_scriptCache.contains(url) && !forceDownload) { | |
| 95 | + qCDebug(scriptengine) << "Found script in cache:" << url.toString(); | |
| 96 | + contentAvailable(url.toString(), _scriptCache[url], true, true); | |
| 97 | + } else { | |
| 98 | + bool alreadyWaiting = _contentCallbacks.contains(url); | |
| 99 | + _contentCallbacks.insert(url, contentAvailable); | |
| 100 | + | |
| 101 | + if (alreadyWaiting) { | |
| 102 | + qCDebug(scriptengine) << "Already downloading script at:" << url.toString(); | |
| 103 | + } else { | |
| 104 | + auto request = ResourceManager::createResourceRequest(this, url); | |
| 105 | + request->setCacheEnabled(!forceDownload); | |
| 106 | + connect(request, &ResourceRequest::finished, this, &ScriptCache::scriptContentAvailable); | |
| 107 | + request->send(); | |
| 108 | + } | |
| 109 | + } | |
| 110 | +} | |
| 111 | + | |
| 112 | +void ScriptCache::scriptContentAvailable() { | |
| 113 | + ResourceRequest* req = qobject_cast<ResourceRequest*>(sender()); | |
| 114 | + QUrl url = req->getUrl(); | |
| 115 | + QList<contentAvailableCallback> allCallbacks = _contentCallbacks.values(url); | |
| 116 | + _contentCallbacks.remove(url); | |
| 117 | + | |
| 118 | + bool success = req->getResult() == ResourceRequest::Success; | |
| 119 | + | |
| 120 | + if (success) { | |
| 121 | + _scriptCache[url] = req->getData(); | |
| 122 | + qCDebug(scriptengine) << "Done downloading script at:" << url.toString(); | |
| 123 | + } else { | |
| 124 | + qCWarning(scriptengine) << "Error loading script from URL " << url; | |
| 125 | + } | |
| 126 | + foreach(contentAvailableCallback thisCallback, allCallbacks) { | |
| 127 | + thisCallback(url.toString(), _scriptCache[url], true, success); | |
| 128 | + } | |
| 129 | + req->deleteLater(); | |
| 130 | +} | |
| 84 | 131 | |