rss.pl 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. warn('Skipping video file: ' . time2str('%Y-%m-%d', $time) . "\n");
  106. }
  107. } else {
  108. if ($DEBUG) {
  109. warn('Unknown MIME type: ' . $enc->{'type'} . "\n");
  110. }
  111. }
  112. }
  113. if (exists($enc->{'length'})) {
  114. $size = $enc->{'length'};
  115. }
  116. }
  117. }
  118. # iTunes data, if available (and useful)
  119. my $duration = undef();
  120. if ($ep->{'http://www.itunes.com/dtds/podcast-1.0.dtd'}) {
  121. my $itunes = $ep->{'http://www.itunes.com/dtds/podcast-1.0.dtd'};
  122. if (exists($itunes->{'duration'})) {
  123. if ($itunes->{'duration'} =~ /(\d+)\:(\d\d)\:(\d\d)/) {
  124. $duration = (3600 * int($1)) + (60 * int($2)) + int($3);
  125. } elsif ($itunes->{'duration'} =~ /(\d+)\:(\d\d)/) {
  126. $duration = (60 * int($1)) + int($2);
  127. } elsif ($itunes->{'duration'} =~ /(\d+)/) {
  128. $duration = int($1);
  129. } elsif ($DEBUG) {
  130. print STDERR 'Unknown duration format: ' . $itunes->{'duration'} . "\n";
  131. }
  132. }
  133. if (!$desc && exists($itunes->{'summary'})) {
  134. $desc = $itunes->{'summary'};
  135. $desc =~ s/^\s+//;
  136. $desc =~ s/\s+$//;
  137. }
  138. if (!$author && exists($itunes->{'author'})) {
  139. $author = $itunes->{'author'};
  140. $author =~ s/^\s+//;
  141. $author =~ s/\s+$//;
  142. }
  143. }
  144. # Collect extracted, cleaned data
  145. if ($title && $time && $url && $ext && $desc) {
  146. my %tmp = (
  147. 'title' => $title,
  148. 'time' => $time,
  149. 'url' => $url,
  150. 'ext' => $ext,
  151. 'description' => $desc,
  152. 'size' => $size,
  153. 'duration' => $duration,
  154. 'author' => $author,
  155. );
  156. $episodes{$time} = \%tmp;
  157. } elsif ($DEBUG) {
  158. print STDERR "Skipping incomplete entry:\n";
  159. print STDERR "\tTitle: ";
  160. if ($title) {
  161. print STDERR $title . "\n";
  162. } else {
  163. print STDERR "<missing>\n";
  164. }
  165. print STDERR "\tTime: ";
  166. if ($time) {
  167. print STDERR time2str('%Y-%m-%d', $time) . "\n";
  168. } else {
  169. print STDERR "<missing>\n";
  170. }
  171. print STDERR "\tURL: ";
  172. if ($url) {
  173. print STDERR $url . "\n";
  174. } else {
  175. print STDERR "<missing>\n";
  176. }
  177. print STDERR "\tExtension: ";
  178. if ($ext) {
  179. print STDERR $ext . "\n";
  180. } else {
  181. print STDERR "<missing>\n";
  182. }
  183. print STDERR "\tDescription: ";
  184. if ($desc) {
  185. print STDERR substr($desc, 0, 20) . "\n";
  186. } else {
  187. print STDERR "<missing>\n";
  188. }
  189. }
  190. }
  191. # Check for existing files
  192. opendir(my $fh, $OUT_DIR)
  193. or die('Unable to open output directory (' . $! . '): ' . $OUT_DIR . "\n");
  194. while (my $file = readdir($fh)) {
  195. my $path = $OUT_DIR . '/' . $file;
  196. if (-d $path) {
  197. next;
  198. }
  199. if ($file =~ /^(.*)\s+\((\d{7,})\)\.\w{3}$/) {
  200. my $title = $1;
  201. my $time = $2;
  202. if (exists($episodes{$time})) {
  203. if (exists($episodes{$time}->{'size'}) && $episodes{$time}->{'size'}) {
  204. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($path);
  205. my $ratio = 1;
  206. if ($episodes{$time}->{'size'} =~ /^\d+$/) {
  207. $ratio = ($size / $episodes{$time}->{'size'});
  208. } elsif ($DEBUG) {
  209. warn('Invalid episode size: ' . $episodes{$time}->{'size'});
  210. }
  211. if ($ratio < (1 - $ERR_RATIO) && $DEBUG) {
  212. print STDERR 'Invalid output file size (' . $size . '/' . $episodes{$time}->{'size'} . '): ' . $file . "\n";
  213. }
  214. }
  215. $have{$time} = 1;
  216. $episodes{$time}->{'title'} = $title;
  217. }
  218. if ($DEBUG) {
  219. print STDERR 'Found file: ' . $file . "\n";
  220. }
  221. } elsif ($DEBUG > 1) {
  222. print STDERR 'Skipping file: ' . $file . "\n";
  223. }
  224. }
  225. closedir($fh);
  226. # Decide what we want to download
  227. foreach my $time (keys(%episodes)) {
  228. if (!exists($have{$time})) {
  229. push(@need, $time);
  230. if ($DEBUG > 1) {
  231. print STDERR 'Will fetch: ' . time2str('%Y-%m-%d', $time) . "\n";
  232. }
  233. }
  234. }
  235. if ($DEBUG) {
  236. print STDERR 'Need/Total: ' . scalar(@need) . '/' . scalar(keys(%episodes)) . "\n";
  237. }
  238. # Apply naming rules
  239. if (-e $RULE_FILE) {
  240. if ($DEBUG > 1) {
  241. print STDERR 'Importing local rules from: ' . $RULE_FILE . "\n";
  242. }
  243. require $RULE_FILE;
  244. localRules(\%episodes);
  245. } else {
  246. foreach my $time (sort(keys(%episodes))) {
  247. $episodes{$time}->{'title'} = time2str('%Y-%m-%d', $time) . ' - ' . $episodes{$time}->{'title'};
  248. }
  249. }
  250. foreach my $time (keys(%episodes)) {
  251. $episodes{$time}->{'title'} =~ s/\s*\:\s*/ - /g;
  252. $episodes{$time}->{'title'} =~ s/\s+/ /g;
  253. $episodes{$time}->{'title'} =~ s/\"/\'/g;
  254. $episodes{$time}->{'title'} =~ s/[^\w\s\,\-\.\!\'\(\)\#\&\@]//g;
  255. }
  256. # Fetch needed files, with basic validation
  257. my $dlCount = 0;
  258. foreach my $time (sort(@need)) {
  259. if ($dlCount >= $DL_LIMIT) {
  260. die('Download limit (' . $DL_LIMIT . ') reached: ' . $SERIES . "\n");
  261. }
  262. # Build a file path
  263. my $ep = $episodes{$time};
  264. my $file = $OUT_DIR . '/' . $ep->{'title'} . ' (' . int($time) . ').' . $ep->{'ext'};
  265. if (-e $file) {
  266. die('Unexpected output file: ' . $file . "\n");
  267. }
  268. # Debug
  269. if ($DEBUG) {
  270. print STDERR 'Fetching (' . time2str('%Y-%m-%d', $time) . '): ' . $ep->{'title'} . ' => ' . $ep->{'url'} . "\n";
  271. }
  272. # Fetch
  273. my $response = $ua->get($ep->{'url'});
  274. my $code = $response->code();
  275. $dlCount++;
  276. # Validate HTTP
  277. my $err = undef();
  278. if ($code != 200) {
  279. $err = 'Invalid HTTP response: ' . $code;
  280. goto OUT;
  281. }
  282. # Save
  283. {
  284. my $fh;
  285. if (!open($fh, '>', $file)) {
  286. $err = 'Unable to open output file: ' . $file;
  287. goto OUT;
  288. }
  289. print {$fh} $response->decoded_content();
  290. close($fh);
  291. }
  292. # Validate file
  293. if (!-e $file) {
  294. $err = 'No output file: ' . $file;
  295. goto OUT;
  296. }
  297. if ($ep->{'size'}) {
  298. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), my $size) = stat($file);
  299. my $ratio = $size / $ep->{'size'};
  300. if ($ratio < (1 - $ERR_RATIO)) {
  301. $err = 'Invalid download size (' . $size . '/' . $ep->{'size'} . '): ' . $file;
  302. goto OUT;
  303. }
  304. }
  305. # Set MP3/M4A tags
  306. if ($ep->{'ext'} eq 'mp3') {
  307. # Parse the MP3
  308. my $mp3 = MP3::Tag->new($file);
  309. if (!$mp3) {
  310. $err = 'Unable to parse MP3 tags in: ' . $file . "\n";
  311. goto OUT;
  312. }
  313. # Delete any ID3v1 tags
  314. if (exists($mp3->{'ID3v1'})) {
  315. print STDERR "Removing ID3v1 tag\n";
  316. $mp3->{'ID3v1'}->remove_tag();
  317. print STDERR "Removed?\n";
  318. }
  319. # Find or create the ID3v2 tag
  320. my $tags = undef();
  321. if (exists($mp3->{'ID3v2'})) {
  322. $tags = $mp3->{'ID3v2'};
  323. } else {
  324. $tags = $mp3->new_tag('ID3v2');
  325. }
  326. # Update tags
  327. $tags->title($ep->{'title'});
  328. $tags->year(time2str('%Y', $ep->{'time'}));
  329. $tags->comment($ep->{'description'});
  330. $tags->track(1);
  331. $tags->album($SERIES);
  332. $tags->artist($SERIES);
  333. $tags->genre($GENRE);
  334. # Save
  335. if (!$tags->write_tag()) {
  336. $err = 'Unable to update MP3 tags in: ' . $file . "\n";
  337. goto OUT;
  338. }
  339. $mp3->close();
  340. } elsif ($ep->{'ext'} eq 'm4a') {
  341. # Parse the MP3=4
  342. my $m4a = Audio::M4P::QuickTime->new(file => $file);
  343. if (!$m4a) {
  344. $err = 'Unable to parse MP4 tags in: ' . $file . "\n";
  345. goto OUT;
  346. }
  347. # Update tags
  348. $m4a->title($ep->{'title'});
  349. $m4a->year(time2str('%Y', $ep->{'time'}));
  350. $m4a->comment($ep->{'description'});
  351. $m4a->track(1);
  352. $m4a->album($SERIES);
  353. $m4a->artist($SERIES);
  354. $m4a->genre_as_text($GENRE);
  355. # Save
  356. if (!$m4a->WriteFile($file)) {
  357. $err = 'Unable to update M4A tags in: ' . $file . "\n";
  358. goto OUT;
  359. }
  360. } else {
  361. print STDERR 'Tag munging not available for ' . $ep->{'ext'} . ' files: ' . $file . "\n";
  362. }
  363. OUT:
  364. # Cleanup
  365. if (defined($err)) {
  366. if ($DEBUG || !($err =~ /\b40[34]$/)) {
  367. print STDERR 'Unable to download ' . $ep->{'url'} . ': ' . $err . "\n";
  368. }
  369. if (-e $file) {
  370. unlink($file);
  371. }
  372. }
  373. }