subscribe.pl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use FindBin;
  5. use lib "$FindBin::Bin/";
  6. use File::Basename;
  7. use Date::Parse;
  8. use Date::Format;
  9. use LWP::Simple;
  10. use URI::Escape;
  11. use JSON;
  12. use XML::LibXML;
  13. use IPC::System::Simple qw( system );
  14. use WWW::YouTube::Download;
  15. use PrettyPrint;
  16. # Paramters
  17. my $CURL_BIN = 'curl';
  18. my @CURL_ARGS = ('-4', '--insecure', '-C', '-');
  19. my $BATCH_SIZE = 50;
  20. my $MAX_INDEX = 500;
  21. my $URL_PREFIX = 'http://gdata.youtube.com/feeds/api/users/';
  22. my $URL_SUFFIX = '/uploads';
  23. my %CHAN_PARAMS = (
  24. 'strict' => 1,
  25. 'v' => 2,
  26. 'alt' => 'json',
  27. );
  28. my %LIST_PARAMS = (
  29. 'strict' => 1,
  30. 'v' => 2,
  31. 'alt' => 'jsonc',
  32. );
  33. # Prototypes
  34. sub findVideos($);
  35. sub findFiles($);
  36. sub ytURL($);
  37. sub buildNFO($);
  38. sub buildSeriesNFO($);
  39. sub getChannel($);
  40. sub fetchParse($);
  41. sub buildURL($$);
  42. sub saveString($$);
  43. # Sanity check
  44. if (scalar(@ARGV) < 1) {
  45. die('Usage: ' . basename($0) . " output_directory\n");
  46. }
  47. # Command-line parameters
  48. my ($dir) = @ARGV;
  49. $dir =~ s/\/+$//;
  50. if (!-d $dir) {
  51. die('Invalid output directory: ' . $dir . "\n");
  52. }
  53. my $user = basename($dir);
  54. if (length($user) < 1 || !($user =~ /^\w+$/)) {
  55. die('Invalid user: ' . $user . "\n");
  56. }
  57. # Environmental parameters
  58. my $DEBUG = 0;
  59. if ($ENV{'DEBUG'}) {
  60. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  61. $DEBUG = $1;
  62. } else {
  63. $DEBUG = 1;
  64. }
  65. }
  66. my $NO_FETCH = 0;
  67. if ($ENV{'NO_FETCH'}) {
  68. $NO_FETCH = 1;
  69. }
  70. my $RENAME = 0;
  71. if ($ENV{'RENAME'}) {
  72. $RENAME = 1;
  73. }
  74. if ($ENV{'MAX_INDEX'} && $ENV{'MAX_INDEX'} =~ /(\d+)/) {
  75. $MAX_INDEX = $1;
  76. }
  77. if ($ENV{'BATCH_SIZE'} && $ENV{'BATCH_SIZE'} =~ /(\d+)/) {
  78. $BATCH_SIZE = $1;
  79. }
  80. # Construct globals
  81. $LIST_PARAMS{'max-results'} = $BATCH_SIZE;
  82. if (!$DEBUG) {
  83. push(@CURL_ARGS, '--silent');
  84. }
  85. # Grab the channel data
  86. my $channel = getChannel($user);
  87. # Create the channel NFO and poster, if needed
  88. my $nfo = $dir . '/tvshow.nfo';
  89. if (!-e $nfo) {
  90. if ($DEBUG) {
  91. print STDERR 'Saving series data for: ' . $channel->{'title'} . "\n";
  92. }
  93. # Save the poster
  94. if (exists($channel->{'thumbnail'}) && length($channel->{'thumbnail'}) > 5) {
  95. my $poster = $dir . '/poster.jpg';
  96. my $jpg = get($channel->{'thumbnail'});
  97. saveString($poster, $jpg);
  98. }
  99. # Save the series NFO
  100. my $xml = buildSeriesNFO($channel);
  101. if ($DEBUG > 1) {
  102. print STDERR 'Saving NFO: ' . $xml . "\n";
  103. }
  104. saveString($nfo, $xml);
  105. }
  106. # Find all the user's videos on YT
  107. my $videos = findVideos($user);
  108. # Find all existing YT files on disk
  109. my $files = findFiles($dir);
  110. # Fill in missing videos and NFOs
  111. foreach my $id (keys(%{$videos})) {
  112. my $basePath = $dir . '/S01E' . sprintf('%02d', $videos->{$id}->{'number'}) . ' - ' . $id . '.';
  113. $nfo = $basePath . 'nfo';
  114. # Warn (and optionally rename) if the episode numbers drift
  115. if (exists($files->{$id}) && $files->{$id}->{'number'} != $videos->{$id}->{'number'}) {
  116. warn('Video ' . $id . ' had episode number ' . $files->{$id}->{'number'} . ' but now has episode number ' . $videos->{$id}->{'number'} . "\n");
  117. if ($RENAME) {
  118. print STDERR 'Renaming ' . $files->{$id}->{'path'} . ' => ' . $basePath . $files->{$id}->{'suffix'} . "\n";
  119. rename($files->{$id}->{'path'}, $basePath . $files->{$id}->{'suffix'});
  120. unlink($files->{$id}->{'nfo'});
  121. delete($files->{$id});
  122. }
  123. }
  124. # If we haven't heard of the file, or don't have an NFO for it
  125. # Checking for the NFO allows use to resume failed downloads
  126. if (!exists($files->{$id}) || !-e $nfo) {
  127. if ($DEBUG) {
  128. print STDERR 'Fetching video: ' . $id . "\n";
  129. }
  130. # Find the download URL and file suffix
  131. my ($url, $suffix) = ytURL($id);
  132. if (!defined($url) || length($url) < 5) {
  133. warn('Could not determine URL for video: ' . $id . "\n");
  134. $url = undef();
  135. }
  136. # Fetch with cURL
  137. # I know LWP exists (and is even loaded) but cURL makes my life easier
  138. if ($url) {
  139. my @cmd = ($CURL_BIN);
  140. push(@cmd, @CURL_ARGS);
  141. push(@cmd, '-o', $basePath . $suffix, $url);
  142. if ($NO_FETCH) {
  143. print STDERR 'Not fetching: ' . join(' ', @cmd) . "\n";
  144. } else {
  145. if ($DEBUG > 1) {
  146. print STDERR join(' ', @cmd) . "\n";
  147. }
  148. system(@cmd);
  149. }
  150. }
  151. # Build and save the XML document
  152. my $xml = buildNFO($videos->{$id});
  153. if ($DEBUG > 1) {
  154. print STDERR 'Saving NFO: ' . $xml . "\n";
  155. }
  156. saveString($nfo, $xml);
  157. }
  158. }
  159. sub saveString($$) {
  160. my ($path, $str) = @_;
  161. my $fh = undef();
  162. if (!open($fh, '>', $path)) {
  163. warn('Cannot open file for writing: ' . $! . "\n");
  164. return undef();
  165. }
  166. print $fh $str;
  167. close($fh);
  168. return 1;
  169. }
  170. sub buildSeriesNFO($) {
  171. my ($channel) = @_;
  172. # Create an XML tree
  173. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  174. $doc->setStandalone(1);
  175. my $show = $doc->createElement('tvshow');
  176. $doc->setDocumentElement($show);
  177. my $elm;
  178. # Add data
  179. $elm = $doc->createElement('title');
  180. $elm->appendText($channel->{'title'});
  181. $show->appendChild($elm);
  182. $elm = $doc->createElement('premiered');
  183. $elm->appendText(time2str('%Y-%m-%d', $channel->{'date'}));
  184. $show->appendChild($elm);
  185. $elm = $doc->createElement('plot');
  186. $elm->appendText($channel->{'description'});
  187. $show->appendChild($elm);
  188. # Return the string
  189. return $doc->toString();
  190. }
  191. sub buildNFO($) {
  192. my ($video) = @_;
  193. # Create an XML tree
  194. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  195. $doc->setStandalone(1);
  196. my $show = $doc->createElement('episodedetails');
  197. $doc->setDocumentElement($show);
  198. my $elm;
  199. # Add data
  200. $elm = $doc->createElement('season');
  201. $elm->appendText('1');
  202. $show->appendChild($elm);
  203. $elm = $doc->createElement('episode');
  204. $elm->appendText($video->{'number'});
  205. $show->appendChild($elm);
  206. $elm = $doc->createElement('title');
  207. $elm->appendText($video->{'title'});
  208. $show->appendChild($elm);
  209. $elm = $doc->createElement('aired');
  210. $elm->appendText(time2str('%Y-%m-%d', $video->{'date'}));
  211. $show->appendChild($elm);
  212. $elm = $doc->createElement('plot');
  213. $elm->appendText($video->{'description'});
  214. $show->appendChild($elm);
  215. $elm = $doc->createElement('runtime');
  216. $elm->appendText($video->{'duration'});
  217. $show->appendChild($elm);
  218. $elm = $doc->createElement('rating');
  219. $elm->appendText($video->{'rating'});
  220. $show->appendChild($elm);
  221. $elm = $doc->createElement('director');
  222. $elm->appendText($video->{'creator'});
  223. $show->appendChild($elm);
  224. # Return the string
  225. return $doc->toString();
  226. }
  227. sub ytURL($) {
  228. my ($id) = @_;
  229. # Init the YT object
  230. my $tube = WWW::YouTube::Download->new;
  231. # Fetch metadata
  232. my $meta = eval { $tube->prepare_download($id); };
  233. if (!defined($meta) || ref($meta) ne 'HASH' || !exists($meta->{'video_url_map'}) || ref($meta->{'video_url_map'}) ne 'HASH') {
  234. return undef();
  235. }
  236. # Find the best stream (i.e. highest resolution, prefer mp4)
  237. my $bestStream = undef();
  238. my $bestResolution = 0;
  239. foreach my $streamID (keys(%{ $meta->{'video_url_map'} })) {
  240. my $stream = $meta->{'video_url_map'}->{$streamID};
  241. my ($res) = $stream->{'resolution'} =~ /^\s*(\d+)/;
  242. if ($DEBUG > 1) {
  243. print STDERR $streamID . ' (' . $stream->{'suffix'} . ')' . ' => ' . $stream->{'resolution'} . ' : ' . $stream->{'url'} . "\n";
  244. }
  245. if ( ($res > $bestResolution)
  246. || ($res == $bestResolution && defined($bestStream) && $bestStream->{'suffix'} ne 'mp4'))
  247. {
  248. $bestStream = $stream;
  249. $bestResolution = $res;
  250. }
  251. }
  252. if (!exists($bestStream->{'suffix'}) || length($bestStream->{'suffix'}) < 2) {
  253. $bestStream->{'suffix'} = 'mp4';
  254. }
  255. return ($bestStream->{'url'}, $bestStream->{'suffix'});
  256. }
  257. sub findFiles($) {
  258. my ($dir) = @_;
  259. my %files = ();
  260. # Read the output directory
  261. my $fh = undef();
  262. opendir($fh, $dir)
  263. or die('Unable to open output directory: ' . $! . "\n");
  264. while (my $file = readdir($fh)) {
  265. my ($num, $id, $suffix) = $file =~ /S\d+E(\d+) - ([\w\-]+)\.(\w\w\w)$/i;
  266. if (defined($id) && length($id) > 0) {
  267. if ($suffix eq 'nfo') {
  268. next;
  269. }
  270. my %tmp = (
  271. 'number' => $num,
  272. 'suffix' => $suffix,
  273. 'path' => $dir . '/' . $file,
  274. );
  275. $tmp{'nfo'} = $tmp{'path'};
  276. $tmp{'nfo'} =~ s/\.\w\w\w$/\.nfo/;
  277. if (exists($files{$id})) {
  278. warn('Duplicate ID: ' . $id . "\n\t" . $files{$id}->{'path'} . "\n\t" . $tmp{'path'} . "\n");
  279. if ($RENAME) {
  280. print STDERR 'Deleting duplicate: ' . $files{$id}->{'path'} . "\n";
  281. unlink($files{$id}->{'path'});
  282. unlink($files{$id}->{'nfo'});
  283. delete($files{$id});
  284. }
  285. }
  286. $files{$id} = \%tmp;
  287. }
  288. }
  289. close($fh);
  290. if ($DEBUG) {
  291. print STDERR "\nFound " . scalar(keys(%files)) . " files:\n\t" . join("\n\t", keys(%files)) . "\n";
  292. if ($DEBUG > 1) {
  293. print STDERR prettyPrint(\%files, "\t") . "\n";
  294. }
  295. }
  296. return \%files;
  297. }
  298. sub buildURL($$) {
  299. my ($base, $params) = @_;
  300. my $url = $base . '?';
  301. foreach my $name (keys(%{$params})) {
  302. $url .= '&' . uri_escape($name) . '=' . uri_escape($params->{$name});
  303. }
  304. return $url;
  305. }
  306. sub fetchParse($) {
  307. my ($url) = @_;
  308. # Fetch
  309. if ($DEBUG) {
  310. print STDERR 'Fetching list URL: ' . $url . "\n";
  311. }
  312. my $content = get($url);
  313. if (!defined($content) || length($content) < 10) {
  314. die('Invalid content from URL: ' . $url . "\n");
  315. }
  316. # Parse
  317. my $data = decode_json($content);
  318. if (!defined($data) || ref($data) ne 'HASH') {
  319. die('Invalid JSON: ' . $content . "\n");
  320. }
  321. if ($DEBUG > 2) {
  322. print STDERR "Raw JSON data:\n" . prettyPrint($data, ' ') . "\n";
  323. }
  324. return $data;
  325. }
  326. sub getChannel($) {
  327. my ($user) = @_;
  328. # Build, fetch, parse
  329. my $url = buildURL($URL_PREFIX . $user, \%CHAN_PARAMS);
  330. my $data = fetchParse($url);
  331. if (!exists($data->{'entry'}) || ref($data->{'entry'}) ne 'HASH') {
  332. die("Invalid channel data\n");
  333. }
  334. $data = $data->{'entry'};
  335. # Extract the data we want
  336. my %channel = (
  337. 'id' => $data->{'yt$channelId'}->{'$t'},
  338. 'title' => $data->{'title'}->{'$t'},
  339. 'date' => str2time($data->{'published'}->{'$t'}),
  340. 'description' => $data->{'summary'}->{'$t'},
  341. 'thumbnail' => $data->{'media$thumbnail'}->{'url'},
  342. );
  343. return \%channel;
  344. }
  345. sub findVideos($) {
  346. my ($user) = @_;
  347. my %videos = ();
  348. # Prepare the static URL elements
  349. my $baseURL = $URL_PREFIX . $user . $URL_SUFFIX;
  350. my %params = %LIST_PARAMS;
  351. # Loop through until we have all the entries
  352. my $index = 1;
  353. my $itemCount = undef();
  354. LOOP:
  355. {
  356. # Build, fetch, parse
  357. $params{'start-index'} = $index;
  358. my $url = buildURL($baseURL, \%params);
  359. my $data = fetchParse($url);
  360. # Grab the total count, so we know when to stop
  361. if (!exists($data->{'data'})) {
  362. die("Invalid video list\n");
  363. }
  364. $data = $data->{'data'};
  365. if (!defined($itemCount) && exists($data->{'totalItems'})) {
  366. $itemCount = $data->{'totalItems'};
  367. }
  368. # Process each item
  369. if (!exists($data->{'items'}) || ref($data->{'items'}) ne 'ARRAY') {
  370. die("Invalid video list\n");
  371. }
  372. my $items = $data->{'items'};
  373. my $offset = 0;
  374. foreach my $item (@{$items}) {
  375. my %tmp = (
  376. 'number' => ($itemCount - $index - $offset + 1),
  377. 'title' => $item->{'title'},
  378. 'date' => str2time($item->{'uploaded'}),
  379. 'description' => $item->{'description'},
  380. 'duration' => $item->{'duration'},
  381. 'rating' => $item->{'rating'},
  382. 'creator' => $item->{'uploader'},
  383. );
  384. $videos{ $item->{'id'} } = \%tmp;
  385. $offset++;
  386. }
  387. # Loop if there are results left to fetch
  388. $index += $BATCH_SIZE;
  389. if (defined($itemCount) && $itemCount > $index) {
  390. # But don't go past the max supported index
  391. if ($index <= $MAX_INDEX) {
  392. redo LOOP;
  393. }
  394. }
  395. }
  396. if ($DEBUG) {
  397. print STDERR "\nFound " . scalar(keys(%videos)) . ' videos for YouTube user ' . $user . ":\n\t" . join("\n\t", keys(%videos)) . "\n";
  398. if ($DEBUG > 1) {
  399. print STDERR prettyPrint(\%videos, "\t") . "\n";
  400. }
  401. }
  402. return \%videos;
  403. }