Exemplo n.º 1
0
    def __init__(self, address_book, filename = None):
        self.vcard = None
        self.address_book = address_book
        self.filename = filename
        self.old_vobject_version = False

        # at the moment khard must support two different behavior of the vobject module
        # the versions < 0.8.2 are still widely in use and expect unicode strings for non-ascii characters
        # all newer versions use utf-8 encoded strings directly
        # so we must determine, which version is installed
        try:
            # try to compare the version numbers
            if parse_version(get_distribution("vobject").version) < parse_version("0.8.2"):
                self.old_vobject_version = True
        except Exception as e:
            # if something goes wrong during vobject version comparison, try to serialize a
            # minimal vcard object with umlauts
            # if that fails, khard still uses a vobject version < 0.8.2
            v = vobject.vCard()
            o = v.add("fn")
            o.value = "Markus Schröder"
            o = v.add("n")
            o.value = vobject.vcard.Name(family="Schröder", given="Markus")
            try:
                v.serialize()
            except UnicodeDecodeError as e:
                self.old_vobject_version = True

        # load vcard
        if self.filename is None:
            # create new vcard object
            self.vcard = vobject.vCard()
            # uid
            choice = string.ascii_uppercase + string.digits
            uid_obj = self.vcard.add('uid')
            uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
            # use uid for vcard filename
            self.filename = os.path.join(address_book.get_path(),
                    self.vcard.uid.value + ".vcf")

        else:
            # create vcard from .vcf file
            try:
                file = open(self.filename, "r")
                contents = file.read()
                file.close()
            except IOError as e:
                raise
            # create vcard object
            try:
                self.vcard = vobject.readOne(contents)
            except vobject.base.ParseError as e:
                # if creation fails, try to repair vcard contents
                try:
                    self.vcard = vobject.readOne(
                            self.filter_invalid_tags(contents))
                    self.write_to_file(overwrite=True)
                except vobject.base.ParseError as e:
                    raise
Exemplo n.º 2
0
def ghostbuster_to_vcard(gbr):
    """Convert a GhostbusterRequest object into a vCard object."""

    import vobject

    vcard = vobject.vCard()
    vcard.add('N').value = vobject.vcard.Name(family=gbr.family_name,
                                              given=gbr.given_name)

    adr_fields = [
        'box', 'extended', 'street', 'city', 'region', 'code', 'country'
    ]
    adr_dict = dict((f, getattr(gbr, f, '')) for f in adr_fields)
    if any(adr_dict.itervalues()):
        vcard.add('ADR').value = vobject.vcard.Address(**adr_dict)

    # mapping from vCard type to Ghostbuster model field
    # the ORG type is a sequence of organization unit names, so
    # transform the org name into a tuple before stuffing into the
    # vCard object
    attrs = [('FN', 'full_name', None), ('TEL', 'telephone', None),
             ('ORG', 'organization', lambda x: (x, )),
             ('EMAIL', 'email_address', None)]
    for vtype, field, transform in attrs:
        v = getattr(gbr, field)
        if v:
            vcard.add(vtype).value = transform(v) if transform else v
    return vcard.serialize()
Exemplo n.º 3
0
def ghostbuster_to_vcard(gbr):
    """Convert a GhostbusterRequest object into a vCard object."""

    import vobject

    vcard = vobject.vCard()
    vcard.add('N').value = vobject.vcard.Name(family=gbr.family_name,
                                              given=gbr.given_name)

    adr_fields = ['box', 'extended', 'street', 'city', 'region', 'code',
                  'country']
    adr_dict = dict((f, getattr(gbr, f, '')) for f in adr_fields)
    if any(adr_dict.itervalues()):
        vcard.add('ADR').value = vobject.vcard.Address(**adr_dict)

    # mapping from vCard type to Ghostbuster model field
    # the ORG type is a sequence of organization unit names, so
    # transform the org name into a tuple before stuffing into the
    # vCard object
    attrs = [('FN',    'full_name',      None),
             ('TEL',   'telephone',      None),
             ('ORG',   'organization',   lambda x: (x,)),
             ('EMAIL', 'email_address',  None)]
    for vtype, field, transform in attrs:
        v = getattr(gbr, field)
        if v:
            vcard.add(vtype).value = transform(v) if transform else v
    return vcard.serialize()
Exemplo n.º 4
0
def MergeVcards(vcard1, vcard2):
    """Create a new vCard and populate it."""
    new_vcard = vobject.vCard()
    vcard1_fields = set(vcard1.contents.keys())
    vcard2_fields = set(vcard2.contents.keys())
    mutual_fields = vcard1_fields.intersection(vcard2_fields)
    logger.debug('Potentially conflicting fields: {}'.format(mutual_fields))
    for field in mutual_fields:
        val1 = vcard1.contents.get(field)
        val2 = vcard2.contents.get(field)
        new_values = []
        if not VcardFieldsEqual(val1, val2):
            # we have a conflict, if a list maybe append otherwise prompt user
            if field not in MERGEABLE_FIELDS:
                context_str = GetVcardContextString(vcard1, vcard2)
                new_values.extend(
                    SelectFieldPrompt(field, context_str, val1, val2))
            else:
                new_values.extend(VcardMergeListFields(val1, val2))
        else:
            new_values.extend(val1)

        logger.debug('Merged values for field {}: {}'.format(
            field.upper(), u(str(new_values))))
        new_vcard = SetVcardField(new_vcard, field, new_values)

    new_vcard = CopyVcardFields(new_vcard, vcard1,
                                vcard1_fields - vcard2_fields)
    new_vcard = CopyVcardFields(new_vcard, vcard2,
                                vcard2_fields - vcard1_fields)

    return new_vcard
Exemplo n.º 5
0
def vcard(name,lista):
	count = 1
	c = 0
	separado = zip(*[iter(list(lista))]*200)
	partes = len(list(lista))/150
	print partes + 1
	separado = split_list(list(lista),partes+1)
	jj=""
	for sep in separado:	
		print count
		j = vobject.vCard()
		o = j.add('fn')
		o.value = "Lista Negra IGNORAR" + str(count)

		o = j.add('n')
		o.value = vobject.vcard.Name( family='IGNORAR', given='Lista Negra' + str(count) )

		for i,num in enumerate(sep):
			c+=1
			
			o = j.add('tel')
			o.type_param = "cell"
			if isinstance(num, dict):
				o.value = "+"+num['numero']
			else:
				o.value = "+"+num.numero
		count += 1
		jj += j.serialize()
		print "vCard" + str(count)+ " " + str(c) + " numeros"
		c=0


	return(jj)
Exemplo n.º 6
0
def export_vcf(filename):
    """ exports contacts to VCF file
	"""

    # append file extension if not included
    if filename[-4:] != ".vcf":
        filename += ".vcf"

    try:
        with open(filename, "a", newline='') as vcf_file:
            people = db.getAllPeople(conn)
            for person in people:
                new_person = vobject.vCard()
                new_person.add('n')
                new_person.n.value = vobject.vcard.Name(family=person[1],
                                                        given=person[0])
                new_person.add('fn')
                new_person.fn.value = person[0] + " " + person[1]
                new_person.add('tel')
                new_person.tel.value = person[2]
                new_person.add('org')
                new_person.org.value = [person[3]]
                vcf_file.write(new_person.serialize())

    except Exception as e:
        print("Error processing VCF file: {}".format(e))
        return None
    else:
        print("Successfully exported to VCF")
        return None
Exemplo n.º 7
0
def createRawVcard(c):
    """
    Converts internal contact entry to VObject format
    """
    j = vobject.vCard()
    _createNameAttribute(c, j)
    
    if c.attributes['firstname']:
        if c.attributes['lastname']:
            fn = c.attributes['firstname'] + ' ' +  c.attributes['lastname']
        else:
            fn = c.attributes['firstname']
    else:
        fn = c.attributes['lastname']
    _createRawAttribute(c,  j,  'fn',  "'''" + fn + "'''")
    _createRawAttribute(c,  j,  'title',  "c.attributes['title']")

    _createRawAttribute(c,  j,  'email',  "c.attributes['email']",  [['type_param',  "'INTERNET'"]])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_HOME[0])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_WORK[0])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_MOBILE[0])
    _createPhoneAttribute(c, j,  VCF_PHONETYPE_FAX[0])
    
    _createAddressAttribute(c,  j, VCF_ADDRESSTYPE_HOME[0])
    _createAddressAttribute(c,  j, VCF_ADDRESSTYPE_WORK[0])
    _createBusinessDetails(c,  j)
    return j
Exemplo n.º 8
0
    def __init__(self, address_book, filename = None):
        self.vcard = None
        self.address_book = address_book
        self.filename = filename

        if self.filename is None:
            # create new vcard object
            self.vcard = vobject.vCard()
            # uid
            choice = string.ascii_uppercase + string.digits
            uid_obj = self.vcard.add('uid')
            uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
            # use uid for vcard filename
            self.filename = os.path.join(address_book.get_path(),
                    self.vcard.uid.value + ".vcf")

        else:
            # create vcard from .vcf file
            try:
                file = open(self.filename, "r")
                contents = file.read()
                file.close()
            except IOError as e:
                raise
            # create vcard object
            try:
                self.vcard = vobject.readOne(contents)
            except vobject.base.ParseError as e:
                # if creation fails, try to repair vcard contents
                try:
                    self.vcard = vobject.readOne(
                            self.filter_invalid_tags(contents))
                    self.write_to_file(overwrite=True)
                except vobject.base.ParseError as e:
                    raise
Exemplo n.º 9
0
def vcard(request, id):
	import vobject
	qq = Contact.objects.get(id=id)
	card = vobject.vCard()
	card.add('n')
	card.n.value=vobject.vcard.Name(family=qq.surname, given=qq.name)
	card.add('fn')
	card.fn.value="%s %s" % (qq.name, qq.surname,)
	ei = 0
	for e in qq.emails.all():
		card.add('email')
		card.email_list[ei].value=e.address
		card.email_list[ei].type_param ='INTERNET'
	pi = 0
	for p in qq.phones.all():
		card.add('tel')	
		card.tel_list[pi].type_param=str(p.phone_type)
		card.tel_list[pi].value=p.number
		pi = pi + 1
	card.add('org')
	card.org.value = [str(qq.company)]
	card.add('title')
	card.title.value = str(qq.role)

	return HttpResponse(card.serialize())#, content_type = "text/vcard")
Exemplo n.º 10
0
def api_vcf_contacts(request):
    members = Member.objects.exclude(
        deactivation_date__lte=timezone.now().date())
    cards = []
    for member in members:
        card = vobject.vCard()

        attr = card.add('n')
        attr.value = vobject.vcard.Name(family=member.last_name,
                                        given=member.first_name)

        attr = card.add('fn')
        attr.value = member.get_name()

        attr = card.add('email')
        attr.value = member.email

        if member.mobile_phone:
            attr = card.add('tel')
            attr.value = member.mobile_phone
            attr.type_param = 'cell'

        if member.phone:
            attr = card.add('tel')
            attr.value = member.phone
            attr.type_param = 'home'

        attr = card.add('org')
        attr.value = ["meh als gmües"]
        cards.append(card)

    response = HttpResponse(content_type='text/x-vcard')
    response['Content-Disposition'] = 'attachment; filename="members.vcf"'
    response.write("".join([card.serialize() for card in cards]))
    return response
Exemplo n.º 11
0
def generate_vcard(obj):
    """
    Generates a vCard from the object attributes.
    """
    # vCard
    card = vobject.vCard()
    # Name
    card.add('n')
    card.n.value = vobject.vcard.Name(
        family=(obj.lastname or ''),
        given=(obj.firstname or ''),
    )
    # Fullname
    card.add('fn')
    card.fn.value = (obj.title or '')
    # E-Mail
    card.add('email')
    card.email.value = (obj.email or '')
    # Company
    card.add('org')
    account = (obj.account or '')
    if account:
        account = account.to_object.Title()
    card.org.value = [account]
    # Account-Type
    card.add('title')
    card.title.value = (obj.type.title() or '')
    # UID
    card.add('uid')
    card.uid.value = (obj.UID() or '')
    # Phone
    card.add('tel')
    card.tel.value = (obj.phone or '')
    # Serialize
    return card.serialize()
Exemplo n.º 12
0
def vcard(u):
    c = vobject.vCard()
    c.add('n')
    ln = ' '.join(reversed(map(lambda x: x.strip(),
                               u.last_name.split(',', 1))))
    c.n.value = vobject.vcard.Name(ln,
                                   given=u.first_name)
    c.add('fn')
    c.fn.value = u.full_name()
    l = c.add('email', 'kn')
    l.value = u.primary_email
    l.type_paramlist = ['INTERNET']
    c.add('X-ABLabel', 'kn').value = 'kn'
    if u.telephone is not None:
        c.add('tel', 'kn')
        c.tel.value = u.telephone
        c.tel.type_param = 'CELL'
    if (u.addr_street is not None and
            u.addr_city is not None and
            u.addr_number is not None and
            u.addr_zipCode is not None):
        l = c.add('adr', 'kn')
        l.value = vobject.vcard.Address(' '.join((u.addr_street,
                                                  u.addr_number)),
                                        u.addr_city,
                                        '',
                                        u.addr_zipCode,
                                        'Nederland')
        c.add('x-abadr', 'kn').value = 'nl'
    return c.serialize()
Exemplo n.º 13
0
def create(contact):
    vcard = vobject.vCard()
    vcard.add('n').value = vobject.vcard.Name(family=contact.surename or '',
                                              given=contact.forename or '')
    if (contact.is_company):
        vcard.add('fn').value = contact.company
        vcard.add('X-ABShowAs').value = "COMPANY"
    else:
        vcard.add('fn').value = "{} {}".format(contact.forename,
                                               contact.surename)
    vcard.add('nickname').value = contact.nickname or ''
    vcard.add('org').value = [contact.company or '']
    vcard.add('note').value = contact.note or ''
    if (contact.addresses):
        for address in contact.addresses:
            adr = vcard.add('adr')
            adr.value = vobject.vcard.Address(street=address.street,
                                              city=address.city,
                                              code=address.zipcode,
                                              country=address.country,
                                              region=address.state)
            adr.type_param = address.adr_type
    if (contact.emails):
        for email in contact.emails:
            vemail = vcard.add('email')
            vemail.value = email.address
            vemail.type_param = email.email_type
    if (contact.tels):
        for tel in contact.tels:
            vtel = vcard.add('tel')
            vtel.value = tel.number
            vtel.type_param = tel.tel_type
    if (contact.bday):
        vcard.add('bday').value = contact.bday
    return vcard.serialize()
Exemplo n.º 14
0
def genVCardFromJson(infile, outfile):
    outf = open(outfile,'w')
    with open(infile,'r') as inf:
        comps = json.load(inf)
        for comp in comps:
            v = vobject.vCard()
            v.add('n')
            v.n.value = vobject.vcard.Name(family = " ".join(comp['businessName']))
            v.add('fn')
            v.fn.value =" ".join(comp["businessName"])
            for c in comp:
                if c not in requiredVC:
                    lst = comp[c]
                    if type(lst)==type([]):
                        for i in range(len(lst)):

                            if i ==0:
                                t = v.add(c)
                            else:
                                t=v.add(c+str(i))
                            t.value = "".join(comp[c][i])
                    else:
                        t=v.add(c)
                        t.value = "".join(comp[c])
            outf.write(v.serialize())
Exemplo n.º 15
0
def vcard(name, lista):
    count = 1
    c = 0
    separado = zip(*[iter(list(lista))] * 200)
    partes = len(list(lista)) / 150
    print partes + 1
    separado = split_list(list(lista), partes + 1)
    jj = ""
    for sep in separado:
        print count
        j = vobject.vCard()
        o = j.add('fn')
        o.value = "Lista Negra IGNORAR" + str(count)

        o = j.add('n')
        o.value = vobject.vcard.Name(family='IGNORAR',
                                     given='Lista Negra' + str(count))

        for i, num in enumerate(sep):
            c += 1

            o = j.add('tel')
            o.type_param = "cell"
            if isinstance(num, dict):
                o.value = "+" + num['numero']
            else:
                o.value = "+" + num.numero
        count += 1
        jj += j.serialize()
        print "vCard" + str(count) + " " + str(c) + " numeros"
        c = 0

    return (jj)
Exemplo n.º 16
0
 def __init__(self, addressbook_name, addressbook_path, filename=""):
     self.addressbook_name = addressbook_name
     if filename == "":
         # create new vcard
         self.vcard = vobject.vCard()
         choice = string.ascii_uppercase + string.digits
         uid_obj = self.vcard.add('uid')
         uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
         self.vcard_full_filename = os.path.join(addressbook_path,
                 self.vcard.uid.value + ".vcf")
     else:
         # create vcard from file
         self.vcard_full_filename = filename
         # open .vcf file
         try:
             file = open(filename, "r")
             contents = file.read()
             file.close()
         except IOError as e:
             raise CarddavObject.VCardParseError(e)
         # create vcard object
         try:
             self.vcard = vobject.readOne(contents)
         except vobject.base.ParseError as e:
             # if creation fails, try to repair vcard contents
             try:
                 self.vcard = vobject.readOne(
                         self.filter_invalid_tags(contents))
                 self.write_to_file(overwrite=True)
             except vobject.base.ParseError as e:
                 raise CarddavObject.VCardParseError(e)
Exemplo n.º 17
0
def export_contacts_from_db():
    users = IBSUserInfo.objects.all()
    for u in users:
        user_id = u.ibs_uid
        try:
            print '[INFO] Get User Data For : %s' % user_id
            # user_name = u.user.username
            mobile = u.user.fk_user_profile_user.get().mobile
            holder = vobject.vCard()
            o = holder.add('fn')
            o.value = str(user_id)
            o = holder.add('n')
            o.value = vobject.vcard.Name(family=str(user_id))
            o = holder.add('tel')
            o.type_param = 'cell'
            if not mobile:
                continue
            if len(mobile) < 3:
                continue
            o.value = unicode(mobile)
            f = open(settings.EXPORT_DATA_DIR + '/%s.vcf' % user_id, 'w')
            f.write(holder.serialize())
            print '[INFO] Contact Wrote For %s' % user_id
        except Exception as e:
            print '[ERROR] ' + e.message
            continue
Exemplo n.º 18
0
def vcard_factory():
    item = arr[0]
    v = vobject.vCard()
    v.add('fn').value = item.pop(1)
    v.add('phone').value = item.pop(2)
    # v.add('email').value = '*****@*****.**'
    print(v.serialize())
Exemplo n.º 19
0
def create_vcard(last_name=None,
                 first_name=None,
                 mobile_number=None,
                 org=None,
                 email=None):
    j = vobject.vCard()

    if first_name and last_name:
        j.add('n')
        j.n.value = vobject.vcard.Name(family=last_name, given=first_name)
        j.add('fn')
        j.fn.value = last_name + " " + first_name
    else:
        # vCard limitation - must be at least one fn element
        raise RuntimeError("First name and last name must be given")

    if org:
        j.add('ORG')
        j.org.value = org

    if mobile_number:
        tel = j.add("tel")
        tel.type_param = ["WORK", "MOBILE"]
        tel.value = mobile_number

    if email:
        j.add('email')
        j.email.value = email
        j.email.type_param = 'INTERNET'

    return j.serialize()
Exemplo n.º 20
0
 def to_vcard(self):
     """Convert this contact to a vCard."""
     card = vobject.vCard()
     card.add("prodid").value = "-//Modoboa//Contacts plugin {}//EN".format(
         __version__)
     card.add("uid").value = self.uid
     card.add("n").value = vobject.vcard.Name(family=self.last_name,
                                              given=self.first_name)
     card.add("fn").value = self.display_name
     card.add("org").value = [self.company]
     card.add("title").value = self.position
     card.add("adr").value = vobject.vcard.Address(street=self.address,
                                                   city=self.city,
                                                   code=self.zipcode,
                                                   country=self.country,
                                                   region=self.state)
     if self.birth_date:
         card.add("bday").value = self.birth_date.isoformat()
     card.add("note").value = self.note
     for email in EmailAddress.objects.filter(contact=self):
         attr = card.add("email")
         attr.value = email.address
         attr.type_param = email.type
     for phone in PhoneNumber.objects.filter(contact=self):
         attr = card.add("tel")
         attr.value = phone.number
         attr.type_param = phone.type
     return card.serialize()
Exemplo n.º 21
0
    def __init__(self, address_book, filename=None):
        self.vcard = None
        self.address_book = address_book
        self.filename = filename

        if self.filename is None:
            # create new vcard object
            self.vcard = vobject.vCard()
            # uid
            choice = string.ascii_uppercase + string.digits
            uid_obj = self.vcard.add('uid')
            uid_obj.value = ''.join([random.choice(choice) for _ in range(36)])
            # use uid for vcard filename
            self.filename = os.path.join(address_book.get_path(),
                                         self.vcard.uid.value + ".vcf")

        else:
            # create vcard from .vcf file
            try:
                file = open(self.filename, "r")
                contents = file.read()
                file.close()
            except IOError as e:
                raise
            # create vcard object
            try:
                self.vcard = vobject.readOne(contents)
            except vobject.base.ParseError as e:
                # if creation fails, try to repair vcard contents
                try:
                    self.vcard = vobject.readOne(
                        self.filter_invalid_tags(contents))
                    self.write_to_file(overwrite=True)
                except vobject.base.ParseError as e:
                    raise
Exemplo n.º 22
0
def getVcard(attrib):
    """Returns a new vcard object with common attributes populated"""

    entry = vobject.vCard()

    entry.add('n')
    entry.n.value = attrib["name"]
    entry.n.isNative = False

    entry.add('fn')
    entry.fn.value = attrib["name"]

    entry.add('X-D-BLDG-LOC')
    entry.x_d_bldg_loc.value = CAMPUS_LOC

    entry.add('categories')
    entry.categories.value = ["Corvallis"]

    entry.add('note')
    entry.note.value = ""

    if attrib["summary"] is not None:
        entry.note.value = strip_tags(attrib["summary"]).encode('utf-8')

    if "abbreviation" in attrib and attrib["abbreviation"] is not None:
        entry.add("X-D-BLDG-ID")
        entry.x_d_bldg_id.value = attrib["abbreviation"].upper()

    return entry
    def exportVCF(self):
        sql = Contacts.select().order_by(Contacts.id.asc())
        result = list(sql)

        for item in result:
            # print("| ID:\t\t{3}\n| First:\t{0}\n| Last:\t\t{1}\n| Number: \t{2}\n".format(item.first_name, item.last_name, item.phone_number,item.id))
            vcf = vobject.vCard()
            vcf.add('n')
            vcf.add('fn')
            vcf.add('tel')
            vcf.tel.type_param = 'cell'
            vcf.n.value = vobject.vcard.Name(family=item.last_name,
                                             given=item.first_name)
            vcf.fn.value = item.first_name + ' ' + item.last_name
            vcf.tel.value = str(
                phonenumbers.format_number(
                    phonenumbers.parse(str(item.phone_number), 'US'),
                    phonenumbers.PhoneNumberFormat.NATIONAL))
            # vcf.serialize()
            vcf.prettyPrint()
            with open(
                    str(item.id) + '-' + item.first_name + '-' +
                    item.last_name + '.vcf', 'w') as file:
                file.write(str(vcf.serialize()))

        valid_select = False
        input("Press any key to continue. ")
        self.menu()
    def vcard(self, qs):
        """VCARD format."""
        try:
            import vobject
        except ImportError:
            print(
                self.style.ERROR(
                    "Please install python-vobject to use the vcard export format."
                ))
            import sys
            sys.exit(1)
        import sys
        out = sys.stdout
        for ent in qs:
            card = vobject.vCard()
            card.add('fn').value = full_name(**ent)
            if not ent['last_name'] and not ent['first_name']:
                # fallback to fullname, if both first and lastname are not declared
                card.add('n').value = vobject.vcard.Name(full_name(**ent))
            else:
                card.add('n').value = vobject.vcard.Name(
                    ent['last_name'], ent['first_name'])
            emailpart = card.add('email')
            emailpart.value = ent['email']
            emailpart.type_param = 'INTERNET'

            out.write(card.serialize())
Exemplo n.º 25
0
    def to_vcard(self):
        vcard = vobject.vCard()
        user = self.to_dict()

        name = vcard.add('fn')
        name.value = user['full_name']
        name = vcard.add('n')
        name.value = vobject.vcard.Name(family=user['last_name'],
                                        given=user['first_name'])

        for email in user['emails']:
            e = vcard.add('email')
            e.value = email['email']
            e.type_param = email['tag']

        for telephone in user['telephones']:
            t = vcard.add('tel')
            t.value = telephone['telephone']
            t.type_param = telephone['tag']

        filename = '_'.join([self.first_name, self.last_name, 'contact.vcf'])
        filepath = os.path.join(os.path.abspath(''), 'instance', 'vcf',
                                filename)
        with open(filepath, 'w+') as f:
            f.write(vcard.serialize())
        return filename
Exemplo n.º 26
0
    def generate_vcard(self):
        """Generates af VCard """
        context = aq_inner(self.context)

        # XXX department type not implemented yet
        # XXX vcard download from vtu.addressbook.types not yet tested.
        department = None
        if len(context.departments) > 0:
            department = context.departments[0].to_object
        
        card = vobject.vCard()
        card.add('fn').value = context.title
        card.add('n').value = vobject.vcard.Name(given=context.firstname,
                                                 family=context.lastname,)
        card.add('org').value = [getattr(department, 'title', u''),]
        card.add('adr').value = vobject.vcard.Address(
                street=getattr(department, 'street', u''),
                city=getattr(department, 'city', u''),
                country=u'Denmark',
                code=getattr(department, 'zipcode', u''),)
                          
        card.adr.type_param = [u'WORK']
        card.add('title').value = context.jobtitle
        card.add('email').value = context.email
        card.email.type_param = [u'INTERNET', u'WORK']
        card.add('tel').value = context.phone
        card.tel.type_param = [u'WORK']
        return card.serialize()
Exemplo n.º 27
0
def vcard_object(request, url):
    if request.method == "POST":
        if "emailvcard" in request.POST:
            emailvcard = request.POST['emailvcard']
            business_card = BusinessCard.objects.get(url_name=url)
            v = vobject.vCard()
            v.add('n')
            v.n.value = vobject.vcard.Name(family=business_card.name, given=business_card.name)
            v.add('fn')
            v.fn.value = "%s %s" % (business_card.name, business_card.name)
            v.add('email')
            v.email.value = u'%s' % str(business_card.fieldbusiness_set.filter(type_record_field='E')[0])
            v.add('tel')
            v.tel.value = u'%s' % str(business_card.fieldbusiness_set.filter(type_record_field='P')[0])
            v.tel.type_param = 'WORK'
            v.add('url')
            v.url.value = u'%s' % str(business_card.websitecard_set.all()[0].url)
            output = v.serialize()
            filename = "%s.vcf" % (business_card.url_name)
            #response = HttpResponse(output, mimetype="text/x-vCard")
            #response['Content-Disposition'] = 'attachment; filename=%s' % filename
            myvcf = open('%s%s' % (settings.MEDIA_ROOT, filename), 'w')
            myvcf.write(output)
            myvcf.close()
            body = u'''
            <h1 style="background: #0AA8A6; padding: 8px;"><img src="http://qmoqui.com/static/img/logo-w.png"/></h1>
            <p>Add <b>%s</b> to your contact list from the file attached</p>
            ''' % business_card.name
            emailmsg = EmailMessage('Your new contact', body, 'Qmoqui <*****@*****.**>', [emailvcard,])
            emailmsg.attach_file('%s%s' % (settings.MEDIA_ROOT, filename))
            emailmsg.content_subtype = "html"
            emailmsg.send()
            return HttpResponse('Please check your email inbox')
Exemplo n.º 28
0
def process_parent(name, member, section, f):

    # If the name does not appear to have lastname part
    # add it from the member name.
    if len(name.strip().split(' ')) < 2:
        name = "{} {}".format(name.strip(), member['last_name'])

    j = vo.vCard()

    uid = j.add('UID')
    uid.value = "{}{}[email protected]".format(
        name.replace(" ", ""),
        member[OSM_REF_FIELD])

    j.add('n')
    j.n.value = vo.vcard.Name(
        family=f('lastname') if f('lastname').strip() else member['last_name'],
        given=f('firstname'))
    j.add('fn')
    j.fn.value = name

    next_ = next_f(j, 0).next_f

    for _ in ['phone1', 'phone2']:
        number, name = parse_tel(f(_), _)
        next_('tel', name, number)

    for _ in ['email1', 'email2']:
        if f(_).strip() == "":
            # Ignore empty emails.
            continue

        # If the email is marked as private, add it as a note.
        if (f(_).startswith('x ') or
                f("{}_leaders".format(_)) != "yes"):
            next_('note', _,
                  "Private email address: {}".format(f(_)))
        else:
            next_('email', _, f(_))

    next_('adr', 'Primary',
          vo.vcard.Address(
              street=f('address1'),
              city=f('address2'),
              region=f('address3'),
              country=f('address4'),
              code=f('postcode')))

    org = j.add('org')
    org.value = [section, ]

    note = j.add('note')
    note.value = "Child: {} {} ({})\n".format(
        member['first_name'], member['last_name'], section)

    cat = j.add('CATEGORIES')
    cat.value = ("7th", "7th Lichfield Parent")

    return j.serialize()
Exemplo n.º 29
0
def create_vcard(contact, address_book_path: str):
    # TODO: Add Customer Address details?
    if not contact.nextcloud_contact_id:
        contact.nextcloud_contact_id = str(uuid.uuid4())
        frappe.db.set_value('Contact',
                            contact.name,
                            'nextcloud_contact_id',
                            contact.nextcloud_contact_id,
                            update_modified=False)

    # New vCard Object
    card = vobject.vCard()
    card.add('n')
    card.n.value = vobject.vcard.Name(given=contact.first_name,
                                      family=contact.last_name or '',
                                      additional=contact.middle_name or '')

    card.add('fn')
    card.fn.value = "{first_name} {middle_name} {last_name}".format(
        **contact.as_dict())

    for phone in contact.phone_nos:
        p = card.add('tel')
        p.value = phone.phone

        if phone.is_primary_mobile_no:
            p.type_param = 'mobile'  # IOS Compatible

    for email in contact.email_ids:
        card.add('email').value = email.email_id

    for link in contact.links:
        if link.link_doctype == 'Customer':
            card.add('categories')
            card.categories.value = frappe.get_value('Customer',
                                                     link.link_name,
                                                     'customer_group'), ''
            break

    carddav_org_field = frappe.db.get_single_value('Nextcloud Settings',
                                                   'carddav_org_field',
                                                   cache=True)
    if carddav_org_field:
        card.add('org')
        card.org.value = carddav_org_field, ''

    card.add('rev')
    card.rev.value = datetime.datetime.utcnow().replace(
        microsecond=0).isoformat() + 'Z'

    card.add('uid')
    card.uid.value = contact.nextcloud_contact_id

    # TODO: Pragmatically set a address book, because now only one is working for Contact details
    card_file = open(
        os.path.join(address_book_path,
                     '{}.vcf'.format(contact.nextcloud_contact_id)), 'w+')
    card_file.write(card.serialize())
    card_file.close()
Exemplo n.º 30
0
def _vcard_string(person):
    """
    Helper function for vcard views. Accepts a 'person' object 
    with certain attributes (firstname, lastname, email, phone, id)
    and returns a string containing serialized vCard data.
    """
    # vobject API is a bit verbose...
    v = vobject.vCard()
    v.add("n")
    v.n.value = vobject.vcard.Name(family=person.lastname, given=person.firstname)
    v.add("fn")
    v.fn.value = "%s %s" % (person.firstname, person.lastname)
    v.add("email")
    if person.personnal_address:
        a = person.personnal_address
        addr = v.add("ADR")
        addr.type_param = "HOME"
        street = a.street1
        if a.street2:
            street += ", " + a.street2
        addr.value = vobject.vcard.Address(
            street=street, city=a.city, region=a.state, code=a.zipcode, country=a.country
        )
    if person.work and person.work.address:
        a = person.work.address
        addr = v.add("ADR")
        addr.type_param = "WORK"
        street = a.street1
        if a.street2:
            street += ", " + a.street2
        addr.value = vobject.vcard.Address(
            street=street, city=a.city, region=a.state, code=a.zipcode, country=a.country
        )

    if person.email:
        email = v.add("email")
        email.value = person.email
        email.type_param = "INTERNET"
    if person.title:
        v.add("title")
        v.title.value = person.title
    if person.work:
        org = v.add("org")
        org.value = (person.work.name,)
    for tel in person.phone_set.all():
        t = v.add("tel")
        t.type_param = tel.name.upper()
        t.value = tel.number
    for url in person.url_set.all():
        u = v.add("url")
        if url.explicit_url:
            u.type_param = "HOME"
            u.value = url.explicit_url
        else:
            u.type_param = url.type.upper()
            u.value = URLS[url.type] % url.__dict__

    output = v.serialize()
    return output
Exemplo n.º 31
0
def generateVcard(d,vcardfile,jpegfile,count,index,pprint=True):
    '''  We construct vobject using dict which represents pull from sqlite db. '''
    vcard = vobject.vCard()
    o = vcard.add('n')
    o.value = vobject.vcard.Name(
                        family=d.get(SURNAME) or '',
                        given=getForename(d.get(FORENAME),count,index),
                        additional=d.get(ADDITIONAL) or '',
                        prefix=d.get(PREFIX) or '',
                        suffix=d.get(SUFFIX) or ''
    )
    o = vcard.add('fn')
    o.value = getFullName(d.get(SURNAME) or '', d.get(FORENAME) or '',count,index)
    if d.get(ORG):
        for v in d.get(ORG):
            o = vcard.add('org')
            o.value = [v]
    for field,typ in [(NICKNAME,'nickname'),(ROLE,'role'),(BDAY,'bday')]:
        if d.get(field):
            o = vcard.add(typ)
            o.value = d.get(field)
    for fieldname,typ in [(EMAIL,'email'),(TEL,'tel'),(URL,'url')]:
        if d.get(fieldname):
            for k,v in d.get(fieldname).items():
                o = vcard.add(typ)
                o.value = v
                #o.modifier
                o.type_param = k
    if d.get(ADDR):
        for k,v in d.get(ADDR).items():
            a = vcard.add('adr')
            a.type_param = k
            a.value = vobject.vcard.Address(
                getStreet(v.get(STREET),count,index),
                city=v.get(CITY) or '',
                region=v.get(STATE) or '',
                code=v.get(POSTCODE) or '',
                country=v.get(COUNTRY) or '',
                box=v.get(POBOX) or '',
                extended=v.get(EXTADR) or ''
            )
    if d.get(NOTE):
        o=vcard.add('note')
        o.value = getNote(d,vcardfile)
    if d.get(PHOTO):
        o=vcard.add('photo')
        o.value = getPhoto(jpegfile)
        o.encoding_param = 'b'
        o.type_param = 'jpeg'
    # Enable this to prettyprint the vobject representation
    # We'd probably prefer to be in JSON here.
    if pprint:
        vcard.prettyPrint()
    # Check to see we can parse the result back to vobject
    s = vcard.serialize()
    pvcard = vobject.readOne(s)
    if d.get(SURNAME):
        assert(pvcard.n.value.family == d.get(SURNAME))
    return s
Exemplo n.º 32
0
 def __init__(self, contact):
     self.contact = contact
     self.card = vobject.vCard()
     self.card.behavior.sortFirst = (
         'version', 'prodid', 'uid', 'n', 'fn',
         'org', 'title', 'photo', 'tel', 'url',
         'adr', 'email',
     )
Exemplo n.º 33
0
 def __init__(self, contact):
     self.contact = contact
     self.card = vobject.vCard()
     self.card.behavior.sortFirst = (
         'version', 'prodid', 'uid', 'n', 'fn',
         'org', 'title', 'photo', 'tel', 'url',
         'adr', 'email',
     )
 def pretty_print(vcard_object: vobject.vCard()):
     print("\n---------------------------")
     for field in vcard_object.contents:
         field_contents = vcard_object.contents[field]
         for data in field_contents:
             print(f"{data.name}")
             print(f"\tValue - {data.value}")
     print("---------------------------")
Exemplo n.º 35
0
def add_all():
    for index in arr:
        item = arr[index]
        v = vobject.vCard()
        v.add('fn').value = item.pop(1)
        v.add('phone').value = item.pop(2)
        # v.add('email').value = '*****@*****.**'
        print(v.serialize())
Exemplo n.º 36
0
    def test_party_vcard2values(self):
        'Test Party.vcard2values'
        pool = Pool()
        Party = pool.get('party.party')

        vcard = vobject.vCard()
        vcard.add('n').value = vobject.vcard.Name('Pam Beesly')
        vcard.add('fn').value = 'Pam Beesly'
        vcard.add('email').value = '*****@*****.**'
        vcard.add('tel').value = '+55512345'

        self.assertDictEqual(
            Party().vcard2values(vcard), {
                'name':
                'Pam Beesly',
                'addresses': [],
                'contact_mechanisms': [
                    ('create', [{
                        'type': 'email',
                        'value': '*****@*****.**',
                    }]),
                    ('create', [{
                        'type': 'phone',
                        'value': '+55512345',
                    }]),
                ],
                'vcard':
                vcard.serialize(),
            })

        party, = Party.create([{
            'name':
            'Pam',
            'contact_mechanisms': [
                ('create', [{
                    'type': 'email',
                    'value': '*****@*****.**',
                }]),
            ],
        }])
        cm, = party.contact_mechanisms
        self.assertDictEqual(
            party.vcard2values(vcard), {
                'name':
                'Pam Beesly',
                'addresses': [],
                'contact_mechanisms': [
                    ('write', [cm.id], {
                        'value': '*****@*****.**',
                    }),
                    ('create', [{
                        'type': 'phone',
                        'value': '+55512345',
                    }]),
                ],
                'vcard':
                vcard.serialize(),
            })
Exemplo n.º 37
0
def to_vcard(item):
    item = item.map(lambda s: s.strip())

    c = vobject.vCard()

    c.add('n')
    if item['Additional Name']:
        c.n.value = vobject.vcard.Name(family=item['Family Name'],
                                       given=item['Given Name'],
                                       additional=item['Additional Name'])
    else:
        c.n.value = vobject.vcard.Name(family=item['Family Name'],
                                       given=item['Given Name'])

    c.add('fn')
    c.fn.value = item['Name']

    simple_pairs = [('Nickname', 'nickname'), ('Birthday', 'bday'),
                    ('Notes', 'note')]

    for p1, p2 in simple_pairs:
        if item[p1]:
            c.add(p2)
            getattr(c, p2).value = item[p1]

    if item['Group Membership']:
        c.add('categories')
        c.categories.value = [
            g.lstrip('* ') for g in item['Group Membership'].split(' ::: ')
        ]

    for i in range(1, 4):
        if item['E-mail %d - Value' % i]:
            for elem in item['E-mail %d - Value' % i].split(' ::: '):
                c.add('email')
                c.contents['email'][-1].value = elem
                c.contents['email'][-1].type_param = item['E-mail %d - Type' %
                                                          i].lstrip('* ')

    for i in range(1, 6):
        if item['Phone %d - Value' % i]:
            for elem in item['Phone %d - Value' % i].split(' ::: '):
                c.add('tel')
                c.contents['tel'][-1].value = elem
                c.contents['tel'][-1].type_param = item['Phone %d - Type' %
                                                        i].lstrip('* ')

    # Doesn't work, no idea why

    # for i in range(1, 2):
    #     if item['Website %d - Value' % i]:
    #         c.add('item1.URL')
    #         print(c.contents)
    #         c.contents['item1.URL'][i - 1].value = item['Website %d - Value' % i]
    #         c.add('item1.X-ABLabel')
    #         c.contents['item1.X-ABLabel'][i - 1].type_param = item['Website %d - Type' % i]

    return c
Exemplo n.º 38
0
def vcard():
    vc = vobject.vCard()

    vc.add("fn").value = request.form.get("name")
    vc.add("email").value = request.form.get("mail")
    vc.add("tel").value = request.form.get("phone")
    vc.add("adr").value = vobject.vcard.Address(request.form.get("address"))

    return Response(vc.serialize(), mimetype="text/vcard")
Exemplo n.º 39
0
def create_vcard(name, phone_number):
    card = vobject.vCard()
    card.add('fn')
    card.fn.value = name
    card.add('tel')
    card.tel.type_param = 'CELL'
    card.tel.value = phone_number

    return card
Exemplo n.º 40
0
def _vcard_string(user):
    """
    Helper function for vcard views. Accepts a 'user' object
    with certain attributes (firstname, lastname, email, phone, id)
    and returns a string containing serialized vCard data.
    """
    # vobject API is a bit verbose...
    v = vobject.vCard()
    v.add('n')
    v.n.value = vobject.vcard.Name(family=user.person.last_name,
                                   given=user.person.first_name)

    v.add('fn')
    v.fn.value = "%s" % user.common_name

    if user.person.email:
        v.add('email')
        v.email.value = user.person.email
        v.email.type_param = 'WORK'

    # Puesto
    # if card.title:
    #     v.add('title')
    #     v.title.value = card.title

    # if card.company:
    v.add('org')
    v.org.value = ['Adastra International Inc.']

    # TODO correct address format
    # v.add('adr')
    # v.adr.value = card.address or 'Unknown'
    # v.box.value = '00000'

    phone_mobile = user.person.profile.get_phone_mobile()
    # phone_home = user.profile.get_phone_home()

    if phone_mobile:
        print(phone_mobile)
        v.add('tel')
        v.tel.value = phone_mobile
        v.tel.type_param = 'cell'

    # TODO: Save multiple phones
    # if phone_home:
    #     print(phone_home)
    #     v.add('tel')
    #     v.tel.value = phone_home
    #     v.tel.type_param = 'voice'

    # v.add('url')
    # v.url.value = "%s" % str(card.get_card_url())

    output = v.serialize()
    print(output)

    return output
Exemplo n.º 41
0
def vcards(db):
    """
    Yield vcards from a BBDB database.
    """

    for rec in db.records:
        card = vobject.vCard()

        attr = card.add('fn')
        attr.value = rec.name

        attr = card.add('n')
        attr.value = Name(given=rec.firstname, family=rec.lastname)

        for tag, addr in rec.address.items():
            attr = card.add('adr')
            attr.type_param = tag
            attr.value = Address(street=addr.location,
                                 city=addr.city,
                                 region=addr.state,
                                 code=addr.zipcode,
                                 country=addr.country)

        for tag, number in rec.phone.items():
            attr = card.add('tel')
            attr.type_param = tag
            attr.value = number

        if rec.company:
            attr = card.add('org')
            attr.value = [rec.company]

        for addr in rec.net:
            attr = card.add('email')
            attr.value = addr

        for aka in rec.aka:
            attr = card.add('nickname')
            attr.value = aka

        for key, value in rec.fields.items():
            attr = card.add("X-BBDB-" + key)
            attr.value = value

        for tag, date in anniversaries(rec):
            if tag.startswith('birth'):
                tag = 'bday'
            else:
                tag = 'anniversary'

            year, month, day = date
            year = "%04d" % year if year else '----'

            attr = card.add(tag)
            attr.value = "%s%02d%02d" % (year, month, day)

        yield card
Exemplo n.º 42
0
def get_vcard(context):
    vcard = vobject.vCard()
    contactable = IContactable(context)
    contact_details = contactable.get_contact_details()

    email = contact_details['email']
    if email:
        vcard.add('email')
        vcard.email.type_param = 'INTERNET'
        vcard.email.value = email

    phones = contact_details['phone']
    if not isinstance(phones, list):
        phones = [phones]
    for phone in phones:
        if phone:
            vcard.add('tel')
            vcard.tel.type_param = 'WORK'
            vcard.tel.value = phone

    cell_phones = contact_details['cell_phone']
    if not isinstance(cell_phones, list):
        cell_phones = [cell_phones]
    for cell_phone in cell_phones:
        if cell_phone:
            vcard.add('tel')
            last_item = len(vcard.tel_list) - 1
            vcard.tel_list[last_item].type_param = 'CELL'
            vcard.tel_list[last_item].value = cell_phone

    im_handle = contact_details['im_handle']
    if im_handle:
        vcard.add('impp')
        vcard.impp.value = im_handle

    address = contact_details['address']

    # if we don't have relevant address information, we don't need address
    if address:
        vcard.add('adr')
        country = safe_unicode(address['country'], encoding='utf8')
        region = safe_unicode(address['region'], encoding='utf8')
        zip_code = safe_unicode(address['zip_code'], encoding='utf8')
        city = safe_unicode(address['city'], encoding='utf8')
        street = safe_unicode(address['street'], encoding='utf8')
        number = safe_unicode(address['number'], encoding='utf8')
        additional = safe_unicode(address['additional_address_details'],
                                  encoding='utf8')
        vcard.adr.value = vobject.vcard.Address(street=street,
                                                city=city,
                                                region=region,
                                                code=zip_code,
                                                country=country,
                                                box=number,
                                                extended=additional)
    return vcard
Exemplo n.º 43
0
def get_vcard(context):
    vcard = vobject.vCard()
    contactable = IContactable(context)
    contact_details = contactable.get_contact_details()

    email = contact_details['email']
    if email:
        vcard.add('email')
        vcard.email.type_param = 'INTERNET'
        vcard.email.value = email

    phones = contact_details['phone']
    if not isinstance(phones, list):
        phones = [phones]
    for phone in phones:
        if phone:
            vcard.add('tel')
            vcard.tel.type_param = 'WORK'
            vcard.tel.value = phone

    cell_phones = contact_details['cell_phone']
    if not isinstance(cell_phones, list):
        cell_phones = [cell_phones]
    for cell_phone in cell_phones:
        if cell_phone:
            vcard.add('tel')
            last_item = len(vcard.tel_list) - 1
            vcard.tel_list[last_item].type_param = 'CELL'
            vcard.tel_list[last_item].value = cell_phone

    im_handle = contact_details['im_handle']
    if im_handle:
        vcard.add('impp')
        vcard.impp.value = im_handle

    address = contact_details['address']

    # if we don't have relevant address information, we don't need address
    if address:
        vcard.add('adr')
        country = safe_unicode(address['country'], encoding='utf8')
        region = safe_unicode(address['region'], encoding='utf8')
        zip_code = safe_unicode(address['zip_code'], encoding='utf8')
        city = safe_unicode(address['city'], encoding='utf8')
        street = safe_unicode(address['street'], encoding='utf8')
        number = safe_unicode(address['number'], encoding='utf8')
        additional = safe_unicode(address['additional_address_details'],
                                  encoding='utf8')
        vcard.adr.value = vobject.vcard.Address(street=street,
                                                city=city,
                                                region=region,
                                                code=zip_code,
                                                country=country,
                                                box=number,
                                                extended=additional)
    return vcard
Exemplo n.º 44
0
    def to_vcard(self):
        vc = vCard()
        o = vc.add('fn')
        o.value = self.formatted_name

        o = vc.add('tel')
        o.type_param = "cell"
        o.value = '+' + self.id[:self.id.index('@')]

        return vc
Exemplo n.º 45
0
def _create_test_vcard(**kwargs):
    """Create a simple vcard for tests."""
    vcard = vobject.vCard()
    if 'fn' not in kwargs:
        kwargs['fn'] = 'Test vCard'
    if 'version' not in kwargs:
        kwargs['version'] = '3.0'
    for key, value in kwargs.items():
        vcard.add(key.upper()).value = value
    return vcard
Exemplo n.º 46
0
def vcard_from_email(display_name, email):
    fname, lname = get_names(display_name)
    vcard = vobject.vCard()
    vcard.add('n')
    vcard.n.value = vobject.vcard.Name(family=lname, given=fname)
    vcard.add('fn')
    vcard.fn.value = display_name
    vcard.add('email')
    vcard.email.value = email
    vcard.email.type_param = 'INTERNET'
    return vcard_from_vobject(vcard)
Exemplo n.º 47
0
def createVcard(name,phone):
   """Create vcard formated string with name (given and family) and phoneNumber given"""
   import vobject
   j = vobject.vCard()
   j.add('n')
   [nombrePila,apellido] = name.split(' ')
   j.n.value = vobject.vcard.Name( family=apellido, given=nombrePila )
   j.add('fn')
   j.fn.value = name
   j.add('tel')
   j.tel.value = phone
   return j.serialize()
Exemplo n.º 48
0
    def vcard_for_contact(self, entry):
        """Convert and google contact into a vCard string.

        Hacked together from http://vobject.skyhouseconsulting.com/usage.html,
        google contacts feed print example and http://en.wikipedia.org/wiki/VCard.

        :returns: This returns a single string containing the vcard.

        """
        card = vobject.vCard()

        family_name = "?"
        full_name = "?"
        given_name = "?"

        if not entry.name is None:
            family_name = entry.name.family_name is None and " " or entry.name.family_name.text
            full_name = entry.name.full_name is None and " " or entry.name.full_name.text
            given_name = entry.name.given_name is None and " " or entry.name.given_name.text

        if isinstance(family_name, unicode):
            family_name = family_name.encode("ascii", errors="ignore")

        if isinstance(full_name, unicode):
            full_name = full_name.encode("ascii", errors="ignore")

        if isinstance(given_name, unicode):
            given_name = given_name.encode("ascii", errors="ignore")

        self.log.info("family_name: <%s> given_name <%s> full_name <%s>" % (family_name, given_name, full_name))

        card.add('n')
        card.n.value = vobject.vcard.Name(family=family_name, given=given_name)
        card.add('fn')
        card.fn.value = full_name
        card.add('email')
        card.email.value = ''
        card.email.type_param = 'INTERNET'

        if entry.phone_number:
            for num in entry.phone_number:
                card.add('tel')
                card.tel.value = num.text
                card.tel.type_param = 'MOBILE'

        try:
            card = card.serialize()
            self.log.info("card: %s" % card)

        except UnicodeDecodeError, e:
            self.log.error("Unable to serialise due to unicode error <%s>" % e)
            card = None
Exemplo n.º 49
0
 def run_from_ui(self, ar, **kw):
     #~ print 20130912
     #~ obj = ar.selected_rows[0]
     mf = TmpMediaFile(ar, 'vcf')
     settings.SITE.makedirs_if_missing(os.path.dirname(mf.name))
     with open(mf.name, 'w') as wf:
         for obj in ar.selected_rows:
             j = vobject.vCard()
             obj.fill_vcard(j)
             wf.write(j.serialize())
         
     ar.set_response(success=True)
     ar.set_response(open_url=mf.url)
Exemplo n.º 50
0
	def sendVCard(self, target, args):
		account = self.s.query(Account).get(self.account_id)

		card = vobject.vCard()
		params = args.split(",")
		family_name = params[0]
		given_name = params[1]
		name = family_name + " " + given_name

		card.add('fn')
		card.fn.value = name

		card.add('n')
		card.n.value = vobject.vcard.Name(family=family_name, given=given_name)

		self._d("First name %s" %family_name)
		self._d("Last name %s" %given_name)

		api_url = self.url  + "/api/v1/base/status?token=%s" %account.auth_token
		headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
		r = requests.get(api_url, headers=headers)
		response = r.json()

		
		del params[0]
		del params[0]		

		for number in params:
			tel = number.split(":")
			num = card.add('tel')
			num.value = tel[1]
			num.type_param = tel[0]

		self._d("Response is %s" %response)
		if response['profile_pic'] != self.url + '/blank-profile.png':			
			tb = open('tmp/profile_thumb.jpg', 'wb')
			tb.write(requests.get(response['profile_pic']).content)
			tb.close()

			f = open('tmp/profile_thumb.jpg', 'r')
			stream = base64.b64encode(f.read())
			f.close()

			card.add('photo')
			card.photo.value = stream
			card.photo.type_param = "JPEG"
			# card.photo.encoding_param = "b"


		self._d("Data %s" %card.serialize())
		self.methodsInterface.call("message_vcardSend", (target, card.serialize(), name))
Exemplo n.º 51
0
    def _vcard_string(self, contact):
        """Returns a string containing serialized vCard data."""
        v = vobject.vCard()

        if isinstance(contact, Contact):
            v.add("n").value = vobject.vcard.Name(family=contact.name, given=contact.firstname)
            v.add("fn").value = contact.get_full_name()
            if contact.organization:
                v.add("org").value = [contact.organization.corporate_name]
            if contact.birthday:
                v.add("bday").value = contact.birthday.isoformat()

        elif isinstance(contact, Organization):
            v.add("n").value = vobject.vcard.Name()
            v.add("fn").value = ""
            v.add("org").value = [contact.corporate_name]

        # XXX: Add PHOTO

        for email in contact.emails:
            e = v.add("email")
            e.value = email.email
            if email.type:
                e.type_param = email.type

        for phone in contact.phones:
            types = []
            if phone.type:
                types.append(phone.type)
            if phone.subtype:
                types.append(phone.subtype)
            p = v.add("tel")
            if types:
                p.type_paramlist = types
            p.value = phone.phone

        for address in contact.addresses:
            a = v.add("adr")
            if address.type:
                a.type_param = address.type
            a.value = vobject.vcard.Address(
                street=address.street_address or "",
                city=address.city or "",
                region=address.state or "",
                code=address.postal_code or "",
                country=address.country or "",
                box=address.postoffice_box or "",
                extended=address.extended_address or "",
            )

        return v.serialize()
Exemplo n.º 52
0
def build_card(contact):
    card = vCard()
    name = card.add('n')
    name.value = Name(family=contact.name)

    fullname = card.add('fn')
    if contact.user:
        fullname.value = '%s %s' % (contact.user.first_name, contact.user.last_name)
    else:
        fullname.value = contact.name

    tel = card.add('tel')
    tel.value = contact.extension
    return card.serialize()
Exemplo n.º 53
0
 def setUp(self):
     self._dir = os.path.dirname(__file__)
     self.data_path = os.path.join(self._dir, 'data')
     self.golden_path = os.path.join(self._dir, 'golden')
     self.card = vobject.vCard()
     self.card.add('n')
     self.card.n.value = vobject.vcard.Name(family="Thecat", given="Felix")
     self.card.add('fn')
     self.card.fn.value = "Felix Thecat"
     self.photo_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Felix_the_cat.svg/229px-Felix_the_cat.svg.png"  # noqa E501
     self.photo_path = os.path.join(self.data_path, 'felix-229.png')
     if not os.path.isfile(self.photo_path):
         urllib.request.urlretrieve(self.photo_url, self.photo_path)
     self.golden_filepath = os.path.join(self.golden_path, 'Felix.vcf')
Exemplo n.º 54
0
def vcard_contact_export(contact):
    """Export in VCard 3.0 a Contact model instance"""
    if hasattr(contact, 'content_object') and hasattr(contact.content_object, 'vcard_export'):
        return contact.content_object.vcard_export()

    vcard = vobject.vCard()
    vcard.add('n')
    vcard.n.value = vobject.vcard.Name(family=contact.last_name, given=contact.first_name)
    vcard.add('fn')
    vcard.fn.value = '%s %s' % (contact.first_name, contact.last_name)
    vcard.add('email')
    vcard.email.value = contact.email
    vcard.email.type_param = 'INTERNET'
    return vcard.serialize()
Exemplo n.º 55
0
def build_card(contact):
    card = vCard()
    name = card.add("n")
    name.value = Name(family=contact.name)

    fullname = card.add("fn")
    if contact.user:
        fullname.value = "%s %s" % (contact.user.first_name, contact.user.last_name)
    else:
        fullname.value = contact.name

    tel = card.add("tel")
    tel.value = contact.extension
    return card.serialize()
Exemplo n.º 56
0
def vcard_export(request):
    filename = 'addresses'
    if request.method == 'POST':
        form = ExportForm(request.POST,request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            qs = Person.objects.filter(pk__in=data['ids'].split(','))
            result = []
            for person in qs:
                print(person)
                vc = vobject.vCard()
                vc.add('n')
                vc.n.value = vobject.vcard.Name(family=person.last_name, given=person.first_name)
                vc.add('fn')
                vc.fn.value = ' '.join([person.first_name,person.last_name])
                for email in person.emails.all():
                    obj = vc.add('email')
                    obj.value = email.email
                    obj.type_param = email.location.value
                for tel in person.telephones.all():
                    obj = vc.add('tel')
                    obj.value = tel.number
                    obj.type_param = ','.join([tel.location.value,tel.get_type_display()])
                for addr in person.addresses.all():
                    obj = vc.add('adr')
                    street = ''
                    if addr.line1:
                        street = [addr.line1]
                    if addr.line2:
                        street.append(addr.line2)
                    if addr.line3:
                        street.append(addr.line3)
                    region=addr.state.long_name if addr.state else ''
                    country=addr.state.country.name if addr.state else ''
                    obj.value = vobject.vcard.Address(street=street, city=addr.city, region=region, country=country, code=addr.zip)
                    obj.type_param = addr.location.value
                if person.image:
                    obj = vc.add('photo')
                    obj.value = person.image
                    obj.value_param='URL'
                vc.add('rev').value = person.modified.isoformat()
                result.append(vc.serialize())
            if len(result)==1:
                filename = '_'.join([qs[0].first_name, qs[0].last_name])
            else:
                filename += '-'+datetime.datetime.now().date().isoformat()
            resp = http.HttpResponse('\n\n'.join(result),content_type='text/vcard')
            resp['Content-Disposition'] = 'attachment; filename="'+filename+'.vcf"'
            return resp
    raise http.Http404
Exemplo n.º 57
0
 def as_vcard(self):
     # vobject API is a bit verbose...
     v = vobject.vCard()
     v.add('n')
     v.n.value = vobject.vcard.Name(family=self.last_name, given=self.first_name)
     v.add('fn')
     v.fn.value = self.full_name
     v.add('email')
     v.email.value = self.email
     v.add('tel')
     v.tel.value = self.phone
     v.tel.type_param = 'MOBILE'
     output = v.serialize()
     return output
Exemplo n.º 58
-1
def get_vcard(contact):
    card = vobject.vCard()
    card.add('fn')
    card.fn.value = contact['fullname']
    card.add('n')
    card.n.value = vobject.vcard.Name(
        contact['last_name'], contact['first_name'])
    card.add('tel')
    card.tel.type_param = 'cell'
    card.tel.value = contact['contact_no']
    return card.serialize()