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 std::string Root::catalogVersion() const
255 CatalogRef Root::getCatalogById(const std::string& aId) const
257 CatalogDict::const_iterator it = d->catalogs.find(aId);
258 if (it == d->catalogs.end()) {
265 PackageRef Root::getPackageById(const std::string& aName) const
267 size_t lastDot = aName.rfind('.');
269 PackageRef pkg = NULL;
270 if (lastDot == std::string::npos) {
272 CatalogDict::const_iterator it = d->catalogs.begin();
273 for (; it != d->catalogs.end(); ++it) {
274 pkg = it->second->getPackageById(aName);
283 std::string catalogId = aName.substr(0, lastDot);
284 std::string id = aName.substr(lastDot + 1);
285 CatalogRef catalog = getCatalogById(catalogId);
290 return catalog->getPackageById(id);
293 CatalogList Root::catalogs() const
296 CatalogDict::const_iterator it = d->catalogs.begin();
297 for (; it != d->catalogs.end(); ++it) {
298 r.push_back(it->second);
305 Root::allPackages() const
309 CatalogDict::const_iterator it = d->catalogs.begin();
310 for (; it != d->catalogs.end(); ++it) {
311 const PackageList& r2(it->second->packages());
312 r.insert(r.end(), r2.begin(), r2.end());
319 Root::packagesMatching(const SGPropertyNode* aFilter) const
323 CatalogDict::const_iterator it = d->catalogs.begin();
324 for (; it != d->catalogs.end(); ++it) {
325 PackageList r2(it->second->packagesMatching(aFilter));
326 r.insert(r.end(), r2.begin(), r2.end());
333 Root::packagesNeedingUpdate() const
337 CatalogDict::const_iterator it = d->catalogs.begin();
338 for (; it != d->catalogs.end(); ++it) {
339 PackageList r2(it->second->packagesNeedingUpdate());
340 r.insert(r.end(), r2.begin(), r2.end());
346 void Root::refresh(bool aForce)
348 bool didStartAny = false;
349 CatalogDict::iterator it = d->catalogs.begin();
350 for (; it != d->catalogs.end(); ++it) {
351 if (aForce || it->second->needsRefresh()) {
352 it->second->refresh();
358 // signal refresh complete to the delegate already
359 d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
363 void Root::addDelegate(simgear::pkg::Delegate *aDelegate)
365 d->delegates.push_back(aDelegate);
368 void Root::removeDelegate(simgear::pkg::Delegate *aDelegate)
370 DelegateVec::iterator it = std::find(d->delegates.begin(),
371 d->delegates.end(), aDelegate);
372 if (it == d->delegates.end()) {
373 throw sg_exception("unknown delegate in removeDelegate");
375 d->delegates.erase(it);
378 void Root::setLocale(const std::string& aLocale)
383 std::string Root::getLocale() const
388 void Root::scheduleToUpdate(InstallRef aInstall)
391 throw sg_exception("missing argument to scheduleToUpdate");
394 PackageList deps = aInstall->package()->dependencies();
395 BOOST_FOREACH(Package* dep, deps) {
396 // will internally schedule for update if required
397 // hence be careful, this method is re-entered in here!
401 bool wasEmpty = d->updateDeque.empty();
402 d->updateDeque.push_back(aInstall);
405 aInstall->startUpdate();
409 bool Root::isInstallQueued(InstallRef aInstall) const
411 RootPrivate::UpdateDeque::const_iterator it =
412 std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
413 return (it != d->updateDeque.end());
416 void Root::startInstall(InstallRef aInstall)
418 d->fireStartInstall(aInstall);
421 void Root::installProgress(InstallRef aInstall, unsigned int aBytes, unsigned int aTotal)
423 d->fireInstallProgress(aInstall, aBytes, aTotal);
426 void Root::startNext(InstallRef aCurrent)
428 if (d->updateDeque.front() != aCurrent) {
429 SG_LOG(SG_GENERAL, SG_ALERT, "current install of package not head of the deque");
431 d->updateDeque.pop_front();
434 if (!d->updateDeque.empty()) {
435 d->updateDeque.front()->startUpdate();
439 void Root::finishInstall(InstallRef aInstall, Delegate::StatusCode aReason)
441 if (aReason != Delegate::STATUS_SUCCESS) {
442 SG_LOG(SG_GENERAL, SG_ALERT, "failed to install package:"
443 << aInstall->package()->id() << ":" << aReason);
446 d->fireFinishInstall(aInstall, aReason);
450 void Root::cancelDownload(InstallRef aInstall)
452 RootPrivate::UpdateDeque::iterator it =
453 std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
454 if (it != d->updateDeque.end()) {
455 bool startNext = (aInstall == d->updateDeque.front());
456 d->updateDeque.erase(it);
458 if (!d->updateDeque.empty()) {
459 d->updateDeque.front()->startUpdate();
461 } // of install was front item
462 } // of found install in queue
465 void Root::catalogRefreshStatus(CatalogRef aCat, Delegate::StatusCode aReason)
467 CatalogDict::iterator catIt = d->catalogs.find(aCat->id());
468 d->fireRefreshStatus(aCat, aReason);
470 if (aReason == Delegate::STATUS_IN_PROGRESS) {
471 d->refreshing.insert(aCat);
473 if (catIt == d->catalogs.end()) {
474 // first fresh, add to our storage now
475 d->catalogs.insert(catIt, CatalogDict::value_type(aCat->id(), aCat));
478 d->refreshing.erase(aCat);
481 if ((aReason != Delegate::STATUS_REFRESHED) && (aReason != Delegate::STATUS_IN_PROGRESS)) {
482 // if the failure is permanent, delete the catalog from our
483 // list (don't touch it on disk)
484 bool isPermanentFailure = (aReason == Delegate::FAIL_VERSION);
485 if (isPermanentFailure) {
486 SG_LOG(SG_GENERAL, SG_WARN, "permanent failure for catalog:" << aCat->id());
487 if (catIt != d->catalogs.end()) {
488 d->catalogs.erase(catIt);
493 if (d->refreshing.empty()) {
494 d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
498 bool Root::removeCatalogById(const std::string& aId)
500 CatalogDict::iterator catIt = d->catalogs.find(aId);
501 if (catIt == d->catalogs.end()) {
502 SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: unknown ID:" << aId);
506 CatalogRef cat = catIt->second;
508 // drop the reference
509 d->catalogs.erase(catIt);
511 bool ok = cat->uninstall();
513 SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: catalog :" << aId
514 << "failed to uninstall");
520 void Root::requestThumbnailData(const std::string& aUrl)
522 MemThumbnailCache::iterator it = d->thumbnailCache.find(aUrl);
523 if (it == d->thumbnailCache.end()) {
524 // insert into cache to mark as pending
525 d->pendingThumbnails.push_front(aUrl);
526 d->thumbnailCache[aUrl] = std::string();
527 d->downloadNextPendingThumbnail();
528 } else if (!it->second.empty()) {
529 // already loaded, fire data synchronously
530 d->fireDataForThumbnail(aUrl, it->second);
532 // in cache but empty data, still fetching
536 InstallRef Root::existingInstallForPackage(PackageRef p) const
538 RootPrivate::InstallCache::const_iterator it =
539 d->m_installs.find(p);
540 if (it == d->m_installs.end()) {
541 // check if it exists on disk, create
542 SGPath path(p->pathOnDisk());
544 // this will add to our cache, and hence, modify m_installs
545 return Install::createFromPath(path, p->catalog());
554 void Root::registerInstall(InstallRef ins)
560 d->m_installs[ins->package()] = ins;
563 void Root::unregisterInstall(InstallRef ins)
569 d->m_installs.erase(ins->package());
572 } // of namespace pkg
574 } // of namespace simgear