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/Catalog.hxx>
20 #include <boost/foreach.hpp>
25 #include <simgear/debug/logstream.hxx>
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/io/HTTPRequest.hxx>
28 #include <simgear/io/HTTPClient.hxx>
29 #include <simgear/misc/sg_dir.hxx>
30 #include <simgear/structure/exception.hxx>
31 #include <simgear/package/Package.hxx>
32 #include <simgear/package/Root.hxx>
33 #include <simgear/package/Install.hxx>
39 bool checkVersion(const std::string& aVersion, SGPropertyNode_ptr props)
41 BOOST_FOREACH(SGPropertyNode* v, props->getChildren("version")) {
42 std::string s(v->getStringValue());
47 // allow 3.5.* to match any of 3.5.0, 3.5.1rc1, 3.5.11 or so on
48 if (strutils::ends_with(s, ".*")) {
49 size_t lastDot = aVersion.rfind('.');
50 std::string ver = aVersion.substr(0, lastDot);
51 if (ver == s.substr(0, s.length() - 2)) {
59 std::string redirectUrlForVersion(const std::string& aVersion, SGPropertyNode_ptr props)
61 BOOST_FOREACH(SGPropertyNode* v, props->getChildren("alternate-version")) {
62 if (v->getStringValue("version") == aVersion) {
63 return v->getStringValue("url");
70 //////////////////////////////////////////////////////////////////////////////
72 class Catalog::Downloader : public HTTP::Request
75 Downloader(CatalogRef aOwner, const std::string& aUrl) :
80 m_owner->changeStatus(Delegate::STATUS_IN_PROGRESS);
81 SG_LOG(SG_GENERAL, SG_WARN, "downloading " << aUrl);
85 virtual void gotBodyData(const char* s, int n)
87 m_buffer += std::string(s, n);
92 if (responseCode() != 200) {
93 Delegate::StatusCode code = Delegate::FAIL_DOWNLOAD;
94 SG_LOG(SG_GENERAL, SG_ALERT, "catalog download failure:" << m_owner->url()
95 << "\n\t" << responseCode());
96 if (responseCode() == 404) {
97 code = Delegate::FAIL_NOT_FOUND;
99 m_owner->refreshComplete(code);
103 SGPropertyNode* props = new SGPropertyNode;
106 readProperties(m_buffer.data(), m_buffer.size(), props);
107 m_owner->parseProps(props);
108 } catch (sg_exception& e) {
109 SG_LOG(SG_GENERAL, SG_ALERT, "catalog parse failure:" << m_owner->url());
110 m_owner->refreshComplete(Delegate::FAIL_EXTRACT);
114 if (m_owner->root()->catalogVersion() != props->getIntValue("catalog-version")) {
115 SG_LOG(SG_GENERAL, SG_WARN, "catalog:" << m_owner->url() << " is not version "
116 << m_owner->root()->catalogVersion());
117 m_owner->refreshComplete(Delegate::FAIL_VERSION);
122 std::string ver(m_owner->root()->applicationVersion());
123 if (!checkVersion(ver, props)) {
124 SG_LOG(SG_GENERAL, SG_WARN, "downloaded catalog " << m_owner->url() << ", version mismatch:\n\t"
125 << props->getStringValue("version") << " vs required " << ver);
127 // check for a version redirect entry
128 std::string url = redirectUrlForVersion(ver, props);
130 SG_LOG(SG_GENERAL, SG_WARN, "redirecting from " << m_owner->url() <<
133 // update the URL and kick off a new request
134 m_owner->m_url = url;
135 Downloader* dl = new Downloader(m_owner, url);
136 m_owner->root()->makeHTTPRequest(dl);
138 m_owner->refreshComplete(Delegate::FAIL_VERSION);
142 } // of version check failed
144 // cache the catalog data, now we have a valid install root
145 Dir d(m_owner->installRoot());
146 SGPath p = d.file("catalog.xml");
148 std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
149 f.write(m_buffer.data(), m_buffer.size());
152 time(&m_owner->m_retrievedTime);
153 m_owner->writeTimestamp();
154 m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
160 std::string m_buffer;
163 //////////////////////////////////////////////////////////////////////////////
165 Catalog::Catalog(Root *aRoot) :
167 m_status(Delegate::FAIL_UNKNOWN),
176 CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
178 CatalogRef c = new Catalog(aRoot);
180 Downloader* dl = new Downloader(c, aUrl);
181 aRoot->makeHTTPRequest(dl);
186 CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
189 xml.append("catalog.xml");
194 SGPropertyNode_ptr props;
196 props = new SGPropertyNode;
197 readProperties(xml.str(), props);
198 } catch (sg_exception& e) {
202 if (!checkVersion(aRoot->applicationVersion(), props)) {
203 std::string redirect = redirectUrlForVersion(aRoot->applicationVersion(), props);
204 if (!redirect.empty()) {
205 SG_LOG(SG_GENERAL, SG_WARN, "catalog at " << aPath << ", version mismatch:\n\t"
206 << "redirecting to alternate URL:" << redirect);
207 CatalogRef c = Catalog::createFromUrl(aRoot, redirect);
208 c->m_installRoot = aPath;
211 SG_LOG(SG_GENERAL, SG_WARN, "skipping catalog at " << aPath << ", version mismatch:\n\t"
212 << props->getStringValue("version") << " vs required " << aRoot->catalogVersion());
217 SG_LOG(SG_GENERAL, SG_INFO, "creating catalog from:" << aPath);
220 CatalogRef c = new Catalog(aRoot);
221 c->m_installRoot = aPath;
222 c->parseProps(props); // will set status
228 bool Catalog::uninstall()
231 bool atLeastOneFailure = false;
233 BOOST_FOREACH(PackageRef p, installedPackages()) {
234 ok = p->existingInstall()->uninstall();
236 SG_LOG(SG_GENERAL, SG_WARN, "uninstall of package " <<
237 p->id() << " failed");
238 // continue trying other packages, bailing out here
240 atLeastOneFailure = true;
244 Dir d(m_installRoot);
245 ok = d.remove(true /* recursive */);
247 atLeastOneFailure = true;
250 changeStatus(atLeastOneFailure ? Delegate::FAIL_FILESYSTEM
251 : Delegate::STATUS_SUCCESS);
256 Catalog::packages() const
262 Catalog::packagesMatching(const SGPropertyNode* aFilter) const
265 BOOST_FOREACH(PackageRef p, m_packages) {
266 if (p->matches(aFilter)) {
274 Catalog::packagesNeedingUpdate() const
277 BOOST_FOREACH(PackageRef p, m_packages) {
278 if (!p->isInstalled()) {
282 if (p->install()->hasUpdate()) {
290 Catalog::installedPackages() const
293 BOOST_FOREACH(PackageRef p, m_packages) {
294 if (p->isInstalled()) {
301 void Catalog::refresh()
303 Downloader* dl = new Downloader(this, url());
304 // will update status to IN_PROGRESS
305 m_root->makeHTTPRequest(dl);
310 FindById(const std::string &id) : m_id(id) {}
312 bool operator()(const PackageRef& ref) const
314 return ref->id() == m_id;
320 void Catalog::parseProps(const SGPropertyNode* aProps)
322 // copy everything except package children?
323 m_props = new SGPropertyNode;
325 m_variantDict.clear(); // will rebuild during parse
326 std::set<PackageRef> orphans;
327 orphans.insert(m_packages.begin(), m_packages.end());
329 int nChildren = aProps->nChildren();
330 for (int i = 0; i < nChildren; i++) {
331 const SGPropertyNode* pkgProps = aProps->getChild(i);
332 if (strcmp(pkgProps->getName(), "package") == 0) {
333 // can't use getPackageById here becuase the variant dict isn't
334 // built yet. Instead we need to look at m_packages directly.
336 PackageList::iterator pit = std::find_if(m_packages.begin(), m_packages.end(),
337 FindById(pkgProps->getStringValue("id")));
339 if (pit != m_packages.end()) {
342 p->updateFromProps(pkgProps);
343 orphans.erase(p); // not an orphan
346 p = new Package(pkgProps, this);
347 m_packages.push_back(p);
350 string_list vars(p->variants());
351 for (string_list::iterator it = vars.begin(); it != vars.end(); ++it) {
352 m_variantDict[*it] = p.ptr();
355 SGPropertyNode* c = m_props->getChild(pkgProps->getName(), pkgProps->getIndex(), true);
356 copyProperties(pkgProps, c);
358 } // of children iteration
360 if (!orphans.empty()) {
361 SG_LOG(SG_GENERAL, SG_WARN, "have orphan packages: will become inaccesible");
362 std::set<PackageRef>::iterator it;
363 for (it = orphans.begin(); it != orphans.end(); ++it) {
364 SG_LOG(SG_GENERAL, SG_WARN, "\torphan package:" << (*it)->qualifiedId());
365 PackageList::iterator pit = std::find(m_packages.begin(), m_packages.end(), *it);
366 assert(pit != m_packages.end());
367 m_packages.erase(pit);
371 if (!m_url.empty()) {
372 if (m_url != m_props->getStringValue("url")) {
373 // this effectively allows packages to migrate to new locations,
374 // although if we're going to rely on that feature we should
375 // maybe formalise it!
376 SG_LOG(SG_GENERAL, SG_WARN, "package downloaded from:" << m_url
377 << " is now at: " << m_props->getStringValue("url"));
381 m_url = m_props->getStringValue("url");
383 if (m_installRoot.isNull()) {
384 m_installRoot = m_root->path();
385 m_installRoot.append(id());
387 Dir d(m_installRoot);
391 // parsed XML ok, mark status as valid
392 changeStatus(Delegate::STATUS_SUCCESS);
395 PackageRef Catalog::getPackageById(const std::string& aId) const
397 // search the variant dict here, so looking up aircraft variants
398 // works as expected.
399 PackageWeakMap::const_iterator it = m_variantDict.find(aId);
400 if (it == m_variantDict.end())
406 PackageRef Catalog::getPackageByPath(const std::string& aPath) const
408 PackageList::const_iterator it;
409 for (it = m_packages.begin(); it != m_packages.end(); ++it) {
410 if ((*it)->dirName() == aPath) {
418 std::string Catalog::id() const
420 return m_props->getStringValue("id");
423 std::string Catalog::url() const
428 std::string Catalog::description() const
430 return getLocalisedString(m_props, "description");
433 SGPropertyNode* Catalog::properties() const
435 return m_props.ptr();
438 void Catalog::parseTimestamp()
440 SGPath timestampFile = m_installRoot;
441 timestampFile.append(".timestamp");
442 std::ifstream f(timestampFile.c_str(), std::ios::in);
443 f >> m_retrievedTime;
446 void Catalog::writeTimestamp()
448 SGPath timestampFile = m_installRoot;
449 timestampFile.append(".timestamp");
450 std::ofstream f(timestampFile.c_str(), std::ios::out | std::ios::trunc);
451 f << m_retrievedTime << std::endl;
454 unsigned int Catalog::ageInSeconds() const
458 int diff = ::difftime(now, m_retrievedTime);
459 return (diff < 0) ? 0 : diff;
462 bool Catalog::needsRefresh() const
464 unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds());
465 return (ageInSeconds() > maxAge);
468 std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const
471 return std::string();
474 if (aRoot->hasChild(m_root->getLocale())) {
475 const SGPropertyNode* localeRoot = aRoot->getChild(m_root->getLocale().c_str());
476 if (localeRoot->hasChild(aName)) {
477 return localeRoot->getStringValue(aName);
481 return aRoot->getStringValue(aName);
484 void Catalog::refreshComplete(Delegate::StatusCode aReason)
486 m_root->catalogRefreshStatus(this, aReason);
487 changeStatus(aReason);
490 void Catalog::changeStatus(Delegate::StatusCode newStatus)
492 if (m_status == newStatus) {
496 m_status = newStatus;
497 m_root->catalogRefreshStatus(this, newStatus);
498 m_statusCallbacks(this);
501 void Catalog::addStatusCallback(const Callback& cb)
503 m_statusCallbacks.push_back(cb);
506 Delegate::StatusCode Catalog::status() const
511 } // of namespace pkg
513 } // of namespace simgear