rss.pl 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. # Fetch and analyize the feed
  34. my $feed = undef();
  35. {
  36. open(my $fh, '<', $URL_FILE)
  37. or die('Unable to open feed file: ' . $URL_FILE . "\n");
  38. my $url = <$fh>;
  39. close($fh);
  40. if (!$url || length($url) < 5) {
  41. die('Invalid feed URL: ' . $url . "\n");
  42. }
  43. $feed = XML::Feed->parse(URI->new($url));
  44. if (!$feed) {
  45. die('Unable to parse feed (' . XML::Feed->errstr() . '): ' . $url . "\n");
  46. }
  47. }
  48. # Parse each episode from the feed
  49. for my $entry ($feed->entries()) {
  50. my $ep = $entry->unwrap();
  51. # Title
  52. my $title = $hs->parse($ep->{'title'});
  53. $hs->eof();
  54. $title =~ s/^\s+//;
  55. $title =~ s/\s+$//;
  56. # Description
  57. my $desc = $hs->parse($ep->{'description'});
  58. $hs->eof();
  59. $desc =~ s/^\s+//;
  60. $desc =~ s/\s+$//;
  61. # Timestamp
  62. my $time = str2time($ep->{'pubDate'});
  63. # Author
  64. my $author = undef();
  65. if (exists($ep->{'author'})) {
  66. $author = $ep->{'author'};
  67. $author =~ s/^\s+//;
  68. $author =~ s/\s+$//;
  69. }
  70. # Enclosure (i.e. attachment/file) data
  71. my ($url, $ext, $size) = undef();
  72. {
  73. my $enc = $ep->{'enclosure'};
  74. if ($enc && ref($enc) eq 'HASH' && exists($enc->{'url'})) {
  75. $url = $enc->{'url'};
  76. if (exists($enc->{'type'})) {
  77. if ($enc->{'type'} =~ /audio\/mp4/i) {
  78. $ext = 'm4a';
  79. } elsif ($enc->{'type'} =~ /audio\/mpeg/i) {
  80. $ext = 'mp3';
  81. } elsif ($enc->{'type'} =~ /video\//i) {
  82. if ($DEBUG > 1) {
  83. print STDERR 'Skipping video file: ' . $time . "\n";
  84. }
  85. } else {
  86. print STDERR 'Unknown MIME type: ' . $enc->{'type'} . "\n";
  87. }
  88. }
  89. if (exists($enc->{'length'})) {
  90. $size = $enc->{'length'};
  91. }
  92. }
  93. }
  94. # iTunes data, if available (and useful)
  95. my $duration = undef();
  96. if (exists($ep->{'itunes:duration'})) {
  97. if ($ep->{'itunes:duration'} =~ /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/) {
  98. $duration = (3600 * int($1)) + (60 * int($2)) + int($3);
  99. } else {
  100. $duration = int($ep->{'itunes:duration'});
  101. }
  102. }
  103. if (!$desc && exists($ep->{'itunes:summary'})) {
  104. $desc = $ep->{'itunes:summary'};
  105. $desc =~ s/^\s+//;
  106. $desc =~ s/\s+$//;
  107. }
  108. # Collect extracted, cleaned data
  109. if ($title && $desc && $time && $url && $ext) {
  110. my %tmp = (
  111. 'title' => $title,
  112. 'description' => $desc,
  113. 'time' => $time,
  114. 'url' => $url,
  115. 'ext' => $ext,
  116. 'size' => $size,
  117. 'duration' => $duration,
  118. 'author' => $author,
  119. );
  120. $episodes{$time} = \%tmp;
  121. } elsif ($DEBUG) {
  122. print STDERR 'Skipping incomplete entry: ' . $title . ': ' . $time . "\n";
  123. }
  124. }
  125. # Check for existing files
  126. opendir(my $fh, $OUT_DIR)
  127. or die('Unable to open output directory (' . $! . '): ' . $OUT_DIR . "\n");
  128. while (my $file = readdir($fh)) {
  129. my $path = $OUT_DIR . '/' . $file;
  130. if (-d $path) {
  131. next;
  132. }
  133. if ($file =~ /^(.*)\s+\((\d{7,})\)\.\w{3}$/) {
  134. my $title = $1;
  135. my $time = $2;
  136. if (exists($episodes{$time})) {
  137. if (exists($episodes{$time}->{'size'}) && $episodes{$time}->{'size'}) {
  138. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($path);
  139. my $ratio = ($size / $episodes{$time}->{'size'});
  140. if ($ratio < (1 - $ERR_RATIO) || $ratio > (1 + $ERR_RATIO)) {
  141. print STDERR 'Invalid output file size (' . $size . '/' . $episodes{$time}->{'size'} . '): ' . $file . "\n";
  142. }
  143. }
  144. $have{$time} = 1;
  145. $episodes{$time}->{'title'} = $title;
  146. }
  147. if ($DEBUG) {
  148. print STDERR 'Found file: ' . $file . "\n";
  149. }
  150. } elsif ($DEBUG > 1) {
  151. print STDERR 'Skipping file: ' . $file . "\n";
  152. }
  153. }
  154. closedir($fh);
  155. # Decide what we want to download
  156. foreach my $time (keys(%episodes)) {
  157. if (!exists($have{$time})) {
  158. push(@need, $time);
  159. if ($DEBUG > 1) {
  160. print STDERR 'Will fetch: ' . $time . "\n";
  161. }
  162. }
  163. }
  164. # Apply naming rules
  165. if (-e $RULE_FILE) {
  166. if ($DEBUG > 1) {
  167. print STDERR 'Importing local rules from: ' . $RULE_FILE . "\n";
  168. }
  169. require $RULE_FILE;
  170. localRules(\%episodes);
  171. } else {
  172. foreach my $time (sort(keys(%episodes))) {
  173. $episodes{$time}->{'title'} = time2str('%Y-%m-%d', $time) . ' - ' . $episodes{$time}->{'title'};
  174. }
  175. }
  176. foreach my $time (keys(%episodes)) {
  177. $episodes{$time}->{'title'} =~ s/\s*\:\s*/ - /g;
  178. $episodes{$time}->{'title'} =~ s/\s+/ /g;
  179. $episodes{$time}->{'title'} =~ s/\"/\'/g;
  180. $episodes{$time}->{'title'} =~ s/[^\w\s\,\-\.\!\'\(\)\#\&\@]//g;
  181. }
  182. # Fetch needed files, with basic validation
  183. my $dlCount = 0;
  184. foreach my $time (sort(@need)) {
  185. if ($dlCount >= $DL_LIMIT) {
  186. die('Download limit (' . $DL_LIMIT . ') reached: ' . $SERIES . "\n");
  187. }
  188. # Build a file path
  189. my $ep = $episodes{$time};
  190. my $file = $OUT_DIR . '/' . $ep->{'title'} . ' (' . int($time) . ').' . $ep->{'ext'};
  191. if (-e $file) {
  192. die('Unexpected output file: ' . $file . "\n");
  193. }
  194. # Debug
  195. if ($DEBUG) {
  196. print STDERR 'Fetching (' . $time . '): ' . $ep->{'title'} . ' => ' . $ep->{'url'} . "\n";
  197. }
  198. # Fetch
  199. my $code = getstore($ep->{'url'}, $file);
  200. $dlCount++;
  201. # Validate
  202. my $err = undef();
  203. if ($code != 200) {
  204. $err = 'Invalid HTTP response: ' . $code;
  205. goto OUT;
  206. }
  207. if (!-e $file) {
  208. $err = 'No output file: ' . $file;
  209. goto OUT;
  210. }
  211. if ($ep->{'size'}) {
  212. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($file);
  213. my $ratio = $size / $ep->{'size'};
  214. if ($ratio < (1 - $ERR_RATIO) || $ratio > (1 + $ERR_RATIO)) {
  215. $err = 'Invalid download size (' . $size . '/' . $ep->{'size'} . '): ' . $file;
  216. goto OUT;
  217. }
  218. }
  219. # Set MP3/M4A tags
  220. if ($ep->{'ext'} eq 'mp3') {
  221. # Parse the MP3
  222. my $mp3 = MP3::Tag->new($file);
  223. if (!$mp3) {
  224. $err = 'Unable to parse MP3 tags in: ' . $file . "\n";
  225. goto OUT;
  226. }
  227. # Delete any ID3v1 tags
  228. if (exists($mp3->{'ID3v1'})) {
  229. print STDERR "Removing ID3v1 tag\n";
  230. $mp3->{'ID3v1'}->remove_tag();
  231. print STDERR "Removed?\n";
  232. }
  233. # Find or create the ID3v2 tag
  234. my $tags = undef();
  235. if (exists($mp3->{'ID3v2'})) {
  236. $tags = $mp3->{'ID3v2'};
  237. } else {
  238. $tags = $mp3->new_tag('ID3v2');
  239. }
  240. # Update tags
  241. $tags->title($ep->{'title'});
  242. $tags->year(time2str('%Y', $ep->{'time'}));
  243. $tags->comment($ep->{'description'});
  244. $tags->album($SERIES);
  245. $tags->artist($SERIES);
  246. $tags->genre($GENRE);
  247. # Save
  248. if (!$tags->write_tag()) {
  249. $err = 'Unable to update MP3 tags in: ' . $file . "\n";
  250. goto OUT;
  251. }
  252. $mp3->close();
  253. } else {
  254. print STDERR 'Tag munging not available for ' . $ep->{'ext'} . ' files: ' . $file . "\n";
  255. }
  256. OUT:
  257. # Cleanup
  258. if (defined($err)) {
  259. print STDERR 'Unable to download ' . $ep->{'url'} . ': ' . $err . "\n";
  260. if (-e $file) {
  261. unlink($file);
  262. }
  263. }
  264. }