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>
34 #include <simgear/misc/strutils.hxx>
40 bool checkVersion(const std::string& aVersion, SGPropertyNode_ptr props)
42 BOOST_FOREACH(SGPropertyNode* v, props->getChildren("version")) {
43 std::string s(v->getStringValue());
48 // examine each dot-seperated component in turn, supporting a wildcard
49 // in the versions from the catalog.
50 string_list appVersionParts = simgear::strutils::split(aVersion, ".");
51 string_list catVersionParts = simgear::strutils::split(s, ".");
53 size_t partCount = appVersionParts.size();
54 if (partCount != catVersionParts.size()) {
59 for (unsigned int p=0; p < partCount; ++p) {
60 if (catVersionParts[p] == "*") {
62 } else if (appVersionParts[p] != catVersionParts[p]) {
74 std::string redirectUrlForVersion(const std::string& aVersion, SGPropertyNode_ptr props)
76 BOOST_FOREACH(SGPropertyNode* v, props->getChildren("alternate-version")) {
77 if (v->getStringValue("version") == aVersion) {
78 return v->getStringValue("url");
85 //////////////////////////////////////////////////////////////////////////////
87 class Catalog::Downloader : public HTTP::Request
90 Downloader(CatalogRef aOwner, const std::string& aUrl) :
95 m_owner->changeStatus(Delegate::STATUS_IN_PROGRESS);
99 virtual void gotBodyData(const char* s, int n)
101 m_buffer += std::string(s, n);
104 virtual void onDone()
106 if (responseCode() != 200) {
107 Delegate::StatusCode code = Delegate::FAIL_DOWNLOAD;
108 SG_LOG(SG_GENERAL, SG_ALERT, "catalog download failure:" << m_owner->url()
109 << "\n\t" << responseCode());
110 if (responseCode() == 404) {
111 code = Delegate::FAIL_NOT_FOUND;
113 m_owner->refreshComplete(code);
117 SGPropertyNode* props = new SGPropertyNode;
120 readProperties(m_buffer.data(), m_buffer.size(), props);
121 m_owner->parseProps(props);
122 } catch (sg_exception& e) {
123 SG_LOG(SG_GENERAL, SG_ALERT, "catalog parse failure:" << m_owner->url());
124 m_owner->refreshComplete(Delegate::FAIL_EXTRACT);
128 if (m_owner->root()->catalogVersion() != props->getIntValue("catalog-version")) {
129 SG_LOG(SG_GENERAL, SG_WARN, "catalog:" << m_owner->url() << " is not version "
130 << m_owner->root()->catalogVersion());
131 m_owner->refreshComplete(Delegate::FAIL_VERSION);
136 std::string ver(m_owner->root()->applicationVersion());
137 if (!checkVersion(ver, props)) {
138 SG_LOG(SG_GENERAL, SG_WARN, "downloaded catalog " << m_owner->url() << ", version mismatch:\n\t"
139 << props->getStringValue("version") << " vs required " << ver);
141 // check for a version redirect entry
142 std::string url = redirectUrlForVersion(ver, props);
144 SG_LOG(SG_GENERAL, SG_WARN, "redirecting from " << m_owner->url() <<
147 // update the URL and kick off a new request
148 m_owner->m_url = url;
149 Downloader* dl = new Downloader(m_owner, url);
150 m_owner->root()->makeHTTPRequest(dl);
152 m_owner->refreshComplete(Delegate::FAIL_VERSION);
156 } // of version check failed
158 // cache the catalog data, now we have a valid install root
159 Dir d(m_owner->installRoot());
160 SGPath p = d.file("catalog.xml");
162 std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
163 f.write(m_buffer.data(), m_buffer.size());
166 time(&m_owner->m_retrievedTime);
167 m_owner->writeTimestamp();
168 m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
174 std::string m_buffer;
177 //////////////////////////////////////////////////////////////////////////////
179 Catalog::Catalog(Root *aRoot) :
181 m_status(Delegate::FAIL_UNKNOWN),
190 CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
192 CatalogRef c = new Catalog(aRoot);
198 CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
201 xml.append("catalog.xml");
206 SGPropertyNode_ptr props;
208 props = new SGPropertyNode;
209 readProperties(xml.str(), props);
210 } catch (sg_exception& e) {
214 bool versionCheckOk = checkVersion(aRoot->applicationVersion(), props);
216 if (!versionCheckOk) {
217 SG_LOG(SG_GENERAL, SG_INFO, "catalog at:" << aPath << " failed version check: need" << aRoot->applicationVersion());
218 // keep the catalog but mark it as needing an update
220 SG_LOG(SG_GENERAL, SG_DEBUG, "creating catalog from:" << aPath);
223 CatalogRef c = new Catalog(aRoot);
224 c->m_installRoot = aPath;
225 c->parseProps(props);
228 if (versionCheckOk) {
229 // parsed XML ok, mark status as valid
230 c->changeStatus(Delegate::STATUS_SUCCESS);
232 c->changeStatus(Delegate::FAIL_VERSION);
238 bool Catalog::uninstall()
241 bool atLeastOneFailure = false;
243 BOOST_FOREACH(PackageRef p, installedPackages()) {
244 ok = p->existingInstall()->uninstall();
246 SG_LOG(SG_GENERAL, SG_WARN, "uninstall of package " <<
247 p->id() << " failed");
248 // continue trying other packages, bailing out here
250 atLeastOneFailure = true;
254 Dir d(m_installRoot);
255 ok = d.remove(true /* recursive */);
257 atLeastOneFailure = true;
260 changeStatus(atLeastOneFailure ? Delegate::FAIL_FILESYSTEM
261 : Delegate::STATUS_SUCCESS);
266 Catalog::packages() const
272 Catalog::packagesMatching(const SGPropertyNode* aFilter) const
275 BOOST_FOREACH(PackageRef p, m_packages) {
276 if (p->matches(aFilter)) {
284 Catalog::packagesNeedingUpdate() const
287 BOOST_FOREACH(PackageRef p, m_packages) {
288 if (!p->isInstalled()) {
292 if (p->install()->hasUpdate()) {
300 Catalog::installedPackages() const
303 BOOST_FOREACH(PackageRef p, m_packages) {
304 if (p->isInstalled()) {
311 void Catalog::refresh()
313 if (m_refreshRequest.valid()) {
314 // refresh in progress
318 Downloader* dl = new Downloader(this, url());
319 m_refreshRequest = dl;
320 // will update status to IN_PROGRESS
321 m_root->makeHTTPRequest(dl);
326 FindById(const std::string &id) : m_id(id) {}
328 bool operator()(const PackageRef& ref) const
330 return ref->id() == m_id;
336 void Catalog::parseProps(const SGPropertyNode* aProps)
338 // copy everything except package children?
339 m_props = new SGPropertyNode;
341 m_variantDict.clear(); // will rebuild during parse
342 std::set<PackageRef> orphans;
343 orphans.insert(m_packages.begin(), m_packages.end());
345 int nChildren = aProps->nChildren();
346 for (int i = 0; i < nChildren; i++) {
347 const SGPropertyNode* pkgProps = aProps->getChild(i);
348 if (strcmp(pkgProps->getName(), "package") == 0) {
349 // can't use getPackageById here becuase the variant dict isn't
350 // built yet. Instead we need to look at m_packages directly.
352 PackageList::iterator pit = std::find_if(m_packages.begin(), m_packages.end(),
353 FindById(pkgProps->getStringValue("id")));
355 if (pit != m_packages.end()) {
358 p->updateFromProps(pkgProps);
359 orphans.erase(p); // not an orphan
362 p = new Package(pkgProps, this);
363 m_packages.push_back(p);
366 string_list vars(p->variants());
367 for (string_list::iterator it = vars.begin(); it != vars.end(); ++it) {
368 m_variantDict[*it] = p.ptr();
371 SGPropertyNode* c = m_props->getChild(pkgProps->getName(), pkgProps->getIndex(), true);
372 copyProperties(pkgProps, c);
374 } // of children iteration
376 if (!orphans.empty()) {
377 SG_LOG(SG_GENERAL, SG_WARN, "have orphan packages: will become inaccesible");
378 std::set<PackageRef>::iterator it;
379 for (it = orphans.begin(); it != orphans.end(); ++it) {
380 SG_LOG(SG_GENERAL, SG_WARN, "\torphan package:" << (*it)->qualifiedId());
381 PackageList::iterator pit = std::find(m_packages.begin(), m_packages.end(), *it);
382 assert(pit != m_packages.end());
383 m_packages.erase(pit);
387 if (!m_url.empty()) {
388 if (m_url != m_props->getStringValue("url")) {
389 // this effectively allows packages to migrate to new locations,
390 // although if we're going to rely on that feature we should
391 // maybe formalise it!
392 SG_LOG(SG_GENERAL, SG_WARN, "package downloaded from:" << m_url
393 << " is now at: " << m_props->getStringValue("url"));
397 m_url = m_props->getStringValue("url");
399 if (m_installRoot.isNull()) {
400 m_installRoot = m_root->path();
401 m_installRoot.append(id());
403 Dir d(m_installRoot);
408 PackageRef Catalog::getPackageById(const std::string& aId) const
410 // search the variant dict here, so looking up aircraft variants
411 // works as expected.
412 PackageWeakMap::const_iterator it = m_variantDict.find(aId);
413 if (it == m_variantDict.end())
419 PackageRef Catalog::getPackageByPath(const std::string& aPath) const
421 PackageList::const_iterator it;
422 for (it = m_packages.begin(); it != m_packages.end(); ++it) {
423 if ((*it)->dirName() == aPath) {
431 std::string Catalog::id() const
433 return m_props->getStringValue("id");
436 std::string Catalog::url() const
441 std::string Catalog::name() const
443 return getLocalisedString(m_props, "name");
446 std::string Catalog::description() const
448 return getLocalisedString(m_props, "description");
451 SGPropertyNode* Catalog::properties() const
453 return m_props.ptr();
456 void Catalog::parseTimestamp()
458 SGPath timestampFile = m_installRoot;
459 timestampFile.append(".timestamp");
460 std::ifstream f(timestampFile.c_str(), std::ios::in);
461 f >> m_retrievedTime;
464 void Catalog::writeTimestamp()
466 SGPath timestampFile = m_installRoot;
467 timestampFile.append(".timestamp");
468 std::ofstream f(timestampFile.c_str(), std::ios::out | std::ios::trunc);
469 f << m_retrievedTime << std::endl;
472 unsigned int Catalog::ageInSeconds() const
476 int diff = ::difftime(now, m_retrievedTime);
477 return (diff < 0) ? 0 : diff;
480 bool Catalog::needsRefresh() const
482 // always refresh in these cases
483 if ((m_status == Delegate::FAIL_VERSION) || (m_status == Delegate::FAIL_DOWNLOAD)) {
487 unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds());
488 return (ageInSeconds() > maxAge);
491 std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const
494 return std::string();
497 if (aRoot->hasChild(m_root->getLocale())) {
498 const SGPropertyNode* localeRoot = aRoot->getChild(m_root->getLocale().c_str());
499 if (localeRoot->hasChild(aName)) {
500 return localeRoot->getStringValue(aName);
504 return aRoot->getStringValue(aName);
507 void Catalog::refreshComplete(Delegate::StatusCode aReason)
509 changeStatus(aReason);
510 m_refreshRequest.reset();
513 void Catalog::changeStatus(Delegate::StatusCode newStatus)
515 if (m_status == newStatus) {
519 m_status = newStatus;
520 m_root->catalogRefreshStatus(this, newStatus);
521 m_statusCallbacks(this);
524 void Catalog::addStatusCallback(const Callback& cb)
526 m_statusCallbacks.push_back(cb);
529 Delegate::StatusCode Catalog::status() const
534 } // of namespace pkg
536 } // of namespace simgear