MythTV  master
mythsystemevent.cpp
Go to the documentation of this file.
1 
2 #include <QApplication>
3 #include <QFileInfo>
4 #include <QRunnable>
5 #include <utility>
6 
7 #include "mythcorecontext.h"
8 #include "mthreadpool.h"
9 #include "mythsystemlegacy.h"
10 #include "mythsystemevent.h"
11 #include "programinfo.h"
12 #include "cardutil.h"
13 #include "remoteutil.h"
14 #include "exitcodes.h"
15 #include "mythlogging.h"
16 
17 #define LOC QString("MythSystemEventHandler: ")
18 
28 class SystemEventThread : public QRunnable
29 {
30  public:
37  explicit SystemEventThread(QString cmd, QString eventName = "")
38  : m_command(std::move(cmd)), m_event(std::move(eventName)) {};
39 
45  void run(void) override // QRunnable
46  {
48  uint result = myth_system(m_command, flags);
49 
50  LOG(VB_GENERAL,
51  (result == GENERIC_EXIT_OK ? LOG_INFO : LOG_WARNING), LOC +
52  QString("Finished '%1' result %2")
53  .arg(m_command).arg(result));
54 
55  if (m_event.isEmpty())
56  return;
57 
59  QString("SYSTEM_EVENT_RESULT %1 SENDER %2 RESULT %3")
60  .arg(m_event).arg(gCoreContext->GetHostName()).arg(result));
61  }
62 
63  private:
64  // Private data storage
65  QString m_command;
66  QString m_event;
67 };
68 
69 
76 {
77  setObjectName("MythSystemEventHandler");
79 }
80 
87 {
89 }
90 
104 void MythSystemEventHandler::SubstituteMatches(const QStringList &tokens,
105  QString &command)
106 {
107  if (command.isEmpty())
108  return;
109 
110  LOG(VB_FILE, LOG_DEBUG, LOC + QString("SubstituteMatches: BEFORE: %1")
111  .arg(command));
112  QString args;
113  uint chanid = 0;
114  QDateTime recstartts;
115 
116  QStringList::const_iterator it = tokens.begin();
117  ++it;
118  command.replace(QString("%EVENTNAME%"), *it);
119 
120  ++it;
121  while (it != tokens.end())
122  {
123  if (!args.isEmpty())
124  args += " ";
125  args += *it;
126 
127  // Check for some token names that we substitute one for one as
128  // %MATCH% type variables.
129  if ((*it == "CARDID") ||
130  (*it == "COMMAND") ||
131  (*it == "RECSTATUS") ||
132  (*it == "HOSTNAME") ||
133  (*it == "SECS") ||
134  (*it == "SENDER") ||
135  (*it == "PATH") ||
136  (*it == "VIDEODEVICE") ||
137  (*it == "VBIDEVICE"))
138  {
139  QString token = *it;
140 
141  if (++it == tokens.end())
142  break;
143 
144  // The following string is broken up on purpose to indicate
145  // what we're replacing is the token surrounded by percent signs
146  command.replace(QString("%" "%1" "%").arg(token), *it);
147 
148  if (!args.isEmpty())
149  args += " ";
150  args += *it;
151  }
152 
153  // Remember any chanid and starttime so we can lookup info about
154  // the recording from the database.
155  if (*it == "CHANID")
156  {
157  if (++it == tokens.end())
158  break;
159 
160  chanid = (*it).toUInt();
161 
162  if (!args.isEmpty())
163  args += " ";
164  args += *it;
165  }
166 
167  if (*it == "STARTTIME")
168  {
169  if (++it == tokens.end())
170  break;
171 
172  recstartts = MythDate::fromString(*it);
173 
174  if (!args.isEmpty())
175  args += " ";
176  args += *it;
177  }
178 
179  ++it;
180  }
181 
182  command.replace(QString("%ARGS%"), args);
183 
184  // 1st, try loading RecordingInfo / ProgramInfo
185  RecordingInfo recinfo(chanid, recstartts);
186  bool loaded = recinfo.GetChanID() != 0U;
187  if (loaded)
188  recinfo.SubstituteMatches(command);
189  else
190  {
191  // 2rd Try searching for RecordingInfo
193  RecordingInfo recinfo2(chanid, recstartts, false, 0h, &status);
194  if (status == RecordingInfo::kFoundProgram)
195  recinfo2.SubstituteMatches(command);
196  else
197  {
198  // 3th just use what we know
199  command.replace(QString("%CHANID%"), QString::number(chanid));
200  command.replace(QString("%STARTTIME%"),
201  MythDate::toString(recstartts,
203  command.replace(QString("%STARTTIMEISO%"),
204  recstartts.toString(Qt::ISODate));
205  }
206  }
207 
208  command.replace(QString("%VERBOSELEVEL%"), QString("%1").arg(verboseMask));
209  command.replace("%VERBOSEMODE%", QString("%1").arg(logPropagateArgs));
210 
211  LOG(VB_FILE, LOG_DEBUG, LOC + QString("SubstituteMatches: AFTER : %1")
212  .arg(command));
213 }
214 
224 QString MythSystemEventHandler::EventNameToSetting(const QString &name)
225 {
226  QString result("EventCmd");
227 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
228  QStringList parts = name.toLower().split('_', QString::SkipEmptyParts);
229 #else
230  QStringList parts = name.toLower().split('_', Qt::SkipEmptyParts);
231 #endif
232 
233  for (const auto & part : qAsConst(parts))
234  {
235  result += part.at(0).toUpper();
236  result += part.midRef(1);
237  }
238 
239  return result;
240 }
241 
258 {
259  if (e->type() == MythEvent::MythEventMessage)
260  {
261  auto *me = dynamic_cast<MythEvent *>(e);
262  if (me == nullptr)
263  return;
264  QString msg = me->Message().simplified();
265 
266  if (msg == "CLEAR_SETTINGS_CACHE")
267  msg = "SYSTEM_EVENT SETTINGS_CACHE_CLEARED";
268 
269  // Listen for any GLOBAL_SYSTEM_EVENT messages and resend to
270  // the master backend as regular SYSTEM_EVENT messages.
271  if (msg.startsWith("GLOBAL_SYSTEM_EVENT "))
272  {
273  gCoreContext->SendMessage(msg.mid(7) +
274  QString(" SENDER %1").arg(gCoreContext->GetHostName()));
275  return;
276  }
277 
278  if ((!msg.startsWith("SYSTEM_EVENT ")) &&
279  (!msg.startsWith("LOCAL_SYSTEM_EVENT ")))
280  return;
281 
282 #if QT_VERSION < QT_VERSION_CHECK(5,14,0)
283  QStringList tokens = msg.split(' ', QString::SkipEmptyParts);
284 #else
285  QStringList tokens = msg.split(' ', Qt::SkipEmptyParts);
286 #endif
287 
288  // Return if this event is for another host
289  if ((tokens.size() >= 4) &&
290  (tokens[2] == "HOST") &&
291  (tokens[3] != gCoreContext->GetHostName()))
292  return;
293 
294  QString cmd;
295 
296  // See if this system has a command that runs for all system events
297  cmd = gCoreContext->GetSetting("EventCmdAll");
298  if (!cmd.isEmpty())
299  {
300  SubstituteMatches(tokens, cmd);
301 
302  auto *eventThread = new SystemEventThread(cmd);
304  eventThread, "SystemEvent");
305  }
306 
307  // Check for an EventCmd for this particular event
308  cmd = gCoreContext->GetSetting(EventNameToSetting(tokens[1]));
309  if (!cmd.isEmpty())
310  {
311  SubstituteMatches(tokens, cmd);
312 
313  LOG(VB_GENERAL, LOG_INFO, LOC +
314  QString("Starting thread for command '%1'").arg(cmd));
315 
316  auto *eventThread = new SystemEventThread(cmd, tokens[1]);
318  eventThread, "SystemEvent");
319  }
320  }
321 }
322 
323 /****************************************************************************/
324 
331 void SendMythSystemRecEvent(const QString &msg, const RecordingInfo *pginfo)
332 {
333  if (pginfo)
334  {
335  uint cardid = pginfo->GetInputID();
337  QString("%1 CARDID %2 CHANID %3 STARTTIME %4 RECSTATUS %5 "
338  "VIDEODEVICE %6 VBIDEVICE %7")
339  .arg(msg).arg(cardid)
340  .arg(pginfo->GetChanID())
342  .arg(pginfo->GetRecordingStatus())
343  .arg(CardUtil::GetVideoDevice(cardid))
344  .arg(CardUtil::GetVBIDevice(cardid)));
345  }
346  else
347  {
348  LOG(VB_GENERAL, LOG_ERR, LOC +
349  "SendMythSystemRecEvent() called with empty RecordingInfo");
350  }
351 }
352 
359 void SendMythSystemPlayEvent(const QString &msg, const ProgramInfo *pginfo)
360 {
361  if (pginfo)
362  {
364  QString("%1 HOSTNAME %2 CHANID %3 STARTTIME %4")
365  .arg(msg).arg(gCoreContext->GetHostName())
366  .arg(pginfo->GetChanID())
368  }
369  else
370  {
371  LOG(VB_GENERAL, LOG_ERR, LOC + "SendMythSystemPlayEvent() called with "
372  "empty ProgramInfo");
373  }
374 }
375 
376 /****************************************************************************/
377 
390  const char *name)
391  : RawSettingsEditor(parent, name)
392 {
393  m_title = tr("System Event Command Editor");
394 
395  // Event names are programmatically converted to settings names in
396  // EventNameToSetting(). For convenience of searching the code
397  // base, the event names are listed in comments.
398  m_settings["EventCmdRecPending"] = // REC_PENDING
399  tr("Recording pending");
400  m_settings["EventCmdRecPreFail"] = // REC_PREFAIL
401  tr("Recording about to fail");
402  m_settings["EventCmdRecFailing"] = // REC_FAILING
403  tr("Recording failing");
404  m_settings["EventCmdRecStarted"] = // REC_STARTED
405  tr("Recording started");
406  m_settings["EventCmdRecStartedWriting"] = // REC_STARTED_WRITING
407  tr("Recording started writing");
408  m_settings["EventCmdRecFinished"] = // REC_FINISHED
409  tr("Recording finished");
410  m_settings["EventCmdRecDeleted"] = // REC_DELETED
411  tr("Recording deleted");
412  m_settings["EventCmdRecExpired"] = // REC_EXPIRED
413  tr("Recording expired");
414  m_settings["EventCmdLivetvStarted"] = // LIVETV_STARTED
415  tr("LiveTV started");
416  m_settings["EventCmdLivetvEnded"] = // LIVETV_ENDED
417  tr("LiveTV ended");
418  m_settings["EventCmdPlayStarted"] = // PLAY_STARTED
419  tr("Playback started");
420  m_settings["EventCmdPlayStopped"] = // PLAY_STOPPED
421  tr("Playback stopped");
422  m_settings["EventCmdPlayPaused"] = // PLAY_PAUSED
423  tr("Playback paused");
424  m_settings["EventCmdPlayUnpaused"] = // PLAY_UNPAUSED
425  tr("Playback unpaused");
426  m_settings["EventCmdPlayChanged"] = // PLAY_CHANGED
427  tr("Playback program changed");
428  m_settings["EventCmdTuningSignalTimeout"] = // TUNING_SIGNAL_TIMEOUT
429  tr("Tuning signal waiting");
430  m_settings["EventCmdMasterStarted"] = // MASTER_STARTED
431  tr("Master backend started");
432  m_settings["EventCmdMasterShutdown"] = // MASTER_SHUTDOWN
433  tr("Master backend shutdown");
434  m_settings["EventCmdClientConnected"] = // CLIENT_CONNECTED
435  tr("Client connected to master backend");
436  m_settings["EventCmdClientDisconnected"] = // CLIENT_DISCONNECTED
437  tr("Client disconnected from master backend");
438  m_settings["EventCmdSlaveConnected"] = // SLAVE_CONNECTED
439  tr("Slave backend connected to master");
440  m_settings["EventCmdSlaveDisconnected"] = // SLAVE_DISCONNECTED
441  tr("Slave backend disconnected from master");
442  m_settings["EventCmdNetCtrlConnected"] = // NET_CTRL_CONNECTED
443  tr("Network Control client connected");
444  m_settings["EventCmdNetCtrlDisconnected"] = // NET_CTRL_DISCONNECTED
445  tr("Network Control client disconnected");
446  m_settings["EventCmdMythfilldatabaseRan"] = // MYTHFILLDATABASE_RAN
447  tr("mythfilldatabase ran");
448  m_settings["EventCmdSchedulerRan"] = // SCHEDULER_RAN
449  tr("Scheduler ran");
450  m_settings["EventCmdSettingsCacheCleared"] = // SETTINGS_CACHE_CLEARED
451  tr("Settings cache cleared");
452  m_settings["EventCmdScreenType"] = // SCREEN_TYPE
453  tr("Screen created or destroyed");
454  m_settings["EventCmdKey01"] = // KEY_%1
455  tr("Keystroke event #1");
456  m_settings["EventCmdKey02"] = // KEY_%1
457  tr("Keystroke event #2");
458  m_settings["EventCmdKey03"] = // KEY_%1
459  tr("Keystroke event #3");
460  m_settings["EventCmdKey04"] = // KEY_%1
461  tr("Keystroke event #4");
462  m_settings["EventCmdKey05"] = // KEY_%1
463  tr("Keystroke event #5");
464  m_settings["EventCmdKey06"] = // KEY_%1
465  tr("Keystroke event #6");
466  m_settings["EventCmdKey07"] = // KEY_%1
467  tr("Keystroke event #7");
468  m_settings["EventCmdKey08"] = // KEY_%1
469  tr("Keystroke event #8");
470  m_settings["EventCmdKey09"] = // KEY_%1
471  tr("Keystroke event #9");
472  m_settings["EventCmdKey10"] = // KEY_%1
473  tr("Keystroke event #10");
474  m_settings["EventCmdCecCommandReceived"] = // CEC_COMMAND_RECEIVED
475  tr("CEC command received");
476  m_settings["EventCmdAll"] = // EventCmdAll
477  tr("Any event");
478 }
479 
480 /* vim: set expandtab tabstop=4 shiftwidth=4: */
build_compdb.args
args
Definition: build_compdb.py:11
MythSystemEventHandler::MythSystemEventHandler
MythSystemEventHandler()
Null Constructor.
Definition: mythsystemevent.cpp:75
e
QDomElement e
Definition: mythplugins/mytharchive/mytharchivehelper/main.cpp:1420
MythCoreContext::SendMessage
void SendMessage(const QString &message)
Definition: mythcorecontext.cpp:1526
MythDate::toString
QString toString(const QDateTime &raw_dt, uint format)
Returns formatted string representing the time.
Definition: mythdate.cpp:80
MythEvent::MythEventMessage
static Type MythEventMessage
Definition: mythevent.h:73
GENERIC_EXIT_OK
#define GENERIC_EXIT_OK
Exited with no error.
Definition: exitcodes.h:10
RecordingInfo::kFoundProgram
@ kFoundProgram
Definition: recordinginfo.h:181
kMSDontBlockInputDevs
@ kMSDontBlockInputDevs
avoid blocking LIRC & Joystick Menu
Definition: mythsystem.h:35
RecordingInfo
Holds information on a TV Program one might wish to record.
Definition: recordinginfo.h:34
MythEvent
This class is used as a container for messages.
Definition: mythevent.h:16
RawSettingsEditor
An editor screen that allows manipulation of raw settings values.
Definition: rawsettingseditor.h:25
MythScreenStack
Definition: mythscreenstack.h:16
arg
arg(title).arg(filename).arg(doDelete))
RawSettingsEditor::m_title
QString m_title
Definition: rawsettingseditor.h:51
LOC
#define LOC
Definition: mythsystemevent.cpp:17
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23
MythSystemEventHandler::SubstituteMatches
static void SubstituteMatches(const QStringList &tokens, QString &command)
Substitutes MATCH% variables in given command line.
Definition: mythsystemevent.cpp:104
mythsystemevent.h
myth_system
uint myth_system(const QString &command, uint flags, std::chrono::seconds timeout)
Definition: mythsystemlegacy.cpp:502
MThreadPool::startReserved
void startReserved(QRunnable *runnable, const QString &debugName, std::chrono::milliseconds waitForAvailMS=0ms)
Definition: mthreadpool.cpp:360
remoteutil.h
MythEvent::Message
const QString & Message() const
Definition: mythevent.h:65
ProgramInfo::GetRecordingStartTime
QDateTime GetRecordingStartTime(void) const
Approximate time the recording started.
Definition: programinfo.h:402
SystemEventThread
QRunnable class for running MythSystemEvent handler commands.
Definition: mythsystemevent.cpp:28
mythsystemlegacy.h
MythObservable::addListener
void addListener(QObject *listener)
Add a listener to the observable.
Definition: mythobservable.cpp:38
MythSystemEventHandler::EventNameToSetting
static QString EventNameToSetting(const QString &name)
Convert an MythSystemEvent name to a database setting name.
Definition: mythsystemevent.cpp:224
programinfo.h
mythlogging.h
ProgramInfo::GetRecordingStatus
RecStatus::Type GetRecordingStatus(void) const
Definition: programinfo.h:445
MythDate::kFilename
@ kFilename
Default UTC, "yyyyMMddhhmmss".
Definition: mythdate.h:18
MythCoreContext::SendSystemEvent
void SendSystemEvent(const QString &msg)
Definition: mythcorecontext.cpp:1553
SystemEventThread::SystemEventThread
SystemEventThread(QString cmd, QString eventName="")
Constructor for creating a SystemEventThread.
Definition: mythsystemevent.cpp:37
verboseMask
uint64_t verboseMask
Definition: logging.cpp:100
uint
unsigned int uint
Definition: compat.h:140
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:60
RecordingInfo::LoadStatus
LoadStatus
Definition: recordinginfo.h:179
RecordingInfo::kNoProgram
@ kNoProgram
Definition: recordinginfo.h:180
MythDate::fromString
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:30
SystemEventThread::m_event
QString m_event
Definition: mythsystemevent.cpp:66
ProgramInfo::GetInputID
uint GetInputID(void) const
Definition: programinfo.h:461
mthreadpool.h
ProgramInfo::GetChanID
uint GetChanID(void) const
This is the unique key used in the database to locate tuning information.
Definition: programinfo.h:370
SystemEventThread::m_command
QString m_command
Definition: mythsystemevent.cpp:65
RecordingInfo::SubstituteMatches
void SubstituteMatches(QString &str) override
Replace MATCH% vars in the specified string.
Definition: recordinginfo.cpp:1587
ProgramInfo
Holds information on recordings and videos.
Definition: programinfo.h:67
RawSettingsEditor::m_settings
QMap< QString, QString > m_settings
Definition: rawsettingseditor.h:52
mythcorecontext.h
SendMythSystemPlayEvent
void SendMythSystemPlayEvent(const QString &msg, const ProgramInfo *pginfo)
Definition: mythsystemevent.cpp:359
MythSystemEventHandler::customEvent
void customEvent(QEvent *e) override
Custom Event handler for receiving and processing System Events.
Definition: mythsystemevent.cpp:257
cardutil.h
MythSystemEventEditor::MythSystemEventEditor
MythSystemEventEditor(MythScreenStack *parent, const char *name=nullptr)
Constructor for the MythSystemEvent settings editor.
Definition: mythsystemevent.cpp:389
std
Definition: mythchrono.h:23
MythDate::ISODate
@ ISODate
Default UTC.
Definition: mythdate.h:17
CardUtil::GetVBIDevice
static QString GetVBIDevice(uint inputid)
Definition: cardutil.h:288
SendMythSystemRecEvent
void SendMythSystemRecEvent(const QString &msg, const RecordingInfo *pginfo)
Definition: mythsystemevent.cpp:331
MythCoreContext::GetHostName
QString GetHostName(void)
Definition: mythcorecontext.cpp:858
SystemEventThread::run
void run(void) override
Runs the System Event handler command.
Definition: mythsystemevent.cpp:45
logPropagateArgs
QString logPropagateArgs
Definition: logging.cpp:85
MythSystemEventHandler::~MythSystemEventHandler
~MythSystemEventHandler() override
Destructor.
Definition: mythsystemevent.cpp:86
exitcodes.h
MThreadPool::globalInstance
static MThreadPool * globalInstance(void)
Definition: mthreadpool.cpp:306
MythObservable::removeListener
void removeListener(QObject *listener)
Remove a listener to the observable.
Definition: mythobservable.cpp:55
CardUtil::GetVideoDevice
static QString GetVideoDevice(uint inputid)
Definition: cardutil.h:284
MythCoreContext::GetSetting
QString GetSetting(const QString &key, const QString &defaultval="")
Definition: mythcorecontext.cpp:918