transmission.pl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. # Includes
  5. use JSON;
  6. use Date::Parse;
  7. use File::Temp qw/ :mktemp /;
  8. use File::Basename;
  9. use FindBin qw($Bin);
  10. use lib $Bin;
  11. use Fetch;
  12. # Prototypes
  13. sub session($);
  14. sub fetch($);
  15. sub getSSE($);
  16. sub getDest($$$$);
  17. sub delTor($);
  18. sub guessExt($);
  19. sub processFile($$);
  20. sub unrar($$);
  21. sub seriesCleanupLocal($);
  22. sub seriesCleanupCore($);
  23. sub seriesCleanup($);
  24. sub readDir($$);
  25. sub findMediaFiles($$);
  26. sub runAndCheck(@);
  27. # Parameters
  28. my $maxAge = 2.5 * 86400;
  29. my $tvDir = `~/bin/video/mediaPath` . '/TV';
  30. my $monitoredExec = '/Users/profplump/bin/video/torrentMonitored.pl';
  31. my $host = 'http://localhost:9091';
  32. my $url = $host . '/transmission/rpc';
  33. my $content = '{"method":"torrent-get","arguments":{"fields":["hashString","id","addedDate","comment","creator","dateCreated","isPrivate","name","totalSize","pieceCount","pieceSize","downloadedEver","error","errorString","eta","haveUnchecked","haveValid","leftUntilDone","metadataPercentComplete","peersConnected","peersGettingFromUs","peersSendingToUs","rateDownload","rateUpload","recheckProgress","sizeWhenDone","status","trackerStats","uploadedEver","uploadRatio","seedRatioLimit","seedRatioMode","downloadDir","files","fileStats"]}}';
  34. my $delContent = '{"method":"torrent-remove","arguments":{"ids":["#_ID_#"], "delete-local-data":"true"}';
  35. my $delSleep = 10;
  36. my $RAR_MIN_FILES = 4;
  37. my $FIND_MAX_DEPTH = 5;
  38. # Debug
  39. my $DEBUG = 0;
  40. if ($ENV{'DEBUG'}) {
  41. $DEBUG = 1;
  42. }
  43. # Command-line parameters
  44. my ($force, $maxDays, $hash) = @ARGV;
  45. # If a hash is provided, always process matching torrents
  46. if (defined($hash)) {
  47. $force = 1;
  48. }
  49. # Init
  50. my $fetch = Fetch->new();
  51. # Check availability of web interface
  52. $fetch->url($host);
  53. if ($DEBUG) {
  54. print STDERR "Checking for torrent web interface\n";
  55. }
  56. $fetch->fetch('nocheck' => 1);
  57. if ($fetch->status_code() != 200) {
  58. if ($DEBUG) {
  59. die("Transmission web interface not available\n");
  60. }
  61. exit(0);
  62. }
  63. # Fetch the list of paused (i.e. completed) torrents
  64. $fetch->url($url);
  65. $fetch->post_content($content);
  66. &fetch($fetch);
  67. my $torrents = decode_json($fetch->content());
  68. $torrents = $torrents->{'arguments'}->{'torrents'};
  69. # Process
  70. if ($DEBUG) {
  71. print STDERR "Processing torrents...\n";
  72. }
  73. foreach my $tor (@{$torrents}) {
  74. # Skip torrents that aren't yet done
  75. if ($tor->{'leftUntilDone'} > 0 || $tor->{'metadataPercentComplete'} < 1) {
  76. next;
  77. }
  78. # Only process recent files
  79. # Torrents created with magnet links have no dateCreated, so fake it with addedDate
  80. if ($tor->{'dateCreated'} < 946684800) {
  81. $tor->{'dateCreated'} = $tor->{'addedDate'};
  82. }
  83. if (!$force && $tor->{'dateCreated'} < time() - $maxAge) {
  84. my $age = (time() - $tor->{'dateCreated'}) / 86400;
  85. if ($DEBUG) {
  86. print STDERR 'Skipping old torrent: ' . $tor->{'name'} . ' (' . sprintf('%.0f', $age) . " days)\n";
  87. }
  88. next;
  89. }
  90. # If a hash is provided, process only that file
  91. if (defined($hash) && $tor->{'hashString'} ne $hash) {
  92. if ($DEBUG) {
  93. printf STDERR 'Skipping torrent with non-matching hash: ' . $tor->{'name'} . ' (' . $tor->{'hashString'} . ")\n";
  94. }
  95. next;
  96. }
  97. # We've decided to do something about this torrent
  98. if ($DEBUG) {
  99. print STDERR 'Processing completed torrent: ' . $tor->{'name'} . "\n";
  100. }
  101. # Handle individual files and directories
  102. my @files = ();
  103. my @newFiles = ();
  104. my $path = $tor->{'downloadDir'} . '/' . $tor->{'name'};
  105. if (!-d $path) {
  106. push(@files, $path);
  107. } else {
  108. # State variables
  109. my $IS_RAR = '';
  110. my $IS_FAKE = 0;
  111. # Look for RAR files
  112. foreach my $file (@{ $tor->{'files'} }) {
  113. if ($file->{'name'} =~ /\.rar$/i) {
  114. $IS_RAR = $tor->{'downloadDir'} . '/' . $file->{'name'};
  115. last;
  116. }
  117. }
  118. # Check for password files
  119. foreach my $file (@{ $tor->{'files'} }) {
  120. if ($file->{'name'} =~ /passw(?:or)?d/i) {
  121. print STDERR 'Password file detected in: ' . $tor->{'name'} . "\n";
  122. $IS_FAKE = 1;
  123. last;
  124. }
  125. }
  126. # Check for single-file RARs
  127. if ($IS_RAR && scalar(@{ $tor->{'files'} }) < $RAR_MIN_FILES) {
  128. print STDERR 'Single-file RAR detected in: ' . $tor->{'name'} . "\n";
  129. $IS_FAKE = 1;
  130. }
  131. # Delete fake torrents and bail
  132. if ($IS_FAKE) {
  133. if ($DEBUG) {
  134. print STDERR 'Deleting fake torrent: ' . $tor->{'name'} . "\n";
  135. }
  136. delTor($tor);
  137. next;
  138. }
  139. # Unrar if necessary
  140. if (defined($IS_RAR) && length($IS_RAR) > 0) {
  141. @newFiles = &unrar($IS_RAR, $path);
  142. }
  143. # Find all media files, recursively
  144. @files = findMediaFiles($path, 0);
  145. }
  146. # Bail if we found no files
  147. if (scalar(@files) < 1) {
  148. print STDERR 'No media files found in torrent: ' . $tor->{'name'} . "\n";
  149. next;
  150. }
  151. # Do all the normal file naming/copying/etc. if we found at least one file
  152. my $failure = 0;
  153. foreach my $file (@files) {
  154. my $result = -1;
  155. if (defined($file) && length($file) > 0 && -r $file) {
  156. $result = &processFile($file, $path);
  157. }
  158. if (defined($result) && $result == 1) {
  159. if ($DEBUG) {
  160. print STDERR 'Torrent stored successfully: ' . $tor->{'name'} . "\n";
  161. }
  162. } elsif (defined($result) && $result == -1) {
  163. print STDERR 'Deleting bad torrent: ' . $tor->{'name'} . "\n";
  164. last;
  165. } else {
  166. print STDERR 'Error storing file "' . basename($file) . '" from torrent: ' . $tor->{'name'} . "\n";
  167. $failure = 1;
  168. last;
  169. }
  170. }
  171. # Delete any files we added
  172. foreach my $file (@newFiles) {
  173. if ($DEBUG) {
  174. print STDERR 'Deleting new file: ' . basename($file) . "\n";
  175. }
  176. unlink($file);
  177. }
  178. # Only delete the torrent on success
  179. if (!$failure) {
  180. delTor($tor);
  181. next;
  182. }
  183. }
  184. # Cleanup
  185. exit(0);
  186. # Grab the session ID
  187. sub session($) {
  188. my ($fetch) = @_;
  189. my %headers = ();
  190. ($headers{'X-Transmission-Session-Id'}) = $fetch->content() =~ /X\-Transmission\-Session\-Id\:\s+(\w+)/;
  191. $fetch->headers(\%headers);
  192. }
  193. sub fetch($) {
  194. my ($fetch) = @_;
  195. $fetch->fetch('nocheck' => 1);
  196. if ($fetch->status_code() != 200) {
  197. &session($fetch);
  198. $fetch->fetch();
  199. if ($fetch->status_code() != 200) {
  200. die('Unable to fetch: ' . $fetch->status_code() . "\n");
  201. }
  202. }
  203. }
  204. sub getSSE($) {
  205. my ($name) = @_;
  206. if ($DEBUG) {
  207. print STDERR 'Finding series/season/episode for: ' . $name . "\n";
  208. }
  209. my $season = 0;
  210. my $episode = 0;
  211. my $seasonBlock = '';
  212. if ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,2})(?:\b|_)/i) {
  213. $seasonBlock = $1;
  214. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,2})/i;
  215. $season = int($season);
  216. $episode = sprintf('%02d', int($episode));
  217. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  218. $seasonBlock = $1;
  219. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  220. $season = int($season);
  221. $episode = sprintf('%02d', int($episode));
  222. } elsif ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  223. $seasonBlock = $1;
  224. my ($month, $day);
  225. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  226. $season = int($season);
  227. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  228. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  229. $seasonBlock = $1;
  230. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  231. $season = int($season);
  232. $episode = sprintf('%02d', int($episode));
  233. }
  234. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  235. if ($DEBUG) {
  236. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  237. }
  238. return;
  239. }
  240. # Assume the series titles comes before the season/episode block
  241. my $series = '';
  242. my $sIndex = index($name, $seasonBlock);
  243. if ($sIndex > 0) {
  244. $series = substr($name, 0, $sIndex - 1);
  245. $series = seriesCleanupCore($series);
  246. }
  247. if ($DEBUG) {
  248. print STDERR 'Series: ' . $series . ' Season: ' . $season . ' Episode: ' . $episode . "\n";
  249. }
  250. return ($series, $season, $episode);
  251. }
  252. sub getDest($$$$) {
  253. my ($series, $season, $episode, $ext) = @_;
  254. if ($DEBUG) {
  255. print STDERR 'Finding destintion for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  256. }
  257. # Input cleanup
  258. $episode =~ s/^0+//;
  259. # Find all our existing TV series
  260. my @shows = ();
  261. my %showsCan = ();
  262. open(SHOWS, '-|', $monitoredExec, 'STORE')
  263. or die("Unable to fork: ${!}\n");
  264. while (<SHOWS>) {
  265. chomp;
  266. my $orig = $_;
  267. my $clean = seriesCleanupLocal($_);
  268. push(@shows, $clean);
  269. $showsCan{$clean} = $orig;
  270. }
  271. close SHOWS or die("Unable to read monitored series list: ${!} ${?}\n");
  272. # See if we can find a unique series name match
  273. my $sClean = seriesCleanup($series);
  274. my $sCleanCore = seriesCleanupCore($series);
  275. my $sMatch = '\b' . $sClean . '\b';
  276. $series = '';
  277. foreach my $show (@shows) {
  278. # Match the folder name or the search_name
  279. my $coarse_match = 0;
  280. if ($show =~ /${sMatch}/i) {
  281. $coarse_match = 1;
  282. } else {
  283. my $search_name = '';
  284. my $file = $tvDir . '/' . $showsCan{$show} . '/search_name';
  285. if (-e $file) {
  286. open(FH, $file)
  287. or die('Unable to read search_name file: ' . $file . "\n");
  288. $search_name = <FH>;
  289. close(FH);
  290. }
  291. if ($search_name) {
  292. $search_name = seriesCleanup($search_name);
  293. if ($search_name =~ /${sMatch}/i) {
  294. $coarse_match = 1;
  295. }
  296. }
  297. }
  298. # If we got a course match, continue checking
  299. if ($coarse_match) {
  300. # Enforce any secondary matching rules (for ambiguous titles)
  301. my $detail_match = 1;
  302. {
  303. my @lines;
  304. my $file = $tvDir . '/' . $showsCan{$show} . '/must_match';
  305. if (-e $file) {
  306. local ($/, *FH);
  307. open(FH, $file)
  308. or die('Unable to read must_match file: ' . $file . "\n");
  309. my @tmp = <FH>;
  310. close(FH);
  311. push(@lines, @tmp);
  312. }
  313. foreach my $line (@lines) {
  314. chomp($line);
  315. if (!eval('$sCleanCore =~ m' . $line)) {
  316. if ($DEBUG) {
  317. print STDERR 'Skipping ' . $show . ' due to must_match failure for: ' . $line . "\n";
  318. }
  319. $detail_match = 0;
  320. last;
  321. }
  322. }
  323. }
  324. if (!$detail_match) {
  325. next;
  326. }
  327. # Bail if we find more than one matching series
  328. if (length($series) > 0) {
  329. print STDERR 'Matched both ' . $series . ' and ' . $show . "\n";
  330. return;
  331. }
  332. # If we're still around this is the first series title match
  333. $series = $show;
  334. }
  335. }
  336. if (length($series) < 1) {
  337. if ($DEBUG) {
  338. print STDERR 'No series match for: ' . $sMatch . "\n";
  339. }
  340. return;
  341. }
  342. # Lookup the canonical name from the matched name
  343. $series = $showsCan{$series};
  344. # Make sure we have the right season folder
  345. my $seriesDir = $tvDir . '/' . $series;
  346. my $seasonDir = $seriesDir . '/' . 'Season ' . $season;
  347. if (!-d $seasonDir) {
  348. print STDERR 'No season folder for: ' . $series . ' S' . $season . "\n";
  349. return;
  350. }
  351. # Bail if we already have this episode
  352. my @episodes = readDir($seasonDir, 0);
  353. foreach my $ep (@episodes) {
  354. my ($epNum) = $ep =~ /^\s*([\d\-]+)\s*\-\s*/;
  355. if (!defined($epNum)) {
  356. next;
  357. }
  358. $epNum =~ s/^0+//;
  359. if ($epNum eq $episode) {
  360. print STDERR 'Existing episode for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  361. return;
  362. }
  363. }
  364. # Construct the final path
  365. if (!defined($ext) || length($ext) < 1) {
  366. $ext = 'avi';
  367. }
  368. if ($episode =~ /^\d+$/) {
  369. $episode = sprintf('%02d', $episode);
  370. }
  371. my $dest = sprintf('%s/%s - NoName.%s', $seasonDir, $episode, $ext);
  372. if ($DEBUG) {
  373. print STDERR 'Destination: ' . $dest . "\n";
  374. }
  375. return $dest;
  376. }
  377. sub delTor($) {
  378. my ($tor) = @_;
  379. if ($DEBUG) {
  380. print STDERR 'Deleting torrent: ' . $tor->{'name'} . "\n";
  381. }
  382. # Sleep to avoid bugs in Transmission (i.e. multiple deletes fail)
  383. sleep($delSleep);
  384. # Construct the content
  385. my $id = $tor->{'hashString'};
  386. my $content = $delContent;
  387. $content =~ s/\#_ID_\#/${id}/;
  388. # Send the command
  389. &session($fetch);
  390. $fetch->post_content($content);
  391. &fetch($fetch);
  392. }
  393. sub guessExt($) {
  394. my ($file) = @_;
  395. # Believe most non-avi file extensions without checking
  396. # It's mostly "avi" that lies, and the checks are expensive
  397. my $ext = '';
  398. {
  399. my $orig_ext = basename($file);
  400. $orig_ext =~ s/^.*\.(\w{2,3})$/$1/;
  401. $orig_ext = lc($orig_ext);
  402. if ($orig_ext eq 'mkv' || $orig_ext eq 'ts') {
  403. $ext = $orig_ext;
  404. }
  405. }
  406. # Ask movInfo.pl about the demuxer
  407. if (!$ext) {
  408. my $demux = '';
  409. open(INFO, '-|', $ENV{'HOME'} . '/bin/video/movInfo.pl', $file, 'DEMUXER');
  410. while (<INFO>) {
  411. $demux .= $_;
  412. }
  413. close(INFO);
  414. $demux =~ s/^\s+//;
  415. $demux =~ s/\s+$//;
  416. # Grab a MIME type from file(1)
  417. my $mime = '';
  418. open(FILE, '-|', 'file', '-b', $file);
  419. while (<FILE>) {
  420. $mime .= $_;
  421. }
  422. close(FILE);
  423. $mime =~ s/^\s+//;
  424. $mime =~ s/\s+$//;
  425. $mime =~ s/\;.*$//;
  426. $mime =~ s/^video\///i;
  427. # Try to pick an extension we understand
  428. $ext = 'avi';
  429. if ($demux =~ /mkv/i || $mime =~ /Matroska/i) {
  430. $ext = 'mkv';
  431. } elsif ($demux =~ /asf/i || $mime =~ /\bASF\b/i) {
  432. $ext = 'wmv';
  433. } elsif ($mime =~ /\bZIP/i) {
  434. $ext = 'zip';
  435. } elsif ($mime =~ /\bAVI\b/i) {
  436. $ext = 'avi';
  437. } elsif ($demux =~ /mpegts/i) {
  438. $ext = 'ts';
  439. }
  440. }
  441. return $ext;
  442. }
  443. sub processFile($$) {
  444. my ($file, $path) = @_;
  445. if ($DEBUG) {
  446. print STDERR 'Attempting to process file: ' . basename($file) . "\n";
  447. }
  448. # Guess a file extension
  449. my $ext = &guessExt($file);
  450. # Delete WMV files -- mostly viruses
  451. if ($ext =~ /wmv/i) {
  452. print STDERR 'Declining to save WMV file: ' . basename($file) . "\n";
  453. return -1;
  454. }
  455. # Delete ZIP files -- mostly fake
  456. if ($ext =~ /zip/i) {
  457. print STDERR 'Declining to save ZIP file: ' . basename($file) . "\n";
  458. return -1;
  459. }
  460. # Allow multiple guesses at the series/season/episode
  461. my $dest = '';
  462. my $filename = basename($file);
  463. LOOP: {
  464. # Determine the series, season, and episode number
  465. my ($series, $season, $episode) = &getSSE($filename);
  466. if ( defined($series)
  467. && length($series) > 0
  468. && defined($season)
  469. && $season > 0
  470. && defined($episode)
  471. && length($episode) > 0
  472. && $episode ne '0')
  473. {
  474. # Find the proper destination for this torrent, if any
  475. $dest = &getDest($series, $season, $episode, $ext);
  476. }
  477. # Sanity/loop check
  478. if (!defined($dest) || length($dest) < 1) {
  479. # If there is no match but the torrent is a folder
  480. # retry the guess using the torrent path
  481. if ($file ne $path) {
  482. my $newName = basename($path);
  483. if ($newName ne $filename) {
  484. $filename = basename($path);
  485. redo LOOP;
  486. }
  487. }
  488. # Otherwise we just fail
  489. print STDERR 'No destination for: ' . basename($file) . "\n";
  490. return;
  491. }
  492. }
  493. # Copy with system tools
  494. my $tmp = mktemp($dest . '.XXXXXXXX');
  495. runAndCheck(('cp', $file, $tmp));
  496. rename($tmp, $dest);
  497. # Return success
  498. return 1;
  499. }
  500. sub unrar($$) {
  501. my ($file, $path) = @_;
  502. if ($DEBUG) {
  503. print STDERR 'UnRARing: ' . basename($file) . "\n";
  504. }
  505. # Keep a list of old files, so we can find/delete the output
  506. my @beforeFiles = readDir($path, 1);
  507. # Run the unrar utility
  508. my $pid = fork();
  509. if (!defined($pid)) {
  510. print STDERR "Unable to fork for RAR\n";
  511. return;
  512. } elsif ($pid == 0) {
  513. # Child
  514. close(STDOUT);
  515. close(STDERR);
  516. chdir($path);
  517. my @args = ('unrar', 'e', '-p-', '-y', $file);
  518. exec { $args[0] } @args;
  519. }
  520. # Wait for the child
  521. waitpid($pid, 0);
  522. # Compare the old file list to the new one
  523. my @newFiles = ();
  524. my @afterFiles = readDir($path, 1);
  525. foreach my $file (@afterFiles) {
  526. my $found = 0;
  527. foreach my $file2 (@beforeFiles) {
  528. if ($file eq $file2) {
  529. $found = 1;
  530. last;
  531. }
  532. }
  533. if (!$found) {
  534. push(@newFiles, $file);
  535. }
  536. }
  537. # Return the list of added files
  538. return @newFiles;
  539. }
  540. sub seriesCleanupLocal($) {
  541. my ($name) = @_;
  542. $name =~ s/\.//g;
  543. return seriesCleanup($name);
  544. }
  545. sub seriesCleanupCore($) {
  546. my ($name) = @_;
  547. $name =~ s/\b(?:and|\&)\b/ /ig;
  548. $name =~ s/^\s*The\b//ig;
  549. $name =~ s/\[[^\]]*\]//g;
  550. $name =~ s/\{[^\}]*\}//g;
  551. $name =~ s/[\(\)]//g;
  552. $name =~ s/[\'\"]//g;
  553. $name =~ s/[^\w\s]+/ /g;
  554. $name =~ s/_+/ /g;
  555. $name =~ s/\s+/ /g;
  556. $name =~ s/^\s*//;
  557. $name =~ s/\s*$//;
  558. return $name;
  559. }
  560. sub seriesCleanup($) {
  561. my ($name) = @_;
  562. $name =~ s/\s*\(?US\)?\s*$//i;
  563. $name =~ s/\s*\(?20[01][0-9]\)?\s*$//;
  564. return seriesCleanupCore($name);
  565. }
  566. sub readDir($$) {
  567. my ($indir, $long) = @_;
  568. # Clean up the input directory
  569. $indir =~ s/\/+$//;
  570. my @files = ();
  571. if (!opendir(DIR, $indir)) {
  572. warn('readDir: Unable to read directory: ' . $indir . ': ' . $! . "\n");
  573. return;
  574. }
  575. foreach my $file (readdir(DIR)) {
  576. my $keep = 0;
  577. # Skip junk
  578. if ( $file eq '.'
  579. || $file eq '..'
  580. || $file =~ /\._/)
  581. {
  582. next;
  583. }
  584. # Save the full path
  585. if ($long) {
  586. push(@files, $indir . '/' . $file);
  587. } else {
  588. push(@files, $file);
  589. }
  590. }
  591. closedir(DIR);
  592. # Sorts the files before returning to the caller
  593. my @orderedFiles = ();
  594. @orderedFiles = sort(@files);
  595. # Return the file list
  596. return (@orderedFiles);
  597. }
  598. sub findMediaFiles($$) {
  599. my ($path, $depth) = @_;
  600. my @files = ();
  601. # Recursion limit
  602. if ($depth > $FIND_MAX_DEPTH) {
  603. return ();
  604. }
  605. my @tmpFiles = readDir($path, 1);
  606. foreach my $file (@tmpFiles) {
  607. # Skip sample files
  608. if ($file =~ /sample/i) {
  609. next;
  610. }
  611. # Recurse on directories
  612. if (-d $file) {
  613. push(@files, findMediaFiles($file, $depth + 1));
  614. next;
  615. }
  616. # Save matching files
  617. if ($file =~ /\.(?:avi|mkv|m4v|mov|mp4|ts|wmv)$/i) {
  618. push(@files, $file);
  619. next;
  620. }
  621. }
  622. return @files;
  623. }
  624. sub runAndCheck(@) {
  625. my (@args) = (@_);
  626. # Run
  627. system { $args[0] } @args;
  628. my $res = $?;
  629. # Die on any error
  630. if ($res == -1) {
  631. die('Unable to execute program: ' . join(' ', @args) . ': ' . $! . "\n");
  632. } elsif ($res & 127) {
  633. die('Child exited on signal: ' . join(' ', @args) . ': ' . ($res & 127) . "\n");
  634. } elsif ($res != 0) {
  635. die('Child exited with non-zero value: ' . join(' ', @args) . ': ' . ($res >> 8) . "\n");
  636. }
  637. # If we get here, all is well
  638. return 1;
  639. }