rss.pl 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Cwd qw(abs_path);
  5. use MP3::Tag;
  6. use XML::Feed;
  7. use LWP::Simple;
  8. use HTML::Strip;
  9. use Date::Parse;
  10. use Date::Format;
  11. use File::Basename;
  12. # Command-line
  13. my $OUT_DIR = abs_path($ARGV[0]);
  14. if (!$OUT_DIR || !-d $OUT_DIR) {
  15. die('Usage: ' . basename($0) . " output_directory\n");
  16. }
  17. # Parameters
  18. my $GENRE = 'Podcast';
  19. my $SERIES = basename($OUT_DIR);
  20. my $URL_FILE = $OUT_DIR . '/url';
  21. my $RULE_FILE = $OUT_DIR . '/rules.pm';
  22. my $ERR_RATIO = 0.05;
  23. my $DL_LIMIT = 50;
  24. # Init
  25. our $DEBUG = 0;
  26. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'} =~ /(\d+)/) {
  27. $DEBUG = $1;
  28. }
  29. my %episodes = ();
  30. my %have = ();
  31. my @need = ();
  32. my $hs = HTML::Strip->new();
  33. MP3::Tag->config('write_v24' => 1);
  34. # Skip if there is a season_done file
  35. if (-e $OUT_DIR . '/season_done') {
  36. if ($DEBUG) {
  37. print STDERR 'Podcast disabled: ' . $SERIES . "\n";
  38. }
  39. exit(0);
  40. }
  41. # Fetch and analyize the feed
  42. my $feed = undef();
  43. {
  44. open(my $fh, '<', $URL_FILE)
  45. or die('Unable to open feed file: ' . $URL_FILE . "\n");
  46. my $url = <$fh>;
  47. close($fh);
  48. if (!$url || length($url) < 5) {
  49. die('Invalid feed URL: ' . $url . "\n");
  50. }
  51. $feed = XML::Feed->parse(URI->new($url));
  52. if (!$feed) {
  53. die('Unable to parse feed (' . XML::Feed->errstr() . '): ' . $url . "\n");
  54. }
  55. }
  56. # Parse each episode from the feed
  57. for my $entry ($feed->entries()) {
  58. my $ep = $entry->unwrap();
  59. # Title
  60. my $title = '';
  61. if (defined($ep->{'title'})) {
  62. $title = $ep->{'title'};
  63. }
  64. $title = $hs->parse($title);
  65. $hs->eof();
  66. $title =~ s/^\s+//;
  67. $title =~ s/\s+$//;
  68. # Description
  69. my $desc = '';
  70. if (defined($ep->{'description'})) {
  71. $desc = $ep->{'description'};
  72. }
  73. $desc = $hs->parse($desc);
  74. $hs->eof();
  75. $desc =~ s/^\s+//;
  76. $desc =~ s/\s+$//;
  77. # Timestamp
  78. my $time = str2time($ep->{'pubDate'});
  79. # Author
  80. my $author = undef();
  81. if (exists($ep->{'author'})) {
  82. $author = $ep->{'author'};
  83. $author =~ s/^\s+//;
  84. $author =~ s/\s+$//;
  85. }
  86. # Enclosure (i.e. attachment/file) data
  87. my ($url, $ext, $size) = undef();
  88. {
  89. my $enc = $ep->{'enclosure'};
  90. if ($enc && ref($enc) eq 'HASH' && exists($enc->{'url'})) {
  91. $url = $enc->{'url'};
  92. if (exists($enc->{'type'})) {
  93. if ($enc->{'type'} =~ /audio\/mp4/i) {
  94. $ext = 'm4a';
  95. } elsif ($enc->{'type'} =~ /audio\/mpeg/i) {
  96. $ext = 'mp3';
  97. } elsif ($enc->{'type'} =~ /video\//i) {
  98. if ($DEBUG > 1) {
  99. print STDERR 'Skipping video file: ' . time2str('%Y-%m-%d', $time) . "\n";
  100. }
  101. } else {
  102. print STDERR 'Unknown MIME type: ' . $enc->{'type'} . "\n";
  103. }
  104. }
  105. if (exists($enc->{'length'})) {
  106. $size = $enc->{'length'};
  107. }
  108. }
  109. }
  110. # iTunes data, if available (and useful)
  111. my $duration = undef();
  112. if ($ep->{'http://www.itunes.com/dtds/podcast-1.0.dtd'}) {
  113. my $itunes = $ep->{'http://www.itunes.com/dtds/podcast-1.0.dtd'};
  114. if (exists($itunes->{'duration'})) {
  115. if ($itunes->{'duration'} =~ /(\d+)\:(\d\d)\:(\d\d)/) {
  116. $duration = (3600 * int($1)) + (60 * int($2)) + int($3);
  117. } elsif ($itunes->{'duration'} =~ /(\d+)\:(\d\d)/) {
  118. $duration = (60 * int($1)) + int($2);
  119. } elsif ($itunes->{'duration'} =~ /(\d+)/) {
  120. $duration = int($1);
  121. } elsif ($DEBUG) {
  122. print STDERR 'Unknown duration format: ' . $itunes->{'duration'} . "\n";
  123. }
  124. }
  125. if (!$desc && exists($itunes->{'summary'})) {
  126. $desc = $itunes->{'summary'};
  127. $desc =~ s/^\s+//;
  128. $desc =~ s/\s+$//;
  129. }
  130. if (!$author && exists($itunes->{'author'})) {
  131. $author = $itunes->{'author'};
  132. $author =~ s/^\s+//;
  133. $author =~ s/\s+$//;
  134. }
  135. }
  136. # Collect extracted, cleaned data
  137. if ($title && $time && $url && $ext && $desc) {
  138. my %tmp = (
  139. 'title' => $title,
  140. 'time' => $time,
  141. 'url' => $url,
  142. 'ext' => $ext,
  143. 'description' => $desc,
  144. 'size' => $size,
  145. 'duration' => $duration,
  146. 'author' => $author,
  147. );
  148. $episodes{$time} = \%tmp;
  149. } elsif ($DEBUG) {
  150. print STDERR "Skipping incomplete entry:\n";
  151. print STDERR "\tTitle: ";
  152. if ($title) {
  153. print STDERR $title . "\n";
  154. } else {
  155. print STDERR "<missing>\n";
  156. }
  157. print STDERR "\tTime: ";
  158. if ($time) {
  159. print STDERR time2str('%Y-%m-%d', $time) . "\n";
  160. } else {
  161. print STDERR "<missing>\n";
  162. }
  163. print STDERR "\tURL: ";
  164. if ($url) {
  165. print STDERR $url . "\n";
  166. } else {
  167. print STDERR "<missing>\n";
  168. }
  169. print STDERR "\tExtension: ";
  170. if ($ext) {
  171. print STDERR $ext . "\n";
  172. } else {
  173. print STDERR "<missing>\n";
  174. }
  175. print STDERR "\tDescription: ";
  176. if ($desc) {
  177. print STDERR substr($desc, 0, 20) . "\n";
  178. } else {
  179. print STDERR "<missing>\n";
  180. }
  181. }
  182. }
  183. # Check for existing files
  184. opendir(my $fh, $OUT_DIR)
  185. or die('Unable to open output directory (' . $! . '): ' . $OUT_DIR . "\n");
  186. while (my $file = readdir($fh)) {
  187. my $path = $OUT_DIR . '/' . $file;
  188. if (-d $path) {
  189. next;
  190. }
  191. if ($file =~ /^(.*)\s+\((\d{7,})\)\.\w{3}$/) {
  192. my $title = $1;
  193. my $time = $2;
  194. if (exists($episodes{$time})) {
  195. if (exists($episodes{$time}->{'size'}) && $episodes{$time}->{'size'}) {
  196. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($path);
  197. my $ratio = ($size / $episodes{$time}->{'size'});
  198. if ($ratio < (1 - $ERR_RATIO) && $DEBUG) {
  199. print STDERR 'Invalid output file size (' . $size . '/' . $episodes{$time}->{'size'} . '): ' . $file . "\n";
  200. }
  201. }
  202. $have{$time} = 1;
  203. $episodes{$time}->{'title'} = $title;
  204. }
  205. if ($DEBUG) {
  206. print STDERR 'Found file: ' . $file . "\n";
  207. }
  208. } elsif ($DEBUG > 1) {
  209. print STDERR 'Skipping file: ' . $file . "\n";
  210. }
  211. }
  212. closedir($fh);
  213. # Decide what we want to download
  214. foreach my $time (keys(%episodes)) {
  215. if (!exists($have{$time})) {
  216. push(@need, $time);
  217. if ($DEBUG > 1) {
  218. print STDERR 'Will fetch: ' . time2str('%Y-%m-%d', $time) . "\n";
  219. }
  220. }
  221. }
  222. if ($DEBUG) {
  223. print STDERR 'Need/Total: ' . scalar(@need) . '/' . scalar(keys(%episodes)) . "\n";
  224. }
  225. # Apply naming rules
  226. if (-e $RULE_FILE) {
  227. if ($DEBUG > 1) {
  228. print STDERR 'Importing local rules from: ' . $RULE_FILE . "\n";
  229. }
  230. require $RULE_FILE;
  231. localRules(\%episodes);
  232. } else {
  233. foreach my $time (sort(keys(%episodes))) {
  234. $episodes{$time}->{'title'} = time2str('%Y-%m-%d', $time) . ' - ' . $episodes{$time}->{'title'};
  235. }
  236. }
  237. foreach my $time (keys(%episodes)) {
  238. $episodes{$time}->{'title'} =~ s/\s*\:\s*/ - /g;
  239. $episodes{$time}->{'title'} =~ s/\s+/ /g;
  240. $episodes{$time}->{'title'} =~ s/\"/\'/g;
  241. $episodes{$time}->{'title'} =~ s/[^\w\s\,\-\.\!\'\(\)\#\&\@]//g;
  242. }
  243. # Fetch needed files, with basic validation
  244. my $dlCount = 0;
  245. foreach my $time (sort(@need)) {
  246. if ($dlCount >= $DL_LIMIT) {
  247. die('Download limit (' . $DL_LIMIT . ') reached: ' . $SERIES . "\n");
  248. }
  249. # Build a file path
  250. my $ep = $episodes{$time};
  251. my $file = $OUT_DIR . '/' . $ep->{'title'} . ' (' . int($time) . ').' . $ep->{'ext'};
  252. if (-e $file) {
  253. die('Unexpected output file: ' . $file . "\n");
  254. }
  255. # Debug
  256. if ($DEBUG) {
  257. print STDERR 'Fetching (' . time2str('%Y-%m-%d', $time) . '): ' . $ep->{'title'} . ' => ' . $ep->{'url'} . "\n";
  258. }
  259. # Fetch
  260. my $code = getstore($ep->{'url'}, $file);
  261. $dlCount++;
  262. # Validate
  263. my $err = undef();
  264. if ($code != 200) {
  265. $err = 'Invalid HTTP response: ' . $code;
  266. goto OUT;
  267. }
  268. if (!-e $file) {
  269. $err = 'No output file: ' . $file;
  270. goto OUT;
  271. }
  272. if ($ep->{'size'}) {
  273. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($file);
  274. my $ratio = $size / $ep->{'size'};
  275. if ($ratio < (1 - $ERR_RATIO)) {
  276. $err = 'Invalid download size (' . $size . '/' . $ep->{'size'} . '): ' . $file;
  277. goto OUT;
  278. }
  279. }
  280. # Set MP3/M4A tags
  281. if ($ep->{'ext'} eq 'mp3') {
  282. # Parse the MP3
  283. my $mp3 = MP3::Tag->new($file);
  284. if (!$mp3) {
  285. $err = 'Unable to parse MP3 tags in: ' . $file . "\n";
  286. goto OUT;
  287. }
  288. # Delete any ID3v1 tags
  289. if (exists($mp3->{'ID3v1'})) {
  290. print STDERR "Removing ID3v1 tag\n";
  291. $mp3->{'ID3v1'}->remove_tag();
  292. print STDERR "Removed?\n";
  293. }
  294. # Find or create the ID3v2 tag
  295. my $tags = undef();
  296. if (exists($mp3->{'ID3v2'})) {
  297. $tags = $mp3->{'ID3v2'};
  298. } else {
  299. $tags = $mp3->new_tag('ID3v2');
  300. }
  301. # Update tags
  302. $tags->title($ep->{'title'});
  303. $tags->year(time2str('%Y', $ep->{'time'}));
  304. $tags->comment($ep->{'description'});
  305. $tags->track(1);
  306. $tags->album($SERIES);
  307. $tags->artist($SERIES);
  308. $tags->genre($GENRE);
  309. # Save
  310. if (!$tags->write_tag()) {
  311. $err = 'Unable to update MP3 tags in: ' . $file . "\n";
  312. goto OUT;
  313. }
  314. $mp3->close();
  315. } else {
  316. print STDERR 'Tag munging not available for ' . $ep->{'ext'} . ' files: ' . $file . "\n";
  317. }
  318. OUT:
  319. # Cleanup
  320. if (defined($err)) {
  321. if ($DEBUG || ! ($err =~ /\b40[34]$/)) {
  322. print STDERR 'Unable to download ' . $ep->{'url'} . ': ' . $err . "\n";
  323. }
  324. if (-e $file) {
  325. unlink($file);
  326. }
  327. }
  328. }