def load_contacts_with_twitter():
	contacts_with_twitter = []
	all_people = contacts.get_all_people()
	for person in all_people:
		view['currently_loading_info_label'].text = 'Loading image for {}'.format(person.full_name)
		social = person.social_profile
		if social:
			for service in social:
				if service[1]['service'] == 'twitter':
					twitter_username = service[1]['username']
					should_dismiss_view_because_no_account_error = False
					try:
						twitter_image = profile_picture_for_account(twitter_username)
					except LoadTwitterProfilePictureError as error:
						twitter_image = None
					except NoTwitterAccountSetUpError as error:
						twitter_image = None
						should_dismiss_view_because_no_account_error = True
						if console.alert(error.message, button1='open settings') == 1:
							webbrowser.open('app-settings://')
						view.close()
					finally:
						if should_dismiss_view_because_no_account_error == True:
							view.close()
					image = None
					result = addressBook_account_with_name(person.full_name)
					has_image = result.imageDataAvailable()
					if has_image == True:
						data = NSData.dataWithData_(result.imageData())
						image = UIImage.imageWithData_(data)
					contacts_with_twitter.append(Contact(person.full_name, twitter_username, has_image, image, twitter_image))
	return contacts_with_twitter
Example #2
0
def main():
	days_list = []
	people = contacts.get_all_people()
	now = datetime.now()
	for p in people:
		b = p.birthday
		if not b:
			continue
		next_birthday = datetime(now.year, b.month, b.day)
		if next_birthday < now:
			next_birthday = datetime(now.year + 1, b.month, b.day)
		days = (next_birthday - now).days
		days_list.append({'name': p.first_name, 'days': days})
	if not days_list:
		print('You don\'t have any birthdays in your address book.')
	else:
		days_list.sort(key=operator.itemgetter('days'))
		print('Upcoming Birthdays\n' + '=' * 40)
		for item in days_list:
			print('* %s in %i days' % (item['name'], item['days']))
Example #3
0
def main():
	days_list = []
	people = contacts.get_all_people()
	now = datetime.now()
	for p in people:
		b = p.birthday
		if not b:
			continue
		next_birthday = datetime(now.year, b.month, b.day)
		if next_birthday < now:
			next_birthday = datetime(now.year + 1, b.month, b.day)
		days = (next_birthday - now).days
		days_list.append({'name': p.first_name, 'days': days})
	if not days_list:
		print 'You don\'t have any birthdays in your address book.'
	else:
		days_list.sort(key=operator.itemgetter('days'))
		print 'Upcoming Birthdays\n' + '=' * 40
		for item in days_list:
			print '* %s in %i days' % (item['name'], item['days'])
def load_contacts_with_twitter():
    contacts_with_twitter = []
    all_people = contacts.get_all_people()
    for person in all_people:
        view[
            'currently_loading_info_label'].text = 'Loading image for {}'.format(
                person.full_name)
        social = person.social_profile
        if social:
            for service in social:
                if service[1]['service'] == 'twitter':
                    twitter_username = service[1]['username']
                    should_dismiss_view_because_no_account_error = False
                    try:
                        twitter_image = profile_picture_for_account(
                            twitter_username)
                    except LoadTwitterProfilePictureError as error:
                        twitter_image = None
                    except NoTwitterAccountSetUpError as error:
                        twitter_image = None
                        should_dismiss_view_because_no_account_error = True
                        if console.alert(error.message,
                                         button1='open settings') == 1:
                            webbrowser.open('app-settings://')
                        view.close()
                    finally:
                        if should_dismiss_view_because_no_account_error == True:
                            view.close()
                    image = None
                    result = addressBook_account_with_name(person.full_name)
                    has_image = result.imageDataAvailable()
                    if has_image == True:
                        data = NSData.dataWithData_(result.imageData())
                        image = UIImage.imageWithData_(data)
                    contacts_with_twitter.append(
                        Contact(person.full_name, twitter_username, has_image,
                                image, twitter_image))
    return contacts_with_twitter
    def scan_contacts(self):
        global limit_reached
        if not self.simulation:
            all_people = contacts.get_all_people()
        else:
            simul = namedtuple('simul', ['full_name', 'address', 'image_data'])
            all_people = [
                simul('Old Brueghel', [('home', {
                    'Street': 'Rue de la Regence 3',
                    'ZIP': '',
                    'City': 'Bruxelles',
                    'Country': 'Belgium'
                })], 'test:Lenna'),
                simul('Young Brueghel', [('home', {
                    'Street': 'Rue de la Regence 3',
                    'ZIP': '',
                    'City': 'Bruxelles',
                    'Country': 'Belgium'
                })], 'test:Peppers'),
                simul('Rene Magritte', [('home', {
                    'Street': 'Rue de la Regence 3',
                    'ZIP': '',
                    'City': 'Bruxelles',
                    'Country': 'Belgium'
                })], 'test:Sailboat'),
                simul('Auguste Renoir', [('home', {
                    'Street': 'Rue d Rivoli',
                    'ZIP': '',
                    'City': 'Paris',
                    'Country': 'France'
                })], 'test:Mandrill'),
                simul('Vincent Van Gogh', [('home', {
                    'Street': 'Museumplein 6',
                    'ZIP': '',
                    'City': 'Amsterdam',
                    'Country': 'Holland'
                })], 'test:Boat'),
                simul('Albrecht Durer', [('home', {
                    'Street': 'Pariser Platz 4',
                    'ZIP': '',
                    'City': 'Berlin',
                    'Country': 'Germany'
                })], 'test:Bridge'),
                simul('example without photo', [('home', {
                    'Street': '',
                    'ZIP': '',
                    'City': 'Prague',
                    'Country': 'Tchekie'
                })], None),
                simul('example without address', [('home', {
                    'Street': '',
                    'ZIP': '',
                    'City': '',
                    'Country': ''
                })], None)
            ]
        self.ntot = len(all_people)
        self['msg_label'].hidden = False
        self['msg_label'].text = 'Scan Contacts'
        self['msg_label'].bring_to_front()
        n = 0
        for person in all_people:
            n = n + 1
            self.callback(n)
            #if n==3:		# for quicker test
            #	break			# for quicker test
            ads = person.address
            #[('_$!<Home>!$_', {'Street': 'xxxx', 'ZIP': 'yyy', 'City': 'zzz', 'CountryCode': 'uu', 'State': '', 'Country': 'vv'})]
            try:
                for ad in ads:  # if multiple addresses
                    dic = ad[1]  # ('name',dict)
                    #print(dic)
                    street = dic['Street']
                    b = street.lower().find('bte')
                    if b >= 0:
                        street = street[:b]
                    ad_string = street + ',' + dic['ZIP'] + ' ' + dic[
                        'City'] + ',' + dic['Country']
                    name = person.full_name
                    if person.image_data == None:
                        contacts_photos[name] = None
                    else:
                        # store reduced photo to win memory
                        if not self.simulation:
                            img = ui.Image.from_data(person.image_data)
                        else:
                            img = ui.Image.named(person.image_data)
                        wh = img.size
                        # normal photo
                        h = map_pin_size
                        w = int(h * wh[0] / wh[1])
                        with ui.ImageContext(w, h) as ctx:
                            img.draw(0, 0, w, h)
                            img = ctx.get_image()
                        contacts_photos[name] = img
                    if ad_string.replace(',', '').strip() == '':
                        # no address
                        self.not_yet_localized[name] = ('', 0)
                        continue
                    gps = geocodeAddressString(ad_string)
                    if gps == (None, None):
                        self.not_yet_localized[name] = (ad_string, 1)
                    else:
                        k = (gps[0], gps[1])
                        if k not in self.points:
                            self.points[k] = (name, ad_string, None)
                        else:
                            old_name, old_ad_string, annot = self.points[k]
                            join_photos(old_name, name)
                            # no del contacts_photos[old_name] because could be used
                            # for other gps if a contact has several addresses
                            new_name = join_names(old_name, name)
                            self.points[k] = (new_name, old_ad_string, annot)
            except Exception as e:
                print(str(e))
                gps = (None, None)
            self.contacts.append([person, gps])
        self.callback(self.ntot)
        ui.delay(self.disp, 0.1)

        if self.not_yet_localized != {}:
            self.right_button_items[1].title = str(len(
                self.not_yet_localized)) + ' not (yet) localized'
            self.right_button_items[1].tint_color = 'green'
            self.run = True
            server_thread = my_thread()
            server_thread.start()
Example #6
0
def load_upcoming_birthdays(pretty_output=True, leading_zeros=False):

    all_contacts = contacts.get_all_people()
    all_birthdays = []
    all_output = []
    number_of_contacts_without_birthday = 0
    now = datetime.now()

    for person in all_contacts:
        if person.kind == 0:  #0: Person, 1: company
            if person.birthday:
                birthday = person.birthday
                next_birthday = datetime(now.year, birthday.month,
                                         birthday.day)
                if next_birthday < now:
                    next_birthday = datetime(now.year + 1, birthday.month,
                                             birthday.day)
                number_of_days_to_next_birthday = (next_birthday - now).days
                all_birthdays.append({
                    'first_name': person.first_name,
                    'last_name': person.last_name,
                    'days': number_of_days_to_next_birthday,
                    'date': birthday
                })
            else:  # no birthday set
                number_of_contacts_without_birthday += 1

    all_birthdays.sort(key=operator.itemgetter('days'))

    # add the first part (* 012 days to Renate)
    for birthday in all_birthdays:
        if pretty_output:
            if leading_zeros:
                days_formatted = '%.3i' % birthday[
                    'days']  # old format (leading 0s)
            else:
                days_as_string = '{0}'.format(birthday['days'])
                days_formatted = ' ' * (
                    3 - len(days_as_string)) + '{0}'.format(birthday['days'])
        else:
            days_formatted = '{0}'.format(birthday['days'])

        days_text_string = ''
        if not birthday['days'] == 1:
            days_text_string = 'days'
        else:
            days_text_string = 'day '
        output = '* {0} {1} to {2}'.format(days_formatted, days_text_string,
                                           birthday['first_name'])
        all_output.append(output)

    length_first_name = 0
    for output_string in all_output:
        first_name = output_string.split()[4]
        if len(first_name) > length_first_name:
            length_first_name = len(first_name)

    # add the second part (Altinger)
    for birthday in all_birthdays:
        index = all_birthdays.index(birthday)
        _length_shorter = length_first_name + 1 - len(birthday['first_name'])
        new_output = ''
        if pretty_output:
            new_output = all_output[index] + ' ' * _length_shorter + birthday[
                'last_name']
        else:
            new_output = all_output[index] + ' ' + birthday['last_name']
        all_output[index] = new_output

    #
    # add the birthdate at the end
    #
    length_last_name = 0
    for output_string in all_output:
        last_name = output_string.split()[5]
        if len(last_name) > length_last_name:
            length_last_name = len(last_name)

    # add the date
    for birthday in all_birthdays:
        index = all_birthdays.index(birthday)
        _length_shorter = length_last_name + 1 - len(birthday['last_name'])
        actual_birthday = birthday['date']
        date_format = ''
        trailing_text = ''
        if actual_birthday.year < 1900:
            actual_birthday = actual_birthday.replace(2015)
            date_format = '%d. %b'
            trailing_text = '    *'
        else:
            date_format = '%d. %b %y'
            trailing_text = ' *'
        new_output = ''
        if pretty_output:
            new_output = all_output[
                index] + ' ' * _length_shorter + '({0}){1}'.format(
                    actual_birthday.strftime(date_format), trailing_text)
        else:
            new_output = all_output[index] + ' ' + '({0}){1}'.format(
                actual_birthday.strftime(date_format), trailing_text)
        all_output[index] = new_output

    longest_row = 0
    for output in all_output:
        output_length = len(output)
        if output_length > longest_row:
            longest_row = output_length

    console.clear()

    print 'Next Birthdays from your Address Book'
    print '=' * longest_row

    for output in all_output:
        print output

    #print '='*longest_row

    print
    print '{0} of {1} contacts have no birthday set'.format(
        number_of_contacts_without_birthday, len(all_contacts))
# https://forum.omz-software.com/topic/2496/add-email-to-contacts/2

import contacts
people = contacts.get_all_people()
print(people[0].full_name)

emails = people[0].email
emails.append(('$!<Other>!$', '*****@*****.**'))
people[0].email = emails

contacts.save()

Example #8
0
            k: getattr(obj, k)
            for k in dir(obj) if not k.startswith('_') and k not in filter_list
            and not callable(k)
        }
        np = namedtuple('DataItem', d.keys())(**d)
        tup_list.append(np)

    return tup_list


def objlist_to_named_tp(people, filter_list=None):
    filter_list = filter_list or []  # avoid default mutable arguements
    # See: http://docs.python-guide.org/en/latest/writing/gotchas
    fields = (field for field in dir(people[0]) if not field.startswith('_')
              and field not in filter_list and not callable(field))
    np = namedtuple('DataItem', fields)
    return [
        np(**{field: getattr(person, field)
              for field in np._fields}) for person in people
    ]


if __name__ == '__main__':

    lst = objlist_to_named_tp(contacts.get_all_people(), filter_list='vcard')
    p = lst[0]
    print(p.first_name, p.last_name, p.birthday)
    print('records=', len(lst))
    print('*' * 50)
    #print(p._source)
Example #9
0
"""
Prints a list of birthdays in your address book (in days from now).

NOTE: This script requires access to your contacts in order to work.
"""

import contacts, datetime  # noqa


def days_until_next(date):
    now = datetime.datetime.now()
    inc = int(datetime.datetime(now.year, date.month, date.day) < now)
    return (datetime.datetime(now.year + inc, date.month, date.day) - now).days


text = "\n".join("* {p.first_name} in {days} days".format(**x) for x in sorted(
    ({
        "p": p,
        "days": days_until_next(p.birthday)
    } for p in contacts.get_all_people() if p.birthday),
    key=lambda x: x["days"],
))  # noqa

print("Upcoming Birthdays:\n{}\n{}".format("=" * 19, text) if text else
      "You don't have any birthdays in your address book.")  # noqa
import contacts
from datetime import datetime
import operator

days_list = []
people = contacts.get_all_people()
now = datetime.now()
for p in people:
    b = p.birthday
    if b:
        next_birthday = datetime(now.year, b.month, b.day)
        if next_birthday < now:
            next_birthday = datetime(now.year + 1, b.month, b.day)
        days = (next_birthday - now).days
        days_list.append({"name": p.full_name, "days": days})

if not days_list:
    print "You don't have any birthdays in your address book."
else:
    days_list.sort(key=operator.itemgetter("days"))
    print "Upcoming Birthdays"
    print "=" * 40
    for item in days_list:
        print "* %s in %i days" % (item["name"], item["days"])
for num in range(280, 290):
    print contacts.get_person(num).name
# The above line works as it calls the contacts list using the id, iterated as num, which
# allows the fullname to be call based on the id. Saves a lot of pfaffing with lists.
Example #11
0
# https://gist.github.com/rjames86/79f857f427599f6e145c
import contacts
import sys, os
import console

sys.path += [os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib')]
from dropboxlogin import get_client
from datetime import datetime

# Update this path here for the backup
# location in your Dropbox account.
BACKUP_PATH = '/Backups/Contacts'

TODAY = datetime.today().strftime('%Y-%m-%d')

dropbox_client = get_client()

VCARD = "".join(person.vcard for person in contacts.get_all_people())

console.clear()

dropbox_client.put_file(BACKUP_PATH + '/contacts {}.vcf'.format(TODAY), VCARD)
print 'Backup complete!'
Example #12
0
import console, contacts, feedparser, sys, urllib, webbrowser
console.clear()
outp = [
    '**{}**\n{}'.format(p.full_name, p.note)
    for p in contacts.get_all_people() if p.note
]
if not outp:
    sys.exit('No output!!')
dayone_entry = 'Address Book Notes\n{}\n\n#people'.format('\n\n'.join(outp))
print(dayone_entry)
if not raw_input('-- Press enter to import'):
    dayone_entry = urllib.quote(dayone_entry.encode('utf-8'))
    webbrowser.open('dayone://post?entry=' + dayone_entry)
	def scan_contacts(self):	
		global limit_reached	
		if not self.simulation:
			all_people = contacts.get_all_people()
		else:
			simul = namedtuple('simul', ['full_name','address','image_data'])
			all_people = [
				simul('Old Brueghel',[('home',{'Street':'Rue de la Regence 3', 'ZIP':'', 'City':'Bruxelles', 'Country':'Belgium'})], 'test:Lenna'),
				simul('Young Brueghel',[('home',{'Street':'Rue de la Regence 3', 'ZIP':'', 'City':'Bruxelles', 'Country':'Belgium'})], 'test:Peppers'),
				simul('Rene Magritte',[('home',{'Street':'Rue de la Regence 3', 'ZIP':'', 'City':'Bruxelles', 'Country':'Belgium'})], 'test:Sailboat'),
				simul('Auguste Renoir',[('home',{'Street':'Rue d Rivoli', 'ZIP':'','City':'Paris','Country':'France'})], 'test:Mandrill'),
				simul('Vincent Van Gogh',[('home',{'Street':'Museumplein 6', 'ZIP':'', 'City':'Amsterdam', 'Country':'Holland'})], 'test:Boat'),
				simul('Albrecht Durer',[('home',{'Street':'Pariser Platz 4', 'ZIP':'', 'City':'Berlin', 'Country':'Germany'})], 'test:Bridge'),
				simul('example without photo',[('home',{'Street':'', 'ZIP':'', 'City':'Prague', 'Country':'Tchekie'})], None),
				simul('example without address',[('home',{'Street':'', 'ZIP':'', 'City':'', 'Country':''})], None)
				]
		self.ntot = len(all_people)
		self['msg_label'].hidden = False
		self['msg_label'].text = 'Scan Contacts'
		self['msg_label'].bring_to_front()	
		n = 0
		for person in all_people:
			n = n + 1
			self.callback(n)
			#if n==3:		# for quicker test
			#	break			# for quicker test
			ads = person.address
			#[('_$!<Home>!$_', {'Street': 'xxxx', 'ZIP': 'yyy', 'City': 'zzz', 'CountryCode': 'uu', 'State': '', 'Country': 'vv'})]
			try:
				for ad in ads:	# if multiple addresses
					dic = ad[1]		# ('name',dict)
					#print(dic)
					street = dic['Street']
					b = street.lower().find('bte')
					if b >= 0:
						street = street[:b]
					ad_string = street + ',' + dic['ZIP'] + ' ' + dic['City'] + ',' + dic['Country']
					name = person.full_name
					if person.image_data == None:
						contacts_photos[name] = None
					else:
						# store reduced photo to win memory 
						if not self.simulation:
							img = ui.Image.from_data(person.image_data)
						else:
							img = ui.Image.named(person.image_data)
						wh = img.size
						# normal photo 
						h = map_pin_size
						w = int(h * wh[0] / wh[1])
						with ui.ImageContext(w,h) as ctx:
							img.draw(0,0,w,h)
							img = ctx.get_image()				
						contacts_photos[name] = img
					if ad_string.replace(',','').strip() == '':
						# no address
						self.not_yet_localized[name] = ('',0)
						continue
					gps = geocodeAddressString(ad_string)			
					if gps == (None,None):
						self.not_yet_localized[name] = (ad_string,1)
					else:
						k = (gps[0],gps[1])
						if k not in self.points:
							self.points[k] = (name,ad_string,None)
						else:
							old_name,old_ad_string,annot = self.points[k]
							join_photos(old_name,name)
							# no del contacts_photos[old_name] because could be used
							# for other gps if a contact has several addresses
							new_name = join_names(old_name,name)
							self.points[k] = (new_name,old_ad_string,annot)
			except Exception as e:
				print(str(e))
				gps = (None,None)
			self.contacts.append([person,gps])
		self.callback(self.ntot)
		ui.delay(self.disp,0.1)

		if self.not_yet_localized != {}:	
			self.right_button_items[1].title = str(len(self.not_yet_localized)) + ' not (yet) localized'
			self.right_button_items[1].tint_color = 'green'
			self.run = True
			server_thread = my_thread()
			server_thread.start()
'''
Prints a list of birthdays in your address book (in days from now).

NOTE: This script requires access to your contacts in order to work.
'''

import contacts, datetime

def days_until_next(date):
    now = datetime.datetime.now()
    inc = int(datetime.datetime(now.year, date.month, date.day) < now)
    return (datetime.datetime(now.year + inc, date.month, date.day) - now).days

text = '\n'.join('* {p.first_name} in {days} days'.format(**x) for x
    in sorted(({'p': p, 'days': days_until_next(p.birthday)} for p
    in contacts.get_all_people() if p.birthday), key=lambda x: x['days']))

print('Upcoming Birthdays:\n{}\n{}'.format('=' * 19, text) if text else
    "You don't have any birthdays in your address book.")
Example #15
0
import console, contacts, feedparser, sys, urllib, webbrowser
console.clear()
outp = ['**{}**\n{}'.format(p.full_name, p.note)
           for p in contacts.get_all_people() if p.note]
if not outp:
    sys.exit('No output!!')
dayone_entry = 'Address Book Notes\n{}\n\n#people'.format('\n\n'.join(outp))
print(dayone_entry)
if not raw_input('-- Press enter to import'):
    dayone_entry = urllib.quote(dayone_entry.encode('utf-8'))
    webbrowser.open('dayone://post?entry=' + dayone_entry)