4 use vars qw(@ISA @EXPORT_OK);
14 @EXPORT_OK = qw(init register_api check_for_link);
22 my %builtin_config = ();
26 # The default config. These values will be set in the config
27 # if they do not exist already.
30 'getter' => 'filegetter',
32 'active-connectors' => 'direct',
33 'defined-connectors' => 'direct',
44 # List of known commands and handlers
46 my $videosite_commands = {
89 foreach (@grabbers, @getters) {
92 _io('Enabled debugging');
97 foreach (@grabbers, @getters) {
100 _io('Disabled debugging');
105 # This is a list of default values for the remote API. These
106 # are used if the values are not registered by the library user.
109 io => sub { print @_, "\n" },
110 config_init => \&_builtin_config_init,
111 config_get => \&_builtin_config_get,
112 config_set => \&_builtin_config_set,
113 config_has => \&_builtin_config_has,
114 config_save => \&_builtin_config_save,
115 config_del => \&_builtin_config_del,
116 color => sub { return '' },
117 module_path => sub { return dirname(realpath($0)) },
118 quote => sub { return $_ },
122 # Output a string on the client.
123 # Works like (s)printf in that it takes a format string and a list of
124 # values to be replaced. Undefined values will be printed as '(undef)'
126 # All parameters (except for the format string itself) will be quoted
127 # using the client specific quote function
133 # This will define the outputprefix once, so we don't have
134 # do do this every time.
135 $outputprefix //= sprintf("%svideosite: %s",
136 $remote_api->{color}->('magenta'),
137 $remote_api->{color}->());
138 $format = $outputprefix . shift(@text);
141 # The format string is assumed to be appropriately quoted.
142 # Quote the rest of the text, replacing undefined strings by (undef)
144 @text = map { defined($_)?$remote_api->{quote}->($_):'(undef)' } @text;
146 $outputstack[0]->(sprintf($format, @text));
150 # Recursively walk through a hash-of-hashes, calling the given function
151 # for each found leaf with the path to the leaf
153 sub _recursive_hash_walk {
155 my $callback = shift;
158 foreach (keys(%{$hash})) {
159 if (ref($hash->{$_}) eq 'HASH') {
160 _recursive_hash_walk($hash->{$_}, $callback, @path, $_);
162 $callback->([@path, $_], $hash->{$_});
168 # Return the color code for the given foreground/background color
169 # pair. Both can be undef, which means "default"
174 return $remote_api->{color}->($fg, $bg);
178 # Sets the given config item if it is not set already
180 sub _init_config_item {
184 unless($remote_api->{config_has}->($path)) {
185 $remote_api->{config_set}->($path, $value);
190 # Print a message if debug is enabled
199 # Load a list of modules matching a pattern from a given directory.
211 opendir(D, $dir) || return ();
212 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
216 _debug("Trying to load $p:");
219 load "videosite::$p";
222 _io("Failed to load plugin: $@");
227 $g = "videosite::$p"->new();
230 _io("Failed to instanciate: $@");
235 _debug("found $g->{'TYPE'} $g->{'NAME'}");
236 if ($type eq $g->{'TYPE'}) {
240 connectors => sub { return _connectorlist('active-connectors') },
241 config_get => \&_config_get,
242 config_set => \&_config_set,
243 config_has => \&_config_has,
245 $g->setdebug($debug);
247 _io('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
252 _debug("Loaded %d plugins", $#g+1);
258 # Populate the @grabbers and @getters lists from the given
261 sub _load_modules($) {
265 foreach (keys(%INC)) {
266 if ($INC{$_} =~ m|^$path|) {
267 _debug("Removing %s from \$INC", $_);
271 @grabbers = _ploader($path, '.*Grabber\.pm$', 'grabber');
272 @getters = _ploader($path, '.*Getter\.pm$', 'getter');
276 # Wrapper functions for config management to put in
283 $value = $remote_api->{config_get}->($path);
284 _debug("config: getting %s=%s", join('.', @{$path}), $value);
293 _debug("config: setting %s=%s", join('.', @{$path}), $value);
294 return $remote_api->{config_set}->($path, $value);
301 $b = $remote_api->{config_has}->($path);
302 _debug("config: testing %s (%s)", join('.', @{$path}), $b?'true':'false');
308 # The _config_list_* are helper functions taking a path to a comma separated
309 # string. The string is interpreted as a list and the action performed
310 # on it, storing back the modified version
314 # Add an item to the list, checking for duplicates
316 sub _config_list_add {
321 if (_config_has($path)) {
322 @c = split(/\s*,\s*/, _config_get($path));
327 _debug("Adding %s to list %s", $item, join(".", $path));
328 unless(grep { $_ eq $item } @c) {
332 _config_set($path, join(',', @c));
336 # Remove an item from the list
338 sub _config_list_del {
343 unless(_config_has($path)) {
347 _debug("Removing %s from list %s", $item, join('.', $path));
348 @c = map { $item ne $_ } split(/\s*,\s*/, _config_get($path));
350 _config_set($path, join('.', @c));
354 # Return true if the item contains the given list, false otherwise
356 sub _config_list_has {
360 unless(_config_has($path)) {
364 _debug("Checking for %s in list %s", $item, join('.', $path));
366 return grep { $item eq $_ } split(/\s*,\s*/, _config_get($path));
370 # Replace a list with the given items
372 sub _config_list_set {
375 _debug("Replacing %s with (%s)", join('.', $path), join(",", @_));
377 _config_set($path, join(',', @_));
381 # Return the list of currently active connectors, in the configured
388 foreach(split(/,/, _config_get([$key]))) {
389 push(@c, _unserialize_connector_hash($_));
396 # Convert a connector hash from it's config structure back to a perl
399 sub _unserialize_connector_hash {
403 if (_config_has(['connectors', $name, 'name'])) {
404 $connector->{name} = _config_get(['connectors', $name, 'name']);
405 $connector->{schemas} = {};
406 foreach ('http', 'https') {
407 if (_config_has(['connectors', $name, 'schemas', $_])) {
408 $connector->{schemas}->{$_} = _config_get(['connectors', $name, 'schemas', $_]);
413 _debug("Returning connector %s: %s", $name, Dumper($connector));
419 # Push a new output function on the IO stack.
422 unshift(@outputstack, shift);
426 # Pop the topmost output function from the stack, leaving
427 # at least one function on it.
430 if (scalar(@outputstack) > 0) {
436 # Takes a string and replaces commonly used URL shorteners recursively,
437 # up to 10 levels deep
439 sub _expand_url_shortener {
443 'is\.gd/[[:alnum:]]+',
444 'otf\.me/[[:alnum:]]+',
445 'hel\.me/[[:alnum:]]+',
446 '7ax\.de/[[:alnum:]]+',
447 'ow\.ly/[[:alnum:]]+',
448 'j\.mp/[[:alnum:]]+',
449 'bit\.ly/[[:alnum:]]+',
450 'tinyurl\.com/[[:alnum:]]+',
451 'pop\.is/[[:alnum:]]+',
452 'post\.ly/[[:alnum:]]+',
453 '1\.ly/[[:alnum:]]+',
454 '2\.ly/[[:alnum:]]+',
455 't\.co/[[:alnum:]]+',
456 'shar\.es/[[:alnum:]]+',
457 'goo\.gl/[[:alnum:]]+',
459 my $ua = LWP::UserAgent->new(agent => 'Mozilla', max_redirect => 0, timeout => 5);
462 OUTER: while (($os ne $s) and ($i > 0)) {
467 foreach my $pattern (@urlshortener) {
468 my $p = "https?:\/\/" . $pattern;
470 _debug("Matching %s against %s", $p, $s);
475 _debug("Found %s", $matched);
476 $res = $ua->head($matched);
477 if ($res->is_redirect()) {
478 my $new = $res->headers()->header("Location");
480 _debug("Replacing %s with %s", $matched, $new);
481 $s =~ s/$matched/$new/;
484 _debug("Error resolving %s", $matched);
491 _debug("Loop terminated by counter");
494 _debug("Final string: %s", $s);
500 # Save the config to durable storage
503 $remote_api->{config_save}->();
507 # Set a configuration element
515 foreach $p (@getters, @grabbers) {
516 if ($p->{'NAME'} eq $target) {
517 $p->setval($key, $val);
521 _io('No such module');
526 # Enable a given module
532 foreach $p (@grabbers) {
533 if ($p->{'NAME'} eq $target) {
538 _io('No such module');
542 # Disable given module
548 foreach $p (@grabbers) {
549 if ($p->{'NAME'} eq $target) {
554 _io('No such module');
558 # Show settings for modules
565 if (defined($target)) {
566 foreach $p (@getters, @grabbers) {
567 if ($p->{'NAME'} eq $target) {
568 _io($p->getconfstr());
572 _io('No such module');
574 _io('Loaded grabbers (* denotes enabled modules):');
575 foreach $p (@grabbers) {
576 $e = $p->_getval('enabled');
577 _io(' %s%s', $p->{'NAME'}, $e?'*':'');
580 _io('Loaded getters:');
581 foreach $p (@getters) {
582 _io(' %s', $p->{'NAME'});
588 # Show help for the commands
594 if (defined($target)) {
595 foreach $p (@getters, @grabbers) {
596 if ($p->{'NAME'} eq $target) {
597 _io($p->gethelpstr());
601 _io('No such module');
605 save: save the current configuration
606 help [modulename]: display this help, or module specific help
607 show [modulename]: show loaded modules, or the current parameters of a module
608 set modulename parameter value: set a module parameter to a new value
609 getter [modulename]: display or set the getter to use
610 enable [modulename]: enable the usage of this module (grabbers only)
611 disable [modulename]: disable the usage of this module (grabbers only)
612 reload: reload all modules (this is somewhat experimental)
613 mode [modename]: display or set the operation mode (download/display)
614 connector [subcommand]: manage connectors (proxies)
615 debug: enable debugging messages
616 nodebug: disable debugging messages
622 # Set the getter to use
628 if (defined($target)) {
629 foreach $p (@getters) {
630 if ($p->{'NAME'} eq $target) {
632 _config_set(['getter'], $target);
633 _io("Getter changed to %s", $target);
637 _io('No such getter');
639 _io('Current getter: %s', _config_get(['getter']));
644 # Show/set the working mode
649 if (defined($mode)) {
651 if (('download' eq $mode) or ('display' eq $mode)) {
652 _config_set(['mode'], $mode);
653 _io('Now using %s mode', $mode);
655 _io('Invalid mode: %s', $mode);
658 _io('Current mode: %s', _config_get(['mode']));
664 # Manage the connectors
670 unless(defined($subcmd)) {
674 $subcmd = lc($subcmd);
676 if ($subcmd eq 'list') {
677 _io("Defined connectors");
678 foreach $c (_connectorlist('defined-connectors')) {
680 my $schemas = $c->{schemas};
681 if (scalar(keys(%{$schemas})) == 0) {
682 _io(" No schemas defined");
684 foreach (keys(%{$schemas})) {
685 _io(' %s: %s', $_, $schemas->{$_});
691 _io("Selected connectors: %s", _config_get(['active-connectors']));
692 } elsif ($subcmd eq 'add') {
695 unless(defined($name)) {
696 _io("No name given");
702 if (_config_list_has(['defined-connectors'], $name)) {
703 _io("Connector already exists");
707 _config_set(['connectors', $name, 'name'], $name);
708 _config_list_add(['defined-connectors'], $name);
709 } elsif ($subcmd eq 'del') {
713 unless(defined($name)) {
714 _io("No name given");
718 unless (_config_list_has(['defined-connectors'])) {
719 _io("Connector does not exist");
723 if (_config_has(['connectors', $name, '_immutable'])) {
724 _io("Connector cannot be removed");
728 # Remove from list of active connectors
729 _config_list_del(['defined-connectors'], $name);
730 _config_list_del(['active-connectors'], $name);
732 _config_del(['connectors', $name, 'name']);
733 _config_del(['connectors', $name, '_immutable']);
734 _config_del(['connectors', $name, 'schemas', 'http']);
735 _config_del(['connectors', $name, 'schemas', 'https']);
737 @dcon = split(/,/, _config_get(['active-connectors']));
739 if (scalar(@dcon) == 0) {
740 _io("List of selected connectors is empty, resetting to direct");
741 _config_list_add(['active-connectors', 'direct']);
743 } elsif ($subcmd eq 'addschema') {
744 my ($conn, $schema, $proxy) = @_;
746 unless(defined($conn)) {
747 _io("No connector name given");
751 unless(defined($schema)) {
752 _io("No schema given");
756 unless(defined($proxy)) {
757 _io("No proxy given");
762 unless(_config_list_has(['defined-connectors'], $conn)) {
763 _io("Connector does not exist");
767 if (_config_has(['connectors', $conn, '_immutable'])) {
768 _io("Connector cannot be modified");
772 $schema = lc($schema);
773 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
774 } elsif ($subcmd eq 'delschema') {
775 my ($conn, $schema) = @_;
777 unless(defined($conn)) {
778 _io("No connector name given");
782 unless(defined($schema)) {
783 _io("No schema given");
788 unless(_config_list_has(['defined-connectors'], $conn)) {
789 _io("Connector does not exist");
793 $schema = lc($schema);
794 _config_del(['connectors', $conn, 'schemas', $schema]);
795 } elsif ($subcmd eq 'select') {
796 my @connlist = map { lc } @_;
798 if (scalar(@connlist) == 0) {
799 _io("No connectors given");
803 foreach (@connlist) {
804 unless(_config_list_has(['defined-connectors'], $_)) {
805 _io("Connector %s does not exist", $_);
810 _config_list_set(['active-connectors'], @connlist);
812 _io("connector [list|add|del|addschema|delschema|help] <options>");
813 _io(" help: Show this help");
814 _io(" list: List the defined connectors");
815 _io(" add <name>: Add a connector with name <name>");
816 _io(" del <name>: Delete the connector with name <name>");
817 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
818 _io(" delschema <name> <schema>: Remove the schema from the connector");
819 _io(" select <name> [<name>...]: Select the connectors to use");
824 # Return the list of loaded grabbers.
825 # This is used by the test programs, and is not meant to be
833 # ==============================================
834 # Builtin config handling functions
835 # These are used if the library used does not
836 # register it's own config_* handlers
837 # ==============================================
839 sub _builtin_config_init {
842 sub _builtin_config_get {
843 return $builtin_config{join(".", @{$_[0]})};
846 sub _builtin_config_set {
847 $builtin_config{join(".", @{$_[0]})} = $_[1];
850 sub _builtin_config_has {
851 return exists($builtin_config{join(".", @{$_[0]})});
854 sub _builtin_config_save {
857 sub _builtin_config_del {
858 delete($builtin_config{join(".", @{$_[0]})});
862 # ==============================================
863 # From this point on publicly callable functions
864 # ==============================================
869 # Initialization function for the library
870 # Actually not the first thing to be called, it expects an API
871 # has (register_api) to be registered first
874 unless($remote_api) {
875 $error = "No API set";
879 # Initialize configuration data
880 $remote_api->{config_init}->();
882 # Check/create default values, if they do not exist
883 _recursive_hash_walk($defaultconfig, \&_init_config_item);
886 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
888 unless (@grabbers && @getters) {
889 _io('No grabbers or no getters found, can not proceed.');
894 $getter = $getters[0];
895 foreach my $p (@getters) {
896 if (_config_get(['getter']) eq $p->{'NAME'}) {
900 _debug('Selected %s as getter', $getter->{'NAME'});
901 _config_set(['getter'], $getter->{'NAME'});
904 _io('initialized successfully');
909 # Register a remote API. This API contains a basic output function (used
910 # when no window specific function is available), some config functions
911 # and a color code function.
915 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
919 unless(defined($a)) {
924 # The config_* handlers are special in that they either all have
925 # provided by the user, or none. In the latter case builtin
926 # handlers will be used, but the config will not persist.
929 foreach (@config_functions) {
930 if (exists($a->{$_})) {
937 unless (($c == 0) or ($c == scalar(@config_functions))) {
938 $error = sprintf("Missing config function: %s", $missing[0]);
942 foreach (keys(%{$a})) {
943 if (ref($a->{$_}) ne 'CODE') {
944 $error = sprintf("API handler %s is not a subroutine reference", $_);
946 $remote_api->{$_} = $a->{$_};
949 if (exists($a->{_debug})) {
950 $debug = $a->{_debug}->();
953 @outputstack = ($remote_api->{'io'});
959 # Check a message for useable links
963 my $message = $event->{message};
969 # Look if we should ignore this line
970 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
974 _push_output($event->{ewpf});
975 $message = _expand_url_shortener($message);
979 # Offer the message to all Grabbers in turn
980 GRABBER: foreach $g (@grabbers) {
981 ($m, $p) = $g->get($message);
982 while (defined($m)) {
983 _debug('Metadata: %s', Dumper($m));
984 if (exists($remote_api->{link_callback})) {
985 $remote_api->{link_callback}->($m);
987 if ('download' eq _config_get(['mode'])) {
989 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
990 $remote_api->{color}->('*red'),
991 $remote_api->{color}->(),
992 $remote_api->{color}->('*yellow'),
993 $remote_api->{color}->(),
994 $remote_api->{color}->('*green'),
999 unless($getter->get($m)) {
1000 _io(sprintf('%s>>> FAILED', $remote_api->{color}->('*red')));
1002 } elsif ('display' eq _config_get(['mode'])) {
1004 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1005 $remote_api->{color}->('*magenta'),
1006 $remote_api->{color}->(),
1007 $remote_api->{color}->('*yellow'),
1008 $remote_api->{color}->(),
1009 $remote_api->{color}->('*green')
1015 _io(sprintf('%s>>> Invalid operation mode', $remote_api->{color}->('*red')));
1018 # Remove the matched part from the message and try again (there may be
1022 last GRABBER if ($message =~ /^\s*$/);
1024 ($m, $p) = $g->get($message);
1032 # Handle a videosite command (/videosite ...) entered in the client
1034 sub handle_command {
1036 my ($cmd, @params) = split(/\s+/, $event->{message});
1038 _push_output($event->{ewpf});
1040 if (exists($videosite_commands->{$cmd})) {
1041 $videosite_commands->{$cmd}->(@params);