ytSubscribe.pl 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use File::Basename;
  5. use Date::Parse;
  6. use Date::Format;
  7. use LWP::Simple;
  8. use URI::Escape;
  9. use JSON;
  10. use XML::LibXML;
  11. use IPC::System::Simple qw( system );
  12. use WWW::YouTube::Download;
  13. # Paramters
  14. my $CURL_BIN = 'curl';
  15. my @CURL_ARGS = ('-4', '--insecure', '-C', '-');
  16. my $BATCH_SIZE = 50;
  17. my $MAX_INDEX = 500;
  18. my $URL_PREFIX = 'http://gdata.youtube.com/feeds/api/users/';
  19. my $URL_SUFFIX = '/uploads';
  20. my %API_PARAMS = (
  21. 'strict' => 1,
  22. 'v' => 2,
  23. 'alt' => 'jsonc',
  24. 'orderby' => 'published',
  25. );
  26. # Prototypes
  27. sub findVideos($);
  28. sub findFiles($);
  29. sub ytURL($);
  30. sub buildNFO($);
  31. # Sanity check
  32. if (scalar(@ARGV) < 1) {
  33. die('Usage: ' . basename($0) . " output_directory\n");
  34. }
  35. # Command-line parameters
  36. my ($dir) = @ARGV;
  37. $dir =~ s/\/+$//;
  38. if (!-d $dir) {
  39. die('Invalid output directory: ' . $dir . "\n");
  40. }
  41. my $user = basename($dir);
  42. if (length($user) < 1 || !($user =~ /^\w+$/)) {
  43. die('Invalid user: ' . $user . "\n");
  44. }
  45. # Environmental parameters
  46. my $DEBUG = 0;
  47. if ($ENV{'DEBUG'}) {
  48. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  49. $DEBUG = $1;
  50. } else {
  51. $DEBUG = 1;
  52. }
  53. }
  54. my $NO_FETCH = 0;
  55. if ($ENV{'NO_FETCH'}) {
  56. $NO_FETCH = 1;
  57. }
  58. if ($ENV{'MAX_INDEX'} && $ENV{'MAX_INDEX'} =~ /(\d+)/) {
  59. $MAX_INDEX = $1;
  60. }
  61. if ($ENV{'BATCH_SIZE'} && $ENV{'BATCH_SIZE'} =~ /(\d+)/) {
  62. $BATCH_SIZE = $1;
  63. }
  64. # Construct globals
  65. $API_PARAMS{'max-results'} = $BATCH_SIZE;
  66. if (!$DEBUG) {
  67. push(@CURL_ARGS, '--silent');
  68. }
  69. # Find all the user's videos on YT
  70. my $videos = findVideos($user);
  71. # Find all existing YT files on disk
  72. my $files = findFiles($dir);
  73. # Fill in missing videos and NFOs
  74. foreach my $id (keys(%{$videos})) {
  75. my $basePath;
  76. {
  77. my $safeTitle = $videos->{$id}->{'title'};
  78. $safeTitle =~ s/\:/ - /g;
  79. $safeTitle =~ s/\s+/ /g;
  80. $safeTitle =~ s/[^\w\-\.\?\!\&\,\; ]/_/g;
  81. $basePath = $dir . '/' . sprintf('%02d', $videos->{$id}->{'number'}) . ' - ' . $safeTitle . ' (' . $id . ').';
  82. }
  83. my $nfo = $basePath . 'nfo';
  84. # If we haven't heard of the file, or don't have an NFO for it
  85. # Checking for the NFO allows use to resume failed downloads
  86. if (!exists($files->{$id}) || !-e $nfo) {
  87. if ($DEBUG) {
  88. print STDERR 'Fetching video: ' . $id . "\n";
  89. }
  90. # Find the download URL and file suffix
  91. my ($url, $suffix) = ytURL($id);
  92. if (!defined($url) || length($url) < 5) {
  93. warn('Could not determine URL for video: ' . $id . "\n");
  94. next;
  95. }
  96. # Fetch with cURL
  97. # I know LWP exists (and is even loaded) but cURL makes my life easier
  98. {
  99. my @cmd = ($CURL_BIN);
  100. push(@cmd, @CURL_ARGS);
  101. push(@cmd, '-o', $basePath . $suffix, $url);
  102. if ($NO_FETCH) {
  103. print STDERR 'Not fetching: ' . join(' ', @cmd) . "\n";
  104. } else {
  105. if ($DEBUG > 1) {
  106. print STDERR join(' ', @cmd) . "\n";
  107. }
  108. system(@cmd);
  109. }
  110. }
  111. # Build the XML document
  112. my $xml = buildNFO($videos->{$id});
  113. if ($DEBUG > 1) {
  114. print STDERR 'Saving NFO: ' . $xml . "\n";
  115. }
  116. # Save to disk
  117. my $fh = undef();
  118. if (!open($fh, '>', $nfo)) {
  119. warn('Cannot open NFO: ' . $! . "\n");
  120. next;
  121. }
  122. print $fh $xml;
  123. close($fh);
  124. }
  125. }
  126. sub buildNFO($) {
  127. my ($video) = @_;
  128. # Create an XML tree
  129. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  130. $doc->setStandalone(1);
  131. my $show = $doc->createElement('episodedetails');
  132. $doc->setDocumentElement($show);
  133. my $elm;
  134. # Generic elements (in case we get excited later)
  135. my $fileinfo = $doc->createElement('fileinfo');
  136. $show->appendChild($fileinfo);
  137. my $streamdetails = $doc->createElement('streamdetails');
  138. $fileinfo->appendChild($streamdetails);
  139. $elm = $doc->createElement('video');
  140. $streamdetails->appendChild($elm);
  141. $elm = $doc->createElement('playcount');
  142. $show->appendChild($elm);
  143. $elm = $doc->createElement('credits');
  144. $show->appendChild($elm);
  145. my $actor = $doc->createElement('actor');
  146. $show->appendChild($actor);
  147. $elm = $doc->createElement('name');
  148. $actor->appendChild($elm);
  149. $elm = $doc->createElement('role');
  150. $actor->appendChild($elm);
  151. # Static elements (per the nature of this process)
  152. $elm = $doc->createElement('season');
  153. $elm->appendText('1');
  154. $show->appendChild($elm);
  155. # Dynamic data
  156. $elm = $doc->createElement('episode');
  157. $elm->appendText($video->{'number'});
  158. $show->appendChild($elm);
  159. $elm = $doc->createElement('title');
  160. $elm->appendText($video->{'title'});
  161. $show->appendChild($elm);
  162. $elm = $doc->createElement('aired');
  163. $elm->appendText(time2str('%Y-%m-%d', $video->{'date'}));
  164. $show->appendChild($elm);
  165. $elm = $doc->createElement('plot');
  166. $elm->appendText($video->{'description'});
  167. $show->appendChild($elm);
  168. $elm = $doc->createElement('runtime');
  169. $elm->appendText($video->{'duration'});
  170. $show->appendChild($elm);
  171. $elm = $doc->createElement('rating');
  172. $elm->appendText($video->{'rating'});
  173. $show->appendChild($elm);
  174. $elm = $doc->createElement('director');
  175. $elm->appendText($video->{'creator'});
  176. $show->appendChild($elm);
  177. # Return the string
  178. return $doc->toString();
  179. }
  180. sub ytURL($) {
  181. my ($id) = @_;
  182. # Init the YT object
  183. my $tube = WWW::YouTube::Download->new;
  184. # Fetch metadata
  185. my $meta = $tube->prepare_download($id);
  186. if (!defined($meta) || ref($meta) ne 'HASH' || !exists($meta->{'video_url_map'}) || ref($meta->{'video_url_map'}) ne 'HASH') {
  187. return undef();
  188. }
  189. # Find the best stream (i.e. highest resolution, prefer mp4)
  190. my $bestStream = undef();
  191. my $bestResolution = 0;
  192. foreach my $streamID (keys(%{ $meta->{'video_url_map'} })) {
  193. my $stream = $meta->{'video_url_map'}->{$streamID};
  194. my ($res) = $stream->{'resolution'} =~ /^\s*(\d+)/;
  195. if ($DEBUG > 1) {
  196. print STDERR $streamID . ' (' . $stream->{'suffix'} . ')' . ' => ' . $stream->{'resolution'} . ' : ' . $stream->{'url'} . "\n\n";
  197. }
  198. if ( ($res > $bestResolution)
  199. || ($res == $bestResolution && defined($bestStream) && $bestStream->{'suffix'} ne 'mp4'))
  200. {
  201. $bestStream = $stream;
  202. $bestResolution = $res;
  203. }
  204. }
  205. if (!exists($bestStream->{'suffix'}) || length($bestStream->{'suffix'}) < 2) {
  206. $bestStream->{'suffix'} = 'mp4';
  207. }
  208. return ($bestStream->{'url'}, $bestStream->{'suffix'});
  209. }
  210. sub findFiles($) {
  211. my ($dir) = @_;
  212. my %files = ();
  213. # Read the output directory
  214. my $fh = undef();
  215. opendir($fh, $dir)
  216. or die('Unable to open output directory: ' . $! . "\n");
  217. while (my $file = readdir($fh)) {
  218. my ($num, $title, $id, $suffix) = $file =~ /(\d+) - (.+) \(([\w\-]+)\)\.(\w\w\w)$/;
  219. if (defined($id) && length($id) > 0) {
  220. if ($suffix eq 'nfo') {
  221. next;
  222. }
  223. my %tmp = (
  224. 'number' => $num,
  225. 'title' => $title,
  226. 'suffix' => $suffix,
  227. 'path' => $dir . '/' . $file,
  228. );
  229. $tmp{'nfo'} = $tmp{'path'};
  230. $tmp{'nfo'} =~ s/\.\w\w\w$/\.nfo/;
  231. $files{$id} = \%tmp;
  232. }
  233. }
  234. close($fh);
  235. if ($DEBUG) {
  236. print STDERR "\n\nFound " . scalar(keys(%files)) . " files:\n\t" . join("\n\t", keys(%files)) . "\n\n";
  237. if ($DEBUG > 1) {
  238. use PrettyPrint;
  239. print STDERR prettyPrint(\%files, "\t") . "\n";
  240. }
  241. }
  242. return \%files;
  243. }
  244. sub findVideos($) {
  245. my ($user) = @_;
  246. my %videos = ();
  247. # Build the base URL
  248. my $baseURL = $URL_PREFIX . $user . $URL_SUFFIX;
  249. # And the static URL parameters
  250. my %params = %API_PARAMS;
  251. # Loop through until we have all the entries
  252. my $index = 1;
  253. my $itemCount = undef();
  254. LOOP:
  255. {
  256. # Build the actual URL
  257. my $url = $baseURL . '?start-index=' . $index;
  258. foreach my $name (keys(%params)) {
  259. $url .= '&' . uri_escape($name) . '=' . uri_escape($params{$name});
  260. }
  261. # Fetch
  262. if ($DEBUG) {
  263. print STDERR 'Fetching list URL: ' . $url . "\n";
  264. }
  265. my $content = get($url);
  266. if (!defined($content) || length($content) < 10) {
  267. die('Invalid content from URL: ' . $url . "\n");
  268. }
  269. # Parse
  270. my $data = decode_json($content);
  271. if (!defined($data) || ref($data) ne 'HASH') {
  272. die('Invalid JSON: ' . $content . "\n");
  273. }
  274. if (!exists($data->{'data'})) {
  275. die('Invalid data set: ' . $content . "\n");
  276. }
  277. $data = $data->{'data'};
  278. # Grab the total count, so we know when to stop
  279. if (!defined($itemCount) && exists($data->{'totalItems'})) {
  280. $itemCount = $data->{'totalItems'};
  281. }
  282. # Process each item
  283. if (!exists($data->{'items'}) || ref($data->{'items'}) ne 'ARRAY') {
  284. die('Invalid item list: ' . $content . "\n");
  285. }
  286. my $items = $data->{'items'};
  287. my $offset = 0;
  288. foreach my $item (@{$items}) {
  289. my %tmp = (
  290. 'number' => ($itemCount - $index - $offset + 1),
  291. 'title' => $item->{'title'},
  292. 'date' => str2time($item->{'uploaded'}),
  293. 'description' => $item->{'description'},
  294. 'duration' => $item->{'duration'},
  295. 'rating' => $item->{'rating'},
  296. 'creator' => $item->{'uploader'},
  297. );
  298. $videos{ $item->{'id'} } = \%tmp;
  299. $offset++;
  300. }
  301. # Loop if there are results left to fetch
  302. $index += $BATCH_SIZE;
  303. if (defined($itemCount) && $itemCount > $index) {
  304. # But don't go past the max supported index
  305. if ($index <= $MAX_INDEX) {
  306. redo LOOP;
  307. }
  308. }
  309. }
  310. if ($DEBUG) {
  311. print STDERR "\n\nFound " . scalar(keys(%videos)) . ' videos for YouTube user ' . $user . ":\n\t" . join("\n\t", keys(%videos)) . "\n\n";
  312. if ($DEBUG > 1) {
  313. use PrettyPrint;
  314. print STDERR prettyPrint(\%videos, "\t") . "\n";
  315. }
  316. }
  317. return \%videos;
  318. }