mirror of
https://github.com/starovoid/rxing.git
synced 2026-07-27 21:02:35 +00:00
vcard port no tests
This commit is contained in:
@@ -13,6 +13,7 @@ regex = "1.6"
|
|||||||
encoding = "0.2"
|
encoding = "0.2"
|
||||||
rand = "0.8.5"
|
rand = "0.8.5"
|
||||||
urlencoding = "2.1.2"
|
urlencoding = "2.1.2"
|
||||||
|
uriparse = "0.6.4"
|
||||||
image = {version = "0.24.3", optional = true}
|
image = {version = "0.24.3", optional = true}
|
||||||
imageproc = {version = "0.23.0", optional = true}
|
imageproc = {version = "0.23.0", optional = true}
|
||||||
|
|
||||||
|
|||||||
@@ -28,347 +28,515 @@
|
|||||||
// import java.util.regex.Matcher;
|
// import java.util.regex.Matcher;
|
||||||
// import java.util.regex.Pattern;
|
// import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
|
use encoding::all::encodings;
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
use crate::RXingResult;
|
use crate::RXingResult;
|
||||||
|
|
||||||
use super::ParsedClientResult;
|
use uriparse::URI;
|
||||||
|
|
||||||
const BEGIN_VCARD : &'static str = "BEGIN:VCARD";//, Pattern.CASE_INSENSITIVE);
|
use super::{AddressBookParsedRXingResult, ParsedClientResult, ResultParser};
|
||||||
const VCARD_LIKE_DATE : &'static str = "\\d{4}-?\\d{2}-?\\d{2}";
|
|
||||||
const CR_LF_SPACE_TAB : &'static str = "\r\n[ \t]";
|
|
||||||
const NEWLINE_ESCAPE : &'static str = "\\\\[nN]";
|
|
||||||
const VCARD_ESCAPES : &'static str = "\\\\([,;\\\\])";
|
|
||||||
const EQUALS : &'static str = "=";
|
|
||||||
const SEMICOLON : &'static str = ";";
|
|
||||||
const UNESCAPED_SEMICOLONS : &'static str = "(?<!\\\\);+";
|
|
||||||
const COMMA : &'static str = ",";
|
|
||||||
const SEMICOLON_OR_COMMA : &'static str = "[;,]";
|
|
||||||
|
|
||||||
/**
|
const BEGIN_VCARD: &'static str = "BEGIN:VCARD"; //, Pattern.CASE_INSENSITIVE);
|
||||||
|
const VCARD_LIKE_DATE: &'static str = "\\d{4}-?\\d{2}-?\\d{2}";
|
||||||
|
const CR_LF_SPACE_TAB: &'static str = "\r\n[ \t]";
|
||||||
|
const NEWLINE_ESCAPE: &'static str = "\\\\[nN]";
|
||||||
|
const VCARD_ESCAPES: &'static str = "\\\\([,;\\\\])";
|
||||||
|
const EQUALS: &'static str = "=";
|
||||||
|
const SEMICOLON: &'static str = ";";
|
||||||
|
const UNESCAPED_SEMICOLONS: &'static str = "(?<!\\\\);+";
|
||||||
|
const COMMA: &'static str = ",";
|
||||||
|
const SEMICOLON_OR_COMMA: &'static str = "[;,]";
|
||||||
|
|
||||||
|
/**
|
||||||
* Parses contact information formatted according to the VCard (2.1) format. This is not a complete
|
* Parses contact information formatted according to the VCard (2.1) format. This is not a complete
|
||||||
* implementation but should parse information as commonly encoded in 2D barcodes.
|
* implementation but should parse information as commonly encoded in 2D barcodes.
|
||||||
*
|
*
|
||||||
* @author Sean Owen
|
* @author Sean Owen
|
||||||
*/
|
*/
|
||||||
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
|
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
|
||||||
// Although we should insist on the raw text ending with "END:VCARD", there's no reason
|
// Although we should insist on the raw text ending with "END:VCARD", there's no reason
|
||||||
// to throw out everything else we parsed just because this was omitted. In fact, Eclair
|
// to throw out everything else we parsed just because this was omitted. In fact, Eclair
|
||||||
// is doing just that, and we can't parse its contacts without this leniency.
|
// is doing just that, and we can't parse its contacts without this leniency.
|
||||||
let rawText = getMassagedText(result);
|
let rawText = ResultParser::getMassagedText(result);
|
||||||
Matcher m = BEGIN_VCARD.matcher(rawText);
|
|
||||||
if (!m.find() || m.start() != 0) {
|
let semicolon_comma_regex = Regex::new(SEMICOLON_OR_COMMA).unwrap();
|
||||||
return null;
|
|
||||||
|
let rg = Regex::new(BEGIN_VCARD).unwrap();
|
||||||
|
let mtch = rg.find(&rawText)?;
|
||||||
|
// Matcher m = BEGIN_VCARD.matcher(rawText);
|
||||||
|
if mtch.start() != 0 {
|
||||||
|
return None;
|
||||||
}
|
}
|
||||||
List<List<String>> names = matchVCardPrefixedField("FN", rawText, true, false);
|
let names: Vec<Vec<String>> =
|
||||||
if (names == null) {
|
if let Some(m) = matchVCardPrefixedField("FN", &rawText, true, false) {
|
||||||
|
m
|
||||||
|
} else {
|
||||||
// If no display names found, look for regular name fields and format them
|
// If no display names found, look for regular name fields and format them
|
||||||
names = matchVCardPrefixedField("N", rawText, true, false);
|
let mut n = matchVCardPrefixedField("N", &rawText, true, false)?;
|
||||||
formatNames(names);
|
formatNames(&mut n);
|
||||||
|
n
|
||||||
|
};
|
||||||
|
// if names == null {
|
||||||
|
|
||||||
|
// }
|
||||||
|
let nicknames = if let Some(nicknameString) =
|
||||||
|
matchSingleVCardPrefixedField("NICKNAME", &rawText, true, false)
|
||||||
|
{
|
||||||
|
nicknameString[0]
|
||||||
|
.split(COMMA)
|
||||||
|
.map(|x| x.to_owned())
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
// COMMA.split(nicknameString.get(0)
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
// let nicknames = nicknameString == null ? null : COMMA.split(nicknameString.get(0));
|
||||||
|
let phoneNumbers = matchVCardPrefixedField("TEL", &rawText, true, false);
|
||||||
|
let emails = matchVCardPrefixedField("EMAIL", &rawText, true, false);
|
||||||
|
let note = matchSingleVCardPrefixedField("NOTE", &rawText, false, false);
|
||||||
|
let addresses = matchVCardPrefixedField("ADR", &rawText, true, true);
|
||||||
|
let org = matchSingleVCardPrefixedField("ORG", &rawText, true, true);
|
||||||
|
let birthday =
|
||||||
|
if let Some(bday_array) = matchSingleVCardPrefixedField("BDAY", &rawText, true, false) {
|
||||||
|
if isLikeVCardDate(&bday_array[0]) {
|
||||||
|
bday_array
|
||||||
|
} else {
|
||||||
|
vec!["".to_owned()]
|
||||||
}
|
}
|
||||||
List<String> nicknameString = matchSingleVCardPrefixedField("NICKNAME", rawText, true, false);
|
} else {
|
||||||
String[] nicknames = nicknameString == null ? null : COMMA.split(nicknameString.get(0));
|
vec!["".to_owned()]
|
||||||
List<List<String>> phoneNumbers = matchVCardPrefixedField("TEL", rawText, true, false);
|
};
|
||||||
List<List<String>> emails = matchVCardPrefixedField("EMAIL", rawText, true, false);
|
// if birthday != null && !isLikeVCardDate(birthday.get(0)) {
|
||||||
List<String> note = matchSingleVCardPrefixedField("NOTE", rawText, false, false);
|
// birthday = null;
|
||||||
List<List<String>> addresses = matchVCardPrefixedField("ADR", rawText, true, true);
|
// }
|
||||||
List<String> org = matchSingleVCardPrefixedField("ORG", rawText, true, true);
|
let title = matchSingleVCardPrefixedField("TITLE", &rawText, true, false);
|
||||||
List<String> birthday = matchSingleVCardPrefixedField("BDAY", rawText, true, false);
|
let urls = matchVCardPrefixedField("URL", &rawText, true, false);
|
||||||
if (birthday != null && !isLikeVCardDate(birthday.get(0))) {
|
let instantMessenger = matchSingleVCardPrefixedField("IMPP", &rawText, true, false);
|
||||||
birthday = null;
|
let geoString = matchSingleVCardPrefixedField("GEO", &rawText, true, false);
|
||||||
}
|
let geo = if geoString.is_none() {
|
||||||
List<String> title = matchSingleVCardPrefixedField("TITLE", rawText, true, false);
|
Vec::new()
|
||||||
List<List<String>> urls = matchVCardPrefixedField("URL", rawText, true, false);
|
} else {
|
||||||
List<String> instantMessenger = matchSingleVCardPrefixedField("IMPP", rawText, true, false);
|
semicolon_comma_regex
|
||||||
List<String> geoString = matchSingleVCardPrefixedField("GEO", rawText, true, false);
|
.split(&geoString.unwrap()[0])
|
||||||
String[] geo = geoString == null ? null : SEMICOLON_OR_COMMA.split(geoString.get(0));
|
.map(|x| x.to_owned())
|
||||||
if (geo != null && geo.length != 2) {
|
.collect()
|
||||||
geo = null;
|
// SEMICOLON_OR_COMMA.split(geoString.unwrap()[0])
|
||||||
}
|
};
|
||||||
return new AddressBookParsedRXingResult(toPrimaryValues(names),
|
// if geo.len() != 2 {
|
||||||
|
// geo = null;
|
||||||
|
// }
|
||||||
|
if let Ok(adb) = AddressBookParsedRXingResult::with_details(
|
||||||
|
toPrimaryValues(Some(names))?,
|
||||||
nicknames,
|
nicknames,
|
||||||
null,
|
"".to_owned(),
|
||||||
toPrimaryValues(phoneNumbers),
|
toPrimaryValues(phoneNumbers.clone())?,
|
||||||
toTypes(phoneNumbers),
|
toTypes(phoneNumbers)?,
|
||||||
toPrimaryValues(emails),
|
toPrimaryValues(emails.clone())?,
|
||||||
toTypes(emails),
|
toTypes(emails)?,
|
||||||
toPrimaryValue(instantMessenger),
|
toPrimaryValue(instantMessenger),
|
||||||
toPrimaryValue(note),
|
toPrimaryValue(note),
|
||||||
toPrimaryValues(addresses),
|
toPrimaryValues(addresses.clone())?,
|
||||||
toTypes(addresses),
|
toTypes(addresses)?,
|
||||||
toPrimaryValue(org),
|
toPrimaryValue(org),
|
||||||
toPrimaryValue(birthday),
|
toPrimaryValue(Some(birthday)),
|
||||||
toPrimaryValue(title),
|
toPrimaryValue(title),
|
||||||
toPrimaryValues(urls),
|
toPrimaryValues(urls)?,
|
||||||
geo);
|
geo,
|
||||||
|
) {
|
||||||
|
Some(ParsedClientResult::AddressBookResult(adb))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn matchVCardPrefixedField( prefix:&str,
|
fn matchVCardPrefixedField(
|
||||||
rawText:&str,
|
prefix: &str,
|
||||||
trim:bool,
|
rawText: &str,
|
||||||
parseFieldDivider:bool) -> Vec<String> {
|
trim: bool,
|
||||||
List<List<String>> matches = null;
|
parseFieldDivider: bool,
|
||||||
int i = 0;
|
) -> Option<Vec<Vec<String>>> {
|
||||||
int max = rawText.length();
|
let mut matches: Vec<Vec<String>> = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
let max = rawText.len();
|
||||||
|
|
||||||
while (i < max) {
|
let equals_regex = Regex::new(EQUALS).unwrap();
|
||||||
|
let unescaped_semis = Regex::new(UNESCAPED_SEMICOLONS).unwrap();
|
||||||
|
let cr_lf_space_tab = Regex::new(CR_LF_SPACE_TAB).unwrap();
|
||||||
|
let newline_esc = Regex::new(NEWLINE_ESCAPE).unwrap();
|
||||||
|
let vcard_esc = Regex::new(VCARD_ESCAPES).unwrap();
|
||||||
|
|
||||||
// At start or after newline, match prefix, followed by optional metadata
|
// At start or after newline, match prefix, followed by optional metadata
|
||||||
// (led by ;) ultimately ending in colon
|
// (led by ;) ultimately ending in colon
|
||||||
Matcher matcher = Pattern.compile("(?:^|\n)" + prefix + "(?:;([^:]*))?:",
|
let matcher_primary = Regex::new(&format!("(?:^|\n){}(?:;([^:]*))?:", prefix)).unwrap();
|
||||||
Pattern.CASE_INSENSITIVE).matcher(rawText);
|
let lower_case_raw_text = rawText.to_lowercase();
|
||||||
if (i > 0) {
|
|
||||||
i--; // Find from i-1 not i since looking at the preceding character
|
while i < max {
|
||||||
|
//let rawText = rawText.to_lowercase();
|
||||||
|
// Pattern.CASE_INSENSITIVE).matcher(rawText);
|
||||||
|
if i > 0 {
|
||||||
|
i -= 1; // Find from i-1 not i since looking at the preceding character
|
||||||
}
|
}
|
||||||
if (!matcher.find(i)) {
|
let cap_maybe = matcher_primary.captures(&lower_case_raw_text[i..]);
|
||||||
|
//let matcher_maybe = matcher_primary.find_at(&lower_case_raw_text, i);
|
||||||
|
if cap_maybe.is_none() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
i = matcher.end(0); // group 0 = whole pattern; end(0) is past final colon
|
let matcher = cap_maybe?;
|
||||||
|
i = matcher.get(0)?.end(); // group 0 = whole pattern; end(0) is past final colon
|
||||||
|
|
||||||
String metadataString = matcher.group(1); // group 1 = metadata substring
|
let metadataString = matcher.get(1); // group 1 = metadata substring
|
||||||
List<String> metadata = null;
|
let mut metadata: Vec<String> = Vec::new();
|
||||||
boolean quotedPrintable = false;
|
let mut quotedPrintable = false;
|
||||||
String quotedPrintableCharset = null;
|
let mut quotedPrintableCharset = "";
|
||||||
String valueType = null;
|
let mut valueType = "";
|
||||||
if (metadataString != null) {
|
if metadataString.is_some() {
|
||||||
for (String metadatum : SEMICOLON.split(metadataString)) {
|
// let mds = metadataString?.as_str().split(SEMICOLON).collect();
|
||||||
if (metadata == null) {
|
for metadatum in metadataString?.as_str().split(SEMICOLON) {
|
||||||
metadata = new ArrayList<>(1);
|
// for (String metadatum : SEMICOLON.split(metadataString)) {
|
||||||
}
|
// if (metadata == null) {
|
||||||
metadata.add(metadatum);
|
// metadata = new ArrayList<>(1);
|
||||||
String[] metadatumTokens = EQUALS.split(metadatum, 2);
|
// }
|
||||||
if (metadatumTokens.length > 1) {
|
metadata.push(metadatum.to_owned());
|
||||||
String key = metadatumTokens[0];
|
|
||||||
String value = metadatumTokens[1];
|
let metadatumTokens = equals_regex.splitn(metadatum, 2).collect::<Vec<&str>>();
|
||||||
if ("ENCODING".equalsIgnoreCase(key) && "QUOTED-PRINTABLE".equalsIgnoreCase(value)) {
|
if metadatumTokens.len() > 1 {
|
||||||
|
let key = metadatumTokens[0];
|
||||||
|
let value = metadatumTokens[1];
|
||||||
|
if "ENCODING" == key.to_uppercase()
|
||||||
|
&& "QUOTED-PRINTABLE" == value.to_uppercase()
|
||||||
|
{
|
||||||
quotedPrintable = true;
|
quotedPrintable = true;
|
||||||
} else if ("CHARSET".equalsIgnoreCase(key)) {
|
} else if "CHARSET" == key.to_uppercase() {
|
||||||
quotedPrintableCharset = value;
|
quotedPrintableCharset = value;
|
||||||
} else if ("VALUE".equalsIgnoreCase(key)) {
|
} else if "VALUE" == key.to_uppercase() {
|
||||||
valueType = value;
|
valueType = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int matchStart = i; // Found the start of a match here
|
let matchStart = i; // Found the start of a match here
|
||||||
|
while let Some(pos) = rawText[i..].find('\n') {
|
||||||
while ((i = rawText.indexOf('\n', i)) >= 0) { // Really, end in \r\n
|
// Really, end in \r\n
|
||||||
if (i < rawText.length() - 1 && // But if followed by tab or space,
|
i = pos;
|
||||||
(rawText.charAt(i + 1) == ' ' || // this is only a continuation
|
// while (i = rawText.indexOf('\n', i)) >= 0 { // Really, end in \r\n
|
||||||
rawText.charAt(i + 1) == '\t')) {
|
if i < rawText.len() - 1 && // But if followed by tab or space,
|
||||||
|
(rawText.chars().nth(i + 1)? == ' ' || // this is only a continuation
|
||||||
|
rawText.chars().nth(i + 1)? == '\t')
|
||||||
|
{
|
||||||
i += 2; // Skip \n and continutation whitespace
|
i += 2; // Skip \n and continutation whitespace
|
||||||
} else if (quotedPrintable && // If preceded by = in quoted printable
|
} else if quotedPrintable && // If preceded by = in quoted printable
|
||||||
((i >= 1 && rawText.charAt(i - 1) == '=') || // this is a continuation
|
((i >= 1 && rawText.chars().nth(i - 1)? == '=') || // this is a continuation
|
||||||
(i >= 2 && rawText.charAt(i - 2) == '='))) {
|
(i >= 2 && rawText.chars().nth(i - 2)? == '='))
|
||||||
i++; // Skip \n
|
{
|
||||||
|
i += 1; // Skip \n
|
||||||
} else {
|
} else {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (i < 0) {
|
if i < 0 {
|
||||||
// No terminating end character? uh, done. Set i such that loop terminates and break
|
// No terminating end character? uh, done. Set i such that loop terminates and break
|
||||||
i = max;
|
i = max;
|
||||||
} else if (i > matchStart) {
|
} else if i > matchStart {
|
||||||
// found a match
|
// found a match
|
||||||
if (matches == null) {
|
// if matches == null {
|
||||||
matches = new ArrayList<>(1); // lazy init
|
// matches = new ArrayList<>(1); // lazy init
|
||||||
|
// }
|
||||||
|
if i >= 1 && rawText.chars().nth(i - 1)? == '\r' {
|
||||||
|
i -= 1; // Back up over \r, which really should be there
|
||||||
}
|
}
|
||||||
if (i >= 1 && rawText.charAt(i - 1) == '\r') {
|
let mut element = rawText[matchStart..i].to_owned();
|
||||||
i--; // Back up over \r, which really should be there
|
if trim {
|
||||||
|
element = element.trim().to_owned();
|
||||||
}
|
}
|
||||||
String element = rawText.substring(matchStart, i);
|
|
||||||
if (trim) {
|
if quotedPrintable {
|
||||||
element = element.trim();
|
element = decodeQuotedPrintable(&element, quotedPrintableCharset);
|
||||||
}
|
if parseFieldDivider {
|
||||||
if (quotedPrintable) {
|
element = unescaped_semis
|
||||||
element = decodeQuotedPrintable(element, quotedPrintableCharset);
|
.replace_all(&element, "\n")
|
||||||
if (parseFieldDivider) {
|
.to_mut()
|
||||||
element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim();
|
.trim()
|
||||||
|
.to_owned();
|
||||||
|
// element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (parseFieldDivider) {
|
if parseFieldDivider {
|
||||||
element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim();
|
element = unescaped_semis
|
||||||
|
.replace_all(&element, "\n")
|
||||||
|
.to_mut()
|
||||||
|
.trim()
|
||||||
|
.to_owned();
|
||||||
|
// element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim();
|
||||||
}
|
}
|
||||||
element = CR_LF_SPACE_TAB.matcher(element).replaceAll("");
|
element = cr_lf_space_tab
|
||||||
element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n");
|
.replace_all(&element, "")
|
||||||
element = VCARD_ESCAPES.matcher(element).replaceAll("$1");
|
.to_mut()
|
||||||
|
.to_owned();
|
||||||
|
element = newline_esc.replace_all(&element, "\n").to_mut().to_owned();
|
||||||
|
element = vcard_esc.replace_all(&element, "$1").to_mut().to_owned();
|
||||||
|
// element = CR_LF_SPACE_TAB.matcher(element).replaceAll("");
|
||||||
|
// element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n");
|
||||||
|
// element = VCARD_ESCAPES.matcher(element).replaceAll("$1");
|
||||||
}
|
}
|
||||||
// Only handle VALUE=uri specially
|
// Only handle VALUE=uri specially
|
||||||
if ("uri".equals(valueType)) {
|
if "uri" == valueType.to_lowercase() {
|
||||||
// Don't actually support dereferencing URIs, but use scheme-specific part not URI
|
// Don't actually support dereferencing URIs, but use scheme-specific part not URI
|
||||||
// as value, to support tel: and mailto:
|
// as value, to support tel: and mailto:
|
||||||
try {
|
if let Ok(uri) = URI::try_from(element.as_str()) {
|
||||||
element = URI.create(element).getSchemeSpecificPart();
|
element = uri.scheme().to_string();
|
||||||
} catch (IllegalArgumentException iae) {
|
|
||||||
// ignore
|
|
||||||
}
|
}
|
||||||
|
// try {
|
||||||
|
// element = URI.create(element).getSchemeSpecificPart();
|
||||||
|
// } catch (IllegalArgumentException iae) {
|
||||||
|
// // ignore
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
if (metadata == null) {
|
// if metadata == null {
|
||||||
List<String> match = new ArrayList<>(1);
|
// List<String> match = new ArrayList<>(1);
|
||||||
match.add(element);
|
// match.add(element);
|
||||||
matches.add(match);
|
// matches.add(match);
|
||||||
|
// } else {
|
||||||
|
metadata.push(element);
|
||||||
|
matches.push(metadata.into_iter().map(|s| s.to_owned()).collect());
|
||||||
|
// }
|
||||||
|
i += 1;
|
||||||
} else {
|
} else {
|
||||||
metadata.add(0, element);
|
i += 1;
|
||||||
matches.add(metadata);
|
|
||||||
}
|
}
|
||||||
i++;
|
|
||||||
} else {
|
|
||||||
i++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
Some(matches)
|
||||||
|
}
|
||||||
|
|
||||||
return matches;
|
fn decodeQuotedPrintable(value: &str, charset: &str) -> String {
|
||||||
}
|
let length = value.len();
|
||||||
|
let mut result = String::with_capacity(length);
|
||||||
fn decodeQuotedPrintable( value:&str, charset:&str) -> String{
|
let mut fragmentBuffer: Vec<u8> = Vec::new(); //new ByteArrayOutputStream();
|
||||||
int length = value.length();
|
let mut i = 0;
|
||||||
StringBuilder result = new StringBuilder(length);
|
// for i in 0..length {
|
||||||
ByteArrayOutputStream fragmentBuffer = new ByteArrayOutputStream();
|
while i < length {
|
||||||
for (int i = 0; i < length; i++) {
|
// for (int i = 0; i < length; i++) {
|
||||||
char c = value.charAt(i);
|
let c = value.chars().nth(i).unwrap_or_default();
|
||||||
switch (c) {
|
match c {
|
||||||
case '\r':
|
'\r' | '\n' => break,
|
||||||
case '\n':
|
'=' if i < length - 2 => {
|
||||||
break;
|
let nextChar = value.chars().nth(i + 1).unwrap();
|
||||||
case '=':
|
if nextChar != '\r' && nextChar != '\n' {
|
||||||
if (i < length - 2) {
|
let nextNextChar = value.chars().nth(i + 2).unwrap();
|
||||||
char nextChar = value.charAt(i + 1);
|
let firstDigit = ResultParser::parseHexDigit(nextChar);
|
||||||
if (nextChar != '\r' && nextChar != '\n') {
|
let secondDigit = ResultParser::parseHexDigit(nextNextChar);
|
||||||
char nextNextChar = value.charAt(i + 2);
|
if firstDigit >= 0 && secondDigit >= 0 {
|
||||||
int firstDigit = parseHexDigit(nextChar);
|
fragmentBuffer.push(((firstDigit << 4) + secondDigit) as u8);
|
||||||
int secondDigit = parseHexDigit(nextNextChar);
|
|
||||||
if (firstDigit >= 0 && secondDigit >= 0) {
|
|
||||||
fragmentBuffer.write((firstDigit << 4) + secondDigit);
|
|
||||||
} // else ignore it, assume it was incorrectly encoded
|
} // else ignore it, assume it was incorrectly encoded
|
||||||
i += 2;
|
i += 2;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
default:
|
}
|
||||||
maybeAppendFragment(fragmentBuffer, charset, result);
|
_ => {
|
||||||
result.append(c);
|
maybeAppendFragment(&mut fragmentBuffer, charset, &mut result);
|
||||||
|
result.push(c);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
maybeAppendFragment(fragmentBuffer, charset, result);
|
// switch (c) {
|
||||||
return result.toString();
|
// case '\r':
|
||||||
|
// case '\n':
|
||||||
|
// break;
|
||||||
|
// case '=':
|
||||||
|
// if (i < length - 2) {
|
||||||
|
// char nextChar = value.charAt(i + 1);
|
||||||
|
// if (nextChar != '\r' && nextChar != '\n') {
|
||||||
|
// char nextNextChar = value.charAt(i + 2);
|
||||||
|
// int firstDigit = parseHexDigit(nextChar);
|
||||||
|
// int secondDigit = parseHexDigit(nextNextChar);
|
||||||
|
// if (firstDigit >= 0 && secondDigit >= 0) {
|
||||||
|
// fragmentBuffer.write((firstDigit << 4) + secondDigit);
|
||||||
|
// } // else ignore it, assume it was incorrectly encoded
|
||||||
|
// i += 2;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// break;
|
||||||
|
// default:
|
||||||
|
// maybeAppendFragment(fragmentBuffer, charset, result);
|
||||||
|
// result.append(c);
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
maybeAppendFragment(&mut fragmentBuffer, charset, &mut result);
|
||||||
|
|
||||||
fn maybeAppendFragment( fragmentBuffer &Vec<u8>,
|
result
|
||||||
charset:&str,
|
}
|
||||||
result:&mut String) {
|
|
||||||
if (fragmentBuffer.size() > 0) {
|
fn maybeAppendFragment(fragmentBuffer: &mut Vec<u8>, charset: &str, result: &mut String) {
|
||||||
byte[] fragmentBytes = fragmentBuffer.toByteArray();
|
if fragmentBuffer.len() > 0 {
|
||||||
String fragment;
|
let fragmentBytes = fragmentBuffer.clone();
|
||||||
if (charset == null) {
|
let fragment;
|
||||||
fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
|
if charset.is_empty() {
|
||||||
|
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned());
|
||||||
|
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
|
||||||
} else {
|
} else {
|
||||||
try {
|
if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) {
|
||||||
fragment = new String(fragmentBytes, charset);
|
fragment = if let Ok(encoded_result) =
|
||||||
} catch (UnsupportedEncodingException e) {
|
enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict)
|
||||||
fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
|
{
|
||||||
|
encoded_result
|
||||||
|
} else {
|
||||||
|
String::from_utf8(fragmentBytes).unwrap_or("".to_owned())
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned())
|
||||||
|
}
|
||||||
|
// try {
|
||||||
|
// fragment = new String(fragmentBytes, charset);
|
||||||
|
// } catch (UnsupportedEncodingException e) {
|
||||||
|
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
fragmentBuffer.clear();
|
||||||
|
result.push_str(&fragment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matchSingleVCardPrefixedField(
|
||||||
|
prefix: &str,
|
||||||
|
rawText: &str,
|
||||||
|
trim: bool,
|
||||||
|
parseFieldDivider: bool,
|
||||||
|
) -> Option<Vec<String>> {
|
||||||
|
let values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider)?;
|
||||||
|
if values.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(values.get(0)?.clone())
|
||||||
|
// return values == null || values.isEmpty() ? null : values.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn toPrimaryValue(list: Option<Vec<String>>) -> String {
|
||||||
|
if let Some(l) = list {
|
||||||
|
if l.is_empty() {
|
||||||
|
"".to_owned()
|
||||||
|
} else {
|
||||||
|
l.get(0).unwrap_or(&"".to_owned()).clone()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
"".to_owned()
|
||||||
|
}
|
||||||
|
// if list.is_empty() {
|
||||||
|
// "".to_owned()
|
||||||
|
// }else {
|
||||||
|
// *list.get(0).unwrap_or(&"".to_owned())
|
||||||
|
// }
|
||||||
|
// return list == null || list.isEmpty() ? null : list.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn toPrimaryValues(lists: Option<Vec<Vec<String>>>) -> Option<Vec<String>> {
|
||||||
|
let local_lists = lists?;
|
||||||
|
if local_lists.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut result = vec!["".to_owned(); local_lists.len()]; // new ArrayList<>(lists.size());
|
||||||
|
for list in local_lists {
|
||||||
|
// for (List<String> list : lists) {
|
||||||
|
if let Some(value) = list.get(0) {
|
||||||
|
if !value.is_empty() {
|
||||||
|
result.push(value.clone());
|
||||||
}
|
}
|
||||||
fragmentBuffer.reset();
|
|
||||||
result.append(fragment);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn matchSingleVCardPrefixedField( prefix:&str,
|
Some(result)
|
||||||
rawText:&str,
|
}
|
||||||
trim :bool,
|
|
||||||
parseFieldDivider:bool)->Vec<String> {
|
|
||||||
List<List<String>> values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider);
|
|
||||||
return values == null || values.isEmpty() ? null : values.get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn toPrimaryValue(list:&Vec<String>) -> String{
|
fn toTypes(lists: Option<Vec<Vec<String>>>) -> Option<Vec<String>> {
|
||||||
return list == null || list.isEmpty() ? null : list.get(0);
|
let local_lists = lists?;
|
||||||
|
if local_lists.is_empty() {
|
||||||
|
return None;
|
||||||
}
|
}
|
||||||
|
let mut result = vec!["".to_owned(); local_lists.len()]; //new ArrayList<>(lists.size());
|
||||||
fn toPrimaryValues( lists:&Vec<String>) -> Vec<String>{
|
for list in local_lists {
|
||||||
if (lists == null || lists.isEmpty()) {
|
// for (List<String> list : lists) {
|
||||||
return null;
|
if let Some(value) = list.get(0) {
|
||||||
|
if !value.is_empty() {
|
||||||
|
let mut v_type = String::new();
|
||||||
|
for i in 0..list.len() {
|
||||||
|
// for (int i = 1; i < list.size(); i++) {
|
||||||
|
let metadatum = list.get(i)?;
|
||||||
|
if let Some(equals) = metadatum.find('=') {
|
||||||
|
if "TYPE" == (metadatum[0..equals]).to_uppercase() {
|
||||||
|
v_type = metadatum[equals + 1..].to_owned();
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
List<String> result = new ArrayList<>(lists.size());
|
} else {
|
||||||
for (List<String> list : lists) {
|
// if (equals < 0) {
|
||||||
String value = list.get(0);
|
|
||||||
if (value != null && !value.isEmpty()) {
|
|
||||||
result.add(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result.toArray(EMPTY_STR_ARRAY);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn toTypes( lists: &Vec<String>) -> Vec<String>{
|
|
||||||
if (lists == null || lists.isEmpty()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
List<String> result = new ArrayList<>(lists.size());
|
|
||||||
for (List<String> list : lists) {
|
|
||||||
String value = list.get(0);
|
|
||||||
if (value != null && !value.isEmpty()) {
|
|
||||||
String type = null;
|
|
||||||
for (int i = 1; i < list.size(); i++) {
|
|
||||||
String metadatum = list.get(i);
|
|
||||||
int equals = metadatum.indexOf('=');
|
|
||||||
if (equals < 0) {
|
|
||||||
// take the whole thing as a usable label
|
// take the whole thing as a usable label
|
||||||
type = metadatum;
|
v_type = metadatum.to_owned();
|
||||||
break;
|
|
||||||
}
|
|
||||||
if ("TYPE".equalsIgnoreCase(metadatum.substring(0, equals))) {
|
|
||||||
type = metadatum.substring(equals + 1);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result.add(type);
|
result.push(v_type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result.toArray(EMPTY_STR_ARRAY);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn isLikeVCardDate( value:&str) -> bool{
|
Some(result)
|
||||||
return value == null || VCARD_LIKE_DATE.matcher(value).matches();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
fn isLikeVCardDate(value: &str) -> bool {
|
||||||
|
let rg = Regex::new(VCARD_LIKE_DATE).unwrap();
|
||||||
|
let matches = if let Some(mtch) = rg.find(value) {
|
||||||
|
mtch.start() == 0 && mtch.end() == value.len()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
|
||||||
|
value.is_empty() || matches
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
* Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like
|
* Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like
|
||||||
* "Reverend John Q. Public III".
|
* "Reverend John Q. Public III".
|
||||||
*
|
*
|
||||||
* @param names name values to format, in place
|
* @param names name values to format, in place
|
||||||
*/
|
*/
|
||||||
fn formatNames( names : &mut Vec<String>) {
|
fn formatNames(names: &mut Vec<Vec<String>>) {
|
||||||
if !names.is_empty() {
|
if !names.is_empty() {
|
||||||
for list in names {
|
for list in names {
|
||||||
// for (List<String> list : names) {
|
// for (List<String> list : names) {
|
||||||
let name = list.get(0);
|
let name = list.get(0).unwrap_or(&"".to_owned()).clone();
|
||||||
let components = vec!["";5];
|
let mut components = vec!["".to_owned(); 5];
|
||||||
let start = 0;
|
let mut start = 0;
|
||||||
let end;
|
let mut end = 0;
|
||||||
let componentIndex = 0;
|
let mut componentIndex = 0;
|
||||||
while componentIndex < components.len() - 1 && (end = name.indexOf(';', start)) >= 0 {
|
while componentIndex < components.len() - 1 && end >= 0 {
|
||||||
components[componentIndex] = name.substring(start, end);
|
end = if let Some(pos) = name[start..].find(';') {
|
||||||
componentIndex+=1;
|
pos + start
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
components[componentIndex] = name[start..end].to_owned();
|
||||||
|
componentIndex += 1;
|
||||||
start = end + 1;
|
start = end + 1;
|
||||||
}
|
}
|
||||||
components[componentIndex] = name.substring(start);
|
components[componentIndex] = name[start..].to_owned();
|
||||||
let newName = String::with_capacity(100);
|
let mut newName = String::with_capacity(100);
|
||||||
maybeAppendComponent(components, 3, newName);
|
maybeAppendComponent(&components, 3, &mut newName);
|
||||||
maybeAppendComponent(components, 1, newName);
|
maybeAppendComponent(&components, 1, &mut newName);
|
||||||
maybeAppendComponent(components, 2, newName);
|
maybeAppendComponent(&components, 2, &mut newName);
|
||||||
maybeAppendComponent(components, 0, newName);
|
maybeAppendComponent(&components, 0, &mut newName);
|
||||||
maybeAppendComponent(components, 4, newName);
|
maybeAppendComponent(&components, 4, &mut newName);
|
||||||
list.set(0, newName.toString().trim());
|
list[0] = newName.trim().to_owned();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn maybeAppendComponent( components : &Vec<String>, i:usize, newName:&mut String) {
|
fn maybeAppendComponent(components: &Vec<String>, i: usize, newName: &mut String) {
|
||||||
if !components[i].is_empty() {
|
if !components[i].is_empty() {
|
||||||
if newName.len() > 0 {
|
if newName.len() > 0 {
|
||||||
newName.push(' ');
|
newName.push(' ');
|
||||||
}
|
}
|
||||||
newName.push_str(&components[i]);
|
newName.push_str(&components[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user