subscribe.pl 34 KB

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