subscribe.pl 34 KB

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