transmission.pl 20 KB

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