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->{reload}->();
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 if ($remote_api->{config_save}->()) {
529 _io(sprintf("%sConfig save failed%s", _colorpair("*red"), _colorpair()));
534 # Set a configuration element
542 foreach $p (@getters, @grabbers) {
543 if ($p->{'NAME'} eq $target) {
544 $p->setval($key, $val);
548 _io('No such module');
553 # Enable a given module
559 foreach $p (@grabbers) {
560 if ($p->{'NAME'} eq $target) {
565 _io('No such module');
569 # Disable given module
575 foreach $p (@grabbers) {
576 if ($p->{'NAME'} eq $target) {
581 _io('No such module');
585 # Show settings for modules
592 if (defined($target)) {
593 foreach $p (@getters, @grabbers) {
594 if ($p->{'NAME'} eq $target) {
595 _io($p->getconfstr());
599 _io('No such module');
601 _io('Loaded grabbers (* denotes enabled modules):');
602 foreach $p (@grabbers) {
603 $e = $p->_getval('enabled');
604 _io(' %s%s', $p->{'NAME'}, $e?'*':'');
607 _io('Loaded getters:');
608 foreach $p (@getters) {
609 _io(' %s', $p->{'NAME'});
615 # Show help for the commands
621 if (defined($target)) {
622 foreach $p (@getters, @grabbers) {
623 if ($p->{'NAME'} eq $target) {
624 _io($p->gethelpstr());
628 _io('No such module');
632 save: save the current configuration
633 help [modulename]: display this help, or module specific help
634 show [modulename]: show loaded modules, or the current parameters of a module
635 set modulename parameter value: set a module parameter to a new value
636 getter [modulename]: display or set the getter to use
637 enable [modulename]: enable the usage of this module (grabbers only)
638 disable [modulename]: disable the usage of this module (grabbers only)
639 reload: reload all modules (this is somewhat experimental)
640 mode [modename]: display or set the operation mode (download/display)
641 connector [subcommand]: manage connectors (proxies)
642 debug: enable debugging messages
643 nodebug: disable debugging messages
649 # Set the getter to use
655 if (defined($target)) {
656 foreach $p (@getters) {
657 if ($p->{'NAME'} eq $target) {
659 _config_set(['getter'], $target);
660 _io("Getter changed to %s", $target);
664 _io('No such getter');
666 _io('Current getter: %s', _config_get(['getter']));
671 # Show/set the working mode
676 if (defined($mode)) {
678 if (('download' eq $mode) or ('display' eq $mode)) {
679 _config_set(['mode'], $mode);
680 _io('Now using %s mode', $mode);
682 _io('Invalid mode: %s', $mode);
685 _io('Current mode: %s', _config_get(['mode']));
691 # Manage the connectors
697 unless(defined($subcmd)) {
701 $subcmd = lc($subcmd);
703 if ($subcmd eq 'list') {
704 _io("Defined connectors");
705 foreach $c (_connectorlist('defined-connectors')) {
707 my $schemas = $c->{schemas};
708 if (scalar(keys(%{$schemas})) == 0) {
709 _io(" No schemas defined");
711 foreach (keys(%{$schemas})) {
712 _io(' %s: %s', $_, $schemas->{$_});
718 _io("Selected connectors: %s", _config_get(['active-connectors']));
719 } elsif ($subcmd eq 'add') {
722 unless(defined($name)) {
723 _io("No name given");
729 unless($name =~ m|^[a-z]+$|) {
730 _io("%s is not a valid connector name (only letters are allowed)", $name);
734 if (_config_list_has(['defined-connectors'], $name)) {
735 _io("Connector already exists");
739 _config_set(['connectors', $name, 'name'], $name);
740 _config_list_add(['defined-connectors'], $name);
741 } elsif ($subcmd eq 'del') {
745 unless(defined($name)) {
746 _io("No name given");
750 unless (_config_list_has(['defined-connectors'], $name)) {
751 _io("Connector does not exist");
755 if (_config_has(['connectors', $name, '_immutable'])) {
756 _io("Connector cannot be removed");
760 # Remove from list of active connectors
761 _config_list_del(['defined-connectors'], $name);
762 _config_list_del(['active-connectors'], $name);
764 _config_del(['connectors', $name, 'name']);
765 _config_del(['connectors', $name, '_immutable']);
766 _config_del(['connectors', $name, 'schemas', 'http']);
767 _config_del(['connectors', $name, 'schemas', 'https']);
769 @dcon = split(/,/, _config_get(['active-connectors']));
771 if (scalar(@dcon) == 0) {
772 _io("List of selected connectors is empty, resetting to direct");
773 _config_list_add(['active-connectors', 'direct']);
775 } elsif ($subcmd eq 'addschema') {
776 my ($conn, $schema, $proxy) = @_;
778 unless(defined($conn)) {
779 _io("No connector name given");
783 unless(defined($schema)) {
784 _io("No schema given");
788 unless(defined($proxy)) {
789 _io("No proxy given");
794 unless(_config_list_has(['defined-connectors'], $conn)) {
795 _io("Connector does not exist");
799 if (_config_has(['connectors', $conn, '_immutable'])) {
800 _io("Connector cannot be modified");
804 $schema = lc($schema);
805 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
806 } elsif ($subcmd eq 'delschema') {
807 my ($conn, $schema) = @_;
809 unless(defined($conn)) {
810 _io("No connector name given");
814 unless(defined($schema)) {
815 _io("No schema given");
820 unless(_config_list_has(['defined-connectors'], $conn)) {
821 _io("Connector does not exist");
825 $schema = lc($schema);
826 _config_del(['connectors', $conn, 'schemas', $schema]);
827 } elsif ($subcmd eq 'select') {
828 my @connlist = map { lc } @_;
830 if (scalar(@connlist) == 0) {
831 _io("No connectors given");
835 foreach (@connlist) {
836 unless(_config_list_has(['defined-connectors'], $_)) {
837 _io("Connector %s does not exist", $_);
842 _config_list_set(['active-connectors'], @connlist);
844 _io("connector [list|add|del|addschema|delschema|help] <options>");
845 _io(" help: Show this help");
846 _io(" list: List the defined connectors");
847 _io(" add <name>: Add a connector with name <name>");
848 _io(" del <name>: Delete the connector with name <name>");
849 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
850 _io(" delschema <name> <schema>: Remove the schema from the connector");
851 _io(" select <name> [<name>...]: Select the connectors to use");
856 # Return the list of loaded grabbers.
857 # This is used by the test programs, and is not meant to be
865 # ==============================================
866 # Builtin config handling functions
867 # These are used if the library used does not
868 # register it's own config_* handlers
869 # ==============================================
871 sub _builtin_config_init {
874 sub _builtin_config_get {
875 return $builtin_config{join(".", @{$_[0]})};
878 sub _builtin_config_set {
879 $builtin_config{join(".", @{$_[0]})} = $_[1];
882 sub _builtin_config_has {
883 return exists($builtin_config{join(".", @{$_[0]})});
886 sub _builtin_config_save {
889 sub _builtin_config_del {
890 delete($builtin_config{join(".", @{$_[0]})});
894 # ==============================================
895 # From this point on publicly callable functions
896 # ==============================================
901 # Initialization function for the library
902 # Actually not the first thing to be called, it expects an API
903 # has (register_api) to be registered first
906 unless($remote_api) {
907 $error = "No API set";
911 # Initialize configuration data
912 $remote_api->{config_init}->();
914 # Check/create default values, if they do not exist
915 _recursive_hash_walk($defaultconfig, \&_init_config_item);
918 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
920 unless (@grabbers && @getters) {
921 _io('No grabbers or no getters found, can not proceed.');
926 $getter = $getters[0];
927 foreach my $p (@getters) {
928 if (_config_get(['getter']) eq $p->{'NAME'}) {
932 _debug('Selected %s as getter', $getter->{'NAME'});
933 _config_set(['getter'], $getter->{'NAME'});
936 _io('initialized successfully');
941 # Register a remote API. This API contains a basic output function (used
942 # when no window specific function is available), some config functions
943 # and a color code function.
947 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
951 unless(defined($a)) {
956 # The config_* handlers are special in that they either all have
957 # provided by the user, or none. In the latter case builtin
958 # handlers will be used, but the config will not persist.
961 foreach (@config_functions) {
962 if (exists($a->{$_})) {
969 unless (($c == 0) or ($c == scalar(@config_functions))) {
970 $error = sprintf("Missing config function: %s", $missing[0]);
974 foreach (keys(%{$a})) {
975 if (ref($a->{$_}) ne 'CODE') {
976 $error = sprintf("API handler %s is not a subroutine reference", $_);
978 $remote_api->{$_} = $a->{$_};
981 if (exists($a->{_debug})) {
982 $debug = $a->{_debug}->();
985 @outputstack = ($remote_api->{'io'});
991 # Check a message for useable links
995 my $message = $event->{message};
1000 my $mode = _config_get(['mode']);
1004 # If /nosave is present in the message switch to display mode, regardless
1007 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
1011 _push_output($event->{ewpf});
1012 $message = _expand_url_shortener($message);
1016 # Offer the message to all Grabbers in turn
1017 GRABBER: foreach $g (@grabbers) {
1018 ($m, $p) = $g->get($message);
1019 while (defined($m)) {
1020 _debug('Metadata: %s', Dumper($m));
1022 if (exists($remote_api->{link_callback})) {
1023 $skip = $remote_api->{link_callback}->($m);
1026 if ('download' eq $mode) {
1028 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
1031 _colorpair('*yellow'),
1033 _colorpair('*green'),
1038 unless($getter->get($m)) {
1039 _io(sprintf('%s>>> FAILED', _colorpair('*red')));
1041 } elsif ('display' eq $mode) {
1043 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1044 _colorpair('*magenta'),
1046 _colorpair('*yellow'),
1048 _colorpair('*green')
1054 _io(sprintf('%s>>> Invalid operation mode', _colorpair('*red')));
1058 # Remove the matched part from the message and try again (there may be
1062 last GRABBER if ($message =~ /^\s*$/);
1064 ($m, $p) = $g->get($message);
1072 # Handle a videosite command (/videosite ...) entered in the client
1074 sub handle_command {
1076 my ($cmd, @params) = split(/\s+/, $event->{message});
1078 _push_output($event->{ewpf});
1080 if (exists($videosite_commands->{$cmd})) {
1081 $videosite_commands->{$cmd}->(@params);