rss.pl 11 KB

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