contact_gc.py 29.5 KB
Newer Older
1
##
2
## Created : Tue Mar 13 14:26:01 IST 2012
3
##
4
## Copyright (C) 2012, 2013 Sriram Karra <karra.etc@gmail.com>
5
##
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## This file is part of ASynK
##
## ASynK is free software: you can redistribute it and/or modify it under
## the terms of the GNU Affero General Public License as published by the
## Free Software Foundation, version 3 of the License
##
## ASynK 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 Affero General Public
## License for more details.
##
## You should have a copy of the license in the doc/ directory of ASynK.  If
## not, see <http://www.gnu.org/licenses/>.
##
## ####
21 22 23 24 25 26 27
##
## This file defines a wrapper class around a Google Contact entry, by
## extending the Contact abstract base Contact class. Using this class one can
## create and update contact entires in google contact folders, and manipulate
## properties, etc.
##

28 29 30
import logging, getopt, re, string, sys, time
import atom, iso8601
import gdata, gdata.data, gdata.contacts.data, gdata.contacts.client
31

32
import demjson, utils
33
from   contact    import Contact
34
import folder_gc
35 36 37 38 39 40 41 42

class GCContact(Contact):
    """This class extends the Contact abstract base class to wrap a Google
    Contact"""

    def __init__ (self, folder, con=None, gce=None):
        Contact.__init__(self, folder, con)

43 44 45 46 47
        ## Sometimes we might be creating a contact object from Outlook or
        ## other entry which might have the google contact ID in its sync tags
        ## field. if that is present, we should use it to initialize the
        ## itemid field for the current object

48
        conf = self.get_config()
49 50
        if con:
            try:
51 52
                pname_re = conf.get_profile_name_re()
                label    = conf.make_sync_label(pname_re, self.get_dbid())
53 54
                tag, itemid = con.get_sync_tags(label)[0]

55
                self.set_itemid(self.normalize_gcid(itemid))
56
            except Exception, e:
57
                logging.debug('Potential new GCContact: %s', con.get_name())
58

59 60 61 62
        self.set_gce(gce)
        if gce:
            self.init_props_from_gce(gce)

63 64
        self.in_init(False)

65 66 67 68 69 70 71 72 73
    @classmethod
    def normalize_gcid (self, itemid):
        """Replace the projection to a normalized 'thin', regardless of
        whether the original contact had a full or a base. Also make all the
        contact URIs as https://. Return value is the itemid fixed for these
        things."""

        # Workaround for a weird Google API behaviour. Certain
        # operations only succed with the 'full' projection.
74
        itemid = string.replace(itemid, '/base/', '/full/')
75

76 77 78 79
        # The /thin/ projection has a problem with updating etags and for
        # modifications... Not sure I really understand this projection
        # stuff.
        itemid = string.replace(itemid, '/thin/', '/full/')
80 81 82 83 84 85 86 87 88

        # Finally, since we use the entire URL as the contact's key,
        # we need to normalize the URLs. I am not sure why Google
        # can't be more consistent at its end... but this is what we
        # got.
        itemid = string.replace(itemid, 'http://', 'https://')

        return itemid

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
    ##
    ## First the inherited abstract methods from the base classes
    ##

    def save (self):
        """Saves the current contact on the server. For now we are only
        handling a new contact creation scneario. The protocol for updates is
        different"""

        ## FIXME: Handle the case of updating an existing contact's details.

        gce   = self.init_gce_from_props()
        entry = self.get_db().get_gdc().CreateContact(gce)

        if entry:
            logging.debug('Creation Successful!')
            logging.debug('ID for the new contact: %s', entry.id.text)
            self.set_itemid(entry.id.text)
        else:
            logging.error('Contact creation error.')
            return None

        return entry.id.text

    ##
    ## Now onto the non-abstract methods.
    ##

117
    def get_gce (self, refresh=False):
118
        gce = self._get_att('gce')
119
        if gce and (not refresh):
120 121 122 123 124
            return gce

        return self.init_gce_from_props()

    def set_gce (self, gce):
125
        return self._set_att('gce', gce)
126

127 128 129 130 131 132 133 134 135
    def get_etag (self):
        try:
            return self._get_att('etag')
        except Exception, e:
            return None

    def set_etag (self, etag):
        return self._set_att('etag', etag)

136 137 138 139
    def init_props_from_gce (self, gce):
        self._snarf_itemid_from_gce(gce)
        self._snarf_names_gender_from_gce(gce)
        self._snarf_notes_from_gce(gce)
140
        self._snarf_group_membership_from_gce(gce)
141 142 143 144 145 146 147
        self._snarf_emails_from_gce(gce)
        self._snarf_postal_from_gce(gce)
        self._snarf_org_details_from_gce(gce)
        self._snarf_phones_and_faxes_from_gce(gce)
        self._snarf_dates_from_gce(gce)
        self._snarf_websites_from_gce(gce)
        self._snarf_ims_from_gce(gce)
148
        self._snarf_sync_tags_from_gce(gce)
149 150 151

        self._snarf_custom_props_from_gce(gce)

152 153 154 155 156 157
        # Google entries do not have a created entry. We should just set it to
        # the current time, and take it from there.
        if not self.get_created():
            self.set_created(iso8601.tostring(time.time()))
            self.set_updated(iso8601.tostring(time.time()))
        
158 159 160 161 162 163 164 165 166 167 168 169 170 171
    def init_gce_from_props (self):
        gce = gdata.contacts.data.ContactEntry()

        self._add_itemid_to_gce(gce)
        self._add_names_gender_to_gce(gce)
        self._add_notes_to_gce(gce)
        self._add_group_membership_to_gce(gce)
        self._add_emails_to_gce(gce)
        self._add_postal_to_gce(gce)
        self._add_org_details_to_gce(gce)
        self._add_phones_and_faxes_to_gce(gce)
        self._add_dates_to_gce(gce)
        self._add_websites_to_gce(gce)
        self._add_ims_to_gce(gce)
172
        self._add_sync_tags_to_gce(gce)
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

        self._add_custom_props_to_gce(gce)

        return self.set_gce(gce)

    def __str__ (self):
        ret = ''

        props = self.get_prop_names()
        for prop in props:
            ret += '%18s: %s\n' % (prop, self._get_prop(prop))

        return ret

    ##
    ## Internal functions that are not inteded to be called from outside.
    ##

    def _snarf_itemid_from_gce (self, ce):
        if ce.id:
193
            self.set_itemid(self.normalize_gcid(ce.id.text))
194

195 196 197
        if ce.etag:
            self.set_etag(ce.etag)

198 199
    def _snarf_names_gender_from_gce (self, ce):
        if ce.name:
200 201 202
            if ce.name.additional_name:
                self.set_middlename(ce.name.additional_name.text)

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
            if ce.name.family_name:
                self.set_lastname(ce.name.family_name.text)

            if ce.name.given_name:
                self.set_firstname(ce.name.given_name.text)

            if ce.name.full_name:
                # The FileAs property is required for Outlook. So we need to
                # keep this around
                self.set_fileas(ce.name.full_name.text)

            if ce.name.name_prefix:
                self.set_prefix(ce.name.name_prefix.text)

            if ce.name.name_suffix:
                self.set_suffix(ce.name.name_suffix.text)

        if ce.nickname:
            self.set_nickname(ce.nickname.text)

        if ce.gender:
            self.set_gender(ce.gender.value)

    def _snarf_notes_from_gce (self, ce):
        if ce.content and ce.content.text:
228
            self.add_notes(ce.content.text)
229

230 231 232 233 234 235 236 237 238 239 240
    def _snarf_group_membership_from_gce (self, ce):
        # The group id corresponding to the current folder is ignored, the
        # rest go into custom properties
        gids = []
        if ce.group_membership_info:
            if len(ce.group_membership_info) > 0:
                for gid in ce.group_membership_info:
                    if gid.href == self.get_folder().get_itemid():
                        continue
                    gids.append(gid.href)

241
                if len(gids) > 0:
242
                    self.add_custom('gids', demjson.encode(gids))
243

244 245 246 247 248 249
    def _snarf_emails_from_gce (self, ce):
        """Fetch the email entries in the specified ContactEntry object and
        populate them in the internal email address strutures."""

        if ce.email:
            for email in ce.email:
250 251 252 253 254 255 256 257 258
                if email.address:
                    if email.rel:
                        if email.rel == gdata.data.WORK_REL:
                            self.add_email_work(email.address)
                        elif email.rel == gdata.data.HOME_REL:
                            self.add_email_home(email.address)
                        elif email.rel == gdata.data.OTHER_REL:
                            self.add_email_other(email.address)
                    else:
259 260
                        self.add_email_other(email.address)

261 262 263
                    if email.primary:
                        self.set_email_prim(email.address)

264 265 266 267
    rel_map = {gdata.data.WORK_REL : 'Work',
               gdata.data.HOME_REL : 'Home',
               gdata.data.OTHER_REL : 'Other',}

268
    def _snarf_postal_from_gce (self, ce):
269 270
        self.set_postal_prim_label(None)

271
        if ce.structured_postal_address:
272
            if len(ce.structured_postal_address) > 0:
273
                for addr in ce.structured_postal_address:
274 275 276 277 278
                    if addr.label:
                        label = addr.label
                    else:
                        label = self.rel_map[addr.rel]

279 280 281
                    if addr.primary == 'true':
                        ## What happens if more than one is marked as primary? Hm.
                        self.set_postal_prim_label(label)
282

283 284 285 286 287 288
                    ad = {'street'  : None,
                          'city'    : None,
                          'state'   : None,
                          'country' : None,
                          'zip'     : None,}
                    
289 290
                    fa = addr.formatted_address
                    if fa:
291
                        ad.update({'formatted_address' : fa.text})
292 293 294

                    st = addr.street
                    if st:
295
                        ad.update({'street' : st.text})
296 297 298

                    ci = addr.city
                    if ci:
299
                        ad.update({'city' : ci.text})
300 301 302

                    st = addr.region
                    if st:
303
                        ad.update({'state' : st.text})
304 305 306

                    co = addr.country
                    if co:
307
                        ad.update({'country' : co.text})
308 309 310

                    zi = addr.postcode
                    if zi:
311
                        ad.update({'zip' : zi.text})
312 313

                    self.add_postal(label, ad)
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

    def _snarf_org_details_from_gce (self, ce):
        if ce.organization:
            if ce.organization.name and ce.organization.name.text:
                self.set_company(ce.organization.name.text)

            if ce.organization.title and ce.organization.title.text:
                self.set_title(ce.organization.title.text)

            if ce.organization.department:
                self.set_dept(ce.organization.department.text)

    def _snarf_phones_and_faxes_from_gce (self, ce):
        if ce.phone_number:
            for ph in ce.phone_number:
                if not ph.text:
                    continue

332 333 334
                label = ph.label
                num   = ph.text

335 336 337 338 339 340 341 342 343 344
                if label:
                    if re.search('Home', label):
                        self.add_phone_home((label, num))
                    elif re.search('(Work)|(Office)', label):
                        self.add_phone_work((label, num))
                    elif re.search('(Other)|(Misc)', label):
                        self.add_phone_other((label, num))
                    elif re.search('Mobile', label):
                        self.add_phone_mob((label, num))
    
345
                    elif re.search('Home Fax', label):
346
                        self.add_fax_home(('Home', num))
347
                    elif re.search('Work Fax', label):
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
                        self.add_fax_work(('Work', num))                    
                else:
                    if ph.rel == gdata.data.HOME_REL:
                        self.add_phone_home(('Home', num))
                    elif ph.rel == gdata.data.WORK_REL:
                        self.add_phone_work(('Work', num))
                    elif ph.rel == gdata.data.OTHER_REL:
                        self.add_phone_other(('Other', num))
                    elif ph.rel == gdata.data.MOBILE_REL:
                        self.add_phone_mob(('Mobile', num))
    
                    elif ph.rel == gdata.data.HOME_FAX_REL:
                        self.add_fax_home(('Home', num))
                    elif ph.rel == gdata.data.WORK_FAX_REL:
                        self.add_fax_work(('Work', num))
363 364 365 366

                if ph.primary == 'true':
                    if ph.rel in [gdata.data.HOME_REL, gdata.data.WORK_REL,
                                  gdata.data.OTHER_REL, gdata.data.MOBILE_REL]:
367
                        self.set_phone_prim(num)
368 369
                    elif ph.rel in [gdata.data.HOME_FAX_REL,
                                    gdata.data.WORK_FAX_REL]:
370
                        self.set_fax_prim(num)
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

    def _snarf_dates_from_gce (self, ce):
        if ce.birthday and ce.birthday.when:
            self.set_birthday(ce.birthday.when)

        if ce.event and len(ce.event) > 0:
            ann = utils.get_event_rel(ce.event, 'anniversary')
            if ann:
                self.set_anniv(ann.start)

    def _snarf_websites_from_gce (self, ce):
        if ce.website:
            for site in ce.website:
                if site.rel == 'home-page':
                    self.add_web_home(site.href)
                elif site.rel == 'work':
                    self.add_web_work(site.href)

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    im_proto_label_map = {
        'http://schemas.google.com/g/2005#AIM'         : 'AOL',
        'http://schemas.google.com/g/2005#MSN'         : 'MSN',
        'http://schemas.google.com/g/2005#YAHOO'       : 'Yahoo',
        'http://schemas.google.com/g/2005#SKYPE'       : 'Skype',
        'http://schemas.google.com/g/2005#QQ'          :  'QQ',
        'http://schemas.google.com/g/2005#GOOGLE_TALK' : 'GTalk',
        'http://schemas.google.com/g/2005#ICQ'         : 'ICQ',
        'http://schemas.google.com/g/2005#JABBER'      : 'Jabber',
    }

    im_label_proto_map = {}
    for key, val in im_proto_label_map.iteritems():
        im_label_proto_map.update({val : key})

404
    def _snarf_ims_from_gce (self, ce):
405 406 407 408 409 410
        ## FIXME: The Google IMs list implementation is rather complex. There
        ## can be labels, rels, and protocols. They all appear
        ## redundant. Perhaps label will not always be set? This needs to be
        ## investigated. But this is a good start
        if ce.im:
            for im in ce.im:
411 412
                label = 'Default'         # this should never go 'on the wire'

413 414 415 416 417
                # The way Google uses protocol and label is a bit confusing...
                if im.label:
                    if not im.protocol:
                        im.protocol = im.label

418
                if im.protocol:
419 420 421 422
                    if im.protocol in self.im_proto_label_map:
                        label = self.im_proto_label_map[im.protocol]
                    else:
                        label = im.protocol
423 424 425 426 427 428 429 430 431 432 433 434 435
                else:
                    ## No protocol, and no label. We need to do some general
                    ## stuff here...
                    rel_re = 'http://schemas.google.com/g/2005#(.*)'
                    res = re.search(rel_re, im.rel)
                    if res:
                        label = res.group(1)
                    else:
                        label = 'Other'   # Hm, alright. I give up
                    
                self.add_im(label, im.address)
                if im.primary == 'true':
                    self.set_im_prim(label)
436

437 438 439 440
    def _snarf_sync_tags_from_gce (self, ce):
        if ce.user_defined_field:
            keyprefix = (self.get_config().get_label_prefix() +
                         self.get_config().get_label_separator())
441 442 443 444
            stgs = folder_gc.get_udps_by_key_prefix(
                ce.user_defined_field, keyprefix)

            self.set_sync_tags(stgs)
445

446
    def _snarf_custom_props_from_gce (self, ce):
447 448
        ## Iterate through the user_defined_propertie and do something with
        ## them...
449 450
        stag_re = (self.get_config().get_label_prefix() +
                   self.get_config().get_label_separator())
451 452 453 454
        if ce.user_defined_field:
            for ep in ce.user_defined_field:
                if ep.key == 'created':
                    self.set_created(ep.value)
455
                elif not re.search(stag_re, ep.key):
456
                    self.add_custom(ep.key, ep.value)
457

458
    def _is_valid_ph (self, phone, type):
459 460 461 462 463 464
        phone = phone.strip()
        valid = True
        if (phone == '' or phone == '-' or phone == '_'):
            valid = False

        if not valid:
465 466
            logging.info('Invalid %s number for contact %s. Skipping field',
                         type, self.get_name())
467 468 469

        return valid

470 471 472
    def _is_invalid_ph (self, phone, type):
        return (not self._is_valid_ph(phone, type))

473 474 475
    def _add_itemid_to_gce (self, gce):
        itemid = self.get_itemid()
        if itemid:
476
            gce.id = atom.data.Id(text=itemid)
477
        else:
478 479 480
            pass
            # logging.debug('Potential new contact to GC: %s',
            #               self.get_name())
481

482 483 484 485
        etag = self.get_etag()
        if etag:
            gce.etag = etag

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    def _add_names_gender_to_gce (self, gce):
        """Populate the Name fields in gce, which is a Google ContactEntry
        object. Values for the name fields are obtained from the current
        objects property fields that should have been set earlier"""

        n = gdata.data.Name()

        text = self.get_firstname()
        if text:
            n.given_name = gdata.data.GivenName(text=text)

        text = self.get_lastname()
        if text:
            n.family_name = gdata.data.FamilyName(text=text)

501 502 503 504
        text = self.get_middlename()
        if text:
            n.additional_name = gdata.data.AdditionalName(text=text)

505 506 507 508 509 510 511 512
        text = self.get_name()
        if text:
            n.full_name = gdata.data.FullName(text=text)

        text = self.get_suffix()
        if text:
            n.name_suffix = gdata.data.NameSuffix(text=text)

513
        text = self.get_prefix()
514 515 516 517 518 519 520 521 522 523 524
        if text:
            n.name_prefix = gdata.data.NamePrefix(text=text)

        gce.name = n

        text = self.get_nickname()
        if text:
            gce.nickname = gdata.contacts.data.NickName(text=text)

        text = self.get_gender()
        if text:
525
            gce.gender = gdata.contacts.data.Gender(value=text)
526 527 528 529 530 531 532


    def _add_notes_to_gce (self, gce):
        """Append the Notes field to the specified ContactEntry object. As of
        now only the first Notes entry is copied. In future the remaining
        ones will be mapped into the custom fields section."""

533 534 535 536
        ## FIXME: Google allows only a single notes field, Others, like BBDB,
        ## can have multiple. For now just deal with the first entry and
        ## ignore the rest. Eventually we could put these things in custom
        ## fields...
537 538 539 540 541 542 543 544 545 546 547 548 549

        notes = self.get_notes()
        if notes:
            gce.content = atom.data.Content(text=notes[0])

    def _add_group_membership_to_gce (self, gce):
        """Append the group IDs that denote group membership to the specified
        ContactEntry object."""

        gid = self.get_folder().get_itemid()
        gidm = gdata.contacts.data.GroupMembershipInfo(href=gid)
        gce.group_membership_info.append(gidm)

550 551 552 553 554 555 556 557 558 559
        if not self.get_custom('gids'):
            return

        js = self.get_custom('gids')
        js = js.replace('\\', '')
        gids = demjson.decode(js)
        for gid in gids:
            gidm = gdata.contacts.data.GroupMembershipInfo(href=gid)
            gce.group_membership_info.append(gidm)

560 561 562 563 564 565 566
    def _add_emails_to_gce (self, gce):
        """Append the email addresses from the current Contact object to the
        specified ContactEntry object."""

        email_prim = self.get_email_prim()

        for email in self.get_email_home():
567 568
            if not email:
                continue
569 570 571 572 573 574
            prim = 'true' if email == email_prim else 'false'
            em = gdata.data.Email(address=email, primary=prim,
                                  rel=gdata.data.HOME_REL)
            gce.email.append(em)

        for email in self.get_email_work():
575 576
            if not email:
                continue
577 578 579 580 581 582
            prim = 'true' if email == email_prim else 'false'
            em = gdata.data.Email(address=email, primary=prim,
                                  rel=gdata.data.WORK_REL)
            gce.email.append(em)

        for email in self.get_email_other():
583 584
            if not email:
                continue
585 586 587 588 589 590 591 592 593 594
            prim = 'true' if email == email_prim else 'false'
            em = gdata.data.Email(address=email, primary=prim,
                                  rel=gdata.data.OTHER_REL)
            gce.email.append(em)


    def _add_postal_to_gce (self, gce):
        """Insert the address fields from current contact object into the
        ContactEntry object."""

595 596
        postals = self.get_postal(as_array=True)
        for label, postal in postals:
597
            if postal:
598
                prim = 'true' if self.is_postal_prim(label) else 'false'
599
                add  = gdata.data.StructuredPostalAddress(
600
                    label=label, primary=prim)
601 602 603 604 605 606

                if postal['street']:
                    strt = gdata.data.Street(text=postal['street'])
                    add.street = strt

                if postal['city']:
607
                    city = gdata.data.City(text=postal['city'])
608 609 610
                    add.city = city

                if postal['state']:
611
                    state = gdata.data.Region(text=postal['state'])
612 613 614 615 616 617 618 619 620
                    add.region = state

                if postal['country']:
                    country = gdata.data.Country(text=postal['country'])
                    add.country = country

                if postal['zip']:
                    postcode = gdata.data.Postcode(text=postal['zip'])
                    add.postcode = postcode
621

622 623
                k = 'formatted_address'
                fa = postal[k] if k in postal else None
624 625 626
                if fa:
                    fad = gdata.data.FormattedAddress(text=fa)
                    add.formatted_address = fad
627

628
                gce.structured_postal_address.append(add)
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

    def _add_org_details_to_gce (self, gce):
        """Insert the contact's company, department and other such
        organization details into the specified ContactEntry."""

        company = self.get_company()
        title   = self.get_title()
        dept    = self.get_dept()

        on = gdata.data.OrgName(text=company)    if company else None
        ot = gdata.data.OrgTitle(text=title)     if title   else None
        od = gdata.data.OrgDepartment(text=dept) if dept    else None

        org = gdata.data.Organization(primary='true', name=on, title=ot,
                                      department=od, rel=gdata.data.WORK_REL)
        gce.organization = org


    def _add_phones_and_faxes_to_gce (self, gce):
        """Append the contact's phone details into the specified ContactEntr
        object."""

        ph_prim = self.get_phone_prim()

653
        for label, ph in self.get_phone_home():
654
            if not ph or self._is_invalid_ph(ph, 'Home'):
655
                continue
656 657
            prim = 'true' if ph == ph_prim else 'false'
            phone = gdata.data.PhoneNumber(text=ph, primary=prim,
658
                                           label=label)
659 660
            gce.phone_number.append(phone)

661
        for label, ph in self.get_phone_work():
662
            if not ph or self._is_invalid_ph(ph, 'Work'):
663
                continue
664 665
            prim = 'true' if ph == ph_prim else 'false'
            phone = gdata.data.PhoneNumber(text=ph, primary=prim,
666
                                           label=label)
667 668
            gce.phone_number.append(phone)

669
        for label, ph in self.get_phone_other():
670
            if not ph or self._is_invalid_ph(ph, 'Other'):
671
                continue
672 673
            prim = 'true' if ph == ph_prim else 'false'
            phone = gdata.data.PhoneNumber(text=ph, primary=prim,
674
                                           label=label)
675 676
            gce.phone_number.append(phone)

677
        for label, ph in self.get_phone_mob():
678
            if not ph or self._is_invalid_ph(ph, 'Mobile'):
679
                continue
680 681
            prim = 'true' if ph == ph_prim else 'false'
            phone = gdata.data.PhoneNumber(text=ph, primary=prim,
682
                                           label=label)
683 684 685 686
            gce.phone_number.append(phone)

        fax_prim = self.get_fax_prim()

687
        for label, fa in self.get_fax_home():
688
            if not fa or self._is_invalid_ph(fa, 'Home Fax'):
689
                continue
690
            prim = 'true' if fa == fax_prim else 'false'
691
            fax  = gdata.data.PhoneNumber(text=fa, primary=prim,
692
                                           label=label)
693 694
            gce.phone_number.append(fax)

695
        for label, fa in self.get_fax_work():
696
            if not fa or self._is_invalid_ph(fa, 'Work Fax'):
697
                continue
698
            prim = 'true' if fa == fax_prim else 'false'
699
            fax  = gdata.data.PhoneNumber(text=fa, primary=prim,
700
                                           label=label)
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            gce.phone_number.append(fax)

    def _add_dates_to_gce (self, gce):
        """Append the date entries such as birthday and anniversary to the
        specified ContactEntry"""

        dt = self.get_birthday()
        if dt:
            gce.birthday = gdata.contacts.data.Birthday(when=dt)

        dt = self.get_anniv()
        if dt:
            date = gdata.data.When(start=dt)
            ann  = gdata.contacts.data.Event(when=date, rel='anniversary')
            gce.event.append(ann)

    def _add_websites_to_gce (self, gce):
        """Append any Web URLs from the current contact to the specified
        ContatEntry object."""

        web_prim = self.get_web_prim()

        for web in self.get_web_home():
724 725
            if not web:
                continue
726 727 728 729 730 731
            prim = 'true' if web == web_prim else 'false'
            home = gdata.contacts.data.Website(href=web, primary=prim,
                                               rel='home-page')
            gce.website.append(home)

        for web in self.get_web_work():
732 733
            if not web:
                continue
734 735 736 737 738 739
            prim = 'true' if web == web_prim else 'false'
            work = gdata.contacts.data.Website(href=web, primary=prim,
                                               rel='work')
            gce.website.append(work)

    def _add_ims_to_gce (self, gce):
740
        im_prim = self.get_im_prim()
741
        for label, addr in self.get_im().iteritems():
742 743
            prim  = 'true' if im_prim == label else 'false'
            rel   = 'http://schemas.google.com/g/2005#other'
744
            proto = None
745

746 747
            if label in self.im_label_proto_map:
                proto = self.im_label_proto_map[label]
748 749
            else:
                proto = label
750

751
            im = gdata.data.Im(protocol=proto, rel=rel,
752
                               address=addr, primary=prim)
753
            gce.im.append(im)
754

755
    def _add_sync_tags_to_gce (self, gce):
756 757 758 759
        conf     = self.get_config()
        pname_re = conf.get_profile_name_re()
        label    = conf.make_sync_label(pname_re, self.get_dbid())

760 761 762 763
        ## These will be stored as extended properties. Note that if this
        ## routine keeps appending the sync_tags tot he user_defined_fields,
        ## with no regard for whether it already exists or not...
        for key, val in self.get_sync_tags().iteritems():
764 765 766 767
            # Skip any sync tag with GCIDs as values.
            if re.search(label, key):
                continue

768 769 770 771 772
            ud       = gdata.contacts.data.UserDefinedField()
            ud.key   = key
            ud.value = val
            gce.user_defined_field.append(ud)

773
    def _add_custom_props_to_gce (self, gce):
774 775 776 777 778 779
        c = self.get_created()
        if c:
            ud       = gdata.contacts.data.UserDefinedField()
            ud.key   = 'created'
            ud.value = c
            gce.user_defined_field.append(ud)
780

781
        for key, val in self.get_custom().iteritems():
782 783 784
            # We skip certain keys that have been processed already and
            # populated into other elements of the contact entry.
            if val and not key in ['gids']:
785 786 787 788 789
                ud       = gdata.contacts.data.UserDefinedField()
                ud.key   = key
                ud.value = val
                gce.user_defined_field.append(ud)
                
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    ##
    ## Temporarily placing keeping this stuff here while we start by cleaning
    ## up pimdb_gc.py
    ##

    # ## We will delete this guy very soon.

    # def add_olid_to_ce (self, ce, olid, replace=True):
    #     """Insert the Outlook EntryID for a contact as a  userdefined property
    #     in the Google ContactEntry and returned the modified ContactEntry.

    #     olid is the values as returned by GetProps - and, as a result a binary
    #     value. We base64 encode it before inserting into ContactEntry.

    #     If replace is True, then the first existing olid entry (if any) will
    #     be replaced with teh provided value. If it is False, then it is
    #     appended to existing list."""

    #     entryid_b64 = base64.b64encode(olid)
    #     ud       = gdata.contacts.data.UserDefinedField()
    #     ud.key   = 'olid'
    #     ud.value = entryid_b64

    #     if replace and len(ce.user_defined_field) > 0:
    #         ce.user_defined_field.pop()

    #     ce.user_defined_field.append(ud)

    #     return ce