plexMonitor.pl 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use File::Basename;
  5. use Time::HiRes qw( usleep );
  6. use File::Temp qw( tempfile );
  7. # App config
  8. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  9. chomp($TEMP_DIR);
  10. my $DATA_DIR = $TEMP_DIR . '/plexMonitor';
  11. my $EXEC_DIR = $ENV{'HOME'} . '/bin/video';
  12. # Debug
  13. my $DEBUG = 0;
  14. if ($ENV{'DEBUG'}) {
  15. $DEBUG = 1;
  16. }
  17. # Command-line arguments
  18. my ($DELAY) = @ARGV;
  19. if (!$DELAY) {
  20. $DELAY = 0;
  21. }
  22. $DELAY = int($DELAY) * 1000000; # Microseconds;
  23. # Sanity check
  24. if (!-d $EXEC_DIR || !-d $TEMP_DIR) {
  25. die("Bad config\n");
  26. }
  27. # Mode
  28. my $MODE = 'PLAYING';
  29. my $CMD = 'plex-playing';
  30. if (basename($0) =~ /GUI/i) {
  31. $MODE = 'GUI';
  32. $CMD = 'plex-gui';
  33. }
  34. # Add the data directory as needed
  35. if (!-d $DATA_DIR) {
  36. mkdir($DATA_DIR);
  37. }
  38. # Loop forever (unless no delay is set)
  39. my $dataLast = '';
  40. do {
  41. my $changed = 0;
  42. # Run the monitor command
  43. my $cmd = $EXEC_DIR . '/' . $CMD;
  44. my $data = `$cmd`;
  45. # Compare this data set to the last
  46. if ($data ne $dataLast) {
  47. $changed = 1;
  48. }
  49. # If anything changed, save the data to disk
  50. if ($changed) {
  51. my ($fh, $tmp) = tempfile($DATA_DIR . '/' . $MODE . '.XXXXXXXX', 'UNLINK' => 0);
  52. print $fh $data;
  53. close($fh);
  54. rename($tmp, $DATA_DIR . '/' . $MODE);
  55. }
  56. # Special handling for PLAYING mode -- it's a bit of a hack, but it saves a lot of code other places
  57. if ($changed && $MODE eq 'PLAYING') {
  58. my $playing = 0;
  59. if ($data =~ /PlayStatus\:Playing/) {
  60. $playing = 1;
  61. }
  62. my ($fh, $tmp) = tempfile($DATA_DIR . '/PLAY_STATUS.XXXXXXXX', 'UNLINK' => 0);
  63. print $fh $playing;
  64. close($fh);
  65. rename($tmp, $DATA_DIR . '/PLAY_STATUS');
  66. }
  67. # Delay and loop
  68. usleep($DELAY);
  69. } until ($DELAY == 0);
  70. # Exit cleanly
  71. exit(0);