subscribe.pl 29 KB

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