rss.pl 9.5 KB

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