]> git.mxchange.org Git - simgear.git/blob - simgear/package/Root.cxx
Guard against disabling a not-yet-active catalog.
[simgear.git] / simgear / package / Root.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/Root.hxx>
19
20 #include <boost/foreach.hpp>
21 #include <cstring>
22 #include <map>
23 #include <deque>
24 #include <set>
25
26 #include <simgear/debug/logstream.hxx>
27 #include <simgear/props/props_io.hxx>
28 #include <simgear/io/HTTPRequest.hxx>
29 #include <simgear/io/HTTPClient.hxx>
30 #include <simgear/misc/sg_dir.hxx>
31 #include <simgear/structure/exception.hxx>
32 #include <simgear/package/Package.hxx>
33 #include <simgear/package/Install.hxx>
34 #include <simgear/package/Catalog.hxx>
35
36 namespace simgear {
37
38 namespace pkg {
39
40 typedef std::map<std::string, CatalogRef> CatalogDict;
41 typedef std::vector<Delegate*> DelegateVec;
42 typedef std::map<std::string, std::string> MemThumbnailCache;
43 typedef std::deque<std::string> StringDeque;
44
45 class Root::ThumbnailDownloader : public HTTP::Request
46 {
47 public:
48     ThumbnailDownloader(Root::RootPrivate* aOwner, const std::string& aUrl) :
49     HTTP::Request(aUrl),
50     m_owner(aOwner)
51     {
52     }
53
54 protected:
55     virtual void gotBodyData(const char* s, int n)
56     {
57         m_buffer += std::string(s, n);
58     }
59
60     virtual void onDone();
61
62 private:
63     Root::RootPrivate* m_owner;
64     std::string m_buffer;
65 };
66
67 class Root::RootPrivate
68 {
69 public:
70     RootPrivate() :
71         http(NULL),
72         maxAgeSeconds(60 * 60 * 24)
73     {
74     }
75
76     void fireStartInstall(InstallRef install)
77     {
78         DelegateVec::const_iterator it;
79         for (it = delegates.begin(); it != delegates.end(); ++it) {
80             (*it)->startInstall(install);
81         }
82     }
83
84     void fireInstallProgress(InstallRef install,
85                              unsigned int aBytes, unsigned int aTotal)
86     {
87         DelegateVec::const_iterator it;
88         for (it = delegates.begin(); it != delegates.end(); ++it) {
89             (*it)->installProgress(install, aBytes, aTotal);
90         }
91     }
92
93     void fireFinishInstall(InstallRef install, Delegate::StatusCode status)
94     {
95         DelegateVec::const_iterator it;
96         for (it = delegates.begin(); it != delegates.end(); ++it) {
97             (*it)->finishInstall(install, status);
98         }
99     }
100
101     void fireRefreshStatus(CatalogRef catalog, Delegate::StatusCode status)
102     {
103         DelegateVec::const_iterator it;
104         for (it = delegates.begin(); it != delegates.end(); ++it) {
105             (*it)->catalogRefreshed(catalog, status);
106         }
107     }
108
109     void firePackagesChanged()
110     {
111       DelegateVec::const_iterator it;
112       for (it = delegates.begin(); it != delegates.end(); ++it) {
113           (*it)->availablePackagesChanged();
114       }
115     }
116
117     void thumbnailDownloadComplete(HTTP::Request_ptr request,
118                                    Delegate::StatusCode status, const std::string& bytes)
119     {
120         std::string u(request->url());
121         if (status == Delegate::STATUS_SUCCESS) {
122             thumbnailCache[u] = bytes;
123             fireDataForThumbnail(u, bytes);
124         }
125
126         downloadNextPendingThumbnail();
127     }
128
129     void fireDataForThumbnail(const std::string& aUrl, const std::string& bytes)
130     {
131         DelegateVec::const_iterator it;
132         const uint8_t* data = reinterpret_cast<const uint8_t*>(bytes.data());
133         for (it = delegates.begin(); it != delegates.end(); ++it) {
134             (*it)->dataForThumbnail(aUrl, bytes.size(), data);
135         }
136     }
137
138     void downloadNextPendingThumbnail()
139     {
140         thumbnailDownloadRequest.clear();
141         if (pendingThumbnails.empty()) {
142             return;
143         }
144
145         std::string u = pendingThumbnails.front();
146         pendingThumbnails.pop_front();
147         thumbnailDownloadRequest = new Root::ThumbnailDownloader(this, u);
148
149         if (http) {
150             http->makeRequest(thumbnailDownloadRequest);
151         } else {
152             httpPendingRequests.push_back(thumbnailDownloadRequest);
153         }
154     }
155
156     DelegateVec delegates;
157
158     SGPath path;
159     std::string locale;
160     HTTP::Client* http;
161     CatalogDict catalogs;
162     CatalogList disabledCatalogs;
163     unsigned int maxAgeSeconds;
164     std::string version;
165
166     std::set<CatalogRef> refreshing;
167     typedef std::deque<InstallRef> UpdateDeque;
168     UpdateDeque updateDeque;
169     std::deque<HTTP::Request_ptr> httpPendingRequests;
170
171     HTTP::Request_ptr thumbnailDownloadRequest;
172     StringDeque pendingThumbnails;
173     MemThumbnailCache thumbnailCache;
174
175     typedef std::map<PackageRef, InstallRef> InstallCache;
176     InstallCache m_installs;
177 };
178
179
180 void Root::ThumbnailDownloader::onDone()
181 {
182     if (responseCode() != 200) {
183         SG_LOG(SG_GENERAL, SG_ALERT, "thumbnail download failure:" << url());
184         m_owner->thumbnailDownloadComplete(this, Delegate::FAIL_DOWNLOAD, std::string());
185         return;
186     }
187
188     m_owner->thumbnailDownloadComplete(this, Delegate::STATUS_SUCCESS, m_buffer);
189     //time(&m_owner->m_retrievedTime);
190     //m_owner->writeTimestamp();
191     //m_owner->refreshComplete(Delegate::STATUS_REFRESHED);
192 }
193
194 SGPath Root::path() const
195 {
196     return d->path;
197 }
198
199 void Root::setMaxAgeSeconds(unsigned int seconds)
200 {
201     d->maxAgeSeconds = seconds;
202 }
203
204 unsigned int Root::maxAgeSeconds() const
205 {
206     return d->maxAgeSeconds;
207 }
208
209 void Root::setHTTPClient(HTTP::Client* aHTTP)
210 {
211     d->http = aHTTP;
212     BOOST_FOREACH(HTTP::Request_ptr req, d->httpPendingRequests) {
213         d->http->makeRequest(req);
214     }
215
216     d->httpPendingRequests.clear();
217 }
218
219 void Root::makeHTTPRequest(HTTP::Request *req)
220 {
221     if (d->http) {
222         d->http->makeRequest(req);
223         return;
224     }
225
226     d->httpPendingRequests.push_back(req);
227 }
228
229 Root::Root(const SGPath& aPath, const std::string& aVersion) :
230     d(new RootPrivate)
231 {
232     d->path = aPath;
233     d->version = aVersion;
234     if (getenv("LOCALE")) {
235         d->locale = getenv("LOCALE");
236     }
237
238     Dir dir(aPath);
239     if (!dir.exists()) {
240         dir.create(0755);
241         return;
242     }
243
244     BOOST_FOREACH(SGPath c, dir.children(Dir::TYPE_DIR | Dir::NO_DOT_OR_DOTDOT)) {
245         CatalogRef cat = Catalog::createFromPath(this, c);
246         if (cat) {
247             if (cat->status() == Delegate::STATUS_SUCCESS) {
248                 d->catalogs[cat->id()] = cat;
249             } else {
250                 // catalog has problems, such as needing an update
251                 // keep it out of the main collection for now
252                 d->disabledCatalogs.push_back(cat);
253             }
254         }
255     } // of child directories iteration
256 }
257
258 Root::~Root()
259 {
260
261 }
262
263 int Root::catalogVersion() const
264 {
265     return 4;
266 }
267
268 std::string Root::applicationVersion() const
269 {
270     return d->version;
271 }
272
273 CatalogRef Root::getCatalogById(const std::string& aId) const
274 {
275     CatalogDict::const_iterator it = d->catalogs.find(aId);
276     if (it == d->catalogs.end()) {
277         return NULL;
278     }
279
280     return it->second;
281 }
282
283 PackageRef Root::getPackageById(const std::string& aName) const
284 {
285     size_t lastDot = aName.rfind('.');
286
287     PackageRef pkg = NULL;
288     if (lastDot == std::string::npos) {
289         // naked package ID
290         CatalogDict::const_iterator it = d->catalogs.begin();
291         for (; it != d->catalogs.end(); ++it) {
292             pkg = it->second->getPackageById(aName);
293             if (pkg) {
294                 return pkg;
295             }
296         }
297
298         return NULL;
299     }
300
301     std::string catalogId = aName.substr(0, lastDot);
302     std::string id = aName.substr(lastDot + 1);
303     CatalogRef catalog = getCatalogById(catalogId);
304     if (!catalog) {
305         return NULL;
306     }
307
308     return catalog->getPackageById(id);
309 }
310
311 CatalogList Root::catalogs() const
312 {
313     CatalogList r;
314     CatalogDict::const_iterator it = d->catalogs.begin();
315     for (; it != d->catalogs.end(); ++it) {
316         r.push_back(it->second);
317     }
318
319     return r;
320 }
321
322 PackageList
323 Root::allPackages() const
324 {
325     PackageList r;
326
327     CatalogDict::const_iterator it = d->catalogs.begin();
328     for (; it != d->catalogs.end(); ++it) {
329         const PackageList& r2(it->second->packages());
330         r.insert(r.end(), r2.begin(), r2.end());
331     }
332
333     return r;
334 }
335
336 PackageList
337 Root::packagesMatching(const SGPropertyNode* aFilter) const
338 {
339     PackageList r;
340
341     CatalogDict::const_iterator it = d->catalogs.begin();
342     for (; it != d->catalogs.end(); ++it) {
343         PackageList r2(it->second->packagesMatching(aFilter));
344         r.insert(r.end(), r2.begin(), r2.end());
345     }
346
347     return r;
348 }
349
350 PackageList
351 Root::packagesNeedingUpdate() const
352 {
353     PackageList r;
354
355     CatalogDict::const_iterator it = d->catalogs.begin();
356     for (; it != d->catalogs.end(); ++it) {
357         PackageList r2(it->second->packagesNeedingUpdate());
358         r.insert(r.end(), r2.begin(), r2.end());
359     }
360
361     return r;
362 }
363
364 void Root::refresh(bool aForce)
365 {
366     bool didStartAny = false;
367
368     // copy all candidate ctalogs to a seperate list, since refreshing
369     // can modify both the main collection and/or the disabled list
370     CatalogList toRefresh;
371     CatalogDict::iterator it = d->catalogs.begin();
372     for (; it != d->catalogs.end(); ++it) {
373         toRefresh.push_back(it->second);
374     }
375
376     toRefresh.insert(toRefresh.end(), d->disabledCatalogs.begin(),
377                      d->disabledCatalogs.end());
378
379
380     CatalogList::iterator j = toRefresh.begin();
381     for (; j != toRefresh.end(); ++j) {
382         (*j)->refresh();
383         didStartAny =  true;
384     }
385
386     if (!didStartAny) {
387         // signal refresh complete to the delegate already
388         d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
389     }
390 }
391
392 void Root::addDelegate(simgear::pkg::Delegate *aDelegate)
393 {
394     d->delegates.push_back(aDelegate);
395 }
396
397 void Root::removeDelegate(simgear::pkg::Delegate *aDelegate)
398 {
399     DelegateVec::iterator it = std::find(d->delegates.begin(),
400                                          d->delegates.end(), aDelegate);
401     if (it == d->delegates.end()) {
402         throw sg_exception("unknown delegate in removeDelegate");
403     }
404     d->delegates.erase(it);
405 }
406
407 void Root::setLocale(const std::string& aLocale)
408 {
409     d->locale = aLocale;
410 }
411
412 std::string Root::getLocale() const
413 {
414     return d->locale;
415 }
416
417 void Root::scheduleToUpdate(InstallRef aInstall)
418 {
419     if (!aInstall) {
420         throw sg_exception("missing argument to scheduleToUpdate");
421     }
422
423     PackageList deps = aInstall->package()->dependencies();
424     BOOST_FOREACH(Package* dep, deps) {
425         // will internally schedule for update if required
426         // hence be careful, this method is re-entered in here!
427         dep->install();
428     }
429
430     bool wasEmpty = d->updateDeque.empty();
431     d->updateDeque.push_back(aInstall);
432
433     if (wasEmpty) {
434         aInstall->startUpdate();
435     }
436 }
437
438 bool Root::isInstallQueued(InstallRef aInstall) const
439 {
440     RootPrivate::UpdateDeque::const_iterator it =
441         std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
442     return (it != d->updateDeque.end());
443 }
444
445 void Root::startInstall(InstallRef aInstall)
446 {
447     d->fireStartInstall(aInstall);
448 }
449
450 void Root::installProgress(InstallRef aInstall, unsigned int aBytes, unsigned int aTotal)
451 {
452     d->fireInstallProgress(aInstall, aBytes, aTotal);
453 }
454
455 void Root::startNext(InstallRef aCurrent)
456 {
457     if (d->updateDeque.front() != aCurrent) {
458         SG_LOG(SG_GENERAL, SG_ALERT, "current install of package not head of the deque");
459     } else {
460         d->updateDeque.pop_front();
461     }
462
463     if (!d->updateDeque.empty()) {
464         d->updateDeque.front()->startUpdate();
465     }
466 }
467
468 void Root::finishInstall(InstallRef aInstall, Delegate::StatusCode aReason)
469 {
470     if (aReason != Delegate::STATUS_SUCCESS) {
471         SG_LOG(SG_GENERAL, SG_ALERT, "failed to install package:"
472                << aInstall->package()->id() << ":" << aReason);
473     }
474
475     // order matters here, so a call to 'isQueued' from a finish-install
476     // callback returns false, not true
477     startNext(aInstall);
478     d->fireFinishInstall(aInstall, aReason);
479 }
480
481 void Root::cancelDownload(InstallRef aInstall)
482 {
483     RootPrivate::UpdateDeque::iterator it =
484         std::find(d->updateDeque.begin(), d->updateDeque.end(), aInstall);
485     if (it != d->updateDeque.end()) {
486         bool startNext = (aInstall == d->updateDeque.front());
487         d->updateDeque.erase(it);
488         if (startNext) {
489             if (!d->updateDeque.empty()) {
490                 d->updateDeque.front()->startUpdate();
491             }
492         } // of install was front item
493     } // of found install in queue
494 }
495
496 void Root::catalogRefreshStatus(CatalogRef aCat, Delegate::StatusCode aReason)
497 {
498     CatalogDict::iterator catIt = d->catalogs.find(aCat->id());
499     d->fireRefreshStatus(aCat, aReason);
500
501     if (aReason == Delegate::STATUS_IN_PROGRESS) {
502         d->refreshing.insert(aCat);
503     } else {
504         d->refreshing.erase(aCat);
505     }
506
507     if ((aReason == Delegate::STATUS_REFRESHED) && (catIt == d->catalogs.end())) {
508         assert(!aCat->id().empty());
509         d->catalogs.insert(catIt, CatalogDict::value_type(aCat->id(), aCat));
510
511         // catalog might have been previously disabled, let's remove in that case
512         CatalogList::iterator j = std::find(d->disabledCatalogs.begin(),
513                                             d->disabledCatalogs.end(),
514                                             aCat);
515         if (j != d->disabledCatalogs.end()) {
516             SG_LOG(SG_GENERAL, SG_INFO, "re-enabling disabled catalog:" << aCat->id());
517             d->disabledCatalogs.erase(j);
518         }
519     }
520
521     if ((aReason != Delegate::STATUS_REFRESHED) &&
522         (aReason != Delegate::STATUS_IN_PROGRESS) &&
523         (aReason != Delegate::STATUS_SUCCESS))
524     {
525         // catalog has errors, disable it
526         CatalogList::iterator j = std::find(d->disabledCatalogs.begin(),
527                                             d->disabledCatalogs.end(),
528                                             aCat);
529         if (j == d->disabledCatalogs.end()) {
530             SG_LOG(SG_GENERAL, SG_INFO, "disabling catalog:" << aCat->id());
531             d->disabledCatalogs.push_back(aCat);
532         }
533
534         // and remove it from the active collection
535         if (catIt != d->catalogs.end()) {
536             d->catalogs.erase(catIt);
537         }
538     } // of catalog has errors case
539
540     if (d->refreshing.empty()) {
541         d->fireRefreshStatus(CatalogRef(), Delegate::STATUS_REFRESHED);
542         d->firePackagesChanged();
543     }
544 }
545
546 bool Root::removeCatalogById(const std::string& aId)
547 {
548     CatalogRef cat;
549
550     CatalogDict::iterator catIt = d->catalogs.find(aId);
551     if (catIt == d->catalogs.end()) {
552         // check the disabled list
553         CatalogList::iterator j = d->disabledCatalogs.begin();
554         for (; j != d->disabledCatalogs.end(); ++j) {
555             if ((*j)->id() == aId) {
556                 break;
557             }
558         }
559
560         if (j == d->disabledCatalogs.end()) {
561             SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: no catalog with id:" << aId);
562             return false;
563         }
564
565         cat = *j;
566         d->disabledCatalogs.erase(j);
567     } else {
568         cat = catIt->second;
569         // drop the reference
570         d->catalogs.erase(catIt);
571     }
572
573     bool ok = cat->uninstall();
574     if (!ok) {
575         SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: catalog :" << aId
576             << "failed to uninstall");
577     }
578
579     // notify that a catalog is being removed
580     d->firePackagesChanged();
581
582     return ok;
583 }
584
585 void Root::requestThumbnailData(const std::string& aUrl)
586 {
587     MemThumbnailCache::iterator it = d->thumbnailCache.find(aUrl);
588     if (it == d->thumbnailCache.end()) {
589         // insert into cache to mark as pending
590         d->pendingThumbnails.push_front(aUrl);
591         d->thumbnailCache[aUrl] = std::string();
592         d->downloadNextPendingThumbnail();
593     } else if (!it->second.empty()) {
594         // already loaded, fire data synchronously
595         d->fireDataForThumbnail(aUrl, it->second);
596     } else {
597         // in cache but empty data, still fetching
598     }
599 }
600
601 InstallRef Root::existingInstallForPackage(PackageRef p) const
602 {
603     RootPrivate::InstallCache::const_iterator it =
604         d->m_installs.find(p);
605     if (it == d->m_installs.end()) {
606         // check if it exists on disk, create
607         SGPath path(p->pathOnDisk());
608         if (path.exists()) {
609             // this will add to our cache, and hence, modify m_installs
610             return Install::createFromPath(path, p->catalog());
611         }
612
613         // insert a null reference into the dictionary, so we don't call
614         // the pathOnDisk -> exists codepath repeatedley
615         d->m_installs[p] = InstallRef();
616         return InstallRef();
617     }
618
619     return it->second;
620 }
621
622 void Root::registerInstall(InstallRef ins)
623 {
624     if (!ins.valid()) {
625         return;
626     }
627
628     d->m_installs[ins->package()] = ins;
629 }
630
631 void Root::unregisterInstall(InstallRef ins)
632 {
633     if (!ins .valid()) {
634         return;
635     }
636
637     d->m_installs.erase(ins->package());
638 }
639
640 } // of namespace pkg
641
642 } // of namespace simgear