1 # library to autodownload flash videos
3 # (c) 2007-2008 by Ralf Ertzinger <ralf@camperquake.de>
4 # licensed under GNU GPL v2
6 # Based on youtube.pl by Christian Garbs <mitch@cgarbs.de>
8 # based on trigger.pl by Wouter Coekaerts <wouter@coekaerts.be>
13 use vars qw(@ISA @EXPORT_OK);
23 @EXPORT_OK = qw(init register_api check_for_link);
31 my %builtin_config = ();
35 # The default config. These values will be set in the config
36 # if they do not exist already.
39 'getter' => 'filegetter',
41 'active-connectors' => 'direct',
42 'defined-connectors' => 'direct',
53 # List of known commands and handlers
55 my $videosite_commands = {
98 foreach (@grabbers, @getters) {
101 _io('Enabled debugging');
106 foreach (@grabbers, @getters) {
109 _io('Disabled debugging');
114 # This is a list of default values for the remote API. These
115 # are used if the values are not registered by the library user.
118 io => sub { print @_, "\n" },
119 config_init => \&_builtin_config_init,
120 config_get => \&_builtin_config_get,
121 config_set => \&_builtin_config_set,
122 config_has => \&_builtin_config_has,
123 config_save => \&_builtin_config_save,
124 config_del => \&_builtin_config_del,
125 color => sub { return '' },
126 module_path => sub { return dirname(realpath($0)) },
127 quote => sub { return $_ },
131 # Output a string on the client.
132 # Works like (s)printf in that it takes a format string and a list of
133 # values to be replaced. Undefined values will be printed as '(undef)'
135 # All parameters (except for the format string itself) will be quoted
136 # using the client specific quote function
142 @text = ('') unless(@text);
144 # This will define the outputprefix once, so we don't have
145 # do do this every time.
146 $outputprefix = sprintf("%svideosite: %s",
147 $remote_api->{color}->('magenta'),
148 $remote_api->{color}->()) unless(defined($outputprefix));
149 $format = $outputprefix . shift(@text);
152 # The format string is assumed to be appropriately quoted.
153 # Quote the rest of the text, replacing undefined strings by (undef)
155 @text = map { defined($_)?$remote_api->{quote}->($_):'(undef)' } @text;
157 $outputstack[0]->(sprintf($format, @text));
161 # Recursively walk through a hash-of-hashes, calling the given function
162 # for each found leaf with the path to the leaf
164 sub _recursive_hash_walk {
166 my $callback = shift;
169 foreach (keys(%{$hash})) {
170 if (ref($hash->{$_}) eq 'HASH') {
171 _recursive_hash_walk($hash->{$_}, $callback, @path, $_);
173 $callback->([@path, $_], $hash->{$_});
179 # Return the color code for the given foreground/background color
180 # pair. Both can be undef, which means "default"
185 return $remote_api->{color}->($fg, $bg);
189 # Sets the given config item if it is not set already
191 sub _init_config_item {
195 unless($remote_api->{config_has}->($path)) {
196 $remote_api->{config_set}->($path, $value);
201 # Print a message if debug is enabled
210 # Load a list of modules matching a pattern from a given directory.
222 opendir(D, $dir) || return ();
223 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
227 _debug("Trying to load $p:");
230 load "videosite::$p";
233 _io("Failed to load plugin: $@");
238 $g = "videosite::$p"->new();
241 _io("Failed to instanciate: $@");
246 _debug("found $g->{'TYPE'} $g->{'NAME'}");
247 if ($type eq $g->{'TYPE'}) {
251 connectors => sub { return _connectorlist('active-connectors') },
252 config_get => \&_config_get,
253 config_set => \&_config_set,
254 config_has => \&_config_has,
256 $g->setdebug($debug);
258 _io('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
263 _debug("Loaded %d plugins", $#g+1);
269 # Populate the @grabbers and @getters lists from the given
272 sub _load_modules($) {
276 foreach (keys(%INC)) {
277 if ($INC{$_} =~ m|^$path|) {
278 _debug("Removing %s from \$INC", $_);
282 @grabbers = _ploader($path, '.*Grabber\.pm$', 'grabber');
283 @getters = _ploader($path, '.*Getter\.pm$', 'getter');
287 # Wrapper functions for config management to put in
294 $value = $remote_api->{config_get}->($path);
295 _debug("config: getting %s=%s", join('.', @{$path}), $value);
304 _debug("config: setting %s=%s", join('.', @{$path}), $value);
305 return $remote_api->{config_set}->($path, $value);
312 $b = $remote_api->{config_has}->($path);
313 _debug("config: testing %s (%s)", join('.', @{$path}), $b?'true':'false');
319 # The _config_list_* are helper functions taking a path to a comma separated
320 # string. The string is interpreted as a list and the action performed
321 # on it, storing back the modified version
325 # Add an item to the list, checking for duplicates
327 sub _config_list_add {
332 if (_config_has($path)) {
333 @c = split(/\s*,\s*/, _config_get($path));
338 _debug("Adding %s to list %s", $item, join(".", $path));
339 unless(grep { $_ eq $item } @c) {
343 _config_set($path, join(',', @c));
347 # Remove an item from the list
349 sub _config_list_del {
354 unless(_config_has($path)) {
358 _debug("Removing %s from list %s", $item, join('.', $path));
359 @c = map { $item ne $_ } split(/\s*,\s*/, _config_get($path));
361 _config_set($path, join('.', @c));
365 # Return true if the item contains the given list, false otherwise
367 sub _config_list_has {
371 unless(_config_has($path)) {
375 _debug("Checking for %s in list %s", $item, join('.', $path));
377 return grep { $item eq $_ } split(/\s*,\s*/, _config_get($path));
381 # Replace a list with the given items
383 sub _config_list_set {
386 _debug("Replacing %s with (%s)", join('.', $path), join(",", @_));
388 _config_set($path, join(',', @_));
392 # Return the list of currently active connectors, in the configured
399 foreach(split(/,/, _config_get([$key]))) {
400 push(@c, _unserialize_connector_hash($_));
407 # Convert a connector hash from it's config structure back to a perl
410 sub _unserialize_connector_hash {
414 if (_config_has(['connectors', $name, 'name'])) {
415 $connector->{name} = _config_get(['connectors', $name, 'name']);
416 $connector->{schemas} = {};
417 foreach ('http', 'https') {
418 if (_config_has(['connectors', $name, 'schemas', $_])) {
419 $connector->{schemas}->{$_} = _config_get(['connectors', $name, 'schemas', $_]);
424 _debug("Returning connector %s: %s", $name, Dumper($connector));
430 # Push a new output function on the IO stack.
433 unshift(@outputstack, shift);
437 # Pop the topmost output function from the stack, leaving
438 # at least one function on it.
441 if (scalar(@outputstack) > 0) {
447 # Takes a string and replaces commonly used URL shorteners recursively,
448 # up to 10 levels deep
450 sub _expand_url_shortener {
454 'is\.gd/[[:alnum:]]+',
455 'otf\.me/[[:alnum:]]+',
456 'hel\.me/[[:alnum:]]+',
457 '7ax\.de/[[:alnum:]]+',
458 'ow\.ly/[[:alnum:]]+',
459 'j\.mp/[[:alnum:]]+',
460 'bit\.ly/[[:alnum:]]+',
461 'tinyurl\.com/[[:alnum:]]+',
462 'pop\.is/[[:alnum:]]+',
463 'post\.ly/[[:alnum:]]+',
464 '1\.ly/[[:alnum:]]+',
465 '2\.ly/[[:alnum:]]+',
466 't\.co/[[:alnum:]]+',
467 'shar\.es/[[:alnum:]]+',
468 'goo\.gl/[[:alnum:]]+',
470 my $ua = LWP::UserAgent->new(agent => 'Mozilla', max_redirect => 0, timeout => 5);
473 OUTER: while (($os ne $s) and ($i > 0)) {
478 foreach my $pattern (@urlshortener) {
479 my $p = "https?:\/\/" . $pattern;
481 _debug("Matching %s against %s", $p, $s);
486 _debug("Found %s", $matched);
487 $res = $ua->head($matched);
488 if ($res->is_redirect()) {
489 my $new = $res->headers()->header("Location");
491 _debug("Replacing %s with %s", $matched, $new);
492 $s =~ s/$matched/$new/;
495 _debug("Error resolving %s", $matched);
502 _debug("Loop terminated by counter");
505 _debug("Final string: %s", $s);
511 # Save the config to durable storage
514 $remote_api->{config_save}->();
518 # Set a configuration element
526 foreach $p (@getters, @grabbers) {
527 if ($p->{'NAME'} eq $target) {
528 $p->setval($key, $val);
532 _io('No such module');
537 # Enable a given module
543 foreach $p (@grabbers) {
544 if ($p->{'NAME'} eq $target) {
549 _io('No such module');
553 # Disable given module
559 foreach $p (@grabbers) {
560 if ($p->{'NAME'} eq $target) {
565 _io('No such module');
569 # Show settings for modules
576 if (defined($target)) {
577 foreach $p (@getters, @grabbers) {
578 if ($p->{'NAME'} eq $target) {
579 _io($p->getconfstr());
583 _io('No such module');
585 _io('Loaded grabbers (* denotes enabled modules):');
586 foreach $p (@grabbers) {
587 $e = $p->_getval('enabled');
588 _io(' %s%s', $p->{'NAME'}, $e?'*':'');
591 _io('Loaded getters:');
592 foreach $p (@getters) {
593 _io(' %s', $p->{'NAME'});
599 # Show help for the commands
605 if (defined($target)) {
606 foreach $p (@getters, @grabbers) {
607 if ($p->{'NAME'} eq $target) {
608 _io($p->gethelpstr());
612 _io('No such module');
616 save: save the current configuration
617 help [modulename]: display this help, or module specific help
618 show [modulename]: show loaded modules, or the current parameters of a module
619 set modulename parameter value: set a module parameter to a new value
620 getter [modulename]: display or set the getter to use
621 enable [modulename]: enable the usage of this module (grabbers only)
622 disable [modulename]: disable the usage of this module (grabbers only)
623 reload: reload all modules (this is somewhat experimental)
624 mode [modename]: display or set the operation mode (download/display)
625 connector [subcommand]: manage connectors (proxies)
626 debug: enable debugging messages
627 nodebug: disable debugging messages
633 # Set the getter to use
639 if (defined($target)) {
640 foreach $p (@getters) {
641 if ($p->{'NAME'} eq $target) {
643 _config_set(['getter'], $target);
644 _io("Getter changed to %s", $target);
648 _io('No such getter');
650 _io('Current getter: %s', _config_get(['getter']));
655 # Show/set the working mode
660 if (defined($mode)) {
662 if (('download' eq $mode) or ('display' eq $mode)) {
663 _config_set(['mode'], $mode);
664 _io('Now using %s mode', $mode);
666 _io('Invalid mode: %s', $mode);
669 _io('Current mode: %s', _config_get(['mode']));
675 # Manage the connectors
681 unless(defined($subcmd)) {
685 $subcmd = lc($subcmd);
687 if ($subcmd eq 'list') {
688 _io("Defined connectors");
689 foreach $c (_connectorlist('defined-connectors')) {
691 my $schemas = $c->{schemas};
692 if (scalar(keys(%{$schemas})) == 0) {
693 _io(" No schemas defined");
695 foreach (keys(%{$schemas})) {
696 _io(' %s: %s', $_, $schemas->{$_});
702 _io("Selected connectors: %s", _config_get(['active-connectors']));
703 } elsif ($subcmd eq 'add') {
706 unless(defined($name)) {
707 _io("No name given");
713 if (_config_list_has(['defined-connectors'], $name)) {
714 _io("Connector already exists");
718 _config_set(['connectors', $name, 'name'], $name);
719 _config_list_add(['defined-connectors'], $name);
720 } elsif ($subcmd eq 'del') {
724 unless(defined($name)) {
725 _io("No name given");
729 unless (_config_list_has(['defined-connectors'])) {
730 _io("Connector does not exist");
734 if (_config_has(['connectors', $name, '_immutable'])) {
735 _io("Connector cannot be removed");
739 # Remove from list of active connectors
740 _config_list_del(['defined-connectors'], $name);
741 _config_list_del(['active-connectors'], $name);
743 _config_del(['connectors', $name, 'name']);
744 _config_del(['connectors', $name, '_immutable']);
745 _config_del(['connectors', $name, 'schemas', 'http']);
746 _config_del(['connectors', $name, 'schemas', 'https']);
748 @dcon = split(/,/, _config_get(['active-connectors']));
750 if (scalar(@dcon) == 0) {
751 _io("List of selected connectors is empty, resetting to direct");
752 _config_list_add(['active-connectors', 'direct']);
754 } elsif ($subcmd eq 'addschema') {
755 my ($conn, $schema, $proxy) = @_;
757 unless(defined($conn)) {
758 _io("No connector name given");
762 unless(defined($schema)) {
763 _io("No schema given");
767 unless(defined($proxy)) {
768 _io("No proxy given");
773 unless(_config_list_has(['defined-connectors'], $conn)) {
774 _io("Connector does not exist");
778 if (_config_has(['connectors', $conn, '_immutable'])) {
779 _io("Connector cannot be modified");
783 $schema = lc($schema);
784 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
785 } elsif ($subcmd eq 'delschema') {
786 my ($conn, $schema) = @_;
788 unless(defined($conn)) {
789 _io("No connector name given");
793 unless(defined($schema)) {
794 _io("No schema given");
799 unless(_config_list_has(['defined-connectors'], $conn)) {
800 _io("Connector does not exist");
804 $schema = lc($schema);
805 _config_del(['connectors', $conn, 'schemas', $schema]);
806 } elsif ($subcmd eq 'select') {
807 my @connlist = map { lc } @_;
809 if (scalar(@connlist) == 0) {
810 _io("No connectors given");
814 foreach (@connlist) {
815 unless(_config_list_has(['defined-connectors'], $_)) {
816 _io("Connector %s does not exist", $_);
821 _config_list_set(['active-connectors'], @connlist);
823 _io("connector [list|add|del|addschema|delschema|help] <options>");
824 _io(" help: Show this help");
825 _io(" list: List the defined connectors");
826 _io(" add <name>: Add a connector with name <name>");
827 _io(" del <name>: Delete the connector with name <name>");
828 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
829 _io(" delschema <name> <schema>: Remove the schema from the connector");
830 _io(" select <name> [<name>...]: Select the connectors to use");
835 # Return the list of loaded grabbers.
836 # This is used by the test programs, and is not meant to be
844 # ==============================================
845 # Builtin config handling functions
846 # These are used if the library used does not
847 # register it's own config_* handlers
848 # ==============================================
850 sub _builtin_config_init {
853 sub _builtin_config_get {
854 return $builtin_config{join(".", @{$_[0]})};
857 sub _builtin_config_set {
858 $builtin_config{join(".", @{$_[0]})} = $_[1];
861 sub _builtin_config_has {
862 return exists($builtin_config{join(".", @{$_[0]})});
865 sub _builtin_config_save {
868 sub _builtin_config_del {
869 delete($builtin_config{join(".", @{$_[0]})});
873 # ==============================================
874 # From this point on publicly callable functions
875 # ==============================================
880 # Initialization function for the library
881 # Actually not the first thing to be called, it expects an API
882 # has (register_api) to be registered first
885 unless($remote_api) {
886 $error = "No API set";
890 # Initialize configuration data
891 $remote_api->{config_init}->();
893 # Check/create default values, if they do not exist
894 _recursive_hash_walk($defaultconfig, \&_init_config_item);
897 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
899 unless (@grabbers && @getters) {
900 _io('No grabbers or no getters found, can not proceed.');
905 $getter = $getters[0];
906 foreach my $p (@getters) {
907 if (_config_get(['getter']) eq $p->{'NAME'}) {
911 _debug('Selected %s as getter', $getter->{'NAME'});
912 _config_set(['getter'], $getter->{'NAME'});
915 _io('initialized successfully');
920 # Register a remote API. This API contains a basic output function (used
921 # when no window specific function is available), some config functions
922 # and a color code function.
926 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
930 unless(defined($a)) {
935 # The config_* handlers are special in that they either all have
936 # provided by the user, or none. In the latter case builtin
937 # handlers will be used, but the config will not persist.
940 foreach (@config_functions) {
941 if (exists($a->{$_})) {
948 unless (($c == 0) or ($c == scalar(@config_functions))) {
949 $error = sprintf("Missing config function: %s", $missing[0]);
953 foreach (keys(%{$a})) {
954 if (ref($a->{$_}) ne 'CODE') {
955 $error = sprintf("API handler %s is not a subroutine reference", $_);
957 $remote_api->{$_} = $a->{$_};
960 if (exists($a->{_debug})) {
961 $debug = $a->{_debug}->();
964 @outputstack = ($remote_api->{'io'});
970 # Check a message for useable links
974 my $message = $event->{message};
980 # Look if we should ignore this line
981 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
985 _push_output($event->{ewpf});
986 $message = _expand_url_shortener($message);
990 # Offer the message to all Grabbers in turn
991 GRABBER: foreach $g (@grabbers) {
992 ($m, $p) = $g->get($message);
993 while (defined($m)) {
994 _debug('Metadata: %s', Dumper($m));
995 if (exists($remote_api->{link_callback})) {
996 $remote_api->{link_callback}->($m);
998 if ('download' eq _config_get(['mode'])) {
1000 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
1001 $remote_api->{color}->('*red'),
1002 $remote_api->{color}->(),
1003 $remote_api->{color}->('*yellow'),
1004 $remote_api->{color}->(),
1005 $remote_api->{color}->('*green'),
1010 unless($getter->get($m)) {
1011 _io(sprintf('%s>>> FAILED', $remote_api->{color}->('*red')));
1013 } elsif ('display' eq _config_get(['mode'])) {
1015 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1016 $remote_api->{color}->('*magenta'),
1017 $remote_api->{color}->(),
1018 $remote_api->{color}->('*yellow'),
1019 $remote_api->{color}->(),
1020 $remote_api->{color}->('*green')
1026 _io(sprintf('%s>>> Invalid operation mode', $remote_api->{color}->('*red')));
1029 # Remove the matched part from the message and try again (there may be
1033 last GRABBER if ($message =~ /^\s*$/);
1035 ($m, $p) = $g->get($message);
1043 # Handle a videosite command (/videosite ...) entered in the client
1045 sub handle_command {
1047 my ($cmd, @params) = split(/\s+/, $event->{message});
1049 _push_output($event->{ewpf});
1051 if (exists($videosite_commands->{$cmd})) {
1052 $videosite_commands->{$cmd}->(@params);