Пример #1
0
    def add(self):
        """
        Add an address from From: field of a mail. This assumes a single mail file is supplied through stdin. . 
        """

        fromLine = ""
        for l in sys.stdin:
            if l.startswith("From: "):
                fromLine = l
                break
        if fromLine == "":
            print "Not a valid mail file!"
            sys.exit(2)
        #In a line like
        #From: John Doe <*****@*****.**>
        els = fromLine.split()
        #Drop "From: "
        del els[0]
        #get the last element as mail
        mailaddr = els[-1]
        if mailaddr.startswith("<"):
            mailaddr = mailaddr[1:]
        if mailaddr.endswith(">"):
            mailaddr = mailaddr[:-1]
        #and the rest as name
        name = " ".join(els[:-1])
        #save to contacts
        client = ContactsService()
        client.ClientLogin(self.username, self.password)
        new_contact = ContactEntry(title=atom.Title(text=name))
        new_contact.email.append(Email(address=mailaddr, primary='true'))
        contact_entry = client.CreateContact(new_contact)
        print contact_entry
Пример #2
0
 def save(self, user):
     contacts_service = ContactsService(self.cleaned_data['email'],
                                        self.cleaned_data['password'])
     contacts_service.ProgrammaticLogin()
     #based on django-friends importer module
     entries = []
     feed = contacts_service.GetContactsFeed()
     entries.extend(feed.entry)
     next_link = feed.GetNextLink()
     while next_link:
         feed = contacts_service.GetContactsFeed(uri=next_link.href)
         entries.extend(feed.entry)
         next_link = feed.GetNextLink()
     total = 0
     imported = 0
     for entry in entries:
         name = entry.title.text
         for e in entry.email:
             email = e.address
             total += 1
             try:
                 Contact.objects.get(user=user, email=email)
             except Contact.DoesNotExist:
                 Contact(user=user, name=name, email=email).save()
                 imported += 1
     return imported, total
Пример #3
0
 def clean(self):
     if 'email' in self.cleaned_data and 'password' in self.cleaned_data:
         contacts_service = ContactsService(self.cleaned_data['email'],
                                            self.cleaned_data['password'])
         try:
             contacts_service.ProgrammaticLogin()
         except gdata.service.BadAuthentication, msg:
             raise forms.ValidationError(
                 _(u'Incorrect Google account credentials'))
Пример #4
0
def authsub_login(request):
    if "token" in request.GET:
        request.session["authsub_token"] = request.GET["token"]
        return render_to_response("account/imported.html",
                                  RequestContext(request, {}))

    contacts_service = ContactsService()
    authsub_url = contacts_service.GenerateAuthSubURL(
        request.build_absolute_uri(), GOOGLE_CONTACTS_URI, False, True)

    return HttpResponseRedirect(authsub_url)
Пример #5
0
def import_google_contacts(request, redirect_to=None):
    """
    If no token in GET params then redirect to Google page for granting permissions.
    If token is available, save it into session and redirect to import_contacts view.
    """
    if redirect_to is None:
        redirect_to = reverse("friends_suggestions_import_contacts")
    if "token" in request.GET:
        request.session["google_authsub_token"] = request.GET["token"]
        return HttpResponseRedirect(redirect_to)
    authsub_url = ContactsService().GenerateAuthSubURL(
        next=request.build_absolute_uri(), scope="http://www.google.com/m8/feeds/", secure=False, session=True
    )
    return HttpResponseRedirect(authsub_url.to_string())
Пример #6
0
def import_google_contacts(request, redirect_to=None):
    """
    If no token in GET params then redirect to Google page for granting permissions.
    If token is available, save it into session and redirect to import_contacts view.
    """
    if redirect_to is None:
        redirect_to = reverse("friends_suggestions_import_contacts")
    if "token" in request.GET:
        request.session["google_authsub_token"] = request.GET["token"]
        return HttpResponseRedirect(redirect_to)
    authsub_url = ContactsService().GenerateAuthSubURL(next=request.build_absolute_uri(),
                                                       scope='http://www.google.com/m8/feeds/',
                                                       secure=False,
                                                       session=True)
    return HttpResponseRedirect(authsub_url.to_string())
Пример #7
0
    def fetch(self):
        """
        Actually go out on the wire and fetch the addressbook.

        """
        client = ContactsService()
        client.ClientLogin(self.username, self.password)
        query = ContactsQuery()
        query.max_results = self.max_results
        feed = client.GetContactsFeed(query.ToUri())
        for e in feed.entry:
            for i in e.email:
                if e.title.text:
                    self.addrbk[i.address] = e.title.text
                else:
                    self.addrbk[i.address] = i.address
Пример #8
0
    def refresh_creds(self, credentials, sleep):
        global gd_client
        time.sleep(sleep)
        credentials.refresh(httplib2.Http())

        now = datetime.utcnow()
        expires = credentials.token_expiry
        expires_seconds = (expires - now).seconds
        # print ("Expires %s from %s = %s" % (expires,now,expires_seconds) )
        if self.service == 'docs':
            gd_client = DocsService(email='default',
                                    additional_headers={
                                        'Authorization':
                                        'Bearer %s' % credentials.access_token
                                    })
        elif self.service == 'picasa':
            gd_client = PhotosService(email='default',
                                      additional_headers={
                                          'Authorization':
                                          'Bearer %s' %
                                          credentials.access_token
                                      })
        elif self.service == 'finance':
            gd_client = FinanceService(email='default',
                                       additional_headers={
                                           'Authorization':
                                           'Bearer %s' %
                                           credentials.access_token
                                       })
        elif self.service == 'calendar':
            gd_client = CalendarService(email='default',
                                        additional_headers={
                                            'Authorization':
                                            'Bearer %s' %
                                            credentials.access_token
                                        })
        elif self.service == 'contacts':
            gd_client = ContactsService(email='default',
                                        additional_headers={
                                            'Authorization':
                                            'Bearer %s' %
                                            credentials.access_token
                                        })
        elif self.service == 'youtube':
            gd_client = YouTubeService(email='default',
                                       additional_headers={
                                           'Authorization':
                                           'Bearer %s' %
                                           credentials.access_token
                                       })
        elif self.service == 'blogger':
            gd_client = BloggerService(email='default',
                                       additional_headers={
                                           'Authorization':
                                           'Bearer %s' %
                                           credentials.access_token
                                       })

        d = threading.Thread(name='refresh_creds',
                             target=self.refresh_creds,
                             args=(credentials, expires_seconds - 10))
        d.setDaemon(True)
        d.start()
        return gd_client
Пример #9
0
def _authsub_url(next):
    contacts_service = ContactsService()
    return contacts_service.GenerateAuthSubURL(next, GOOGLE_CONTACTS_URI, False, True)
Пример #10
0
def sync(info, entries, test=True):
    # setup client
    cli = ContactsService()
    cli.email = info['email']
    cli.password = info['password']
    cli.source = 'sas-contactsImport'
    cli.ProgrammaticLogin()

    # go through and find new groups
    groups = set("(Palm) " + c.category for c in entries)
    existing = [e.title.text for e in cli.GetGroupsFeed().entry]
    new_groups = groups.difference(existing)

    # create new groups
    for grp in new_groups:
        cli.CreateGroup(contacts.GroupEntry(title=atom.Title(text=grp)))

    # build group lookup dictionary
    feed = cli.GetGroupsFeed()
    groups_href = {}
    for entry in feed.entry:
        groups_href[str(entry.title.text)] = str(entry.id.text)

    # loop through contacts
    for contact in entries:
        if (test):
            contact.pprint()
            print ""
            continue

        # create basic info
        info = {}
        if contact.name:
            info['title'] = atom.Title(text=contact.name)

        # company info
        if contact.company or contact.title:
            org = contacts.Organization()
            org.org_name = contacts.OrgName(text=contact.company)
            org.org_title = contacts.OrgTitle(text=contact.title)
            info['organization'] = org

        # emails
        if contact.emails:
            info['email'] = [contacts.Email(address=s) for s in contact.emails]

        # phones
        if contact.phones:
            info['phone_number'] = [
                contacts.PhoneNumber(text=num.text, rel=num.rel)
                for num in contact.phones
            ]

        # addresses
        if contact.addresses:
            info['postal_address'] = [
                contacts.PostalAddress(text=addr.text, rel=addr.rel)
                for addr in contact.addresses
            ]

        # notes
        if contact.notes:
            info['content'] = atom.Content(text=contact.notes)

        # groups
        if contact.category:
            info['group_membership_info'] = [
                contacts.GroupMembershipInfo(
                    href=groups_href["(Palm) " + contact.category])
            ]

        # save contact
        try:
            entry = contacts.ContactEntry(**info)
            cli.CreateContact(entry)
        except Exception as ex:
            print "\nTrouble with contact:"
            contact.pprint()
            print "----------------------------"
            traceback.print_exc()
            sys.exit()
Пример #11
0
def sync(info, entries, test=True):
    # setup client
    cli = ContactsService()
    cli.email = info['email']
    cli.password = info['password']
    cli.source = 'sas-contactsImport'
    cli.ProgrammaticLogin()
    
    # go through and find new groups
    groups = set("(Palm) "+c.category for c in entries)
    existing = [ e.title.text for e in cli.GetGroupsFeed().entry ]
    new_groups = groups.difference(existing)
    
    # create new groups
    for grp in new_groups:
        cli.CreateGroup(contacts.GroupEntry(title=atom.Title(text=grp)))
        
    # build group lookup dictionary
    feed = cli.GetGroupsFeed()
    groups_href = {}
    for entry in feed.entry:
        groups_href[ str(entry.title.text) ] = str(entry.id.text)
    
    # loop through contacts
    for contact in entries:
        if(test):
            contact.pprint()
            print ""
            continue
    
        # create basic info
        info = {}
        if contact.name:
            info['title'] = atom.Title(text=contact.name)
        
        # company info
        if contact.company or contact.title:
            org = contacts.Organization()
            org.org_name = contacts.OrgName(text=contact.company)
            org.org_title = contacts.OrgTitle(text=contact.title)
            info['organization'] = org
            
        # emails
        if contact.emails:
            info['email'] = [ contacts.Email(address=s) for s in contact.emails ]
            
        # phones
        if contact.phones:
            info['phone_number'] = [ contacts.PhoneNumber(text=num.text, rel=num.rel) for num in contact.phones ]
            
        # addresses
        if contact.addresses:
            info['postal_address'] = [ contacts.PostalAddress(text=addr.text, rel=addr.rel) for addr in contact.addresses ]
        
        # notes
        if contact.notes:
            info['content'] = atom.Content(text=contact.notes)
            
        # groups
        if contact.category:
            info['group_membership_info'] = [ contacts.GroupMembershipInfo(href=groups_href["(Palm) "+contact.category]) ]

        # save contact
        try:
            entry = contacts.ContactEntry(**info)
            cli.CreateContact(entry)
        except Exception as ex:
            print "\nTrouble with contact:"
            contact.pprint()
            print "----------------------------"
            traceback.print_exc()
            sys.exit()