transmission.pl 23 KB

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