subscribe.pl 31 KB

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