plexMonitor.pl 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use LWP::Simple;
  5. use File::Basename;
  6. use Time::HiRes qw( sleep );
  7. use File::Temp qw( tempfile );
  8. # Prototypes
  9. sub xbmcHTTP($);
  10. # App config
  11. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  12. chomp($TEMP_DIR);
  13. my $DATA_DIR = $TEMP_DIR . '/plexMonitor';
  14. # xbmcHTTP commands
  15. my %CMDS = (
  16. 'PLAYING' => 'GetCurrentlyPlaying',
  17. 'GUI' => 'GetGuiStatus'
  18. );
  19. # Debug
  20. my $DEBUG = 0;
  21. if ($ENV{'DEBUG'}) {
  22. $DEBUG = 1;
  23. }
  24. # Command-line arguments
  25. my ($DELAY) = @ARGV;
  26. if (!$DELAY) {
  27. $DELAY = 0;
  28. }
  29. # Sanity check
  30. if (!-d $TEMP_DIR) {
  31. die("Bad config\n");
  32. }
  33. # Mode
  34. my $MODE = 'PLAYING';
  35. if (basename($0) =~ /GUI/i) {
  36. $MODE = 'GUI';
  37. }
  38. # Add the data directory as needed
  39. if (!-d $DATA_DIR) {
  40. mkdir($DATA_DIR);
  41. }
  42. # Build our file name
  43. my $OUT_FILE = $DATA_DIR . '/' . $MODE;
  44. # Loop forever (unless no delay is set)
  45. my $data = '';
  46. my $dataLast = '';
  47. do {
  48. # Run the monitor command
  49. my $changed = 0;
  50. $dataLast = $data;
  51. $data = xbmcHTTP($CMDS{$MODE});
  52. # Compare this data set to the last
  53. if ($data ne $dataLast) {
  54. $changed = 1;
  55. if ($DEBUG) {
  56. print STDERR "Change detected in data:\n" . $data . "\n";
  57. }
  58. }
  59. # Ensure the output file exists
  60. if (!-r $OUT_FILE) {
  61. $changed = 1;
  62. }
  63. # If anything changed, save the data to disk
  64. if ($changed) {
  65. my ($fh, $tmp) = tempfile($OUT_FILE . '.XXXXXXXX', 'UNLINK' => 0);
  66. print $fh $data;
  67. close($fh);
  68. rename($tmp, $OUT_FILE);
  69. }
  70. # Delay and loop
  71. sleep($DELAY);
  72. } until ($DELAY == 0);
  73. # Exit cleanly
  74. exit(0);
  75. sub xbmcHTTP($) {
  76. my ($cmd) = @_;
  77. # Build the command
  78. my $url = 'http://localhost:3000/xbmcCmds/xbmcHttp?command=' . $cmd;
  79. if ($DEBUG) {
  80. print STDERR 'Command: ' . $cmd . "\n\t" . $url . "\n";
  81. }
  82. # Send the request
  83. my $data = get($url);
  84. if (!defined($data)) {
  85. if ($DEBUG) {
  86. print STDERR "No data returned from HTTP call\n";
  87. }
  88. $data = '';
  89. }
  90. return $data;
  91. }