subscribe.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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 $EXTRAS_FILE = 'extra_videos.ini';
  18. my $EXCLUDES_FILE = 'exclude_videos.ini';
  19. my $CURL_BIN = 'curl';
  20. my @CURL_ARGS = ('-4', '--insecure', '-C', '-', '--connect-timeout', '10', '--max-time', '600');
  21. my $BATCH_SIZE = 50;
  22. my $MAX_INDEX = 2500;
  23. my $DRIFT_TOLERANCE = 2;
  24. my $DRIFT_FACTOR = 100.0;
  25. my $API_URL = 'https://gdata.youtube.com/feeds/api/';
  26. my %API = (
  27. 'search' => {
  28. 'prefix' => $API_URL . 'users/',
  29. 'suffix' => '/uploads',
  30. 'params' => {
  31. 'start-index' => 1,
  32. 'max-results' => 1,
  33. 'strict' => 1,
  34. 'v' => 2,
  35. 'alt' => 'jsonc',
  36. },
  37. },
  38. 'video' => {
  39. 'prefix' => $API_URL . 'videos/',
  40. 'suffix' => '',
  41. 'params' => {
  42. 'strict' => 1,
  43. 'v' => 2,
  44. 'alt' => 'jsonc'
  45. },
  46. },
  47. 'channel' => {
  48. 'prefix' => $API_URL . 'users/',
  49. 'suffix' => '',
  50. 'params' => {
  51. 'strict' => 1,
  52. 'v' => 2,
  53. 'alt' => 'json'
  54. },
  55. },
  56. );
  57. # Prototypes
  58. sub findVideos($);
  59. sub findFiles($);
  60. sub findVideo($);
  61. sub ytURL($);
  62. sub buildNFO($);
  63. sub buildSeriesNFO($);
  64. sub getChannel($);
  65. sub fetchParse($$);
  66. sub saveString($$);
  67. sub readExcludes($);
  68. sub readExtras($);
  69. sub parseVideoData($);
  70. sub dropExcludes($$);
  71. sub addExtras($$);
  72. sub saveChannel($$);
  73. # Sanity check
  74. if (scalar(@ARGV) < 1) {
  75. die('Usage: ' . basename($0) . " output_directory\n");
  76. }
  77. # Command-line parameters
  78. my ($dir) = @ARGV;
  79. $dir =~ s/\/+$//;
  80. if (!-d $dir) {
  81. die('Invalid output directory: ' . $dir . "\n");
  82. }
  83. my $user = basename($dir);
  84. if (length($user) < 1 || !($user =~ /^\w+$/)) {
  85. die('Invalid user: ' . $user . "\n");
  86. }
  87. # Environmental parameters (debug)
  88. my $DEBUG = 0;
  89. if ($ENV{'DEBUG'}) {
  90. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  91. $DEBUG = $1;
  92. } else {
  93. $DEBUG = 1;
  94. }
  95. }
  96. my $NO_FETCH = 0;
  97. if ($ENV{'NO_FETCH'}) {
  98. $NO_FETCH = 1;
  99. }
  100. my $NO_SEARCH = 0;
  101. if ($ENV{'NO_SEARCH'}) {
  102. $NO_SEARCH = 1;
  103. }
  104. my $NO_FILES = 0;
  105. if ($ENV{'NO_FILES'}) {
  106. $NO_FILES = 1;
  107. }
  108. my $NO_CHANNEL = 0;
  109. if ($ENV{'NO_CHANNEL'}) {
  110. $NO_CHANNEL = 1;
  111. }
  112. my $NO_EXTRAS = 0;
  113. if ($ENV{'NO_EXTRAS'}) {
  114. $NO_EXTRAS = 1;
  115. }
  116. my $NO_EXCLUDES = 0;
  117. if ($ENV{'NO_EXCLUDES'}) {
  118. $NO_EXCLUDES = 1;
  119. }
  120. # Environmental parameters (functional)
  121. my $RENAME = 0;
  122. if ($ENV{'RENAME'}) {
  123. $RENAME = 1;
  124. }
  125. if ($ENV{'MAX_INDEX'} && $ENV{'MAX_INDEX'} =~ /(\d+)/) {
  126. $MAX_INDEX = $1;
  127. }
  128. if ($ENV{'BATCH_SIZE'} && $ENV{'BATCH_SIZE'} =~ /(\d+)/) {
  129. $BATCH_SIZE = $1;
  130. }
  131. # Construct globals
  132. $API{'search'}{'params'}{'max-results'} = $BATCH_SIZE;
  133. if (!$DEBUG) {
  134. push(@CURL_ARGS, '--silent');
  135. }
  136. # Grab the channel data
  137. my $channel = {};
  138. if (!$NO_CHANNEL) {
  139. $channel = getChannel($user);
  140. saveChannel($dir, $channel);
  141. }
  142. # Find all the user's videos on YT
  143. my $videos = {};
  144. if (!$NO_SEARCH) {
  145. $videos = findVideos($user);
  146. }
  147. # Find any requested "extra" videos
  148. my $extras = {};
  149. if (!$NO_EXTRAS) {
  150. $extras = addExtras($dir, $videos);
  151. }
  152. # Drop any "excludes" videos
  153. my $excludes = {};
  154. if (!$NO_EXCLUDES) {
  155. $excludes = dropExcludes($dir, $videos);
  156. }
  157. # Find all existing YT files on disk
  158. my $files = {};
  159. if (!$NO_FILES) {
  160. $files = findFiles($dir);
  161. }
  162. # Fill in missing videos and NFOs
  163. foreach my $id (keys(%{$videos})) {
  164. my $basePath = $dir . '/S01E' . sprintf('%02d', $videos->{$id}->{'number'}) . ' - ' . $id . '.';
  165. my $nfo = $basePath . 'nfo';
  166. # Warn (and optionally rename) if the video numbers drift
  167. if (exists($files->{$id}) && $files->{$id}->{'number'} != $videos->{$id}->{'number'}) {
  168. if ($RENAME) {
  169. print STDERR 'Renaming ' . $files->{$id}->{'path'} . ' => ' . $basePath . $files->{$id}->{'suffix'} . "\n";
  170. rename($files->{$id}->{'path'}, $basePath . $files->{$id}->{'suffix'});
  171. rename($files->{$id}->{'nfo'}, $nfo);
  172. } else {
  173. # Find the old NFO to avoid re-fetching
  174. $nfo = $files->{$id}->{'nfo'};
  175. # Ignore small changes
  176. my $delta = abs($files->{$id}->{'number'} - $videos->{$id}->{'number'});
  177. my $tolerance = $files->{$id}->{'number'} / $DRIFT_FACTOR;
  178. if ($tolerance < $DRIFT_TOLERANCE) {
  179. $tolerance = $DRIFT_TOLERANCE;
  180. }
  181. if ($delta > $tolerance || $DEBUG) {
  182. print STDERR 'Video ' . $id . ' had video number ' . $files->{$id}->{'number'} . ' but now has video number ' . $videos->{$id}->{'number'} . "\n";
  183. }
  184. }
  185. }
  186. # If we haven't heard of the file, or don't have an NFO for it
  187. # Checking for the NFO allows use to resume failed downloads
  188. if (!exists($files->{$id}) || !-e $nfo) {
  189. if ($DEBUG) {
  190. print STDERR 'Fetching video: ' . $id . "\n";
  191. }
  192. # Find the download URL and file suffix
  193. my ($url, $suffix) = ytURL($id);
  194. if (!defined($url) || length($url) < 5) {
  195. warn('Could not determine URL for video: ' . $id . "\n");
  196. $url = undef();
  197. }
  198. # Fetch with cURL
  199. # I know LWP exists (and is even loaded) but cURL makes my life easier
  200. if ($url) {
  201. my @cmd = ($CURL_BIN);
  202. push(@cmd, @CURL_ARGS);
  203. push(@cmd, '-o', $basePath . $suffix, $url);
  204. if ($NO_FETCH) {
  205. print STDERR 'Not running: ' . join(' ', @cmd) . "\n";
  206. } else {
  207. if ($DEBUG > 1) {
  208. print STDERR join(' ', @cmd) . "\n";
  209. }
  210. system(@cmd);
  211. }
  212. }
  213. # Build and save the XML document
  214. my $xml = buildNFO($videos->{$id});
  215. if ($DEBUG > 1) {
  216. print STDERR 'Saving NFO: ' . $xml . "\n";
  217. }
  218. if ($NO_FETCH) {
  219. print STDERR "Not saving NFO\n";
  220. } else {
  221. saveString($nfo, $xml);
  222. }
  223. }
  224. }
  225. sub saveString($$) {
  226. my ($path, $str) = @_;
  227. my $fh = undef();
  228. if (!open($fh, '>', $path)) {
  229. warn('Cannot open file for writing: ' . $! . "\n");
  230. return undef();
  231. }
  232. print $fh $str;
  233. close($fh);
  234. return 1;
  235. }
  236. sub buildSeriesNFO($) {
  237. my ($channel) = @_;
  238. # Create an XML tree
  239. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  240. $doc->setStandalone(1);
  241. my $show = $doc->createElement('tvshow');
  242. $doc->setDocumentElement($show);
  243. my $elm;
  244. # Add data
  245. $elm = $doc->createElement('title');
  246. $elm->appendText($channel->{'title'});
  247. $show->appendChild($elm);
  248. $elm = $doc->createElement('premiered');
  249. $elm->appendText(time2str('%Y-%m-%d', $channel->{'date'}));
  250. $show->appendChild($elm);
  251. $elm = $doc->createElement('plot');
  252. $elm->appendText($channel->{'description'});
  253. $show->appendChild($elm);
  254. # Return the string
  255. return $doc->toString();
  256. }
  257. sub buildNFO($) {
  258. my ($video) = @_;
  259. # Create an XML tree
  260. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  261. $doc->setStandalone(1);
  262. my $show = $doc->createElement('episodedetails');
  263. $doc->setDocumentElement($show);
  264. my $elm;
  265. # Add data
  266. $elm = $doc->createElement('season');
  267. $elm->appendText('1');
  268. $show->appendChild($elm);
  269. $elm = $doc->createElement('episode');
  270. $elm->appendText($video->{'number'});
  271. $show->appendChild($elm);
  272. if (!defined($video->{'title'})) {
  273. $video->{'title'} = 'Episode ' . $video->{'number'};
  274. }
  275. $elm = $doc->createElement('title');
  276. $elm->appendText($video->{'title'});
  277. $show->appendChild($elm);
  278. if (!defined($video->{'date'})) {
  279. $video->{'date'} = time();
  280. }
  281. $elm = $doc->createElement('aired');
  282. $elm->appendText(time2str('%Y-%m-%d', $video->{'date'}));
  283. $show->appendChild($elm);
  284. if (defined($video->{'description'})) {
  285. $elm = $doc->createElement('plot');
  286. $elm->appendText($video->{'description'});
  287. $show->appendChild($elm);
  288. }
  289. if (defined($video->{'duration'})) {
  290. $elm = $doc->createElement('runtime');
  291. $elm->appendText($video->{'duration'});
  292. $show->appendChild($elm);
  293. }
  294. if (defined($video->{'rating'})) {
  295. $elm = $doc->createElement('rating');
  296. $elm->appendText($video->{'rating'});
  297. $show->appendChild($elm);
  298. }
  299. if (defined($video->{'creator'})) {
  300. $elm = $doc->createElement('director');
  301. $elm->appendText($video->{'creator'});
  302. $show->appendChild($elm);
  303. }
  304. # Return the string
  305. return $doc->toString();
  306. }
  307. sub ytURL($) {
  308. my ($id) = @_;
  309. # Init the YT object
  310. my $tube = WWW::YouTube::Download->new;
  311. # Fetch metadata
  312. my $meta = eval { $tube->prepare_download($id); };
  313. if (!defined($meta) || ref($meta) ne 'HASH' || !exists($meta->{'video_url_map'}) || ref($meta->{'video_url_map'}) ne 'HASH') {
  314. if ($@ =~ /age gate/i) {
  315. print STDERR "Video not available due to age gate restrictions\n";
  316. }
  317. return undef();
  318. }
  319. # Find the best stream (i.e. highest resolution, prefer mp4)
  320. my $bestStream = undef();
  321. my $bestResolution = 0;
  322. foreach my $streamID (keys(%{ $meta->{'video_url_map'} })) {
  323. my $stream = $meta->{'video_url_map'}->{$streamID};
  324. my ($res) = $stream->{'resolution'} =~ /^\s*(\d+)/;
  325. if ($DEBUG > 1) {
  326. print STDERR $streamID . ' (' . $stream->{'suffix'} . ')' . ' => ' . $stream->{'resolution'} . ' : ' . $stream->{'url'} . "\n";
  327. }
  328. if ( ($res > $bestResolution)
  329. || ($res == $bestResolution && defined($bestStream) && $bestStream->{'suffix'} ne 'mp4'))
  330. {
  331. $bestStream = $stream;
  332. $bestResolution = $res;
  333. }
  334. }
  335. if (!exists($bestStream->{'suffix'}) || length($bestStream->{'suffix'}) < 2) {
  336. $bestStream->{'suffix'} = 'mp4';
  337. }
  338. return ($bestStream->{'url'}, $bestStream->{'suffix'});
  339. }
  340. sub findFiles($) {
  341. my ($dir) = @_;
  342. my %files = ();
  343. # Allow complete bypass
  344. if ($NO_FILES) {
  345. return \%files;
  346. }
  347. # Read the output directory
  348. my $fh = undef();
  349. opendir($fh, $dir)
  350. or die('Unable to open output directory: ' . $! . "\n");
  351. while (my $file = readdir($fh)) {
  352. my ($num, $id, $suffix) = $file =~ /^S\d+E(\d+) - ([\w\-]+)\.(\w\w\w)$/i;
  353. if (defined($id) && length($id) > 0) {
  354. if ($suffix eq 'nfo') {
  355. next;
  356. }
  357. my %tmp = (
  358. 'number' => $num,
  359. 'suffix' => $suffix,
  360. 'path' => $dir . '/' . $file,
  361. );
  362. $tmp{'nfo'} = $tmp{'path'};
  363. $tmp{'nfo'} =~ s/\.\w\w\w$/\.nfo/;
  364. if (exists($files{$id})) {
  365. warn('Duplicate ID: ' . $id . "\n\t" . $files{$id}->{'path'} . "\n\t" . $tmp{'path'} . "\n");
  366. if ($RENAME) {
  367. # Prefer to delete MP4 files, if the suffixes differ
  368. my $del = $files{$id};
  369. if ($tmp{'suffix'} eq 'mp4' && $del->{'suffix'} ne 'mp4') {
  370. $del = \%tmp;
  371. %tmp = %{ $files{$id} };
  372. }
  373. print STDERR 'Deleting duplicate: ' . $del->{'path'} . "\n";
  374. unlink($del->{'path'});
  375. unlink($del->{'nfo'});
  376. }
  377. }
  378. $files{$id} = \%tmp;
  379. }
  380. }
  381. close($fh);
  382. if ($DEBUG) {
  383. print STDERR "\nFound " . scalar(keys(%files)) . " files:\n\t" . join(', ', keys(%files)) . "\n";
  384. if ($DEBUG > 1) {
  385. print STDERR prettyPrint(\%files, "\t") . "\n";
  386. }
  387. }
  388. return \%files;
  389. }
  390. sub fetchParse($$) {
  391. my ($name, $id) = @_;
  392. my $url = $API{$name}{'prefix'} . $id . $API{$name}{'suffix'} . '?';
  393. foreach my $key (keys(%{ $API{$name}{'params'} })) {
  394. $url .= '&' . uri_escape($key) . '=' . uri_escape($API{$name}{'params'}{$key});
  395. }
  396. # Fetch
  397. if ($DEBUG) {
  398. print STDERR 'Fetching ' . $name . ' API URL: ' . $url . "\n";
  399. }
  400. my $content = get($url);
  401. if (!defined($content) || length($content) < 10) {
  402. die('Invalid content from URL: ' . $url . "\n");
  403. }
  404. # Parse
  405. my $data = decode_json($content);
  406. if (!defined($data) || ref($data) ne 'HASH') {
  407. die('Invalid JSON: ' . $content . "\n");
  408. }
  409. if ($DEBUG > 2) {
  410. print STDERR "Raw JSON data:\n" . prettyPrint($data, ' ') . "\n";
  411. }
  412. return $data;
  413. }
  414. sub saveChannel($$) {
  415. my ($dir, $channel) = @_;
  416. my $nfo = $dir . '/tvshow.nfo';
  417. if (!-e $nfo) {
  418. if ($DEBUG) {
  419. print STDERR 'Saving series data for: ' . $channel->{'title'} . "\n";
  420. }
  421. # Save the poster
  422. if (exists($channel->{'thumbnail'}) && length($channel->{'thumbnail'}) > 5) {
  423. my $poster = $dir . '/poster.jpg';
  424. my $jpg = get($channel->{'thumbnail'});
  425. saveString($poster, $jpg);
  426. }
  427. # Save the series NFO
  428. my $xml = buildSeriesNFO($channel);
  429. if ($DEBUG > 1) {
  430. print STDERR 'Saving NFO: ' . $xml . "\n";
  431. }
  432. saveString($nfo, $xml);
  433. }
  434. }
  435. sub getChannel($) {
  436. my ($user) = @_;
  437. # Build, fetch, parse
  438. my $data = fetchParse('channel', $user);
  439. if (!exists($data->{'entry'}) || ref($data->{'entry'}) ne 'HASH') {
  440. die("Invalid channel data\n");
  441. }
  442. $data = $data->{'entry'};
  443. # Extract the data we want
  444. my %channel = (
  445. 'id' => $data->{'yt$channelId'}->{'$t'},
  446. 'title' => $data->{'title'}->{'$t'},
  447. 'date' => str2time($data->{'published'}->{'$t'}),
  448. 'description' => $data->{'summary'}->{'$t'},
  449. 'thumbnail' => $data->{'media$thumbnail'}->{'url'},
  450. );
  451. return \%channel;
  452. }
  453. sub readExcludes($) {
  454. my ($dir) = @_;
  455. my %excludes = ();
  456. # Read and parse the excludes videos file, if it exists
  457. my $file = $dir . '/' . $EXCLUDES_FILE;
  458. if (-e $file) {
  459. my $fh;
  460. open($fh, $file)
  461. or die('Unable to open excludes videos file: ' . $! . "\n");
  462. while (<$fh>) {
  463. # Skip blank lines and comments
  464. if ($_ =~ /^\s*#/ || $_ =~ /^\s*$/) {
  465. next;
  466. }
  467. # Match our specific format or whine
  468. if ($_ =~ /^\s*([\w\-]+)\s*$/) {
  469. if ($DEBUG > 1) {
  470. print STDERR 'Adding exclude video: ' . $1 . "\n";
  471. }
  472. $excludes{$1} = 1;
  473. } else {
  474. print STDERR 'Skipped exclude video line: ' . $_;
  475. }
  476. }
  477. close($fh);
  478. }
  479. return \%excludes;
  480. }
  481. sub readExtras($) {
  482. my ($dir) = @_;
  483. my %extras = ();
  484. # Read and parse the extra videos file, if it exists
  485. my $file = $dir . '/' . $EXTRAS_FILE;
  486. if (-e $file) {
  487. my $fh;
  488. open($fh, $file)
  489. or die('Unable to open extra videos file: ' . $! . "\n");
  490. while (<$fh>) {
  491. # Skip blank lines and comments
  492. if ($_ =~ /^\s*#/ || $_ =~ /^\s*$/) {
  493. next;
  494. }
  495. # Match our specific format or whine
  496. if ($_ =~ /^\s*(\d+)\s*[=:>]+\s*([\w\-]+)\s*$/) {
  497. if ($DEBUG > 1) {
  498. print STDERR 'Adding extra video: ' . $1 . ' => ' . $2 . "\n";
  499. }
  500. $extras{$2} = $1;
  501. } else {
  502. print STDERR 'Skipped extra video line: ' . $_;
  503. }
  504. }
  505. close($fh);
  506. }
  507. return \%extras;
  508. }
  509. sub parseVideoData($) {
  510. my ($data) = @_;
  511. my %video = (
  512. 'title' => $data->{'title'},
  513. 'date' => str2time($data->{'uploaded'}),
  514. 'description' => $data->{'description'},
  515. 'duration' => $data->{'duration'},
  516. 'rating' => $data->{'rating'},
  517. 'creator' => $data->{'uploader'},
  518. );
  519. return \%video;
  520. }
  521. sub findVideo($) {
  522. my ($id) = @_;
  523. # Build, fetch, parse
  524. my $data = fetchParse('video', $id);
  525. # Validate
  526. if (!exists($data->{'data'})) {
  527. die("Invalid video list\n");
  528. }
  529. $data = $data->{'data'};
  530. # Parse the video data
  531. return parseVideoData($data);
  532. }
  533. sub dropExcludes($$) {
  534. my ($dir, $videos) = @_;
  535. my $excludes = readExcludes($dir);
  536. foreach my $id (keys(%{$excludes})) {
  537. if (!exists($videos->{$id})) {
  538. if ($DEBUG > 1) {
  539. print STDERR 'Skipping unknown excludes video: ' . $id . "\n";
  540. }
  541. next;
  542. }
  543. delete($videos->{$id});
  544. }
  545. return $excludes;
  546. }
  547. sub addExtras($$) {
  548. my ($dir, $videos) = @_;
  549. my $extras = readExtras($dir);
  550. foreach my $id (keys(%{$extras})) {
  551. if (exists($videos->{$id})) {
  552. if ($DEBUG > 1) {
  553. print STDERR 'Skipping known extra video: ' . $id . "\n";
  554. }
  555. next;
  556. }
  557. my $video = findVideo($id);
  558. $video->{'number'} = $extras->{$id};
  559. $videos->{$id} = $video;
  560. }
  561. return $extras;
  562. }
  563. sub findVideos($) {
  564. my ($user) = @_;
  565. my %videos = ();
  566. # Allow complete bypass
  567. if ($NO_SEARCH) {
  568. return \%videos;
  569. }
  570. # Loop through until we have all the entries
  571. my $index = 1;
  572. my $itemCount = undef();
  573. LOOP:
  574. {
  575. # Build, fetch, parse
  576. $API{'search'}{'params'}{'start-index'} = $index;
  577. my $data = fetchParse('search', $user);
  578. # Grab the total count, so we know when to stop
  579. if (!exists($data->{'data'})) {
  580. die("Invalid video list\n");
  581. }
  582. $data = $data->{'data'};
  583. if (!defined($itemCount) && exists($data->{'totalItems'})) {
  584. $itemCount = $data->{'totalItems'};
  585. }
  586. # Process each item
  587. if (!exists($data->{'items'}) || ref($data->{'items'}) ne 'ARRAY') {
  588. die("Invalid video list\n");
  589. }
  590. my $items = $data->{'items'};
  591. my $offset = 0;
  592. foreach my $item (@{$items}) {
  593. my $video = parseVideoData($item);
  594. $video->{'number'} = $itemCount - $index - $offset + 1;
  595. $videos{ $item->{'id'} } = $video;
  596. $offset++;
  597. }
  598. # Loop if there are results left to fetch
  599. $index += $BATCH_SIZE;
  600. if (defined($itemCount) && $itemCount > $index) {
  601. # But don't go past the max supported index
  602. if ($index <= $MAX_INDEX) {
  603. redo LOOP;
  604. }
  605. }
  606. }
  607. if ($DEBUG) {
  608. print STDERR "\nFound " . scalar(keys(%videos)) . ' videos for YouTube user ' . $user . ":\n\t" . join(', ', keys(%videos)) . "\n";
  609. if ($DEBUG > 1) {
  610. print STDERR prettyPrint(\%videos, "\t") . "\n";
  611. }
  612. }
  613. return \%videos;
  614. }