transmission.pl 15 KB

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