-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcallpoppy
executable file
·481 lines (399 loc) · 17.1 KB
/
callpoppy
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python
# -*-coding: utf-8 -*-
"""
Monitor an Asterisk Manager Interface and provide popup notification of
incoming calls.
callPopPy will attempt to look up the incoming number in a SQLite database
and notify the name associated with the caller. Maintaining the SQLite
database is a job for something else - a Thunderbird extension, Squalit,
exists to do this from a Thunderbird address book.
Copyright 2011 - 2019 Chris Hastie
Contains code originally released as pyCalledMe by Olivier H. Beauchesne
and Copyright 2009 Olivier H. Beauchesne
http://olihb.com/2010/08/08/incoming-call-popup-under-ubuntu-and-asterisk/
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/>.
"""
__version_info__ = ('0', '2', '1')
__version__ = '.'.join(__version_info__)
from twisted.internet import gtk2reactor
gtk2reactor.install(True)
from twisted.internet import reactor, defer
from twisted.internet.protocol import ReconnectingClientFactory
from starpy.manager import AMIProtocol
from twisted.internet import task
import logging
import logging.handlers
import sys
import os
import os.path
import re
try:
from sqlite3 import dbapi2 as sqlite # python 2.5
except:
try:
from pysqlite2 import dbapi2 as sqlite
except:
print 'This program requires pysqlite2\n',\
'http://initd.org/tracker/pysqlite/'
sys.exit(1)
import ConfigParser
import gtk
hasGnome = True
try:
import gnome.ui
except:
hasGnome = False
class cpStatusIcon():
def __init__(self, iconpath):
self.iconpath = iconpath
self.tray = gtk.StatusIcon()
self.tray.set_from_file(os.path.join(self.iconpath, 'call-start-grey.png'))
self.tray.set_visible(True)
self.tray.connect('popup-menu', self.on_right_click)
self.tray.set_tooltip(appname + "\nWaiting to connect...")
def on_right_click(self, icon, event_button, event_time):
self.make_menu(event_button, event_time)
def make_menu(self, event_button, event_time):
menu = gtk.Menu()
# show about dialog
about = gtk.MenuItem("About")
about.show()
menu.append(about)
about.connect('activate', self.show_about_dialog)
# add quit item
quit = gtk.MenuItem("Quit")
quit.show()
menu.append(quit)
quit.connect('activate', killapp)
menu.popup(None, None, gtk.status_icon_position_menu,
event_button, event_time, self.tray)
# This seems needed to run in a thread
def __call__(self):
return True
def show_about_dialog(self, widget):
self.about_dialog = gtk.AboutDialog()
self.about_dialog.set_destroy_with_parent (True)
self.about_dialog.set_icon_name (appname)
self.about_dialog.set_name(appname)
self.about_dialog.set_version(__version__)
self.about_dialog.set_copyright("(C) 2011 - 2019 Chris Hastie")
license = """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/"""
self.about_dialog.set_license(license)
self.about_dialog.set_website('http://www.oak-wood.co.uk/oss/callpoppy')
self.about_dialog.set_comments(("Pop up who's calling an Asterisk PBX"))
self.about_dialog.set_authors(['Chris Hastie <[email protected]>'])
self.about_dialog.run()
self.about_dialog.destroy()
def remove(self):
self.tray.set_visible(False)
def changeToolTip(self, tooltip):
log.debug("Updating tooltip to: '" + tooltip + "'")
self.tray.set_tooltip(tooltip)
def changeIcon(self, icon):
log.debug("Changing icon to: '" + icon + "'")
self.tray.set_from_file(os.path.join(self.iconpath, icon))
class CallPopFactory(ReconnectingClientFactory):
""" Factory for connection. Subclassed from ReconnectingClientFactory
to take advantage of backing off reconnection times
"""
protocol = AMIProtocol
connect_callback=None
def __init__(self, username, secret, server='localhost', port=5038, statusicon=None):
self.username = username
self.secret = secret
self.server = server
self.port = port
self.statusicon = statusicon
def login( self, ip='localhost', port=5038, timeout=5 ):
self.loginDefer = defer.Deferred()
reactor.connectTCP(ip,port,self, timeout=timeout)
return self.loginDefer
def clientConnectionFailed(self, connector, reason):
log.warning( 'Connection failed. Reason: %s', reason)
self.statusicon.changeToolTip(appname + ": Connection failed")
self.statusicon.changeIcon('call-start-grey.png')
ReconnectingClientFactory.clientConnectionFailed(self, self, reason)
def clientConnectionLost(self, connector, reason):
log.warning( 'Lost connection. Reason: %s', reason)
self.statusicon.changeToolTip(appname + ": Connection lost")
self.statusicon.changeIcon('call-start-grey.png')
ReconnectingClientFactory.clientConnectionLost(self, self, reason)
def connect(self):
log.info("Connecting to Asterisk at %s:%d", self.server, self.port)
df = self.login(self.server, self.port)
if self.connect_callback!=None:
df.addCallback(self.connect_callback)
class Popup:
""" Abstraction layer to handle popup notifications. Provides a consistent
API whether using pynotify or gtkPopupNotify
"""
def __init__(self, usePyNotify, params):
self.timeout = params['timeout']
self.usePyNotify = usePyNotify
self.imagepath = params['imagepath']
if self.usePyNotify:
try:
log.debug("Attempting to use pynotify")
import pynotify
self.notifier = pynotify
self.notifier.init(params['appname'])
self.caps = self.notifier.get_server_caps()
except:
log.warning("Unable to import pynotify. Using gtkPopupNotify instead")
self.usePyNotify = False
if not self.usePyNotify:
log.debug("Importing gtkPopupNotify")
import gtkPopupNotify, gtk
for k in params.keys():
log.debug("Popup param '%s': %s", k, params[k])
self.notifier=gtkPopupNotify.NotificationStack(timeout=self.timeout)
self.notifier.show_timeout = False
self.notifier.edge_offset_x = params['xoff']
self.notifier.edge_offset_y = params['yoff']
self.notifier.corner = params['left'],params['top']
self.notifier.max_popups = 1
self.notifier.bg_color = gtk.gdk.Color(params['bg'])
self.notifier.fg_color = gtk.gdk.Color(params['fg'])
self.notifier.fontdesc = ("Sans Bold 10", "Sans 10", "Sans 10")
def escape(self, text):
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
return text
def show(self, title, message):
log.debug("Popup.show called")
if self.usePyNotify:
log.debug("Notifying with pynotifier (image at %s)", self.imagepath)
if self.caps and 'body-markup' in self.caps:
title = self.escape(title)
message = self.escape(message)
n=self.notifier.Notification(title,message,self.imagepath)
n.set_timeout(self.timeout * 1000)
n.show()
else:
log.debug("Notifying with gtkPopupNotify (image at %s)", self.imagepath)
self.notifier.new_popup(self.escape(title), self.escape(message), self.imagepath)
return True
class CallPopHandler:
""" Main application handler """
pingtimeout = 5
pinginterval = 120
dbpath = os.path.expanduser('~/.callpoppy/callpoppy.db')
lookupdigits = 10
def __init__(self, extensions, popup, statusicon):
# set up connection to sqllite
self.sqlconnection = sqlite.connect(self.dbpath)
self.extensions = extensions
self.popup = popup
self.statusicon = statusicon
for k in self.extensions.keys():
log.debug("Extension configured: '%s': %s", k, self.extensions[k]['name'])
def onDial(self, protocol, event):
log.debug("Got event %s", event)
# check for both 'destchannel' and 'destination'. Depends on Asterisk version
destination = None
if 'destchannel' in event:
destination=event['destchannel'].lower()
elif 'destination' in event:
destination=event['destination'].lower()
if destination is not None:
for s in self.extensions.keys():
log.debug("Checking destination %s against extension %s", destination, s.lower())
if self.extensions[s]['re'].match(destination):
log.debug("Processing call for %s", s)
if 'calleridnum' in event:
cid=event['calleridnum']
else :
# earlier versions of Asterisk used callerid rather than calleridnum
cid = event['callerid']
cidname=self.lookupnumber(cid,event['calleridname'])
extname=self.extensions[s]['name']
log.info("Call from %s (%s) for %s", cidname, cid, extname)
self.popup.show("Incoming call for "+extname, cidname + "\n"+cid)
def lookupnumber(self, cidnum, out):
idx = cidnum[-self.lookupdigits:]
if len(cidnum) > self.lookupdigits:
idx = '%' + idx
log.debug("Looking up number LIKE '%s'", idx)
try:
row = self.sqlconnection.execute('SELECT name FROM numbers WHERE tel LIKE ?', (idx,)).fetchone()
except Exception as e:
log.warning("Error searching for number: %s", e)
return out
if row:
out = row[0]
return out
def onLogin(self, protocol):
log.debug('Resetting reconnection delay')
self.statusicon.changeToolTip(appname + "\nMonitoring extensions:\n" + ', '.join(self.extensions.keys()))
self.statusicon.changeIcon('call-start.png')
protocol.factory.resetDelay()
# change of event name from 'Dial' to 'DialBegin'
df = protocol.registerEvent("DialBegin",self.onDial)
dfold = protocol.registerEvent("Dial",self.onDial)
self.timeouttask = task.LoopingCall(self.pinglink, protocol)
self.timeouttask.start(self.pinginterval);
#return df
def pinglink(self, protocol):
def ontimeout():
log.debug("Unexpected response or timeout waiting. Closing connection")
self.statusicon.changeToolTip(appname + ": Connection lost")
self.statusicon.changeIcon('call-start-grey.png')
if dc.active():
dc.cancel()
self.timeouttask.stop()
protocol.transport.loseConnection()
def canceltimeout(*val):
if dc.active():
dc.cancel()
log.debug("Received pong. Cancelling timeout")
log.debug("%s", val)
def success(val):
pass
log.debug("Pinging server - setting timeout")
dc = reactor.callLater(self.pingtimeout,ontimeout)
df = protocol.ping()
df.addBoth(canceltimeout)
df.addCallback(success)
df.addErrback(ontimeout)
def main():
# initialise our notifier
popupparams = conf['popupparams']
popupparams['imagepath'] = cpicon
popup = Popup(conf['usePyNotify'], conf['popupparams'])
# initialis our handler, passing the notifier to it
handler = CallPopHandler(conf['extensions'], popup, cpsi)
# some handler configuration
handler.dbpath = conf['dbfile']
handler.lookupdigits = conf['lookupdigits']
# initialise our factory
factory = CallPopFactory(conf['username'], conf['secret'], conf['server'], conf['port'], cpsi)
factory.connect_callback=handler.onLogin
factory.maxDelay = 600
factory.connect()
def killapp(*args):
reactor.stop()
return True
def cleanup():
log.info("Cleaning up...")
if cpsi:
cpsi.remove()
if hasattr(cpsi, 'about_dialog'):
cpsi.about_dialog.destroy()
if __name__ == '__main__':
appname = 'CallPoppy'
# Keep our logs secret
os.umask(0077);
config = ConfigParser.ConfigParser({
'port': '5038',
'uselibnotify': 'True',
'background': '#171717',
'foreground': '#bbbbbb',
'top': "0",
'left': "0",
'x-offset': "0",
'y-offset': "0",
'timeout': "6",
'loglevel': "4",
'logfile': os.path.expanduser('~/.callpoppy/callpoppy.log'),
'dbfile': os.path.expanduser('~/.callpoppy/callpoppy.db'),
'digits': "10"
})
config.optionxform = str
conffile = os.path.expanduser('~/.callpoppy/config')
conf = {}
try:
config.read(conffile)
conf['server'] = config.get('Asterisk', 'server')
conf['port'] = config.getint('Asterisk', 'port')
conf['username'] = config.get('Asterisk', 'username')
conf['secret'] = config.get('Asterisk', 'secret')
conf['loglevel'] = config.getint('Logging', 'loglevel')
conf['logfile'] = config.get('Logging', 'logfile')
conf['dbfile'] = config.get('Database', 'dbfile')
conf['lookupdigits'] = config.getint('Database', 'digits')
conf['popupparams'] = {}
conf['popupparams']['bg'] = config.get('Popup', 'background')
conf['popupparams']['fg'] = config.get('Popup', 'foreground')
conf['popupparams']['top'] = config.getboolean('Popup', 'top')
conf['popupparams']['left'] = config.getboolean('Popup', 'left')
conf['popupparams']['xoff'] = config.getint('Popup', 'x-offset')
conf['popupparams']['yoff'] = config.getint('Popup', 'y-offset')
conf['popupparams']['timeout'] = config.getint('Popup', 'timeout')
conf['popupparams']['appname'] = appname
conf['usePyNotify'] = config.getboolean('Popup', 'uselibnotify')
ext = config.options('Extensions')
conf['extensions'] = {}
for s in ext:
# annoyingly, ConfigParser.options returns all the defaults, so
# we need to filter them out
if s not in config.defaults().keys():
conf['extensions'][s] = {}
conf['extensions'][s]['name'] = config.get('Extensions', s)
conf['extensions'][s]['re'] = re.compile('^' + s + r"(-\w+)?$", re.IGNORECASE)
except ConfigParser.Error as conferr:
sys.exit(appname + " could not read the configuration file '" + conffile +"':\n" + conferr.__str__())
# Set up logging
log = logging.getLogger(appname)
loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
loglevel = loglevels[conf['loglevel'] - 1]
log.setLevel(loglevel)
# create log handler and set level. This creates a rotating log file
lh = logging.handlers.RotatingFileHandler(conf['logfile'], 'a', 102400, 3)
lh.setLevel(loglevel)
logformat = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s')
lh.setFormatter(logformat)
log.addHandler(lh)
# set up logging from starpy
logging.getLogger('AMI').setLevel(loglevel)
logging.getLogger('AMI').addHandler(lh)
log.info("Starting %s version %s", appname, __version__)
log.debug("Configuration read from %s", conffile)
log.debug("Configuration: %s", conf)
# getting the current path depends on whether we're a compiled
# binary, or a script being run through the interpreter
# http://stackoverflow.com/questions/1511461/py2exe-and-the-file-system
frozen = getattr(sys, 'frozen', '')
if not frozen:
# not frozen: in regular python interpreter
approot = sys.path[0]
elif frozen in ('dll', 'console_exe', 'windows_exe'):
# py2exe:
approot = os.path.dirname(sys.executable)
elif frozen in ('macosx_app',):
# py2app:
# Notes on how to find stuff on MAC, by an expert (Bob Ippolito):
# http://mail.python.org/pipermail/pythonmac-sig/2004-November/012121.html
approot = os.environ['RESOURCEPATH']
else:
approot = sys.path[0]
cpicon=os.path.join(approot, 'call-start.png')
# On Gnome, ensure the script exits when the user
# logs out.
if hasGnome:
gnome.program_init (appname, "1.0")
client = gnome.ui.master_client()
client.connect("save-yourself", killapp)
#reactor.callInThread(cpStatusIcon(cpicon))
cpsi = cpStatusIcon(approot)
reactor.callWhenRunning(main)
reactor.addSystemEventTrigger('before', 'shutdown', cleanup)
reactor.run()