subscribe.pl 29 KB

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