plexMonitor.pl 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use LWP::Simple;
  5. use File::Basename;
  6. use Time::HiRes qw( usleep );
  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. $DELAY *= 1000000; # Microseconds;
  30. # Sanity check
  31. if (!-d $TEMP_DIR) {
  32. die("Bad config\n");
  33. }
  34. # Mode
  35. my $MODE = 'PLAYING';
  36. if (basename($0) =~ /GUI/i) {
  37. $MODE = 'GUI';
  38. }
  39. # Add the data directory as needed
  40. if (!-d $DATA_DIR) {
  41. mkdir($DATA_DIR);
  42. }
  43. # Loop forever (unless no delay is set)
  44. my $dataLast = '';
  45. do {
  46. my $changed = 0;
  47. # Run the monitor command
  48. my $data = xbmcHTTP($CMDS{$MODE});
  49. # Compare this data set to the last
  50. if ($data ne $dataLast) {
  51. $changed = 1;
  52. }
  53. # If anything changed, save the data to disk
  54. if ($changed) {
  55. my ($fh, $tmp) = tempfile($DATA_DIR . '/' . $MODE . '.XXXXXXXX', 'UNLINK' => 0);
  56. print $fh $data;
  57. close($fh);
  58. rename($tmp, $DATA_DIR . '/' . $MODE);
  59. }
  60. # Special handling for PLAYING mode -- it's a bit of a hack, but it saves a lot of code other places
  61. if ($changed && $MODE eq 'PLAYING') {
  62. my $playing = 0;
  63. if ($data =~ /PlayStatus\:Playing/) {
  64. $playing = 1;
  65. }
  66. my ($fh, $tmp) = tempfile($DATA_DIR . '/PLAY_STATUS.XXXXXXXX', 'UNLINK' => 0);
  67. print $fh $playing;
  68. close($fh);
  69. rename($tmp, $DATA_DIR . '/PLAY_STATUS');
  70. }
  71. # Delay and loop
  72. usleep($DELAY);
  73. } until ($DELAY == 0);
  74. # Exit cleanly
  75. exit(0);
  76. sub xbmcHTTP($) {
  77. my ($cmd) = @_;
  78. return get('http://localhost:3000/xbmcCmds/xbmcHttp?command=' . $cmd);
  79. }