subscribe.pl 24 KB

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