]> git.mxchange.org Git - flightgear.git/blob - src/Network/HTTPClient.cxx
Merge commit 'refs/merge-requests/1591' of https://gitorious.org/fg/flightgear into...
[flightgear.git] / src / Network / HTTPClient.cxx
1 // HTTPClient.cxx -- Singleton HTTP client object
2 //
3 // Written by James Turner, started April 2012.
4 //
5 // Copyright (C) 2012  James Turner
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #include "HTTPClient.hxx"
22
23 #include <cassert>
24
25 #include <Main/fg_props.hxx>
26 #include <Include/version.h>
27
28 #include <simgear/sg_inlines.h>
29
30 #include <simgear/package/Root.hxx>
31 #include <simgear/package/Catalog.hxx>
32 #include <simgear/package/Delegate.hxx>
33 #include <simgear/package/Install.hxx>
34 #include <simgear/package/Package.hxx>
35
36 #include <simgear/nasal/cppbind/from_nasal.hxx>
37 #include <simgear/nasal/cppbind/to_nasal.hxx>
38 #include <simgear/nasal/cppbind/NasalHash.hxx>
39 #include <simgear/nasal/cppbind/Ghost.hxx>
40
41 #include <Scripting/NasalSys.hxx>
42
43 using namespace simgear;
44
45 typedef nasal::Ghost<pkg::RootRef> NasalPackageRoot;
46 typedef nasal::Ghost<pkg::PackageRef> NasalPackage;
47 typedef nasal::Ghost<pkg::CatalogRef> NasalCatalog;
48 typedef nasal::Ghost<pkg::InstallRef> NasalInstall;
49
50 #define ENABLE_PACKAGE_SYSTEM 1
51
52 namespace {
53   
54   class FGDelegate : public pkg::Delegate
55 {
56 public:
57   virtual void refreshComplete()
58   {
59     SG_LOG(SG_IO, SG_INFO, "all Catalogs refreshed");
60     
61     // auto-update; make this controlled by a property
62     pkg::Root* r = globals->packageRoot();
63     
64     pkg::PackageList toBeUpdated(r->packagesNeedingUpdate());
65     pkg::PackageList::const_iterator it;
66     for (it = toBeUpdated.begin(); it != toBeUpdated.end(); ++it) {
67       assert((*it)->isInstalled());
68       SG_LOG(SG_IO, SG_INFO, "updating:" << (*it)->id());
69       r->scheduleToUpdate((*it)->install());
70     }
71   }
72
73   virtual void failedRefresh(pkg::Catalog* aCat, FailureCode aReason)
74   {
75     switch (aReason) {
76     case pkg::Delegate::FAIL_SUCCESS:
77         SG_LOG(SG_IO, SG_WARN, "refresh of Catalog done");
78         break;
79         
80     default:
81         SG_LOG(SG_IO, SG_WARN, "refresh of Catalog " << aCat->url() << " failed:" << aReason);
82     }
83   }
84   
85   virtual void startInstall(pkg::Install* aInstall)
86   {
87     SG_LOG(SG_IO, SG_INFO, "beginning install of:" << aInstall->package()->id()
88            << " to local path:" << aInstall->path());
89
90   }
91   
92   virtual void installProgress(pkg::Install* aInstall, unsigned int aBytes, unsigned int aTotal)
93   {
94     SG_LOG(SG_IO, SG_INFO, "installing:" << aInstall->package()->id() << ":"
95            << aBytes << " of " << aTotal);
96   }
97   
98   virtual void finishInstall(pkg::Install* aInstall)
99   {
100     SG_LOG(SG_IO, SG_INFO, "finished install of:" << aInstall->package()->id()
101            << " to local path:" << aInstall->path());
102
103   }
104   
105   virtual void failedInstall(pkg::Install* aInstall, FailureCode aReason)
106   {
107     SG_LOG(SG_IO, SG_WARN, "install failed of:" << aInstall->package()->id()
108            << " to local path:" << aInstall->path());
109   }
110
111 };
112
113 } // of anonymous namespace
114
115 FGHTTPClient::FGHTTPClient()
116 {
117 }
118
119 FGHTTPClient::~FGHTTPClient()
120 {
121 }
122
123 void FGHTTPClient::init()
124 {
125   _http.reset(new simgear::HTTP::Client);
126   
127   std::string proxyHost(fgGetString("/sim/presets/proxy/host"));
128   int proxyPort(fgGetInt("/sim/presets/proxy/port"));
129   std::string proxyAuth(fgGetString("/sim/presets/proxy/auth"));
130   
131   if (!proxyHost.empty()) {
132     _http->setProxy(proxyHost, proxyPort, proxyAuth);
133   }
134   
135 #ifdef ENABLE_PACKAGE_SYSTEM
136   pkg::Root* packageRoot = globals->packageRoot();
137   if (packageRoot) {
138     // package system needs access to the HTTP engine too
139     packageRoot->setHTTPClient(_http.get());
140     
141     packageRoot->setDelegate(new FGDelegate);
142
143     const char * defaultCatalogId = fgGetString("/sim/package-system/default-catalog/id", "org.flightgear.default" );
144     const char * defaultCatalogUrl = fgGetString("/sim/package-system/default-catalog/url",
145             "http://fgfs.goneabitbursar.com/pkg/" FLIGHTGEAR_VERSION "/default-catalog.xml");
146     // setup default catalog if not present
147     pkg::Catalog* defaultCatalog = packageRoot->getCatalogById( defaultCatalogId );
148     if (!defaultCatalog) {
149       // always show this message
150       SG_LOG(SG_GENERAL, SG_ALERT, "default catalog not found, installing '"
151         << defaultCatalogId << "' from '" << defaultCatalogUrl << "'.");
152       pkg::Catalog::createFromUrl(packageRoot,defaultCatalogUrl);
153     }
154     
155     // start a refresh now
156     packageRoot->refresh();
157   }
158 #endif // of ENABLE_PACKAGE_SYSTEM
159 }
160
161 static naRef f_package_existingInstall( pkg::Package& pkg,
162                                         const nasal::CallContext& ctx )
163 {
164   return ctx.to_nasal(
165     pkg.existingInstall( ctx.getArg<pkg::Package::InstallCallback>(0) )
166   );
167 }
168
169 static naRef f_package_uninstall(pkg::Package& pkg, const nasal::CallContext& ctx)
170 {
171     pkg::InstallRef ins = pkg.existingInstall();
172     if (ins) {
173         ins->uninstall();
174     }
175
176     return naNil();
177 }
178
179 static SGPropertyNode_ptr queryPropsFromHash(const nasal::Hash& h)
180 {
181     SGPropertyNode_ptr props(new SGPropertyNode);
182
183     for (nasal::Hash::const_iterator it = h.begin(); it != h.end(); ++it) {
184         std::string const key = it->getKey();
185         if ((key == "name") || (key == "description")) {
186             props->setStringValue(key, it->getValue<std::string>());
187         } else if (strutils::starts_with(key, "rating-")) {
188             props->setIntValue(key, it->getValue<int>());
189         } else if (key == "tags") {
190             string_list tags = it->getValue<string_list>();
191             string_list::const_iterator tagIt;
192             int tagCount = 0;
193             for (tagIt = tags.begin(); tagIt != tags.end(); ++tagIt) {
194                 SGPropertyNode_ptr tag = props->getChild("tag", tagCount++, true);
195                 tag->setStringValue(*tagIt);
196             }
197         } else if (key == "installed") {
198             props->setBoolValue(key, it->getValue<bool>());
199         } else {
200             SG_LOG(SG_GENERAL, SG_WARN, "unknown filter term in hash:" << key);
201         }
202     }
203
204     return props;
205 }
206
207 static naRef f_root_search(pkg::Root& root, const nasal::CallContext& ctx)
208 {
209     SGPropertyNode_ptr query = queryPropsFromHash(ctx.requireArg<nasal::Hash>(0));
210     pkg::PackageList result = root.packagesMatching(query);
211     return ctx.to_nasal(result);
212 }
213
214 static naRef f_catalog_search(pkg::Catalog& cat, const nasal::CallContext& ctx)
215 {
216     SGPropertyNode_ptr query = queryPropsFromHash(ctx.requireArg<nasal::Hash>(0));
217     pkg::PackageList result = cat.packagesMatching(query);
218     return ctx.to_nasal(result);
219 }
220
221 static naRef f_package_variants(pkg::Package& pack, naContext c)
222 {
223     nasal::Hash h(c);
224     string_list vars(pack.variants());
225     for (string_list_iterator it  = vars.begin(); it != vars.end(); ++it) {
226         h.set(*it, pack.nameForVariant(*it));
227     }
228
229     return h.get_naRef();
230 }
231
232 void FGHTTPClient::postinit()
233 {
234 #ifdef ENABLE_PACKAGE_SYSTEM
235   NasalPackageRoot::init("PackageRoot")
236   .member("path", &pkg::Root::path)
237   .member("version", &pkg::Root::catalogVersion)
238   .method("refresh", &pkg::Root::refresh)
239   .method("catalogs", &pkg::Root::catalogs)
240   .method("packageById", &pkg::Root::getPackageById)
241   .method("catalogById", &pkg::Root::getCatalogById)
242   .method("search", &f_root_search);
243
244   NasalCatalog::init("Catalog")
245   .member("installRoot", &pkg::Catalog::installRoot)
246   .member("id", &pkg::Catalog::id)
247   .member("url", &pkg::Catalog::url)
248   .member("description", &pkg::Catalog::description)
249   .method("packages", &pkg::Catalog::packages)
250   .method("packageById", &pkg::Catalog::getPackageById)
251   .method("refresh", &pkg::Catalog::refresh)
252   .method("needingUpdate", &pkg::Catalog::packagesNeedingUpdate)
253   .member("installed", &pkg::Catalog::installedPackages)
254   .method("search", &f_catalog_search);
255   
256   NasalPackage::init("Package")
257   .member("id", &pkg::Package::id)
258   .member("name", &pkg::Package::name)
259   .member("description", &pkg::Package::description)
260   .member("installed", &pkg::Package::isInstalled)
261   .member("thumbnails", &pkg::Package::thumbnailUrls)
262   .member("variants", &f_package_variants)
263   .member("revision", &pkg::Package::revision)
264   .member("catalog", &pkg::Package::catalog)
265   .method("install", &pkg::Package::install)
266   .method("uninstall", &f_package_uninstall)
267   .method("existingInstall", &f_package_existingInstall)
268   .method("lprop", &pkg::Package::getLocalisedProp)
269   .member("fileSize", &pkg::Package::fileSizeBytes);
270   
271   typedef pkg::Install* (pkg::Install::*InstallCallback)
272                         (const pkg::Install::Callback&);
273   typedef pkg::Install* (pkg::Install::*ProgressCallback)
274                         (const pkg::Install::ProgressCallback&);
275   NasalInstall::init("Install")
276   .member("revision", &pkg::Install::revsion)
277   .member("pkg", &pkg::Install::package)
278   .member("path", &pkg::Install::path)
279   .member("hasUpdate", &pkg::Install::hasUpdate)
280   .method("startUpdate", &pkg::Install::startUpdate)
281   .method("uninstall", &pkg::Install::uninstall)
282   .method("done", static_cast<InstallCallback>(&pkg::Install::done))
283   .method("fail", static_cast<InstallCallback>(&pkg::Install::fail))
284   .method("always", static_cast<InstallCallback>(&pkg::Install::always))
285   .method("progress", static_cast<ProgressCallback>(&pkg::Install::progress));
286   
287   pkg::Root* packageRoot = globals->packageRoot();
288   if (packageRoot) {
289     FGNasalSys* nasalSys = (FGNasalSys*) globals->get_subsystem("nasal");
290     nasal::Hash nasalGlobals = nasalSys->getGlobals();
291     nasal::Hash nasalPkg = nasalGlobals.createHash("pkg"); // module
292     nasalPkg.set("root", packageRoot);
293   }
294 #endif // of ENABLE_PACKAGE_SYSTEM
295 }
296
297 void FGHTTPClient::shutdown()
298 {
299   _http.reset();
300 }
301
302 void FGHTTPClient::update(double)
303 {
304   _http->update();
305 }
306
307 void FGHTTPClient::makeRequest(const simgear::HTTP::Request_ptr& req)
308 {
309   _http->makeRequest(req);
310 }