transmission.pl 17 KB

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