forked from tipichris/callPopPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
callpoppy
executable file
·374 lines (311 loc) · 12.8 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
#!/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 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', '1', '2')
__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
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
hasGnome = True
try:
import gnome.ui
except:
hasGnome = False
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, id=None):
self.id = id
self.username = username
self.secret = secret
self.server = server
self.port = port
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)
ReconnectingClientFactory.clientConnectionFailed(self, self, reason)
def clientConnectionLost(self, connector, reason):
log.warning( 'Lost connection. Reason: %s', reason)
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
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")
# 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
self.approot = sys.path[0]
elif frozen in ('dll', 'console_exe', 'windows_exe'):
# py2exe:
self.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
self.approot = os.environ['RESOURCEPATH']
else:
self.approot = sys.path[0]
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")
imagepath=os.path.join(self.approot, 'call-start.png')
if self.usePyNotify:
log.debug("Notifying with pynotifier (image at %s)", imagepath)
if self.caps and 'body-markup' in self.caps:
title = self.escape(title)
message = self.escape(message)
n=self.notifier.Notification(title,message,imagepath)
n.set_timeout(self.timeout * 1000)
n.show()
else:
log.debug("Notifying with gtkPopupNotify (image at %s)", imagepath)
self.notifier.new_popup(self.escape(title), self.escape(message), 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):
# set up connection to sqllite
sqlconnection = sqlite.connect(self.dbpath)
self.cursor = sqlconnection.cursor()
self.extensions = extensions
self.popup = popup
for k in self.extensions.keys():
log.debug("Extension configured: '%s': %s", k, self.extensions[k])
def onDial(self, protocol, event):
log.debug("Got event %s", event)
if 'destination' in event:
destination=event['destination'].lower()
for s in self.extensions.keys():
log.debug("Checking destination %s against extension %s", destination, s.lower())
if destination.startswith(s.lower()):
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]
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:
self.cursor.execute('SELECT name FROM numbers WHERE tel LIKE ?', (idx,))
row = self.cursor.fetchone()
except Exception as e:
log.debug("Error searching for number: %s", e)
return out
if row:
out = row[0]
return out
def onLogin(self, protocol):
log.debug('Resetting reconnection delay')
protocol.factory.resetDelay()
df = 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")
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
popup = Popup(conf['usePyNotify'], conf['popupparams'])
# initialis our handler, passing the notifier to it
handler = CallPopHandler(conf['extensions'], popup)
# some handler configuration
handler.dbpath = conf['dbfile']
handler.lookupdigits = conf['lookupdigits']
# initialise our factory
factory = CallPopFactory(conf['username'], conf['secret'], conf['server'], conf['port'])
factory.connect_callback=handler.onLogin
factory.maxDelay = 600
factory.connect()
def killapp(*args):
reactor.stop()
return True
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] = config.get('Extensions', s)
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)
# 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.callWhenRunning(main)
reactor.run()