subscribe.pl 36 KB

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