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 $remote_api->{color}->('magenta'),
149 $remote_api->{color}->()) 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 return $remote_api->{color}->($fg, $bg);
190 # Sets the given config item if it is not set already
192 sub _init_config_item {
196 unless(_config_has($path)) {
197 _config_set($path, $value);
202 # Print a message if debug is enabled
211 # Load a list of modules matching a pattern from a given directory.
223 opendir(D, $dir) || return ();
224 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
228 _debug("Trying to load $p:");
231 load "videosite::$p";
234 _io("Failed to load plugin: $@");
239 $g = "videosite::$p"->new();
242 _io("Failed to instanciate: $@");
247 _debug("found $g->{'TYPE'} $g->{'NAME'}");
248 if ($type eq $g->{'TYPE'}) {
252 connectors => sub { return _connectorlist('active-connectors') },
253 config_get => \&_config_get,
254 config_set => \&_config_set,
255 config_has => \&_config_has,
257 $g->setdebug($debug);
259 _io('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
264 _debug("Loaded %d plugins", $#g+1);
270 # Populate the @grabbers and @getters lists from the given
273 sub _load_modules($) {
277 foreach (keys(%INC)) {
278 if ($INC{$_} =~ m|^$path|) {
279 _debug("Removing %s from \$INC", $_);
283 @grabbers = _ploader($path, '.*Grabber\.pm$', 'grabber');
284 @getters = _ploader($path, '.*Getter\.pm$', 'getter');
288 # Wrapper functions for config management to put in
295 $value = $remote_api->{config_get}->($path);
296 _debug("config: getting %s=%s", join('.', @{$path}), $value);
305 _debug("config: setting %s=%s", join('.', @{$path}), $value);
306 return $remote_api->{config_set}->($path, $value);
313 $b = $remote_api->{config_has}->($path);
314 _debug("config: testing %s (%s)", join('.', @{$path}), $b?'true':'false');
320 # The _config_list_* are helper functions taking a path to a comma separated
321 # string. The string is interpreted as a list and the action performed
322 # on it, storing back the modified version
326 # Add an item to the list, checking for duplicates
328 sub _config_list_add {
333 if (_config_has($path)) {
334 @c = split(/\s*,\s*/, _config_get($path));
339 _debug("Adding %s to list %s", $item, join(".", $path));
340 unless(grep { $_ eq $item } @c) {
344 _config_set($path, join(',', @c));
348 # Remove an item from the list
350 sub _config_list_del {
355 unless(_config_has($path)) {
359 _debug("Removing %s from list %s", $item, join('.', $path));
360 @c = map { $item ne $_ } split(/\s*,\s*/, _config_get($path));
362 _config_set($path, join('.', @c));
366 # Return true if the item contains the given list, false otherwise
368 sub _config_list_has {
372 unless(_config_has($path)) {
376 _debug("Checking for %s in list %s", $item, join('.', $path));
378 return grep { $item eq $_ } split(/\s*,\s*/, _config_get($path));
382 # Replace a list with the given items
384 sub _config_list_set {
387 _debug("Replacing %s with (%s)", join('.', $path), join(",", @_));
389 _config_set($path, join(',', @_));
393 # Return the list of currently active connectors, in the configured
400 foreach(split(/,/, _config_get([$key]))) {
401 push(@c, _unserialize_connector_hash($_));
408 # Convert a connector hash from it's config structure back to a perl
411 sub _unserialize_connector_hash {
415 if (_config_has(['connectors', $name, 'name'])) {
416 $connector->{name} = _config_get(['connectors', $name, 'name']);
417 $connector->{schemas} = {};
418 foreach ('http', 'https') {
419 if (_config_has(['connectors', $name, 'schemas', $_])) {
420 $connector->{schemas}->{$_} = _config_get(['connectors', $name, 'schemas', $_]);
425 _debug("Returning connector %s: %s", $name, Dumper($connector));
431 # Push a new output function on the IO stack.
434 unshift(@outputstack, shift);
438 # Pop the topmost output function from the stack, leaving
439 # at least one function on it.
442 if (scalar(@outputstack) > 0) {
448 # Takes a string and replaces commonly used URL shorteners recursively,
449 # up to 10 levels deep
451 sub _expand_url_shortener {
455 'is\.gd/[[:alnum:]]+',
456 'otf\.me/[[:alnum:]]+',
457 'hel\.me/[[:alnum:]]+',
458 '7ax\.de/[[:alnum:]]+',
459 'ow\.ly/[[:alnum:]]+',
460 'j\.mp/[[:alnum:]]+',
461 'bit\.ly/[[:alnum:]]+',
462 'tinyurl\.com/[[:alnum:]]+',
463 'pop\.is/[[:alnum:]]+',
464 'post\.ly/[[:alnum:]]+',
465 '1\.ly/[[:alnum:]]+',
466 '2\.ly/[[:alnum:]]+',
467 't\.co/[[:alnum:]]+',
468 'shar\.es/[[:alnum:]]+',
469 'goo\.gl/[[:alnum:]]+',
471 my $ua = LWP::UserAgent->new(agent => 'Mozilla', max_redirect => 0, timeout => 5);
474 OUTER: while (($os ne $s) and ($i > 0)) {
479 foreach my $pattern (@urlshortener) {
480 my $p = "https?:\/\/" . $pattern;
482 _debug("Matching %s against %s", $p, $s);
487 _debug("Found %s", $matched);
488 $res = $ua->head($matched);
489 if ($res->is_redirect()) {
490 my $new = $res->headers()->header("Location");
492 _debug("Replacing %s with %s", $matched, $new);
493 $s =~ s/$matched/$new/;
496 _debug("Error resolving %s", $matched);
503 _debug("Loop terminated by counter");
506 _debug("Final string: %s", $s);
512 # Save the config to durable storage
515 $remote_api->{config_save}->();
519 # Set a configuration element
527 foreach $p (@getters, @grabbers) {
528 if ($p->{'NAME'} eq $target) {
529 $p->setval($key, $val);
533 _io('No such module');
538 # Enable a given module
544 foreach $p (@grabbers) {
545 if ($p->{'NAME'} eq $target) {
550 _io('No such module');
554 # Disable given module
560 foreach $p (@grabbers) {
561 if ($p->{'NAME'} eq $target) {
566 _io('No such module');
570 # Show settings for modules
577 if (defined($target)) {
578 foreach $p (@getters, @grabbers) {
579 if ($p->{'NAME'} eq $target) {
580 _io($p->getconfstr());
584 _io('No such module');
586 _io('Loaded grabbers (* denotes enabled modules):');
587 foreach $p (@grabbers) {
588 $e = $p->_getval('enabled');
589 _io(' %s%s', $p->{'NAME'}, $e?'*':'');
592 _io('Loaded getters:');
593 foreach $p (@getters) {
594 _io(' %s', $p->{'NAME'});
600 # Show help for the commands
606 if (defined($target)) {
607 foreach $p (@getters, @grabbers) {
608 if ($p->{'NAME'} eq $target) {
609 _io($p->gethelpstr());
613 _io('No such module');
617 save: save the current configuration
618 help [modulename]: display this help, or module specific help
619 show [modulename]: show loaded modules, or the current parameters of a module
620 set modulename parameter value: set a module parameter to a new value
621 getter [modulename]: display or set the getter to use
622 enable [modulename]: enable the usage of this module (grabbers only)
623 disable [modulename]: disable the usage of this module (grabbers only)
624 reload: reload all modules (this is somewhat experimental)
625 mode [modename]: display or set the operation mode (download/display)
626 connector [subcommand]: manage connectors (proxies)
627 debug: enable debugging messages
628 nodebug: disable debugging messages
634 # Set the getter to use
640 if (defined($target)) {
641 foreach $p (@getters) {
642 if ($p->{'NAME'} eq $target) {
644 _config_set(['getter'], $target);
645 _io("Getter changed to %s", $target);
649 _io('No such getter');
651 _io('Current getter: %s', _config_get(['getter']));
656 # Show/set the working mode
661 if (defined($mode)) {
663 if (('download' eq $mode) or ('display' eq $mode)) {
664 _config_set(['mode'], $mode);
665 _io('Now using %s mode', $mode);
667 _io('Invalid mode: %s', $mode);
670 _io('Current mode: %s', _config_get(['mode']));
676 # Manage the connectors
682 unless(defined($subcmd)) {
686 $subcmd = lc($subcmd);
688 if ($subcmd eq 'list') {
689 _io("Defined connectors");
690 foreach $c (_connectorlist('defined-connectors')) {
692 my $schemas = $c->{schemas};
693 if (scalar(keys(%{$schemas})) == 0) {
694 _io(" No schemas defined");
696 foreach (keys(%{$schemas})) {
697 _io(' %s: %s', $_, $schemas->{$_});
703 _io("Selected connectors: %s", _config_get(['active-connectors']));
704 } elsif ($subcmd eq 'add') {
707 unless(defined($name)) {
708 _io("No name given");
714 if (_config_list_has(['defined-connectors'], $name)) {
715 _io("Connector already exists");
719 _config_set(['connectors', $name, 'name'], $name);
720 _config_list_add(['defined-connectors'], $name);
721 } elsif ($subcmd eq 'del') {
725 unless(defined($name)) {
726 _io("No name given");
730 unless (_config_list_has(['defined-connectors'])) {
731 _io("Connector does not exist");
735 if (_config_has(['connectors', $name, '_immutable'])) {
736 _io("Connector cannot be removed");
740 # Remove from list of active connectors
741 _config_list_del(['defined-connectors'], $name);
742 _config_list_del(['active-connectors'], $name);
744 _config_del(['connectors', $name, 'name']);
745 _config_del(['connectors', $name, '_immutable']);
746 _config_del(['connectors', $name, 'schemas', 'http']);
747 _config_del(['connectors', $name, 'schemas', 'https']);
749 @dcon = split(/,/, _config_get(['active-connectors']));
751 if (scalar(@dcon) == 0) {
752 _io("List of selected connectors is empty, resetting to direct");
753 _config_list_add(['active-connectors', 'direct']);
755 } elsif ($subcmd eq 'addschema') {
756 my ($conn, $schema, $proxy) = @_;
758 unless(defined($conn)) {
759 _io("No connector name given");
763 unless(defined($schema)) {
764 _io("No schema given");
768 unless(defined($proxy)) {
769 _io("No proxy given");
774 unless(_config_list_has(['defined-connectors'], $conn)) {
775 _io("Connector does not exist");
779 if (_config_has(['connectors', $conn, '_immutable'])) {
780 _io("Connector cannot be modified");
784 $schema = lc($schema);
785 _config_set(['connectors', $conn, 'schemas', $schema], $proxy);
786 } elsif ($subcmd eq 'delschema') {
787 my ($conn, $schema) = @_;
789 unless(defined($conn)) {
790 _io("No connector name given");
794 unless(defined($schema)) {
795 _io("No schema given");
800 unless(_config_list_has(['defined-connectors'], $conn)) {
801 _io("Connector does not exist");
805 $schema = lc($schema);
806 _config_del(['connectors', $conn, 'schemas', $schema]);
807 } elsif ($subcmd eq 'select') {
808 my @connlist = map { lc } @_;
810 if (scalar(@connlist) == 0) {
811 _io("No connectors given");
815 foreach (@connlist) {
816 unless(_config_list_has(['defined-connectors'], $_)) {
817 _io("Connector %s does not exist", $_);
822 _config_list_set(['active-connectors'], @connlist);
824 _io("connector [list|add|del|addschema|delschema|help] <options>");
825 _io(" help: Show this help");
826 _io(" list: List the defined connectors");
827 _io(" add <name>: Add a connector with name <name>");
828 _io(" del <name>: Delete the connector with name <name>");
829 _io(" addschema <name> <schema> <proxy>: Add proxy to connector for the given schema");
830 _io(" delschema <name> <schema>: Remove the schema from the connector");
831 _io(" select <name> [<name>...]: Select the connectors to use");
836 # Return the list of loaded grabbers.
837 # This is used by the test programs, and is not meant to be
845 # ==============================================
846 # Builtin config handling functions
847 # These are used if the library used does not
848 # register it's own config_* handlers
849 # ==============================================
851 sub _builtin_config_init {
854 sub _builtin_config_get {
855 return $builtin_config{join(".", @{$_[0]})};
858 sub _builtin_config_set {
859 $builtin_config{join(".", @{$_[0]})} = $_[1];
862 sub _builtin_config_has {
863 return exists($builtin_config{join(".", @{$_[0]})});
866 sub _builtin_config_save {
869 sub _builtin_config_del {
870 delete($builtin_config{join(".", @{$_[0]})});
874 # ==============================================
875 # From this point on publicly callable functions
876 # ==============================================
881 # Initialization function for the library
882 # Actually not the first thing to be called, it expects an API
883 # has (register_api) to be registered first
886 unless($remote_api) {
887 $error = "No API set";
891 # Initialize configuration data
892 $remote_api->{config_init}->();
894 # Check/create default values, if they do not exist
895 _recursive_hash_walk($defaultconfig, \&_init_config_item);
898 _load_modules(File::Spec->catfile($remote_api->{module_path}->(), 'videosite'));
900 unless (@grabbers && @getters) {
901 _io('No grabbers or no getters found, can not proceed.');
906 $getter = $getters[0];
907 foreach my $p (@getters) {
908 if (_config_get(['getter']) eq $p->{'NAME'}) {
912 _debug('Selected %s as getter', $getter->{'NAME'});
913 _config_set(['getter'], $getter->{'NAME'});
916 _io('initialized successfully');
921 # Register a remote API. This API contains a basic output function (used
922 # when no window specific function is available), some config functions
923 # and a color code function.
927 my @config_functions = qw(config_init config_set config_get config_has config_save config_del);
931 unless(defined($a)) {
936 # The config_* handlers are special in that they either all have
937 # provided by the user, or none. In the latter case builtin
938 # handlers will be used, but the config will not persist.
941 foreach (@config_functions) {
942 if (exists($a->{$_})) {
949 unless (($c == 0) or ($c == scalar(@config_functions))) {
950 $error = sprintf("Missing config function: %s", $missing[0]);
954 foreach (keys(%{$a})) {
955 if (ref($a->{$_}) ne 'CODE') {
956 $error = sprintf("API handler %s is not a subroutine reference", $_);
958 $remote_api->{$_} = $a->{$_};
961 if (exists($a->{_debug})) {
962 $debug = $a->{_debug}->();
965 @outputstack = ($remote_api->{'io'});
971 # Check a message for useable links
975 my $message = $event->{message};
981 # Look if we should ignore this line
982 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
986 _push_output($event->{ewpf});
987 $message = _expand_url_shortener($message);
991 # Offer the message to all Grabbers in turn
992 GRABBER: foreach $g (@grabbers) {
993 ($m, $p) = $g->get($message);
994 while (defined($m)) {
995 _debug('Metadata: %s', Dumper($m));
996 if (exists($remote_api->{link_callback})) {
997 $remote_api->{link_callback}->($m);
999 if ('download' eq _config_get(['mode'])) {
1001 sprintf('%s>>> %sSaving %s%%s%s %s%%s',
1002 $remote_api->{color}->('*red'),
1003 $remote_api->{color}->(),
1004 $remote_api->{color}->('*yellow'),
1005 $remote_api->{color}->(),
1006 $remote_api->{color}->('*green'),
1011 unless($getter->get($m)) {
1012 _io(sprintf('%s>>> FAILED', $remote_api->{color}->('*red')));
1014 } elsif ('display' eq _config_get(['mode'])) {
1016 sprintf('%s>>> %sSaw %s%%s%s %s%%s',
1017 $remote_api->{color}->('*magenta'),
1018 $remote_api->{color}->(),
1019 $remote_api->{color}->('*yellow'),
1020 $remote_api->{color}->(),
1021 $remote_api->{color}->('*green')
1027 _io(sprintf('%s>>> Invalid operation mode', $remote_api->{color}->('*red')));
1030 # Remove the matched part from the message and try again (there may be
1034 last GRABBER if ($message =~ /^\s*$/);
1036 ($m, $p) = $g->get($message);
1044 # Handle a videosite command (/videosite ...) entered in the client
1046 sub handle_command {
1048 my ($cmd, @params) = split(/\s+/, $event->{message});
1050 _push_output($event->{ewpf});
1052 if (exists($videosite_commands->{$cmd})) {
1053 $videosite_commands->{$cmd}->(@params);