subscribe.pl 34 KB

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