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);
84 virtual void gotBodyData(const char* s, int n)
86 m_buffer += std::string(s, n);
91 if (responseCode() != 200) {
92 Delegate::StatusCode code = Delegate::FAIL_DOWNLOAD;
93 SG_LOG(SG_GENERAL, SG_ALERT, "catalog download failure:" << m_owner->url()
94 << "\n\t" << responseCode());
95 if (responseCode() == 404) {
96 code = Delegate::FAIL_NOT_FOUND;
98 m_owner->refreshComplete(code);
102 SGPropertyNode* props = new SGPropertyNode;
105 readProperties(m_buffer.data(), m_buffer.size(), props);
106 m_owner->parseProps(props);
107 } catch (sg_exception& e) {
108 SG_LOG(SG_GENERAL, SG_ALERT, "catalog parse failure:" << m_owner->url());
109 m_owner->refreshComplete(Delegate::FAIL_EXTRACT);
113 if (m_owner->root()->catalogVersion() != props->getIntValue("catalog-version")) {
114 SG_LOG(SG_GENERAL, SG_WARN, "catalog:" << m_owner->url() << " is not version "
115 << m_owner->root()->catalogVersion());
116 m_owner->refreshComplete(Delegate::FAIL_VERSION);
121 std::string ver(m_owner->root()->applicationVersion());
122 if (!checkVersion(ver, props)) {
123 SG_LOG(SG_GENERAL, SG_WARN, "downloaded catalog " << m_owner->url() << ", version mismatch:\n\t"
124 << props->getStringValue("version") << " vs required " << ver);
126 // check for a version redirect entry
127 std::string url = redirectUrlForVersion(ver, props);
129 SG_LOG(SG_GENERAL, SG_WARN, "redirecting from " << m_owner->url() <<
132 // update the URL and kick off a new request
133 m_owner->m_url = url;
134 Downloader* dl = new Downloader(m_owner, url);
135 m_owner->root()->makeHTTPRequest(dl);
137 m_owner->refreshComplete(Delegate::FAIL_VERSION);
141 } // of version check failed
143 // cache the catalog data, now we have a valid install root
144 Dir d(m_owner->installRoot());
145 SGPath p = d.file("catalog.xml");
147 std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
148 f.write(m_buffer.data(), m_buffer.size());
151 time(&m_owner->m_retrievedTime);
152 m_owner->writeTimestamp();
153 m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
159 std::string m_buffer;
162 //////////////////////////////////////////////////////////////////////////////
164 Catalog::Catalog(Root *aRoot) :
166 m_status(Delegate::FAIL_UNKNOWN),
175 CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
177 CatalogRef c = new Catalog(aRoot);
183 CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
186 xml.append("catalog.xml");
191 SGPropertyNode_ptr props;
193 props = new SGPropertyNode;
194 readProperties(xml.str(), props);
195 } catch (sg_exception& e) {
199 if (!checkVersion(aRoot->applicationVersion(), props)) {
200 std::string redirect = redirectUrlForVersion(aRoot->applicationVersion(), props);
201 if (!redirect.empty()) {
202 SG_LOG(SG_GENERAL, SG_WARN, "catalog at " << aPath << ", version mismatch:\n\t"
203 << "redirecting to alternate URL:" << redirect);
204 CatalogRef c = Catalog::createFromUrl(aRoot, redirect);
205 c->m_installRoot = aPath;
208 SG_LOG(SG_GENERAL, SG_WARN, "skipping catalog at " << aPath << ", version mismatch:\n\t"
209 << props->getStringValue("version") << " vs required " << aRoot->catalogVersion());
214 SG_LOG(SG_GENERAL, SG_INFO, "creating catalog from:" << aPath);
217 CatalogRef c = new Catalog(aRoot);
218 c->m_installRoot = aPath;
219 c->parseProps(props);
222 // parsed XML ok, mark status as valid
223 c->changeStatus(Delegate::STATUS_SUCCESS);
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 if (m_refreshRequest.valid()) {
304 // refresh in progress
308 Downloader* dl = new Downloader(this, url());
309 m_refreshRequest = dl;
310 // will update status to IN_PROGRESS
311 m_root->makeHTTPRequest(dl);
316 FindById(const std::string &id) : m_id(id) {}
318 bool operator()(const PackageRef& ref) const
320 return ref->id() == m_id;
326 void Catalog::parseProps(const SGPropertyNode* aProps)
328 // copy everything except package children?
329 m_props = new SGPropertyNode;
331 m_variantDict.clear(); // will rebuild during parse
332 std::set<PackageRef> orphans;
333 orphans.insert(m_packages.begin(), m_packages.end());
335 int nChildren = aProps->nChildren();
336 for (int i = 0; i < nChildren; i++) {
337 const SGPropertyNode* pkgProps = aProps->getChild(i);
338 if (strcmp(pkgProps->getName(), "package") == 0) {
339 // can't use getPackageById here becuase the variant dict isn't
340 // built yet. Instead we need to look at m_packages directly.
342 PackageList::iterator pit = std::find_if(m_packages.begin(), m_packages.end(),
343 FindById(pkgProps->getStringValue("id")));
345 if (pit != m_packages.end()) {
348 p->updateFromProps(pkgProps);
349 orphans.erase(p); // not an orphan
352 p = new Package(pkgProps, this);
353 m_packages.push_back(p);
356 string_list vars(p->variants());
357 for (string_list::iterator it = vars.begin(); it != vars.end(); ++it) {
358 m_variantDict[*it] = p.ptr();
361 SGPropertyNode* c = m_props->getChild(pkgProps->getName(), pkgProps->getIndex(), true);
362 copyProperties(pkgProps, c);
364 } // of children iteration
366 if (!orphans.empty()) {
367 SG_LOG(SG_GENERAL, SG_WARN, "have orphan packages: will become inaccesible");
368 std::set<PackageRef>::iterator it;
369 for (it = orphans.begin(); it != orphans.end(); ++it) {
370 SG_LOG(SG_GENERAL, SG_WARN, "\torphan package:" << (*it)->qualifiedId());
371 PackageList::iterator pit = std::find(m_packages.begin(), m_packages.end(), *it);
372 assert(pit != m_packages.end());
373 m_packages.erase(pit);
377 if (!m_url.empty()) {
378 if (m_url != m_props->getStringValue("url")) {
379 // this effectively allows packages to migrate to new locations,
380 // although if we're going to rely on that feature we should
381 // maybe formalise it!
382 SG_LOG(SG_GENERAL, SG_WARN, "package downloaded from:" << m_url
383 << " is now at: " << m_props->getStringValue("url"));
387 m_url = m_props->getStringValue("url");
389 if (m_installRoot.isNull()) {
390 m_installRoot = m_root->path();
391 m_installRoot.append(id());
393 Dir d(m_installRoot);
398 PackageRef Catalog::getPackageById(const std::string& aId) const
400 // search the variant dict here, so looking up aircraft variants
401 // works as expected.
402 PackageWeakMap::const_iterator it = m_variantDict.find(aId);
403 if (it == m_variantDict.end())
409 PackageRef Catalog::getPackageByPath(const std::string& aPath) const
411 PackageList::const_iterator it;
412 for (it = m_packages.begin(); it != m_packages.end(); ++it) {
413 if ((*it)->dirName() == aPath) {
421 std::string Catalog::id() const
423 return m_props->getStringValue("id");
426 std::string Catalog::url() const
431 std::string Catalog::description() const
433 return getLocalisedString(m_props, "description");
436 SGPropertyNode* Catalog::properties() const
438 return m_props.ptr();
441 void Catalog::parseTimestamp()
443 SGPath timestampFile = m_installRoot;
444 timestampFile.append(".timestamp");
445 std::ifstream f(timestampFile.c_str(), std::ios::in);
446 f >> m_retrievedTime;
449 void Catalog::writeTimestamp()
451 SGPath timestampFile = m_installRoot;
452 timestampFile.append(".timestamp");
453 std::ofstream f(timestampFile.c_str(), std::ios::out | std::ios::trunc);
454 f << m_retrievedTime << std::endl;
457 unsigned int Catalog::ageInSeconds() const
461 int diff = ::difftime(now, m_retrievedTime);
462 return (diff < 0) ? 0 : diff;
465 bool Catalog::needsRefresh() const
467 unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds());
468 return (ageInSeconds() > maxAge);
471 std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const
474 return std::string();
477 if (aRoot->hasChild(m_root->getLocale())) {
478 const SGPropertyNode* localeRoot = aRoot->getChild(m_root->getLocale().c_str());
479 if (localeRoot->hasChild(aName)) {
480 return localeRoot->getStringValue(aName);
484 return aRoot->getStringValue(aName);
487 void Catalog::refreshComplete(Delegate::StatusCode aReason)
489 changeStatus(aReason);
490 m_refreshRequest.reset();
493 void Catalog::changeStatus(Delegate::StatusCode newStatus)
495 if (m_status == newStatus) {
499 m_status = newStatus;
500 m_root->catalogRefreshStatus(this, newStatus);
501 m_statusCallbacks(this);
504 void Catalog::addStatusCallback(const Callback& cb)
506 m_statusCallbacks.push_back(cb);
509 Delegate::StatusCode Catalog::status() const
514 } // of namespace pkg
516 } // of namespace simgear