VCard:基于 OpenHarmony 的 VCard 解析与生成工具项目

VCard是电子名片的文件格式标准。它一般附加在电子邮件之后,但也可以用于其它场合(如在网际网路上相互交换)。

Branch1Tags8
FilesLast commitLast update
10 months ago
3 months ago
2 years ago
3 months ago
3 years ago
3 years ago
9 months ago
4 years ago
2 years ago
2 years ago
2 years ago
12 days ago
12 days ago
1 year ago
3 years ago
3 years ago
3 years ago
10 months ago
10 months ago
9 months ago

vCard

Introduction

vCard, a file format standard for electronic business cards, is often attached to e-mail messages, and also can be exchanged in other ways, such as on the World Wide Web. It contains information such as names, addresses, phone numbers, URLs, logos, and photos. This library supports vCard standard 2.0 and 3.0.

img1.png

How to Install

ohpm install @ohos/vcard

For details about the OpenHarmony ohpm environment configuration, see OpenHarmony HAR.

How to Use

Generating a vCard

import {contact,VCardBuilder,VCardConfig} from "@ohos/vcard";

let myCard= new contact.Contact();
let nickName = new contact.NickName();
nickName.nickName ="wangermazi";
myCard.nickName = nickName;

let eMail = new contact.Email();
eMail.labelName = "labelName";
eMail.labelId = 2;
eMail.email = "zhangsan@universe.com";
myCard.emails = [eMail];
      
let builder = new VCardBuilder(VCardConfig.VCARD_TYPE_V21_GENERIC,"UTF-8");
builder.appendNickNames(myCard);
builder.appendEmails(myCard);
let result = builder.toString();

Parsing a vCard Text

VCard parsing supports two methods: file-based parsing and content-based parsing.

Example 1: Parsing VCard files

import fs from '@ohos.file.fs';
import {VCardParserImpl_V21, VCardEntry, VCardInterpreter, VCardProperty} from "@ohos/vcard";

let vCardEntry = new VCardEntry();
class MyVCardInterpreter implements VCardInterpreter{
  onVCardStarted(): void {
  }
  onVCardEnded(): void {
  }
  onEntryStarted(): void {
  }
  onEntryEnded(): void {
  }
  onPropertyCreated(property: VCardProperty): void {
    vCardEntry.addProperty(property);
  }
}
let myParser = new VCardParserImpl_V21();
myParser.addInterpreter(new MyVCardInterpreter());
let fileDescriptor = fs.openSync("./pathTo/00002.vcf", 0o100|0o2);
myParser.parse(fileDescriptor.fd);
vCardEntry.consolidateFields();
let nickName = vCardEntry.getNickNameList();
let emails= vCardEntry.getEmailList();

Example 2: Parsing VCard content

import {VCardParserImpl_V21,VCardEntry,VCardInterpreter,VCardProperty} from "@ohos/vcard";

const vcardContent = `BEGIN:VCARD
VERSION:2.1
N:Smith;John;;;
FN:John Smith
X-PHONETIC-FIRST-NAME:zhangsan
NICKNAME:wangermazi
TEL;TYPE=CELL:135792468102
EMAIL;TYPE=WORK:zhangsan@universe.com
END:VCARD`;

let vCardEntry = new VCardEntry()
class MyVCardInterpreter implements VCardInterpreter{
  onVCardStarted(): void {
  }
  onVCardEnded(): void {
  }
  onEntryStarted(): void {
  }
  onEntryEnded(): void {
  }
  onPropertyCreated(property: VCardProperty): void {
    vCardEntry.addProperty(property)
  }
}
let myParser = new VCardParserImpl_V21();
myParser.addInterpreter(new MyVCardInterpreter());
myParser.parseVCardText(vcardContent);
vCardEntry.consolidateFields();
let nickName = vCardEntry.getNickNameList();
let emails= vCardEntry.getEmailList();

Available APIs

APIs

Module Overview

Modules Description
StringBuilder String builder.
VCardBuilder VCard builder.
VCardParserImpl_V21 Specific implementation class of the parser.
HOSBase64 Base64 encoding and decoding utility class.
Utf8ArrayToStr Method to convert Uint8Array to string.
VCardInterpreter Callback interface/handler for parsing events.
VCardProperty A single property in a vCard.
VCardConfig Parser configuration manager.
contact Contact object model.
VCardEntry VCard object that stores contact information.
TextUtils Text processing utility class.
GlobalContext Global object, function to parse string into integer.

1.StringBuilder
let stringBuilder = new StringBuilder();

Methods Parameter Description
append content: string Add string content.
getUint8Bytes / Get content in Uint8Array format.
clear / Clear content.
size / Get array length.
toString / Convert to string.

2.VCardBuilder
let builder=new VCardBuilder(VCardConfig.VCARD_TYPE_V21_GENERIC,"UTF-8");

Methods Parameter Description
appendNickNames iContact: Contact 昵称。
appendNameProperties iContact: Contact 名字。
appendPhones iContact: Contact 电话。
appendEmails iContact: Contact 电子邮件。
appendPostals iContact: Contact 地址。
appendIms iContact: Contact 社交工具。
appendWebsites iContact: Contact 网站地址。
appendOrganizations iContact: Contact 组织。
appendPhotos iContact: Contact 照片地址。
appendNotes iContact: Contact 备注。
appendGroupMemberShip iContact: Contact 群组。
appendEvents iContact: Contact 事件。
appendRelation iContact: Contact 关系。
appendPostalLine type: number, label: string,
contentValues: contact.PostalAddress ,
isPrimary: boolean,
emitEveryTime: boolean
单个地址。
appendEmailLine type: number, label: string,
rawValue: string,
isPrimary: boolean
单个电子邮件。
appendTelLine typeAsInteger: number , label: string,
encodedValue: string,
isPrimary: boolean
单个电话。
appendPhotoLine encodedValue: string, photoType: string 单个照片地址。
appendSpecificProperty mimeType: string,
typeModel: contact.NickName/contact.Event/contact.Relation
追加特定类型的属性。
appendLineWithCharsetAndQPDetection
PropertyNameAndRawVAlue
propertyName: string,
rawValueList: Array
追加自动检测字符集和QP编码的方法。
appendLineWithCharsetAndQPDetection
PropNameParamListRawValue
propertyName: string,
parameterList: Array,
rawValue: string
带参数列表的字符集和QP检测追加方法。
appendLineWithCharsetAndQPDetection propertyName: string,
parameterList: Array,
rawValueList: Array
通用的字符集和QP检测追加方法。
appendLineWithPropertyNameAndRawValue propertyName: string,
rawValue: string
追加属性名和原始值。
appendLineWithProptynameAndRawValueList propertyName: string,
rawValueList: Array
追加属性名和多个原始值。
appendLineWithPropertyNameAndRawValue
AndCharsetAndQuotePrintable
propertyName: string,
rawValue: string,
needCharset: boolean,
reallyUseQuotedPrintable: boolean
追加带字符集和引用可打印编码的属性。
appendLineWithPropertyNameAndParamter
ListAndRawValue
propertyName: string,
parameterList: Array,
rawValue: string
追加属性名、参数列表和原始值。
appendLineWithPropertyName propertyName: string,
parameterList: Array,
rawValue: string,
needCharset: boolean,
reallyUseQuotedPrintable: boolean
使用属性名追加一行,需要单独设置值。
appendLineWithoutParamterList propertyName: string,
rawValueList: Array,
needCharset: boolean,
needQuotedPrintable: boolean
追加属性名和多个原始值。
appendLine propertyName: string,
parameterList: Array = null,
rawValueList: Array,
needCharset: boolean,
needQuotedPrintable: boolean
追加一行内容。
toString / 将 vCard 对象转换为字符串表示形式。

3.VCardParserImpl_V21
let introduction = new VCardParserImpl_V21();

Methods Parameter Description
addInterpreter interpreter: VCardInterpreter Callback interface for event parsing.
parse is: string/number Parse VCard text, input parameter is a file descriptor.
parseVCardText vCardText: InputStream Parse VCard text, input parameter is a VCard string.
parseOne is: string/number Parse VCard text, input parameter is a file descriptor (parses the first VCard content).
cancel / Cancel.

4.HOSBase64
let hosBase64 = new HOSBase64();

Methods Parameter Description
encode str: string base64 encode.
decode str: string base64 decode.

5.Utf8ArrayToStr
Uint8Array to string conversion method:Utf8ArrayToStr(array: Uint8Array);

6.VCardInterpreter

Methods Parameter Description
onVCardStarted / Called when vCard parsing starts.
onVCardEnded / Called when vCard parsing ends.
onEntryStarted / Called when starting to parse a vCard entry.
onEntryEnded / Called after a vCard entry has been parsed.
onPropertyCreated property: VCardProperty Called when a property is created.

7.VCardProperty

Methods Parameter Description
getParamMapString / Get parameter string.
toString / Convert to string.
setName name: string Set property name.
addGroup group: string Add group.
setParameter paramName: string, paramValue: string Set parameter.
addParameter paramName: string, paramValue: string Add parameter.
setRawValue rawValue: string Set raw property value.
setValues ...propertyValues: string[] Set list of property values.
addValues ...propertyValues: string[] Add items to property value list.
setByteValue byteValue: Uint8Array Set binary value.
getName / Get property name.
getGroupList / Get list of groups.
getParameterMap / Get parameter map object.
getParameters type: string Get specified parameter.
getRawValue / Get raw property value.
getValueList / Get list of property values.
getByteValue / Get binary value.

8.VCardConfig
Attribute:

Names Parameter Description
DEFAULT_INTERMEDIATE_CHARSET string Default character set during intermediate conversion to ensure consistent encoding (UTF-8).
DEFAULT_IMPORT_CHARSET string Default character set when importing vCard text.
DEFAULT_EXPORT_CHARSET string Default character set when exporting vCard text.
VERSION_21 number Bit flag for vCard version 2.1.
VERSION_MASK number Used to extract the version bits from the configuration value.
NAME_ORDER_DEFAULT number Default name order (commonly given name first, family name last, or platform default policy).
NAME_ORDER_EUROPE number Bit flag for the commonly used European order with family name first.
NAME_ORDER_JAPANESE number Indicator for Japanese name order (surname first, given name second).
NAME_ORDER_MASK number Mask for extracting the name order position.
FLAG_USE_PROPERTY number Flag to allow using a specific set of properties.
FLAG_USE_DEFACT_PROPERTY number Flag to enable common but non-standard properties (defact).
FLAG_DOCOMO number Flag indicating the presence of DoCoMo device features.
FLAG_REFRAIN_QP_TO_NAME_PROPERTIES number Prohibit using quoted-printable for name properties.
FLAG_CONVERT_PHONETIC_NAME_STRINGS number Flag indicating that kana/pinyin fields need conversion.
FLAG_APPEND_TYPE_PARAM number Enable when a TYPE= parameter needs to be appended to a field.
FLAG_REFRAIN_PHONE_NUMBER_FORMATTING number Disable phone number formatting.
FLAG_REFRAIN_IMAGE_EXPORT number Skip photos when exporting.
FLAG_REFRAIN_EVENTS_EXPORT number Skip event information when exporting.
FLAG_REFRAIN_ADDRESS_EXPORT number Skip address information when exporting.
FLAG_REFRAIN_EMAIL_EXPORT number Skip email information when exporting.
FLAG_REFRAIN_ORGANIZATION_EXPORT number Skip organization information when exporting.
FLAG_REFRAIN_NOTES_EXPORT number Skip notes when exporting.
FLAG_REFRAIN_PHONETIC_NAME_EXPORT number Skip phonetic name field when exporting.
FLAG_REFRAIN_WEBSITES_EXPORT number Skip websites when exporting.
FLAG_REFRAIN_NICKNAME_EXPORT number Skip nickname when exporting.
VCARD_TYPE_UNKNOWN number Placeholder for unknown type.
VCARD_TYPE_V21_GENERIC number vCard 2.1 Universal Configuration Combination (Default Order + Common Properties).
VCARD_TYPE_V21_GENERIC_STR string The corresponding string identifies 'v21_generic'.
VCARD_TYPE_V21_EUROPE number Version 2.1, Combined configuration of European name order.
VCARD_TYPE_V21_EUROPE_STR string The string identifies 'v21_europe'.
VCARD_TYPE_V21_JAPANESE number 2.1 version, Japanese sequential configuration.
VCARD_TYPE_V21_JAPANESE_STR string The string identifies 'v21_japanese_utf8'.
VCARD_TYPE_V21_JAPANESE_MOBILE number Version 2.1, additional requirements for Japanese mobile phones (conversion pseudonym + restriction QP).
VCARD_TYPE_V21_JAPANESE_MOBILE_STR string The string identifies 'v21_japanese_mobile'
VCARD_TYPE_DOCOMO number Based on a Japanese-style mobile phone configuration with DoCoMo features.
VCARD_TYPE_DOCOMO_STR string The string identifies 'docomo'.
VCARD_TYPE_DEFAULT number Default type, equivalent to VCARD_TYPE_V21_GENERIC.
sVCardTypeMap Map<string, number> The string is identified to the mapping table of the specific type configuration.
sJapaneseMobileTypeSet Set A collection of Japanese mobile device types for quick judgment.

Methods:

Methods Parameter Description
getVCardTypeFromString(vcardTypeString: string) number Maps a string (case-insensitive) to a preset type, falling back to default if it fails.
isVersion21(vcardType: number) boolean Determines whether the configuration is vCard 2.1.
shouldUseQuotedPrintable(vcardType: number) boolean Uses quoted-printable by default except for v3.0.
getNameOrderType(vcardType: number) number Reads the name order position to decide the display order of surname/first name.
usesSpecificProperty(vcardType: number) boolean Indicates whether the property set defined by FLAG_USE_PROPERTY is enabled.
usesDefactProperty(vcardType: number) boolean Indicates whether FLAG_USE_DEFACT_PROPERTY is enabled.
shouldRefrainQPToNameProperties(vcardType: number) boolean When v3.0 is used or the prohibition flag is set, do not use QP for name fields.
appendTypeParamName(vcardType: number) boolean Under v3.0 or explicit flag, a TYPE parameter needs to be appended after the property.
isJapaneseDevice(vcardType: number) boolean Use sJapaneseMobileTypeSet to determine if it is a Japanese device configuration.
refrainPhoneNumberFormatting(vcardType: number) boolean Whether to skip phone number formatting.
needsToConvertPhoneticString(vcardType: number) boolean Whether to convert kana/pinyin strings.
onlyOneNoteFieldIsAvailable(vcardType: number) boolean Under Docomo configuration, only one note field is allowed.
isDoCoMo(vcardType: number) boolean Whether the FLAG_DOCOMO flag is included.

9.VCardEntry
let vCardEntry = new VCardEntry(vcardType?: number);

Methods Parameter Description
addProperty property: VCardProperty Adds a property.
consolidateFields / Merges and deduplicates contact data.
getNameData / Gets name information.
getNickNameList / Gets a list of nicknames.
getBirthday / Gets birthday information.
getNotes / Gets notes information.
getPhoneList / Gets phone number information.
getEmailList / Gets a list of email addresses.
getPostalList / Gets postal address information.
getOrganizationList / Gets organization information.
getImList / Gets social media accounts.
getPhotoList / Gets photo URLs.
getWebsiteList / Gets website URLs.
getDisplayName / Gets display name.
getUnknownXData / Gets unknown extended data.
getCustomData / Retrieves custom information.
getAnniversary / Retrieves the anniversary date.
getGroup / Retrieves the group the user belongs to.

10.TextUtils

Methods Parameter Description
isEmpty params?: string Checks if a string is empty.
equals a: string, b: string Strictly compares two strings for exact equality.
isSurrogate ch: number Checks if a Unicode code point belongs to the surrogate region.
isHighSurrogate ch: number Checks if a Unicode code point is a high surrogate.
isLowSurrogate ch: number Checks if a Unicode code point is a low surrogate.
offsetByCodePointsAImpl seq: string, index: number, codePointOffset: number Calculates the new index position in a string based on the given Unicode code point offset.
offsetByCodePoints seq: string, index: number, codePointOffset: number Safely moves the index position in a string based on the given Unicode code point offset.

11.GlobalContext

Methods Parameter Description
parseInt str, radix?: number ` Parses a string into integers.

12.contact
let Utf8ArrayToStr = new Utf8ArrayToStr(array: Uint8Array, encoding: string = "utf8");

Methods Parameter Description
emails Email[] Email.
events Event[] Event.
groups Group[] Group.
imAddresses ImAddress[] Instant messaging address.
phoneNumbers PhoneNumber[] Phone number.
portrait Portrait Portrait.
postalAddresses PostalAddress[] Address.
relations Relation[] Relationship.
sipAddresses SipAddress[] SIP address.
websites Website[] Website address.
name Name Name.
nickName Nickname Nickname.
note Note Note.
organization Organization Organization.

Interface

Email

Attribute Type Description
email string Email address
labelName string/null Label name
displayName string/null Display name
labelId number ID

Event

Attribute Type Description
eventDate ESObject Event Date
labelName string/null Label Name
labelId ESObject ID

Group

Attribute Type Description
groupId number/null Group ID
title string/null Title

ImAddress

Attribute Type Description
imAddress ESObject Instant Messaging Address
labelName string/null Label Name
labelId ESObject ID

PhoneNumber

Attribute Type Description
labelName string/null Label Name
phoneNumber string/null Phone Number
labelId ESObject ID

Portrait

Attribute Type Description
URI string/null Avatar URL

PostalAddress

Attribute Type Description
city string/null City
country string/null Country
labelName string/null Label Name
neighborhood string/null Neighborhood
pobox string/null Postbox
postalAddress string/null Postal Address
postcode string/null Postcode
region ESObject Region
street string/null Street
labelId ESObject ID

Relation

Attribute Type Description
labelName string/null Label Name
relationName ESObject Relation Name
labelId ESObject ID

SipAddress

Attribute Type Description
labelName string/null Label Name
sipAddress string/null SIP Address
labelId number/null ID

Website

Attribute Type Description
website ESObject website address

Name

Attribute Type Description
familyName string/null Family Name
familyNamePhonetic string/null Family Name phonetic
fullName string/null Full Name
givenName string/null Given Name
givenNamePhonetic string/null Given Name phonetic
middleName string/null Middle Name
middleNamePhonetic string/null Middle Name phonetic
namePrefix string/null Name prefix
nameSuffix string/null Name suffix

NickName

Attribute Type Description
nickName ESObject nick Name

Note

Attribute Type Description
noteContent ESObject Note content

Organization

Attribute Type Description
name ESObject Name of the organization
title ESObject title

About obfuscation

  • Code obfuscation, please seeCode Obfuscation.
  • If you want the vcard library not to be obfuscated during code obfuscation, you need to add corresponding exclusion rules in the obfuscation rule configuration file obfuscation-rules.txt:
-keep
./oh_modules/@ohos/vcard

Constraints

Verified on the following versions:

  • OpenHarmony API version >=15.

Directory Structure

|---- VCard  
|     |---- entry  # Sample code
|     |---- library  # vCard library
|           |---- index.ets  # External APIs
|     |---- README.MD  # Readme                   

How to Contribute

If you find any problem when using the project, submit an issue or a PR.

License

This project is licensed under the terms of the Apache License 2.0.

Introduction

VCard是电子名片的文件格式标准。它一般附加在电子邮件之后,但也可以用于其它场合(如在网际网路上相互交换)。

Customize your domain