transmission.pl 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. # If we find more than one matching series
  328. if (length($series) > 0) {
  329. # If the old match is a subset of the new match, prefer the new match
  330. # If the new match is a subet of the old match, prefer the old match
  331. # Bail if the matches do not overlap
  332. if ($show =~ m/^${series}\b/) {
  333. if ($DEBUG) {
  334. print STDERR 'Using longer match (' . $showsCan{$show} . ') in place of shorter match (' . $showsCan{$series} . ")\n";
  335. }
  336. $series = $show;
  337. } elsif ($series =~ m/^${show}\b/) {
  338. if ($DEBUG) {
  339. print STDERR 'Using longer match (' . $showsCan{$series} . ') in place of shorter match (' . $showsCan{$show} . ")\n";
  340. }
  341. $series = $series;
  342. } else {
  343. print STDERR 'Matched both ' . $showsCan{$series} . ' and ' . $showsCan{$show} . "\n";
  344. return;
  345. }
  346. } else {
  347. # If we're still around this is the first series title match
  348. $series = $show;
  349. }
  350. }
  351. }
  352. if (length($series) < 1) {
  353. if ($DEBUG) {
  354. print STDERR 'No series match for: ' . $sMatch . "\n";
  355. }
  356. return;
  357. }
  358. # Lookup the canonical name from the matched name
  359. $series = $showsCan{$series};
  360. # Make sure we have the right season folder
  361. my $seriesDir = $tvDir . '/' . $series;
  362. my $seasonDir = $seriesDir . '/' . 'Season ' . $season;
  363. if (!-d $seasonDir) {
  364. print STDERR 'No season folder for: ' . $series . ' S' . $season . "\n";
  365. return;
  366. }
  367. # Bail if we already have this episode
  368. my @episodes = readDir($seasonDir, 0);
  369. foreach my $ep (@episodes) {
  370. my ($epNum) = $ep =~ /^\s*([\d\-]+)\s*\-\s*/;
  371. if (!defined($epNum)) {
  372. next;
  373. }
  374. $epNum =~ s/^0+//;
  375. if ($epNum eq $episode) {
  376. print STDERR 'Existing episode for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  377. return;
  378. }
  379. }
  380. # Construct the final path
  381. if (!defined($ext) || length($ext) < 1) {
  382. $ext = 'avi';
  383. }
  384. if ($episode =~ /^\d+$/) {
  385. $episode = sprintf('%02d', $episode);
  386. }
  387. my $dest = sprintf('%s/%s - NoName.%s', $seasonDir, $episode, $ext);
  388. if ($DEBUG) {
  389. print STDERR 'Destination: ' . $dest . "\n";
  390. }
  391. return $dest;
  392. }
  393. sub delTor($) {
  394. my ($tor) = @_;
  395. if ($DEBUG) {
  396. print STDERR 'Deleting torrent: ' . $tor->{'name'} . "\n";
  397. }
  398. # Sleep to avoid bugs in Transmission (i.e. multiple deletes fail)
  399. sleep($delSleep);
  400. # Construct the content
  401. my $id = $tor->{'hashString'};
  402. my $content = $delContent;
  403. $content =~ s/\#_ID_\#/${id}/;
  404. # Send the command
  405. &session($fetch);
  406. $fetch->post_content($content);
  407. &fetch($fetch);
  408. }
  409. sub guessExt($) {
  410. my ($file) = @_;
  411. # Believe most non-avi file extensions without checking
  412. # It's mostly "avi" that lies, and the checks are expensive
  413. my $ext = '';
  414. {
  415. my $orig_ext = basename($file);
  416. $orig_ext =~ s/^.*\.(\w{2,3})$/$1/;
  417. $orig_ext = lc($orig_ext);
  418. if ($orig_ext eq 'mkv' || $orig_ext eq 'ts') {
  419. $ext = $orig_ext;
  420. }
  421. }
  422. # Ask movInfo.pl about the demuxer
  423. if (!$ext) {
  424. my $demux = '';
  425. open(INFO, '-|', $ENV{'HOME'} . '/bin/video/movInfo.pl', $file, 'DEMUXER');
  426. while (<INFO>) {
  427. $demux .= $_;
  428. }
  429. close(INFO);
  430. $demux =~ s/^\s+//;
  431. $demux =~ s/\s+$//;
  432. # Grab a MIME type from file(1)
  433. my $mime = '';
  434. open(FILE, '-|', 'file', '-b', $file);
  435. while (<FILE>) {
  436. $mime .= $_;
  437. }
  438. close(FILE);
  439. $mime =~ s/^\s+//;
  440. $mime =~ s/\s+$//;
  441. $mime =~ s/\;.*$//;
  442. $mime =~ s/^video\///i;
  443. # Try to pick an extension we understand
  444. $ext = 'avi';
  445. if ($demux =~ /mkv/i || $mime =~ /Matroska/i) {
  446. $ext = 'mkv';
  447. } elsif ($demux =~ /asf/i || $mime =~ /\bASF\b/i) {
  448. $ext = 'wmv';
  449. } elsif ($mime =~ /\bZIP/i) {
  450. $ext = 'zip';
  451. } elsif ($mime =~ /\bAVI\b/i) {
  452. $ext = 'avi';
  453. } elsif ($demux =~ /mpegts/i) {
  454. $ext = 'ts';
  455. }
  456. }
  457. return $ext;
  458. }
  459. sub processFile($$) {
  460. my ($file, $path) = @_;
  461. if ($DEBUG) {
  462. print STDERR 'Attempting to process file: ' . basename($file) . "\n";
  463. }
  464. # Guess a file extension
  465. my $ext = &guessExt($file);
  466. # Delete WMV files -- mostly viruses
  467. if ($ext =~ /wmv/i) {
  468. print STDERR 'Declining to save WMV file: ' . basename($file) . "\n";
  469. return -1;
  470. }
  471. # Delete ZIP files -- mostly fake
  472. if ($ext =~ /zip/i) {
  473. print STDERR 'Declining to save ZIP file: ' . basename($file) . "\n";
  474. return -1;
  475. }
  476. # Allow multiple guesses at the series/season/episode
  477. my $dest = '';
  478. my $filename = basename($file);
  479. LOOP: {
  480. # Determine the series, season, and episode number
  481. my ($series, $season, $episode) = &getSSE($filename);
  482. if ( defined($series)
  483. && length($series) > 0
  484. && defined($season)
  485. && $season > 0
  486. && defined($episode)
  487. && length($episode) > 0
  488. && $episode ne '0')
  489. {
  490. # Find the proper destination for this torrent, if any
  491. $dest = &getDest($series, $season, $episode, $ext);
  492. }
  493. # Sanity/loop check
  494. if (!defined($dest) || length($dest) < 1) {
  495. # If there is no match but the torrent is a folder
  496. # retry the guess using the torrent path
  497. if ($file ne $path) {
  498. my $newName = basename($path);
  499. if ($newName ne $filename) {
  500. $filename = basename($path);
  501. redo LOOP;
  502. }
  503. }
  504. # Otherwise we just fail
  505. print STDERR 'No destination for: ' . basename($file) . "\n";
  506. return;
  507. }
  508. }
  509. # Copy with system tools
  510. my $tmp = mktemp($dest . '.XXXXXXXX');
  511. runAndCheck(('cp', $file, $tmp));
  512. rename($tmp, $dest);
  513. # Return success
  514. return 1;
  515. }
  516. sub unrar($$) {
  517. my ($file, $path) = @_;
  518. if ($DEBUG) {
  519. print STDERR 'UnRARing: ' . basename($file) . "\n";
  520. }
  521. # Keep a list of old files, so we can find/delete the output
  522. my @beforeFiles = readDir($path, 1);
  523. # Run the unrar utility
  524. my $pid = fork();
  525. if (!defined($pid)) {
  526. print STDERR "Unable to fork for RAR\n";
  527. return;
  528. } elsif ($pid == 0) {
  529. # Child
  530. close(STDOUT);
  531. close(STDERR);
  532. chdir($path);
  533. my @args = ('unrar', 'e', '-p-', '-y', $file);
  534. exec { $args[0] } @args;
  535. }
  536. # Wait for the child
  537. waitpid($pid, 0);
  538. # Compare the old file list to the new one
  539. my @newFiles = ();
  540. my @afterFiles = readDir($path, 1);
  541. foreach my $file (@afterFiles) {
  542. my $found = 0;
  543. foreach my $file2 (@beforeFiles) {
  544. if ($file eq $file2) {
  545. $found = 1;
  546. last;
  547. }
  548. }
  549. if (!$found) {
  550. push(@newFiles, $file);
  551. }
  552. }
  553. # Return the list of added files
  554. return @newFiles;
  555. }
  556. sub seriesCleanupLocal($) {
  557. my ($name) = @_;
  558. $name =~ s/\.//g;
  559. return seriesCleanupCore($name);
  560. }
  561. sub seriesCleanupCore($) {
  562. my ($name) = @_;
  563. $name =~ s/\b(?:and|\&)\b/ /ig;
  564. $name =~ s/^\s*The\b//ig;
  565. $name =~ s/\[[^\]]*\]//g;
  566. $name =~ s/\{[^\}]*\}//g;
  567. $name =~ s/[\(\)]//g;
  568. $name =~ s/[\'\"]//g;
  569. $name =~ s/[^\w\s]+/ /g;
  570. $name =~ s/_+/ /g;
  571. $name =~ s/\s+/ /g;
  572. $name =~ s/^\s*//;
  573. $name =~ s/\s*$//;
  574. return $name;
  575. }
  576. sub seriesCleanup($) {
  577. my ($name) = @_;
  578. $name =~ s/\s*\(?US\)?\s*$//i;
  579. $name =~ s/\s*\(?20[01][0-9]\)?\s*$//;
  580. return seriesCleanupCore($name);
  581. }
  582. sub readDir($$) {
  583. my ($indir, $long) = @_;
  584. # Clean up the input directory
  585. $indir =~ s/\/+$//;
  586. my @files = ();
  587. if (!opendir(DIR, $indir)) {
  588. warn('readDir: Unable to read directory: ' . $indir . ': ' . $! . "\n");
  589. return;
  590. }
  591. foreach my $file (readdir(DIR)) {
  592. my $keep = 0;
  593. # Skip junk
  594. if ( $file eq '.'
  595. || $file eq '..'
  596. || $file =~ /\._/)
  597. {
  598. next;
  599. }
  600. # Save the full path
  601. if ($long) {
  602. push(@files, $indir . '/' . $file);
  603. } else {
  604. push(@files, $file);
  605. }
  606. }
  607. closedir(DIR);
  608. # Sorts the files before returning to the caller
  609. my @orderedFiles = ();
  610. @orderedFiles = sort(@files);
  611. # Return the file list
  612. return (@orderedFiles);
  613. }
  614. sub findMediaFiles($$) {
  615. my ($path, $depth) = @_;
  616. my @files = ();
  617. # Recursion limit
  618. if ($depth > $FIND_MAX_DEPTH) {
  619. return ();
  620. }
  621. my @tmpFiles = readDir($path, 1);
  622. foreach my $file (@tmpFiles) {
  623. # Skip sample files
  624. if ($file =~ /sample/i) {
  625. next;
  626. }
  627. # Recurse on directories
  628. if (-d $file) {
  629. push(@files, findMediaFiles($file, $depth + 1));
  630. next;
  631. }
  632. # Save matching files
  633. if ($file =~ /\.(?:avi|mkv|m4v|mov|mp4|ts|wmv)$/i) {
  634. push(@files, $file);
  635. next;
  636. }
  637. }
  638. return @files;
  639. }
  640. sub runAndCheck(@) {
  641. my (@args) = (@_);
  642. # Run
  643. system { $args[0] } @args;
  644. my $res = $?;
  645. # Die on any error
  646. if ($res == -1) {
  647. die('Unable to execute program: ' . join(' ', @args) . ': ' . $! . "\n");
  648. } elsif ($res & 127) {
  649. die('Child exited on signal: ' . join(' ', @args) . ': ' . ($res & 127) . "\n");
  650. } elsif ($res != 0) {
  651. die('Child exited with non-zero value: ' . join(' ', @args) . ': ' . ($res >> 8) . "\n");
  652. }
  653. # If we get here, all is well
  654. return 1;
  655. }