]> git.mxchange.org Git - simgear.git/blob - simgear/package/Catalog.cxx
Package support progress
[simgear.git] / simgear / package / Catalog.cxx
1 // Copyright (C) 2013  James Turner - zakalawe@mac.com
2 //
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.
7 //
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.
12 //
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.
16 //
17
18 #include <simgear/package/Catalog.hxx>
19
20 #include <boost/foreach.hpp>
21 #include <algorithm>
22 #include <fstream>
23 #include <cstring>
24
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
35 namespace simgear {
36
37 namespace pkg {
38
39 bool checkVersion(const std::string& aVersion, SGPropertyNode_ptr props)
40 {
41     BOOST_FOREACH(SGPropertyNode* v, props->getChildren("version")) {
42         std::string s(v->getStringValue());
43         if (s== aVersion) {
44             return true;
45         }
46
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)) {
52                 return true;
53             }
54         }
55     }
56     return false;
57 }
58
59 std::string redirectUrlForVersion(const std::string& aVersion, SGPropertyNode_ptr props)
60 {
61     BOOST_FOREACH(SGPropertyNode* v, props->getChildren("alternate-version")) {
62         if (v->getStringValue("version") == aVersion) {
63             return v->getStringValue("url");
64         }
65     }
66     
67     return std::string();
68 }
69
70 //////////////////////////////////////////////////////////////////////////////
71
72 class Catalog::Downloader : public HTTP::Request
73 {
74 public:
75     Downloader(CatalogRef aOwner, const std::string& aUrl) :
76         HTTP::Request(aUrl),
77         m_owner(aOwner)
78     {
79         // refreshing
80         m_owner->changeStatus(Delegate::STATUS_IN_PROGRESS);
81         SG_LOG(SG_GENERAL, SG_WARN, "downloading " << aUrl);
82     }
83
84 protected:
85     virtual void gotBodyData(const char* s, int n)
86     {
87         m_buffer += std::string(s, n);
88     }
89
90     virtual void onDone()
91     {
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;
98             }
99             m_owner->refreshComplete(code);
100             return;
101         }
102
103         SGPropertyNode* props = new SGPropertyNode;
104
105         try {
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);
111             return;
112         }
113
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);
118             return;
119         }
120
121
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);
126
127             // check for a version redirect entry
128             std::string url = redirectUrlForVersion(ver, props);
129             if (!url.empty()) {
130                 SG_LOG(SG_GENERAL, SG_WARN, "redirecting from " << m_owner->url() <<
131                        " to \n\t" << url);
132
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);
137             } else {
138                 m_owner->refreshComplete(Delegate::FAIL_VERSION);
139             }
140
141             return;
142         } // of version check failed
143
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");
147
148         std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
149         f.write(m_buffer.data(), m_buffer.size());
150         f.close();
151
152         time(&m_owner->m_retrievedTime);
153         m_owner->writeTimestamp();
154         m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
155     }
156
157 private:
158
159     CatalogRef m_owner;
160     std::string m_buffer;
161 };
162
163 //////////////////////////////////////////////////////////////////////////////
164
165 Catalog::Catalog(Root *aRoot) :
166     m_root(aRoot),
167     m_status(Delegate::FAIL_UNKNOWN),
168     m_retrievedTime(0)
169 {
170 }
171
172 Catalog::~Catalog()
173 {
174 }
175
176 CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
177 {
178     CatalogRef c = new Catalog(aRoot);
179     c->m_url = aUrl;
180     Downloader* dl = new Downloader(c, aUrl);
181     aRoot->makeHTTPRequest(dl);
182
183     return c;
184 }
185
186 CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
187 {
188     SGPath xml = aPath;
189     xml.append("catalog.xml");
190     if (!xml.exists()) {
191         return NULL;
192     }
193
194     SGPropertyNode_ptr props;
195     try {
196         props = new SGPropertyNode;
197         readProperties(xml.str(), props);
198     } catch (sg_exception& e) {
199         return NULL;
200     }
201
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;
209             return c;
210         } else {
211             SG_LOG(SG_GENERAL, SG_WARN, "skipping catalog at " << aPath << ", version mismatch:\n\t"
212                << props->getStringValue("version") << " vs required " << aRoot->catalogVersion());
213             return NULL;
214         }
215
216     } else {
217         SG_LOG(SG_GENERAL, SG_INFO, "creating catalog from:" << aPath);
218     }
219
220     CatalogRef c = new Catalog(aRoot);
221     c->m_installRoot = aPath;
222     c->parseProps(props); // will set status
223     c->parseTimestamp();
224
225     return c;
226 }
227
228 bool Catalog::uninstall()
229 {
230     bool ok;
231     bool atLeastOneFailure = false;
232     
233     BOOST_FOREACH(PackageRef p, installedPackages()) {
234         ok = p->existingInstall()->uninstall();
235         if (!ok) {
236             SG_LOG(SG_GENERAL, SG_WARN, "uninstall of package " <<
237                 p->id() << " failed");
238             // continue trying other packages, bailing out here
239             // gains us nothing
240             atLeastOneFailure = true;
241         }
242     }
243
244     Dir d(m_installRoot);
245     ok = d.remove(true /* recursive */);
246     if (!ok) {
247         atLeastOneFailure = true;
248     }
249     
250     changeStatus(atLeastOneFailure ? Delegate::FAIL_FILESYSTEM
251                                    : Delegate::STATUS_SUCCESS);
252     return ok;
253 }
254
255 PackageList const&
256 Catalog::packages() const
257 {
258   return m_packages;
259 }
260
261 PackageList
262 Catalog::packagesMatching(const SGPropertyNode* aFilter) const
263 {
264     PackageList r;
265     BOOST_FOREACH(PackageRef p, m_packages) {
266         if (p->matches(aFilter)) {
267             r.push_back(p);
268         }
269     }
270     return r;
271 }
272
273 PackageList
274 Catalog::packagesNeedingUpdate() const
275 {
276     PackageList r;
277     BOOST_FOREACH(PackageRef p, m_packages) {
278         if (!p->isInstalled()) {
279             continue;
280         }
281
282         if (p->install()->hasUpdate()) {
283             r.push_back(p);
284         }
285     }
286     return r;
287 }
288
289 PackageList
290 Catalog::installedPackages() const
291 {
292   PackageList r;
293   BOOST_FOREACH(PackageRef p, m_packages) {
294     if (p->isInstalled()) {
295       r.push_back(p);
296     }
297   }
298   return r;
299 }
300
301 void Catalog::refresh()
302 {
303     Downloader* dl = new Downloader(this, url());
304     // will update status to IN_PROGRESS
305     m_root->makeHTTPRequest(dl);
306 }
307
308 struct FindById
309 {
310     FindById(const std::string &id) : m_id(id) {}
311     
312     bool operator()(const PackageRef& ref) const
313     {
314         return ref->id() == m_id;
315     }
316     
317     std::string m_id;
318 };
319     
320 void Catalog::parseProps(const SGPropertyNode* aProps)
321 {
322     // copy everything except package children?
323     m_props = new SGPropertyNode;
324
325     m_variantDict.clear(); // will rebuild during parse
326     std::set<PackageRef> orphans;
327     orphans.insert(m_packages.begin(), m_packages.end());
328
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.
335             
336             PackageList::iterator pit = std::find_if(m_packages.begin(), m_packages.end(),
337                                                   FindById(pkgProps->getStringValue("id")));
338             PackageRef p;
339             if (pit != m_packages.end()) {
340                 p = *pit;
341                 // existing package
342                 p->updateFromProps(pkgProps);
343                 orphans.erase(p); // not an orphan
344             } else {
345                 // new package
346                 p = new Package(pkgProps, this);
347                 m_packages.push_back(p);
348             }
349
350             string_list vars(p->variants());
351             for (string_list::iterator it = vars.begin(); it != vars.end(); ++it) {
352                 m_variantDict[*it] = p.ptr();
353             }
354         } else {
355             SGPropertyNode* c = m_props->getChild(pkgProps->getName(), pkgProps->getIndex(), true);
356             copyProperties(pkgProps, c);
357         }
358     } // of children iteration
359
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);
368         }
369     }
370
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"));
378         }
379     }
380
381     m_url = m_props->getStringValue("url");
382
383     if (m_installRoot.isNull()) {
384         m_installRoot = m_root->path();
385         m_installRoot.append(id());
386
387         Dir d(m_installRoot);
388         d.create(0755);
389     }
390     
391     // parsed XML ok, mark status as valid
392     changeStatus(Delegate::STATUS_SUCCESS);
393 }
394
395 PackageRef Catalog::getPackageById(const std::string& aId) const
396 {
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())
401         return PackageRef();
402
403     return it->second;
404 }
405
406 PackageRef Catalog::getPackageByPath(const std::string& aPath) const
407 {
408     PackageList::const_iterator it;
409     for (it = m_packages.begin(); it != m_packages.end(); ++it) {
410         if ((*it)->dirName() == aPath) {
411             return *it;
412         }
413     }
414
415     return PackageRef();
416 }
417
418 std::string Catalog::id() const
419 {
420     return m_props->getStringValue("id");
421 }
422
423 std::string Catalog::url() const
424 {
425     return m_url;
426 }
427
428 std::string Catalog::description() const
429 {
430     return getLocalisedString(m_props, "description");
431 }
432
433 SGPropertyNode* Catalog::properties() const
434 {
435     return m_props.ptr();
436 }
437
438 void Catalog::parseTimestamp()
439 {
440     SGPath timestampFile = m_installRoot;
441     timestampFile.append(".timestamp");
442     std::ifstream f(timestampFile.c_str(), std::ios::in);
443     f >> m_retrievedTime;
444 }
445
446 void Catalog::writeTimestamp()
447 {
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;
452 }
453
454 unsigned int Catalog::ageInSeconds() const
455 {
456     time_t now;
457     time(&now);
458     int diff = ::difftime(now, m_retrievedTime);
459     return (diff < 0) ? 0 : diff;
460 }
461
462 bool Catalog::needsRefresh() const
463 {
464     unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds());
465     return (ageInSeconds() > maxAge);
466 }
467
468 std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const
469 {
470     if (!aRoot) {
471         return std::string();
472     }
473     
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);
478         }
479     }
480
481     return aRoot->getStringValue(aName);
482 }
483
484 void Catalog::refreshComplete(Delegate::StatusCode aReason)
485 {
486     m_root->catalogRefreshStatus(this, aReason);
487     changeStatus(aReason);
488 }
489
490 void Catalog::changeStatus(Delegate::StatusCode newStatus)
491 {
492     if (m_status == newStatus) {
493         return;
494     }
495     
496     m_status = newStatus;
497     m_root->catalogRefreshStatus(this, newStatus);
498     m_statusCallbacks(this);
499 }
500
501 void Catalog::addStatusCallback(const Callback& cb)
502 {
503     m_statusCallbacks.push_back(cb);
504 }
505
506 Delegate::StatusCode Catalog::status() const
507 {
508     return m_status;
509 }
510
511 } // of namespace pkg
512
513 } // of namespace simgear