transmission.pl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. # Includes
  5. use JSON;
  6. use Date::Parse;
  7. use File::Copy;
  8. use File::Touch;
  9. use File::Temp 'mktemp';
  10. use File::Path 'remove_tree';
  11. use File::Basename;
  12. use Image::ExifTool qw/ :Public/;
  13. use FindBin qw($Bin);
  14. use lib $Bin;
  15. use Fetch;
  16. # Prototypes
  17. sub session($);
  18. sub fetch($);
  19. sub getSSE($);
  20. sub getDest($$$$);
  21. sub storeFiles($$$);
  22. sub readNZB($$);
  23. sub storeNZB($);
  24. sub storeTor($);
  25. sub delNZB($);
  26. sub delTor($);
  27. sub guessExt($);
  28. sub processFile($$);
  29. sub unrar($$);
  30. sub seriesCleanupLocal($);
  31. sub seriesCleanupCore($);
  32. sub seriesCleanup($);
  33. sub readDir($$);
  34. sub findMediaFiles($$);
  35. sub available($);
  36. # Parameters
  37. my $maxAge = 2.5 * 86400;
  38. my $tvDir = `~/bin/video/mediaPath` . '/TV';
  39. my $monitoredExec = $ENV{'HOME'} . '/bin/video/torrentMonitored.pl';
  40. my $content =
  41. '{"method":"torrent-get","arguments":{"fields":["hashString","id","addedDate","comment","creator",'
  42. . '"dateCreated","isPrivate","name","totalSize","pieceCount","pieceSize","downloadedEver","error","errorString",'
  43. . '"eta","haveUnchecked","haveValid","leftUntilDone","metadataPercentComplete","peersConnected","peersGettingFromUs",'
  44. . '"peersSendingToUs","rateDownload","rateUpload","recheckProgress","sizeWhenDone","status","trackerStats",'
  45. . '"uploadedEver","uploadRatio","seedRatioLimit","seedRatioMode","downloadDir","files","fileStats"]}}';
  46. my $delContent = '{"method":"torrent-remove","arguments":{"ids":["#_ID_#"], "delete-local-data":"true"}';
  47. my $history = '{"method":"history","params":[]}';
  48. my $delHistory = '{"method":"editqueue","params":["historyFinalDelete","",[#_ID_#]]}';
  49. my $delSleep = 2;
  50. my $RAR_MIN_FILES = 4;
  51. my $FIND_MAX_DEPTH = 5;
  52. my $CONF_FILE = $ENV{'HOME'} . '/.download.config';
  53. # Environment
  54. my $DEBUG = 0;
  55. if ($ENV{'DEBUG'}) {
  56. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  57. $DEBUG = $1;
  58. } else {
  59. $DEBUG = 1;
  60. }
  61. }
  62. # Command-line parameters
  63. my ($hash) = @ARGV;
  64. # Config file
  65. my %CONFIG = ();
  66. if ($CONF_FILE && -r $CONF_FILE) {
  67. my $fh;
  68. open($fh, '<', $CONF_FILE)
  69. or die('Unable to open config file: ' . $CONF_FILE . ': ' . $! . "\n");
  70. while (<$fh>) {
  71. # Skip blank lines and comments
  72. if (/^\s*#/ || /^\s*$/) {
  73. next;
  74. }
  75. # Assume everything else is bash variables
  76. if (my ($key, undef(), $val) = $_ =~ /^\s*(\S[^\=]+)\=([\'\"])(.*)\g{-2}\s*$/) {
  77. $CONFIG{$key} = $val;
  78. if ($DEBUG > 1) {
  79. print STDERR 'Adding config: ' . $key . ' => ' . $val . "\n";
  80. }
  81. } else {
  82. warn('Ignoring config line: ' . $_ . "\n");
  83. }
  84. }
  85. close($fh);
  86. }
  87. # Init
  88. my $fetch = undef();
  89. # Tranmission
  90. if (available($CONFIG{'TRANS_URL'})) {
  91. # Fetch the list of paused (i.e. completed) torrents
  92. $fetch->url($CONFIG{'TRANS_URL'});
  93. $fetch->post_content($content);
  94. &fetch($fetch);
  95. my $torrents = decode_json(scalar($fetch->content()));
  96. $torrents = $torrents->{'arguments'}->{'torrents'};
  97. # Process
  98. if ($DEBUG) {
  99. print STDERR "Processing torrents...\n";
  100. }
  101. foreach my $tor (@{$torrents}) {
  102. # Skip torrents that aren't yet done
  103. if ($tor->{'leftUntilDone'} > 0 || $tor->{'metadataPercentComplete'} < 1) {
  104. next;
  105. }
  106. # If a hash is provided, process only that file
  107. if (defined($hash) && $tor->{'hashString'} ne $hash) {
  108. if ($DEBUG) {
  109. printf STDERR 'Skipping torrent with non-matching hash: ' . $tor->{'name'} . ' (' . $tor->{'hashString'} . ")\n";
  110. }
  111. next;
  112. }
  113. # Process this torrent
  114. if ($DEBUG) {
  115. print STDERR 'Processing completed torrent: ' . $tor->{'name'} . "\n";
  116. }
  117. if (storeTor($tor)) {
  118. delTor($tor);
  119. } else {
  120. print STDERR 'Unable to store torrent: ' . $tor->{'name'} . "\n";
  121. }
  122. next;
  123. }
  124. # NZB
  125. if (available($CONFIG{'NZB_URL'})) {
  126. # Fetch the list of historical (i.e. completed) NZBs
  127. $fetch->url($CONFIG{'NZB_URL'});
  128. $fetch->post_content($history);
  129. $fetch->fetch();
  130. my $resp = decode_json(scalar($fetch->content()));
  131. if (!defined($resp) || ref($resp) ne 'HASH' || !exists($resp->{'result'}) || ref($resp->{'result'}) ne 'ARRAY') {
  132. print STDERR 'Invalid NZB response: ' . $fetch->content() . "\n";
  133. }
  134. # Process
  135. if ($DEBUG) {
  136. print STDERR "Processing NZBs...\n";
  137. }
  138. foreach my $data (@{ $resp->{'result'} }) {
  139. my $nzb = undef();
  140. if (!readNZB(\$nzb, $data)) {
  141. warn("Unable to parse NZB\n");
  142. next;
  143. }
  144. # If a hash is provided, process only that file
  145. #if (defined($hash) && $nzb->{'has'} ne $hash) {
  146. # if ($DEBUG) {
  147. # printf STDERR 'Skipping NZB with non-matching hash: ' . $nzb->{'name'} . ' (' . $nzb->{'hash'} . ")\n";
  148. # }
  149. # next;
  150. #}
  151. # Delete failed NZBs
  152. if ($nzb->{'status'} =~ /FAILURE\/(?:HEALTH|PAR|UNPACK|FETCH)/) {
  153. delNZB($nzb);
  154. next;
  155. }
  156. # Process sucessful NZBs
  157. if ($nzb->{'status'} eq 'SUCCESS/UNPACK') {
  158. if (storeNZB($nzb)) {
  159. delNZB($nzb);
  160. } else {
  161. print STDERR 'Unable to store NZB: ' . $nzb->{'name'} . "\n";
  162. }
  163. next;
  164. }
  165. }
  166. }
  167. }
  168. # Cleanup
  169. exit(0);
  170. # Grab the session ID
  171. sub session($) {
  172. my ($fetch) = @_;
  173. my %headers = ();
  174. ($headers{'X-Transmission-Session-Id'}) = $fetch->content() =~ /X\-Transmission\-Session\-Id\:\s+(\w+)/;
  175. $fetch->headers(\%headers);
  176. }
  177. sub fetch($) {
  178. my ($fetch) = @_;
  179. $fetch->fetch('nocheck' => 1);
  180. if ($fetch->status_code() != 200) {
  181. &session($fetch);
  182. $fetch->fetch();
  183. if ($fetch->status_code() != 200) {
  184. die('Unable to fetch: ' . $fetch->status_code() . "\n");
  185. }
  186. }
  187. }
  188. sub getSSE($) {
  189. my ($name) = @_;
  190. if ($DEBUG) {
  191. print STDERR 'Finding series/season/episode for: ' . $name . "\n";
  192. }
  193. my $season = 0;
  194. my $episode = 0;
  195. my $seasonBlock = '';
  196. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  197. $seasonBlock = $1;
  198. my ($month, $day);
  199. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  200. $season = int($season);
  201. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  202. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  203. $seasonBlock = $1;
  204. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  205. $season = int($season);
  206. $episode = sprintf('%02d', int($episode));
  207. } elsif ($name =~ /\b(\d{1,2}x\d{2,3})\b/i) {
  208. $seasonBlock = $1;
  209. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  210. $season = int($season);
  211. $episode = sprintf('%02d', int($episode));
  212. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  213. $seasonBlock = $1;
  214. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  215. $season = int($season);
  216. $episode = sprintf('%02d', int($episode));
  217. }
  218. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  219. if ($DEBUG) {
  220. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  221. }
  222. return;
  223. }
  224. # Assume the series titles comes before the season/episode block
  225. my $series = '';
  226. my $sIndex = index($name, $seasonBlock);
  227. if ($sIndex > 0) {
  228. $series = substr($name, 0, $sIndex - 1);
  229. $series = seriesCleanupCore($series);
  230. }
  231. if ($DEBUG) {
  232. print STDERR 'Series: ' . $series . ' Season: ' . $season . ' Episode: ' . $episode . "\n";
  233. }
  234. return ($series, $season, $episode);
  235. }
  236. sub getDest($$$$) {
  237. my ($series, $season, $episode, $ext) = @_;
  238. if ($DEBUG) {
  239. print STDERR 'Finding destination for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  240. }
  241. # Input cleanup
  242. $episode =~ s/^0+//;
  243. # Find all our existing TV series
  244. my @shows = ();
  245. my %showsCan = ();
  246. open(SHOWS, '-|', $monitoredExec, 'STORE')
  247. or die("Unable to fork: ${!}\n");
  248. while (<SHOWS>) {
  249. chomp;
  250. my $orig = $_;
  251. my $clean = seriesCleanupLocal($_);
  252. push(@shows, $clean);
  253. $showsCan{$clean} = $orig;
  254. }
  255. close SHOWS or die("Unable to read monitored series list: ${!} ${?}\n");
  256. # See if we can find a unique series name match
  257. my $sClean = seriesCleanup($series);
  258. my $sCleanCore = seriesCleanupCore($series);
  259. my $sMatch = '\b' . $sClean . '\b';
  260. $series = '';
  261. foreach my $show (@shows) {
  262. # Match the folder name or the search_name
  263. my $coarse_match = 0;
  264. if ($show =~ /${sMatch}/i) {
  265. $coarse_match = 1;
  266. } else {
  267. my $search_name = '';
  268. my $file = $tvDir . '/' . $showsCan{$show} . '/search_name';
  269. if (-e $file) {
  270. open(FH, $file)
  271. or die('Unable to read search_name file: ' . $file . "\n");
  272. $search_name = <FH>;
  273. close(FH);
  274. }
  275. if ($search_name) {
  276. $search_name = seriesCleanup($search_name);
  277. if ($search_name =~ /${sMatch}/i) {
  278. $coarse_match = 1;
  279. }
  280. }
  281. }
  282. # If we got a course match, continue checking
  283. if ($coarse_match) {
  284. # Enforce any secondary matching rules (for ambiguous titles)
  285. my $detail_match = 1;
  286. {
  287. my @lines;
  288. my $file = $tvDir . '/' . $showsCan{$show} . '/must_match';
  289. if (-e $file) {
  290. local ($/, *FH);
  291. open(FH, $file)
  292. or die('Unable to read must_match file: ' . $file . "\n");
  293. my @tmp = <FH>;
  294. close(FH);
  295. push(@lines, @tmp);
  296. }
  297. foreach my $line (@lines) {
  298. chomp($line);
  299. if (!eval('$sCleanCore =~ m' . $line)) {
  300. if ($DEBUG) {
  301. print STDERR 'Skipping ' . $show . ' due to must_match failure for: ' . $line . "\n";
  302. }
  303. $detail_match = 0;
  304. last;
  305. }
  306. }
  307. }
  308. if (!$detail_match) {
  309. next;
  310. }
  311. # If we find more than one matching series
  312. if (length($series) > 0) {
  313. # If the old match is a subset of the new match, prefer the new match
  314. # If the new match is a subet of the old match, prefer the old match
  315. # Bail if the matches do not overlap
  316. if ($show =~ m/^${series}\b/) {
  317. if ($DEBUG) {
  318. print STDERR 'Using longer match ('
  319. . $showsCan{$show}
  320. . ') in place of shorter match ('
  321. . $showsCan{$series} . ")\n";
  322. }
  323. $series = $show;
  324. } elsif ($series =~ m/^${show}\b/) {
  325. if ($DEBUG) {
  326. print STDERR 'Using longer match ('
  327. . $showsCan{$series}
  328. . ') in place of shorter match ('
  329. . $showsCan{$show} . ")\n";
  330. }
  331. $series = $series;
  332. } else {
  333. print STDERR 'Matched both ' . $showsCan{$series} . ' and ' . $showsCan{$show} . "\n";
  334. return;
  335. }
  336. } else {
  337. # If we're still around this is the first series title match
  338. $series = $show;
  339. }
  340. }
  341. }
  342. if (length($series) < 1) {
  343. if ($DEBUG) {
  344. print STDERR 'No series match for: ' . $sMatch . "\n";
  345. }
  346. return;
  347. }
  348. # Lookup the canonical name from the matched name
  349. $series = $showsCan{$series};
  350. # Make sure we have the right season folder
  351. my $seriesDir = $tvDir . '/' . $series;
  352. my $seasonDir = $seriesDir . '/' . 'Season ' . $season;
  353. if (!-d $seasonDir) {
  354. print STDERR 'No season folder for: ' . $series . ' S' . $season . "\n";
  355. return;
  356. }
  357. # Bail if we already have this episode
  358. my @episodes = readDir($seasonDir, 0);
  359. foreach my $ep (@episodes) {
  360. my ($epNum) = $ep =~ /^\s*([\d\-]+)\s*\-\s*/;
  361. if (!defined($epNum)) {
  362. next;
  363. }
  364. $epNum =~ s/^0+//;
  365. if ($epNum eq $episode) {
  366. print STDERR 'Existing episode for: ' . $series . ' S' . $season . 'E' . $episode . "\n";
  367. return;
  368. }
  369. }
  370. # Construct the final path
  371. if (!defined($ext) || length($ext) < 1) {
  372. $ext = 'avi';
  373. }
  374. if ($episode =~ /^\d+$/) {
  375. $episode = sprintf('%02d', $episode);
  376. }
  377. my $dest = sprintf('%s/%s - NoName.%s', $seasonDir, $episode, $ext);
  378. if ($DEBUG) {
  379. print STDERR 'Destination: ' . $dest . "\n";
  380. }
  381. return $dest;
  382. }
  383. sub storeFiles($$$) {
  384. my ($path, $files, $name) = @_;
  385. my $failure = 0;
  386. foreach my $file (@{$files}) {
  387. my $result = -1;
  388. if (defined($file) && length($file) > 0 && -r $file) {
  389. $result = &processFile($file, $path);
  390. }
  391. if (defined($result) && $result == 1) {
  392. if ($DEBUG) {
  393. print STDERR 'File stored successfully: ' . $name . "\n";
  394. }
  395. } elsif (defined($result) && $result == -1) {
  396. if ($DEBUG) {
  397. print STDERR 'Refusing to save bad download: ' . $name . "\n";
  398. }
  399. last;
  400. } else {
  401. print STDERR 'Error storing file "' . basename($file) . '" from: ' . $name . "\n";
  402. $failure = 1;
  403. last;
  404. }
  405. }
  406. return $failure ? 0 : 1;
  407. }
  408. sub readNZB($$) {
  409. my ($nzb, $data) = @_;
  410. my %tmp = ('id' => undef(), 'name' => undef(), 'status' => undef(), 'path' => undef());
  411. # Sanity
  412. if (ref($data) ne 'HASH') {
  413. print STDERR 'Invalid NZB item: ' . $data . "\n";
  414. return 0;
  415. }
  416. # ID
  417. if (exists($data->{'ID'})) {
  418. $tmp{'id'} = int($data->{'ID'});
  419. }
  420. # Name
  421. if (exists($data->{'Name'})) {
  422. $tmp{'name'} = $data->{'Name'};
  423. }
  424. if (!$tmp{'name'} && exists($data->{'NZBName'})) {
  425. $tmp{'name'} = $data->{'NZBName'};
  426. }
  427. if (!$tmp{'name'} && exists($data->{'NZBNicename'})) {
  428. $tmp{'name'} = $data->{'NZBNicename'};
  429. }
  430. if (!$tmp{'name'}) {
  431. print STDERR 'Unable to retrieve name for: ' . $tmp{'id'} . "\n";
  432. return 0;
  433. }
  434. # Status
  435. if (exists($data->{'Status'})) {
  436. $tmp{'status'} = $data->{'Status'};
  437. }
  438. if (!$tmp{'status'}) {
  439. print STDERR 'Unable to retrieve status for: ' . $tmp{'id'} . "\n";
  440. return 0;
  441. }
  442. # Path
  443. if (exists($data->{'DestDir'})) {
  444. $tmp{'path'} = $data->{'DestDir'};
  445. }
  446. if (!$tmp{'path'} && $DEBUG) {
  447. print STDERR 'Unable to retrieve path for: ' . $tmp{'id'} . "\n";
  448. }
  449. # Debug
  450. if ($DEBUG > 1) {
  451. print STDERR "\n\n";
  452. foreach my $key (keys(%tmp)) {
  453. print STDERR $key . ' => ' . $tmp{$key} . "\n";
  454. }
  455. }
  456. # Store the NZB hash and return success
  457. ${$nzb} = \%tmp;
  458. return 1;
  459. }
  460. sub storeTor($) {
  461. my ($tor) = @_;
  462. if ($DEBUG) {
  463. print STDERR 'Storing torrent: ' . $tor->{'name'} . "\n";
  464. }
  465. # Handle individual files and directories
  466. my @files = ();
  467. my @newFiles = ();
  468. my $path = $tor->{'downloadDir'} . '/' . $tor->{'name'};
  469. if (!-d $path) {
  470. push(@files, $path);
  471. } else {
  472. # State variables
  473. my $IS_RAR = '';
  474. my $IS_FAKE = 0;
  475. # Look for RAR files
  476. foreach my $file (@{ $tor->{'files'} }) {
  477. if ($file->{'name'} =~ /\.rar$/i) {
  478. $IS_RAR = $tor->{'downloadDir'} . '/' . $file->{'name'};
  479. last;
  480. }
  481. }
  482. # Check for password files
  483. foreach my $file (@{ $tor->{'files'} }) {
  484. if ($file->{'name'} =~ /passw(?:or)?d/i) {
  485. print STDERR 'Password file detected in: ' . $tor->{'name'} . "\n";
  486. $IS_FAKE = 1;
  487. last;
  488. }
  489. }
  490. # Check for single-file RARs
  491. if ($IS_RAR && scalar(@{ $tor->{'files'} }) < $RAR_MIN_FILES) {
  492. print STDERR 'Single-file RAR detected in: ' . $tor->{'name'} . "\n";
  493. $IS_FAKE = 1;
  494. }
  495. # Delete fake torrents and bail
  496. if ($IS_FAKE) {
  497. if ($DEBUG) {
  498. print STDERR 'Deleting fake torrent: ' . $tor->{'name'} . "\n";
  499. }
  500. delTor($tor);
  501. next;
  502. }
  503. # Unrar if necessary
  504. if (defined($IS_RAR) && length($IS_RAR) > 0) {
  505. @newFiles = &unrar($IS_RAR, $path);
  506. }
  507. # Find all media files, recursively
  508. @files = findMediaFiles($path, 0);
  509. }
  510. # Process any files we found
  511. if (scalar(@files) < 1) {
  512. print STDERR 'No media files found in torrent: ' . $tor->{'name'} . "\n";
  513. return 0;
  514. }
  515. my $retval = storeFiles($path, \@files, $tor->{'name'});
  516. # Delete any files we added
  517. foreach my $file (@newFiles) {
  518. if ($DEBUG) {
  519. print STDERR 'Deleting new file: ' . basename($file) . "\n";
  520. }
  521. unlink($file);
  522. }
  523. # Return whatever storeFiles() said
  524. return $retval;
  525. }
  526. sub storeNZB($) {
  527. my ($nzb) = @_;
  528. if ($DEBUG) {
  529. print STDERR 'Storing NZB: ' . $nzb->{'name'} . "\n";
  530. }
  531. # Find all media files, recursively
  532. my @files = findMediaFiles($nzb->{'path'}, 0);
  533. # Process any files we found
  534. if (scalar(@files) < 1) {
  535. print STDERR 'No media files found in NZB: ' . $nzb->{'name'} . "\n";
  536. next;
  537. }
  538. return storeFiles($nzb->{'path'}, \@files, $nzb->{'name'});
  539. }
  540. sub delNZB($) {
  541. my ($nzb) = @_;
  542. if ($DEBUG) {
  543. print STDERR 'Deleting NZB: ' . $nzb->{'name'} . "\n";
  544. }
  545. # Remove the files, if any
  546. if (-e $nzb->{'path'} && -d $nzb->{'path'}) {
  547. if ($DEBUG) {
  548. print STDERR 'Removing NZB folder: ' . $nzb->{'path'} . "\n";
  549. }
  550. remove_tree($nzb->{'path'});
  551. # Check for deletion
  552. if (-e $nzb->{'path'}) {
  553. print STDERR 'Unable to remove NZB folder: ' . $nzb->{'path'} . "\n";
  554. return 0;
  555. }
  556. }
  557. # Send the command
  558. my $id = $nzb->{'id'};
  559. my $content = $delHistory;
  560. $content =~ s/\#_ID_\#/${id}/;
  561. $fetch->post_content($content);
  562. $fetch->fetch();
  563. # Check the result
  564. if ($fetch->content() =~ /\"result\" \: true/i) {
  565. return 1;
  566. }
  567. return 0;
  568. }
  569. sub delTor($) {
  570. my ($tor) = @_;
  571. if ($DEBUG) {
  572. print STDERR 'Deleting torrent: ' . $tor->{'name'} . "\n";
  573. }
  574. # Sleep to avoid bugs in Transmission (i.e. multiple deletes fail)
  575. sleep($delSleep);
  576. # Construct the content
  577. my $id = $tor->{'hashString'};
  578. my $content = $delContent;
  579. $content =~ s/\#_ID_\#/${id}/;
  580. # Send the command
  581. &session($fetch);
  582. $fetch->post_content($content);
  583. &fetch($fetch);
  584. }
  585. sub guessExt($) {
  586. my ($file) = @_;
  587. my $ext = '';
  588. # Believe most non-avi file extensions without checking
  589. # It's mostly "avi" that lies, and the checks are expensive
  590. {
  591. my $orig_ext = basename($file);
  592. $orig_ext =~ s/^.*\.(\w{2,3})$/$1/;
  593. $orig_ext = lc($orig_ext);
  594. if ($orig_ext eq 'mkv' || $orig_ext eq 'ts') {
  595. $ext = $orig_ext;
  596. }
  597. }
  598. # Deal with the weird case of text files labeled as .txt.mp4
  599. if ($file =~ /\.txt\.mp4$/i) {
  600. $ext = 'txt';
  601. }
  602. # Guess the file type if we don't have one yet
  603. if (!$ext) {
  604. my $mime = '';
  605. my $demux = '';
  606. # Try ExifTool for MIME and demuxer types
  607. if (!$mime || !$demux) {
  608. my $exif = ImageInfo($file);
  609. if (defined($exif) && ref($exif) eq 'HASH') {
  610. if ($exif->{'MIMEType'}) {
  611. $mime = $exif->{'MIMEType'};
  612. }
  613. if ($exif->{'FileType'}) {
  614. $demux = $exif->{'FileType'};
  615. }
  616. }
  617. }
  618. # Try file(1) for MIME types
  619. if (!$mime) {
  620. open(FILE, '-|', 'file', '-b', $file);
  621. while (<FILE>) {
  622. $mime .= $_;
  623. }
  624. close(FILE);
  625. }
  626. # Cleanup the demuxer and MIME types
  627. $demux =~ s/^\s+//;
  628. $demux =~ s/\s+$//;
  629. $mime =~ s/^\s+//;
  630. $mime =~ s/\s+$//;
  631. $mime =~ s/\;.*$//;
  632. $mime =~ s/^video\///i;
  633. # Try to pick an extension we understand
  634. if ($demux =~ /MKV/i || $mime =~ /Matroska/i) {
  635. $ext = 'mkv';
  636. } elsif ($demux =~ /ASF/i || $mime =~ /\bASF\b/i) {
  637. $ext = 'wmv';
  638. } elsif ($demux =~ /MP4/i || $mime =~ /\bMP4\b/i) {
  639. $ext = 'mp4';
  640. } elsif ($mime =~ /\bZIP/i) {
  641. $ext = 'zip';
  642. } elsif ($demux =~ /MPEGTS/i) {
  643. $ext = 'ts';
  644. } else {
  645. $ext = 'avi';
  646. }
  647. }
  648. return $ext;
  649. }
  650. sub processFile($$) {
  651. my ($file, $path) = @_;
  652. if ($DEBUG) {
  653. print STDERR 'Attempting to process file: ' . basename($file) . "\n";
  654. }
  655. # Skip known packaging files files with success code
  656. if ($file =~ /\/RARBG\.com\.(?:mp4|avi|mkv|txt)$/i || $file =~ /\.txt\.(?:mp4|avi|mkv)$/) {
  657. if ($DEBUG) {
  658. print STDERR 'Declining to save packaging file: ' . $file . "\n";
  659. }
  660. return 1;
  661. }
  662. # Guess a file extension and basename
  663. my $ext = &guessExt($file);
  664. my $filename = basename($file);
  665. # Delete WMV files -- mostly viruses/fake
  666. if ($ext =~ /wmv/i) {
  667. if ($DEBUG) {
  668. print STDERR 'Declining to save WMV file: ' . $filename . "\n";
  669. }
  670. return -1;
  671. }
  672. # Delete ZIP files -- mostly fake
  673. if ($ext =~ /zip/i) {
  674. if ($DEBUG) {
  675. print STDERR 'Declining to save ZIP file: ' . $filename . "\n";
  676. }
  677. return -1;
  678. }
  679. # Allow multiple guesses at the series/season/episode
  680. my $dest = '';
  681. LOOP: {
  682. # Determine the series, season, and episode number
  683. my ($series, $season, $episode) = &getSSE($filename);
  684. if ( defined($series)
  685. && length($series) > 0
  686. && defined($season)
  687. && $season > 0
  688. && defined($episode)
  689. && length($episode) > 0
  690. && $episode ne '0')
  691. {
  692. # Find the proper destination for this torrent, if any
  693. $dest = &getDest($series, $season, $episode, $ext);
  694. }
  695. # Sanity/loop check
  696. if (!defined($dest) || length($dest) < 1) {
  697. # If there is no match but the torrent is a folder
  698. # retry the guess using the torrent path
  699. if ($file ne $path) {
  700. my $newName = basename($path);
  701. if ($newName ne $filename) {
  702. $filename = basename($path);
  703. redo LOOP;
  704. }
  705. }
  706. # Otherwise we just fail
  707. print STDERR 'No destination for: ' . basename($file) . "\n";
  708. return;
  709. }
  710. }
  711. # Copy (to let Transmission deal with local cleanup) and rename into place
  712. my $tmp = mktemp($dest . '.XXXXXXXX');
  713. copy($file, $tmp);
  714. rename($tmp, $dest);
  715. # Touch to avoid carrying dates set in the download process
  716. touch($dest);
  717. # Return success
  718. return 1;
  719. }
  720. sub unrar($$) {
  721. my ($file, $path) = @_;
  722. if ($DEBUG) {
  723. print STDERR 'UnRARing: ' . basename($file) . "\n";
  724. }
  725. # Keep a list of old files, so we can find/delete the output
  726. my @beforeFiles = readDir($path, 1);
  727. # Run the unrar utility
  728. my $pid = fork();
  729. if (!defined($pid)) {
  730. print STDERR "Unable to fork for RAR\n";
  731. return;
  732. } elsif ($pid == 0) {
  733. # Child
  734. close(STDOUT);
  735. close(STDERR);
  736. chdir($path);
  737. my @args = ('unrar', 'e', '-p-', '-y', $file);
  738. exec { $args[0] } @args;
  739. }
  740. # Wait for the child
  741. waitpid($pid, 0);
  742. # Compare the old file list to the new one
  743. my @newFiles = ();
  744. my @afterFiles = readDir($path, 1);
  745. foreach my $file (@afterFiles) {
  746. my $found = 0;
  747. foreach my $file2 (@beforeFiles) {
  748. if ($file eq $file2) {
  749. $found = 1;
  750. last;
  751. }
  752. }
  753. if (!$found) {
  754. push(@newFiles, $file);
  755. }
  756. }
  757. # Return the list of added files
  758. return @newFiles;
  759. }
  760. sub seriesCleanupLocal($) {
  761. my ($name) = @_;
  762. $name =~ s/\.//g;
  763. return seriesCleanupCore($name);
  764. }
  765. sub seriesCleanupCore($) {
  766. my ($name) = @_;
  767. $name =~ s/^.*\[[^\]]*\]\s+//;
  768. $name =~ s/\b(?:and|\&)\b/ /ig;
  769. $name =~ s/^\s*The\b//ig;
  770. $name =~ s/\[[^\]]*\]//g;
  771. $name =~ s/\{[^\}]*\}//g;
  772. $name =~ s/[\(\)]//g;
  773. $name =~ s/[\'\"]//g;
  774. $name =~ s/[^\w\s]+/ /g;
  775. $name =~ s/_+/ /g;
  776. $name =~ s/\s+/ /g;
  777. $name =~ s/^\s*//;
  778. $name =~ s/\s*$//;
  779. return $name;
  780. }
  781. sub seriesCleanup($) {
  782. my ($name) = @_;
  783. $name =~ s/\s*\(?US\)?\s*$//;
  784. $name =~ s/\s*\(?20[01][0-9]\)?\s*$//;
  785. return seriesCleanupCore($name);
  786. }
  787. sub readDir($$) {
  788. my ($indir, $long) = @_;
  789. # Clean up the input directory
  790. $indir =~ s/\/+$//;
  791. my @files = ();
  792. if (!opendir(DIR, $indir)) {
  793. warn('readDir: Unable to read directory: ' . $indir . ': ' . $! . "\n");
  794. return;
  795. }
  796. foreach my $file (readdir(DIR)) {
  797. my $keep = 0;
  798. # Skip junk
  799. if ( $file eq '.'
  800. || $file eq '..'
  801. || $file =~ /\._/)
  802. {
  803. next;
  804. }
  805. # Save the full path
  806. if ($long) {
  807. push(@files, $indir . '/' . $file);
  808. } else {
  809. push(@files, $file);
  810. }
  811. }
  812. closedir(DIR);
  813. # Sorts the files before returning to the caller
  814. my @orderedFiles = ();
  815. @orderedFiles = sort(@files);
  816. # Return the file list
  817. return (@orderedFiles);
  818. }
  819. sub findMediaFiles($$) {
  820. my ($path, $depth) = @_;
  821. my @files = ();
  822. # Recursion limit
  823. if ($depth > $FIND_MAX_DEPTH) {
  824. return ();
  825. }
  826. my @tmpFiles = readDir($path, 1);
  827. foreach my $file (@tmpFiles) {
  828. # Skip sample files
  829. if ($file =~ /sample/i) {
  830. next;
  831. }
  832. # Recurse on directories
  833. if (-d $file) {
  834. push(@files, findMediaFiles($file, $depth + 1));
  835. next;
  836. }
  837. # Save matching files
  838. if ($file =~ /\.(?:avi|mkv|m4v|mov|mp4|ts|wmv)$/i) {
  839. push(@files, $file);
  840. next;
  841. }
  842. }
  843. return @files;
  844. }
  845. # Check availability of web interface
  846. sub available($) {
  847. my ($url) = @_;
  848. if ($DEBUG) {
  849. print STDERR "Checking for interface\n";
  850. }
  851. # Reset from the last host
  852. $fetch = Fetch->new();
  853. my ($host) = $url =~ /^(\w+\:\/\/[^\/]+\/?)/;
  854. $fetch->url($host);
  855. if ($fetch->fetch('nocheck' => 1) != 200) {
  856. if ($DEBUG) {
  857. print STDERR 'Code: ' . $fetch->status_code() . "\n";
  858. print STDERR 'Content: ' . $fetch->content() . "\n";
  859. warn('Interface not available: ' . $host . "\n");
  860. }
  861. return 0;
  862. }
  863. return 1;
  864. }