subscribe.pl 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use FindBin;
  5. use lib "$FindBin::Bin/";
  6. use File::Touch;
  7. use File::Basename;
  8. use Date::Parse;
  9. use Date::Format;
  10. use LWP::Simple;
  11. use URI::Escape;
  12. use JSON;
  13. use XML::LibXML;
  14. use IPC::System::Simple qw( system run capture EXIT_ANY $EXITVAL );
  15. use IPC::Cmd qw( can_run );
  16. use PrettyPrint;
  17. # Paramters
  18. my %USERS = ('profplump' => 'kj-Ob6eYHvzo-P0UWfnQzA', 'shanda' => 'hfwMHzkPXOOFDce5hyQkTA');
  19. my $EXTRAS_FILE = 'extra_videos.ini';
  20. my $EXCLUDES_FILE = 'exclude_videos.ini';
  21. my $YTDL_BIN = $ENV{'HOME'} . '/bin/video/yt/youtube-dl';
  22. my @YTDL_ARGS = ('--force-ipv4', '--socket-timeout', '10', '--no-playlist', '--max-downloads', '1', '--age-limit', '99');
  23. my @YTDL_QUIET = ('--quiet', '--no-warnings');
  24. my @YTDL_DEBUG = ('--verbose');
  25. my $BATCH_SIZE = 50;
  26. my $MAX_INDEX = 25000;
  27. my $FETCH_LIMIT = 50;
  28. my $DELAY = 5;
  29. my $API_URL = 'https://gdata.youtube.com/feeds/api/';
  30. my %API = (
  31. 'search' => {
  32. 'prefix' => $API_URL . 'users/',
  33. 'suffix' => '/uploads',
  34. 'params' => {
  35. 'start-index' => 1,
  36. 'max-results' => 1,
  37. 'strict' => 1,
  38. 'v' => 2,
  39. 'alt' => 'jsonc',
  40. },
  41. },
  42. 'subscriptions' => {
  43. 'prefix' => $API_URL . 'users/',
  44. 'suffix' => '/subscriptions',
  45. 'params' => {
  46. 'start-index' => 1,
  47. 'max-results' => 1,
  48. 'strict' => 1,
  49. 'v' => 2,
  50. 'alt' => 'json',
  51. },
  52. },
  53. 'video' => {
  54. 'prefix' => $API_URL . 'videos/',
  55. 'suffix' => '',
  56. 'params' => {
  57. 'strict' => 1,
  58. 'v' => 2,
  59. 'alt' => 'jsonc'
  60. },
  61. },
  62. 'channel' => {
  63. 'prefix' => $API_URL . 'users/',
  64. 'suffix' => '',
  65. 'params' => {
  66. 'strict' => 1,
  67. 'v' => 2,
  68. 'alt' => 'json'
  69. },
  70. },
  71. );
  72. # Prototypes
  73. sub findVideos($);
  74. sub findFiles($);
  75. sub findVideo($);
  76. sub buildNFO($);
  77. sub buildSeriesNFO($);
  78. sub getSubscriptions($$);
  79. sub saveSubscriptions($$);
  80. sub saveChannel($);
  81. sub getChannel($);
  82. sub fetchParse($$);
  83. sub saveString($$);
  84. sub readExcludes();
  85. sub readExtras();
  86. sub parseVideoData($);
  87. sub dropExcludes($);
  88. sub addExtras($);
  89. sub updateNFOData($$$);
  90. sub videoSE($$);
  91. sub videoPath($$$$);
  92. sub renameVideo($$$$$$);
  93. sub parseFilename($);
  94. # Sanity check
  95. if (scalar(@ARGV) < 1) {
  96. die('Usage: ' . basename($0) . " output_directory\n");
  97. }
  98. # Command-line parameters
  99. my ($dir) = @ARGV;
  100. $dir =~ s/\/+$//;
  101. if (!-d $dir) {
  102. die('Invalid output directory: ' . $dir . "\n");
  103. }
  104. my $user = basename($dir);
  105. if (length($user) < 1 || !($user =~ /^\w+$/)) {
  106. die('Invalid user: ' . $user . "\n");
  107. }
  108. # Move to the target directory so we can use relative paths later
  109. chdir($dir);
  110. # Environmental parameters (debug)
  111. my $DEBUG = 0;
  112. if ($ENV{'DEBUG'}) {
  113. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  114. $DEBUG = $1;
  115. } else {
  116. $DEBUG = 1;
  117. }
  118. }
  119. my $NO_FETCH = 0;
  120. if ($ENV{'NO_FETCH'}) {
  121. $NO_FETCH = 1;
  122. }
  123. my $NO_NFO = 0;
  124. if ($ENV{'NO_NFO'}) {
  125. $NO_NFO = 1;
  126. }
  127. my $NO_SEARCH = 0;
  128. if ($ENV{'NO_SEARCH'}) {
  129. $NO_SEARCH = 1;
  130. }
  131. my $NO_FILES = 0;
  132. if ($ENV{'NO_FILES'}) {
  133. $NO_FILES = 1;
  134. }
  135. my $NO_CHANNEL = 0;
  136. if ($ENV{'NO_CHANNEL'}) {
  137. $NO_CHANNEL = 1;
  138. }
  139. my $NO_EXTRAS = 0;
  140. if ($ENV{'NO_EXTRAS'}) {
  141. $NO_EXTRAS = 1;
  142. }
  143. my $NO_EXCLUDES = 0;
  144. if ($ENV{'NO_EXCLUDES'}) {
  145. $NO_EXCLUDES = 1;
  146. }
  147. my $NO_RENAME = 0;
  148. if ($ENV{'NO_RENAME'}) {
  149. $NO_RENAME = 1;
  150. }
  151. # Environmental parameters (functional)
  152. my $SUDO_CHATTR = 1;
  153. if ($ENV{'NO_CHATTR'} || !can_run('sudo') || !can_run('chattr')) {
  154. $SUDO_CHATTR = 0;
  155. }
  156. if ($ENV{'MAX_INDEX'} && $ENV{'MAX_INDEX'} =~ /(\d+)/) {
  157. $MAX_INDEX = $1;
  158. }
  159. if ($ENV{'BATCH_SIZE'} && $ENV{'BATCH_SIZE'} =~ /(\d+)/) {
  160. $BATCH_SIZE = $1;
  161. }
  162. if (exists($ENV{'FETCH_LIMIT'}) && $ENV{'FETCH_LIMIT'} =~ /(\d+)/) {
  163. $FETCH_LIMIT = $1;
  164. }
  165. # Construct globals
  166. foreach my $key (keys(%API)) {
  167. if (exists($API{$key}{'params'}{'max-results'})) {
  168. $API{$key}{'params'}{'max-results'} = $BATCH_SIZE;
  169. }
  170. }
  171. if ($DEBUG > 1) {
  172. push(@YTDL_ARGS, @YTDL_DEBUG);
  173. } elsif (!$DEBUG) {
  174. push(@YTDL_ARGS, @YTDL_QUIET);
  175. }
  176. # Allow use as a subscription manager
  177. if ($0 =~ /subscription/i) {
  178. my %subs = ();
  179. foreach my $user (keys(%USERS)) {
  180. my $tmp = getSubscriptions($user, $USERS{$user});
  181. foreach my $sub (keys(%{$tmp})) {
  182. if (exists($subs{$sub})) {
  183. $subs{$sub} .= ', ' . $tmp->{$sub};
  184. } else {
  185. $subs{$sub} = $tmp->{$sub};
  186. }
  187. }
  188. }
  189. saveSubscriptions($dir, \%subs);
  190. exit(0);
  191. }
  192. # Grab the channel data
  193. my $channel = {};
  194. if (!$NO_CHANNEL) {
  195. $channel = getChannel($user);
  196. saveChannel($channel);
  197. }
  198. # Find all the user's videos on YT
  199. my $videos = {};
  200. if (!$NO_SEARCH) {
  201. $videos = findVideos($user);
  202. }
  203. # Find any requested "extra" videos
  204. my $extras = {};
  205. if (!$NO_EXTRAS) {
  206. $extras = addExtras($videos);
  207. }
  208. # Drop any "excludes" videos
  209. my $excludes = {};
  210. if (!$NO_EXCLUDES) {
  211. $excludes = dropExcludes($videos);
  212. }
  213. # Calculate the episode number using the publish dates
  214. {
  215. my @byDate = sort { $videos->{$a}->{'date'} <=> $videos->{$b}->{'date'} || $a cmp $b } keys %{$videos};
  216. my $num = undef();
  217. my $lastSeason = undef();
  218. foreach my $id (@byDate) {
  219. if (!$lastSeason || $lastSeason != $videos->{$id}->{'season'}) {
  220. $num = 1;
  221. $lastSeason = $videos->{$id}->{'season'};
  222. }
  223. $videos->{$id}->{'number'} = $num++;
  224. }
  225. }
  226. # Find all existing YT files on disk
  227. my $files = {};
  228. if (!$NO_FILES) {
  229. $files = findFiles($videos);
  230. }
  231. # Whine about unknown videos
  232. foreach my $id (keys(%{$files})) {
  233. if (!exists($videos->{$id}) && $files->{$id}->{'season'} > 0) {
  234. print STDERR 'Local video not known to YT channel (' . $user . '): ' . $id . "\n";
  235. renameVideo($files->{$id}->{'path'}, $files->{$id}->{'suffix'}, $files->{$id}->{'nfo'}, $id, 0, $files->{$id}->{'season'} . $files->{$id}->{'number'});
  236. }
  237. }
  238. # Fill in missing videos and NFOs
  239. my $fetched = 0;
  240. foreach my $id (keys(%{$videos})) {
  241. my $nfo = videoPath($videos->{$id}->{'season'}, $videos->{$id}->{'number'}, $id, 'nfo');
  242. # Determine if we may or must rename
  243. my $rename = 0;
  244. if (exists($files->{$id})) {
  245. # Rename if we drift
  246. if (!$rename && $files->{$id}->{'path'}) {
  247. if ( $files->{$id}->{'number'} != $videos->{$id}->{'number'}
  248. || $files->{$id}->{'season'} != $videos->{$id}->{'season'})
  249. {
  250. if ($DEBUG) {
  251. print STDERR "Rename due to drift\n";
  252. }
  253. $rename = 1;
  254. }
  255. }
  256. # Always rename if the NFO does not match the media
  257. if (!$rename && $files->{$id}->{'path'} && $files->{$id}->{'nfo'}) {
  258. my ($season, $number) = parseFilename($files->{$id}->{'nfo'});
  259. if ($files->{$id}->{'season'} != $season || $files->{$id}->{'number'} != $number) {
  260. if ($DEBUG) {
  261. print STDERR "Rename due to media-metadata mismatch\n";
  262. }
  263. $rename = 1;
  264. }
  265. }
  266. }
  267. # Warn (and optionally rename) as selected
  268. if ($rename) {
  269. print STDERR 'Video ' . $id . ' had number ' . $files->{$id}->{'number'} . ' but now has number ' . $videos->{$id}->{'number'} . "\n";
  270. renameVideo($files->{$id}->{'path'}, $files->{$id}->{'suffix'}, $files->{$id}->{'nfo'}, $id, $videos->{$id}->{'season'}, $videos->{$id}->{'number'});
  271. }
  272. # If we haven't heard of the file, or don't have an NFO for it
  273. # Checking for the NFO allows use to resume failed downloads
  274. if (!exists($files->{$id}) || !-e $nfo) {
  275. if ($DEBUG) {
  276. print STDERR 'Fetching video: ' . $id . "\n";
  277. }
  278. # Let youtube-dl handle the URLs and downloading
  279. {
  280. my @args = ('--output', videoSE($videos->{$id}->{'season'}, $videos->{$id}->{'number'}) . '%(id)s.%(ext)s', '--', $id);
  281. my @name = ($YTDL_BIN);
  282. push(@name, @YTDL_ARGS);
  283. my @fetch = @name;
  284. push(@name, '--get-filename');
  285. push(@fetch, @args);
  286. push(@name, @args);
  287. if ($NO_FETCH) {
  288. print STDERR 'Not running: ' . join(' ', @fetch) . "\n";
  289. } else {
  290. # Count fetch attempts (even if they fail later)
  291. $fetched++;
  292. if ($FETCH_LIMIT && $fetched > $FETCH_LIMIT) {
  293. print STDERR 'Reached fetch limit (' . $FETCH_LIMIT . ') for: ' . $user . "\n";
  294. if ($DEBUG) {
  295. print STDERR "\tLocal/Remote videos at start:" . scalar(keys(%{$files})) . '/' . scalar(keys(%{$videos})) . "\n";
  296. }
  297. exit 1;
  298. }
  299. # Find the output file name
  300. if ($DEBUG > 1) {
  301. print STDERR join(' ', @name) . "\n";
  302. }
  303. sleep($DELAY);
  304. my $file = capture(EXIT_ANY, @name);
  305. if ($EXITVAL != 0) {
  306. warn('Error executing youtube-dl for name: ' . $id . ' (' . $EXITVAL . ")\n");
  307. next;
  308. }
  309. $file =~ s/^\s+//;
  310. $file =~ s/\s+$//;
  311. # Sanity check
  312. if (!$file) {
  313. warn('No file name available for video: ' . $id . "\n");
  314. next;
  315. }
  316. # Download
  317. if ($DEBUG > 1) {
  318. print STDERR join(' ', @fetch) . "\n";
  319. }
  320. sleep($DELAY);
  321. my $exit = run(EXIT_ANY, @fetch);
  322. if ($exit != 0) {
  323. warn('Error executing youtube-dl for video: ' . $file . "\n");
  324. next;
  325. }
  326. # Ensure we found something useful
  327. if (-e $file . '.part') {
  328. warn('Partial download detected: ' . $file . "\n");
  329. next;
  330. }
  331. if (!-s $file) {
  332. warn('No output video file: ' . $file . "\n");
  333. next;
  334. }
  335. # Touch the file to reflect the download time rather than the upload time
  336. touch($file);
  337. }
  338. }
  339. # Build and save the XML document
  340. my $xml = buildNFO($videos->{$id});
  341. if ($DEBUG > 1) {
  342. print STDERR 'Saving NFO: ' . $xml . "\n";
  343. }
  344. if ($NO_NFO) {
  345. print STDERR "Not saving NFO\n";
  346. } else {
  347. saveString($nfo, $xml);
  348. }
  349. }
  350. }
  351. sub saveString($$) {
  352. my ($path, $str) = @_;
  353. my $fh = undef();
  354. if (!open($fh, '>', $path)) {
  355. warn('Cannot open file for writing: ' . $path . ': ' . $! . "\n");
  356. return undef();
  357. }
  358. print $fh $str;
  359. close($fh);
  360. return 1;
  361. }
  362. sub buildSeriesNFO($) {
  363. my ($channel) = @_;
  364. # Create an XML tree
  365. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  366. $doc->setStandalone(1);
  367. my $show = $doc->createElement('tvshow');
  368. $doc->setDocumentElement($show);
  369. my $elm;
  370. # Add data
  371. $elm = $doc->createElement('title');
  372. $elm->appendText($channel->{'title'});
  373. $show->appendChild($elm);
  374. $elm = $doc->createElement('premiered');
  375. $elm->appendText(time2str('%Y-%m-%d', $channel->{'date'}));
  376. $show->appendChild($elm);
  377. $elm = $doc->createElement('plot');
  378. $elm->appendText($channel->{'description'});
  379. $show->appendChild($elm);
  380. # Return the string
  381. return $doc->toString();
  382. }
  383. sub buildNFO($) {
  384. my ($video) = @_;
  385. # Create an XML tree
  386. my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  387. $doc->setStandalone(1);
  388. my $show = $doc->createElement('episodedetails');
  389. $doc->setDocumentElement($show);
  390. my $file = $doc->createElement('fileinfo');
  391. $show->appendChild($file);
  392. my $stream = $doc->createElement('streamdetails');
  393. $file->appendChild($stream);
  394. my $stream_video = $doc->createElement('video');
  395. $stream->appendChild($stream_video);
  396. my $elm;
  397. # Add data
  398. $elm = $doc->createElement('season');
  399. $elm->appendText($video->{'season'});
  400. $show->appendChild($elm);
  401. $elm = $doc->createElement('episode');
  402. $elm->appendText($video->{'number'});
  403. $show->appendChild($elm);
  404. if (!defined($video->{'title'})) {
  405. $video->{'title'} = 'Episode ' . $video->{'number'};
  406. }
  407. $elm = $doc->createElement('title');
  408. $elm->appendText($video->{'title'});
  409. $show->appendChild($elm);
  410. if (!defined($video->{'date'})) {
  411. $video->{'date'} = time();
  412. }
  413. $elm = $doc->createElement('aired');
  414. $elm->appendText(time2str('%Y-%m-%d', $video->{'date'}));
  415. $show->appendChild($elm);
  416. if (defined($video->{'description'})) {
  417. $elm = $doc->createElement('plot');
  418. $elm->appendText($video->{'description'});
  419. $show->appendChild($elm);
  420. }
  421. if (defined($video->{'duration'})) {
  422. $elm = $doc->createElement('runtime');
  423. $elm->appendText($video->{'duration'});
  424. $show->appendChild($elm);
  425. $elm = $doc->createElement('durationinseconds');
  426. $elm->appendText($video->{'duration'});
  427. $stream_video->appendChild($elm);
  428. }
  429. if (defined($video->{'rating'})) {
  430. $elm = $doc->createElement('rating');
  431. $elm->appendText($video->{'rating'});
  432. $show->appendChild($elm);
  433. }
  434. if (defined($video->{'creator'})) {
  435. $elm = $doc->createElement('director');
  436. $elm->appendText($video->{'creator'});
  437. $show->appendChild($elm);
  438. }
  439. # Return the string
  440. return $doc->toString();
  441. }
  442. sub findFiles($) {
  443. my ($videos) = @_;
  444. my %files = ();
  445. # Allow complete bypass
  446. if ($NO_FILES) {
  447. return \%files;
  448. }
  449. # Read the output directory
  450. my $fh = undef();
  451. opendir($fh, '.')
  452. or die('Unable to open files directory: ' . $! . "\n");
  453. while (my $file = readdir($fh)) {
  454. my ($season, $number, $id, $suffix) = parseFilename($file);
  455. if (defined($id) && length($id) > 0) {
  456. # Create the record as needed
  457. if (!exists($files{$id})) {
  458. my %tmp = (
  459. 'season' => $season,
  460. 'number' => $number,
  461. );
  462. $files{$id} = \%tmp;
  463. }
  464. # Video or NFO?
  465. my $type = 'path';
  466. if ($suffix eq 'nfo') {
  467. $type = 'nfo';
  468. }
  469. # Deal with duplicates
  470. if (exists($files{$id}->{$type})) {
  471. if ($type eq 'nfo') {
  472. warn('Duplicate NFO: ' . $id . "\n\t" . $files{$id}->{'nfo'} . "\n\t" . $file . "\n");
  473. if (!$NO_RENAME) {
  474. my $del = $file;
  475. if ( exists($videos->{$id})
  476. && $season == $videos->{$id}->{'season'}
  477. && $number == $videos->{$id}->{'number'})
  478. {
  479. $del = $files{$id}->{'nfo'};
  480. }
  481. warn("\tDeleting: " . $file . "\n");
  482. if ($SUDO_CHATTR) {
  483. system('sudo', 'chattr', '-i', $file);
  484. }
  485. unlink($file);
  486. next;
  487. }
  488. } else {
  489. warn('Duplicate video: ' . $id . "\n\t" . $files{$id}->{'path'} . "\n\t" . $file . "\n");
  490. if (!$NO_RENAME) {
  491. my $del = $file;
  492. if ( exists($videos->{$id})
  493. && $season == $videos->{$id}->{'season'}
  494. && $number == $videos->{$id}->{'number'})
  495. {
  496. $del = $files{$id}->{'path'};
  497. } elsif ($suffix ne 'mp4' && $files{$id}->{'suffix'} eq 'mp4') {
  498. $del = $files{$id}->{'path'};
  499. }
  500. warn("\tDeleting: " . $del . "\n");
  501. if ($SUDO_CHATTR) {
  502. system('sudo', 'chattr', '-i', $del);
  503. }
  504. unlink($del);
  505. next;
  506. }
  507. }
  508. }
  509. # Assign the component paths
  510. $files{$id}->{$type} = $file;
  511. if ($type ne 'nfo') {
  512. $files{$id}->{'suffix'} = $suffix;
  513. }
  514. }
  515. }
  516. close($fh);
  517. if ($DEBUG) {
  518. print STDERR 'Found ' . scalar(keys(%files)) . " local videos\n";
  519. if ($DEBUG > 1) {
  520. print STDERR prettyPrint(\%files, "\t") . "\n";
  521. }
  522. }
  523. return \%files;
  524. }
  525. sub fetchParse($$) {
  526. my ($name, $id) = @_;
  527. my $url = $API{$name}{'prefix'} . $id . $API{$name}{'suffix'} . '?';
  528. foreach my $key (keys(%{ $API{$name}{'params'} })) {
  529. $url .= '&' . uri_escape($key) . '=' . uri_escape($API{$name}{'params'}{$key});
  530. }
  531. # Fetch
  532. if ($DEBUG) {
  533. print STDERR 'Fetching ' . $name . ' API URL: ' . $url . "\n";
  534. }
  535. sleep($DELAY);
  536. my $content = get($url);
  537. if (!defined($content) || length($content) < 10) {
  538. die('Invalid content from URL: ' . $url . "\n");
  539. }
  540. # Parse
  541. my $data = decode_json($content);
  542. if (!defined($data) || ref($data) ne 'HASH') {
  543. die('Invalid JSON: ' . $content . "\n");
  544. }
  545. if ($DEBUG > 2) {
  546. print STDERR "Raw JSON data:\n" . prettyPrint($data, ' ') . "\n";
  547. }
  548. return $data;
  549. }
  550. sub getSubscriptions($$) {
  551. my ($user, $id) = @_;
  552. my $index = 1;
  553. my $itemCount = undef();
  554. my %subs = ();
  555. SUBS_LOOP:
  556. {
  557. # Build, fetch, parse
  558. $API{'subscriptions'}{'params'}{'start-index'} = $index;
  559. my $data = fetchParse('subscriptions', $id);
  560. # It's all in the feed
  561. if (!exists($data->{'feed'}) || ref($data->{'feed'}) ne 'HASH') {
  562. die("Invalid subscription data\n");
  563. }
  564. $data = $data->{'feed'};
  565. # Grab the total count, so we know when to stop
  566. if (!defined($itemCount)) {
  567. if ( !exists($data->{'openSearch$totalResults'})
  568. || ref($data->{'openSearch$totalResults'}) ne 'HASH'
  569. || !exists($data->{'openSearch$totalResults'}->{'$t'}))
  570. {
  571. die("Invalid subscription feed metadata\n");
  572. }
  573. $itemCount = $data->{'openSearch$totalResults'}->{'$t'};
  574. }
  575. # Process each item
  576. if (!exists($data->{'entry'}) || ref($data->{'entry'}) ne 'ARRAY') {
  577. die("Invalid subscription entries\n");
  578. }
  579. my $items = $data->{'entry'};
  580. foreach my $item (@{$items}) {
  581. if ( ref($item) ne 'HASH'
  582. || !exists($item->{'yt$username'})
  583. || ref($item->{'yt$username'}) ne 'HASH'
  584. || !exists($item->{'yt$username'}->{'$t'}))
  585. {
  586. next;
  587. }
  588. if ($DEBUG) {
  589. print STDERR prettyPrint($item->{'yt$username'}, "\t") . "\n";
  590. }
  591. $subs{ $item->{'yt$username'}->{'$t'} } = $user;
  592. }
  593. # Loop if there are results left to fetch
  594. $index += $BATCH_SIZE;
  595. if (defined($itemCount) && $itemCount >= $index) {
  596. # But don't go past the max supported index
  597. if ($index <= $MAX_INDEX) {
  598. redo SUBS_LOOP;
  599. }
  600. }
  601. }
  602. # Return the list of subscribed usernames
  603. return \%subs;
  604. }
  605. sub saveSubscriptions($$) {
  606. my ($folder, $subs) = @_;
  607. # Check for local subscriptions missing from YT
  608. my %locals = ();
  609. my $fh = undef();
  610. opendir($fh, '.')
  611. or die('Unable to open subscriptions directory: ' . $folder . ': ' . $! . "\n");
  612. while (my $file = readdir($fh)) {
  613. # Skip dotfiles
  614. if ($file =~ /^\./) {
  615. next;
  616. }
  617. # Skip non-directories
  618. if (!-d $file) {
  619. next;
  620. }
  621. # YT has some trouble with case
  622. my $lcFile = lc($file);
  623. # Anything else should be in the list
  624. if (!$subs->{$file} && !$subs->{$lcFile}) {
  625. print STDERR 'Missing YT subscription for: ' . $file . "\n";
  626. }
  627. # Note local subscriptions
  628. $locals{$lcFile} = 1;
  629. }
  630. closedir($fh);
  631. # Check for YT subscriptions missing locally
  632. foreach my $sub (keys(%{$subs})) {
  633. if (!exists($locals{ lc($sub) })) {
  634. print STDERR 'Adding local subscription for: ' . $sub . ' (' . $subs->{$sub} . ")\n";
  635. mkdir($folder . '/' . $sub);
  636. }
  637. }
  638. }
  639. sub saveChannel($) {
  640. my ($channel) = @_;
  641. my $nfo = 'tvshow.nfo';
  642. if (!-e $nfo) {
  643. if ($DEBUG) {
  644. print STDERR 'Saving series data for: ' . $channel->{'title'} . "\n";
  645. }
  646. # Save the poster
  647. if (exists($channel->{'thumbnail'}) && length($channel->{'thumbnail'}) > 5) {
  648. my $jpg = get($channel->{'thumbnail'});
  649. saveString('poster.jpg', $jpg);
  650. }
  651. # Save the series NFO
  652. my $xml = buildSeriesNFO($channel);
  653. if ($DEBUG > 1) {
  654. print STDERR 'Saving NFO: ' . $xml . "\n";
  655. }
  656. saveString($nfo, $xml);
  657. }
  658. }
  659. sub getChannel($) {
  660. my ($user) = @_;
  661. # Build, fetch, parse
  662. my $data = fetchParse('channel', $user);
  663. if (!exists($data->{'entry'}) || ref($data->{'entry'}) ne 'HASH') {
  664. die("Invalid channel data\n");
  665. }
  666. $data = $data->{'entry'};
  667. # Extract the data we want
  668. my %channel = (
  669. 'id' => $data->{'yt$channelId'}->{'$t'},
  670. 'title' => $data->{'title'}->{'$t'},
  671. 'date' => str2time($data->{'published'}->{'$t'}),
  672. 'description' => $data->{'summary'}->{'$t'},
  673. 'thumbnail' => $data->{'media$thumbnail'}->{'url'},
  674. );
  675. return \%channel;
  676. }
  677. sub readExcludes() {
  678. my %excludes = ();
  679. # Read and parse the excludes videos file, if it exists
  680. if (-e $EXCLUDES_FILE) {
  681. my $fh;
  682. open($fh, $EXCLUDES_FILE)
  683. or die('Unable to open excludes videos file: ' . $! . "\n");
  684. while (<$fh>) {
  685. # Skip blank lines and comments
  686. if ($_ =~ /^\s*#/ || $_ =~ /^\s*$/) {
  687. next;
  688. }
  689. # Match our specific format or whine
  690. if ($_ =~ /^\s*([\w\-]+)\s*$/) {
  691. if ($DEBUG > 1) {
  692. print STDERR 'Adding exclude video: ' . $1 . "\n";
  693. }
  694. $excludes{$1} = 1;
  695. } else {
  696. print STDERR 'Skipped exclude video line: ' . $_;
  697. }
  698. }
  699. close($fh);
  700. }
  701. return \%excludes;
  702. }
  703. sub readExtras() {
  704. my %extras = ();
  705. # Read and parse the extra videos file, if it exists
  706. if (-e $EXTRAS_FILE) {
  707. my $fh;
  708. open($fh, $EXTRAS_FILE)
  709. or die('Unable to open extra videos file: ' . $! . "\n");
  710. while (<$fh>) {
  711. # Skip blank lines and comments
  712. if ($_ =~ /^\s*#/ || $_ =~ /^\s*$/) {
  713. next;
  714. }
  715. # Match our specific format or whine
  716. if ($_ =~ /^\s*([\w\-]+)\s*$/) {
  717. if ($DEBUG > 1) {
  718. print STDERR 'Adding extra video: ' . $1 . "\n";
  719. }
  720. $extras{$1} = 1;
  721. } else {
  722. print STDERR 'Skipped extra video line: ' . $_;
  723. }
  724. }
  725. close($fh);
  726. }
  727. return \%extras;
  728. }
  729. sub parseVideoData($) {
  730. my ($data) = @_;
  731. my %video = (
  732. 'title' => $data->{'title'},
  733. 'date' => str2time($data->{'uploaded'}),
  734. 'description' => $data->{'description'},
  735. 'duration' => $data->{'duration'},
  736. 'rating' => $data->{'rating'},
  737. 'creator' => $data->{'uploader'},
  738. );
  739. $video{'season'} = time2str('%Y', $video{'date'});
  740. return \%video;
  741. }
  742. sub findVideo($) {
  743. my ($id) = @_;
  744. # Build, fetch, parse
  745. my $data = fetchParse('video', $id);
  746. # Validate
  747. if (!exists($data->{'data'})) {
  748. die("Invalid video list\n");
  749. }
  750. $data = $data->{'data'};
  751. # Parse the video data
  752. return parseVideoData($data);
  753. }
  754. sub dropExcludes($) {
  755. my ($videos) = @_;
  756. my $excludes = readExcludes();
  757. foreach my $id (keys(%{$excludes})) {
  758. if (!exists($videos->{$id})) {
  759. if ($DEBUG > 1) {
  760. print STDERR 'Skipping unknown excludes video: ' . $id . "\n";
  761. }
  762. next;
  763. }
  764. delete($videos->{$id});
  765. }
  766. return $excludes;
  767. }
  768. sub addExtras($) {
  769. my ($videos) = @_;
  770. my $extras = readExtras();
  771. foreach my $id (keys(%{$extras})) {
  772. if (exists($videos->{$id})) {
  773. if ($DEBUG > 1) {
  774. print STDERR 'Skipping known extra video: ' . $id . "\n";
  775. }
  776. next;
  777. }
  778. my $video = findVideo($id);
  779. $videos->{$id} = $video;
  780. }
  781. return $extras;
  782. }
  783. sub findVideos($) {
  784. my ($user) = @_;
  785. my %videos = ();
  786. # Allow complete bypass
  787. if ($NO_SEARCH) {
  788. return \%videos;
  789. }
  790. # Loop through until we have all the entries
  791. my $index = 1;
  792. my $itemCount = undef();
  793. LOOP:
  794. {
  795. # Build, fetch, parse
  796. $API{'search'}{'params'}{'start-index'} = $index;
  797. my $data = fetchParse('search', $user);
  798. # Grab the total count, so we know when to stop
  799. if (!exists($data->{'data'})) {
  800. die("Invalid video list\n");
  801. }
  802. $data = $data->{'data'};
  803. if (!defined($itemCount) && exists($data->{'totalItems'})) {
  804. $itemCount = $data->{'totalItems'};
  805. }
  806. # Process each item
  807. if (!exists($data->{'items'}) || ref($data->{'items'}) ne 'ARRAY') {
  808. die("Invalid video list\n");
  809. }
  810. my $items = $data->{'items'};
  811. my $offset = 0;
  812. foreach my $item (@{$items}) {
  813. my $video = parseVideoData($item);
  814. $videos{ $item->{'id'} } = $video;
  815. $offset++;
  816. }
  817. # Loop if there are results left to fetch
  818. $index += $BATCH_SIZE;
  819. if (defined($itemCount) && $itemCount >= $index) {
  820. # But don't go past the max supported index
  821. if ($index <= $MAX_INDEX) {
  822. redo LOOP;
  823. }
  824. }
  825. }
  826. if ($DEBUG) {
  827. print STDERR 'Found ' . scalar(keys(%videos)) . " remote videos\n";
  828. if ($DEBUG > 1) {
  829. print STDERR prettyPrint(\%videos, "\t") . "\n";
  830. }
  831. }
  832. return \%videos;
  833. }
  834. sub updateNFOData($$$) {
  835. my ($file, $season, $episode) = @_;
  836. my $nfoData = undef();
  837. {
  838. open(my $fh, '<', $file)
  839. or warn('Unable to open NFO for renumber: ' . $file . ': ' . $! . "\n");
  840. $/ = undef;
  841. $nfoData = <$fh>;
  842. close($fh);
  843. }
  844. if ($nfoData) {
  845. $nfoData =~ s/<season>\d+<\/season>/<season>${season}<\/season>/;
  846. $nfoData =~ s/<episode>\d+<\/episode>/<episode>${episode}<\/episode>/;
  847. }
  848. return $nfoData;
  849. }
  850. sub videoSE($$) {
  851. my ($season, $episode) = @_;
  852. my $str = '';
  853. if ($season == 0 && $episode ~= /^(20[012]\d)(\d{2,4})$/) {
  854. $str = sprintf('S00E%04d%04d - ', $1, $2);
  855. } else {
  856. $str = sprintf('S%02dE%02d - ', $season, $episode);
  857. }
  858. return $str;
  859. }
  860. sub videoPath($$$$) {
  861. my ($season, $episode, $id, $ext) = @_;
  862. return videoSE($season, $episode) . $id . '.' . $ext;
  863. }
  864. sub renameVideo($$$$$$) {
  865. my ($video, $suffix, $nfo, $id, $season, $episode) = @_;
  866. # Bail if disabled
  867. if ($NO_RENAME) {
  868. print STDERR 'Not renaming: ' . $video . "\n";
  869. return;
  870. }
  871. # General sanity checks
  872. if (!defined($id) || !defined($season) || !defined($episode)) {
  873. die("Invalid call to renameVideo()\n\t" . $video . "\n\t" . $suffix . "\n\t" . $nfo . "\n\t" . $id . "\n\t" . $season . "\n\t" . $episode . "\n");
  874. }
  875. # Warning about useless calls
  876. if (!defined($nfo) && (!defined($video) || !defined($suffix))) {
  877. warn("No NFO or video path provided in renameVideo()\n");
  878. return;
  879. }
  880. # Video
  881. if (defined($video) && defined($suffix)) {
  882. my $videoNew = videoPath($season, $episode, $id, $suffix);
  883. # Sanity checks, as we do dangerous work here
  884. if (!-r $video) {
  885. die('Invalid video source in rename: ' . $video . "\n");
  886. }
  887. if ($video ne $videoNew) {
  888. print STDERR 'Renaming ' . $video . ' => ' . $videoNew . "\n";
  889. if (-e $videoNew) {
  890. die('Rename: Target exists: ' . $videoNew . "\n");
  891. }
  892. if ($SUDO_CHATTR) {
  893. system('sudo', 'chattr', '-i', $video);
  894. }
  895. rename($video, $videoNew)
  896. or die('Unable to rename: ' . $video . ': ' . $! . "\n");
  897. }
  898. }
  899. # NFO
  900. if (defined($nfo)) {
  901. my $nfoNew = videoPath($season, $episode, $id, 'nfo');
  902. # Sanity checks, as we do dangerous work here
  903. if (!-r $nfo) {
  904. die('Invalid NFO source in rename: ' . $nfo . "\n");
  905. }
  906. # Parse old NFO data
  907. my $nfoData = updateNFOData($nfo, $season, $episode)
  908. or die('No NFO data found, refusing to rename: ' . $id . "\n");
  909. # Write a new NFO and unlink the old one
  910. if ($SUDO_CHATTR) {
  911. system('sudo', 'chattr', '-i', $nfo);
  912. }
  913. saveString($nfoNew, $nfoData);
  914. if ($nfo ne $nfoNew) {
  915. print STDERR 'Renaming ' . $nfo . ' => ' . $nfoNew . "\n";
  916. unlink($nfo)
  917. or warn('Unable to delete NFO during rename: ' . $! . "\n");
  918. }
  919. }
  920. }
  921. sub parseFilename($) {
  922. my ($file) = @_;
  923. return $file =~ /^S(\d+)+E(\d+) - ([\w\-]+)\.(\w\w\w)$/i;
  924. }