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 # This is a list of default values for the remote API. These
55 # are used if the values are not registered by the library user.
58 io => sub { print @_, "\n" },
59 config_init => \&_builtin_config_init,
60 config_get => \&_builtin_config_get,
61 config_set => \&_builtin_config_set,
62 config_has => \&_builtin_config_has,
63 config_save => \&_builtin_config_save,
64 config_del => \&_builtin_config_del,
65 color => sub { return '' },
66 module_path => sub { return dirname(realpath($0)) },
67 quote => sub { return $_ },
72 # List of known commands and handlers
74 my $videosite_commands = {
104 $remote_api->{reset}->();
117 foreach (@grabbers, @getters) {
120 _io('Enabled debugging');
125 foreach (@grabbers, @getters) {
128 _io('Disabled debugging');
133 # Output a string on the client.
134 # Works like (s)printf in that it takes a format string and a list of
135 # values to be replaced. Undefined values will be printed as '(undef)'
137 # All parameters (except for the format string itself) will be quoted
138 # using the client specific quote function
144 @text = ('') unless(@text);
146 # This will define the outputprefix once, so we don't have
147 # do do this every time.
148 $outputprefix = sprintf("%svideosite: %s",
149 _colorpair('magenta'),
150 _colorpair()) unless(defined($outputprefix));
151 $format = $outputprefix . shift(@text);
154 # The format string is assumed to be appropriately quoted.
155 # Quote the rest of the text, replacing undefined strings by (undef)
157 @text = map { defined($_)?$remote_api->{quote}->($_):'(undef)' } @text;
159 $outputstack[0]->(sprintf($format, @text));
163 # Recursively walk through a hash-of-hashes, calling the given function
164 # for each found leaf with the path to the leaf
166 sub _recursive_hash_walk {
168 my $callback = shift;
171 foreach (keys(%{$hash})) {
172 if (ref($hash->{$_}) eq 'HASH') {
173 _recursive_hash_walk($hash->{$_}, $callback, @path, $_);
175 $callback->([@path, $_], $hash->{$_});
181 # Return the color code for the given foreground/background color
182 # pair. Both can be undef, which means "default"
187 $fg = defined($fg)?$fg:'default';
188 $bg = defined($bg)?$bg:'default';
190 return $remote_api->{color}->($fg, $bg);
194 # Sets the given config item if it is not set already
196 sub _init_config_item {
200 unless(_config_has($path)) {
201 _config_set($path, $value);
206 # Print a message if debug is enabled
215 # Load a list of modules matching a pattern from a given directory.
227 opendir(D, $dir) || return ();
228 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
232 _debug("Trying to load $p:");
235 load "videosite::$p";
238 _io("Failed to load plugin: $@");
243 $g = "videosite::$p"->new();
246 _io("Failed to instanciate: $@");
251 _debug("found $g->{'TYPE'} $g->{'NAME'}");
252 if ($type eq $g->{'TYPE'}) {
256 connectors => sub { return _connectorlist('active-connectors') },
257 config_get => \&_config_get,
258 config_set => \&_config_set,
259 config_has => \&_config_has,
261 $g->setdebug($debug);
263 _io('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
268 _debug("Loaded %d plugins", $#g+1);
274 # Populate the @grabbers and @getters lists from the given
277 sub _load_modules($) {
281 foreach (keys(%INC)) {
282 if ($INC{$_} =~ m|^$path|) {
283 _debug("Removing %s from \$INC", $_);
287 @grabbers = _ploader($path, '.*Grabber\.pm$', 'grabber');
288 @getters = _ploader($path, '.*Getter\.pm$', 'getter');
292 # Wrapper functions for config management to put in
299 $value = $remote_api->{config_get}->($path);
300 _debug("config: getting %s=%s", join('.', @{$path}), $value);
309 _debug("config: setting %s=%s", join('.', @{$path}), $value);
310 return $remote_api->{config_set}->($path, $value);
317 $b = $remote_api->{config_has}->($path);
318 _debug("config: testing %s (%s)", join('.', @{$path}), $b?'true':'false');
326 _debug("config: removing %s", join('.', @{$path}));
327 $remote_api->{config_del}->($path);
331 # The _config_list_* are helper functions taking a path to a comma separated
332 # string. The string is interpreted as a list and the action performed
333 # on it, storing back the modified version
337 # Add an item to the list, checking for duplicates
339 sub _config_list_add {
344 if (_config_has($path)) {
345 @c = split(/\s*,\s*/, _config_get($path));
350 _debug("Adding %s to list %s", $item, join(".", @{$path}));
351 unless(grep { $_ eq $item } @c) {
355 _config_set($path, join(',', @c));
359 # Remove an item from the list
361 sub _config_list_del {
366 unless(_config_has($path)) {
370 _debug("Removing %s from list %s", $item, join('.', @{$path}));
371 @c = grep { $item ne $_ } split(/\s*,\s*/, _config_get($path));
373 _config_set($path, join(',', @c));
377 # Return true if the item contains the given list, false otherwise
379 sub _config_list_has {
383 unless(_config_has($path)) {
387 _debug("Checking for %s in list %s", $item, join('.', @{$path}));
389 return grep { $item eq $_ } split(/\s*,\s*/, _config_get($path));
393 # Replace a list with the given items
395 sub _config_list_set {
398 _debug("Replacing %s with (%s)", join('.', @{$path}), join(",", @_));
400 _config_set($path, join(',', @_));
404 # Return the list of currently active connectors, in the configured
411 foreach(split(/,/, _config_get([$key]))) {
412 push(@c, _unserialize_connector_hash($_));
419 # Convert a connector hash from it's config structure back to a perl
422 sub _unserialize_connector_hash {
426 if (_config_has(['connectors', $name, 'name'])) {
427 $connector->{name} = _config_get(['connectors', $name, 'name']);
428 $connector->{schemas} = {};
429 foreach ('http', 'https') {
430 if (_config_has(['connectors', $name, 'schemas', $_])) {
431 $connector->{schemas}->{$_} = _config_get(['connectors', $name, 'schemas', $_]);
436 _debug("Returning connector %s: %s", $name, Dumper($connector));
442 # Push a new output function on the IO stack.
445 unshift(@outputstack, shift);
449 # Pop the topmost output function from the stack, leaving
450 # at least one function on it.
453 if (scalar(@outputstack) > 0) {
459 # Takes a string and replaces commonly used URL shorteners recursively,
460 # up to 10 levels deep
462 sub _expand_url_shortener {
466 'is\.gd/[[:alnum:]]+',
467 'otf\.me/[[:alnum:]]+',
468 'hel\.me/[[:alnum:]]+',
469 '7ax\.de/[[:alnum:]]+',
470 'ow\.ly/[[:alnum:]]+',
471 'j\.mp/[[:alnum:]]+',
472 'bit\.ly/[[:alnum:]]+',
473 'tinyurl\.com/[[:alnum:]]+',
474 'pop\.is/[[:alnum:]]+',
475 'post\.ly/[[:alnum:]]+',
476 '1\.ly/[[:alnum:]]+',
477 '2\.ly/[[:alnum:]]+',
478 't\.co/[[:alnum:]]+',
479 'shar\.es/[[:alnum:]]+',
480 'goo\.gl/[[:alnum:]]+',
482 my $ua = LWP::UserAgent->new(agent => 'Mozilla', max_redirect => 0, timeout => 5);
485 OUTER: while (($os ne $s) and ($i > 0)) {
490 foreach my $pattern (@urlshortener) {
491 my $p = "https?:\/\/" . $pattern;
493 _debug("Matching %s against %s", $p, $s);
498 _debug("Found %s", $matched);
499 $res = $ua->head($matched);
500 if ($res->is_redirect()) {
501 my $new = $res->headers()->header("Location");
503 _debug("Replacing %s with %s", $matched, $new);
504 $s =~ s/$matched/$new/;
507 _debug("Error resolving %s", $matched);
514 _debug("Loop terminated by counter");
517 _debug("Final string: %s", $s);
523 # Save the config to durable storage
526 $remote_api->{config_save}->();
530 # Set a configuration element
538 foreach $p (@getters, @grabbers) {
539 if ($p->{'NAME'} eq $target) {
540 $p->setval($key, $val);
544 _io('No such module');
549 # Enable a given module
555 foreach $p (@grabbers) {
556 if ($p->{'NAME'} eq $target) {
561 _io('No such module');
565 # Disable given module
571 foreach $p (@grabbers) {
572 if ($p->{'NAME'} eq $target) {
577 _io('No such module');
581 # Show settings for modules
588 if (defined($target)) {
589 foreach $p (@getters, @grabbers) {
590 if ($p->{'NAME'} eq $target) {
591 _io($p->getconfstr());
595 _io('No such module');
597 _io('Loaded grabbers (* denotes enabled modules):');
598 foreach $p (@grabbers) {
599 $e = $p->_getval('enabled');
600 _io(' %s%s', $p->{'NAME'}, $e?'*':'');
603 _io('Loaded getters:');
604 foreach $p (@getters) {
605 _io(' %s', $p->{'NAME'});
611 # Show help for the commands
617 if (defined($target)) {
618 foreach $p (@getters, @grabbers) {
619 if ($p->{'NAME'} eq $target) {
620 _io($p->gethelpstr());
624 _io('No such module');
628 save: save the current configuration
629 help [modulename]: display this help, or module specific help
630 show [modulename]: show loaded modules, or the current parameters of a module
631 set modulename parameter value: set a module parameter to a new value
632 getter [modulename]: display or set the getter to use
633 enable [modulename]: enable the usage of this module (grabbers only)
634 disable [modulename]: disable the usage of this module (grabbers only)
635 reload: reload all modules (this is somewhat experimental)
636 mode [modename]: display or set the operation mode (download/display)
637 connector [subcommand]: manage connectors (proxies)
638 debug: enable debugging messages
639 nodebug: disable debugging messages
645 # Set the getter to use
651 if (defined($target)) {
652 foreach $p (@getters) {
653 if ($p->{'NAME'} eq $target) {
655 _config_set(['getter'], $target);
656 _io("Getter changed to %s", $target);
660 _io('No such getter');
662 _io('Current getter: %s', _config_get(['getter']));
667 # Show/set the working mode
672 if (defined($mode)) {
674 if (('download' eq $mode) or ('display' eq $mode)) {
675 _config_set(['mode'], $mode);
676 _io('Now using %s mode', $mode);
678 _io('Invalid mode: %s', $mode);
681 _io('Current mode: %s', _config_get(['mode']));
687 # Manage the connectors
693 unless(defined($subcmd)) {
697 $subcmd = lc($subcmd);
699 if ($subcmd eq 'list') {
700 _io("Defined connectors");
701 foreach $c (_connectorlist('defined-connectors')) {
703 my $schemas = $c->{schemas};
704 if (scalar(keys(%{$schemas})) == 0) {
705 _io(" No schemas defined");
707 foreach (keys(%{$schemas})) {
708 _io(' %s: %s', $_, $schemas->{$_});
714 _io("Selected connectors: %s", _config_get(['active-connectors']));
715 } elsif ($subcmd eq 'add') {
718 unless(defined($name)) {
719 _io("No name given");
725 unless($name =~ m|^[a-z]+$|) {
726 _io("%s is not a valid connector name (only letters are allowed)", $name);
730 if (_config_list_has(['defined-connectors'], $name)) {
731 _io("Connector already exists");
735 _config_set(['connectors', $name, 'name'], $name);
736 _config_list_add(['defined-connectors'], $name);
737 } elsif ($subcmd eq 'del') {
741 unless(defined($name)) {
742 _io("No name given");
746 unless (_config_list_has(['defined-connectors'], $name)) {
747 _io("Connector does not exist");
751 if (_config_has(['connectors', $name, '_immutable'])) {
752 _io("Connector cannot be removed");
756 # Remove from list of active connectors
757 _config_list_del(['defined-connectors'], $name);
758 _config_list_del(['active-connectors'], $name);
760 _config_del(['connectors', $name, 'name']);
761 _config_del(['connectors', $name, '_immutable']);
762 _config_del(['connectors', $name, 'schemas', 'http']);
763 _config_del(['connectors', $name, 'schemas', 'https']);
765 @dcon = split(/,/, _config_get(['active-connectors']));
767 if (scalar(@dcon) == 0) {
768 _io("List of selected connectors is empty, resetting to direct");
769 _config_list_add(['active-connectors', 'direct']);
771 } elsif ($subcmd eq 'addschema') {
772 my ($conn, $schema, $proxy) = @_;
774 unless(defined($conn)) {
775 _io("No connector name given");
779 unless(defined($schema)) {
780 _io("No schema given");
784 unless(defined($proxy)) {
785 _io("No proxy given");
790 unless(_config_list_has(['defined-connectors'], $conn)) {
791 _io("Connector does not exist");
795 if (_config_has(['connectors', $conn, '_immutable'])) {
796 _io("Connector cannot be modified");
800 $schema = lc($schema);
801 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
802 } elsif ($subcmd eq 'delschema') {
803 my ($conn, $schema) = @_;
805 unless(defined($conn)) {
806 _io("No connector name given");
810 unless(defined($schema)) {
811 _io("No schema given");
816 unless(_config_list_has(['defined-connectors'], $conn)) {
817 _io("Connector does not exist");
821 $schema = lc($schema);
822 _config_del(['connectors', $conn, 'schemas', $schema]);
823 } elsif ($subcmd eq 'select') {
824 my @connlist = map { lc } @_;
826 if (scalar(@connlist) == 0) {
827 _io("No connectors given");
831 foreach (@connlist) {
832 unless(_config_list_has(['defined-connectors'], $_)) {
833 _io("Connector %s does not exist", $_);
838 _config_list_set(['active-connectors'], @connlist);
840 _io("connector [list|add|del|addschema|delschema|help] <options>");
841 _io(" help: Show this help");
842 _io(" list: List the defined connectors");
843 _io(" add <name>: Add a connector with name <name>");
844 _io(" del <name>: Delete the connector with name <name>");
845 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
846 _io(" delschema <name> <schema>: Remove the schema from the connector");
847 _io(" select <name> [<name>...]: Select the connectors to use");
852 # Return the list of loaded grabbers.
853 # This is used by the test programs, and is not meant to be
861 # ==============================================
862 # Builtin config handling functions
863 # These are used if the library used does not
864 # register it's own config_* handlers
865 # ==============================================
867 sub _builtin_config_init {
870 sub _builtin_config_get {
871 return $builtin_config{join(".", @{$_[0]})};
874 sub _builtin_config_set {
875 $builtin_config{join(".", @{$_[0]})} = $_[1];
878 sub _builtin_config_has {
879 return exists($builtin_config{join(".", @{$_[0]})});
882 sub _builtin_config_save {
885 sub _builtin_config_del {
886 delete($builtin_config{join(".", @{$_[0]})});
890 # ==============================================
891 # From this point on publicly callable functions
892 # ==============================================
897 # Initialization function for the library
898 # Actually not the first thing to be called, it expects an API
899 # has (register_api) to be registered first
902 unless($remote_api) {
903 $error = "No API set";
907 # Initialize configuration data
908 $remote_api->{config_init}->();
910 # Check/create default values, if they do not exist
911 _recursive_hash_walk($defaultconfig, \&_init_config_item);
914 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
916 unless (@grabbers && @getters) {
917 _io('No grabbers or no getters found, can not proceed.');
922 $getter = $getters[0];
923 foreach my $p (@getters) {
924 if (_config_get(['getter']) eq $p->{'NAME'}) {
928 _debug('Selected %s as getter', $getter->{'NAME'});
929 _config_set(['getter'], $getter->{'NAME'});
932 _io('initialized successfully');
937 # Register a remote API. This API contains a basic output function (used
938 # when no window specific function is available), some config functions
939 # and a color code function.
943 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
947 unless(defined($a)) {
952 # The config_* handlers are special in that they either all have
953 # provided by the user, or none. In the latter case builtin
954 # handlers will be used, but the config will not persist.
957 foreach (@config_functions) {
958 if (exists($a->{$_})) {
965 unless (($c == 0) or ($c == scalar(@config_functions))) {
966 $error = sprintf("Missing config function: %s", $missing[0]);
970 foreach (keys(%{$a})) {
971 if (ref($a->{$_}) ne 'CODE') {
972 $error = sprintf("API handler %s is not a subroutine reference", $_);
974 $remote_api->{$_} = $a->{$_};
977 if (exists($a->{_debug})) {
978 $debug = $a->{_debug}->();
981 @outputstack = ($remote_api->{'io'});
987 # Check a message for useable links
991 my $message = $event->{message};
996 my $mode = _config_get(['mode']);
1000 # If /nosave is present in the message switch to display mode, regardless
1003 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
1007 _push_output($event->{ewpf});
1008 $message = _expand_url_shortener($message);
1012 # Offer the message to all Grabbers in turn
1013 GRABBER: foreach $g (@grabbers) {
1014 ($m, $p) = $g->get($message);
1015 while (defined($m)) {
1016 _debug('Metadata: %s', Dumper($m));
1018 if (exists($remote_api->{link_callback})) {
1019 $skip = $remote_api->{link_callback}->($m);
1022 if ('download' eq $mode) {
1024 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
1027 _colorpair('*yellow'),
1029 _colorpair('*green'),
1034 unless($getter->get($m)) {
1035 _io(sprintf('%s>>> FAILED', _colorpair('*red')));
1037 } elsif ('display' eq $mode) {
1039 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1040 _colorpair('*magenta'),
1042 _colorpair('*yellow'),
1044 _colorpair('*green')
1050 _io(sprintf('%s>>> Invalid operation mode', _colorpair('*red')));
1054 # Remove the matched part from the message and try again (there may be
1058 last GRABBER if ($message =~ /^\s*$/);
1060 ($m, $p) = $g->get($message);
1068 # Handle a videosite command (/videosite ...) entered in the client
1070 sub handle_command {
1072 my ($cmd, @params) = split(/\s+/, $event->{message});
1074 _push_output($event->{ewpf});
1076 if (exists($videosite_commands->{$cmd})) {
1077 $videosite_commands->{$cmd}->(@params);