transmission.pl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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'} eq 'FAILURE/HEALTH' || $nzb->{'status'} eq 'FAILURE/PAR') {
  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'}) {
  447. print STDERR 'Unable to retrieve path for: ' . $tmp{'id'} . "\n";
  448. return 0;
  449. }
  450. # Debug
  451. if ($DEBUG > 1) {
  452. print STDERR "\n\n";
  453. foreach my $key (keys(%tmp)) {
  454. print STDERR $key . ' => ' . $tmp{$key} . "\n";
  455. }
  456. }
  457. # Store the NZB hash and return success
  458. ${$nzb} = \%tmp;
  459. return 1;
  460. }
  461. sub storeTor($) {
  462. my ($tor) = @_;
  463. if ($DEBUG) {
  464. print STDERR 'Storing torrent: ' . $tor->{'name'} . "\n";
  465. }
  466. # Handle individual files and directories
  467. my @files = ();
  468. my @newFiles = ();
  469. my $path = $tor->{'downloadDir'} . '/' . $tor->{'name'};
  470. if (!-d $path) {
  471. push(@files, $path);
  472. } else {
  473. # State variables
  474. my $IS_RAR = '';
  475. my $IS_FAKE = 0;
  476. # Look for RAR files
  477. foreach my $file (@{ $tor->{'files'} }) {
  478. if ($file->{'name'} =~ /\.rar$/i) {
  479. $IS_RAR = $tor->{'downloadDir'} . '/' . $file->{'name'};
  480. last;
  481. }
  482. }
  483. # Check for password files
  484. foreach my $file (@{ $tor->{'files'} }) {
  485. if ($file->{'name'} =~ /passw(?:or)?d/i) {
  486. print STDERR 'Password file detected in: ' . $tor->{'name'} . "\n";
  487. $IS_FAKE = 1;
  488. last;
  489. }
  490. }
  491. # Check for single-file RARs
  492. if ($IS_RAR && scalar(@{ $tor->{'files'} }) < $RAR_MIN_FILES) {
  493. print STDERR 'Single-file RAR detected in: ' . $tor->{'name'} . "\n";
  494. $IS_FAKE = 1;
  495. }
  496. # Delete fake torrents and bail
  497. if ($IS_FAKE) {
  498. if ($DEBUG) {
  499. print STDERR 'Deleting fake torrent: ' . $tor->{'name'} . "\n";
  500. }
  501. delTor($tor);
  502. next;
  503. }
  504. # Unrar if necessary
  505. if (defined($IS_RAR) && length($IS_RAR) > 0) {
  506. @newFiles = &unrar($IS_RAR, $path);
  507. }
  508. # Find all media files, recursively
  509. @files = findMediaFiles($path, 0);
  510. }
  511. # Process any files we found
  512. if (scalar(@files) < 1) {
  513. print STDERR 'No media files found in torrent: ' . $tor->{'name'} . "\n";
  514. return 0;
  515. }
  516. my $retval = storeFiles($path, \@files, $tor->{'name'});
  517. # Delete any files we added
  518. foreach my $file (@newFiles) {
  519. if ($DEBUG) {
  520. print STDERR 'Deleting new file: ' . basename($file) . "\n";
  521. }
  522. unlink($file);
  523. }
  524. # Return whatever storeFiles() said
  525. return $retval;
  526. }
  527. sub storeNZB($) {
  528. my ($nzb) = @_;
  529. if ($DEBUG) {
  530. print STDERR 'Storing NZB: ' . $nzb->{'name'} . "\n";
  531. }
  532. # Find all media files, recursively
  533. my @files = findMediaFiles($nzb->{'path'}, 0);
  534. # Process any files we found
  535. if (scalar(@files) < 1) {
  536. print STDERR 'No media files found in NZB: ' . $nzb->{'name'} . "\n";
  537. next;
  538. }
  539. return storeFiles($nzb->{'path'}, \@files, $nzb->{'name'});
  540. }
  541. sub delNZB($) {
  542. my ($nzb) = @_;
  543. if ($DEBUG) {
  544. print STDERR 'Deleting NZB: ' . $nzb->{'name'} . "\n";
  545. }
  546. # Remove the files, if any
  547. if (-e $nzb->{'path'} && -d $nzb->{'path'}) {
  548. if ($DEBUG) {
  549. print STDERR 'Removing NZB folder: ' . $nzb->{'path'} . "\n";
  550. }
  551. remove_tree($nzb->{'path'});
  552. # Check for deletion
  553. if (-e $nzb->{'path'}) {
  554. print STDERR 'Unable to remove NZB folder: ' . $nzb->{'path'} . "\n";
  555. return 0;
  556. }
  557. }
  558. # Send the command
  559. my $id = $nzb->{'id'};
  560. my $content = $delHistory;
  561. $content =~ s/\#_ID_\#/${id}/;
  562. $fetch->post_content($content);
  563. $fetch->fetch();
  564. # Check the result
  565. if ($fetch->content() =~ /\"result\" \: true/i) {
  566. return 1;
  567. }
  568. return 0;
  569. }
  570. sub delTor($) {
  571. my ($tor) = @_;
  572. if ($DEBUG) {
  573. print STDERR 'Deleting torrent: ' . $tor->{'name'} . "\n";
  574. }
  575. # Sleep to avoid bugs in Transmission (i.e. multiple deletes fail)
  576. sleep($delSleep);
  577. # Construct the content
  578. my $id = $tor->{'hashString'};
  579. my $content = $delContent;
  580. $content =~ s/\#_ID_\#/${id}/;
  581. # Send the command
  582. &session($fetch);
  583. $fetch->post_content($content);
  584. &fetch($fetch);
  585. }
  586. sub guessExt($) {
  587. my ($file) = @_;
  588. my $ext = '';
  589. # Believe most non-avi file extensions without checking
  590. # It's mostly "avi" that lies, and the checks are expensive
  591. {
  592. my $orig_ext = basename($file);
  593. $orig_ext =~ s/^.*\.(\w{2,3})$/$1/;
  594. $orig_ext = lc($orig_ext);
  595. if ($orig_ext eq 'mkv' || $orig_ext eq 'ts') {
  596. $ext = $orig_ext;
  597. }
  598. }
  599. # Deal with the weird case of text files labeled as .txt.mp4
  600. if ($file =~ /\.txt\.mp4$/i) {
  601. $ext = 'txt';
  602. }
  603. # Guess the file type if we don't have one yet
  604. if (!$ext) {
  605. my $mime = '';
  606. my $demux = '';
  607. # Try ExifTool for MIME and demuxer types
  608. if (!$mime || !$demux) {
  609. my $exif = ImageInfo($file);
  610. if (defined($exif) && ref($exif) eq 'HASH') {
  611. if ($exif->{'MIMEType'}) {
  612. $mime = $exif->{'MIMEType'};
  613. }
  614. if ($exif->{'FileType'}) {
  615. $demux = $exif->{'FileType'};
  616. }
  617. }
  618. }
  619. # Try file(1) for MIME types
  620. if (!$mime) {
  621. open(FILE, '-|', 'file', '-b', $file);
  622. while (<FILE>) {
  623. $mime .= $_;
  624. }
  625. close(FILE);
  626. }
  627. # Cleanup the demuxer and MIME types
  628. $demux =~ s/^\s+//;
  629. $demux =~ s/\s+$//;
  630. $mime =~ s/^\s+//;
  631. $mime =~ s/\s+$//;
  632. $mime =~ s/\;.*$//;
  633. $mime =~ s/^video\///i;
  634. # Try to pick an extension we understand
  635. if ($demux =~ /MKV/i || $mime =~ /Matroska/i) {
  636. $ext = 'mkv';
  637. } elsif ($demux =~ /ASF/i || $mime =~ /\bASF\b/i) {
  638. $ext = 'wmv';
  639. } elsif ($demux =~ /MP4/i || $mime =~ /\bMP4\b/i) {
  640. $ext = 'mp4';
  641. } elsif ($mime =~ /\bZIP/i) {
  642. $ext = 'zip';
  643. } elsif ($demux =~ /MPEGTS/i) {
  644. $ext = 'ts';
  645. } else {
  646. $ext = 'avi';
  647. }
  648. }
  649. return $ext;
  650. }
  651. sub processFile($$) {
  652. my ($file, $path) = @_;
  653. if ($DEBUG) {
  654. print STDERR 'Attempting to process file: ' . basename($file) . "\n";
  655. }
  656. # Skip known packaging files files with success code
  657. if ($file =~ /\/RARBG\.com\.(?:mp4|avi|mkv|txt)$/i || $file =~ /\.txt\.(?:mp4|avi|mkv)$/) {
  658. if ($DEBUG) {
  659. print STDERR 'Declining to save packaging file: ' . $file . "\n";
  660. }
  661. return 1;
  662. }
  663. # Guess a file extension and basename
  664. my $ext = &guessExt($file);
  665. my $filename = basename($file);
  666. # Delete WMV files -- mostly viruses/fake
  667. if ($ext =~ /wmv/i) {
  668. if ($DEBUG) {
  669. print STDERR 'Declining to save WMV file: ' . $filename . "\n";
  670. }
  671. return -1;
  672. }
  673. # Delete ZIP files -- mostly fake
  674. if ($ext =~ /zip/i) {
  675. if ($DEBUG) {
  676. print STDERR 'Declining to save ZIP file: ' . $filename . "\n";
  677. }
  678. return -1;
  679. }
  680. # Allow multiple guesses at the series/season/episode
  681. my $dest = '';
  682. LOOP: {
  683. # Determine the series, season, and episode number
  684. my ($series, $season, $episode) = &getSSE($filename);
  685. if ( defined($series)
  686. && length($series) > 0
  687. && defined($season)
  688. && $season > 0
  689. && defined($episode)
  690. && length($episode) > 0
  691. && $episode ne '0')
  692. {
  693. # Find the proper destination for this torrent, if any
  694. $dest = &getDest($series, $season, $episode, $ext);
  695. }
  696. # Sanity/loop check
  697. if (!defined($dest) || length($dest) < 1) {
  698. # If there is no match but the torrent is a folder
  699. # retry the guess using the torrent path
  700. if ($file ne $path) {
  701. my $newName = basename($path);
  702. if ($newName ne $filename) {
  703. $filename = basename($path);
  704. redo LOOP;
  705. }
  706. }
  707. # Otherwise we just fail
  708. print STDERR 'No destination for: ' . basename($file) . "\n";
  709. return;
  710. }
  711. }
  712. # Copy (to let Transmission deal with local cleanup) and rename into place
  713. my $tmp = mktemp($dest . '.XXXXXXXX');
  714. copy($file, $tmp);
  715. rename($tmp, $dest);
  716. # Touch to avoid carrying dates set in the download process
  717. touch($dest);
  718. # Return success
  719. return 1;
  720. }
  721. sub unrar($$) {
  722. my ($file, $path) = @_;
  723. if ($DEBUG) {
  724. print STDERR 'UnRARing: ' . basename($file) . "\n";
  725. }
  726. # Keep a list of old files, so we can find/delete the output
  727. my @beforeFiles = readDir($path, 1);
  728. # Run the unrar utility
  729. my $pid = fork();
  730. if (!defined($pid)) {
  731. print STDERR "Unable to fork for RAR\n";
  732. return;
  733. } elsif ($pid == 0) {
  734. # Child
  735. close(STDOUT);
  736. close(STDERR);
  737. chdir($path);
  738. my @args = ('unrar', 'e', '-p-', '-y', $file);
  739. exec { $args[0] } @args;
  740. }
  741. # Wait for the child
  742. waitpid($pid, 0);
  743. # Compare the old file list to the new one
  744. my @newFiles = ();
  745. my @afterFiles = readDir($path, 1);
  746. foreach my $file (@afterFiles) {
  747. my $found = 0;
  748. foreach my $file2 (@beforeFiles) {
  749. if ($file eq $file2) {
  750. $found = 1;
  751. last;
  752. }
  753. }
  754. if (!$found) {
  755. push(@newFiles, $file);
  756. }
  757. }
  758. # Return the list of added files
  759. return @newFiles;
  760. }
  761. sub seriesCleanupLocal($) {
  762. my ($name) = @_;
  763. $name =~ s/\.//g;
  764. return seriesCleanupCore($name);
  765. }
  766. sub seriesCleanupCore($) {
  767. my ($name) = @_;
  768. $name =~ s/^.*\[[^\]]*\]\s+//;
  769. $name =~ s/\b(?:and|\&)\b/ /ig;
  770. $name =~ s/^\s*The\b//ig;
  771. $name =~ s/\[[^\]]*\]//g;
  772. $name =~ s/\{[^\}]*\}//g;
  773. $name =~ s/[\(\)]//g;
  774. $name =~ s/[\'\"]//g;
  775. $name =~ s/[^\w\s]+/ /g;
  776. $name =~ s/_+/ /g;
  777. $name =~ s/\s+/ /g;
  778. $name =~ s/^\s*//;
  779. $name =~ s/\s*$//;
  780. return $name;
  781. }
  782. sub seriesCleanup($) {
  783. my ($name) = @_;
  784. $name =~ s/\s*\(?US\)?\s*$//;
  785. $name =~ s/\s*\(?20[01][0-9]\)?\s*$//;
  786. return seriesCleanupCore($name);
  787. }
  788. sub readDir($$) {
  789. my ($indir, $long) = @_;
  790. # Clean up the input directory
  791. $indir =~ s/\/+$//;
  792. my @files = ();
  793. if (!opendir(DIR, $indir)) {
  794. warn('readDir: Unable to read directory: ' . $indir . ': ' . $! . "\n");
  795. return;
  796. }
  797. foreach my $file (readdir(DIR)) {
  798. my $keep = 0;
  799. # Skip junk
  800. if ( $file eq '.'
  801. || $file eq '..'
  802. || $file =~ /\._/)
  803. {
  804. next;
  805. }
  806. # Save the full path
  807. if ($long) {
  808. push(@files, $indir . '/' . $file);
  809. } else {
  810. push(@files, $file);
  811. }
  812. }
  813. closedir(DIR);
  814. # Sorts the files before returning to the caller
  815. my @orderedFiles = ();
  816. @orderedFiles = sort(@files);
  817. # Return the file list
  818. return (@orderedFiles);
  819. }
  820. sub findMediaFiles($$) {
  821. my ($path, $depth) = @_;
  822. my @files = ();
  823. # Recursion limit
  824. if ($depth > $FIND_MAX_DEPTH) {
  825. return ();
  826. }
  827. my @tmpFiles = readDir($path, 1);
  828. foreach my $file (@tmpFiles) {
  829. # Skip sample files
  830. if ($file =~ /sample/i) {
  831. next;
  832. }
  833. # Recurse on directories
  834. if (-d $file) {
  835. push(@files, findMediaFiles($file, $depth + 1));
  836. next;
  837. }
  838. # Save matching files
  839. if ($file =~ /\.(?:avi|mkv|m4v|mov|mp4|ts|wmv)$/i) {
  840. push(@files, $file);
  841. next;
  842. }
  843. }
  844. return @files;
  845. }
  846. # Check availability of web interface
  847. sub available($) {
  848. my ($url) = @_;
  849. if ($DEBUG) {
  850. print STDERR "Checking for interface\n";
  851. }
  852. # Reset from the last host
  853. $fetch = Fetch->new();
  854. my ($host) = $url =~ /^(\w+\:\/\/[^\/]+\/?)/;
  855. $fetch->url($host);
  856. if ($fetch->fetch('nocheck' => 1) != 200) {
  857. if ($DEBUG) {
  858. print STDERR 'Code: ' . $fetch->status_code() . "\n";
  859. print STDERR 'Content: ' . $fetch->content() . "\n";
  860. warn('Interface not available: ' . $host . "\n");
  861. }
  862. return 0;
  863. }
  864. return 1;
  865. }