Debian Codegraph @

src/Gui/NetworkRetriever.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QApplication>
25 #include <QDir>
26 #include <QFileInfo>
27 #include <QMessageBox>
28 #include <QTimer>
29
30 #include <FCConfig.h>
31
32 #include <App/Application.h>
33 #include <Base/Console.h>
34
35 #include "NetworkRetriever.h"
36 #include "Action.h"
37 #include "BitmapFactory.h"
38 #include "FileDialog.h"
39 #include "MainWindow.h"
40 #include "Dialogs/ui_DlgAuthorization.h"
41
42
43 using namespace Gui;
44 using namespace Gui::Dialog;
45
46 namespace Gui
47 {
48
49 struct NetworkRetrieverP
50 {
51 // wget options
52 int tries;
53 int level;
54 QString outputFile;
55 QString user;
56 QString passwd;
57 bool timeStamp;
58 bool img;
59 bool convert;
60 bool recurse;
61 bool folRel;
62 bool html;
63 bool nop;
64 // wget argument
65 QString startUrl;
66
67 QString proxy;
68 QString dir;
69 bool fail;
70 };
71
72 } // namespace Gui
73
74 /* TRANSLATOR Gui::NetworkRetriever */
75
76 NetworkRetriever::NetworkRetriever(QObject* parent)
77 : QObject(parent)
78 {
79 d = new NetworkRetrieverP;
80 d->tries = 3;
81 d->level = 1;
82 d->timeStamp = false;
83 d->img = false;
84 d->html = false;
85 d->convert = true;
86 d->recurse = false;
87 d->folRel = false;
88 d->nop = false;
89
90 wget = new QProcess(this);
91
92 // if wgets exits emit signal
93 connect(
94 wget,
95 qOverload<int, QProcess::ExitStatus>(&QProcess::finished),
96 this,
97 &NetworkRetriever::wgetFinished
98 );
99
100 // if application quits kill wget immediately to avoid dangling processes
101 connect(qApp, &QApplication::lastWindowClosed, wget, &QProcess::kill);
102 }
103
104 NetworkRetriever::~NetworkRetriever()
105 {
106 delete wget;
107 delete d;
108 }
109
110 /**
111 * This method is connected to QTimer::singleShot() and executed after 5 seconds. If wget then is
112 * still running we can assume that everything is fine.
113 * \note This test is necessary since \a wget writes all its output on stderr and we cannot
114 * determine surely if an error occurred or not.
115 *
116 * There is still a problem that is not solved so far. If wget requires the proxy settings and if
117 * these are not set, wget could take more than 5 seconds without downloading anything.
118 */
119 void NetworkRetriever::testFailure()
120 {
121 if (wget->state() == QProcess::Running) {
122 d->fail = false;
123 QString msg = tr("Download started…");
124 Base::Console().message("%s\n", msg.toUtf8().constData());
125 }
126 }
127
128 /**
129 * Sets the number of retries to \a tries. If \a tries is 0 the number of tries
130 * is unlimited. The default value of the tries property is set to 3.
131 */
132 void NetworkRetriever::setNumberOfTries(int tries)
133 {
134 d->tries = tries;
135 }
136
137 /**
138 * Sets output file to \a out where documents are written to.
139 */
140 void NetworkRetriever::setOutputFile(const QString& out)
141 {
142 d->outputFile = out;
143 }
144
145 /**
146 * If \a ts is true the timestamping is enabled, otherwise timestamping is
147 * disabled. If timestamping is enabled files are no more re-retrieved unless
148 * they are newer than the local files. As default the timestamping property is disabled.
149 */
150 void NetworkRetriever::setEnableTimestamp(bool ts)
151 {
152 d->timeStamp = ts;
153 }
154
155 /**
156 * If you are behind a proxy server then you have to specify your proxy url with \a proxy.
157 * Moreover, if the proxy requires user authentication then you can specify the username
158 * with \a user and the password with \a passwd.
159 */
160 void NetworkRetriever::setProxy(const QString& proxy, const QString& user, const QString& passwd)
161 {
162 d->proxy = proxy;
163 d->user = user;
164 d->passwd = passwd;
165 }
166
167 /**
168 * If \a recursive is true all referenced files are downloaded recursively.
169 * As default recursion is disabled. \a level specifies the maximum recursion
170 * depth. If \a level is 0 the recursion depth is infinite. As default the level
171 * property is 1.
172 * \note: Use this with care!
173 */
174 void NetworkRetriever::setEnableRecursive(bool recursive, int level)
175 {
176 d->recurse = recursive;
177 d->level = level;
178 }
179
180 /**
181 * If \a folRel is true wget follows relative links only. As default
182 * the follows relative property is false.
183 */
184 void NetworkRetriever::setFollowRelative(bool folRel)
185 {
186 d->folRel = folRel;
187 }
188
189 /**
190 * If \a convert is true all non-relative links are converted to
191 * relative links. As default the convert property is true.
192 */
193 void NetworkRetriever::setEnableConvert(bool convert)
194 {
195 d->convert = convert;
196 }
197
198 /**
199 * If \a img is true wget tries to get all needed image files
200 * to display the HTML page. As default this behaviour is disabled..
201 */
202 void NetworkRetriever::setFetchImages(bool img)
203 {
204 d->img = img;
205 }
206
207 /**
208 * Saves all text/html documents with .html extionsion if \a html is true.
209 * As default the html property is false.
210 */
211 void NetworkRetriever::setEnableHTMLExtension(bool html)
212 {
213 d->html = html;
214 }
215
216 /**
217 * Do not ever ascend to the parent directory when retrieving recursively.
218 */
219 void NetworkRetriever::setNoParent(bool nop)
220 {
221 d->nop = nop;
222 }
223
224 /**
225 * Sets the output directory to \a dir where all downloaded are written into.
226 */
227 void NetworkRetriever::setOutputDirectory(const QString& dir)
228 {
229 d->dir = dir;
230 }
231
232 /**
233 * wget starts to download \a startUrl and all referenced pages.
234 */
235 bool NetworkRetriever::startDownload(const QString& startUrl)
236 {
237 if (!testWget()) {
238 return false;
239 }
240
241 d->startUrl = startUrl;
242
243 // proxy as environment variable
244 if (!d->proxy.isEmpty()) {
245 QStringList env = wget->environment();
246 env << QStringLiteral("http_proxy=%1").arg(d->proxy);
247 env << QStringLiteral("ftp_proxy=%1").arg(d->proxy);
248 wget->setEnvironment(env);
249 }
250 else {
251 QStringList env = wget->environment();
252 env.removeAll(QStringLiteral("http_proxy=%1").arg(d->proxy));
253 env.removeAll(QStringLiteral("ftp_proxy=%1").arg(d->proxy));
254 wget->setEnvironment(env);
255 }
256
257 QStringList wgetArguments;
258
259 // since the wget option '--directory-prefix' seems not to work as expected
260 // and QProcess::setWorkingDirectory() fails if the 'doc' directory doesn't
261 // exist we must check for this and create it if needed.
262 if (!d->dir.isEmpty()) {
263 QDir dir(d->dir);
264 if (!dir.exists(d->dir)) {
265 if (!dir.mkdir(d->dir)) {
266 Base::Console().error(
267 "Directory '%s' could not be created.",
268 (const char*)d->dir.toLatin1()
269 );
270 return true; // please, no error message
271 }
272 }
273
274 wget->setWorkingDirectory(dir.path());
275 }
276
277 // user authentication
278 if (!d->proxy.isEmpty()) {
279 if (!d->user.isEmpty()) {
280 wgetArguments << QStringLiteral("--proxy-user=%1").arg(d->user);
281 if (!d->passwd.isEmpty()) {
282 wgetArguments << QStringLiteral("--proxy-passwd=%1").arg(d->passwd);
283 }
284 }
285 }
286
287 // output file
288 if (!d->outputFile.isEmpty()) {
289 wgetArguments << QStringLiteral("--output-document=%1").arg(d->outputFile);
290 }
291 // timestamping enabled -> update newer files only
292 if (d->timeStamp) {
293 wgetArguments << QStringLiteral("-N");
294 }
295 // get all needed image files
296 if (d->img) {
297 wgetArguments << QStringLiteral("-p");
298 }
299 // follow relative links only
300 if (d->folRel) {
301 wgetArguments << QStringLiteral("-L");
302 }
303 if (d->recurse) {
304 wgetArguments << QStringLiteral("-r");
305 wgetArguments << QStringLiteral("--level=%1").arg(d->level);
306 }
307
308 if (d->nop) {
309 wgetArguments << QStringLiteral("-np");
310 }
311
312 // convert absolute links in to relative
313 if (d->convert) {
314 wgetArguments << QStringLiteral("-k");
315 }
316 // number of tries
317 wgetArguments << QStringLiteral("--tries=%1").arg(d->tries);
318 // use HTML file extension
319 if (d->html) {
320 wgetArguments << QStringLiteral("-E");
321 }
322
323 // start URL
324 wgetArguments << startUrl;
325
326 #ifdef FC_OS_LINUX
327 // on Linux it seems that we have to change cwd
328 QString cwd = QDir::currentPath();
329 if (!d->dir.isEmpty()) {
330 QDir::setCurrent(d->dir);
331 }
332
333 wget->start(QStringLiteral("wget"), wgetArguments);
334 QDir::setCurrent(cwd);
335 #else
336 wget->start(QStringLiteral("wget"), wgetArguments);
337 #endif
338
339 return wget->state() == QProcess::Running;
340 }
341
342 /**
343 * Returns true if wget is still downloading, otherwise returns false.
344 */
345 bool NetworkRetriever::isDownloading() const
346 {
347 return wget->state() == QProcess::Running;
348 }
349
350 /**
351 * Kills wget if it is still running.
352 */
353 void NetworkRetriever::abort()
354 {
355 if (wget->state() == QProcess::Running) {
356 QTimer::singleShot(2000, wget, &QProcess::kill);
357 }
358 }
359
360 void NetworkRetriever::wgetFinished(int exitCode, QProcess::ExitStatus status)
361 {
362 Q_UNUSED(exitCode);
363 Q_UNUSED(status);
364 wget->setReadChannel(QProcess::StandardError);
365 if (wget->canReadLine()) {
366 QByteArray data = wget->readAll();
367 Base::Console().warning(data);
368 }
369 Q_EMIT wgetExited();
370 }
371
372 /**
373 * This is a test if wget is in PATH environment or not.
374 * If the test succeeds true is returned, false otherwise.
375 */
376 bool NetworkRetriever::testWget()
377 {
378 QProcess proc;
379 proc.setProgram(QStringLiteral("wget"));
380 proc.start();
381 bool ok = proc.state() == QProcess::Running;
382 proc.kill();
383 proc.waitForFinished();
384 return ok;
385 }
386
387 // --------------------------------------------------------------------
388
389 StdCmdDownloadOnlineHelp::StdCmdDownloadOnlineHelp(QObject* parent)
390 : QObject(parent)
391 , Command("Std_DownloadOnlineHelp")
392 {
393 sGroup = "Help";
394 sMenuText = QT_TR_NOOP("Download Online Help");
395 sToolTipText = QT_TR_NOOP("Downloads %1's online help");
396 sWhatsThis = "Std_DownloadOnlineHelp";
397 sStatusTip = sToolTipText;
398 sPixmap = "help";
399
400 wget = new NetworkRetriever(this);
401 // downloading recursively and depth 5
402 wget->setEnableRecursive(true, 5);
403 wget->setNumberOfTries(3);
404 wget->setEnableHTMLExtension(true);
405 wget->setEnableConvert(true);
406
407 wget->setEnableTimestamp(true);
408 wget->setFetchImages(true);
409 wget->setFollowRelative(false);
410 wget->setNoParent(true);
411
412 connect(wget, &NetworkRetriever::wgetExited, this, &StdCmdDownloadOnlineHelp::wgetFinished);
413 }
414
415 StdCmdDownloadOnlineHelp::~StdCmdDownloadOnlineHelp()
416 {
417 delete wget;
418 }
419
420 Action* StdCmdDownloadOnlineHelp::createAction()
421 {
422 Action* pcAction;
423
424 QString exe = QString::fromStdString(App::Application::getExecutableName());
425 pcAction = new Action(this, getMainWindow());
426 pcAction->setText(QCoreApplication::translate(this->className(), getMenuText()));
427 pcAction->setToolTip(QCoreApplication::translate(this->className(), getToolTipText()).arg(exe));
428 pcAction->setStatusTip(QCoreApplication::translate(this->className(), getStatusTip()).arg(exe));
429 pcAction->setWhatsThis(QCoreApplication::translate(this->className(), getWhatsThis()).arg(exe));
430 pcAction->setIcon(Gui::BitmapFactory().pixmap(getPixmap()));
431 pcAction->setShortcut(QString::fromLatin1(getAccel()));
432
433 return pcAction;
434 }
435
436 void StdCmdDownloadOnlineHelp::languageChange()
437 {
438 if (_pcAction) {
439 QString exe = QString::fromStdString(App::Application::getExecutableName());
440 _pcAction->setText(QCoreApplication::translate(this->className(), getMenuText()));
441 _pcAction->setToolTip(
442 QCoreApplication::translate(this->className(), getToolTipText()).arg(exe)
443 );
444 _pcAction->setStatusTip(
445 QCoreApplication::translate(this->className(), getStatusTip()).arg(exe)
446 );
447 _pcAction->setWhatsThis(
448 QCoreApplication::translate(this->className(), getWhatsThis()).arg(exe)
449 );
450 }
451 }
452
453 void StdCmdDownloadOnlineHelp::activated(int iMsg)
454 {
455 Q_UNUSED(iMsg);
456 if (!wget->isDownloading()) {
457 ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp");
458 hGrp = hGrp->GetGroup("Preferences")->GetGroup("OnlineHelp");
459 std::string url = hGrp->GetASCII("DownloadURL", "www.freecad.org/wiki/");
460 std::string prx = hGrp->GetASCII("ProxyText", "");
461 bool bUseProxy = hGrp->GetBool("UseProxy", false);
462 bool bAuthor = hGrp->GetBool("Authorize", false);
463
464 if (bUseProxy) {
465 QString username;
466 QString password;
467
468 if (bAuthor) {
469 QDialog dlg(getMainWindow());
470 dlg.setModal(true);
471 Ui_DlgAuthorization ui;
472 ui.setupUi(&dlg);
473
474 if (dlg.exec() == QDialog::Accepted) {
475 username = ui.username->text();
476 password = ui.password->text();
477 }
478 }
479
480 wget->setProxy(QString::fromLatin1(prx.c_str()), username, password);
481 }
482
483 int loop = 3;
484 bool canStart = false;
485
486 // set output directory
487 QString path = QString::fromStdString(App::Application::getHomePath());
488 path += QStringLiteral("/doc/");
489 ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath(
490 "User parameter:BaseApp/Preferences/OnlineHelp"
491 );
492 path = QString::fromUtf8(hURLGrp->GetASCII("DownloadLocation", path.toLatin1()).c_str());
493
494 while (loop > 0) {
495 loop--;
496 QFileInfo fi(path);
497 if (!fi.exists()) {
498 if (QMessageBox::critical(
499 getMainWindow(),
500 tr("Non-existing directory"),
501 tr("The directory '%1' does not exist.\n\n"
502 "Specify an existing directory?")
503 .arg(fi.filePath()),
504 QMessageBox::Yes | QMessageBox::No
505 )
506 != QMessageBox::Yes) {
507 // exit the command
508 return;
509 }
510 else {
511 path = FileDialog::getExistingDirectory();
512 if (path.isEmpty()) {
513 return;
514 }
515 }
516 }
517
518 if (!fi.permission(QFile::WriteUser)) {
519 if (QMessageBox::critical(
520 getMainWindow(),
521 tr("Missing permission"),
522 tr("You don't have write permission to '%1'\n\n"
523 "Specify another directory?")
524 .arg(fi.filePath()),
525 QMessageBox::Yes | QMessageBox::No
526 )
527 != QMessageBox::Yes) {
528 // exit the command
529 return;
530 }
531 else {
532 path = FileDialog::getExistingDirectory();
533 if (path.isEmpty()) {
534 return;
535 }
536 }
537 }
538 else {
539 wget->setOutputDirectory(path);
540 canStart = true;
541 break;
542 }
543 }
544
545 if (canStart) {
546 bool ok = wget->startDownload(QString::fromLatin1(url.c_str()));
547 if (!ok) {
548 Base::Console().error("The tool 'wget' could not be found. Check the installation.");
549 }
550 else if (wget->isDownloading() && _pcAction) {
551 _pcAction->setText(tr("Stop downloading"));
552 }
553 }
554 }
555 else // kill the process now
556 {
557 wget->abort();
558 }
559 }
560
561 void StdCmdDownloadOnlineHelp::wgetFinished()
562 {
563 if (_pcAction) {
564 _pcAction->setText(QCoreApplication::translate(this->className(), getMenuText()));
565 }
566 }
567
568 #include "moc_NetworkRetriever.cpp"