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',
50 'config-version' => '2',
54 # List of known commands and handlers
56 my $videosite_commands = {
99 foreach (@grabbers, @getters) {
102 _io('Enabled debugging');
107 foreach (@grabbers, @getters) {
110 _io('Disabled debugging');
115 # This is a list of default values for the remote API. These
116 # are used if the values are not registered by the library user.
119 io => sub { print @_, "\n" },
120 config_init => \&_builtin_config_init,
121 config_get => \&_builtin_config_get,
122 config_set => \&_builtin_config_set,
123 config_has => \&_builtin_config_has,
124 config_save => \&_builtin_config_save,
125 config_del => \&_builtin_config_del,
126 color => sub { return '' },
127 module_path => sub { return dirname(realpath($0)) },
128 quote => sub { return $_ },
132 # Output a string on the client.
133 # Works like (s)printf in that it takes a format string and a list of
134 # values to be replaced. Undefined values will be printed as '(undef)'
136 # All parameters (except for the format string itself) will be quoted
137 # using the client specific quote function
143 @text = ('') unless(@text);
145 # This will define the outputprefix once, so we don't have
146 # do do this every time.
147 $outputprefix = sprintf("%svideosite: %s",
148 _colorpair('magenta'),
149 _colorpair()) unless(defined($outputprefix));
150 $format = $outputprefix . shift(@text);
153 # The format string is assumed to be appropriately quoted.
154 # Quote the rest of the text, replacing undefined strings by (undef)
156 @text = map { defined($_)?$remote_api->{quote}->($_):'(undef)' } @text;
158 $outputstack[0]->(sprintf($format, @text));
162 # Recursively walk through a hash-of-hashes, calling the given function
163 # for each found leaf with the path to the leaf
165 sub _recursive_hash_walk {
167 my $callback = shift;
170 foreach (keys(%{$hash})) {
171 if (ref($hash->{$_}) eq 'HASH') {
172 _recursive_hash_walk($hash->{$_}, $callback, @path, $_);
174 $callback->([@path, $_], $hash->{$_});
180 # Return the color code for the given foreground/background color
181 # pair. Both can be undef, which means "default"
186 $fg = defined($fg)?$fg:'default';
187 $bg = defined($bg)?$bg:'default';
189 return $remote_api->{color}->($fg, $bg);
193 # Sets the given config item if it is not set already
195 sub _init_config_item {
199 unless(_config_has($path)) {
200 _config_set($path, $value);
205 # Print a message if debug is enabled
214 # Load a list of modules matching a pattern from a given directory.
226 opendir(D, $dir) || return ();
227 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
231 _debug("Trying to load $p:");
234 load "videosite::$p";
237 _io("Failed to load plugin: $@");
242 $g = "videosite::$p"->new();
245 _io("Failed to instanciate: $@");
250 _debug("found $g->{'TYPE'} $g->{'NAME'}");
251 if ($type eq $g->{'TYPE'}) {
255 connectors => sub { return _connectorlist('active-connectors') },
256 config_get => \&_config_get,
257 config_set => \&_config_set,
258 config_has => \&_config_has,
260 $g->setdebug($debug);
262 _io('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
267 _debug("Loaded %d plugins", $#g+1);
273 # Populate the @grabbers and @getters lists from the given
276 sub _load_modules($) {
280 foreach (keys(%INC)) {
281 if ($INC{$_} =~ m|^$path|) {
282 _debug("Removing %s from \$INC", $_);
286 @grabbers = _ploader($path, '.*Grabber\.pm$', 'grabber');
287 @getters = _ploader($path, '.*Getter\.pm$', 'getter');
291 # Wrapper functions for config management to put in
298 $value = $remote_api->{config_get}->($path);
299 _debug("config: getting %s=%s", join('.', @{$path}), $value);
308 _debug("config: setting %s=%s", join('.', @{$path}), $value);
309 return $remote_api->{config_set}->($path, $value);
316 $b = $remote_api->{config_has}->($path);
317 _debug("config: testing %s (%s)", join('.', @{$path}), $b?'true':'false');
325 _debug("config: removing %s", join('.', @{$path}));
326 $remote_api->{config_del}->($path);
330 # The _config_list_* are helper functions taking a path to a comma separated
331 # string. The string is interpreted as a list and the action performed
332 # on it, storing back the modified version
336 # Add an item to the list, checking for duplicates
338 sub _config_list_add {
343 if (_config_has($path)) {
344 @c = split(/\s*,\s*/, _config_get($path));
349 _debug("Adding %s to list %s", $item, join(".", @{$path}));
350 unless(grep { $_ eq $item } @c) {
354 _config_set($path, join(',', @c));
358 # Remove an item from the list
360 sub _config_list_del {
365 unless(_config_has($path)) {
369 _debug("Removing %s from list %s", $item, join('.', @{$path}));
370 @c = map { $item ne $_ } split(/\s*,\s*/, _config_get($path));
372 _config_set($path, join('.', @c));
376 # Return true if the item contains the given list, false otherwise
378 sub _config_list_has {
382 unless(_config_has($path)) {
386 _debug("Checking for %s in list %s", $item, join('.', @{$path}));
388 return grep { $item eq $_ } split(/\s*,\s*/, _config_get($path));
392 # Replace a list with the given items
394 sub _config_list_set {
397 _debug("Replacing %s with (%s)", join('.', @{$path}), join(",", @_));
399 _config_set($path, join(',', @_));
403 # Return the list of currently active connectors, in the configured
410 foreach(split(/,/, _config_get([$key]))) {
411 push(@c, _unserialize_connector_hash($_));
418 # Convert a connector hash from it's config structure back to a perl
421 sub _unserialize_connector_hash {
425 if (_config_has(['connectors', $name, 'name'])) {
426 $connector->{name} = _config_get(['connectors', $name, 'name']);
427 $connector->{schemas} = {};
428 foreach ('http', 'https') {
429 if (_config_has(['connectors', $name, 'schemas', $_])) {
430 $connector->{schemas}->{$_} = _config_get(['connectors', $name, 'schemas', $_]);
435 _debug("Returning connector %s: %s", $name, Dumper($connector));
441 # Push a new output function on the IO stack.
444 unshift(@outputstack, shift);
448 # Pop the topmost output function from the stack, leaving
449 # at least one function on it.
452 if (scalar(@outputstack) > 0) {
458 # Takes a string and replaces commonly used URL shorteners recursively,
459 # up to 10 levels deep
461 sub _expand_url_shortener {
465 'is\.gd/[[:alnum:]]+',
466 'otf\.me/[[:alnum:]]+',
467 'hel\.me/[[:alnum:]]+',
468 '7ax\.de/[[:alnum:]]+',
469 'ow\.ly/[[:alnum:]]+',
470 'j\.mp/[[:alnum:]]+',
471 'bit\.ly/[[:alnum:]]+',
472 'tinyurl\.com/[[:alnum:]]+',
473 'pop\.is/[[:alnum:]]+',
474 'post\.ly/[[:alnum:]]+',
475 '1\.ly/[[:alnum:]]+',
476 '2\.ly/[[:alnum:]]+',
477 't\.co/[[:alnum:]]+',
478 'shar\.es/[[:alnum:]]+',
479 'goo\.gl/[[:alnum:]]+',
481 my $ua = LWP::UserAgent->new(agent => 'Mozilla', max_redirect => 0, timeout => 5);
484 OUTER: while (($os ne $s) and ($i > 0)) {
489 foreach my $pattern (@urlshortener) {
490 my $p = "https?:\/\/" . $pattern;
492 _debug("Matching %s against %s", $p, $s);
497 _debug("Found %s", $matched);
498 $res = $ua->head($matched);
499 if ($res->is_redirect()) {
500 my $new = $res->headers()->header("Location");
502 _debug("Replacing %s with %s", $matched, $new);
503 $s =~ s/$matched/$new/;
506 _debug("Error resolving %s", $matched);
513 _debug("Loop terminated by counter");
516 _debug("Final string: %s", $s);
522 # Save the config to durable storage
525 $remote_api->{config_save}->();
529 # Set a configuration element
537 foreach $p (@getters, @grabbers) {
538 if ($p->{'NAME'} eq $target) {
539 $p->setval($key, $val);
543 _io('No such module');
548 # Enable a given module
554 foreach $p (@grabbers) {
555 if ($p->{'NAME'} eq $target) {
560 _io('No such module');
564 # Disable given module
570 foreach $p (@grabbers) {
571 if ($p->{'NAME'} eq $target) {
576 _io('No such module');
580 # Show settings for modules
587 if (defined($target)) {
588 foreach $p (@getters, @grabbers) {
589 if ($p->{'NAME'} eq $target) {
590 _io($p->getconfstr());
594 _io('No such module');
596 _io('Loaded grabbers (* denotes enabled modules):');
597 foreach $p (@grabbers) {
598 $e = $p->_getval('enabled');
599 _io(' %s%s', $p->{'NAME'}, $e?'*':'');
602 _io('Loaded getters:');
603 foreach $p (@getters) {
604 _io(' %s', $p->{'NAME'});
610 # Show help for the commands
616 if (defined($target)) {
617 foreach $p (@getters, @grabbers) {
618 if ($p->{'NAME'} eq $target) {
619 _io($p->gethelpstr());
623 _io('No such module');
627 save: save the current configuration
628 help [modulename]: display this help, or module specific help
629 show [modulename]: show loaded modules, or the current parameters of a module
630 set modulename parameter value: set a module parameter to a new value
631 getter [modulename]: display or set the getter to use
632 enable [modulename]: enable the usage of this module (grabbers only)
633 disable [modulename]: disable the usage of this module (grabbers only)
634 reload: reload all modules (this is somewhat experimental)
635 mode [modename]: display or set the operation mode (download/display)
636 connector [subcommand]: manage connectors (proxies)
637 debug: enable debugging messages
638 nodebug: disable debugging messages
644 # Set the getter to use
650 if (defined($target)) {
651 foreach $p (@getters) {
652 if ($p->{'NAME'} eq $target) {
654 _config_set(['getter'], $target);
655 _io("Getter changed to %s", $target);
659 _io('No such getter');
661 _io('Current getter: %s', _config_get(['getter']));
666 # Show/set the working mode
671 if (defined($mode)) {
673 if (('download' eq $mode) or ('display' eq $mode)) {
674 _config_set(['mode'], $mode);
675 _io('Now using %s mode', $mode);
677 _io('Invalid mode: %s', $mode);
680 _io('Current mode: %s', _config_get(['mode']));
686 # Manage the connectors
692 unless(defined($subcmd)) {
696 $subcmd = lc($subcmd);
698 if ($subcmd eq 'list') {
699 _io("Defined connectors");
700 foreach $c (_connectorlist('defined-connectors')) {
702 my $schemas = $c->{schemas};
703 if (scalar(keys(%{$schemas})) == 0) {
704 _io(" No schemas defined");
706 foreach (keys(%{$schemas})) {
707 _io(' %s: %s', $_, $schemas->{$_});
713 _io("Selected connectors: %s", _config_get(['active-connectors']));
714 } elsif ($subcmd eq 'add') {
717 unless(defined($name)) {
718 _io("No name given");
724 if (_config_list_has(['defined-connectors'], $name)) {
725 _io("Connector already exists");
729 _config_set(['connectors', $name, 'name'], $name);
730 _config_list_add(['defined-connectors'], $name);
731 } elsif ($subcmd eq 'del') {
735 unless(defined($name)) {
736 _io("No name given");
740 unless (_config_list_has(['defined-connectors'], $name)) {
741 _io("Connector does not exist");
745 if (_config_has(['connectors', $name, '_immutable'])) {
746 _io("Connector cannot be removed");
750 # Remove from list of active connectors
751 _config_list_del(['defined-connectors'], $name);
752 _config_list_del(['active-connectors'], $name);
754 _config_del(['connectors', $name, 'name']);
755 _config_del(['connectors', $name, '_immutable']);
756 _config_del(['connectors', $name, 'schemas', 'http']);
757 _config_del(['connectors', $name, 'schemas', 'https']);
759 @dcon = split(/,/, _config_get(['active-connectors']));
761 if (scalar(@dcon) == 0) {
762 _io("List of selected connectors is empty, resetting to direct");
763 _config_list_add(['active-connectors', 'direct']);
765 } elsif ($subcmd eq 'addschema') {
766 my ($conn, $schema, $proxy) = @_;
768 unless(defined($conn)) {
769 _io("No connector name given");
773 unless(defined($schema)) {
774 _io("No schema given");
778 unless(defined($proxy)) {
779 _io("No proxy given");
784 unless(_config_list_has(['defined-connectors'], $conn)) {
785 _io("Connector does not exist");
789 if (_config_has(['connectors', $conn, '_immutable'])) {
790 _io("Connector cannot be modified");
794 $schema = lc($schema);
795 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
796 } elsif ($subcmd eq 'delschema') {
797 my ($conn, $schema) = @_;
799 unless(defined($conn)) {
800 _io("No connector name given");
804 unless(defined($schema)) {
805 _io("No schema given");
810 unless(_config_list_has(['defined-connectors'], $conn)) {
811 _io("Connector does not exist");
815 $schema = lc($schema);
816 _config_del(['connectors', $conn, 'schemas', $schema]);
817 } elsif ($subcmd eq 'select') {
818 my @connlist = map { lc } @_;
820 if (scalar(@connlist) == 0) {
821 _io("No connectors given");
825 foreach (@connlist) {
826 unless(_config_list_has(['defined-connectors'], $_)) {
827 _io("Connector %s does not exist", $_);
832 _config_list_set(['active-connectors'], @connlist);
834 _io("connector [list|add|del|addschema|delschema|help] <options>");
835 _io(" help: Show this help");
836 _io(" list: List the defined connectors");
837 _io(" add <name>: Add a connector with name <name>");
838 _io(" del <name>: Delete the connector with name <name>");
839 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
840 _io(" delschema <name> <schema>: Remove the schema from the connector");
841 _io(" select <name> [<name>...]: Select the connectors to use");
846 # Return the list of loaded grabbers.
847 # This is used by the test programs, and is not meant to be
855 # ==============================================
856 # Builtin config handling functions
857 # These are used if the library used does not
858 # register it's own config_* handlers
859 # ==============================================
861 sub _builtin_config_init {
864 sub _builtin_config_get {
865 return $builtin_config{join(".", @{$_[0]})};
868 sub _builtin_config_set {
869 $builtin_config{join(".", @{$_[0]})} = $_[1];
872 sub _builtin_config_has {
873 return exists($builtin_config{join(".", @{$_[0]})});
876 sub _builtin_config_save {
879 sub _builtin_config_del {
880 delete($builtin_config{join(".", @{$_[0]})});
884 # ==============================================
885 # From this point on publicly callable functions
886 # ==============================================
891 # Initialization function for the library
892 # Actually not the first thing to be called, it expects an API
893 # has (register_api) to be registered first
896 unless($remote_api) {
897 $error = "No API set";
901 # Initialize configuration data
902 $remote_api->{config_init}->();
904 # Check/create default values, if they do not exist
905 _recursive_hash_walk($defaultconfig, \&_init_config_item);
908 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
910 unless (@grabbers && @getters) {
911 _io('No grabbers or no getters found, can not proceed.');
916 $getter = $getters[0];
917 foreach my $p (@getters) {
918 if (_config_get(['getter']) eq $p->{'NAME'}) {
922 _debug('Selected %s as getter', $getter->{'NAME'});
923 _config_set(['getter'], $getter->{'NAME'});
926 _io('initialized successfully');
931 # Register a remote API. This API contains a basic output function (used
932 # when no window specific function is available), some config functions
933 # and a color code function.
937 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
941 unless(defined($a)) {
946 # The config_* handlers are special in that they either all have
947 # provided by the user, or none. In the latter case builtin
948 # handlers will be used, but the config will not persist.
951 foreach (@config_functions) {
952 if (exists($a->{$_})) {
959 unless (($c == 0) or ($c == scalar(@config_functions))) {
960 $error = sprintf("Missing config function: %s", $missing[0]);
964 foreach (keys(%{$a})) {
965 if (ref($a->{$_}) ne 'CODE') {
966 $error = sprintf("API handler %s is not a subroutine reference", $_);
968 $remote_api->{$_} = $a->{$_};
971 if (exists($a->{_debug})) {
972 $debug = $a->{_debug}->();
975 @outputstack = ($remote_api->{'io'});
981 # Check a message for useable links
985 my $message = $event->{message};
992 # Look if we should ignore this line
993 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
997 _push_output($event->{ewpf});
998 $message = _expand_url_shortener($message);
1002 # Offer the message to all Grabbers in turn
1003 GRABBER: foreach $g (@grabbers) {
1004 ($m, $p) = $g->get($message);
1005 while (defined($m)) {
1006 _debug('Metadata: %s', Dumper($m));
1008 if (exists($remote_api->{link_callback})) {
1009 $skip = $remote_api->{link_callback}->($m);
1012 if ('download' eq _config_get(['mode'])) {
1014 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
1017 _colorpair('*yellow'),
1019 _colorpair('*green'),
1024 unless($getter->get($m)) {
1025 _io(sprintf('%s>>> FAILED', _colorpair('*red')));
1027 } elsif ('display' eq _config_get(['mode'])) {
1029 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1030 _colorpair('*magenta'),
1032 _colorpair('*yellow'),
1034 _colorpair('*green')
1040 _io(sprintf('%s>>> Invalid operation mode', _colorpair('*red')));
1044 # Remove the matched part from the message and try again (there may be
1048 last GRABBER if ($message =~ /^\s*$/);
1050 ($m, $p) = $g->get($message);
1058 # Handle a videosite command (/videosite ...) entered in the client
1060 sub handle_command {
1062 my ($cmd, @params) = split(/\s+/, $event->{message});
1064 _push_output($event->{ewpf});
1066 if (exists($videosite_commands->{$cmd})) {
1067 $videosite_commands->{$cmd}->(@params);