forked from gitRigge/CardDAV2MicroSIP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.py
More file actions
158 lines (146 loc) · 6.68 KB
/
bridge.py
File metadata and controls
158 lines (146 loc) · 6.68 KB
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
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2022, Roland Rickborn (r_2@gmx.net)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Revision history:
# 2021-03-25 Created
# 2022-05-02 Replaced pyCardDAV with vobject
# 2022-06-17 Added reading MicroSIP config to retrieve country code
#
# This script generates Contacts.xml valid for MicroSIP VoIP client v3.10
# ---------------------------------------------------------------------------
import configparser
import os
import re
import requests
import vobject
from requests.auth import HTTPBasicAuth
__author__ = 'Roland Rickborn'
__copyright__ = 'Copyright (c) 2022 {}'.format(__author__)
__version__ = '1.0'
__url__ = 'https://github.com/gitRigge/CardDAV2MicroSIP'
__license__ = 'MIT License (MIT)'
microSipDataPath = os.path.join(os.environ['APPDATA'], 'MicroSIP')
bridgeDataPath = os.path.join(os.environ['LOCALAPPDATA'], 'CardDAV2MicroSIP')
bridge_config = configparser.ConfigParser()
bridge_config.read(os.path.join(bridgeDataPath, 'bridge.conf'))
microsip_config = configparser.ConfigParser()
microsip_config.read_file(open(os.path.join(microSipDataPath, 'microsip.ini'), 'r', encoding='utf16'))
def get_country_code():
"""Tries to find country code info in MicroSIP config file and returns it."""
p = re.compile(r'(\+[0-9]{1,3})')
for section in microsip_config.sections():
if microsip_config.has_option(section,'dialPlan'):
m = p.search(microsip_config.get(section,'dialPlan'))
if m:
return m.group(1)
return '+49'
def get_carddav_data():
"""Retrieves CardDAV data from all accounts specified in the bridge config and returns all content in one string"""
accounts = {}
servers = bridge_config.sections()
counter = 1
for server in servers:
print("Reading ", server, " from servers.")
accounts[counter] = {}
_urls = []
_files = []
for key in bridge_config[server]:
if key == 'user':
accounts[counter]['user'] = bridge_config[server]['user']
elif key == 'pass':
accounts[counter]['pass'] = bridge_config[server]['pass']
elif key.startswith('url'):
_urls.append(bridge_config[server][key])
elif key.startswith('file'):
_files.append(bridge_config[server][key])
accounts[counter]['url'] = _urls
accounts[counter]['file'] = _files
counter = counter + 1
contents = ''
for account in accounts:
print("Processing ", account, " from servers.")
for abook in accounts[account]['file']:
try:
if os.path.exists(abook):
with open(abook, 'r', encoding='utf8') as file:
content = file.read()
contents = contents + content
else:
print("File ", abook, " not found! Please check bridge.conf.")
except:
continue
for abook in accounts[account]['url']:
try:
response = requests.get(abook+'/?export', auth = HTTPBasicAuth(accounts[account]['user'], accounts[account]['pass']))
contents = contents + str(response.content.decode('utf-8'))
except:
continue
return contents
def create_cards_list(file_content):
"""Turns the given string into VCard objects and returns it as a list"""
_l = str(file_content).replace('\\r\\n','\n').split('END:VCARD')
_l.pop(-1)
cards = []
for i in _l:
v = vobject.readOne(i+'END:VCARD\n')
try:
_o = v.org.value
except:
v.add('org').value = ['']
cards.append(v)
return cards
def nice_number(phone_number):
"""Strips space, -, ( and ) from the given string, replaces counrty cody with 0 and returns the string"""
nice_phone_number = phone_number.replace(get_country_code(),'0').replace(' ' ,'').replace('-' ,'').replace('(' ,'').replace(')' ,'').strip()
return nice_phone_number
def export_to_xml(items):
"""Exports the given list into an XML file"""
f = open(os.path.join(microSipDataPath, 'Contacts.xml'), 'w', encoding='utf8')
f.write(u'\ufeff')
f.write('<?xml version="1.0"?>\n')
f.write('<contacts>\n')
for item in items:
try:
if item.org.value[0] != '':
_org = '{}, '.format(item.org.value[0])
else:
_org = ''
for tel in item.tel_list:
if tel.type_param == 'HOME':
f.write('<contact number="{}" name="{} ({}Home)" presence="0" directory="0" ></contact>\n'.format(nice_number(tel.value), item.fn.value, _org))
elif tel.type_param == 'WORK':
f.write('<contact number="{}" name="{} ({}Work)" presence="0" directory="0" ></contact>\n'.format(nice_number(tel.value), item.fn.value, _org))
elif tel.type_param == 'CELL':
f.write('<contact number="{}" name="{} ({}Mobile)" presence="0" directory="0" ></contact>\n'.format(nice_number(tel.value), item.fn.value, _org))
else:
f.write('<contact number="{}" name="{} ({}Voice)" presence="0" directory="0" ></contact>\n'.format(nice_number(tel.value), item.fn.value, _org))
except:
continue
f.write('</contacts>\n')
f.close()
def convert_file_into_xml(fileName):
"""Converts the given file into an XML file"""
card_list = create_cards_list(fileName)
export_to_xml(card_list)
vcf = get_carddav_data()
convert_file_into_xml(vcf)