transmission.pl 18 KB

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