#!/usr/bin/env python
""" Simple python server to allow Remote phonebook of ST2030 to work with
Asterisk server, using the phone and fullname settings of the config file
as input values, like
[20012]
fullname=Rick van der Zwet
In order to get it working alter HOST and PORT to the location of your webserver
Next specify remote phone book URL to be http://HOST:PORT/search?q=#SEARCH
at Advanced -> Phone Lists -> Remote Phone Book in the webinterface
OR
In your autoprovising files the entries under the section [sys]
Phonebook1_url=http://HOST:PORT/search?q=#SEARCH
Phonebook1_name=example.com phone book
Original webserver template - Copyright Jon Berg , turtlemeat.com
"""
from __future__ import with_statement
import string,cgi,time,os
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse, urllib
import ConfigParser
__author__ = "Rick van der Zwet"
__copyright = "Copyright 2008, Rick van der Zwet"
__licence__ = "BSD"
__version__ = "0.0.2"
__maitainer__ = "Rick van der Zwet"
__email__ = "rick@wzoeterwoude.net"
__status__ = "Production"
__credits__ = [" Jon Berg , turtlemeat.com"]
__website__ = "http://rickvanderzwet.nl/svn/data/develop/pythonplaza/asterisk-remote-phonebook.py"
#
# Specify your asterisk config file and the IP/host you like the mini-server to
# be running on
USERFILE='/etc/asterisk/users.conf'
LOGFILE='/var/log/phonebook.log'
HOST='192.168.50.10'
PORT=8000
class MyHandler(BaseHTTPRequestHandler):
__base = BaseHTTPRequestHandler
protocol_version = "HTTP/1.0"
def log_message(self, format, *args):
"""Log an arbitrary message., custom function, log to file, instead of stdout
"""
with open(LOGFILE,"a") as f:
f.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format%args))
def do_GET(self):
parsed_path = urlparse.urlparse(self.path)
rpath = parsed_path.path
qdict = cgi.parse_qs(parsed_path.query,True)
if rpath == '/search':
if qdict.has_key('q'):
searchkey = qdict['q'][0].lower()
else:
qdict['q'] = ' '
searchkey = ' '
#Parse astrisk file, fetch phone number and Name
config = ConfigParser.ConfigParser()
try:
config.readfp(open(USERFILE))
except IOError:
self.send_error(404,'Config file not found/readable: %s' % USERFILE)
return
#Do matching
results = []
for section in config.sections():
try:
if config.get(section, 'fullname').lower().find(searchkey) != -1:
results.append(([config.get(section, 'fullname')][0], section));
except ConfigParser.NoOptionError:
pass
results.sort()
#Get right output part
if qdict.has_key('from'):
f = int(qdict['from'][0])
t = f + 31
if t > len(results):
t = len(results)
results = results[f:t]
output = ''
if (len(results) < 32):
output += '\n'
#result smaller 32 hits
for name, phone in results:
output += '\n'
output += '\t%s\n' % name
output += '\t%s\n' % phone
output += '\n'
output += '\n'
else:
output += '\n'
p = 0
while (p < len(results)):
# Damm phone, no & but & only
url = 'http://%s:%s/search?q=%s&from=%s' % (HOST, PORT, urllib.quote_plus(qdict['q'][0]), p)
#url = 'http://%s:%s/search' % (HOST, PORT)
name_start = results[p][0]
if (p + 31 < len(results)):
name_end = results[p+31][0]
else:
name_end = results[len(results) - 1][0]
output += '\n'
p = p + 32
output += '\n'
# Output file
# Broken Phone ST2030, requires \r on all headers
# Broken Phone ST2030 does not properly support HTTP/1.1 as keep-alive
# is not running properly , could _not_ be seperated into properly
# self.send_response(200), self.send_header('Connnection: close')
# Allow easy XML debugging in Mozilla Firefox 3
# * Content-Type is don't care value, might as well text/plain
# * Connection: close is don't care value
head = 'HTTP/1.0 200 OK\r\n'
head += 'Content-Length: %s\r\n' % len(output)
head += 'Content-Type: application/xml\r\n'
head += 'Connection: close\r\n'
head += '\r\n'
self.wfile.write(head + output + '\r\n');
# Force connection closing
self.close_connection = 1
# Log succesfull request
self.log_request(200,len(output))
def main():
server = HTTPServer((HOST, PORT), MyHandler)
try:
pid = os.fork()
except OSError, e:
raise Exception, "%s [%d]" % (e.strerror, e.errno)
if (pid==0):
os.setsid()
print 'started httpserver on %s:%s... (pid=%s)' % (HOST, PORT, os.getpid())
print 'Logfile at: %s' % LOGFILE
server.serve_forever()
# On any signal close socket
# server.socket.close()
else:
os._exit(0)
if __name__ == '__main__':
main()