subscribe.pl 34 KB

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