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);
110 void thumbnailDownloadComplete(HTTP::Request_ptr request,
111 Delegate::StatusCode status, const std::string& bytes)
113 std::string u(request->url());
114 SG_LOG(SG_IO, SG_INFO, "downloaded thumbnail:" << u);
115 if (status == Delegate::STATUS_SUCCESS) {
116 thumbnailCache[u] = bytes;
117 fireDataForThumbnail(u, bytes);
120 downloadNextPendingThumbnail();
123 void fireDataForThumbnail(const std::string& aUrl, const std::string& bytes)
125 DelegateVec::const_iterator it;
126 const uint8_t* data = reinterpret_cast<const uint8_t*>(bytes.data());
127 for (it = delegates.begin(); it != delegates.end(); ++it) {
128 (*it)->dataForThumbnail(aUrl, bytes.size(), data);
132 void downloadNextPendingThumbnail()
134 thumbnailDownloadRequest.clear();
135 if (pendingThumbnails.empty()) {
139 std::string u = pendingThumbnails.front();
140 pendingThumbnails.pop_front();
141 thumbnailDownloadRequest = new Root::ThumbnailDownloader(this, u);
144 http->makeRequest(thumbnailDownloadRequest);
146 httpPendingRequests.push_back(thumbnailDownloadRequest);
150 DelegateVec delegates;
155 CatalogDict catalogs;
156 unsigned int maxAgeSeconds;
159 std::set<CatalogRef> refreshing;
160 typedef std::deque<InstallRef> UpdateDeque;
161 UpdateDeque updateDeque;
162 std::deque<HTTP::Request_ptr> httpPendingRequests;
164 HTTP::Request_ptr thumbnailDownloadRequest;
165 StringDeque pendingThumbnails;
166 MemThumbnailCache thumbnailCache;
168 typedef std::map<PackageRef, InstallRef> InstallCache;
169 InstallCache m_installs;
173 void Root::ThumbnailDownloader::onDone()
175 if (responseCode() != 200) {
176 SG_LOG(SG_GENERAL, SG_ALERT, "thumbnail download failure:" << url());
177 m_owner->thumbnailDownloadComplete(this, Delegate::FAIL_DOWNLOAD, std::string());
181 m_owner->thumbnailDownloadComplete(this, Delegate::STATUS_SUCCESS, m_buffer);
182 //time(&m_owner->m_retrievedTime);
183 //m_owner->writeTimestamp();
184 //m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
187 SGPath Root::path() const
192 void Root::setMaxAgeSeconds(unsigned int seconds)
194 d->maxAgeSeconds = seconds;
197 unsigned int Root::maxAgeSeconds() const
199 return d->maxAgeSeconds;
202 void Root::setHTTPClient(HTTP::Client* aHTTP)
205 BOOST_FOREACH(HTTP::Request_ptr req, d->httpPendingRequests) {
206 d->http->makeRequest(req);
209 d->httpPendingRequests.clear();
212 void Root::makeHTTPRequest(HTTP::Request *req)
215 d->http->makeRequest(req);
219 d->httpPendingRequests.push_back(req);
222 Root::Root(const SGPath& aPath, const std::string& aVersion) :
226 d->version = aVersion;
227 if (getenv("LOCALE")) {
228 d->locale = getenv("LOCALE");
237 BOOST_FOREACH(SGPath c, dir.children(Dir::TYPE_DIR)) {
238 CatalogRef cat = Catalog::createFromPath(this, c);
240 d->catalogs[cat->id()] = cat;
242 } // of child directories iteration
250 int Root::catalogVersion() const
255 std::string Root::applicationVersion() const
260 CatalogRef Root::getCatalogById(const std::string& aId) const
262 CatalogDict::const_iterator it = d->catalogs.find(aId);
263 if (it == d->catalogs.end()) {
270 PackageRef Root::getPackageById(const std::string& aName) const
272 size_t lastDot = aName.rfind('.');
274 PackageRef pkg = NULL;
275 if (lastDot == std::string::npos) {
277 CatalogDict::const_iterator it = d->catalogs.begin();
278 for (; it != d->catalogs.end(); ++it) {
279 pkg = it->second->getPackageById(aName);
288 std::string catalogId = aName.substr(0, lastDot);
289 std::string id = aName.substr(lastDot + 1);
290 CatalogRef catalog = getCatalogById(catalogId);
295 return catalog->getPackageById(id);
298 CatalogList Root::catalogs() const
301 CatalogDict::const_iterator it = d->catalogs.begin();
302 for (; it != d->catalogs.end(); ++it) {
303 r.push_back(it->second);
310 Root::allPackages() const
314 CatalogDict::const_iterator it = d->catalogs.begin();
315 for (; it != d->catalogs.end(); ++it) {
316 const PackageList& r2(it->second->packages());
317 r.insert(r.end(), r2.begin(), r2.end());
324 Root::packagesMatching(const SGPropertyNode* aFilter) const
328 CatalogDict::const_iterator it = d->catalogs.begin();
329 for (; it != d->catalogs.end(); ++it) {
330 PackageList r2(it->second->packagesMatching(aFilter));
331 r.insert(r.end(), r2.begin(), r2.end());
338 Root::packagesNeedingUpdate() const
342 CatalogDict::const_iterator it = d->catalogs.begin();
343 for (; it != d->catalogs.end(); ++it) {
344 PackageList r2(it->second->packagesNeedingUpdate());
345 r.insert(r.end(), r2.begin(), r2.end());
351 void Root::refresh(bool aForce)
353 bool didStartAny = false;
354 CatalogDict::iterator it = d->catalogs.begin();
355 for (; it != d->catalogs.end(); ++it) {
356 if (aForce || it->second->needsRefresh()) {
357 it->second->refresh();
363 // signal refresh complete to the delegate already
364 d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
368 void Root::addDelegate(simgear::pkg::Delegate *aDelegate)
370 d->delegates.push_back(aDelegate);
373 void Root::removeDelegate(simgear::pkg::Delegate *aDelegate)
375 DelegateVec::iterator it = std::find(d->delegates.begin(),
376 d->delegates.end(), aDelegate);
377 if (it == d->delegates.end()) {
378 throw sg_exception("unknown delegate in removeDelegate");
380 d->delegates.erase(it);
383 void Root::setLocale(const std::string& aLocale)
388 std::string Root::getLocale() const
393 void Root::scheduleToUpdate(InstallRef aInstall)
396 throw sg_exception("missing argument to scheduleToUpdate");
399 PackageList deps = aInstall->package()->dependencies();
400 BOOST_FOREACH(Package* dep, deps) {
401 // will internally schedule for update if required
402 // hence be careful, this method is re-entered in here!
406 bool wasEmpty = d->updateDeque.empty();
407 d->updateDeque.push_back(aInstall);
410 aInstall->startUpdate();
414 bool Root::isInstallQueued(InstallRef aInstall) const
416 RootPrivate::UpdateDeque::const_iterator it =
417 std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
418 return (it != d->updateDeque.end());
421 void Root::startInstall(InstallRef aInstall)
423 d->fireStartInstall(aInstall);
426 void Root::installProgress(InstallRef aInstall, unsigned int aBytes, unsigned int aTotal)
428 d->fireInstallProgress(aInstall, aBytes, aTotal);
431 void Root::startNext(InstallRef aCurrent)
433 if (d->updateDeque.front() != aCurrent) {
434 SG_LOG(SG_GENERAL, SG_ALERT, "current install of package not head of the deque");
436 d->updateDeque.pop_front();
439 if (!d->updateDeque.empty()) {
440 d->updateDeque.front()->startUpdate();
444 void Root::finishInstall(InstallRef aInstall, Delegate::StatusCode aReason)
446 if (aReason != Delegate::STATUS_SUCCESS) {
447 SG_LOG(SG_GENERAL, SG_ALERT, "failed to install package:"
448 << aInstall->package()->id() << ":" << aReason);
451 // order matters here, so a call to 'isQueued' from a finish-install
452 // callback returns false, not true
454 d->fireFinishInstall(aInstall, aReason);
457 void Root::cancelDownload(InstallRef aInstall)
459 RootPrivate::UpdateDeque::iterator it =
460 std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
461 if (it != d->updateDeque.end()) {
462 bool startNext = (aInstall == d->updateDeque.front());
463 d->updateDeque.erase(it);
465 if (!d->updateDeque.empty()) {
466 d->updateDeque.front()->startUpdate();
468 } // of install was front item
469 } // of found install in queue
472 void Root::catalogRefreshStatus(CatalogRef aCat, Delegate::StatusCode aReason)
474 CatalogDict::iterator catIt = d->catalogs.find(aCat->id());
475 d->fireRefreshStatus(aCat, aReason);
477 if (aReason == Delegate::STATUS_IN_PROGRESS) {
478 d->refreshing.insert(aCat);
480 if (catIt == d->catalogs.end()) {
481 // first fresh, add to our storage now
482 d->catalogs.insert(catIt, CatalogDict::value_type(aCat->id(), aCat));
485 d->refreshing.erase(aCat);
488 if ((aReason != Delegate::STATUS_REFRESHED) && (aReason != Delegate::STATUS_IN_PROGRESS)) {
489 // if the failure is permanent, delete the catalog from our
490 // list (don't touch it on disk)
491 bool isPermanentFailure = (aReason == Delegate::FAIL_VERSION);
492 if (isPermanentFailure) {
493 SG_LOG(SG_GENERAL, SG_WARN, "permanent failure for catalog:" << aCat->id());
494 if (catIt != d->catalogs.end()) {
495 d->catalogs.erase(catIt);
500 if (d->refreshing.empty()) {
501 d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
505 bool Root::removeCatalogById(const std::string& aId)
507 CatalogDict::iterator catIt = d->catalogs.find(aId);
508 if (catIt == d->catalogs.end()) {
509 SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: unknown ID:" << aId);
513 CatalogRef cat = catIt->second;
515 // drop the reference
516 d->catalogs.erase(catIt);
518 bool ok = cat->uninstall();
520 SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: catalog :" << aId
521 << "failed to uninstall");
527 void Root::requestThumbnailData(const std::string& aUrl)
529 MemThumbnailCache::iterator it = d->thumbnailCache.find(aUrl);
530 if (it == d->thumbnailCache.end()) {
531 // insert into cache to mark as pending
532 d->pendingThumbnails.push_front(aUrl);
533 d->thumbnailCache[aUrl] = std::string();
534 d->downloadNextPendingThumbnail();
535 } else if (!it->second.empty()) {
536 // already loaded, fire data synchronously
537 d->fireDataForThumbnail(aUrl, it->second);
539 // in cache but empty data, still fetching
543 InstallRef Root::existingInstallForPackage(PackageRef p) const
545 RootPrivate::InstallCache::const_iterator it =
546 d->m_installs.find(p);
547 if (it == d->m_installs.end()) {
548 // check if it exists on disk, create
549 SGPath path(p->pathOnDisk());
551 // this will add to our cache, and hence, modify m_installs
552 return Install::createFromPath(path, p->catalog());
555 // insert a null reference into the dictionary, so we don't call
556 // the pathOnDisk -> exists codepath repeatedley
557 d->m_installs[p] = InstallRef();
564 void Root::registerInstall(InstallRef ins)
570 d->m_installs[ins->package()] = ins;
573 void Root::unregisterInstall(InstallRef ins)
579 d->m_installs.erase(ins->package());
582 } // of namespace pkg
584 } // of namespace simgear