jnotify.pl 16.8 KB
Newer Older
1
#
2
# Copyright (c) 2010-2012 by Nils Görs <weechatter@arcor.de>
3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
17 18
# 1.1: fix:  invalid pointer for function infolist_get()
# 1.0: added: allow internal WeeChat command(s)
19
# v0.9: fixed: mem leak, infolist not removed with infolist_free()
20 21
# v0.8: get_color() is now using API function weechat::info_get("irc_nick_color")
# v0.7: quakenet uses different JOIN format (JOIN #channelname instead of JOIN :#channelname)
22 23 24
# v0.6: newsbar support
#     : internal changes (thanks to rettub)
#     : added option 'block_all_buffers'
25 26 27
# v0.5: unhook notify_me() (by rettub)
#     : option for external command (by rettub)
#     : standard command is now only display beep (by rettub)
28
#     : external command does not freeze weechat anymore
29 30 31 32
#     : using %N and %C for nick and channel-name
#     : added %S for internal server-name
#     : added whitelist and blacklist (suggested and code used from rettub)
#     : added "block_current_buffer" option
33
# v0.4: auto completion
34 35 36
# v0.3: $extern_command better readable and typo "toogle" instead of "toggle" removed
# v0.2: variable bug removed
# v0.1: first step (in perl)
37
#
38
# This script starts an external progam when a user JOIN a chat you are in.
39
# possible arguments you can give to the external program:
40 41 42 43 44 45 46 47 48 49
# %N : for the nick-name
# %C : for the channel-name
# %S : for the internal server-name
#
# /set plugins.var.perl.jnotify.blacklist = "jn-blacklist.txt"
# /set plugins.var.perl.jnotify.whitelist = "jn-whitelist.txt"
# /set plugins.var.perl.jnotify.block_current_buffer = "on"
# /set plugins.var.perl.jnotify.cmd = "echo -en "\a"" 
# /set plugins.var.perl.jnotify.status = "on"
#
50 51 52
# Development is currently hosted at
# https://github.com/weechatter/weechat-scripts

53 54
use strict;
#### Use your own external command here (do not forget the ";" at the end of line):
55
my $extern_command = qq(echo -en "\a");
56

57 58 59 60
# examples:
# playing a sound
# my $extern_command = qq(play -q $HOME/sounds/hello.wav);
# write to an output file.
61
# my $extern_command = qq('echo "\"%C\" \"neuer User: %N\"">>/tmp/jnotify-`date +"%Y%m%d"`.log');
62 63
# this is my favorite. Displays weechat-logo + channel + nick using system-notification.
# my $extern_command = qq(notify-send -t 9000 -i $HOME/.weechat/120px-Weechat_logo.png "\"%C\" \"neuer User: %N\");
64

65 66 67 68
# example to run an internal command:
# /echo -b %C -level 3 %N joined channel


69
# default values in setup file (~/.weechat/plugins.conf)
70
my $version		= "1.1";
71
my $prgname 		= "jnotify";
72
my $description 	= "starts an internal command or external program if a user or one of your buddies JOIN a channel you are in";
73
my $status		= "status";
74
my $default_status	= "on";
75 76 77 78 79
my $block_current_buffer= "off";
my $whitelist		= "whitelist";
my $default_whitelist	= "jn-whitelist.txt";
my $blacklist		= "blacklist";
my $default_blacklist	= "jn-blacklist.txt";
80
my $command_chars       = "/";
81 82 83
my %Hooks               = ();
my %Allowed = ();
my %Disallowed = ();
84 85

# first function called by a WeeChat-script.
86
weechat::register($prgname, "Nils Görs <weechatter\@arcor.de>", $version,
87
                  "GPL3", $description, "", "");
88 89

# commands used by jnotify. Type: /help jnotify
90
weechat::hook_command($prgname, $description,
91

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        "<toggle> | <status> | <block> | <wl> | <wl> | <wl_add> / <wl_del> / <bl_add> / <bl_del> [nick_1 [... nick_n]]", 

        "<toggle>           $prgname between on and off\n".
        "<status>           tells you if $prgname is on or off\n".
        "<block>            toggle the 'block current channel' option on/off\n".
        "<wl>               shows entries in whitelist\n".
        "<bl>               shows entries in blacklist\n".
        "<wl_add> [nick(s)] add nick(s) to the whitelist\n".
        "<wl_del> [nick(s)] delete nick(s) from the whitelist\n".
        "<bl_add> [nick(s)] add nick(s) to the blacklist\n".
        "<bl_del> [nick(s)] delete nick(s) from the blacklist\n".
        "\n".
        "Options:\n".
        "'status'   : status of $prgname (on/off)\n".
        "'whitelist': path/file-name to store a list of nicks, channels and servers you would like to be inform if someone joins.\n".
        "'blacklist': path/file-name to store a list of nicks, channels and servers you would like to ignore.\n".
        "'cmd'      : command that should be executed if a user joins a channel you are in.\n".
        "             '%N' will be replaced with users nick\n".
        "             '%C' will be replaced with name of channel\n".
        "             '%S' will be replaced with the internal server name (use '/server' to see the internal server names)\n".
        "to execute internal weechat command(s) you have to initiate the command line with a weechat command_char (\"/\" or weechat.look.command_chars)\n".
        "'block_current_buffer': if option is 'on', notices will be blocked if user joins the channel you are currently in. Other channels will be displayed.\n".
        "'block_all_buffers'   : if option is 'on', all channels will be blocked and notification will be shown for whitelist entries only.\n".
        "'use_newsbar'         : if option is 'on' and newsbar.pl is running notices will be printed there.\n".
        "\n".
        "Examples:\n".
        "Show entries in whitelist:\n".
        "  /$prgname wl\n".
        "Add entries to blacklist (nick, server, channel):\n".
        "  /$prgname bl_add nickname freenode #weechat\n".
        "Delete entries from whitelist (channel, nick, server):\n".
        "  /$prgname wl_del #weechat nickname freenode\n".
        "Toggle option block_current_buffer (on|off):\n".
        "  /$prgname block\n".
        "Set the variable for the external command (i recommend to use /iset script):\n".
        "  /set plugins.var.perl.$prgname.cmd \"notify-send -t 9000 -i ~/.weechat/some_pic.png \"Channel: %C on Server: %S\" \"new User: %N\"\n".
        "Set the variable for an internal command (script /echo):\n".
        "  /set plugins.var.perl.$prgname.cmd \"/echo -b %C -level 3 %N joined channel\"",
        "toggle|status|block|wl|bl|wl_add|wl_del|bl_add|bl_del", "switch", "");
131

132 133
init();
weechat::hook_config( "plugins.var.perl.$prgname.$status", 'toggled_by_set', "" );
134 135

# create hook_signal for IRC command JOIN 
136 137 138
hook() if (weechat::config_get_plugin($status) eq "on");

# return 0 on error
139
sub hook{
140
	$Hooks{notify_me} = weechat::hook_signal("*,irc_in_join", "notify_me", ""); # (servername, signal, script command, arguments)
141
		if ($Hooks{notify_me} eq '')
142 143 144 145 146 147 148
		{
			weechat::print("","ERROR: can't enable $prgname, hook failed ");
			return 0;
		}

	return 1;
}
149
sub unhook{
150 151 152
	weechat::unhook($Hooks{notify_me}) if %Hooks;
	%Hooks = ();
}
153

154 155
sub _notify {
    my ( $server_name, $newnick, $channelname ) = @_;
156

157
    if ( weechat::config_get_plugin("use_newsbar") eq "on" and newsbar() ) {	# option "use_newsbar" is on and newsbar is running!
158 159
        info2newsbar( 'lightgreen', '[JNOTIFY]', $server_name, $newnick, $channelname );
    } else {
160 161 162 163
        my $external_command = weechat::config_get_plugin('cmd');		# get external command (user settings)
        $external_command =~ s/%C/$channelname/;				# replace string '%C' with $channelname
        $external_command =~ s/%N/$newnick/;					# replace string '%N' with $newnick
        $external_command =~ s/%S/$server_name/;				# replace string '%S' with $server_name
164

165 166 167 168 169 170 171
        my $command_char = substr($external_command,0,1);                       # get first char of external command.

        if ( index($command_chars,$command_char) == -1) {
          system( $external_command . "&" );                                    # start external program
        }else{
          weechat::command("",$external_command);                               # start internalt command
        }
172 173
    }
}
174

175
sub notify_me {
176
    my ( undef, $buffer, $args ) = @_;						# save callback from hook_signal
177

178 179 180 181 182
    my $mynick = weechat::info_get( "irc_nick", split( /,/, $buffer ) );	# get current nick on a server
    my $newnick = weechat::info_get( "irc_nick_from_host", $args );		# get nickname from new user
    my ($channelname) = ( $args =~ m!.*JOIN (.*)! );				# extract channel name from hook_signal
    ($channelname)  = ($channelname =~ m!.*:(.*)!) if ($channelname =~ m!.*:(.*)!); # ":" in channelname?
    my ($server_name) = split( /,/, $buffer );					# extract internal server name from hook_signal
183

184
    return weechat::WEECHAT_RC_OK if ( $mynick eq $newnick );			# did i join the channel?
185

186 187 188 189
    # If user setting "block_current_buffer" is "on"
    if ( weechat::config_get_plugin("block_current_buffer") eq "on" ) {
        return weechat::WEECHAT_RC_OK if ( weechat::buffer_get_string( weechat::current_buffer(), "short_name" ) eq $channelname );
    }
190

191 192 193 194 195 196 197 198 199 200
    if ( exists $Allowed{$newnick} or exists $Allowed{$channelname} or exists $Allowed{$server_name} ) {          # User or Channel or Buffer in Whitelist?
        _notify( $server_name, $newnick, $channelname );
        return weechat::WEECHAT_RC_OK;
    } elsif (
        ( scalar keys %Allowed ) == 0                                                                             # whitelist empty?
        or exists $Disallowed{$newnick} or exists $Disallowed{$channelname} or exists $Disallowed{$server_name}   # User, Channel or Server in Blacklist?
      )
    {
        return weechat::WEECHAT_RC_OK;
    }
201

202 203 204
    if ( weechat::config_get_plugin("block_all_buffers") eq "off" ) {
      _notify( $server_name, $newnick, $channelname );
    }
205

206
    return weechat::WEECHAT_RC_OK;
207 208
}

209
sub toggled_by_set{
210 211
	my $value = $_[2];

212 213
        $command_chars = weechat::config_string( weechat::config_get("weechat.look.command_chars") ) . "/";

214
	if ($value ne 'on')
215 216 217 218 219
	{
		weechat::config_set_plugin($status, "off")	unless ($value eq 'off') ;
		if (defined $Hooks{notify_me}) {
			weechat::print('',"$prgname disabled value: $value");
			unhook();
220
		}
221
	}
222
	else
223 224 225 226
	{
		if (not defined $Hooks{notify_me}) {
			weechat::print("","$prgname enabled");
			weechat::config_set_plugin($status, "off")
227
				unless  hook();									# fall back to 'off' if hook fails
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
						}
						}
						return weechat::WEECHAT_RC_OK;
						}

sub switch{
						my ($getargs) = ($_[2]);
						my $jnotify = weechat::config_get_plugin($status);		# get value from jnotify
						my $block_current_stat = weechat::config_get_plugin("block_current_buffer");

						if ($getargs eq $status or "")
						{
						weechat::print("","Status of $prgname is         : $jnotify");	# print status of jnotify
						weechat::print("","blocking of current buffer is: $block_current_stat");
						return weechat::WEECHAT_RC_OK;
						}

						if ($getargs eq "toggle"){
						if ($jnotify eq "on")
						{
							weechat::config_set_plugin($status, "off");
						}
						else
						{
							weechat::config_set_plugin($status, "on");
						}
						return weechat::WEECHAT_RC_OK;
						}

						if ($getargs eq "block"){
							if ($block_current_stat eq "on")
							{
								weechat::config_set_plugin("block_current_buffer", "off");
							}
							else
							{
								weechat::config_set_plugin("block_current_buffer", "on");
							}
							return weechat::WEECHAT_RC_OK;
						}

						if ($getargs eq "wl")
						{
							list_show( "whitelist", \%Allowed);
							return weechat::WEECHAT_RC_OK;
						}
						if ($getargs eq "bl")
						{
							list_show( "blacklist", \%Disallowed);
							return weechat::WEECHAT_RC_OK;
						}
						else
						{
							my ( $cmd, $arg ) = ( $getargs =~ /(.*?)\s+(.*)/ );			# cut cmd from nicks
								$cmd = $getargs unless $cmd;
# check cmd "whitelist add/del" and "blacklist add/del"
							if ($cmd eq "wl_add")
							{
								_add("wl_add",$arg);
							}
							if ($cmd eq "wl_del")
							{
								_del("wl_del",$arg);
							}
							if ($cmd eq "bl_add")
							{
								_add("bl_add",$arg);
							}
							if ($cmd eq "bl_del")
							{
								_del("bl_del",$arg);
							}
						}
301 302
}

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
# whitelist and blacklist reader and saver (routines from rettubs query_blocker)
sub whitelist_save{
	list_save( "whitelist", \%Allowed, "write whitelist" );
}
sub blacklist_save{
	list_save( "blacklist", \%Disallowed, "write blacklist" );
}
sub list_save {
	my ( $list, $hash_ref, $err_msg ) = @_;
	my $file = weechat::config_get_plugin($list);
	open( LIST, ">", $file ) || DEBUG("$err_msg: $!");
	print LIST "$_\n" foreach ( sort { "\L$a" cmp "\L$b" } keys %$hash_ref );
	close LIST;
}
sub list_read{
	my $list     = shift;
	my $hash_ref = shift;
	my $file    = weechat::config_get_plugin($list);
321

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
	return unless -e $file;

	open( LIST, "<", $file ) || DEBUG("$file: $!");
	while (<LIST>) {
		chomp;
		$hash_ref->{$_} = 1 if length $_;
	}
	close LIST;
}
sub list_show{
	my ( $list, $hash_ref ) = @_;

	weechat::print( "", "$prgname: $list" );
	if ( ( my $n = keys %$hash_ref ) eq "0" ) {
		weechat::print( "", "     list is empty" );
		return;
	}
339

340 341 342 343 344 345 346 347 348 349 350
	foreach ( sort { "\L$a" cmp "\L$b" } keys %$hash_ref ) {
		weechat::print( "", "     " . $_ );
	}
}
# add and delete nicks from white and blacklist
sub _add{
	my ($cmd,$args) = ($_[0],$_[1]);

	if (defined $args) {
		foreach ( split( / +/, $args ) ) {
			if ($cmd eq "wl_add")
351
			{
352 353
				$Allowed{$_} = 1;
				whitelist_save();
354
			}
355
			elsif ($cmd eq "bl_add")
356
			{
357 358
				$Disallowed{$_} = 1;
				blacklist_save();
359
			}
360
		}
361 362 363 364 365 366 367 368 369 370
	}
	else{
		weechat::print("", "$prgname : There is no nick to be added.");
	}
}
sub _del{
	my ($cmd,$args) = ($_[0],$_[1]);
	if (defined $args) {
		foreach ( split( / +/, $args ) ) {
			if ($cmd eq "wl_del" and exists $Allowed{$_})
371
			{
372 373 374 375 376 377
				$Allowed{$_} = 1;
				delete $Allowed{$_};
				weechat::print("", "$prgname: Nick ". get_color($_) . $_ . weechat::color("reset") . " removed from whitelist.");
				whitelist_save();
			}elsif ($cmd eq "wl_del") {
				weechat::print("", "$prgname: Nick " . get_color($_) .  $_ . weechat::color("reset") . " not in whitelist. Nothing removed.");
378
			}
379 380

			if ($cmd eq "bl_del" and exists $Disallowed{$_})
381
			{
382 383 384 385 386 387
				$Disallowed{$_} = 1;
				delete $Disallowed{$_};
				weechat::print("", "$prgname: Nick ". get_color($_) . $_ . weechat::color("reset") . " removed from blacklist.");
				blacklist_save();
			}elsif ($cmd eq "bl_del") {
				weechat::print("", "$prgname: Nick " . get_color($_) .  $_ . weechat::color("reset") . " not in blacklist. Nothing removed.");
388
			}
389 390
		}
	}
391 392
	else{
		weechat::print("", "$prgname : There is no nick to be removed.");
393 394
	}
}
395
sub get_color{
396 397
    my $nick_name = $_[0];
    return weechat::info_get("irc_nick_color", $nick_name);
398
}
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
# newsbar support starts here (code by rettub)
sub info2newsbar{
	my ( $color, $category, $server, $nick, $channelname ) = @_;
	weechat::command( '',
			"/newsbar  add --color $color $category\t"
			. get_color($nick)
			. $nick
			. weechat::color('reset') . '@'
			. get_color($server)
			. $server
			. weechat::color('reset')
			. weechat::color('bold')
			. " joined Channel: "
			. weechat::color('reset')
			. get_color($channelname)
			. $channelname );
415
}
416
sub newsbar{
417
        my $info_list = weechat::infolist_get( "perl_script", "", "newsbar" );
418 419 420 421
        weechat::infolist_next($info_list);
        my $newsbar = weechat::infolist_string( $info_list, "name" ) eq 'newsbar';
        weechat::infolist_free($info_list);
        return $newsbar if (defined $newsbar);
422 423
}
# newsbar support ends here
424 425
sub init{
# set value of script (for example starting script the first time)
426 427
	weechat::config_set_plugin("cmd", $extern_command)
		if (weechat::config_get_plugin("cmd") eq "");
428

429 430
	weechat::config_set_plugin($status, $default_status)
		if (weechat::config_get_plugin($status) eq "");
431

432 433 434 435 436 437 438 439 440 441
	if ( weechat::config_get_plugin($whitelist) eq '' ) {
		my $wd = weechat::info_get( "weechat_dir", "" );
		$wd =~ s/\/$//;
		weechat::config_set_plugin($whitelist, $wd . "/" . $default_whitelist );
	}
	if ( weechat::config_get_plugin($blacklist) eq '' ) {
		my $wd = weechat::info_get( "weechat_dir", "" );
		$wd =~ s/\/$//;
		weechat::config_set_plugin($blacklist, $wd . "/" . $default_blacklist );
	}
442

443 444 445 446 447 448
	weechat::config_set_plugin("block_current_buffer", $block_current_buffer)
		if (weechat::config_get_plugin("block_current_buffer") eq "");
	weechat::config_set_plugin("use_newsbar", "off")
		if (weechat::config_get_plugin("use_newsbar") eq "");
	weechat::config_set_plugin("block_all_buffers", "off")
		if (weechat::config_get_plugin("block_all_buffers") eq "");
449

450

451 452
	list_read('whitelist', \%Allowed);
	list_read('blacklist', \%Disallowed);
453 454

        $command_chars = weechat::config_string( weechat::config_get("weechat.look.command_chars") ) . "/";
455
}
456
sub DEBUG {weechat::print('', "***\t" . $_[0]);}