Skip to content

Instantly share code, notes, and snippets.

@jaydg
Last active March 26, 2024 19:06
Show Gist options
  • Save jaydg/7fde269f732060399ed59ef05f66a2d2 to your computer and use it in GitHub Desktop.
Save jaydg/7fde269f732060399ed59ef05f66a2d2 to your computer and use it in GitHub Desktop.
Convert Google Contacts CSV export to Grandstream's dubious XML file format
#!/usr/bin/env python3
import csv
import re
import sys
from xml.dom.minidom import getDOMImplementation
contacts = []
# strip unwanted characters from strings
def clean(s):
s = s.replace('+49', '0')
s = s.replace('+', '00')
return ''.join(n for n in s if n.isdigit())
# Import Contacts
with open(sys.argv[1], encoding='utf-16-le') as csvfile:
records = csv.DictReader(csvfile)
noFax = re.compile(".*fax.*", re.IGNORECASE)
for record in records:
contact = {
'FirstName': record['Given Name'],
'LastName': record['Family Name'],
'Company' : record['Organization 1 - Name'],
'numbers': []
}
for number in range(1, 4):
typ = 'Phone {} - Type'.format(number)
val = 'Phone {} - Value'.format(number)
if (record[typ] and not noFax.match(record[typ])):
# Grandstream uses three types of phone numbers,
# "Work", "Cell", "Home"
record[typ] = 'Cell' if record[typ] == 'Mobile' else record[typ]
# Split field value - multiple numbers of the same
# type are stuffed into a single field, sepatated
# by ':::'
for n in map(clean, record[val].split(':::')):
contact['numbers'].append({
'type': record[typ],
'value': n
})
# Only use this contact if it has any phone number
if len(contact['numbers']):
contacts.append(contact)
impl = getDOMImplementation()
xml = impl.createDocument(None, "AddressBook", None)
top_element = xml.documentElement
for contact in contacts:
c = xml.createElement('Contact')
# Names
for part in ['FirstName', 'LastName', 'Company']:
if not contact[part]:
continue
f = xml.createElement(part)
f.appendChild(xml.createTextNode(contact[part]))
c.appendChild(f)
# Numbers
for number in contact['numbers']:
group = xml.createElement('Phone')
group.setAttribute('type', number['type'])
# phonenumber
num = xml.createElement('phonenumber')
num.appendChild(xml.createTextNode(number['value']))
group.appendChild(num)
# accountindex
idx = xml.createElement('accountindex')
idx.appendChild(xml.createTextNode('0'))
group.appendChild(idx)
c.appendChild(group)
top_element.appendChild(c)
print(xml.toprettyxml(encoding='UTF-8').decode())
@nerdosity
Copy link

Hallo bekomme immer diesen fehler beim ausführen.mfg
image

Just try to change it to another encoding type, I make it working with ISO-8859-1 in Italy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment