rss.pl 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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: ' . $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{1,2})\:(\d{1,2})\:(\d{1,2})/) {
  116. $duration = (3600 * int($1)) + (60 * int($2)) + int($3);
  117. } else {
  118. $duration = int($itunes->{'duration'});
  119. }
  120. }
  121. if (!$desc && exists($itunes->{'summary'})) {
  122. $desc = $itunes->{'summary'};
  123. $desc =~ s/^\s+//;
  124. $desc =~ s/\s+$//;
  125. }
  126. if (!$author && exists($itunes->{'author'})) {
  127. $author = $itunes->{'author'};
  128. $author =~ s/^\s+//;
  129. $author =~ s/\s+$//;
  130. }
  131. }
  132. # Collect extracted, cleaned data
  133. if ($title && $desc && $time && $url && $ext) {
  134. my %tmp = (
  135. 'title' => $title,
  136. 'description' => $desc,
  137. 'time' => $time,
  138. 'url' => $url,
  139. 'ext' => $ext,
  140. 'size' => $size,
  141. 'duration' => $duration,
  142. 'author' => $author,
  143. );
  144. $episodes{$time} = \%tmp;
  145. } elsif ($DEBUG) {
  146. print STDERR 'Skipping incomplete entry: ' . $title . ': ' . $time . "\n";
  147. }
  148. }
  149. # Check for existing files
  150. opendir(my $fh, $OUT_DIR)
  151. or die('Unable to open output directory (' . $! . '): ' . $OUT_DIR . "\n");
  152. while (my $file = readdir($fh)) {
  153. my $path = $OUT_DIR . '/' . $file;
  154. if (-d $path) {
  155. next;
  156. }
  157. if ($file =~ /^(.*)\s+\((\d{7,})\)\.\w{3}$/) {
  158. my $title = $1;
  159. my $time = $2;
  160. if (exists($episodes{$time})) {
  161. if (exists($episodes{$time}->{'size'}) && $episodes{$time}->{'size'}) {
  162. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($path);
  163. my $ratio = ($size / $episodes{$time}->{'size'});
  164. if ($ratio < (1 - $ERR_RATIO) || $ratio > (1 + $ERR_RATIO)) {
  165. print STDERR 'Invalid output file size (' . $size . '/' . $episodes{$time}->{'size'} . '): ' . $file . "\n";
  166. }
  167. }
  168. $have{$time} = 1;
  169. $episodes{$time}->{'title'} = $title;
  170. }
  171. if ($DEBUG) {
  172. print STDERR 'Found file: ' . $file . "\n";
  173. }
  174. } elsif ($DEBUG > 1) {
  175. print STDERR 'Skipping file: ' . $file . "\n";
  176. }
  177. }
  178. closedir($fh);
  179. # Decide what we want to download
  180. foreach my $time (keys(%episodes)) {
  181. if (!exists($have{$time})) {
  182. push(@need, $time);
  183. if ($DEBUG > 1) {
  184. print STDERR 'Will fetch: ' . $time . "\n";
  185. }
  186. }
  187. }
  188. # Apply naming rules
  189. if (-e $RULE_FILE) {
  190. if ($DEBUG > 1) {
  191. print STDERR 'Importing local rules from: ' . $RULE_FILE . "\n";
  192. }
  193. require $RULE_FILE;
  194. localRules(\%episodes);
  195. } else {
  196. foreach my $time (sort(keys(%episodes))) {
  197. $episodes{$time}->{'title'} = time2str('%Y-%m-%d', $time) . ' - 1 - ' . $episodes{$time}->{'title'};
  198. }
  199. }
  200. foreach my $time (keys(%episodes)) {
  201. $episodes{$time}->{'title'} =~ s/\s*\:\s*/ - /g;
  202. $episodes{$time}->{'title'} =~ s/\s+/ /g;
  203. $episodes{$time}->{'title'} =~ s/\"/\'/g;
  204. $episodes{$time}->{'title'} =~ s/[^\w\s\,\-\.\!\'\(\)\#\&\@]//g;
  205. }
  206. # Fetch needed files, with basic validation
  207. my $dlCount = 0;
  208. foreach my $time (sort(@need)) {
  209. if ($dlCount >= $DL_LIMIT) {
  210. die('Download limit (' . $DL_LIMIT . ') reached: ' . $SERIES . "\n");
  211. }
  212. # Build a file path
  213. my $ep = $episodes{$time};
  214. my $file = $OUT_DIR . '/' . $ep->{'title'} . ' (' . int($time) . ').' . $ep->{'ext'};
  215. if (-e $file) {
  216. die('Unexpected output file: ' . $file . "\n");
  217. }
  218. # Debug
  219. if ($DEBUG) {
  220. print STDERR 'Fetching (' . $time . '): ' . $ep->{'title'} . ' => ' . $ep->{'url'} . "\n";
  221. }
  222. # Fetch
  223. my $code = getstore($ep->{'url'}, $file);
  224. $dlCount++;
  225. # Validate
  226. my $err = undef();
  227. if ($code != 200) {
  228. $err = 'Invalid HTTP response: ' . $code;
  229. goto OUT;
  230. }
  231. if (!-e $file) {
  232. $err = 'No output file: ' . $file;
  233. goto OUT;
  234. }
  235. if ($ep->{'size'}) {
  236. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($file);
  237. my $ratio = $size / $ep->{'size'};
  238. if ($ratio < (1 - $ERR_RATIO) || $ratio > (1 + $ERR_RATIO)) {
  239. $err = 'Invalid download size (' . $size . '/' . $ep->{'size'} . '): ' . $file;
  240. goto OUT;
  241. }
  242. }
  243. # Set MP3/M4A tags
  244. if ($ep->{'ext'} eq 'mp3') {
  245. # Parse the MP3
  246. my $mp3 = MP3::Tag->new($file);
  247. if (!$mp3) {
  248. $err = 'Unable to parse MP3 tags in: ' . $file . "\n";
  249. goto OUT;
  250. }
  251. # Delete any ID3v1 tags
  252. if (exists($mp3->{'ID3v1'})) {
  253. print STDERR "Removing ID3v1 tag\n";
  254. $mp3->{'ID3v1'}->remove_tag();
  255. print STDERR "Removed?\n";
  256. }
  257. # Find or create the ID3v2 tag
  258. my $tags = undef();
  259. if (exists($mp3->{'ID3v2'})) {
  260. $tags = $mp3->{'ID3v2'};
  261. } else {
  262. $tags = $mp3->new_tag('ID3v2');
  263. }
  264. # Update tags
  265. $tags->title($ep->{'title'});
  266. $tags->year(time2str('%Y', $ep->{'time'}));
  267. $tags->comment($ep->{'description'});
  268. $tags->album($SERIES);
  269. $tags->artist($SERIES);
  270. $tags->genre($GENRE);
  271. # Save
  272. if (!$tags->write_tag()) {
  273. $err = 'Unable to update MP3 tags in: ' . $file . "\n";
  274. goto OUT;
  275. }
  276. $mp3->close();
  277. } else {
  278. print STDERR 'Tag munging not available for ' . $ep->{'ext'} . ' files: ' . $file . "\n";
  279. }
  280. OUT:
  281. # Cleanup
  282. if (defined($err)) {
  283. print STDERR 'Unable to download ' . $ep->{'url'} . ': ' . $err . "\n";
  284. if (-e $file) {
  285. unlink($file);
  286. }
  287. }
  288. }