subscribe.pl 34 KB

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