subscribe.pl 16 KB

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