subscribe.pl 34 KB

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