subscribe.pl 32 KB

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