contrib/script/sip_to_pjsip: add support for realtime
[asterisk/asterisk.git] / contrib / scripts / sip_to_pjsip / sqlconfigparser.py
1 from astconfigparser import MultiOrderedConfigParser
2
3 import MySQLdb
4 import traceback
5
6 class SqlConfigParser(MultiOrderedConfigParser):
7
8     _tablename = "sippeers"
9
10     def __init__(self,tablename="sippeers"):
11         self._tablename=tablename
12         MultiOrderedConfigParser.__init__(self)
13
14     def connect(self, user, password, host, port, database):
15         self.cnx = MySQLdb.connect(user=user,passwd=password,host=host,port=int(port),db=database)
16
17     def read(self, filename, sect=None):
18         MultiOrderedConfigParser.read(self, filename, sect)
19         # cursor = self.cnx.cursor(dictionary=True)
20         cursor = self.cnx.cursor(cursorclass=MySQLdb.cursors.DictCursor)
21         cursor.execute("SELECT * from `" + MySQLdb.escape_string(self._tablename) + "`")
22         rows = cursor.fetchall()
23
24         for row in rows:
25             sect = self.add_section(row['name'])
26             for key in row:
27                 if (row[key] != None):
28                     for elem in str(row[key]).split(";"):
29                         sect[key] = elem
30                     #sect[key] = str(row[key]).split(";")
31
32     def write_dicts(self, config_file, mdicts):
33         """Write the contents of the mdicts to the specified config file"""
34         for section, sect_list in mdicts.iteritems():
35             # every section contains a list of dictionaries
36             for sect in sect_list:
37                 sql = "INSERT INTO "
38                 if (sect.get('type')[0] == "endpoint"):
39                     sql += "ps_endpoints "
40                 elif (sect.get('type')[0] == "aor" and section != "sbc"):
41                     sql += "ps_aors "
42                 elif (sect.get('type')[0] == "identify"):
43                     sql += "ps_endpoint_id_ips"
44                 else:
45                     continue
46
47                 sql += " SET `id` = " + "\"" + MySQLdb.escape_string(section) + "\""
48                 for key, val_list in sect.iteritems():
49                     if key == "type":
50                         continue
51                     # every value is also a list
52
53                     key_val = " `" + key + "`"
54                     key_val += " = " + "\"" + MySQLdb.escape_string(";".join(val_list)) + "\""
55                     sql += ","
56                     sql += key_val
57
58                 config_file.write("%s;\n" % (sql))
59
60     def write(self, config_file):
61         """Write configuration information out to a file"""
62         try:
63             self.write_dicts(config_file, self._sections)
64         except Exception,e:
65                 print "Could not open file ", config_file, " for writing"
66                 traceback.print_exc()
67
68
69