Script: zmq_notify.rb

Send notifications to a ZMQ socket.
Author: Mahlon — Version: 0.1 — License: BSD-3-Clause
For WeeChat ≥ 0.3.0, requires: zmq.
Tags: notify
Added: 2011-11-15

Download GitHub Repository

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# vim: set noet nosta sw=4 ts=4 :
#
# Mahlon E. Smith <mahlon@martini.nu>
# http://www.martini.nu/
# (See below for LICENSE.)
#
# ZMQ Notify
# ----------
#
# Catch private messages and highlights, relaying them onward to a
# ZeroMQ publisher, for subscriber consumption.
#
# Writing a client to pull messages off the queue and send them to
# growl/libnotify/dzen/sms/email/your-tv/whatever-your-heart-desires
# is left as an exercise to the reader, but it should be as trivial as
# receiving the message and unwrapping YAML.  Fun!
#
#    ctx = ZMQ::Context.new
#    zmq = ctx.socket( ZMQ::SUB )
#    zmq.connect( "tcp://example.com:2428" )
#    zmq.setsockopt( ZMQ::SUBSCRIBE, '' )
#    
#    loop do
#        pp YAML.load( zmq.recv )
#    end
#
#
#
# Install instructions:
# ---------------------
#
#   This script requires the "zmq" ruby module, available
#   from rubygems, and of course, your Weechat to be built with
#   ruby.
#
#   Load into Weechat like any other plugin, after putting it into
#   your ~/.weechat/ruby directory:
#
#        /ruby load zmq_notify.rb
#
# Options:
# --------
#
#   plugins.var.ruby.zmq_notify.endpoint
#
#       The ZMQ connection endpoint.  The socket type is always PUB.
#       Default: tcp://*:2428
#
#   plugins.var.ruby.zmq_notify.ignore_tags
#
#       A comma separated list of message types to ignore
#       completely, regardless of away state.
#       Default: "irc_quit"
#
#   plugins.var.ruby.zmq_notify.enabled
#
#       A global on/off toggle.
#       Default: "off"
#
#   plugins.var.ruby.zmq_notify.only_when_away
#
#       Only relay messages to the ZMQ socket if you are set to /away.
#       Default: "on"
#
#
# ZMQ message payload
# -------------------
#
# Highlighted message:
#
#    {:type=>"channel",
#     :highlight=>true,
#     :message=>"Something said in #ruby-lang on my highlight list!",
#     :away=>false,
#     :channel=>"#ruby-lang",
#     :server=>"freenode",
#     :date=>"1294733587",
#     :tags=>["irc_privmsg", "notify_message", "log1"]}
#
# Private message:
#
#    {:type=>"private",
#     :highlight=>false,
#     :message=>"Here we go, yo.  So what's the scenario?",
#     :away=>false,
#     :channel=>"grangeromatic",
#     :server=>"bitlbee",
#     :date=>"1294733597",
#     :tags=>["irc_privmsg", "notify_private", "log1"]}
#


### Convenience 'truth' module for Weechat config strings, because:
###
###     self.enabled.true?
###
### reads a whole lot nicer than:
###
###     Weechat.config_string_to_boolean(Weechat.config_get_plugin('enabled')) == "1"
###
### I resist the temptation to monkeypatch all of String during my
### time with Weechat.  Heh.
###
module Truthy
	def true?
		return Weechat.config_string_to_boolean( self.to_s ).to_i.zero? ? false : true
	end
end


### The actual Weechat plugin.
###
class ZMQNotify
	include Weechat

	DEBUG = false

	SIGNATURE = [
		'zmq_notify',
		'Mahlon E. Smith',
		'0.1',
		'BSD',
		'Send private messages and highlights to a ZMQ socket.',
		'weechat_unload',
		'UTF-8'
	]

	DEFAULT_OPTIONS = {
		:endpoint       => 'tcp://*:2428',
		:ignore_tags    => 'irc_quit',
		:enabled        => 'off',
		:only_when_away => 'on'
	}


	### Prepare configuration and bind a ZMQ endpoint.
	###
	def initialize

		@zmq = @ctx = nil

		DEFAULT_OPTIONS.each_pair do |option, value|

			# install default options if needed.
			#
			if Weechat.config_is_set_plugin( option.to_s ).zero?
				self.print_info "Setting value '%s' to %p" % [ option, value ] if DEBUG
				Weechat.config_set_plugin( option.to_s, value.to_s )
			end

			# read in existing config values, attaching
			# them to instance variables.
			#
			val = Weechat.config_get_plugin( option.to_s )
			val.extend( Truthy )
			instance_variable_set( "@#{option}".to_sym, val )
			self.class.send( :attr, option.to_sym, true )
		end

		self.bind
		self.print_info "Initalized!"
	end

	# The ZMQ socket and context.
	#
	attr :zmq, true
	attr :ctx, true


	########################################################################
	### W E E C H A T   H O O K S
	########################################################################

	### Validate values for config changes, and take appropriate action
	### on any changes that immediately require it.
	###
	def config_changed( data, option, new_value )
		option = option.match( /\.(\w+)$/ )[1]
		bounce_connection = false
		new_value.extend( Truthy )

		case option

			# reset the connection if needed
			#
			when 'endpoint'
				instance_variable_set( "@#{option}".to_sym, new_value )
				bounce_connection = true

			# Disconnect/reconnect to endpoint
			#
			when 'enabled'
				self.enabled = new_value
				new_value.true? ? self.bind : self.unbind

			# ... just change the setting, no validation/action needed.
			else
				instance_variable_set( "@#{option}".to_sym, new_value )
		end

		# Refresh the endpoint connection.
		#
		if bounce_connection
			self.unbind
			self.bind
		end

		return WEECHAT_RC_OK
	end


	### Process all incoming messages, filtering out anything we're not
	### interested in seeing.
	###
	def notify_msg( data, buffer, date, tags, visible, highlight, prefix, message )

		return WEECHAT_RC_OK unless self.enabled.true?

		# Grab the channel metadata.
		data = {}
		%w[ away type channel server ].each do |meta|
			data[ meta.to_sym ] = Weechat.buffer_get_string( buffer, "localvar_#{meta}" );
		end
		data[ :away ] = data[ :away ].empty? ? false : true

		# Are we currently marked as away?
		return WEECHAT_RC_OK if self.only_when_away.true? && ! data[ :away ]

		# Only bother with the message if it is a highlight, or a private message.
		return WEECHAT_RC_OK if highlight.to_i.zero? && data[ :type ] != 'private'

		# Are we specifically ignoring this message tag type?
		#
		ignored = self.ignore_tags.split( ',' )
		tags    = tags.split( ',' )
		return WEECHAT_RC_OK unless ( ignored & tags ).empty? 

		notify = {
			:highlight => ! highlight.to_i.zero?,
			:type      => data[ :type ],
			:channel   => data[ :channel ],
			:away      => data[ :away ],
			:server    => data[ :server ],
			:date      => date,
			:tags      => tags,
			:message   => message
		}

		# Ship it off.
		#
		self.print_info "Message notification: %p" % [ notify ] if DEBUG
		self.zmq.send( notify.to_yaml )

		return WEECHAT_RC_OK

	rescue => err
		self.disable "%s, %s" % [ err.class.name, err.message ]
		return WEECHAT_RC_OK
	end


	########################################################################
	### I N S T A N C E   M E T H O D S
	########################################################################

	### Instantiate a ZMQ endpoint.
	###
	def bind
		return unless self.enabled.true?

		self.print_info "Setting up endpoint at %s" % [ self.endpoint ]

		self.ctx = ZMQ::Context.new if self.ctx.nil?
		self.zmq = self.ctx.socket( ZMQ::PUB )
		self.zmq.bind( self.endpoint )

	rescue => err
		self.print_info "Unable to create endpoint: %s, %s" % [ err.class.name, err.message ]
		self.zmq = nil
	end


	### Tear down the ZMQ endpoint.
	###
	def unbind
		return if self.zmq.nil?
		self.zmq.close
	end


	### Disable the plugin on repeated error.
	### TODO:  Set a timer to attempt a re-connect?
	###
	def disable( reason )
		self.print_info "Disabling plugin due to error: %s" % [ reason ]
		Weechat.config_set_plugin( 'enabled', 'off' )
	end



	#########
	protected
	#########

	### Quick wrapper for sending info messages to the weechat main buffer.
	###
	def print_info( msg )
		Weechat.print '', "%sZMQ\t%s" % [
			Weechat.color('yellow'),
			msg
		]
	end
end



### Weechat entry point.
###
def weechat_init
	require 'rubygems'
	require 'zmq'
	require 'yaml'

	Weechat::register *ZMQNotify::SIGNATURE
	$zmq = ZMQNotify.new
	Weechat.hook_print( '', '', '', 1, 'notify_msg', '' )
	Weechat.hook_config( 'plugins.var.ruby.zmq_notify.*', 'config_changed', '' )

	return Weechat::WEECHAT_RC_OK

rescue LoadError => err
	Weechat.print '', "zmq_notify: %s, %s\n$LOAD_PATH: %p" % [
		err.class.name,
		err.message,
		$LOAD_PATH
	]
	Weechat.print '', 'zmq_notify: Unable to initialize due to missing dependencies.'
	return Weechat::WEECHAT_RC_ERROR
end


### Hook for manually unloading this script.
###
def weechat_unload
	$zmq.unbind
	return Weechat::WEECHAT_RC_OK
end


### Allow Weechat namespace callbacks to forward to the ZMQNotify object.
###
require 'forwardable'
extend Forwardable
def_delegators :$zmq, :notify_msg, :config_changed


__END__
__LICENSE__

Copyright (c) 2011, Mahlon E. Smith <mahlon@martini.nu>

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, this
      list of conditions and the following disclaimer in the documentation and/or
      other materials provided with the distribution.

    * Neither the name of the author, nor the names of contributors may be used to
      endorse or promote products derived from this software without specific prior
      written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.