subscribe.pl 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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 $elm;
  398. # Add data
  399. $elm = $doc->createElement('season');
  400. $elm->appendText($video->{'season'});
  401. $show->appendChild($elm);
  402. $elm = $doc->createElement('episode');
  403. $elm->appendText($video->{'number'});
  404. $show->appendChild($elm);
  405. if (!defined($video->{'title'})) {
  406. $video->{'title'} = 'Episode ' . $video->{'number'};
  407. }
  408. $elm = $doc->createElement('title');
  409. $elm->appendText($video->{'title'});
  410. $show->appendChild($elm);
  411. if (!defined($video->{'date'})) {
  412. $video->{'date'} = time();
  413. }
  414. $elm = $doc->createElement('aired');
  415. $elm->appendText(time2str('%Y-%m-%d', $video->{'date'}));
  416. $show->appendChild($elm);
  417. if (defined($video->{'description'})) {
  418. $elm = $doc->createElement('plot');
  419. $elm->appendText($video->{'description'});
  420. $show->appendChild($elm);
  421. }
  422. if (defined($video->{'duration'})) {
  423. $elm = $doc->createElement('durationinseconds');
  424. $elm->appendText($video->{'duration'});
  425. $show->appendChild($elm);
  426. }
  427. if (defined($video->{'rating'})) {
  428. $elm = $doc->createElement('rating');
  429. $elm->appendText($video->{'rating'});
  430. $show->appendChild($elm);
  431. }
  432. if (defined($video->{'creator'})) {
  433. $elm = $doc->createElement('director');
  434. $elm->appendText($video->{'creator'});
  435. $show->appendChild($elm);
  436. }
  437. # Return the string
  438. return $doc->toString();
  439. }
  440. sub findFiles() {
  441. my %files = ();
  442. # Allow complete bypass
  443. if ($NO_FILES) {
  444. return \%files;
  445. }
  446. # Read the output directory
  447. my $fh = undef();
  448. opendir($fh, '.')
  449. or die('Unable to open files directory: ' . $! . "\n");
  450. while (my $file = readdir($fh)) {
  451. my ($season, $num, $id, $suffix) = $file =~ /^S(\d+)+E(\d+) - ([\w\-]+)\.(\w\w\w)$/i;
  452. if (defined($id) && length($id) > 0) {
  453. if ($suffix eq 'nfo') {
  454. next;
  455. }
  456. my %tmp = (
  457. 'season' => $season,
  458. 'number' => $num,
  459. 'suffix' => $suffix,
  460. 'path' => $file,
  461. );
  462. $tmp{'nfo'} = $tmp{'path'};
  463. $tmp{'nfo'} =~ s/\.\w\w\w$/\.nfo/;
  464. if (exists($files{$id})) {
  465. warn('Duplicate ID: ' . $id . "\n\t" . $files{$id}->{'path'} . "\n\t" . $tmp{'path'} . "\n");
  466. if (!$NO_RENAME) {
  467. # Prefer to delete MP4 files, if the suffixes differ
  468. my $del = $files{$id};
  469. if ($tmp{'suffix'} eq 'mp4' && $del->{'suffix'} ne 'mp4') {
  470. $del = \%tmp;
  471. %tmp = %{ $files{$id} };
  472. }
  473. print STDERR 'Deleting duplicate: ' . $del->{'path'} . "\n";
  474. unlink($del->{'path'});
  475. if ($del->{'nfo'} ne $tmp{'nfo'}) {
  476. unlink($del->{'nfo'});
  477. }
  478. }
  479. }
  480. $files{$id} = \%tmp;
  481. }
  482. }
  483. close($fh);
  484. if ($DEBUG) {
  485. print STDERR 'Found ' . scalar(keys(%files)) . " local videos\n";
  486. if ($DEBUG > 1) {
  487. print STDERR prettyPrint(\%files, "\t") . "\n";
  488. }
  489. }
  490. return \%files;
  491. }
  492. sub fetchParse($$) {
  493. my ($name, $id) = @_;
  494. my $url = $API{$name}{'prefix'} . $id . $API{$name}{'suffix'} . '?';
  495. foreach my $key (keys(%{ $API{$name}{'params'} })) {
  496. $url .= '&' . uri_escape($key) . '=' . uri_escape($API{$name}{'params'}{$key});
  497. }
  498. # Fetch
  499. if ($DEBUG) {
  500. print STDERR 'Fetching ' . $name . ' API URL: ' . $url . "\n";
  501. }
  502. sleep($DELAY);
  503. my $content = get($url);
  504. if (!defined($content) || length($content) < 10) {
  505. die('Invalid content from URL: ' . $url . "\n");
  506. }
  507. # Parse
  508. my $data = decode_json($content);
  509. if (!defined($data) || ref($data) ne 'HASH') {
  510. die('Invalid JSON: ' . $content . "\n");
  511. }
  512. if ($DEBUG > 2) {
  513. print STDERR "Raw JSON data:\n" . prettyPrint($data, ' ') . "\n";
  514. }
  515. return $data;
  516. }
  517. sub getSubscriptions($$) {
  518. my ($user, $id) = @_;
  519. my $index = 1;
  520. my $itemCount = undef();
  521. my %subs = ();
  522. SUBS_LOOP:
  523. {
  524. # Build, fetch, parse
  525. $API{'subscriptions'}{'params'}{'start-index'} = $index;
  526. my $data = fetchParse('subscriptions', $id);
  527. # It's all in the feed
  528. if (!exists($data->{'feed'}) || ref($data->{'feed'}) ne 'HASH') {
  529. die("Invalid subscription data\n");
  530. }
  531. $data = $data->{'feed'};
  532. # Grab the total count, so we know when to stop
  533. if (!defined($itemCount)) {
  534. if ( !exists($data->{'openSearch$totalResults'})
  535. || ref($data->{'openSearch$totalResults'}) ne 'HASH'
  536. || !exists($data->{'openSearch$totalResults'}->{'$t'}))
  537. {
  538. die("Invalid subscription feed metadata\n");
  539. }
  540. $itemCount = $data->{'openSearch$totalResults'}->{'$t'};
  541. }
  542. # Process each item
  543. if (!exists($data->{'entry'}) || ref($data->{'entry'}) ne 'ARRAY') {
  544. die("Invalid subscription entries\n");
  545. }
  546. my $items = $data->{'entry'};
  547. foreach my $item (@{$items}) {
  548. if ( ref($item) ne 'HASH'
  549. || !exists($item->{'yt$username'})
  550. || ref($item->{'yt$username'}) ne 'HASH'
  551. || !exists($item->{'yt$username'}->{'$t'}))
  552. {
  553. next;
  554. }
  555. if ($DEBUG) {
  556. print STDERR prettyPrint($item->{'yt$username'}, "\t") . "\n";
  557. }
  558. $subs{ $item->{'yt$username'}->{'$t'} } = $user;
  559. }
  560. # Loop if there are results left to fetch
  561. $index += $BATCH_SIZE;
  562. if (defined($itemCount) && $itemCount >= $index) {
  563. # But don't go past the max supported index
  564. if ($index <= $MAX_INDEX) {
  565. redo SUBS_LOOP;
  566. }
  567. }
  568. }
  569. # Return the list of subscribed usernames
  570. return \%subs;
  571. }
  572. sub saveSubscriptions($$) {
  573. my ($folder, $subs) = @_;
  574. # Check for local subscriptions missing from YT
  575. my %locals = ();
  576. my $fh = undef();
  577. opendir($fh, '.')
  578. or die('Unable to open subscriptions directory: ' . $folder . ': ' . $! . "\n");
  579. while (my $file = readdir($fh)) {
  580. # Skip dotfiles
  581. if ($file =~ /^\./) {
  582. next;
  583. }
  584. # Skip non-directories
  585. if (!-d $file) {
  586. next;
  587. }
  588. # YT has some trouble with case
  589. my $lcFile = lc($file);
  590. # Anything else should be in the list
  591. if (!$subs->{$file} && !$subs->{$lcFile}) {
  592. print STDERR 'Missing YT subscription for: ' . $file . "\n";
  593. }
  594. # Note local subscriptions
  595. $locals{$lcFile} = 1;
  596. }
  597. closedir($fh);
  598. # Check for YT subscriptions missing locally
  599. foreach my $sub (keys(%{$subs})) {
  600. if (!exists($locals{ lc($sub) })) {
  601. print STDERR 'Adding local subscription for: ' . $sub . ' (' . $subs->{$sub} . ")\n";
  602. mkdir($folder . '/' . $sub);
  603. }
  604. }
  605. }
  606. sub saveChannel($) {
  607. my ($channel) = @_;
  608. my $nfo = 'tvshow.nfo';
  609. if (!-e $nfo) {
  610. if ($DEBUG) {
  611. print STDERR 'Saving series data for: ' . $channel->{'title'} . "\n";
  612. }
  613. # Save the poster
  614. if (exists($channel->{'thumbnail'}) && length($channel->{'thumbnail'}) > 5) {
  615. my $jpg = get($channel->{'thumbnail'});
  616. saveString('poster.jpg', $jpg);
  617. }
  618. # Save the series NFO
  619. my $xml = buildSeriesNFO($channel);
  620. if ($DEBUG > 1) {
  621. print STDERR 'Saving NFO: ' . $xml . "\n";
  622. }
  623. saveString($nfo, $xml);
  624. }
  625. }
  626. sub getChannel($) {
  627. my ($user) = @_;
  628. # Build, fetch, parse
  629. my $data = fetchParse('channel', $user);
  630. if (!exists($data->{'entry'}) || ref($data->{'entry'}) ne 'HASH') {
  631. die("Invalid channel data\n");
  632. }
  633. $data = $data->{'entry'};
  634. # Extract the data we want
  635. my %channel = (
  636. 'id' => $data->{'yt$channelId'}->{'$t'},
  637. 'title' => $data->{'title'}->{'$t'},
  638. 'date' => str2time($data->{'published'}->{'$t'}),
  639. 'description' => $data->{'summary'}->{'$t'},
  640. 'thumbnail' => $data->{'media$thumbnail'}->{'url'},
  641. );
  642. return \%channel;
  643. }
  644. sub readExcludes() {
  645. my %excludes = ();
  646. # Read and parse the excludes videos file, if it exists
  647. if (-e $EXCLUDES_FILE) {
  648. my $fh;
  649. open($fh, $EXCLUDES_FILE)
  650. or die('Unable to open excludes videos file: ' . $! . "\n");
  651. while (<$fh>) {
  652. # Skip blank lines and comments
  653. if ($_ =~ /^\s*#/ || $_ =~ /^\s*$/) {
  654. next;
  655. }
  656. # Match our specific format or whine
  657. if ($_ =~ /^\s*([\w\-]+)\s*$/) {
  658. if ($DEBUG > 1) {
  659. print STDERR 'Adding exclude video: ' . $1 . "\n";
  660. }
  661. $excludes{$1} = 1;
  662. } else {
  663. print STDERR 'Skipped exclude video line: ' . $_;
  664. }
  665. }
  666. close($fh);
  667. }
  668. return \%excludes;
  669. }
  670. sub readExtras() {
  671. my %extras = ();
  672. # Read and parse the extra videos file, if it exists
  673. if (-e $EXTRAS_FILE) {
  674. my $fh;
  675. open($fh, $EXTRAS_FILE)
  676. or die('Unable to open extra videos file: ' . $! . "\n");
  677. while (<$fh>) {
  678. # Skip blank lines and comments
  679. if ($_ =~ /^\s*#/ || $_ =~ /^\s*$/) {
  680. next;
  681. }
  682. # Match our specific format or whine
  683. if ($_ =~ /^\s*(\d+)\s*[=:>]+\s*([\w\-]+)\s*$/) {
  684. if ($DEBUG > 1) {
  685. print STDERR 'Adding extra video: ' . $1 . ' => ' . $2 . "\n";
  686. }
  687. $extras{$2} = $1;
  688. } else {
  689. print STDERR 'Skipped extra video line: ' . $_;
  690. }
  691. }
  692. close($fh);
  693. }
  694. return \%extras;
  695. }
  696. sub parseVideoData($) {
  697. my ($data) = @_;
  698. my %video = (
  699. 'title' => $data->{'title'},
  700. 'date' => str2time($data->{'uploaded'}),
  701. 'description' => $data->{'description'},
  702. 'duration' => $data->{'duration'},
  703. 'rating' => $data->{'rating'},
  704. 'creator' => $data->{'uploader'},
  705. );
  706. $video{'season'} = time2str('%Y', $video{'date'});
  707. return \%video;
  708. }
  709. sub findVideo($) {
  710. my ($id) = @_;
  711. # Build, fetch, parse
  712. my $data = fetchParse('video', $id);
  713. # Validate
  714. if (!exists($data->{'data'})) {
  715. die("Invalid video list\n");
  716. }
  717. $data = $data->{'data'};
  718. # Parse the video data
  719. return parseVideoData($data);
  720. }
  721. sub dropExcludes($) {
  722. my ($videos) = @_;
  723. my $excludes = readExcludes();
  724. foreach my $id (keys(%{$excludes})) {
  725. if (!exists($videos->{$id})) {
  726. if ($DEBUG > 1) {
  727. print STDERR 'Skipping unknown excludes video: ' . $id . "\n";
  728. }
  729. next;
  730. }
  731. delete($videos->{$id});
  732. }
  733. return $excludes;
  734. }
  735. sub addExtras($) {
  736. my ($videos) = @_;
  737. my $extras = readExtras();
  738. foreach my $id (keys(%{$extras})) {
  739. if (exists($videos->{$id})) {
  740. if ($DEBUG > 1) {
  741. print STDERR 'Skipping known extra video: ' . $id . "\n";
  742. }
  743. next;
  744. }
  745. my $video = findVideo($id);
  746. $videos->{$id} = $video;
  747. }
  748. return $extras;
  749. }
  750. sub findVideos($) {
  751. my ($user) = @_;
  752. my %videos = ();
  753. # Allow complete bypass
  754. if ($NO_SEARCH) {
  755. return \%videos;
  756. }
  757. # Loop through until we have all the entries
  758. my $index = 1;
  759. my $itemCount = undef();
  760. LOOP:
  761. {
  762. # Build, fetch, parse
  763. $API{'search'}{'params'}{'start-index'} = $index;
  764. my $data = fetchParse('search', $user);
  765. # Grab the total count, so we know when to stop
  766. if (!exists($data->{'data'})) {
  767. die("Invalid video list\n");
  768. }
  769. $data = $data->{'data'};
  770. if (!defined($itemCount) && exists($data->{'totalItems'})) {
  771. $itemCount = $data->{'totalItems'};
  772. }
  773. # Process each item
  774. if (!exists($data->{'items'}) || ref($data->{'items'}) ne 'ARRAY') {
  775. die("Invalid video list\n");
  776. }
  777. my $items = $data->{'items'};
  778. my $offset = 0;
  779. foreach my $item (@{$items}) {
  780. my $video = parseVideoData($item);
  781. $videos{ $item->{'id'} } = $video;
  782. $offset++;
  783. }
  784. # Loop if there are results left to fetch
  785. $index += $BATCH_SIZE;
  786. if (defined($itemCount) && $itemCount >= $index) {
  787. # But don't go past the max supported index
  788. if ($index <= $MAX_INDEX) {
  789. redo LOOP;
  790. }
  791. }
  792. }
  793. if ($DEBUG) {
  794. print STDERR 'Found ' . scalar(keys(%videos)) . " remote videos\n";
  795. if ($DEBUG > 1) {
  796. print STDERR prettyPrint(\%videos, "\t") . "\n";
  797. }
  798. }
  799. return \%videos;
  800. }
  801. sub updateNFOData($$$) {
  802. my ($file, $season, $episode) = @_;
  803. my $nfoData = undef();
  804. {
  805. open(my $fh, '<', $file)
  806. or warn('Unable to open NFO for renumber: ' . $file . ': ' . $! . "\n");
  807. $/ = undef;
  808. $nfoData = <$fh>;
  809. close($fh);
  810. }
  811. if ($nfoData) {
  812. $nfoData =~ s/<season>\d+<\/season>/<season>${season}<\/season>/;
  813. $nfoData =~ s/<episode>\d+<\/episode>/<episode>${episode}<\/episode>/;
  814. }
  815. return $nfoData;
  816. }
  817. sub videoSE($$) {
  818. my ($season, $episode) = @_;
  819. return sprintf('S%02dE%02d - ', $season, $episode);
  820. }
  821. sub videoPath($$$$) {
  822. my ($season, $episode, $id, $ext) = @_;
  823. return videoSE($season, $episode) . $id . '.' . $ext;
  824. }
  825. sub renameVideo($$$$$) {
  826. my ($video, $suffix, $id, $season, $episode) = @_;
  827. # Bail if disabled
  828. if ($NO_RENAME) {
  829. print STDERR 'Not renaming: ' . $video . "\n";
  830. return;
  831. }
  832. # General sanity checks
  833. if (!defined($video) || !defined($suffix) || !defined($id) || !defined($season) || !defined($episode)) {
  834. die("Invalid call to renameVideo()\n\t" . $video . "\n\t" . $suffix . "\n\t" . $id . "\n\t" . $season . "\n\t" . $episode . "\n");
  835. }
  836. # We could ask for this but there are already a lot of parameters
  837. my $nfo = $video;
  838. $nfo =~ s/\.${suffix}$/\.nfo/;
  839. # Build a new path
  840. my $videoNew = videoPath($season, $episode, $id, $suffix);
  841. my $nfoNew = videoPath($season, $episode, $id, 'nfo');
  842. print STDERR 'Renaming ' . $video . ' => ' . $videoNew . "\n";
  843. # Parse old NFO data
  844. my $nfoData = updateNFOData($nfo, $season, $episode)
  845. or die('No NFO data found, refusing to rename: ' . $id . "\n");
  846. # Specific sanity checks, as we do dangerous work here
  847. if (!-r $video || !-r $nfo) {
  848. die('Invalid video or NFO sources in rename: ' . $video . '/' . $nfo);
  849. }
  850. if (-e $videoNew) {
  851. die('Rename: Target exists: ' . $videoNew . "\n");
  852. }
  853. # Rename video
  854. if ($SUDO_CHATTR) {
  855. system('sudo', 'chattr', '-i', $video);
  856. }
  857. rename($video, $videoNew)
  858. or die('Unable to rename: ' . $video . ': ' . $! . "\n");
  859. # Write a new NFO and unlink the old one
  860. saveString($nfoNew, $nfoData);
  861. if ($SUDO_CHATTR) {
  862. system('sudo', 'chattr', '-i', $nfo);
  863. }
  864. unlink($nfo)
  865. or warn('Unable to delete NFO during rename: ' . $! . "\n");
  866. }