1 // Copyright (C) 2013 James Turner - zakalawe@mac.com
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Library General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 #include <simgear/package/Root.hxx>
20 #include <boost/foreach.hpp>
26 #include <simgear/debug/logstream.hxx>
27 #include <simgear/props/props_io.hxx>
28 #include <simgear/io/HTTPRequest.hxx>
29 #include <simgear/io/HTTPClient.hxx>
30 #include <simgear/misc/sg_dir.hxx>
31 #include <simgear/structure/exception.hxx>
32 #include <simgear/package/Package.hxx>
33 #include <simgear/package/Install.hxx>
34 #include <simgear/package/Catalog.hxx>
40 typedef std::map<std::string, CatalogRef> CatalogDict;
41 typedef std::vector<Delegate*> DelegateVec;
42 typedef std::map<std::string, std::string> MemThumbnailCache;
43 typedef std::deque<std::string> StringDeque;
45 class Root::ThumbnailDownloader : public HTTP::Request
48 ThumbnailDownloader(Root::RootPrivate* aOwner, const std::string& aUrl) :
55 virtual void gotBodyData(const char* s, int n)
57 m_buffer += std::string(s, n);
60 virtual void onDone();
63 Root::RootPrivate* m_owner;
67 class Root::RootPrivate
72 maxAgeSeconds(60 * 60 * 24)
76 void fireStartInstall(InstallRef install)
78 DelegateVec::const_iterator it;
79 for (it = delegates.begin(); it != delegates.end(); ++it) {
80 (*it)->startInstall(install);
84 void fireInstallProgress(InstallRef install,
85 unsigned int aBytes, unsigned int aTotal)
87 DelegateVec::const_iterator it;
88 for (it = delegates.begin(); it != delegates.end(); ++it) {
89 (*it)->installProgress(install, aBytes, aTotal);
93 void fireFinishInstall(InstallRef install, Delegate::StatusCode status)
95 DelegateVec::const_iterator it;
96 for (it = delegates.begin(); it != delegates.end(); ++it) {
97 (*it)->finishInstall(install, status);
101 void fireRefreshStatus(CatalogRef catalog, Delegate::StatusCode status)
103 DelegateVec::const_iterator it;
104 for (it = delegates.begin(); it != delegates.end(); ++it) {
105 (*it)->catalogRefreshed(catalog, status);
109 void firePackagesChanged()
111 DelegateVec::const_iterator it;
112 for (it = delegates.begin(); it != delegates.end(); ++it) {
113 (*it)->availablePackagesChanged();
117 void thumbnailDownloadComplete(HTTP::Request_ptr request,
118 Delegate::StatusCode status, const std::string& bytes)
120 std::string u(request->url());
121 if (status == Delegate::STATUS_SUCCESS) {
122 thumbnailCache[u] = bytes;
123 fireDataForThumbnail(u, bytes);
126 downloadNextPendingThumbnail();
129 void fireDataForThumbnail(const std::string& aUrl, const std::string& bytes)
131 DelegateVec::const_iterator it;
132 const uint8_t* data = reinterpret_cast<const uint8_t*>(bytes.data());
133 for (it = delegates.begin(); it != delegates.end(); ++it) {
134 (*it)->dataForThumbnail(aUrl, bytes.size(), data);
138 void downloadNextPendingThumbnail()
140 thumbnailDownloadRequest.clear();
141 if (pendingThumbnails.empty()) {
145 std::string u = pendingThumbnails.front();
146 pendingThumbnails.pop_front();
147 thumbnailDownloadRequest = new Root::ThumbnailDownloader(this, u);
150 http->makeRequest(thumbnailDownloadRequest);
152 httpPendingRequests.push_back(thumbnailDownloadRequest);
156 DelegateVec delegates;
161 CatalogDict catalogs;
162 unsigned int maxAgeSeconds;
165 std::set<CatalogRef> refreshing;
166 typedef std::deque<InstallRef> UpdateDeque;
167 UpdateDeque updateDeque;
168 std::deque<HTTP::Request_ptr> httpPendingRequests;
170 HTTP::Request_ptr thumbnailDownloadRequest;
171 StringDeque pendingThumbnails;
172 MemThumbnailCache thumbnailCache;
174 typedef std::map<PackageRef, InstallRef> InstallCache;
175 InstallCache m_installs;
179 void Root::ThumbnailDownloader::onDone()
181 if (responseCode() != 200) {
182 SG_LOG(SG_GENERAL, SG_ALERT, "thumbnail download failure:" << url());
183 m_owner->thumbnailDownloadComplete(this, Delegate::FAIL_DOWNLOAD, std::string());
187 m_owner->thumbnailDownloadComplete(this, Delegate::STATUS_SUCCESS, m_buffer);
188 //time(&m_owner->m_retrievedTime);
189 //m_owner->writeTimestamp();
190 //m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
193 SGPath Root::path() const
198 void Root::setMaxAgeSeconds(unsigned int seconds)
200 d->maxAgeSeconds = seconds;
203 unsigned int Root::maxAgeSeconds() const
205 return d->maxAgeSeconds;
208 void Root::setHTTPClient(HTTP::Client* aHTTP)
211 BOOST_FOREACH(HTTP::Request_ptr req, d->httpPendingRequests) {
212 d->http->makeRequest(req);
215 d->httpPendingRequests.clear();
218 void Root::makeHTTPRequest(HTTP::Request *req)
221 d->http->makeRequest(req);
225 d->httpPendingRequests.push_back(req);
228 Root::Root(const SGPath& aPath, const std::string& aVersion) :
232 d->version = aVersion;
233 if (getenv("LOCALE")) {
234 d->locale = getenv("LOCALE");
243 BOOST_FOREACH(SGPath c, dir.children(Dir::TYPE_DIR)) {
244 CatalogRef cat = Catalog::createFromPath(this, c);
246 d->catalogs[cat->id()] = cat;
248 } // of child directories iteration
256 int Root::catalogVersion() const
261 std::string Root::applicationVersion() const
266 CatalogRef Root::getCatalogById(const std::string& aId) const
268 CatalogDict::const_iterator it = d->catalogs.find(aId);
269 if (it == d->catalogs.end()) {
276 PackageRef Root::getPackageById(const std::string& aName) const
278 size_t lastDot = aName.rfind('.');
280 PackageRef pkg = NULL;
281 if (lastDot == std::string::npos) {
283 CatalogDict::const_iterator it = d->catalogs.begin();
284 for (; it != d->catalogs.end(); ++it) {
285 pkg = it->second->getPackageById(aName);
294 std::string catalogId = aName.substr(0, lastDot);
295 std::string id = aName.substr(lastDot + 1);
296 CatalogRef catalog = getCatalogById(catalogId);
301 return catalog->getPackageById(id);
304 CatalogList Root::catalogs() const
307 CatalogDict::const_iterator it = d->catalogs.begin();
308 for (; it != d->catalogs.end(); ++it) {
309 r.push_back(it->second);
316 Root::allPackages() const
320 CatalogDict::const_iterator it = d->catalogs.begin();
321 for (; it != d->catalogs.end(); ++it) {
322 const PackageList& r2(it->second->packages());
323 r.insert(r.end(), r2.begin(), r2.end());
330 Root::packagesMatching(const SGPropertyNode* aFilter) const
334 CatalogDict::const_iterator it = d->catalogs.begin();
335 for (; it != d->catalogs.end(); ++it) {
336 PackageList r2(it->second->packagesMatching(aFilter));
337 r.insert(r.end(), r2.begin(), r2.end());
344 Root::packagesNeedingUpdate() const
348 CatalogDict::const_iterator it = d->catalogs.begin();
349 for (; it != d->catalogs.end(); ++it) {
350 PackageList r2(it->second->packagesNeedingUpdate());
351 r.insert(r.end(), r2.begin(), r2.end());
357 void Root::refresh(bool aForce)
359 bool didStartAny = false;
360 CatalogDict::iterator it = d->catalogs.begin();
361 for (; it != d->catalogs.end(); ++it) {
362 if (aForce || it->second->needsRefresh()) {
363 it->second->refresh();
369 // signal refresh complete to the delegate already
370 d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
374 void Root::addDelegate(simgear::pkg::Delegate *aDelegate)
376 d->delegates.push_back(aDelegate);
379 void Root::removeDelegate(simgear::pkg::Delegate *aDelegate)
381 DelegateVec::iterator it = std::find(d->delegates.begin(),
382 d->delegates.end(), aDelegate);
383 if (it == d->delegates.end()) {
384 throw sg_exception("unknown delegate in removeDelegate");
386 d->delegates.erase(it);
389 void Root::setLocale(const std::string& aLocale)
394 std::string Root::getLocale() const
399 void Root::scheduleToUpdate(InstallRef aInstall)
402 throw sg_exception("missing argument to scheduleToUpdate");
405 PackageList deps = aInstall->package()->dependencies();
406 BOOST_FOREACH(Package* dep, deps) {
407 // will internally schedule for update if required
408 // hence be careful, this method is re-entered in here!
412 bool wasEmpty = d->updateDeque.empty();
413 d->updateDeque.push_back(aInstall);
416 aInstall->startUpdate();
420 bool Root::isInstallQueued(InstallRef aInstall) const
422 RootPrivate::UpdateDeque::const_iterator it =
423 std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
424 return (it != d->updateDeque.end());
427 void Root::startInstall(InstallRef aInstall)
429 d->fireStartInstall(aInstall);
432 void Root::installProgress(InstallRef aInstall, unsigned int aBytes, unsigned int aTotal)
434 d->fireInstallProgress(aInstall, aBytes, aTotal);
437 void Root::startNext(InstallRef aCurrent)
439 if (d->updateDeque.front() != aCurrent) {
440 SG_LOG(SG_GENERAL, SG_ALERT, "current install of package not head of the deque");
442 d->updateDeque.pop_front();
445 if (!d->updateDeque.empty()) {
446 d->updateDeque.front()->startUpdate();
450 void Root::finishInstall(InstallRef aInstall, Delegate::StatusCode aReason)
452 if (aReason != Delegate::STATUS_SUCCESS) {
453 SG_LOG(SG_GENERAL, SG_ALERT, "failed to install package:"
454 << aInstall->package()->id() << ":" << aReason);
457 // order matters here, so a call to 'isQueued' from a finish-install
458 // callback returns false, not true
460 d->fireFinishInstall(aInstall, aReason);
463 void Root::cancelDownload(InstallRef aInstall)
465 RootPrivate::UpdateDeque::iterator it =
466 std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
467 if (it != d->updateDeque.end()) {
468 bool startNext = (aInstall == d->updateDeque.front());
469 d->updateDeque.erase(it);
471 if (!d->updateDeque.empty()) {
472 d->updateDeque.front()->startUpdate();
474 } // of install was front item
475 } // of found install in queue
478 void Root::catalogRefreshStatus(CatalogRef aCat, Delegate::StatusCode aReason)
480 CatalogDict::iterator catIt = d->catalogs.find(aCat->id());
481 d->fireRefreshStatus(aCat, aReason);
483 if (aReason == Delegate::STATUS_IN_PROGRESS) {
484 d->refreshing.insert(aCat);
486 d->refreshing.erase(aCat);
489 if ((aReason != Delegate::STATUS_REFRESHED) && (aReason != Delegate::STATUS_IN_PROGRESS)) {
490 // if the failure is permanent, delete the catalog from our
491 // list (don't touch it on disk)
492 bool isPermanentFailure = (aReason == Delegate::FAIL_VERSION);
493 if (isPermanentFailure) {
494 SG_LOG(SG_GENERAL, SG_WARN, "permanent failure for catalog:" << aCat->id());
495 if (catIt != d->catalogs.end()) {
496 d->catalogs.erase(catIt);
501 if ((aReason == Delegate::STATUS_REFRESHED) && (catIt == d->catalogs.end())) {
502 assert(!aCat->id().empty());
503 d->catalogs.insert(catIt, CatalogDict::value_type(aCat->id(), aCat));
506 if (d->refreshing.empty()) {
507 d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
508 d->firePackagesChanged();
512 bool Root::removeCatalogById(const std::string& aId)
514 CatalogDict::iterator catIt = d->catalogs.find(aId);
515 if (catIt == d->catalogs.end()) {
516 SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: unknown ID:" << aId);
520 CatalogRef cat = catIt->second;
522 // drop the reference
523 d->catalogs.erase(catIt);
525 bool ok = cat->uninstall();
527 SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: catalog :" << aId
528 << "failed to uninstall");
531 // notify that a catalog is being removed
532 d->firePackagesChanged();
537 void Root::requestThumbnailData(const std::string& aUrl)
539 MemThumbnailCache::iterator it = d->thumbnailCache.find(aUrl);
540 if (it == d->thumbnailCache.end()) {
541 // insert into cache to mark as pending
542 d->pendingThumbnails.push_front(aUrl);
543 d->thumbnailCache[aUrl] = std::string();
544 d->downloadNextPendingThumbnail();
545 } else if (!it->second.empty()) {
546 // already loaded, fire data synchronously
547 d->fireDataForThumbnail(aUrl, it->second);
549 // in cache but empty data, still fetching
553 InstallRef Root::existingInstallForPackage(PackageRef p) const
555 RootPrivate::InstallCache::const_iterator it =
556 d->m_installs.find(p);
557 if (it == d->m_installs.end()) {
558 // check if it exists on disk, create
559 SGPath path(p->pathOnDisk());
561 // this will add to our cache, and hence, modify m_installs
562 return Install::createFromPath(path, p->catalog());
565 // insert a null reference into the dictionary, so we don't call
566 // the pathOnDisk -> exists codepath repeatedley
567 d->m_installs[p] = InstallRef();
574 void Root::registerInstall(InstallRef ins)
580 d->m_installs[ins->package()] = ins;
583 void Root::unregisterInstall(InstallRef ins)
589 d->m_installs.erase(ins->package());
592 } // of namespace pkg
594 } // of namespace simgear