Quickfix: Import your nextcloud addressbook into twinkle

Hi All,

 

I just switched to the twinkle-softphone and found that there is no way to import anything into the addressbook. I am currently learning python so I thought this is a nice little project to work on. Note that this only works on python 2.

Tested on Ubuntu 16.04LTS, Ubuntu 18.04,  Nextcloud 13 and TWINKLE 1.9.0

It works for me and may not work for you. Please comment if you have any issues with this.

 

#twinkle addressbook importer for nextcloud

nextcloud_protocol="https://" 
nextcloud_username="your_nextcloud_username"
nextcloud_password="your_nextcloud_password"
nextcloud_url="the_nextcloud_url"

#############################################################
import urllib
from os.path import expanduser
import os.path
from shutil import copyfile

# get the home path
home = expanduser("~")

#build the twinkle addressbook path
twinkle_phonebook_path=home+"/.twinkle/twinkle.ab"

#create a backup if a file exists
if(os.path.isfile(twinkle_phonebook_path)):
    copyfile(twinkle_phonebook_path, twinkle_phonebook_path+".bak")

#open the addressbook file
file=open(twinkle_phonebook_path,"w")

# build the nextcloud URL
url=nextcloud_protocol+nextcloud_username+":"+nextcloud_password+"@"+nextcloud_url+"/remote.php/dav/addressbooks/users/"+nextcloud_username+"/contacts?export"

#load the VCF Data
try:
    response = urllib.urlopen(url)

except:
    print("Error!");
    exit()

else:
vcf = response.read()

#go through the lines in the vcf-document 
for line in vcf.splitlines():

    #check if it's a "full name" line
    if line.startswith("FN"):
        r=line.split(":")
        full_name=r[1];
        names=full_name.split(" ")
        first_name=names[0]
        if len(names)==1:
            last_name=""
        else:
            last_name=names[1]

    #check if it's a phone number line
    if line.startswith("TEL;TYPE"):
        r2=line.split(":")
        phone_number=r2[1]
        r3=r2[0].split("=")
        phone_type=r3[1]

        #write new line to file. 
        this_line=last_name.strip()+"||"+first_name.strip()+"|"+phone_number.strip()+"|"+phone_type.strip()
        file.write(this_line+"\n")

#close the file
file.close()