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 CatalogList static_catalogs;
41 //////////////////////////////////////////////////////////////////////////////
43 class Catalog::Downloader : public HTTP::Request
46 Downloader(CatalogRef aOwner, const std::string& aUrl) :
53 virtual void gotBodyData(const char* s, int n)
55 m_buffer += std::string(s, n);
60 if (responseCode() != 200) {
61 SG_LOG(SG_GENERAL, SG_ALERT, "catalog download failure:" << m_owner->url());
62 m_owner->refreshComplete(Delegate::FAIL_DOWNLOAD);
66 SGPropertyNode* props = new SGPropertyNode;
69 readProperties(m_buffer.data(), m_buffer.size(), props);
70 m_owner->parseProps(props);
71 } catch (sg_exception& e) {
72 SG_LOG(SG_GENERAL, SG_ALERT, "catalog parse failure:" << m_owner->url());
73 m_owner->refreshComplete(Delegate::FAIL_EXTRACT);
77 std::string ver(m_owner->root()->catalogVersion());
78 if (!checkVersion(ver, props)) {
79 SG_LOG(SG_GENERAL, SG_WARN, "downloaded catalog " << m_owner->url() << ", version mismatch:\n\t"
80 << props->getStringValue("version") << " vs required " << ver);
81 m_owner->refreshComplete(Delegate::FAIL_VERSION);
85 // cache the catalog data, now we have a valid install root
86 Dir d(m_owner->installRoot());
87 SGPath p = d.file("catalog.xml");
89 std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
90 f.write(m_buffer.data(), m_buffer.size());
93 time(&m_owner->m_retrievedTime);
94 m_owner->writeTimestamp();
95 m_owner->refreshComplete(Delegate::FAIL_SUCCESS);
99 bool checkVersion(const std::string& aVersion, SGPropertyNode* aProps)
101 BOOST_FOREACH(SGPropertyNode* v, aProps->getChildren("version")) {
102 if (v->getStringValue() == aVersion) {
110 std::string m_buffer;
113 //////////////////////////////////////////////////////////////////////////////
115 CatalogList Catalog::allCatalogs()
117 return static_catalogs;
120 Catalog::Catalog(Root *aRoot) :
124 static_catalogs.push_back(this);
129 CatalogList::iterator it = std::find(static_catalogs.begin(), static_catalogs.end(), this);
130 static_catalogs.erase(it);
133 CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
135 CatalogRef c = new Catalog(aRoot);
137 Downloader* dl = new Downloader(c, aUrl);
138 aRoot->makeHTTPRequest(dl);
143 CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
146 xml.append("catalog.xml");
151 SGPropertyNode_ptr props;
153 props = new SGPropertyNode;
154 readProperties(xml.str(), props);
155 } catch (sg_exception& e) {
159 if (props->getStringValue("version") != aRoot->catalogVersion()) {
160 SG_LOG(SG_GENERAL, SG_WARN, "skipping catalog at " << aPath << ", version mismatch:\n\t"
161 << props->getStringValue("version") << " vs required " << aRoot->catalogVersion());
165 CatalogRef c = new Catalog(aRoot);
166 c->m_installRoot = aPath;
167 c->parseProps(props);
174 Catalog::packages() const
180 Catalog::packagesMatching(const SGPropertyNode* aFilter) const
183 BOOST_FOREACH(PackageRef p, m_packages) {
184 if (p->matches(aFilter)) {
192 Catalog::packagesNeedingUpdate() const
195 BOOST_FOREACH(PackageRef p, m_packages) {
196 if (!p->isInstalled()) {
200 if (p->install()->hasUpdate()) {
208 Catalog::installedPackages() const
211 BOOST_FOREACH(PackageRef p, m_packages) {
212 if (p->isInstalled()) {
219 InstallRef Catalog::installForPackage(PackageRef pkg) const
221 PackageInstallDict::const_iterator it = m_installed.find(pkg);
222 if (it == m_installed.end()) {
223 // check if it exists on disk, create
225 SGPath p(pkg->pathOnDisk());
227 return Install::createFromPath(p, CatalogRef(const_cast<Catalog*>(this)));
236 void Catalog::refresh()
238 Downloader* dl = new Downloader(this, url());
239 m_root->makeHTTPRequest(dl);
240 m_root->catalogRefreshBegin(this);
243 void Catalog::parseProps(const SGPropertyNode* aProps)
245 // copy everything except package children?
246 m_props = new SGPropertyNode;
248 m_variantDict.clear(); // will rebuild during parse
249 std::set<PackageRef> orphans;
250 orphans.insert(m_packages.begin(), m_packages.end());
252 int nChildren = aProps->nChildren();
253 for (int i = 0; i < nChildren; i++) {
254 const SGPropertyNode* pkgProps = aProps->getChild(i);
255 if (strcmp(pkgProps->getName(), "package") == 0) {
256 PackageRef p = getPackageById(pkgProps->getStringValue("id"));
259 p->updateFromProps(pkgProps);
260 orphans.erase(p); // not an orphan
263 p = new Package(pkgProps, this);
264 m_packages.push_back(p);
267 string_list vars(p->variants());
268 for (string_list::iterator it = vars.begin(); it != vars.end(); ++it) {
269 m_variantDict[*it] = p.ptr();
272 SGPropertyNode* c = m_props->getChild(pkgProps->getName(), pkgProps->getIndex(), true);
273 copyProperties(pkgProps, c);
275 } // of children iteration
277 if (!orphans.empty()) {
278 SG_LOG(SG_GENERAL, SG_WARN, "have orphan packages: will become inaccesible");
279 std::set<PackageRef>::iterator it;
280 for (it = orphans.begin(); it != orphans.end(); ++it) {
281 SG_LOG(SG_GENERAL, SG_WARN, "\torphan package:" << (*it)->qualifiedId());
282 PackageList::iterator pit = std::find(m_packages.begin(), m_packages.end(), *it);
283 assert(pit != m_packages.end());
284 m_packages.erase(pit);
288 if (!m_url.empty()) {
289 if (m_url != m_props->getStringValue("url")) {
290 // this effectively allows packages to migrate to new locations,
291 // although if we're going to rely on that feature we should
292 // maybe formalise it!
293 SG_LOG(SG_GENERAL, SG_WARN, "package downloaded from:" << m_url
294 << " is now at: " << m_props->getStringValue("url"));
298 m_url = m_props->getStringValue("url");
300 if (m_installRoot.isNull()) {
301 m_installRoot = m_root->path();
302 m_installRoot.append(id());
304 Dir d(m_installRoot);
309 PackageRef Catalog::getPackageById(const std::string& aId) const
311 // search the variant dict here, so looking up aircraft variants
312 // works as expected.
313 PackageWeakMap::const_iterator it = m_variantDict.find(aId);
314 if (it == m_variantDict.end())
320 std::string Catalog::id() const
322 return m_props->getStringValue("id");
325 std::string Catalog::url() const
330 std::string Catalog::description() const
332 return getLocalisedString(m_props, "description");
335 SGPropertyNode* Catalog::properties() const
337 return m_props.ptr();
340 void Catalog::parseTimestamp()
342 SGPath timestampFile = m_installRoot;
343 timestampFile.append(".timestamp");
344 std::ifstream f(timestampFile.c_str(), std::ios::in);
345 f >> m_retrievedTime;
348 void Catalog::writeTimestamp()
350 SGPath timestampFile = m_installRoot;
351 timestampFile.append(".timestamp");
352 std::ofstream f(timestampFile.c_str(), std::ios::out | std::ios::trunc);
353 f << m_retrievedTime << std::endl;
356 unsigned int Catalog::ageInSeconds() const
360 int diff = ::difftime(now, m_retrievedTime);
361 return (diff < 0) ? 0 : diff;
364 bool Catalog::needsRefresh() const
366 unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds());
367 return (ageInSeconds() > maxAge);
370 std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const
372 if (aRoot->hasChild(m_root->getLocale())) {
373 const SGPropertyNode* localeRoot = aRoot->getChild(m_root->getLocale().c_str());
374 if (localeRoot->hasChild(aName)) {
375 return localeRoot->getStringValue(aName);
379 return aRoot->getStringValue(aName);
382 void Catalog::refreshComplete(Delegate::FailureCode aReason)
384 m_root->catalogRefreshComplete(this, aReason);
387 void Catalog::registerInstall(Install* ins)
389 if (!ins || ins->package()->catalog() != this) {
393 m_installed[ins->package()] = ins;
396 void Catalog::unregisterInstall(Install* ins)
398 if (!ins || ins->package()->catalog() != this) {
402 m_installed.erase(ins->package());
405 } // of namespace pkg
407 } // of namespace simgear