#!/usr/bin/python
# googlecontacts.py v0.1
# By: John Baab
# Email: rhpot1991@ubuntu.com
# Purpose: syncs contacts from google to asterisk server
# Requirements: python, gdata python client, asterisk
#
# License:
#
# This Package is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# This package is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# On Debian & Ubuntu systems, a complete copy of the GPL can be found under
# /usr/share/common-licenses/GPL-3, or (at your option) any later version

import atom,re,sys,os
import gdata.contacts
import gdata.contacts.service

def main():
    # Change this if you aren't in the US.  If you have more than one country code in your contacts,
    # then use an empty string and make sure that each number has a country code.
    country_code = "1"

    gd_client = gdata.contacts.service.ContactsService()
    gd_client.email = "your@google.mail"
    gd_client.password = "and your pass"
    gd_client.source = 'gcontact2ast'
    gd_client.ProgrammaticLogin()
    query = gdata.contacts.service.ContactsQuery()
    query.max_results = 1000
    feed = gd_client.GetContactsFeed(query.ToUri())

    # delete all of our contacts before we refetch them, this will allow deletions
    os.system("asterisk -rx \'database deltree cidname\'")

    # for each phone number in the contacts
    for i, entry in enumerate(feed.entry):
        for phone in entry.phone_number:
            # Strip out any non numeric characters
            phone.text = re.sub('\D', '', phone.text)

            # Remove leading digit if it exists, we will add this again later for all numbers
            # Only if a country code is defined.
            if country_code != "":
                phone.text = re.sub('^\+?%s' % country_code, '', phone.text)

            # Insert the number into the cidname database, reinsert the country code if defined.
            os.system("asterisk -rx \'database put cidname +%s%s \"%s\"\'" % (country_code,phone.text,entry.title.text))


if __name__ == "__main__":
        main()

