transmission.pl 18 KB

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