transmission.pl 23 KB

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