subscribe.pl 24 KB

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