subscribe.pl 20 KB

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