subscribe.pl 20 KB

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