MythTV  master
mythbackend_main_helpers.cpp
Go to the documentation of this file.
1 #include "libmythbase/mythconfig.h"
2 #if CONFIG_SYSTEMD_NOTIFY
3 #include <systemd/sd-daemon.h>
4 static inline void be_sd_notify(const char *str) { sd_notify(0, str); };
5 #else
6 static inline void be_sd_notify(const char */*str*/) {};
7 #endif
8 
9 // C++ headers
10 #include <cerrno>
11 #include <csignal>
12 #include <cstdlib>
13 #include <fcntl.h>
14 #include <sys/stat.h>
15 #include <sys/time.h> // for setpriority
16 #include <sys/types.h>
17 #include <unistd.h>
18 
19 // Qt
20 #include <QCoreApplication>
21 #include <QFileInfo>
22 #include <QFile>
23 #include <QDir>
24 #include <QMap>
25 
26 // MythTV
27 #include "libmythbase/compat.h"
28 #include "libmythbase/dbutil.h"
29 #include "libmythbase/exitcodes.h"
32 #include "libmythbase/mythdb.h"
36 #include "libmythbase/mythversion.h"
38 #include "libmythbase/remoteutil.h"
40 #include "libmythtv/dbcheck.h"
41 #include "libmythtv/eitcache.h"
42 #include "libmythtv/jobqueue.h"
46 #include "libmythtv/tv_rec.h"
47 
48 // MythBackend
49 #include "autoexpire.h"
50 #include "backendcontext.h"
51 #include "backendhousekeeper.h"
52 #include "encoderlink.h"
53 #include "httpstatus.h"
54 #include "mainserver.h"
55 #include "mediaserver.h"
58 #include "scheduler.h"
59 
60 // New webserver
64 #include "servicesv2/v2myth.h"
65 #include "servicesv2/v2video.h"
66 #include "servicesv2/v2dvr.h"
67 #include "servicesv2/v2content.h"
68 #include "servicesv2/v2guide.h"
69 #include "servicesv2/v2channel.h"
70 #include "servicesv2/v2status.h"
71 #include "servicesv2/v2capture.h"
72 #include "servicesv2/v2music.h"
73 #include "servicesv2/v2config.h"
74 
75 #define LOC QString("MythBackend: ")
76 #define LOC_WARN QString("MythBackend, Warning: ")
77 #define LOC_ERR QString("MythBackend, Error: ")
78 
79 static HouseKeeper *gHousekeeping { nullptr };
80 static JobQueue *gJobQueue { nullptr };
82 static MediaServer *g_pUPnp { nullptr };
83 static MainServer *mainServer { nullptr };
84 
85 bool setupTVs(bool ismaster, bool &error)
86 {
87  error = false;
88  QString localhostname = gCoreContext->GetHostName();
89 
91 
92  if (ismaster)
93  {
94  // Hack to make sure recorded.basename gets set if the user
95  // downgrades to a prior version and creates new entries
96  // without it.
97  if (!query.exec("UPDATE recorded SET basename = CONCAT(chanid, '_', "
98  "DATE_FORMAT(starttime, '%Y%m%d%H%i00'), '_', "
99  "DATE_FORMAT(endtime, '%Y%m%d%H%i00'), '.nuv') "
100  "WHERE basename = '';"))
101  MythDB::DBError("Updating record basename", query);
102 
103  // Hack to make sure record.station gets set if the user
104  // downgrades to a prior version and creates new entries
105  // without it.
106  if (!query.exec("UPDATE channel SET callsign=chanid "
107  "WHERE callsign IS NULL OR callsign='';"))
108  MythDB::DBError("Updating channel callsign", query);
109 
110  if (query.exec("SELECT MIN(chanid) FROM channel;"))
111  {
112  query.first();
113  int min_chanid = query.value(0).toInt();
114  if (!query.exec(QString("UPDATE record SET chanid = %1 "
115  "WHERE chanid IS NULL;").arg(min_chanid)))
116  MythDB::DBError("Updating record chanid", query);
117  }
118  else
119  {
120  MythDB::DBError("Querying minimum chanid", query);
121  }
122 
123  MSqlQuery records_without_station(MSqlQuery::InitCon());
124  records_without_station.prepare("SELECT record.chanid,"
125  " channel.callsign FROM record LEFT JOIN channel"
126  " ON record.chanid = channel.chanid WHERE record.station='';");
127  if (records_without_station.exec() && records_without_station.next())
128  {
129  MSqlQuery update_record(MSqlQuery::InitCon());
130  update_record.prepare("UPDATE record SET station = :CALLSIGN"
131  " WHERE chanid = :CHANID;");
132  do
133  {
134  update_record.bindValue(":CALLSIGN",
135  records_without_station.value(1));
136  update_record.bindValue(":CHANID",
137  records_without_station.value(0));
138  if (!update_record.exec())
139  {
140  MythDB::DBError("Updating record station", update_record);
141  }
142  } while (records_without_station.next());
143  }
144  }
145 
146  if (!query.exec(
147  "SELECT cardid, parentid, videodevice, hostname, sourceid "
148  "FROM capturecard "
149  "ORDER BY cardid"))
150  {
151  MythDB::DBError("Querying Recorders", query);
152  return false;
153  }
154 
155  std::vector<unsigned int> cardids;
156  std::vector<QString> hosts;
157  while (query.next())
158  {
159  uint cardid = query.value(0).toUInt();
160  uint parentid = query.value(1).toUInt();
161  QString videodevice = query.value(2).toString();
162  QString hostname = query.value(3).toString();
163  uint sourceid = query.value(4).toUInt();
164  QString cidmsg = QString("Card[%1](%2)").arg(cardid).arg(videodevice);
165 
166  if (hostname.isEmpty())
167  {
168  LOG(VB_GENERAL, LOG_ERR, cidmsg +
169  " does not have a hostname defined.\n"
170  "Please run setup and confirm all of the capture cards.\n");
171  continue;
172  }
173 
174  // Skip all cards that do not have a video source
175  if (sourceid == 0)
176  {
177  if (parentid == 0)
178  {
179  LOG(VB_GENERAL, LOG_WARNING, cidmsg +
180  " does not have a video source");
181  }
182  continue;
183  }
184 
185  cardids.push_back(cardid);
186  hosts.push_back(hostname);
187  }
188 
189  QWriteLocker tvlocker(&TVRec::s_inputsLock);
190 
191  // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
192  for (size_t i = 0; i < cardids.size(); i++)
193  {
194  if (hosts[i] == localhostname) {
195  // No memory leak. The constructor for TVRec adds the item
196  // to the static map TVRec::s_inputs.
197  new TVRec(cardids[i]);
198  }
199  }
200 
201  for (size_t i = 0; i < cardids.size(); i++)
202  {
203  uint cardid = cardids[i];
204  const QString& host = hosts[i];
205  QString cidmsg = QString("Card %1").arg(cardid);
206 
207  if (!ismaster)
208  {
209  if (host == localhostname)
210  {
211  TVRec *tv = TVRec::GetTVRec(cardid);
212  if (tv && tv->Init())
213  {
214  auto *enc = new EncoderLink(cardid, tv);
215  gTVList[cardid] = enc;
216  }
217  else
218  {
219  LOG(VB_GENERAL, LOG_ERR, "Problem with capture cards. " +
220  cidmsg + " failed init");
221  delete tv;
222  // No longer set an error here, because we need the
223  // slave backend to be able to start without a capture
224  // card, so that it can be setup through the web app
225  }
226  }
227  }
228  else
229  {
230  if (host == localhostname)
231  {
232  TVRec *tv = TVRec::GetTVRec(cardid);
233  if (tv && tv->Init())
234  {
235  auto *enc = new EncoderLink(cardid, tv);
236  gTVList[cardid] = enc;
237  }
238  else
239  {
240  LOG(VB_GENERAL, LOG_ERR, "Problem with capture cards. " +
241  cidmsg + " failed init");
242  delete tv;
243  }
244  }
245  else
246  {
247  auto *enc = new EncoderLink(cardid, nullptr, host);
248  gTVList[cardid] = enc;
249  }
250  }
251  }
252 
253  if (gTVList.empty())
254  {
255  LOG(VB_GENERAL, LOG_WARNING, LOC +
256  "No valid capture cards are defined in the database.");
257  }
258 
259  return true;
260 }
261 
262 void cleanup(void)
263 {
264  if (mainServer)
265  {
266  mainServer->Stop();
267  qApp->processEvents();
268  }
269 
270  if (gCoreContext)
272 
273  delete gSysEventHandler;
274  gSysEventHandler = nullptr;
275 
276  delete gHousekeeping;
277  gHousekeeping = nullptr;
278 
279  if (gCoreContext)
280  {
281  delete gCoreContext->GetScheduler();
282  gCoreContext->SetScheduler(nullptr);
283  }
284 
285  delete gExpirer;
286  gExpirer = nullptr;
287 
288  delete gJobQueue;
289  gJobQueue = nullptr;
290 
291  delete g_pUPnp;
292  g_pUPnp = nullptr;
293 
294  if (SSDP::Instance())
295  {
297  SSDP::Instance()->wait();
298  }
299 
300  if (TaskQueue::Instance())
301  {
304  }
305 
306  while (!TVRec::s_inputs.empty())
307  {
308  TVRec *rec = *TVRec::s_inputs.begin();
309  delete rec;
310  }
311 
312  delete mainServer;
313  mainServer = nullptr;
314 
315  delete gBackendContext;
316  gBackendContext = nullptr;
317 }
318 
320 {
321  if (cmdline.toBool("setverbose"))
322  {
324  {
325  QString message = "SET_VERBOSE ";
326  message += cmdline.toString("setverbose");
327 
328  gCoreContext->SendMessage(message);
329  LOG(VB_GENERAL, LOG_INFO,
330  QString("Sent '%1' message").arg(message));
331  return GENERIC_EXIT_OK;
332  }
333  LOG(VB_GENERAL, LOG_ERR,
334  "Unable to connect to backend, verbose mask unchanged ");
336  }
337 
338  if (cmdline.toBool("setloglevel"))
339  {
341  {
342  QString message = "SET_LOG_LEVEL ";
343  message += cmdline.toString("setloglevel");
344 
345  gCoreContext->SendMessage(message);
346  LOG(VB_GENERAL, LOG_INFO,
347  QString("Sent '%1' message").arg(message));
348  return GENERIC_EXIT_OK;
349  }
350  LOG(VB_GENERAL, LOG_ERR,
351  "Unable to connect to backend, log level unchanged ");
353  }
354 
355  if (cmdline.toBool("printsched") ||
356  cmdline.toBool("testsched"))
357  {
358  auto *sched = new Scheduler(false, &gTVList);
359  if (cmdline.toBool("printsched"))
360  {
362  {
363  LOG(VB_GENERAL, LOG_ERR, "Cannot connect to master");
364  delete sched;
366  }
367  std::cout << "Retrieving Schedule from Master backend.\n";
369  }
370  else
371  {
372  std::cout << "Calculating Schedule from database.\n" <<
373  "Inputs, Card IDs, and Conflict info may be invalid "
374  "if you have multiple tuners.\n";
377  }
378 
379  verboseMask |= VB_SCHEDULE;
380  LogLevel_t oldLogLevel = logLevel;
381  logLevel = LOG_DEBUG;
382  sched->PrintList(true);
383  logLevel = oldLogLevel;
384  delete sched;
385  return GENERIC_EXIT_OK;
386  }
387 
388  if (cmdline.toBool("printexpire"))
389  {
390  gExpirer = new AutoExpire();
391  gExpirer->PrintExpireList(cmdline.toString("printexpire"));
392  return GENERIC_EXIT_OK;
393  }
394 
395  // This should never actually be reached..
396  return GENERIC_EXIT_OK;
397 }
398 using namespace MythTZ;
399 
401 {
402  auto *tempMonitorConnection = new MythSocket();
403  if (tempMonitorConnection->ConnectToHost(
406  {
407  if (!gCoreContext->CheckProtoVersion(tempMonitorConnection))
408  {
409  LOG(VB_GENERAL, LOG_ERR, "Master backend is incompatible with "
410  "this backend.\nCannot become a slave.");
411  tempMonitorConnection->DecrRef();
413  }
414 
415  QStringList tempMonitorDone("DONE");
416 
417  QStringList tempMonitorAnnounce(QString("ANN Monitor %1 0")
418  .arg(gCoreContext->GetHostName()));
419  tempMonitorConnection->SendReceiveStringList(tempMonitorAnnounce);
420  if (tempMonitorAnnounce.empty() ||
421  tempMonitorAnnounce[0] == "ERROR")
422  {
423  tempMonitorConnection->DecrRef();
424  tempMonitorConnection = nullptr;
425  if (tempMonitorAnnounce.empty())
426  {
427  LOG(VB_GENERAL, LOG_ERR, LOC +
428  "Failed to open event socket, timeout");
429  }
430  else
431  {
432  LOG(VB_GENERAL, LOG_ERR, LOC +
433  "Failed to open event socket" +
434  ((tempMonitorAnnounce.size() >= 2) ?
435  QString(", error was %1").arg(tempMonitorAnnounce[1]) :
436  QString(", remote error")));
437  }
438  }
439 
440  QStringList timeCheck;
441  if (tempMonitorConnection)
442  {
443  timeCheck.push_back("QUERY_TIME_ZONE");
444  tempMonitorConnection->SendReceiveStringList(timeCheck);
445  tempMonitorConnection->WriteStringList(tempMonitorDone);
446  }
447  if (timeCheck.size() < 3)
448  {
449  if (tempMonitorConnection)
450  tempMonitorConnection->DecrRef();
452  }
453 
454  QDateTime our_time = MythDate::current();
455  QDateTime master_time = MythDate::fromString(timeCheck[2]);
456  int timediff = abs(our_time.secsTo(master_time));
457 
458  if (timediff > 300)
459  {
460  LOG(VB_GENERAL, LOG_ERR,
461  QString("Current time on the master backend differs by "
462  "%1 seconds from time on this system. Exiting.")
463  .arg(timediff));
464  if (tempMonitorConnection)
465  tempMonitorConnection->DecrRef();
467  }
468 
469  if (timediff > 20)
470  {
471  LOG(VB_GENERAL, LOG_WARNING,
472  QString("Time difference between the master "
473  "backend and this system is %1 seconds.")
474  .arg(timediff));
475  }
476  }
477  if (tempMonitorConnection)
478  tempMonitorConnection->DecrRef();
479 
480  return GENERIC_EXIT_OK;
481 }
482 
483 
485 {
486  if (cmdline.toBool("nohousekeeper"))
487  {
488  LOG(VB_GENERAL, LOG_WARNING, LOC +
489  "****** The Housekeeper has been DISABLED with "
490  "the --nohousekeeper option ******");
491  }
492  if (cmdline.toBool("nosched"))
493  {
494  LOG(VB_GENERAL, LOG_WARNING, LOC +
495  "********** The Scheduler has been DISABLED with "
496  "the --nosched option **********");
497  }
498  if (cmdline.toBool("noautoexpire"))
499  {
500  LOG(VB_GENERAL, LOG_WARNING, LOC +
501  "********* Auto-Expire has been DISABLED with "
502  "the --noautoexpire option ********");
503  }
504  if (cmdline.toBool("nojobqueue"))
505  {
506  LOG(VB_GENERAL, LOG_WARNING, LOC +
507  "********* The JobQueue has been DISABLED with "
508  "the --nojobqueue option *********");
509  }
510 }
511 
513 {
515 
517  {
518  return run_setup_webserver();
519  }
521  {
522  LOG(VB_GENERAL, LOG_ERR,
523  "MySQL time zone support is missing. "
524  "Please install it and try again. "
525  "See 'mysql_tzinfo_to_sql' for assistance.");
526  gCoreContext->GetDB()->IgnoreDatabase(true);
528  return run_setup_webserver();
529  }
530  bool ismaster = gCoreContext->IsMasterHost();
531 
532  if (!UpgradeTVDatabaseSchema(ismaster, ismaster, true))
533  {
534  LOG(VB_GENERAL, LOG_ERR,
535  QString("Couldn't upgrade database to new schema on %1 backend.")
536  .arg(ismaster ? "master" : "slave"));
538  return run_setup_webserver();
539  }
540 #ifndef NDEBUG
541  if (cmdline.toBool("upgradedbonly"))
542  {
543  LOG(VB_GENERAL, LOG_ERR, "Exiting as requested.");
544  return GENERIC_EXIT_OK;
545  }
546 #endif
547 
548  be_sd_notify("STATUS=Loading translation");
549  MythTranslation::load("mythfrontend");
550 
551  if (cmdline.toBool("webonly"))
552  {
554  return run_setup_webserver();
555  }
556  if (!ismaster)
557  {
558  be_sd_notify("STATUS=Connecting to master backend");
559  int ret = connect_to_master();
560  if (ret != GENERIC_EXIT_OK)
561  return ret;
562  }
563 
564  be_sd_notify("STATUS=Get backend server port");
565  int port = gCoreContext->GetBackendServerPort();
566  if (gCoreContext->GetBackendServerIP().isEmpty())
567  {
568  std::cerr << "No setting found for this machine's BackendServerAddr.\n"
569  << "MythBackend starting in Web App only mode for initial setup.\n"
570  << "Use http://<yourBackend>:6544 to perform setup.\n";
572  return run_setup_webserver();
573  }
574 
576 
577  if (ismaster)
578  {
579  LOG(VB_GENERAL, LOG_NOTICE, LOC + "Starting up as the master server.");
580  }
581  else
582  {
583  LOG(VB_GENERAL, LOG_NOTICE, LOC + "Running as a slave backend.");
584  }
585 
586  if (ismaster)
587  {
589  }
590 
592 
593  bool fatal_error = false;
594  bool runsched = setupTVs(ismaster, fatal_error);
595  if (fatal_error)
597 
598  Scheduler *sched = nullptr;
599  if (ismaster)
600  {
601  if (runsched)
602  {
603  be_sd_notify("STATUS=Creating scheduler");
604  sched = new Scheduler(true, &gTVList);
605  int err = sched->GetError();
606  if (err)
607  {
608  delete sched;
609  return err;
610  }
611 
612  if (cmdline.toBool("nosched"))
614  }
615 
616  if (!cmdline.toBool("noautoexpire"))
617  {
618  gExpirer = new AutoExpire(&gTVList);
619  if (sched)
621  }
624  }
625 
626  if (!cmdline.toBool("nohousekeeper"))
627  {
628  be_sd_notify("STATUS=Creating housekeeper");
629  gHousekeeping = new HouseKeeper();
630 
631  if (ismaster)
632  {
637 
638  // only run this task if MythMusic is installed and we have a new enough schema
639  if (gCoreContext->GetNumSetting("MusicDBSchemaVer", 0) >= 1024)
641  }
642 
644 #ifdef __linux__
645  #ifdef CONFIG_BINDINGS_PYTHON
647  #endif
648 #endif
649 
650  gHousekeeping->Start();
651  }
652 
653  if (!cmdline.toBool("nojobqueue"))
654  gJobQueue = new JobQueue(ismaster);
655 
656  // ----------------------------------------------------------------------
657  //
658  // ----------------------------------------------------------------------
659 
660  if (g_pUPnp == nullptr)
661  {
662  be_sd_notify("STATUS=Creating UPnP media server");
663  g_pUPnp = new MediaServer();
664 
665  g_pUPnp->Init(ismaster, cmdline.toBool("noupnp"));
666  }
667 
668  if (cmdline.toBool("dvbv3"))
669  {
670  LOG(VB_GENERAL, LOG_INFO, LOC + "Use legacy DVBv3 API");
671  gCoreContext->SetDVBv3(true);
672  }
673 
674  // ----------------------------------------------------------------------
675  // Setup status server
676  // ----------------------------------------------------------------------
677 
678  HttpStatus *httpStatus = nullptr;
679  HttpServer *pHS = g_pUPnp->GetHttpServer();
680 
681  if (pHS)
682  {
683  LOG(VB_GENERAL, LOG_INFO, "Main::Registering HttpStatus Extension");
684  be_sd_notify("STATUS=Registering HttpStatus Extension");
685 
686  httpStatus = new HttpStatus( &gTVList, sched, ismaster );
687  pHS->RegisterExtension( httpStatus );
688  }
689 
690  be_sd_notify("STATUS=Creating main server");
691  mainServer = new MainServer(
692  ismaster, port, &gTVList, sched, gExpirer);
693 
694  int exitCode = mainServer->GetExitCode();
695  if (exitCode != GENERIC_EXIT_OK)
696  {
697  LOG(VB_GENERAL, LOG_CRIT,
698  "Backend exiting, MainServer initialization error.");
699  cleanup();
700  return exitCode;
701  }
702 
703  if (httpStatus && mainServer)
704  httpStatus->SetMainServer(mainServer);
705 
706  be_sd_notify("STATUS=Check all storage groups");
708 
709  be_sd_notify("STATUS=Sending \"master started\" message");
711  gCoreContext->SendSystemEvent("MASTER_STARTED");
712 
713  // Provide systemd ready notification (for Type=notify)
714  be_sd_notify("READY=1");
715 
716  const HTTPServices be_services = {
717  { VIDEO_SERVICE, &MythHTTPService::Create<V2Video> },
718  { MYTH_SERVICE, &MythHTTPService::Create<V2Myth> },
719  { DVR_SERVICE, &MythHTTPService::Create<V2Dvr> },
720  { CONTENT_SERVICE, &MythHTTPService::Create<V2Content> },
721  { GUIDE_SERVICE, &MythHTTPService::Create<V2Guide> },
722  { CHANNEL_SERVICE, &MythHTTPService::Create<V2Channel> },
723  { STATUS_SERVICE, &MythHTTPService::Create<V2Status> },
724  { CAPTURE_SERVICE, &MythHTTPService::Create<V2Capture> },
725  { MUSIC_SERVICE, &MythHTTPService::Create<V2Music> },
726  { CONFIG_SERVICE, &MythHTTPService::Create<V2Config> },
727  };
728 
729  MythHTTPInstance::Addservices(be_services);
730 
731  // Send all unknown requests into the web app. make bookmarks and direct access work.
732  auto spa_index = [](auto && PH1) { return MythHTTPRewrite::RewriteToSPA(std::forward<decltype(PH1)>(PH1), "apps/backend/index.html"); };
733  MythHTTPInstance::AddErrorPageHandler({ "=404", spa_index });
734 
735  // Serve components of the backend web app as if they were hosted at '/'
736  auto main_js = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/main.js"); };
737  auto styles_css = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/styles.css"); };
738  auto polyfills_js = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/polyfills.js"); };
739  auto runtime_js = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/runtime.js"); };
740 
741  // Default index page
742  auto root = [](auto && PH1) { return MythHTTPRoot::RedirectRoot(std::forward<decltype(PH1)>(PH1), "apps/backend/index.html"); };
743 
744  const HTTPHandlers be_handlers = {
745  { "/main.js", main_js },
746  { "/styles.css", styles_css },
747  { "/polyfills.js", polyfills_js },
748  { "/runtime.js", runtime_js },
749  { "/", root }
750  };
751 
752  MythHTTPScopedInstance webserver(be_handlers);
753 
756  exitCode = qApp->exec();
759 
761  {
762  gCoreContext->SendSystemEvent("MASTER_SHUTDOWN");
763  qApp->processEvents();
764  }
765 
766  LOG(VB_GENERAL, LOG_NOTICE, "MythBackend exiting");
767  be_sd_notify("STOPPING=1\nSTATUS=Exiting");
768 
769  return exitCode;
770 }
771 
772 // This is a copy of the code from above, to start backend in a restricted mode, only running the web server
773 // when the database is unusable, so thet the user can use the web app to fix the settings.
774 
776 {
777  LOG(VB_GENERAL, LOG_NOTICE, "***********************************************************************");
778  LOG(VB_GENERAL, LOG_NOTICE, "***** MythBackend starting in Web App only mode for initial setup *****");
779  LOG(VB_GENERAL, LOG_NOTICE, "***** Use http://<yourBackend>:6544 to perform setup *****");
780  LOG(VB_GENERAL, LOG_NOTICE, "***********************************************************************");
781 
782  const HTTPServices be_services = {
783  { VIDEO_SERVICE, &MythHTTPService::Create<V2Video> },
784  { MYTH_SERVICE, &MythHTTPService::Create<V2Myth> },
785  { DVR_SERVICE, &MythHTTPService::Create<V2Dvr> },
786  { CONTENT_SERVICE, &MythHTTPService::Create<V2Content> },
787  { GUIDE_SERVICE, &MythHTTPService::Create<V2Guide> },
788  { CHANNEL_SERVICE, &MythHTTPService::Create<V2Channel> },
789  { STATUS_SERVICE, &MythHTTPService::Create<V2Status> },
790  { CAPTURE_SERVICE, &MythHTTPService::Create<V2Capture> },
791  { MUSIC_SERVICE, &MythHTTPService::Create<V2Music> },
792  { CONFIG_SERVICE, &MythHTTPService::Create<V2Config> },
793  };
794 
795  MythHTTPInstance::Addservices(be_services);
796 
797  // Send all unknown requests into the web app. make bookmarks and direct access work.
798  auto spa_index = [](auto && PH1) { return MythHTTPRewrite::RewriteToSPA(std::forward<decltype(PH1)>(PH1), "apps/backend/index.html"); };
799  MythHTTPInstance::AddErrorPageHandler({ "=404", spa_index });
800 
801  // Serve components of the backend web app as if they were hosted at '/'
802  auto main_js = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/main.js"); };
803  auto styles_css = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/styles.css"); };
804  auto polyfills_js = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/polyfills.js"); };
805  auto runtime_js = [](auto && PH1) { return MythHTTPRewrite::RewriteFile(std::forward<decltype(PH1)>(PH1), "apps/backend/runtime.js"); };
806 
807  // Default index page
808  auto root = [](auto && PH1) { return MythHTTPRoot::RedirectRoot(std::forward<decltype(PH1)>(PH1), "apps/backend/index.html"); };
809 
810  const HTTPHandlers be_handlers = {
811  { "/main.js", main_js },
812  { "/styles.css", styles_css },
813  { "/polyfills.js", polyfills_js },
814  { "/runtime.js", runtime_js },
815  { "/", root }
816  };
817 
818  MythHTTPScopedInstance webserver(be_handlers);
819 
822  // Provide systemd ready notification (for Type=notify)
823  be_sd_notify("READY=1\nSTATUS=Started in 'Web App only mode'");
824  int exitCode = qApp->exec();
825 
826  be_sd_notify("STOPPING=1\nSTATUS='Exiting Web App only mode'");
827  LOG(VB_GENERAL, LOG_NOTICE, "MythBackend Web App only mode exiting");
828  return exitCode;
829 }
setupTVs
bool setupTVs(bool ismaster, bool &error)
Definition: mythbackend_main_helpers.cpp:85
run_setup_webserver
int run_setup_webserver()
Definition: mythbackend_main_helpers.cpp:775
Scheduler
Definition: scheduler.h:45
MSqlQuery::next
bool next(void)
Wrap QSqlQuery::next() so we can display the query results.
Definition: mythdbcon.cpp:812
MSqlQuery
QSqlQuery wrapper that fetches a DB connection from the connection pool.
Definition: mythdbcon.h:127
hardwareprofile.h
v2video.h
HouseKeeper
Manages registered HouseKeeperTasks and queues tasks for operation.
Definition: housekeeper.h:149
MythCoreContext::SendMessage
void SendMessage(const QString &message)
Definition: mythcorecontext.cpp:1527
AutoExpire::PrintExpireList
void PrintExpireList(const QString &expHost="ALL")
Prints a summary of the files that can be deleted.
Definition: autoexpire.cpp:795
MythHTTPScopedInstance
Definition: mythhttpinstance.h:35
ThemeUpdateTask
Definition: backendhousekeeper.h:34
v2music.h
Scheduler::GetError
int GetError(void) const
Definition: scheduler.h:120
dbutil.h
backendcontext.h
EITCache::ClearChannelLocks
static MTV_PUBLIC void ClearChannelLocks(void)
Removes old channel locks, use it only at master backend start.
Definition: eitcache.cpp:462
CONTENT_SERVICE
#define CONTENT_SERVICE
Definition: v2content.h:34
MediaServer
Definition: mediaserver.h:32
MythCoreContext::GetScheduler
MythScheduler * GetScheduler(void)
Definition: mythcorecontext.cpp:1915
connect_to_master
int connect_to_master(void)
Definition: mythbackend_main_helpers.cpp:400
CONFIG_SERVICE
#define CONFIG_SERVICE
Definition: v2config.h:11
mythdb.h
HttpStatus
Definition: httpstatus.h:42
cmdline
MythCommFlagCommandLineParser cmdline
Definition: mythcommflag.cpp:63
TVRec::Init
bool Init(void)
Performs instance initialization, returns true on success.
Definition: tv_rec.cpp:157
BackendContext
Definition: backendcontext.h:33
MythCoreContext::ConnectToMasterServer
bool ConnectToMasterServer(bool blockingClient=true, bool openEventSocket=true)
Definition: mythcorecontext.cpp:359
MThread::wait
bool wait(std::chrono::milliseconds time=std::chrono::milliseconds::max())
Wait for the MThread to exit, with a maximum timeout.
Definition: mthread.cpp:300
logLevel
LogLevel_t logLevel
Definition: logging.cpp:85
TaskQueue::RequestTerminate
void RequestTerminate()
Definition: taskqueue.cpp:103
gExpirer
AutoExpire * gExpirer
Definition: backendcontext.cpp:8
gHousekeeping
static HouseKeeper * gHousekeeping
Definition: mythbackend_main_helpers.cpp:79
HttpServer::RegisterExtension
void RegisterExtension(HttpServerExtension *pExtension)
Definition: httpserver.cpp:321
MythCoreContext::SetScheduler
void SetScheduler(MythScheduler *sched)
Definition: mythcorecontext.cpp:1910
Scheduler::FillRecordListFromDB
void FillRecordListFromDB(uint recordid=0)
Definition: scheduler.cpp:491
v2content.h
httpstatus.h
sched
Scheduler * sched
mythhttpinstance.h
RadioStreamUpdateTask
Definition: backendhousekeeper.h:22
MythCoreContext::IsDatabaseIgnored
bool IsDatabaseIgnored(void) const
/brief Returns true if database is being ignored.
Definition: mythcorecontext.cpp:882
MSqlQuery::value
QVariant value(int i) const
Definition: mythdbcon.h:204
MainServer
Definition: mainserver.h:115
AutoExpire
Used to expire recordings to make space for new recordings.
Definition: autoexpire.h:60
v2myth.h
Scheduler::DisableScheduling
void DisableScheduling(void)
Definition: scheduler.h:110
MSqlQuery::exec
bool exec(void)
Wrap QSqlQuery::exec() so we can display SQL.
Definition: mythdbcon.cpp:618
UPnp::GetHttpServer
HttpServer * GetHttpServer()
Definition: upnp.h:128
MythCoreContext::CheckProtoVersion
bool CheckProtoVersion(MythSocket *socket, std::chrono::milliseconds timeout=kMythSocketLongTimeout, bool error_dialog_desired=false)
Definition: mythcorecontext.cpp:1671
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
mythsystemevent.h
HouseKeeper::RegisterTask
void RegisterTask(HouseKeeperTask *task)
Definition: housekeeper.cpp:643
gBackendContext
BackendContext * gBackendContext
Definition: backendcontext.cpp:9
HttpStatus::SetMainServer
void SetMainServer(MainServer *mainServer)
Definition: httpstatus.h:87
v2dvr.h
remoteutil.h
V2Myth::s_WebOnlyStartup
static WebOnlyStartup s_WebOnlyStartup
Definition: v2myth.h:66
scheduler.h
be_sd_notify
static void be_sd_notify(const char *)
Definition: mythbackend_main_helpers.cpp:6
MythDate::current
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:15
VIDEO_SERVICE
#define VIDEO_SERVICE
Definition: v2video.h:13
MythSocket
Class for communcating between myth backends and frontends.
Definition: mythsocket.h:25
mythbackend_commandlineparser.h
SSDP::Instance
static SSDP * Instance()
Definition: ssdp.cpp:102
V2Myth::kWebOnlyWebOnlyParm
@ kWebOnlyWebOnlyParm
Definition: v2myth.h:62
MythCoreContext::IsMasterBackend
bool IsMasterBackend(void)
is this the actual MBE process
Definition: mythcorecontext.cpp:701
MythHTTPRewrite::RewriteFile
static HTTPResponse RewriteFile(const HTTPRequest2 &Request, const QString &File)
A convenience method to seemlessly redirect requests for files to a context specific file.
Definition: mythhttprewrite.cpp:22
v2channel.h
autoexpire.h
MythHTTPInstance::Addservices
static void Addservices(const HTTPServices &Services)
Definition: mythhttpinstance.cpp:102
programinfo.h
mythlogging.h
UpgradeTVDatabaseSchema
bool UpgradeTVDatabaseSchema(const bool upgradeAllowed, const bool upgradeIfNoUI, [[maybe_unused]] const bool informSystemd)
Called from outside dbcheck.cpp to update the schema.
Definition: dbcheck.cpp:362
dbcheck.h
MythCoreContext::GetBackendServerPort
int GetBackendServerPort(void)
Returns the locally defined backend control port.
Definition: mythcorecontext.cpp:1070
MythCoreContext::SendSystemEvent
void SendSystemEvent(const QString &msg)
Definition: mythcorecontext.cpp:1554
MythCoreContext::GetMasterServerIP
QString GetMasterServerIP(void)
Returns the Master Backend IP address If the address is an IPv6 address, the scope Id is removed.
Definition: mythcorecontext.cpp:972
verboseMask
uint64_t verboseMask
Definition: logging.cpp:97
MSqlQuery::first
bool first(void)
Wrap QSqlQuery::first() so we can display the query results.
Definition: mythdbcon.cpp:822
GENERIC_EXIT_OK
@ GENERIC_EXIT_OK
Exited with no error.
Definition: exitcodes.h:13
TaskQueue::Instance
static TaskQueue * Instance()
Definition: taskqueue.cpp:60
MSqlQuery::InitCon
static MSqlQueryInfo InitCon(ConnectionReuse _reuse=kNormalConnection)
Only use this in combination with MSqlQuery constructor.
Definition: mythdbcon.cpp:550
compat.h
MythCoreContext::GetBackendServerIP
QString GetBackendServerIP(void)
Returns the IP address of the locally defined backend IP.
Definition: mythcorecontext.cpp:1010
MythCoreContext::SetDVBv3
void SetDVBv3(bool dvbv3)
Definition: mythcorecontext.h:308
eitcache.h
MythDB::DBError
static void DBError(const QString &where, const MSqlQuery &query)
Definition: mythdb.cpp:226
mythhttprewrite.h
Scheduler::SetExpirer
void SetExpirer(AutoExpire *autoExpirer)
Definition: scheduler.h:55
MythCoreContext::GetDB
MythDB * GetDB(void)
Definition: mythcorecontext.cpp:1763
mythtranslation.h
v2capture.h
V2Myth::kWebOnlyDBTimezone
@ kWebOnlyDBTimezone
Definition: v2myth.h:61
MythTZ
Definition: mythtimezone.cpp:15
HardwareProfileTask
Definition: hardwareprofile.h:52
GENERIC_EXIT_CONNECT_ERROR
@ GENERIC_EXIT_CONNECT_ERROR
Can't connect to master backend.
Definition: exitcodes.h:23
scheduledrecording.h
ArtworkTask
Definition: backendhousekeeper.h:49
DBUtil::CheckTimeZoneSupport
static bool CheckTimeZoneSupport(void)
Check if MySQL has working timz zone support.
Definition: dbutil.cpp:865
CHANNEL_SERVICE
#define CHANNEL_SERVICE
Definition: v2channel.h:39
storagegroup.h
jobqueue.h
Scheduler::PrintList
void PrintList(bool onlyFutureRecordings=false)
Definition: scheduler.h:99
TVRec::s_inputsLock
static QReadWriteLock s_inputsLock
Definition: tv_rec.h:432
g_pUPnp
static MediaServer * g_pUPnp
Definition: mythbackend_main_helpers.cpp:82
DVR_SERVICE
#define DVR_SERVICE
Definition: v2dvr.h:41
MythHTTPRoot::RedirectRoot
static HTTPResponse RedirectRoot(const HTTPRequest2 &Request, const QString &File)
A convenience method to seemlessly redirect requests for index.html to a context specific file.
Definition: mythhttproot.cpp:24
gTVList
QMap< int, EncoderLink * > gTVList
Definition: backendcontext.cpp:7
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:57
JobQueueRecoverTask
Definition: backendhousekeeper.h:62
v2config.h
MythCoreContext::GetNumSetting
int GetNumSetting(const QString &key, int defaultval=0)
Definition: mythcorecontext.cpp:918
MediaServer::Init
void Init(bool bIsMaster, bool bDisableUPnp=false)
Definition: mediaserver.cpp:57
mainServer
static MainServer * mainServer
Definition: mythbackend_main_helpers.cpp:83
hardwareprofile.smolt.error
def error(message)
Definition: smolt.py:409
MythDate::fromString
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:39
MainServer::GetExitCode
int GetExitCode() const
Definition: mainserver.h:152
STATUS_SERVICE
#define STATUS_SERVICE
Definition: v2status.h:34
GUIDE_SERVICE
#define GUIDE_SERVICE
Definition: v2guide.h:43
MythCoreContext::GetMasterServerPort
static int GetMasterServerPort(void)
Returns the Master Backend control port If no master server port has been defined in the database,...
Definition: mythcorecontext.cpp:986
backendhousekeeper.h
mediaserver.h
V2Myth::kWebOnlySchemaUpdate
@ kWebOnlySchemaUpdate
Definition: v2myth.h:64
CleanupTask
Definition: backendhousekeeper.h:7
MythCommandLineParser::toString
QString toString(const QString &key) const
Returns stored QVariant as a QString, falling to default if not provided.
Definition: mythcommandlineparser.cpp:2360
mythhttproot.h
mythcorecontext.h
MythCommandLineParser::toBool
bool toBool(const QString &key) const
Returns stored QVariant as a boolean.
Definition: mythcommandlineparser.cpp:2203
gSysEventHandler
static MythSystemEventHandler * gSysEventHandler
Definition: mythbackend_main_helpers.cpp:81
GENERIC_EXIT_SETUP_ERROR
@ GENERIC_EXIT_SETUP_ERROR
Incorrectly setup system.
Definition: exitcodes.h:24
V2Myth::kWebOnlyIPAddress
@ kWebOnlyIPAddress
Definition: v2myth.h:63
MSqlQuery::bindValue
void bindValue(const QString &placeholder, const QVariant &val)
Add a single binding.
Definition: mythdbcon.cpp:888
CAPTURE_SERVICE
#define CAPTURE_SERVICE
Definition: v2capture.h:33
TVRec
This is the coordinating class of the Recorder Subsystem.
Definition: tv_rec.h:142
tv_rec.h
v2guide.h
handle_command
int handle_command(const MythBackendCommandLineParser &cmdline)
Definition: mythbackend_main_helpers.cpp:319
MYTH_SERVICE
#define MYTH_SERVICE
Definition: v2myth.h:16
ChannelGroup::UpdateChannelGroups
static void UpdateChannelGroups(void)
Definition: channelgroup.cpp:494
HttpServer
Definition: httpserver.h:112
mainserver.h
MUSIC_SERVICE
#define MUSIC_SERVICE
Definition: v2music.h:17
JobQueue
Definition: jobqueue.h:128
mythbackend_main_helpers.h
MythCoreContext::GetHostName
QString GetHostName(void)
Definition: mythcorecontext.cpp:844
MythBackendCommandLineParser
Definition: mythbackend_commandlineparser.h:7
HTTPServices
std::vector< HTTPService > HTTPServices
Definition: mythhttptypes.h:55
gJobQueue
static JobQueue * gJobQueue
Definition: mythbackend_main_helpers.cpp:80
MythCoreContext::IsMasterHost
bool IsMasterHost(void)
is this the same host as the master
Definition: mythcorecontext.cpp:665
musicbrainzngs.caa.hostname
string hostname
Definition: caa.py:17
GENERIC_EXIT_INVALID_TIME
@ GENERIC_EXIT_INVALID_TIME
Invalid time.
Definition: exitcodes.h:25
previewgenerator.h
MythFillDatabaseTask
Definition: backendhousekeeper.h:71
ProgramInfo::CheckProgramIDAuthorities
static void CheckProgramIDAuthorities(void)
Definition: programinfo.cpp:2382
MythTranslation::load
static void load(const QString &module_name)
Load a QTranslator for the user's preferred language.
Definition: mythtranslation.cpp:38
exitcodes.h
MainServer::Stop
void Stop(void)
Definition: mainserver.cpp:365
run_backend
int run_backend(MythBackendCommandLineParser &cmdline)
Definition: mythbackend_main_helpers.cpp:512
MythSystemEventHandler
Handles incoming MythSystemEvent messages.
Definition: mythsystemevent.h:24
Scheduler::FillRecordListFromMaster
void FillRecordListFromMaster(void)
Definition: scheduler.cpp:574
cleanup
void cleanup(void)
Definition: mythbackend_main_helpers.cpp:262
print_warnings
void print_warnings(const MythBackendCommandLineParser &cmdline)
Definition: mythbackend_main_helpers.cpp:484
GENERIC_EXIT_SOCKET_ERROR
@ GENERIC_EXIT_SOCKET_ERROR
Socket error.
Definition: exitcodes.h:21
StorageGroup::CheckAllStorageGroupDirs
static void CheckAllStorageGroupDirs(void)
Definition: storagegroup.cpp:724
HouseKeeper::Start
void Start(void)
Definition: housekeeper.cpp:677
MythHTTPRewrite::RewriteToSPA
static HTTPResponse RewriteToSPA(const HTTPRequest2 &Request, const QString &File)
A convenience method to seemlessly redirect requests to a Single Page web app (SPA)
Definition: mythhttprewrite.cpp:50
mythtimezone.h
MythCoreContext::SetExiting
void SetExiting(bool exiting=true)
Definition: mythcorecontext.cpp:2122
TVRec::GetTVRec
static TVRec * GetTVRec(uint inputid)
Definition: tv_rec.cpp:4896
v2status.h
SSDP::RequestTerminate
void RequestTerminate(void)
Definition: ssdp.cpp:186
uint
unsigned int uint
Definition: freesurround.h:24
HTTPHandlers
std::vector< HTTPHandler > HTTPHandlers
Definition: mythhttptypes.h:48
MSqlQuery::prepare
bool prepare(const QString &query)
QSqlQuery::prepare() is not thread safe in Qt <= 3.3.2.
Definition: mythdbcon.cpp:837
TVRec::s_inputs
static QMap< uint, TVRec * > s_inputs
Definition: tv_rec.h:433
MythHTTPInstance::AddErrorPageHandler
static void AddErrorPageHandler(const HTTPHandler &Handler)
Definition: mythhttpinstance.cpp:112
LOC
#define LOC
Definition: mythbackend_main_helpers.cpp:75