plexMonitor-json.pl 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. use URI::Escape;
  9. use JSON;
  10. # Prototypes
  11. sub buildCmd($$);
  12. sub xbmcJSON($$);
  13. sub printHash($$);
  14. # App config
  15. my $BASE_URL = 'http://localhost:3005/jsonrpc?request=';
  16. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  17. chomp($TEMP_DIR);
  18. my $DATA_DIR = $TEMP_DIR . '/plexMonitor';
  19. # Debug
  20. my $DEBUG = 0;
  21. if ($ENV{'DEBUG'}) {
  22. $DEBUG = 1;
  23. }
  24. my $JSON_DEBUG = 0;
  25. if ($ENV{'JSON_DEBUG'}) {
  26. $JSON_DEBUG = 1;
  27. }
  28. # Command-line arguments
  29. my ($DELAY) = @ARGV;
  30. if (!$DELAY) {
  31. $DELAY = 0;
  32. }
  33. # Sanity check
  34. if (!-d $TEMP_DIR) {
  35. die("Bad config\n");
  36. }
  37. # Add the data directory as needed
  38. if (!-d $DATA_DIR) {
  39. mkdir($DATA_DIR);
  40. }
  41. # Build our output file name
  42. my $OUT_FILE = $DATA_DIR . '/PLEX';
  43. # Loop forever (unless no delay is set)
  44. my %data = ();
  45. my %dataLast = ();
  46. do {
  47. # Only update the file on a change
  48. my $changed = 0;
  49. %dataLast = %data;
  50. %data = (
  51. 'playing' => 0,
  52. 'playerid' => -1,
  53. 'time' => 0,
  54. 'title' => '',
  55. 'season', => '',
  56. 'episode', => '',
  57. 'duration', => '',
  58. 'showtitle', => '',
  59. 'thumbnail', => '',
  60. 'file', => '',
  61. 'fanart', => '',
  62. 'album' => '',
  63. 'artist', => '',
  64. 'type' => '',
  65. 'windowid' => '',
  66. 'window' => '',
  67. 'selection' => '',
  68. );
  69. # See if anything is playing
  70. my $result = xbmcJSON('Player.GetActivePlayers', undef());
  71. if (defined($result) && exists($result->{'playerid'})) {
  72. $data{'playing'} = 1;
  73. $data{'playerid'} = $result->{'playerid'} + 0;
  74. }
  75. # Get details about the playing item
  76. if ($data{'playing'}) {
  77. $result = xbmcJSON('Player.GetProperties', { 'playerid' => $data{'playerid'}, 'properties' => ['time'] });
  78. if (defined($result) && exists($result->{'time'})) {
  79. $data{'time'} = 0;
  80. if (exists($result->{'time'}->{'hours'})) {
  81. $data{'time'} += ($result->{'time'}->{'hours'} * 3600);
  82. }
  83. if (exists($result->{'time'}->{'minutes'})) {
  84. $data{'time'} += ($result->{'time'}->{'minutes'} * 60);
  85. }
  86. if (exists($result->{'time'}->{'seconds'})) {
  87. $data{'time'} += $result->{'time'}->{'seconds'};
  88. }
  89. if (exists($result->{'time'}->{'milliseconds'})) {
  90. $data{'time'} += ($result->{'time'}->{'milliseconds'} / 1000);
  91. }
  92. }
  93. $result = xbmcJSON(
  94. 'Player.GetItem',
  95. {
  96. 'playerid' => $data{'playerid'},
  97. 'properties' => [ 'title', 'season', 'episode', 'duration', 'showtitle', 'thumbnail', 'file', 'fanart', 'album', 'artist' ]
  98. }
  99. );
  100. if (defined($result) && exists($result->{'item'})) {
  101. foreach my $key ('title', 'season', 'episode', 'duration', 'showtitle', 'thumbnail', 'file', 'fanart', 'album', 'type') {
  102. if (exists($result->{'item'}->{$key})) {
  103. $data{$key} = $result->{'item'}->{$key};
  104. }
  105. }
  106. if (exists($result->{'item'}->{'artist'})) {
  107. if (ref($result->{'item'}->{'artist'}) eq 'ARRAY') {
  108. $data{'artist'} = join(', ', @{ $result->{'item'}->{'artist'} });
  109. } else {
  110. warn("Invalid artist array\n");
  111. }
  112. }
  113. }
  114. }
  115. # Get details about the GUI
  116. $result = xbmcJSON('GUI.GetProperties', { 'properties' => [ 'currentcontrol', 'currentwindow' ] });
  117. if (defined($result)) {
  118. if (exists($result->{'currentwindow'})) {
  119. if (exists($result->{'currentwindow'}->{'label'})) {
  120. $data{'window'} = $result->{'currentwindow'}->{'label'};
  121. }
  122. if (exists($result->{'currentwindow'}->{'id'})) {
  123. $data{'windowid'} = $result->{'currentwindow'}->{'id'};
  124. }
  125. }
  126. if (exists($result->{'currentcontrol'})) {
  127. if (exists($result->{'currentcontrol'}->{'label'})) {
  128. $data{'selection'} = $result->{'currentcontrol'}->{'label'};
  129. }
  130. }
  131. }
  132. # Compare this data set to the last
  133. foreach my $key (keys(%data)) {
  134. if (!exists($dataLast{$key}) || $data{$key} ne $dataLast{$key}) {
  135. $changed = 1;
  136. last;
  137. }
  138. }
  139. # Ensure the output file exists
  140. if (!-r $OUT_FILE) {
  141. $changed = 1;
  142. }
  143. # If anything changed, save the data to disk
  144. if ($changed) {
  145. my $str = '';
  146. foreach my $key (keys(%data)) {
  147. $str .= $key . ' => ' . $data{$key} . "\n";
  148. }
  149. if ($DEBUG) {
  150. print STDERR $str;
  151. }
  152. my ($fh, $tmp) = tempfile($OUT_FILE . '.XXXXXXXX', 'UNLINK' => 0);
  153. print $fh $str;
  154. close($fh);
  155. rename($tmp, $OUT_FILE);
  156. }
  157. # Delay and loop
  158. sleep($DELAY);
  159. } until ($DELAY == 0);
  160. # Exit cleanly
  161. exit(0);
  162. sub buildCmd($$) {
  163. my ($method, $params) = @_;
  164. if (!defined($method) || length($method) < 1) {
  165. warn('No method name provided');
  166. return undef();
  167. }
  168. # Init the command structure
  169. my %cmd = (
  170. 'jsonrpc' => '2.0',
  171. 'id' => '1',
  172. 'method' => $method,
  173. );
  174. # Add parameters, if provided
  175. if (defined($params) && ref($params) eq 'HASH') {
  176. $cmd{'params'} = $params;
  177. }
  178. # Return as JSON
  179. return encode_json(\%cmd);
  180. }
  181. sub xbmcJSON($$) {
  182. my ($method, $params) = @_;
  183. my $cmd = buildCmd($method, $params);
  184. # Send the request
  185. if ($JSON_DEBUG) {
  186. print STDERR 'Sending command: ' . $cmd . "\n";
  187. }
  188. my $data = get($BASE_URL . uri_escape($cmd));
  189. if (!defined($data)) {
  190. if ($DEBUG) {
  191. print STDERR "No data returned from RPC call\n";
  192. }
  193. return undef();
  194. }
  195. # Parse into a perl data structure
  196. my $retval = decode_json($data);
  197. if (!defined($retval) || ref($retval) ne 'HASH') {
  198. print STDERR 'Invalid JSON: ' . $data . "\n";
  199. return undef();
  200. }
  201. # Reduce to the result section
  202. if (exists($retval->{'result'})) {
  203. if (ref($retval->{'result'}) eq 'HASH') {
  204. $retval = $retval->{'result'};
  205. } elsif (ref($retval->{'result'}) eq 'ARRAY') {
  206. $retval = @{ $retval->{'result'} }[0];
  207. }
  208. }
  209. # Return what we've got
  210. if ($JSON_DEBUG) {
  211. print "Result:\n";
  212. printHash($retval, "\t");
  213. }
  214. return $retval;
  215. }
  216. sub printHash($$) {
  217. my ($hash, $prefix) = @_;
  218. my $nextPrefix = $prefix . substr($prefix, 0, 1);
  219. if (!defined($hash)) {
  220. return;
  221. } elsif (ref($hash) ne 'HASH') {
  222. print STDERR 'Invalid hash: ' . $hash . "\n";
  223. } else {
  224. foreach my $key (keys(%{$hash})) {
  225. if (ref($hash->{$key}) eq 'HASH') {
  226. print STDERR $prefix . $key . ":\n";
  227. printHash($hash->{$key}, $nextPrefix);
  228. } elsif (ref($hash->{$key}) eq 'ARRAY') {
  229. print STDERR $prefix . $key . " => [\n";
  230. foreach my $element (@{ $hash->{$key} }) {
  231. if (ref($element) eq 'HASH') {
  232. printHash($element, $nextPrefix);
  233. } else {
  234. print STDERR $nextPrefix . $element . "\n";
  235. }
  236. }
  237. print STDERR $prefix . "]\n";
  238. } else {
  239. print STDERR $prefix . $key . ' => ' . $hash->{$key} . "\n";
  240. }
  241. }
  242. }
  243. }