transmission.pl 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. # Includes
  5. use JSON;
  6. use Date::Parse;
  7. use File::Touch;
  8. use File::Temp qw/ :mktemp /;
  9. use File::Basename;
  10. use Image::ExifTool qw/ :Public/;
  11. use FindBin qw($Bin);
  12. use lib $Bin;
  13. use Fetch;
  14. # Prototypes
  15. sub session($);
  16. sub fetch($);
  17. sub getSSE($);
  18. sub getDest($$$$);
  19. sub delTor($);
  20. sub guessExt($);
  21. sub processFile($$);
  22. sub unrar($$);
  23. sub seriesCleanupLocal($);
  24. sub seriesCleanupCore($);
  25. sub seriesCleanup($);
  26. sub readDir($$);
  27. sub findMediaFiles($$);
  28. sub runAndCheck(@);
  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://baldwin-ipv4.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})(?:\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 =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/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
  435. my $exif = ImageInfo($file);
  436. if (defined($exif) && ref($exif) eq 'HASH') {
  437. if ($exif->{'MIMEType'}) {
  438. $mime = $exif->{'MIMEType'};
  439. }
  440. if ($exif->{'FileType'}) {
  441. $demux = $exif->{'FileType'};
  442. }
  443. }
  444. # Try file(1) if we didn't find a MIME type yet
  445. if (!$mime) {
  446. open(FILE, ' - | ', ' file ', ' -b ', $file);
  447. while (<FILE>) {
  448. $mime .= $_;
  449. }
  450. close(FILE);
  451. }
  452. # Cleanup the demuxer and MIME type
  453. $demux =~ s/^\s+//;
  454. $demux =~ s/\s+$//;
  455. $mime =~ s/^\s+//;
  456. $mime =~ s/\s+$//;
  457. $mime =~ s/\;.*$//;
  458. $mime =~ s/^video\///i;
  459. # Try to pick an extension we understand
  460. $ext = 'avi';
  461. if ($demux =~ /MKV/i || $mime =~ /Matroska/i) {
  462. $ext = 'mkv';
  463. } elsif ($demux =~ /ASF/i || $mime =~ /\bASF\b/i) {
  464. $ext = 'wmv';
  465. } elsif ($mime =~ /\bZIP/i) {
  466. $ext = 'zip';
  467. } elsif ($mime =~ /\bAVI\b/i) {
  468. $ext = 'avi';
  469. } elsif ($demux =~ /MPEGTS/i) {
  470. $ext = 'ts';
  471. }
  472. }
  473. return $ext;
  474. }
  475. sub processFile($$) {
  476. my ($file, $path) = @_;
  477. if ($DEBUG) {
  478. print STDERR 'Attempting to process file: ' . basename($file) . "\n";
  479. }
  480. # Skip known packaging files files with success code
  481. if ($file =~ /\/RARBG\.com.mp4$/i || $file =~ /\/RARBG\.com\.txt\//i || $file =~ /\.txt\.mp4$/) {
  482. if ($DEBUG) {
  483. print STDERR 'Declining to save packaging file: ' . $file . "\n";
  484. }
  485. return 1;
  486. }
  487. # Guess a file extension and basename
  488. my $ext = &guessExt($file);
  489. my $filename = basename($file);
  490. # Delete WMV files -- mostly viruses/fake
  491. if ($ext =~ /wmv/i) {
  492. if ($DEBUG) {
  493. print STDERR 'Declining to save WMV file: ' . $filename . "\n";
  494. }
  495. return -1;
  496. }
  497. # Delete ZIP files -- mostly fake
  498. if ($ext =~ /zip/i) {
  499. if ($DEBUG) {
  500. print STDERR 'Declining to save ZIP file: ' . $filename . "\n";
  501. }
  502. return -1;
  503. }
  504. # Allow multiple guesses at the series/season/episode
  505. my $dest = '';
  506. LOOP: {
  507. # Determine the series, season, and episode number
  508. my ($series, $season, $episode) = &getSSE($filename);
  509. if ( defined($series)
  510. && length($series) > 0
  511. && defined($season)
  512. && $season > 0
  513. && defined($episode)
  514. && length($episode) > 0
  515. && $episode ne '0')
  516. {
  517. # Find the proper destination for this torrent, if any
  518. $dest = &getDest($series, $season, $episode, $ext);
  519. }
  520. # Sanity/loop check
  521. if (!defined($dest) || length($dest) < 1) {
  522. # If there is no match but the torrent is a folder
  523. # retry the guess using the torrent path
  524. if ($file ne $path) {
  525. my $newName = basename($path);
  526. if ($newName ne $filename) {
  527. $filename = basename($path);
  528. redo LOOP;
  529. }
  530. }
  531. # Otherwise we just fail
  532. print STDERR 'No destination for: ' . basename($file) . "\n";
  533. return;
  534. }
  535. }
  536. # Copy with system tools
  537. my $tmp = mktemp($dest . '.XXXXXXXX');
  538. runAndCheck(('cp', $file, $tmp));
  539. rename($tmp, $dest);
  540. # Touch to avoid carrying dates set in the download process
  541. touch($dest);
  542. # Return success
  543. return 1;
  544. }
  545. sub unrar($$) {
  546. my ($file, $path) = @_;
  547. if ($DEBUG) {
  548. print STDERR 'UnRARing: ' . basename($file) . "\n";
  549. }
  550. # Keep a list of old files, so we can find/delete the output
  551. my @beforeFiles = readDir($path, 1);
  552. # Run the unrar utility
  553. my $pid = fork();
  554. if (!defined($pid)) {
  555. print STDERR "Unable to fork for RAR\n";
  556. return;
  557. } elsif ($pid == 0) {
  558. # Child
  559. close(STDOUT);
  560. close(STDERR);
  561. chdir($path);
  562. my @args = ('unrar', 'e', '-p-', '-y', $file);
  563. exec { $args[0] } @args;
  564. }
  565. # Wait for the child
  566. waitpid($pid, 0);
  567. # Compare the old file list to the new one
  568. my @newFiles = ();
  569. my @afterFiles = readDir($path, 1);
  570. foreach my $file (@afterFiles) {
  571. my $found = 0;
  572. foreach my $file2 (@beforeFiles) {
  573. if ($file eq $file2) {
  574. $found = 1;
  575. last;
  576. }
  577. }
  578. if (!$found) {
  579. push(@newFiles, $file);
  580. }
  581. }
  582. # Return the list of added files
  583. return @newFiles;
  584. }
  585. sub seriesCleanupLocal($) {
  586. my ($name) = @_;
  587. $name =~ s/\.//g;
  588. return seriesCleanupCore($name);
  589. }
  590. sub seriesCleanupCore($) {
  591. my ($name) = @_;
  592. $name =~ s/\b(?:and|\&)\b/ /ig;
  593. $name =~ s/^\s*The\b//ig;
  594. $name =~ s/\[[^\]]*\]//g;
  595. $name =~ s/\{[^\}]*\}//g;
  596. $name =~ s/[\(\)]//g;
  597. $name =~ s/[\'\"]//g;
  598. $name =~ s/[^\w\s]+/ /g;
  599. $name =~ s/_+/ /g;
  600. $name =~ s/\s+/ /g;
  601. $name =~ s/^\s*//;
  602. $name =~ s/\s*$//;
  603. return $name;
  604. }
  605. sub seriesCleanup($) {
  606. my ($name) = @_;
  607. $name =~ s/\s*\(?US\)?\s*$//;
  608. $name =~ s/\s*\(?20[01][0-9]\)?\s*$//;
  609. return seriesCleanupCore($name);
  610. }
  611. sub readDir($$) {
  612. my ($indir, $long) = @_;
  613. # Clean up the input directory
  614. $indir =~ s/\/+$//;
  615. my @files = ();
  616. if (!opendir(DIR, $indir)) {
  617. warn('readDir: Unable to read directory: ' . $indir . ': ' . $! . "\n");
  618. return;
  619. }
  620. foreach my $file (readdir(DIR)) {
  621. my $keep = 0;
  622. # Skip junk
  623. if ( $file eq '.'
  624. || $file eq '..'
  625. || $file =~ /\._/)
  626. {
  627. next;
  628. }
  629. # Save the full path
  630. if ($long) {
  631. push(@files, $indir . '/' . $file);
  632. } else {
  633. push(@files, $file);
  634. }
  635. }
  636. closedir(DIR);
  637. # Sorts the files before returning to the caller
  638. my @orderedFiles = ();
  639. @orderedFiles = sort(@files);
  640. # Return the file list
  641. return (@orderedFiles);
  642. }
  643. sub findMediaFiles($$) {
  644. my ($path, $depth) = @_;
  645. my @files = ();
  646. # Recursion limit
  647. if ($depth > $FIND_MAX_DEPTH) {
  648. return ();
  649. }
  650. my @tmpFiles = readDir($path, 1);
  651. foreach my $file (@tmpFiles) {
  652. # Skip sample files
  653. if ($file =~ /sample/i) {
  654. next;
  655. }
  656. # Recurse on directories
  657. if (-d $file) {
  658. push(@files, findMediaFiles($file, $depth + 1));
  659. next;
  660. }
  661. # Save matching files
  662. if ($file =~ /\.(?:avi|mkv|m4v|mov|mp4|ts|wmv)$/i) {
  663. push(@files, $file);
  664. next;
  665. }
  666. }
  667. return @files;
  668. }
  669. sub runAndCheck(@) {
  670. my (@args) = (@_);
  671. # Run
  672. system { $args[0] } @args;
  673. my $res = $?;
  674. # Die on any error
  675. if ($res == -1) {
  676. die('Unable to execute program: ' . join(' ', @args) . ': ' . $! . "\n");
  677. } elsif ($res & 127) {
  678. die('Child exited on signal: ' . join(' ', @args) . ': ' . ($res & 127) . "\n");
  679. } elsif ($res != 0) {
  680. die('Child exited with non-zero value: ' . join(' ', @args) . ': ' . ($res >> 8) . "\n");
  681. }
  682. # If we get here, all is well
  683. return 1;
  684. }