subscribe.pl 33 KB

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