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 = grep { $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 unless($name =~ m|^[a-z]+$|) {
725 _io("%s is not a valid connector name (only letters are allowed)", $name);
729 if (_config_list_has(['defined-connectors'], $name)) {
730 _io("Connector already exists");
734 _config_set(['connectors', $name, 'name'], $name);
735 _config_list_add(['defined-connectors'], $name);
736 } elsif ($subcmd eq 'del') {
740 unless(defined($name)) {
741 _io("No name given");
745 unless (_config_list_has(['defined-connectors'], $name)) {
746 _io("Connector does not exist");
750 if (_config_has(['connectors', $name, '_immutable'])) {
751 _io("Connector cannot be removed");
755 # Remove from list of active connectors
756 _config_list_del(['defined-connectors'], $name);
757 _config_list_del(['active-connectors'], $name);
759 _config_del(['connectors', $name, 'name']);
760 _config_del(['connectors', $name, '_immutable']);
761 _config_del(['connectors', $name, 'schemas', 'http']);
762 _config_del(['connectors', $name, 'schemas', 'https']);
764 @dcon = split(/,/, _config_get(['active-connectors']));
766 if (scalar(@dcon) == 0) {
767 _io("List of selected connectors is empty, resetting to direct");
768 _config_list_add(['active-connectors', 'direct']);
770 } elsif ($subcmd eq 'addschema') {
771 my ($conn, $schema, $proxy) = @_;
773 unless(defined($conn)) {
774 _io("No connector name given");
778 unless(defined($schema)) {
779 _io("No schema given");
783 unless(defined($proxy)) {
784 _io("No proxy given");
789 unless(_config_list_has(['defined-connectors'], $conn)) {
790 _io("Connector does not exist");
794 if (_config_has(['connectors', $conn, '_immutable'])) {
795 _io("Connector cannot be modified");
799 $schema = lc($schema);
800 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
801 } elsif ($subcmd eq 'delschema') {
802 my ($conn, $schema) = @_;
804 unless(defined($conn)) {
805 _io("No connector name given");
809 unless(defined($schema)) {
810 _io("No schema given");
815 unless(_config_list_has(['defined-connectors'], $conn)) {
816 _io("Connector does not exist");
820 $schema = lc($schema);
821 _config_del(['connectors', $conn, 'schemas', $schema]);
822 } elsif ($subcmd eq 'select') {
823 my @connlist = map { lc } @_;
825 if (scalar(@connlist) == 0) {
826 _io("No connectors given");
830 foreach (@connlist) {
831 unless(_config_list_has(['defined-connectors'], $_)) {
832 _io("Connector %s does not exist", $_);
837 _config_list_set(['active-connectors'], @connlist);
839 _io("connector [list|add|del|addschema|delschema|help] <options>");
840 _io(" help: Show this help");
841 _io(" list: List the defined connectors");
842 _io(" add <name>: Add a connector with name <name>");
843 _io(" del <name>: Delete the connector with name <name>");
844 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
845 _io(" delschema <name> <schema>: Remove the schema from the connector");
846 _io(" select <name> [<name>...]: Select the connectors to use");
851 # Return the list of loaded grabbers.
852 # This is used by the test programs, and is not meant to be
860 # ==============================================
861 # Builtin config handling functions
862 # These are used if the library used does not
863 # register it's own config_* handlers
864 # ==============================================
866 sub _builtin_config_init {
869 sub _builtin_config_get {
870 return $builtin_config{join(".", @{$_[0]})};
873 sub _builtin_config_set {
874 $builtin_config{join(".", @{$_[0]})} = $_[1];
877 sub _builtin_config_has {
878 return exists($builtin_config{join(".", @{$_[0]})});
881 sub _builtin_config_save {
884 sub _builtin_config_del {
885 delete($builtin_config{join(".", @{$_[0]})});
889 # ==============================================
890 # From this point on publicly callable functions
891 # ==============================================
896 # Initialization function for the library
897 # Actually not the first thing to be called, it expects an API
898 # has (register_api) to be registered first
901 unless($remote_api) {
902 $error = "No API set";
906 # Initialize configuration data
907 $remote_api->{config_init}->();
909 # Check/create default values, if they do not exist
910 _recursive_hash_walk($defaultconfig, \&_init_config_item);
913 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
915 unless (@grabbers && @getters) {
916 _io('No grabbers or no getters found, can not proceed.');
921 $getter = $getters[0];
922 foreach my $p (@getters) {
923 if (_config_get(['getter']) eq $p->{'NAME'}) {
927 _debug('Selected %s as getter', $getter->{'NAME'});
928 _config_set(['getter'], $getter->{'NAME'});
931 _io('initialized successfully');
936 # Register a remote API. This API contains a basic output function (used
937 # when no window specific function is available), some config functions
938 # and a color code function.
942 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
946 unless(defined($a)) {
951 # The config_* handlers are special in that they either all have
952 # provided by the user, or none. In the latter case builtin
953 # handlers will be used, but the config will not persist.
956 foreach (@config_functions) {
957 if (exists($a->{$_})) {
964 unless (($c == 0) or ($c == scalar(@config_functions))) {
965 $error = sprintf("Missing config function: %s", $missing[0]);
969 foreach (keys(%{$a})) {
970 if (ref($a->{$_}) ne 'CODE') {
971 $error = sprintf("API handler %s is not a subroutine reference", $_);
973 $remote_api->{$_} = $a->{$_};
976 if (exists($a->{_debug})) {
977 $debug = $a->{_debug}->();
980 @outputstack = ($remote_api->{'io'});
986 # Check a message for useable links
990 my $message = $event->{message};
995 my $mode = _config_get(['mode']);
999 # If /nosave is present in the message switch to display mode, regardless
1002 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
1006 _push_output($event->{ewpf});
1007 $message = _expand_url_shortener($message);
1011 # Offer the message to all Grabbers in turn
1012 GRABBER: foreach $g (@grabbers) {
1013 ($m, $p) = $g->get($message);
1014 while (defined($m)) {
1015 _debug('Metadata: %s', Dumper($m));
1017 if (exists($remote_api->{link_callback})) {
1018 $skip = $remote_api->{link_callback}->($m);
1021 if ('download' eq $mode) {
1023 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
1026 _colorpair('*yellow'),
1028 _colorpair('*green'),
1033 unless($getter->get($m)) {
1034 _io(sprintf('%s>>> FAILED', _colorpair('*red')));
1036 } elsif ('display' eq $mode) {
1038 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1039 _colorpair('*magenta'),
1041 _colorpair('*yellow'),
1043 _colorpair('*green')
1049 _io(sprintf('%s>>> Invalid operation mode', _colorpair('*red')));
1053 # Remove the matched part from the message and try again (there may be
1057 last GRABBER if ($message =~ /^\s*$/);
1059 ($m, $p) = $g->get($message);
1067 # Handle a videosite command (/videosite ...) entered in the client
1069 sub handle_command {
1071 my ($cmd, @params) = split(/\s+/, $event->{message});
1073 _push_output($event->{ewpf});
1075 if (exists($videosite_commands->{$cmd})) {
1076 $videosite_commands->{$cmd}->(@params);