subscribe.pl 35 KB

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