MythTV  master
mythcontext.cpp
Go to the documentation of this file.
1 #include <QCoreApplication>
2 #include <QDir>
3 #include <QFileInfo>
4 #include <QDebug>
5 #include <QMutex>
6 #include <QDateTime>
7 #include <QTcpSocket>
8 #include <QEventLoop>
9 
10 #ifdef Q_OS_ANDROID
11 #include <QtAndroidExtras>
12 #endif
13 
14 #include <cmath>
15 #include <iostream>
16 
17 #include <queue>
18 #include <algorithm>
19 #include <thread>
20 
21 using namespace std;
22 
23 #include "config.h"
24 #include "mythcontext.h"
25 #include "exitcodes.h"
26 #include "mythdate.h"
27 #include "remotefile.h"
28 #include "backendselect.h"
29 #include "dbsettings.h"
30 #include "langsettings.h"
31 #include "mythtranslation.h"
32 #include "mythxdisplay.h"
33 #include "mythevent.h"
34 #include "dbutil.h"
35 #include "DisplayRes.h"
36 #include "mythmediamonitor.h"
37 
38 #include "mythdb.h"
39 #include "mythdirs.h"
40 #include "mythversion.h"
41 #include "mythdialogbox.h"
42 #include "mythmainwindow.h"
43 #include "mythuihelper.h"
44 #include "mythimage.h"
45 #include "mythxmlclient.h"
46 #include "upnp.h"
47 #include "mythlogging.h"
48 #include "mythsystemlegacy.h"
49 #include "mythmiscutil.h"
50 
51 #include "mythplugin.h"
52 #include "portchecker.h"
53 #include "guistartup.h"
54 
55 #include <unistd.h> // for usleep(), gethostname
56 
57 #ifdef _WIN32
58 #include "compat.h"
59 #endif
60 
61 #define LOC QString("MythContext: ")
62 
63 MythContext *gContext = nullptr;
64 
65 static const QString _Location = "MythContext";
66 
67 class MythContextPrivate : public QObject
68 {
69  friend class MythContextSlotHandler;
70 
71  public:
73  ~MythContextPrivate() override;
74 
75  bool Init (bool gui,
76  bool prompt, bool noPrompt,
77  bool ignoreDB);
78  bool FindDatabase(bool prompt, bool noAutodetect);
79 
80  void TempMainWindow(bool languagePrompt = true);
81  void EndTempWindow(void);
82 
83  bool LoadDatabaseSettings(void);
84  bool SaveDatabaseParams(const DatabaseParams &params, bool force);
85 
86  bool PromptForDatabaseParams(const QString &error);
87  QString TestDBconnection(bool prompt=true);
88  void SilenceDBerrors(void);
89  void EnableDBerrors(void);
90  void ResetDatabase(void);
91 
92  int ChooseBackend(const QString &error);
93  int UPnPautoconf(int milliSeconds = 2000);
94  bool DefaultUPnP(QString &error);
95  bool UPnPconnect(const DeviceLocation *backend, const QString &PIN);
96  void ShowGuiStartup(void);
97  bool checkPort(QString &host, int port, int timeLimit);
98  void processEvents(void);
99  bool saveSettingsCache(void);
100  void loadSettingsCacheOverride(void);
101  void clearSettingsCacheOverride(void);
102 
103 
104  protected:
105  bool event(QEvent* /*e*/) override; // QObject
106 
107  void ShowConnectionFailurePopup(bool persistent);
108  void HideConnectionFailurePopup(void);
109 
110  void ShowVersionMismatchPopup(uint remote_version);
111 
112  public slots:
113  void OnCloseDialog();
114 
115  public:
116  MythContext *m_parent {nullptr};
117 
119  bool m_gui {false};
120 
122 
124  QString m_DBhostCp;
125 
126  Configuration *m_pConfig {nullptr};
127 
128  bool m_disableeventpopup {false};
129 
130  MythUIHelper *m_ui {nullptr};
131  MythContextSlotHandler *m_sh {nullptr};
132  GUIStartup *m_guiStartup {nullptr};
133  QEventLoop *m_loop {nullptr};
134  bool m_needsBackend {false};
135  bool m_settingsCacheDirty {false};
136 
137  private:
138  MythConfirmationDialog *m_MBEversionPopup {nullptr};
139  int m_registration {-1};
140  QDateTime m_lastCheck;
141  QTcpSocket *m_socket {nullptr};
142  static const QString s_settingsToSave[];
143 };
144 
145 static void exec_program_cb(const QString &cmd)
146 {
147  myth_system(cmd);
148 }
149 
150 static void exec_program_tv_cb(const QString &cmd)
151 {
152  QString s = cmd;
153  QStringList tokens = cmd.simplified().split(" ");
154  QStringList strlist;
155 
156  bool cardidok;
157  int wantcardid = tokens[0].toInt(&cardidok, 10);
158 
159  if (cardidok && wantcardid > 0)
160  {
161  strlist << QString("LOCK_TUNER %1").arg(wantcardid);
162  s = s.replace(0, tokens[0].length() + 1, "");
163  }
164  else
165  strlist << "LOCK_TUNER";
166 
168  int cardid = strlist[0].toInt();
169 
170  if (cardid >= 0)
171  {
172  s = s.sprintf(qPrintable(s),
173  qPrintable(strlist[1]),
174  qPrintable(strlist[2]),
175  qPrintable(strlist[3]));
176 
177  myth_system(s);
178 
179  strlist = QStringList(QString("FREE_TUNER %1").arg(cardid));
181  QString ret = strlist[0];
182  }
183  else
184  {
185  QString label;
186 
187  if (cardidok)
188  {
189  if (cardid == -1)
190  label = QObject::tr("Could not find specified tuner (%1).")
191  .arg(wantcardid);
192  else
193  label = QObject::tr("Specified tuner (%1) is already in use.")
194  .arg(wantcardid);
195  }
196  else
197  {
198  label = QObject::tr("All tuners are currently in use. If you want "
199  "to watch TV, you can cancel one of the "
200  "in-progress recordings from the delete menu");
201  }
202 
203  LOG(VB_GENERAL, LOG_ALERT, QString("exec_program_tv: ") + label);
204 
205  ShowOkPopup(label);
206  }
207 }
208 
209 static void configplugin_cb(const QString &cmd)
210 {
212  if (!pmanager)
213  return;
214 
215  if (GetNotificationCenter() && pmanager->config_plugin(cmd.trimmed()))
216  {
218  QObject::tr("Failed to configure plugin"));
219  }
220 }
221 
222 static void plugin_cb(const QString &cmd)
223 {
225  if (!pmanager)
226  return;
227 
228  if (GetNotificationCenter() && pmanager->run_plugin(cmd.trimmed()))
229  {
230  ShowNotificationError(QObject::tr("Plugin failure"),
231  _Location,
232  QObject::tr("%1 failed to run for some reason").arg(cmd));
233  }
234 }
235 
236 static void eject_cb(void)
237 {
239 }
240 
242  : m_parent(lparent),
243  m_sh(new MythContextSlotHandler(this))
244 {
245  m_loop = new QEventLoop(this);
247 }
248 
250 {
251  delete m_pConfig;
253  {
255  }
256 
257  delete m_loop;
258 
259  if (m_ui)
260  DestroyMythUI();
261  if (m_sh)
262  m_sh->deleteLater();
263 }
264 
275 void MythContextPrivate::TempMainWindow(bool languagePrompt)
276 {
277  if (HasMythMainWindow())
278  return;
279 
280  SilenceDBerrors();
281 
282 #ifdef Q_OS_MAC
283  // Qt 4.4 has window-focus problems
284  gCoreContext->OverrideSettingForSession("RunFrontendInWindow", "1");
285 #endif
286  GetMythUI()->Init();
287  GetMythUI()->LoadQtConfig();
288 
289  MythMainWindow *mainWindow = MythMainWindow::getMainWindow(false);
290  mainWindow->Init();
291 
292  if (languagePrompt)
293  {
294  // ask user for language settings
296  MythTranslation::load("mythfrontend");
297  }
298 }
299 
301 {
302  if (HasMythMainWindow())
303  {
305  {
307  if (mainStack) {
308  mainStack->PopScreen(m_guiStartup, false);
309  m_guiStartup = nullptr;
310  }
311  }
312  }
313  EnableDBerrors();
314 }
315 
325 bool MythContextPrivate::checkPort(QString &host, int port, int timeLimit)
326 {
327  PortChecker checker;
328  if (m_guiStartup)
329  QObject::connect(m_guiStartup,SIGNAL(cancelPortCheck()),&checker,SLOT(cancelPortCheck()));
330  return checker.checkPort(host, port, timeLimit*1000);
331 }
332 
333 
334 bool MythContextPrivate::Init(const bool gui,
335  const bool promptForBackend,
336  const bool noPrompt,
337  const bool ignoreDB)
338 {
339  gCoreContext->GetDB()->IgnoreDatabase(ignoreDB);
340  m_gui = gui;
342 
343  if (gCoreContext->IsFrontend())
344  m_needsBackend = true;
345 
346  // We don't have a database yet, so lets use the config.xml file.
347  m_pConfig = new XmlConfiguration("config.xml");
348 
349  // Creates screen saver control if we will have a GUI
350  if (gui)
351  m_ui = GetMythUI();
352 
353  // ---- database connection stuff ----
354 
355  if (!ignoreDB && !FindDatabase(promptForBackend, noPrompt))
356  {
357  EndTempWindow();
358  return false;
359  }
360 
361  // ---- keep all DB-using stuff below this line ----
362 
363  // Prompt for language if this is a first time install and
364  // we didn't already do so.
365  if (m_gui && !gCoreContext->GetDB()->HaveSchema())
366  {
367  TempMainWindow(false);
369  MythTranslation::load("mythfrontend");
370  }
373 
374  // Close GUI Startup Window.
375  if (m_guiStartup) {
377  if (mainStack)
378  mainStack->PopScreen(m_guiStartup, false);
379  m_guiStartup=nullptr;
380  }
381  EndTempWindow();
382 
383  if (gui)
384  {
389  cbs.plugin = plugin_cb;
390  cbs.eject = eject_cb;
391 
392  m_ui->Init(cbs);
393  }
394 
395  return true;
396 }
397 
410 bool MythContextPrivate::FindDatabase(bool prompt, bool noAutodetect)
411 {
412  // We can only prompt if autodiscovery is enabled..
413  bool manualSelect = prompt && !noAutodetect;
414 
415  QString failure;
416 
417  // 1. Either load config.xml or use sensible "localhost" defaults:
418  bool loaded = LoadDatabaseSettings();
419  DatabaseParams dbParamsFromFile = m_DBparams;
420 
421  // In addition to the UI chooser, we can also try to autoSelect later,
422  // but only if we're not doing manualSelect and there was no
423  // valid config.xml
424  bool autoSelect = !manualSelect && !loaded && !noAutodetect;
425 
426  // 2. If the user isn't forcing up the chooser UI, look for a default
427  // backend in config.xml, then test DB settings we've got so far:
428  if (!manualSelect)
429  {
430  // config.xml may contain a backend host UUID and PIN.
431  // If so, try to AutoDiscover UPnP server, and use its DB settings:
432 
433  if (DefaultUPnP(failure)) // Probably a valid backend,
434  autoSelect = manualSelect = false; // so disable any further UPnP
435  else
436  if (failure.length())
437  LOG(VB_GENERAL, LOG_ALERT, failure);
438 
439  failure = TestDBconnection(loaded);
440  if (failure.isEmpty())
441  goto DBfound;
443  return false;
445  autoSelect=true;
446  }
447 
448  // 3. Try to automatically find the single backend:
449  if (autoSelect)
450  {
451  int count = UPnPautoconf();
452 
453  if (count == 0)
454  failure = QObject::tr("No UPnP backends found", "Backend Setup");
455 
456  if (count == 1)
457  {
458  failure = TestDBconnection();
459  if (failure.isEmpty())
460  goto DBfound;
462  return false;
463  }
464 
465  // Multiple BEs, or needs PIN.
466  manualSelect |= (count > 1 || count == -1);
467  // Search requested
469  manualSelect=true;
470  }
471 
472  manualSelect &= m_gui; // no interactive command-line chooser yet
473 
474  // Queries the user for the DB info
475  do
476  {
477  if (manualSelect)
478  {
479  // Get the user to select a backend from a possible list:
481  ChooseBackend(failure);
482  switch (d)
483  {
485  break;
487  manualSelect = false;
488  break;
490  goto NoDBfound;
491  }
492  }
493 
494  if (!manualSelect)
495  {
496  if (!PromptForDatabaseParams(failure))
497  goto NoDBfound;
498  }
499  failure = TestDBconnection();
500  if (!failure.isEmpty())
501  LOG(VB_GENERAL, LOG_ALERT, failure);
503  return false;
505  manualSelect=true;
507  manualSelect=false;
508  }
509  while (!failure.isEmpty());
510 
511 DBfound:
512  LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - Success!");
513  // If we got the database from UPNP then the wakeup settings are lost.
514  // Restore them.
515  m_DBparams.wolEnabled = dbParamsFromFile.wolEnabled;
516  m_DBparams.wolReconnect = dbParamsFromFile.wolReconnect;
517  m_DBparams.wolRetry = dbParamsFromFile.wolRetry;
518  m_DBparams.wolCommand = dbParamsFromFile.wolCommand;
519 
521  !loaded || m_DBparams.forceSave ||
522  dbParamsFromFile != m_DBparams);
523  EnableDBerrors();
524  ResetDatabase();
525  return true;
526 
527 NoDBfound:
528  LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - failed");
529  return false;
530 }
531 
536 {
537  // try new format first
539 
540  m_DBparams.localHostName = m_pConfig->GetValue("LocalHostName", "");
541  m_DBparams.dbHostPing = m_pConfig->GetBoolValue(kDefaultDB + "PingHost", true);
543  m_DBparams.dbUserName = m_pConfig->GetValue(kDefaultDB + "UserName", "");
544  m_DBparams.dbPassword = m_pConfig->GetValue(kDefaultDB + "Password", "");
545  m_DBparams.dbName = m_pConfig->GetValue(kDefaultDB + "DatabaseName", "");
547 
549  m_pConfig->GetBoolValue(kDefaultWOL + "Enabled", false);
551  m_pConfig->GetValue(kDefaultWOL + "SQLReconnectWaitTime", 0);
553  m_pConfig->GetValue(kDefaultWOL + "SQLConnectRetry", 5);
555  m_pConfig->GetValue(kDefaultWOL + "Command", "");
556 
557  bool ok = m_DBparams.IsValid("config.xml");
558  if (!ok) // if new format fails, try legacy format
559  {
562  kDefaultMFE + "DBHostName", "");
564  kDefaultMFE + "DBUserName", "");
566  kDefaultMFE + "DBPassword", "");
568  kDefaultMFE + "DBName", "");
570  kDefaultMFE + "DBPort", 0);
571  m_DBparams.forceSave = true;
572  ok = m_DBparams.IsValid("config.xml");
573  }
574  if (!ok)
576 
577  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
578 
580  if (hostname.isEmpty() ||
581  hostname == "my-unique-identifier-goes-here")
582  {
583  char localhostname[1024];
584  if (gethostname(localhostname, 1024))
585  {
586  LOG(VB_GENERAL, LOG_ALERT,
587  "MCP: Error, could not determine host name." + ENO);
588  localhostname[0] = '\0';
589  }
590 #ifdef Q_OS_ANDROID
591 #define ANDROID_EXCEPTION_CHECK \
592  if (env->ExceptionCheck()) { \
593  env->ExceptionClear(); \
594  exception=true; \
595  }
596  if (strcmp(localhostname, "localhost") == 0
597  || localhostname[0] == '\0')
598  {
599  hostname = "android";
600  bool exception=false;
601  QAndroidJniEnvironment env;
602  QAndroidJniObject myID = QAndroidJniObject::fromString("android_id");
603  QAndroidJniObject activity = QtAndroid::androidActivity();
605  QAndroidJniObject appctx = activity.callObjectMethod
606  ("getApplicationContext","()Landroid/content/Context;");
608  QAndroidJniObject contentR = appctx.callObjectMethod
609  ("getContentResolver", "()Landroid/content/ContentResolver;");
611  QAndroidJniObject androidId = QAndroidJniObject::callStaticObjectMethod
612  ("android/provider/Settings$Secure","getString",
613  "(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;",
614  contentR.object<jobject>(),
615  myID.object<jstring>());
617  if (exception)
618  LOG(VB_GENERAL, LOG_ALERT,
619  "Java exception looking for android id");
620  else
621  hostname = QString("android-%1").arg(androidId.toString());
622  }
623  else
624  hostname = localhostname;
625 #else
626  hostname = localhostname;
627 #endif
628  LOG(VB_GENERAL, LOG_INFO, "Empty LocalHostName. This is typical.");
629  }
630  else
631  {
632  m_DBparams.localEnabled = true;
633  }
634 
635  LOG(VB_GENERAL, LOG_INFO, QString("Using a profile name of: '%1' (Usually the "
636  "same as this host's name.)")
637  .arg(hostname));
639 
640  return ok;
641 }
642 
644  const DatabaseParams &params, bool force)
645 {
646  bool ret = true;
647 
648  // only rewrite file if it has changed
649  if (params != m_DBparams || force)
650  {
652  "LocalHostName", params.localHostName);
653 
655  kDefaultDB + "PingHost", params.dbHostPing);
656 
657  // If dbHostName is an IPV6 address with scope,
658  // remove the scope. Unescaped % signs are an
659  // xml violation
660  QString dbHostName(params.dbHostName);
661  QHostAddress addr;
662  if (addr.setAddress(dbHostName))
663  {
664  addr.setScopeId(QString());
665  dbHostName = addr.toString();
666  }
668  kDefaultDB + "Host", dbHostName);
670  kDefaultDB + "UserName", params.dbUserName);
672  kDefaultDB + "Password", params.dbPassword);
674  kDefaultDB + "DatabaseName", params.dbName);
676  kDefaultDB + "Port", params.dbPort);
677 
679  kDefaultWOL + "Enabled", params.wolEnabled);
681  kDefaultWOL + "SQLReconnectWaitTime", params.wolReconnect);
683  kDefaultWOL + "SQLConnectRetry", params.wolRetry);
685  kDefaultWOL + "Command", params.wolCommand);
686 
687  // clear out any legacy nodes..
688  m_pConfig->ClearValue(kDefaultMFE + "DBHostName");
689  m_pConfig->ClearValue(kDefaultMFE + "DBUserName");
690  m_pConfig->ClearValue(kDefaultMFE + "DBPassword");
691  m_pConfig->ClearValue(kDefaultMFE + "DBName");
692  m_pConfig->ClearValue(kDefaultMFE + "DBPort");
693  m_pConfig->ClearValue(kDefaultMFE + "DBHostPing");
694 
695  // actually save the file
696  m_pConfig->Save();
697 
698  // Save the new settings:
699  m_DBparams = params;
700  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
701 
702  // If database has changed, force its use:
703  ResetDatabase();
704  }
705  return ret;
706 }
707 
709 {
710  if (d && d->m_loop
711  && d->m_loop->isRunning())
712  d->m_loop->exit();
713 }
714 
715 
717 {
718  bool accepted = false;
719  if (m_gui)
720  {
721  TempMainWindow();
722 
723  // Tell the user what went wrong:
724  if (error.length())
726 
727  // ask user for database parameters
728 
729  EnableDBerrors();
731  DatabaseSettings *dbsetting = new DatabaseSettings();
732  StandardSettingDialog *ssd =
733  new StandardSettingDialog(mainStack, "databasesettings",
734  dbsetting);
735  if (ssd->Create())
736  {
737  mainStack->AddScreen(ssd);
738  connect(dbsetting, &DatabaseSettings::isClosing,
740  if (!m_loop->isRunning())
741  m_loop->exec();
742  }
743  else
744  delete ssd;
745  SilenceDBerrors();
746  EndTempWindow();
747  accepted = true;
748  }
749  else
750  {
752  QString response;
753  std::this_thread::sleep_for(std::chrono::seconds(1));
754  // give user chance to skip config
755  cout << endl << error.toLocal8Bit().constData() << endl << endl;
756  response = getResponse("Would you like to configure the database "
757  "connection now?",
758  "no");
759  if (!response.startsWith('y', Qt::CaseInsensitive))
760  return false;
761 
762  params.dbHostName = getResponse("Database host name:",
763  params.dbHostName);
764  response = getResponse("Should I test connectivity to this host "
765  "using the ping command?", "yes");
766  params.dbHostPing = response.startsWith('y', Qt::CaseInsensitive);
767 
768  params.dbPort = intResponse("Database non-default port:",
769  params.dbPort);
770  params.dbName = getResponse("Database name:",
771  params.dbName);
772  params.dbUserName = getResponse("Database user name:",
773  params.dbUserName);
774  params.dbPassword = getResponse("Database password:",
775  params.dbPassword);
776 
777  params.localHostName = getResponse("Unique identifier for this machine "
778  "(if empty, the local host name "
779  "will be used):",
780  params.localHostName);
781  params.localEnabled = !params.localHostName.isEmpty();
782 
783  response = getResponse("Would you like to use Wake-On-LAN to retry "
784  "database connections?",
785  (params.wolEnabled ? "yes" : "no"));
786  params.wolEnabled = response.startsWith('y', Qt::CaseInsensitive);
787 
788  if (params.wolEnabled)
789  {
790  params.wolReconnect = intResponse("Seconds to wait for "
791  "reconnection:",
792  params.wolReconnect);
793  params.wolRetry = intResponse("Number of times to retry:",
794  params.wolRetry);
795  params.wolCommand = getResponse("Command to use to wake server or server MAC address:",
796  params.wolCommand);
797  }
798 
799  accepted = m_parent->SaveDatabaseParams(params);
800  }
801  return accepted;
802 }
803 
810 {
811  QString err;
812  QString host;
813 
814  // Jan 20, 2017
815  // Changed to use port check instead of ping
816 
817  int port = 0;
818 
819  // 1 = db awake, 2 = db listening, 3 = db connects,
820  // 4 = backend awake, 5 = backend listening
821  // 9 = all ok, 10 = quit
822 
823  enum startupStates {
824  st_start = 0,
825  st_dbAwake = 1,
826  st_dbStarted = 2,
827  st_dbConnects = 3,
828  st_beWOL = 4,
829  st_beAwake = 5,
830  st_success = 6
831  } startupState = st_start;
832 
833  static const QString guiStatuses[7] =
834  {"start","dbAwake","dbStarted","dbConnects","beWOL","beAwake",
835  "success" };
836 
837  int msStartupScreenDelay = gCoreContext->GetNumSetting("StartupScreenDelay",2);
838  if (msStartupScreenDelay > 0)
839  msStartupScreenDelay *= 1000;
840  do
841  {
842  QElapsedTimer timer;
843  timer.start();
844  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
845  host = m_DBhostCp;
846  else
847  host = m_DBparams.dbHostName;
848  port = m_DBparams.dbPort;
849  if (port == 0)
850  port = 3306;
851  int wakeupTime = 3;
852  int attempts = 11;
853  if (m_DBparams.wolEnabled) {
854  wakeupTime = m_DBparams.wolReconnect;
855  attempts = m_DBparams.wolRetry + 1;
856  startupState = st_start;
857  }
858  else
859  startupState = st_dbAwake;
860  if (attempts < 6)
861  attempts = 6;
862  if (!prompt)
863  attempts=1;
864  if (wakeupTime < 5)
865  wakeupTime = 5;
866 
867  int progressTotal = wakeupTime * attempts;
868 
870  m_guiStartup->setTotal(progressTotal);
871 
872  QString beWOLCmd = QString();
873  QString backendIP = QString();
874  int backendPort = 0;
875  QString masterserver;
876 
877  for (int attempt = 0;
878  attempt < attempts && startupState != st_success;
879  ++attempt)
880  {
881  // The first time do everything with minimum timeout and
882  // no GUI, for the normal case where all is OK
883  // After that show the GUI (if this is a GUI program)
884 
885  LOG(VB_GENERAL, LOG_INFO,
886  QString("Start up testing connections. DB %1, BE %2, attempt %3, status %4, Delay: %5")
887  .arg(host).arg(backendIP).arg(attempt).arg(guiStatuses[startupState]).arg(msStartupScreenDelay) );
888 
889  int useTimeout = wakeupTime;
890  if (attempt == 0)
891  useTimeout=1;
892 
893  if (m_gui && !m_guiStartup)
894  {
895  if (msStartupScreenDelay==0 || timer.hasExpired(msStartupScreenDelay))
896  {
897  ShowGuiStartup();
898  if (m_guiStartup)
899  m_guiStartup->setTotal(progressTotal);
900  }
901  }
903  {
904  if (attempt > 0)
905  m_guiStartup->setStatusState(guiStatuses[startupState]);
906  m_guiStartup->setMessageState("empty");
907  processEvents();
908  }
909  switch (startupState) {
910  case st_start:
912  {
913  if (attempt > 0)
915  if (!checkPort(host, port, useTimeout))
916  break;
917  }
918  startupState = st_dbAwake;
919  [[clang::fallthrough]];
920  case st_dbAwake:
921  if (!checkPort(host, port, useTimeout))
922  break;
923  startupState = st_dbStarted;
924  [[clang::fallthrough]];
925  case st_dbStarted:
926  // If the database is connecting with link-local
927  // address, it may have changed
928  if (m_DBparams.dbHostName != host)
929  {
930  m_DBparams.dbHostName = host;
931  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
932  }
933  EnableDBerrors();
934  ResetDatabase();
936  {
937  for (int temp = 0; temp < useTimeout * 2 ; temp++)
938  {
939  processEvents();
940  std::this_thread::sleep_for(std::chrono::milliseconds(500));
941  }
942  break;
943  }
944  startupState = st_dbConnects;
945  [[clang::fallthrough]];
946  case st_dbConnects:
947  if (m_needsBackend)
948  {
949  beWOLCmd = gCoreContext->GetSetting("WOLbackendCommand", "");
950  if (!beWOLCmd.isEmpty())
951  {
952  wakeupTime += gCoreContext->GetNumSetting
953  ("WOLbackendReconnectWaitTime", 0);
954  attempts += gCoreContext->GetNumSetting
955  ("WOLbackendConnectRetry", 0);
956  useTimeout = wakeupTime;
957  if (m_gui && !m_guiStartup && attempt == 0)
958  useTimeout=1;
959  progressTotal = wakeupTime * attempts;
961  m_guiStartup->setTotal(progressTotal);
962  startupState = st_beWOL;
963  }
964  }
965  else {
966  startupState = st_success;
967  break;
968  }
969  masterserver = gCoreContext->GetSetting
970  ("MasterServerName");
971  backendIP = gCoreContext->GetSettingOnHost
972  ("BackendServerAddr", masterserver);
973  backendPort = gCoreContext->GetMasterServerPort();
974  [[clang::fallthrough]];
975  case st_beWOL:
976  if (!beWOLCmd.isEmpty()) {
977  if (attempt > 0)
978  MythWakeup(beWOLCmd);
979  if (!checkPort(backendIP, backendPort, useTimeout))
980  break;
981  }
982  startupState = st_beAwake;
983  [[clang::fallthrough]];
984  case st_beAwake:
985  if (!checkPort(backendIP, backendPort, useTimeout))
986  break;
987  startupState = st_success;
988  [[clang::fallthrough]];
989  case st_success:
990  // Quiet compiler warning.
991  break;
992  }
993  if (m_guiStartup)
994  {
995  if (m_guiStartup->m_Exit
998  || m_guiStartup->m_Retry)
999  break;
1000  }
1001  processEvents();
1002  }
1003  if (startupState == st_success)
1004  break;
1005 
1006  QString stateMsg = guiStatuses[startupState];
1007  stateMsg.append("Fail");
1008  LOG(VB_GENERAL, LOG_INFO,
1009  QString("Start up failure. host %1, status %2")
1010  .arg(host).arg(stateMsg));
1011 
1012  if (m_gui && !m_guiStartup)
1013  {
1014  ShowGuiStartup();
1015  if (m_guiStartup)
1016  m_guiStartup->setTotal(progressTotal);
1017  }
1018 
1019  if (m_guiStartup
1020  && !m_guiStartup->m_Exit
1021  && !m_guiStartup->m_Setup
1022  && !m_guiStartup->m_Search
1023  && !m_guiStartup->m_Retry)
1024  {
1026  m_guiStartup->setStatusState(stateMsg);
1027  m_guiStartup->setMessageState("makeselection");
1028  m_loop->exec();
1029  }
1030  }
1031  while (m_guiStartup && m_guiStartup->m_Retry);
1032 
1033  if (startupState < st_dbAwake)
1034  {
1035  LOG(VB_GENERAL, LOG_WARNING, QString("Pinging to %1 failed, database will be unavailable").arg(host));
1036  SilenceDBerrors();
1037  err = QObject::tr(
1038  "Cannot find (ping) database host %1 on the network",
1039  "Backend Setup");
1040  return err.arg(host);
1041  }
1042 
1043  if (startupState < st_dbConnects)
1044  {
1045  SilenceDBerrors();
1046  return QObject::tr("Cannot login to database", "Backend Setup");
1047  }
1048 
1049  if (startupState < st_success)
1050  {
1051  return QObject::tr("Cannot connect to backend", "Backend Setup");
1052  }
1053 
1054  // Current DB connection may have been silenced (invalid):
1055  EnableDBerrors();
1056  ResetDatabase();
1057 
1058  return QString();
1059 }
1060 
1061 // Show the Gui Startup window.
1062 // This is called if there is a delay in startup for any reason
1063 // such as the database being unavailable
1065 {
1066  if (!m_gui)
1067  return;
1068  TempMainWindow(false);
1069  MythMainWindow *mainWindow = GetMythMainWindow();
1070  MythScreenStack *mainStack = mainWindow->GetMainStack();
1071  if (mainStack) {
1072  if (!m_guiStartup) {
1073  m_guiStartup = new GUIStartup(mainStack,m_loop);
1074  if (!m_guiStartup->Create()) {
1075  delete m_guiStartup;
1076  m_guiStartup = nullptr;
1077  }
1078  if (m_guiStartup) {
1079  mainStack->AddScreen(m_guiStartup, false);
1080  processEvents();
1081  }
1082  }
1083  }
1084 }
1085 
1095 {
1096  // This silences any DB errors from Get*Setting(),
1097  // (which is the vast majority of them)
1098  gCoreContext->GetDB()->SetSuppressDBMessages(true);
1099 
1100  // Save the configured hostname, so that we can
1101  // still display it in the DatabaseSettings screens
1102  if (m_DBparams.dbHostName.length())
1104 
1105  m_DBparams.dbHostName.clear();
1106  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1107 }
1108 
1110 {
1111  // Restore (possibly) blanked hostname
1112  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
1113  {
1115  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1116  }
1117 
1118  gCoreContext->GetDB()->SetSuppressDBMessages(false);
1119 }
1120 
1121 
1134 {
1136  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1138 }
1139 
1144 {
1145  TempMainWindow();
1146 
1147  // Tell the user what went wrong:
1148  if (!error.isEmpty())
1149  {
1150  LOG(VB_GENERAL, LOG_ERR, QString("Error: %1").arg(error));
1151  ShowOkPopup(error);
1152  }
1153 
1154  LOG(VB_GENERAL, LOG_INFO, "Putting up the UPnP backend chooser");
1155 
1158 
1159  EndTempWindow();
1160 
1161  return (int)ret;
1162 }
1163 
1170 int MythContextPrivate::UPnPautoconf(const int milliSeconds)
1171 {
1172  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1173  .arg(milliSeconds / 1000));
1174 
1175  SSDP::Instance()->PerformSearch(gBackendURI, milliSeconds / 1000);
1176 
1177  // Search for a total of 'milliSeconds' ms, sending new search packet
1178  // about every 250 ms until less than one second remains.
1179  MythTimer totalTime; totalTime.start();
1180  MythTimer searchTime; searchTime.start();
1181  while (totalTime.elapsed() < milliSeconds)
1182  {
1183  usleep(25000);
1184  int ttl = milliSeconds - totalTime.elapsed();
1185  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1186  {
1187  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1188  .arg(ttl / 1000));
1189  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1190  searchTime.start();
1191  }
1192  }
1193 
1195 
1196  if (!backends)
1197  {
1198  LOG(VB_GENERAL, LOG_INFO, "No UPnP backends found");
1199  return 0;
1200  }
1201 
1202  int count = backends->Count();
1203  if (count)
1204  {
1205  LOG(VB_GENERAL, LOG_INFO,
1206  QString("Found %1 UPnP backends").arg(count));
1207  }
1208  else
1209  {
1210  LOG(VB_GENERAL, LOG_ERR,
1211  "No UPnP backends found, but SSDP::Find() not NULL");
1212  }
1213 
1214  if (count != 1)
1215  {
1216  backends->DecrRef();
1217  return count;
1218  }
1219 
1220  // Get this backend's location:
1221  DeviceLocation *BE = backends->GetFirst();
1222  backends->DecrRef();
1223  backends = nullptr;
1224 
1225  // We don't actually know the backend's access PIN, so this will
1226  // only work for ones that have PIN access disabled (i.e. 0000)
1227  int ret = (UPnPconnect(BE, QString())) ? 1 : -1;
1228 
1229  BE->DecrRef();
1230 
1231  return ret;
1232 }
1233 
1240 {
1241  QString loc = "DefaultUPnP() - ";
1242  QString PIN = m_pConfig->GetValue(kDefaultPIN, "");
1243  QString USN = m_pConfig->GetValue(kDefaultUSN, "");
1244 
1245  if (USN.isEmpty())
1246  {
1247  LOG(VB_UPNP, LOG_INFO, loc + "No default UPnP backend");
1248  return false;
1249  }
1250 
1251  LOG(VB_UPNP, LOG_INFO, loc + "config.xml has default " +
1252  QString("PIN '%1' and host USN: %2") .arg(PIN).arg(USN));
1253 
1254  // ----------------------------------------------------------------------
1255 
1256  int timeout_ms = 2000;
1257  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1258  .arg(timeout_ms / 1000));
1259  SSDP::Instance()->PerformSearch(gBackendURI, timeout_ms / 1000);
1260 
1261  // ----------------------------------------------------------------------
1262  // We need to give the server time to respond...
1263  // ----------------------------------------------------------------------
1264 
1265  DeviceLocation *pDevLoc = nullptr;
1266  MythTimer totalTime; totalTime.start();
1267  MythTimer searchTime; searchTime.start();
1268  while (totalTime.elapsed() < timeout_ms)
1269  {
1270  pDevLoc = SSDP::Find( gBackendURI, USN );
1271 
1272  if (pDevLoc)
1273  break;
1274 
1275  usleep(25000);
1276 
1277  int ttl = timeout_ms - totalTime.elapsed();
1278  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1279  {
1280  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1281  .arg(ttl / 1000));
1282  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1283  searchTime.start();
1284  }
1285  }
1286 
1287  // ----------------------------------------------------------------------
1288 
1289  if (!pDevLoc)
1290  {
1291  error = "Cannot find default UPnP backend";
1292  return false;
1293  }
1294 
1295  if (UPnPconnect(pDevLoc, PIN))
1296  {
1297  pDevLoc->DecrRef();
1298  return true;
1299  }
1300 
1301  pDevLoc->DecrRef();
1302 
1303  error = "Cannot connect to default backend via UPnP. Wrong saved PIN?";
1304  return false;
1305 }
1306 
1311  const QString &PIN)
1312 {
1313  QString error;
1314  QString loc = "UPnPconnect() - ";
1315  QString URL = backend->m_sLocation;
1316  MythXMLClient client(URL);
1317 
1318  LOG(VB_UPNP, LOG_INFO, loc + QString("Trying host at %1").arg(URL));
1319  switch (client.GetConnectionInfo(PIN, &m_DBparams, error))
1320  {
1321  case UPnPResult_Success:
1322  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1323  LOG(VB_UPNP, LOG_INFO, loc +
1324  "Got database hostname: " + m_DBparams.dbHostName);
1325  return true;
1326 
1328  // The stored PIN is probably not correct.
1329  // We could prompt for the PIN and try again, but that needs a UI.
1330  // Easier to fail for now, and put up the full UI selector later
1331  LOG(VB_UPNP, LOG_ERR, loc + "Wrong PIN?");
1332  return false;
1333 
1334  default:
1335  LOG(VB_UPNP, LOG_ERR, loc + error);
1336  break;
1337  }
1338 
1339  // This backend may have a local DB with the default user/pass/DBname.
1340  // For whatever reason, we have failed to get anything back via UPnP,
1341  // so we might as well try the database directly as a last resort.
1342  QUrl theURL(URL);
1343  URL = theURL.host();
1344  if (URL.isEmpty())
1345  return false;
1346 
1347  LOG(VB_UPNP, LOG_INFO, "Trying default DB credentials at " + URL);
1349 
1350  return true;
1351 }
1352 
1354 {
1355  if (e->type() == MythEvent::MythEventMessage)
1356  {
1357  if (m_disableeventpopup)
1358  return true;
1359 
1361  {
1363  }
1364 
1365  MythEvent *me = static_cast<MythEvent*>(e);
1366  if (me->Message() == "VERSION_MISMATCH" && (1 == me->ExtraDataCount()))
1367  ShowVersionMismatchPopup(me->ExtraData(0).toUInt());
1368  else if (me->Message() == "CONNECTION_FAILURE")
1370  else if (me->Message() == "PERSISTENT_CONNECTION_FAILURE")
1372  else if (me->Message() == "CONNECTION_RESTABLISHED")
1374  return true;
1375  }
1376 
1377  return QObject::event(e);
1378 }
1379 
1381 {
1382  QDateTime now = MythDate::current();
1383 
1384  if (!GetNotificationCenter() || !m_ui || !m_ui->IsScreenSetup())
1385  return;
1386 
1387  if (m_lastCheck.isValid() && now < m_lastCheck)
1388  return;
1389 
1390  // When WOL is disallowed, standy mode,
1391  // we should not show connection failures.
1392  if (!gCoreContext->IsWOLAllowed())
1393  return;
1394 
1395  m_lastCheck = now.addMSecs(5000); // don't refresh notification more than every 5s
1396 
1397  QString description = (persistent) ?
1398  QObject::tr(
1399  "The connection to the master backend "
1400  "server has gone away for some reason. "
1401  "Is it running?") :
1402  QObject::tr(
1403  "Could not connect to the master backend server. Is "
1404  "it running? Is the IP address set for it in "
1405  "mythtv-setup correct?");
1406 
1407  QString message = QObject::tr("Could not connect to master backend");
1408  MythErrorNotification n(message, _Location, description);
1409  n.SetId(m_registration);
1410  n.SetParent(this);
1412 }
1413 
1415 {
1416  if (!GetNotificationCenter())
1417  return;
1418 
1419  if (!m_lastCheck.isValid())
1420  return;
1421 
1422  MythCheckNotification n(QObject::tr("Backend is online"), _Location);
1423  n.SetId(m_registration);
1424  n.SetParent(this);
1425  n.SetDuration(5);
1427  m_lastCheck = QDateTime();
1428 }
1429 
1431 {
1432  if (m_MBEversionPopup)
1433  return;
1434 
1435  QString message =
1436  QObject::tr(
1437  "The server uses network protocol version %1, "
1438  "but this client only understands version %2. "
1439  "Make sure you are running compatible versions of "
1440  "the backend and frontend.")
1441  .arg(remote_version).arg(MYTH_PROTO_VERSION);
1442 
1443  if (HasMythMainWindow() && m_ui && m_ui->IsScreenSetup())
1444  {
1446  message, m_sh, SLOT(VersionMismatchPopupClosed()));
1447  }
1448  else
1449  {
1450  LOG(VB_GENERAL, LOG_ERR, LOC + message);
1451  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1452  }
1453 }
1454 
1455 // Process Events while waiting for connection
1456 // return true if progress is 100%
1458 {
1459 // bool ret = false;
1460 // if (m_guiStartup)
1461 // ret = m_guiStartup->updateProgress();
1462  qApp->processEvents(QEventLoop::AllEvents, 250);
1463  qApp->processEvents(QEventLoop::AllEvents, 250);
1464 // return ret;
1465 }
1466 
1467 // cache some settings in cache/contextcache.xml
1468 // only call this if the database is available.
1469 
1470 const QString MythContextPrivate::s_settingsToSave[] =
1471 { "Theme", "Language", "Country", "GuiHeight",
1472  "GuiOffsetX", "GuiOffsetY", "GuiWidth", "RunFrontendInWindow",
1473  "AlwaysOnTop", "HideMouseCursor", "ThemePainter", "libCECEnabled",
1474  "StartupScreenDelay" };
1475 
1476 
1478 {
1479  if (!m_gui)
1480  return true;
1481  QString cacheDirName = GetConfDir() + "/cache/";
1482  QDir dir(cacheDirName);
1483  dir.mkpath(cacheDirName);
1484  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1485  static const int arraySize = sizeof(s_settingsToSave)/sizeof(s_settingsToSave[0]);
1486  for (int ix = 0; ix < arraySize; ix++)
1487  {
1488  QString cacheValue = config.GetValue("Settings/"+s_settingsToSave[ix],QString());
1490  QString value = gCoreContext->GetSetting(s_settingsToSave[ix],QString());
1491  if (value != cacheValue)
1492  {
1493  config.SetValue("Settings/"+s_settingsToSave[ix],value);
1494  m_settingsCacheDirty = true;
1495  }
1496  }
1498  return config.Save();
1499 }
1500 
1502 {
1503  if (!m_gui)
1504  return;
1505  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1506  static const int arraySize = sizeof(s_settingsToSave)/sizeof(s_settingsToSave[0]);
1507  for (int ix = 0; ix < arraySize; ix++)
1508  {
1509  if (!gCoreContext->GetSetting(s_settingsToSave[ix],QString()).isEmpty())
1510  continue;
1511  QString value = config.GetValue("Settings/"+s_settingsToSave[ix],QString());
1512  if (!value.isEmpty())
1514  }
1515  // Prevent power off TV after temporary window
1516  gCoreContext->OverrideSettingForSession("PowerOffTVAllowed", nullptr);
1517 
1518  QString language = gCoreContext->GetSetting("Language",QString());
1519  MythTranslation::load("mythfrontend");
1520 }
1521 
1523 {
1524  QString language = gCoreContext->GetSetting("Language",QString());
1525  static const int arraySize = sizeof(s_settingsToSave)/sizeof(s_settingsToSave[0]);
1526  for (int ix = 0; ix < arraySize; ix++)
1527  {
1529  }
1530  // Restore power off TV setting
1531  gCoreContext->ClearOverrideSettingForSession("PowerOffTVAllowed");
1532 
1533  if (language != gCoreContext->GetSetting("Language",QString()))
1534  MythTranslation::load("mythfrontend");
1535 }
1536 
1537 
1539 {
1540  d->m_MBEversionPopup = nullptr;
1541  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1542 }
1543 
1544 MythContext::MythContext(const QString &binversion, bool needsBackend)
1545  : m_app_binary_version(binversion)
1546 {
1547 #ifdef _WIN32
1548  static bool WSAStarted = false;
1549  if (!WSAStarted) {
1550  WSADATA wsadata;
1551  int res = WSAStartup(MAKEWORD(2, 0), &wsadata);
1552  LOG(VB_SOCKET, LOG_INFO,
1553  QString("WSAStartup returned %1").arg(res));
1554  }
1555 #endif
1556 
1557  d = new MythContextPrivate(this);
1558  d->m_needsBackend = needsBackend;
1559 
1561 
1562  if (!gCoreContext || !gCoreContext->Init())
1563  {
1564  LOG(VB_GENERAL, LOG_EMERG, LOC + "Unable to allocate MythCoreContext");
1565  qApp->exit(GENERIC_EXIT_NO_MYTHCONTEXT);
1566  }
1567 }
1568 
1569 bool MythContext::Init(const bool gui,
1570  const bool promptForBackend,
1571  const bool disableAutoDiscovery,
1572  const bool ignoreDB)
1573 {
1574  if (!d)
1575  {
1576  LOG(VB_GENERAL, LOG_EMERG, LOC + "Init() Out-of-memory");
1577  return false;
1578  }
1579 
1580  SetDisableEventPopup(true);
1581 
1583  {
1584  LOG(VB_GENERAL, LOG_EMERG,
1585  QString("Application binary version (%1) does not "
1586  "match libraries (%2)")
1588 
1589  QString warning = QObject::tr(
1590  "This application is not compatible "
1591  "with the installed MythTV libraries.");
1592  if (gui)
1593  {
1594  d->TempMainWindow(false);
1595  ShowOkPopup(warning);
1596  }
1597  LOG(VB_GENERAL, LOG_WARNING, warning);
1598 
1599  return false;
1600  }
1601 
1602 #ifdef _WIN32
1603  // HOME environment variable might not be defined
1604  // some libraries will fail without it
1605  QString home = getenv("HOME");
1606  if (home.isEmpty())
1607  {
1608  home = getenv("LOCALAPPDATA"); // Vista
1609  if (home.isEmpty())
1610  home = getenv("APPDATA"); // XP
1611  if (home.isEmpty())
1612  home = QString("."); // getenv("TEMP")?
1613 
1614  _putenv(QString("HOME=%1").arg(home).toLocal8Bit().constData());
1615  }
1616 #endif
1617 
1618  // If HOME isn't defined, we won't be able to use default confdir of
1619  // $HOME/.mythtv nor can we rely on a MYTHCONFDIR that references $HOME
1620  QString homedir = QDir::homePath();
1621  QString confdir = getenv("MYTHCONFDIR");
1622  if ((homedir.isEmpty() || homedir == "/") &&
1623  (confdir.isEmpty() || confdir.contains("$HOME")))
1624  {
1625  QString warning = "Cannot locate your home directory."
1626  " Please set the environment variable HOME";
1627  if (gui)
1628  {
1629  d->TempMainWindow(false);
1630  ShowOkPopup(warning);
1631  }
1632  LOG(VB_GENERAL, LOG_WARNING, warning);
1633 
1634  return false;
1635  }
1636 
1637  if (!d->Init(gui, promptForBackend, disableAutoDiscovery, ignoreDB))
1638  {
1639  return false;
1640  }
1641 
1642  SetDisableEventPopup(false);
1644  if (d->m_settingsCacheDirty)
1645  {
1646 #ifndef Q_OS_ANDROID
1648 #endif
1649  d->m_settingsCacheDirty = false;
1650  }
1652 
1653  return true;
1654 }
1655 
1657 {
1658  if (MThreadPool::globalInstance()->activeThreadCount())
1659  LOG(VB_GENERAL, LOG_INFO, "Waiting for threads to exit.");
1660 
1662  logStop();
1663 
1664  SSDP::Shutdown();
1666 
1667  delete gCoreContext;
1668  gCoreContext = nullptr;
1669 
1670  delete d;
1671 }
1672 
1674 {
1675  d->m_disableeventpopup = check;
1676 }
1677 
1679 {
1680  return d->m_DBparams;
1681 }
1682 
1684 {
1685  return d->SaveDatabaseParams(params, false);
1686 }
1687 
1689 {
1690  return d->saveSettingsCache();
1691 }
1692 
1693 /* vim: set expandtab tabstop=4 shiftwidth=4: */
void SaveLocaleDefaults(void)
void ShowGuiStartup(void)
Startup context for MythTV.
Definition: mythcontext.h:42
void SetParent(void *parent)
contains the parent address.
bool wolEnabled
true if wake-on-lan params are used
Definition: mythdbparams.h:33
virtual int GetValue(const QString &sSetting, int Default)=0
bool setStatusState(const QString &name)
Definition: guistartup.cpp:107
int intResponse(const QString &query, int def)
In an interactive shell, prompt the user to input a number.
unsigned int slots[4]
Definition: element.c:38
A QElapsedTimer based timer to replace use of QTime as a timer.
Definition: mythtimer.h:13
QString wolCommand
command to use for wake-on-lan
Definition: mythdbparams.h:36
static void configplugin_cb(const QString &cmd)
QString dbName
database name
Definition: mythdbparams.h:26
void LoadQtConfig(void)
Dialog asking for user confirmation.
void EndTempWindow(void)
MythConfirmationDialog * ShowOkPopup(const QString &message, QObject *parent, const char *slot, bool showCancel)
Non-blocking version of MythPopupBox::showOkPopup()
virtual void ClearValue(const QString &sSetting)=0
void SetId(int id)
Optional MythNotification elements.
bool setMessageState(const QString &name)
Definition: guistartup.cpp:117
static void exec_program_tv_cb(const QString &cmd)
const QString kDefaultWOL
Definition: backendselect.h:23
static Type MythEventMessage
Definition: mythevent.h:66
static void error(const char *str,...)
Definition: vbi.c:42
int GetMasterServerPort(void)
Returns the Master Backend control port If no master server port has been defined in the database,...
static void ejectOpticalDisc(void)
Eject a disk, unmount a drive, open a tray.
static MythMainWindow * getMainWindow(const bool useDB=true)
Return the existing main window, or create one.
const QString gBackendURI
Service type for the backend's UPnP server.
Definition: backendselect.h:21
void isClosing(void)
static const char URL[]
Definition: cddb.cpp:29
bool m_Retry
Definition: guistartup.h:56
void UnRegister(void *from, int id, bool closeimemdiately=false)
Unregister the client.
MythConfirmationDialog * m_MBEversionPopup
bool IsFrontend(void) const
is this process a frontend process
QString GetSettingOnHost(const QString &key, const QString &host, const QString &defaultval="")
bool SaveDatabaseParams(const DatabaseParams &params, bool force)
void DestroyMythMainWindow(void)
bool MythWakeup(const QString &wakeUpCommand, uint flags, uint timeout)
void SetDisableEventPopup(bool check)
bool IsScreenSetup(void)
unsigned int uint
Definition: compat.h:140
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
static Decision Prompt(DatabaseParams *dbParams, Configuration *pConfig)
MythScreenStack * GetMainStack()
DatabaseParams GetDatabaseParams(void)
bool saveSettingsCache(void)
void waitForDone(void)
bool localEnabled
true if localHostName is not default
Definition: mythdbparams.h:29
MythContext * gContext
This global variable contains the MythContext instance for the application.
Definition: mythcontext.cpp:63
#define ANDROID_EXCEPTION_CHECK
void ShowVersionMismatchPopup(uint remote_version)
void DestroyMythUI()
void Init(const QString &forcedpainter=QString(), bool mayReInit=true)
void SetLocalHostname(const QString &hostname)
const QString kDefaultDB
Definition: backendselect.h:22
void(* exec_program)(const QString &cmd)
Definition: mythuihelper.h:34
~MythContextPrivate() override
QString dbPassword
DB password.
Definition: mythdbparams.h:25
bool checkPort(QString &host, int port, int timeLimit=30000, bool linkLocalOnly=false)
Check if a port is open and sort out the link-local scope.
Definition: portchecker.cpp:73
QString GetConfDir(void)
Definition: mythdirs.cpp:224
static void Shutdown()
Definition: taskqueue.cpp:68
void Init(MythUIMenuCallbacks &cbs)
MythContextPrivate(MythContext *lparent)
static void eject_cb(void)
bool config_plugin(const QString &plugname)
Definition: mythplugin.cpp:184
bool SendReceiveStringList(QStringList &strlist, bool quickTimeout=false, bool block=true)
Send a message to the backend and wait for a response.
int UPnPautoconf(int milliSeconds=2000)
If there is only a single UPnP backend, use it.
virtual void AddScreen(MythScreenType *screen, bool allowFade=true)
MythContextSlotHandler * m_sh
QString dbUserName
DB user name.
Definition: mythdbparams.h:24
DeviceLocation * GetFirst(void)
Returns random entry in cache, returns nullptr when list is empty.
Definition: ssdpcache.cpp:73
static void plugin_cb(const QString &cmd)
void PerformSearch(const QString &sST, uint timeout_secs=2)
Definition: ssdp.cpp:206
MythPluginManager * GetPluginManager(void)
This class is used as a container for messages.
Definition: mythevent.h:16
void ClearOverrideSettingForSession(const QString &key)
void EnableDBerrors(void)
void VersionMismatchPopupClosed(void)
int ChooseBackend(const QString &error)
Search for backends via UPnP, put up a UI for the user to choose one.
QString TestDBconnection(bool prompt=true)
Some quick sanity checks before opening a database connection.
uint Count(void) const
Definition: ssdpcache.h:44
QString m_app_binary_version
Definition: mythcontext.h:61
void setTotal(int total)
Definition: guistartup.cpp:128
virtual bool GetBoolValue(const QString &sSetting, bool Default)=0
bool PromptForDatabaseParams(const QString &error)
MythContext * m_parent
static const uint16_t * d
void OverrideSettingForSession(const QString &key, const QString &value)
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:10
QString GetSetting(const QString &key, const QString &defaultval="")
DatabaseParams m_DBparams
Current database host & WOL details.
MythContext(const QString &binversion, bool needsBackend=false)
void SetDuration(int duration)
contains a duration during which the notification will be displayed for.
bool UPnPconnect(const DeviceLocation *backend, const QString &PIN)
Query a backend via UPnP for its database connection parameters.
bool m_Setup
Definition: guistartup.h:55
#define GENERIC_EXIT_SOCKET_ERROR
Socket error.
Definition: exitcodes.h:18
virtual int DecrRef(void)
Decrements reference count and deletes on 0.
virtual bool Save(void)=0
bool updateProgress(bool finished=false)
Definition: guistartup.cpp:144
QEventLoop * m_loop
MythContextPrivate * d
Definition: mythcontext.h:60
static void load(const QString &module_name)
Load a QTranslator for the user's preferred language.
void ShowNotificationError(const QString &msg, const QString &from, const QString &detail, const VNMask visibility, const MythNotification::Priority priority)
convenience utility to display error message as notification
#define MYTH_PROTO_VERSION
Increment this whenever the MythTV network protocol changes.
Definition: mythversion.h:48
Small class to handle TCP port checking and finding link-local context.
Definition: portchecker.h:43
static bool testDBConnection()
Checks DB connection + login (login info via Mythcontext)
Definition: mythdbcon.cpp:851
void(* configplugin)(const QString &cmd)
Definition: mythuihelper.h:36
static const QString s_settingsToSave[]
bool Queue(const MythNotification &notification)
Queue a notification Queue() is thread-safe and can be called from anywhere.
bool dbHostPing
Can we test connectivity using ping?
Definition: mythdbparams.h:22
string hostname
Definition: caa.py:17
void TempMainWindow(bool languagePrompt=true)
Setup a minimal themed main window, and prompt for user's language.
QString m_masterhostname
master backend hostname
QString m_DBhostCp
dbHostName backup
QString getResponse(const QString &query, const QString &def)
In an interactive shell, prompt the user to input a string.
static bool prompt(bool force=false)
Ask the user for the language to use.
uint myth_system(const QString &command, uint flags, uint timeout)
#define ENO
This can be appended to the LOG args with "+".
Definition: mythlogging.h:99
bool Save(void) override
static const QString _Location
Definition: mythcontext.cpp:65
bool LoadDatabaseSettings(void)
Load database and host settings from config.xml, or set some defaults.
bool IsValid(const QString &source=QString("Unknown")) const
MythUIHelper * GetMythUI()
void SilenceDBerrors(void)
Cause MSqlDatabase::OpenDatabase() and MSqlQuery to fail silently.
int wolReconnect
seconds to wait for reconnect
Definition: mythdbparams.h:34
bool HasMythMainWindow(void)
MythMainWindow * GetMythMainWindow(void)
void clearSettingsCacheOverride(void)
int elapsed(void) const
Returns milliseconds elapsed since last start() or restart()
Definition: mythtimer.cpp:90
bool m_Exit
Definition: guistartup.h:54
static MThreadPool * globalInstance(void)
static void exec_program_cb(const QString &cmd)
bool SaveDatabaseParams(const DatabaseParams &params)
int Register(void *from)
An application can register in which case it will be assigned a reusable screen, which can be modifie...
int GetNumSetting(const QString &key, int defaultval=0)
Structure containing the basic Database parameters.
Definition: mythdbparams.h:9
QString m_sLocation
Definition: upnpdevice.h:230
bool Create(void) override
Definition: guistartup.cpp:67
#define LOG(_MASK_, _LEVEL_, _STRING_)
Definition: mythlogging.h:41
QString dbHostName
database server
Definition: mythdbparams.h:21
bool Create(void) override
void LoadDefaults(void)
Load sensible connection defaults.
Definition: mythdbparams.cpp:9
static SSDP * Instance()
Definition: ssdp.cpp:54
bool forceSave
set to true to force a save of the settings file
Definition: mythdbparams.h:39
int GetValue(const QString &sSetting, int Default) override
const QString & ExtraData(int idx=0) const
Definition: mythevent.h:59
virtual void PopScreen(MythScreenType *screen=nullptr, bool allowFade=true, bool deleteScreen=true)
virtual void SetBoolValue(const QString &sSetting, bool value)=0
void(* eject)(void)
Definition: mythuihelper.h:38
void logStop(void)
Entry point for stopping logging for an application.
Definition: logging.cpp:753
bool checkPort(QString &host, int port, int timeLimit)
Check if a port is open and sort out the link-local scope.
MythContextPrivate * d
Definition: mythcontext.h:30
Configuration * m_pConfig
UPnPResultCode GetConnectionInfo(const QString &sPin, DatabaseParams *pParams, QString &sMsg)
void(* plugin)(const QString &cmd)
Definition: mythuihelper.h:37
const QString kDefaultPIN
Definition: backendselect.h:25
void ClearSettingsCache(const QString &myKey=QString(""))
#define MYTH_BINARY_VERSION
Update this whenever the plug-in ABI changes.
Definition: mythversion.h:16
bool IsWOLAllowed() const
bool saveSettingsCache(void)
MythDB * GetDB(void)
MDBManager * GetDBManager(void)
void loadSettingsCacheOverride(void)
bool event(QEvent *) override
void HideConnectionFailurePopup(void)
bool Init(const bool gui=true, const bool promptForBackend=false, const bool disableAutoDiscovery=false, const bool ignoreDB=false)
const QString kDefaultUSN
Definition: backendselect.h:26
int ExtraDataCount() const
Definition: mythevent.h:61
bool m_Search
Definition: guistartup.h:57
MythUIHelper * m_ui
bool Init(bool gui, bool prompt, bool noPrompt, bool ignoreDB)
static SSDPCacheEntries * Find(const QString &sURI)
Definition: ssdp.h:129
const QString kDefaultMFE
Definition: backendselect.h:24
#define GENERIC_EXIT_NO_MYTHCONTEXT
No MythContext available.
Definition: exitcodes.h:13
void(* exec_program_tv)(const QString &cmd)
Definition: mythuihelper.h:35
void ResetDatabase(void)
Called when the user changes the DB connection settings.
const QString & Message() const
Definition: mythevent.h:58
QString localHostName
name used for loading/saving settings
Definition: mythdbparams.h:30
void ActivateSettingsCache(bool activate=true)
int dbPort
database port
Definition: mythdbparams.h:23
void processEvents(void)
GUIStartup * m_guiStartup
void ShowConnectionFailurePopup(bool persistent)
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:30
void start(void)
starts measuring elapsed time.
Definition: mythtimer.cpp:47
void CloseDatabases(void)
Definition: mythdbcon.cpp:468
virtual ~MythContext()
int wolRetry
times to retry to reconnect
Definition: mythdbparams.h:35
bool DefaultUPnP(QString &error)
Get the default backend from config.xml, use UPnP to find it.
static QString confdir
Definition: mythdirs.cpp:20
This class contains the runtime context for MythTV.
void SetValue(const QString &sSetting, int value) override
static void Shutdown()
Definition: ssdp.cpp:64
#define LOC
Definition: mythcontext.cpp:61
MythNotificationCenter * GetNotificationCenter(void)
bool run_plugin(const QString &plugname)
Definition: mythplugin.cpp:166
void InitializeMythDirs(void)
Definition: mythdirs.cpp:30
virtual void SetValue(const QString &sSetting, int value)=0
bool FindDatabase(bool prompt, bool noAutodetect)
Get database connection settings and test connectivity.
bool m_gui
Should this context use GUI elements?