subscribe.pl 25 KB

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