rss.pl 6.9 KB

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