cargo fmt

This commit is contained in:
Henry Schimke
2022-10-17 10:51:08 -05:00
parent 111fe47566
commit ae11af8c5b
136 changed files with 2117 additions and 1776 deletions

View File

@@ -1 +1 @@
pub mod result;
pub mod result;

View File

@@ -13,7 +13,6 @@
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
// package com.google.zxing.client.result;
// /**

View File

@@ -62,7 +62,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
Vec::new()
},
Vec::new(),
pronunciation.unwrap_or_default(),//"".to_owned(),
pronunciation.unwrap_or_default(), //"".to_owned(),
phoneNumbers,
Vec::new(),
emails, //Vec::new(),

View File

@@ -117,17 +117,17 @@ impl AddressBookParsedRXingResult {
urls: Vec<String>,
geo: Vec<String>,
) -> Result<Self, Exceptions> {
if phone_numbers.len() != phone_types.len() && phone_types.len() > 0{
if phone_numbers.len() != phone_types.len() && phone_types.len() > 0 {
return Err(Exceptions::IllegalArgumentException(
"Phone numbers and types lengths differ".to_owned(),
));
}
if emails.len() != email_types.len() && email_types.len() > 0{
if emails.len() != email_types.len() && email_types.len() > 0 {
return Err(Exceptions::IllegalArgumentException(
"Emails and types lengths differ".to_owned(),
));
}
if addresses.len() != address_types.len() && address_types.len() > 0{
if addresses.len() != address_types.len() && address_types.len() > 0 {
return Err(Exceptions::IllegalArgumentException(
"Addresses and types lengths differ".to_owned(),
));

View File

@@ -46,8 +46,10 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let lastName = ResultParser::match_single_do_co_mo_prefixed_field("X:", &rawText, true)
.unwrap_or_default();
let fullName = buildName(&firstName, &lastName);
let title = ResultParser::match_single_do_co_mo_prefixed_field("T:", &rawText, true).unwrap_or_default();
let org = ResultParser::match_single_do_co_mo_prefixed_field("C:", &rawText, true).unwrap_or_default();
let title = ResultParser::match_single_do_co_mo_prefixed_field("T:", &rawText, true)
.unwrap_or_default();
let org = ResultParser::match_single_do_co_mo_prefixed_field("C:", &rawText, true)
.unwrap_or_default();
let addresses = ResultParser::match_do_co_mo_prefixed_field("A:", &rawText);
let phoneNumber1 = ResultParser::match_single_do_co_mo_prefixed_field("B:", &rawText, true)
.unwrap_or_default();

View File

@@ -20,9 +20,7 @@
use crate::RXingResult;
use super::{
ParsedClientResult, ResultParser, URIParsedRXingResult, URIResultParser,
};
use super::{ParsedClientResult, ResultParser, URIParsedRXingResult, URIResultParser};
/**
* @author Sean Owen
@@ -40,7 +38,8 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let uri = rawUri?[0].clone();
if URIResultParser::is_basically_valid_uri(&uri) {
Some(ParsedClientResult::URIResult(URIParsedRXingResult::new(
uri, title.unwrap_or("".to_owned()),
uri,
title.unwrap_or("".to_owned()),
)))
} else {
None

View File

@@ -27,16 +27,14 @@
// import java.util.regex.Matcher;
// import java.util.regex.Pattern;
use chrono::{ DateTime, NaiveDateTime, TimeZone, Utc};
use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use chrono_tz::Tz;
use regex::Regex;
use lazy_static::lazy_static;
use regex::Regex;
use crate::exceptions::Exceptions;
use super::{
maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType
};
use super::{maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType};
// const RFC2445_DURATION: &'static str =
// "P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?";
@@ -49,8 +47,9 @@ const RFC2445_DURATION_FIELD_UNITS: [i64; 5] = [
];
lazy_static! {
static ref DATE_TIME : Regex = Regex::new("[0-9]{8}(T[0-9]{6}Z?)?").unwrap();
static ref RFC2445_DURATION: Regex = Regex::new("P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?").unwrap();
static ref DATE_TIME: Regex = Regex::new("[0-9]{8}(T[0-9]{6}Z?)?").unwrap();
static ref RFC2445_DURATION: Regex =
Regex::new("P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?").unwrap();
}
// const DATE_TIME: &'static str = "[0-9]{8}(T[0-9]{6}Z?)?";

View File

@@ -34,7 +34,7 @@
// */
// public final class CalendarParsedRXingResultTestCase extends Assert {
use chrono::{NaiveDateTime};
use chrono::NaiveDateTime;
use crate::{
client::result::{ParsedClientResult, ParsedRXingResultType},

View File

@@ -16,7 +16,7 @@
// package com.google.zxing.client.result;
use super::{ ParsedRXingResult, ParsedRXingResultType, ResultParser};
use super::{ParsedRXingResult, ParsedRXingResultType, ResultParser};
/**
* Represents a parsed result that encodes an email message including recipients, subject

View File

@@ -22,7 +22,7 @@
// import org.junit.Test;
use crate::{
client::result::{ParsedClientResult, ParsedRXingResultType, ResultParser, ParsedRXingResult},
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType, ResultParser},
BarcodeFormat, RXingResult,
};

View File

@@ -27,11 +27,14 @@ use crate::RXingResult;
use lazy_static::lazy_static;
lazy_static! {
static ref COMMA :Regex = Regex::new(",").unwrap();
static ref ATEXT_ALPHANUMERIC:Regex = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
static ref COMMA: Regex = Regex::new(",").unwrap();
static ref ATEXT_ALPHANUMERIC: Regex =
Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
}
use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddressParsedRXingResult};
use super::{
EmailAddressParsedRXingResult, EmailDoCoMoResultParser, ParsedClientResult, ResultParser,
};
/**
* Represents a result that encodes an e-mail address, either as a plain address
@@ -39,74 +42,100 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr
*
* @author Sean Owen
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// let comma_regex = Regex::new(",").unwrap();
// private static final Pattern COMMA = Pattern.compile(",");
let rawText = ResultParser::getMassagedText(result);
if rawText.starts_with("mailto:") || rawText.starts_with("MAILTO:") {
// If it starts with mailto:, assume it is definitely trying to be an email address
let mut hostEmail = &rawText[7..];
if let Some(queryStart) = hostEmail.find('?'){
hostEmail = &hostEmail[..queryStart];
}
// int queryStart = hostEmail.indexOf('?');
// if (queryStart >= 0) {
// hostEmail = hostEmail.substring(0, queryStart);
// }
// try {
let tmp = if let Ok(res) = ResultParser::urlDecode(hostEmail){
res
}else {
return None;
// If it starts with mailto:, assume it is definitely trying to be an email address
let mut hostEmail = &rawText[7..];
if let Some(queryStart) = hostEmail.find('?') {
hostEmail = &hostEmail[..queryStart];
}
// int queryStart = hostEmail.indexOf('?');
// if (queryStart >= 0) {
// hostEmail = hostEmail.substring(0, queryStart);
// }
// try {
let tmp = if let Ok(res) = ResultParser::urlDecode(hostEmail) {
res
} else {
return None;
};
hostEmail = tmp.as_str();
// } catch (IllegalArgumentException iae) {
// return null;
// }
let mut tos = if hostEmail.is_empty() {
Vec::new()
}else {
COMMA.split(hostEmail).into_iter().map(|s| s.to_owned()).collect()
};
// if (!hostEmail.isEmpty()) {
// tos = COMMA.split(hostEmail);
// }
let nameValues = ResultParser::parseNameValuePairs(&rawText);
let mut ccs:Vec<String> = Vec::new();
let mut bccs:Vec<String> = Vec::new();
let mut subject = "".to_owned();
let mut body = "".to_owned();
if let Some(nv) = nameValues {
// if (nameValues != null) {
if tos.is_empty() {
if let Some(tosString) = nv.get("to"){
tos = COMMA.split(tosString).into_iter().map(|s| s.to_owned()).collect();
}
// if tosString != null {
// tos = COMMA.split(tosString);
// }
}
if let Some(ccString) = nv.get("cc"){
ccs = COMMA.split(ccString).into_iter().map(|s| s.to_owned()).collect();
}
// if ccString != null {
// ccs = COMMA.split(ccString);
// } catch (IllegalArgumentException iae) {
// return null;
// }
if let Some(bccString) = nv.get("bcc"){
bccs = COMMA.split(bccString).into_iter().map(|s| s.to_owned()).collect();
}
// if bccString != null {
// bccs = COMMA.split(bccString);
let mut tos = if hostEmail.is_empty() {
Vec::new()
} else {
COMMA
.split(hostEmail)
.into_iter()
.map(|s| s.to_owned())
.collect()
};
// if (!hostEmail.isEmpty()) {
// tos = COMMA.split(hostEmail);
// }
subject = nv.get("subject").unwrap_or(&"".to_owned()).clone();
body = nv.get("body").unwrap_or(&"".to_owned()).clone();
}
return Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(tos, ccs, bccs, subject.to_owned(), body.to_owned())));
let nameValues = ResultParser::parseNameValuePairs(&rawText);
let mut ccs: Vec<String> = Vec::new();
let mut bccs: Vec<String> = Vec::new();
let mut subject = "".to_owned();
let mut body = "".to_owned();
if let Some(nv) = nameValues {
// if (nameValues != null) {
if tos.is_empty() {
if let Some(tosString) = nv.get("to") {
tos = COMMA
.split(tosString)
.into_iter()
.map(|s| s.to_owned())
.collect();
}
// if tosString != null {
// tos = COMMA.split(tosString);
// }
}
if let Some(ccString) = nv.get("cc") {
ccs = COMMA
.split(ccString)
.into_iter()
.map(|s| s.to_owned())
.collect();
}
// if ccString != null {
// ccs = COMMA.split(ccString);
// }
if let Some(bccString) = nv.get("bcc") {
bccs = COMMA
.split(bccString)
.into_iter()
.map(|s| s.to_owned())
.collect();
}
// if bccString != null {
// bccs = COMMA.split(bccString);
// }
subject = nv.get("subject").unwrap_or(&"".to_owned()).clone();
body = nv.get("body").unwrap_or(&"".to_owned()).clone();
}
return Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(
tos,
ccs,
bccs,
subject.to_owned(),
body.to_owned(),
),
));
} else {
// let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText,&ATEXT_ALPHANUMERIC) {
return None;
}
return Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::new(rawText)));
// let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) {
return None;
}
return Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::new(rawText),
));
}
}
}

View File

@@ -24,13 +24,13 @@ use regex::Regex;
use crate::RXingResult;
use super::{ParsedClientResult, ResultParser, EmailAddressParsedRXingResult};
use super::{EmailAddressParsedRXingResult, ParsedClientResult, ResultParser};
use lazy_static::lazy_static;
lazy_static! {
static ref ATEXT_ALPHANUMERIC :Regex = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
static ref ATEXT_ALPHANUMERIC: Regex =
Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
}
/**
@@ -40,38 +40,41 @@ lazy_static! {
*
* @author Sean Owen
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if !rawText.starts_with("MATMSG:") {
return None;
return None;
}
let tos = ResultParser::match_do_co_mo_prefixed_field("TO:", &rawText)?;
for to in &tos {
if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) {
return None;
}
if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) {
return None;
}
}
let subject = ResultParser::match_single_do_co_mo_prefixed_field("SUB:", &rawText, false).unwrap_or_default();
let body = ResultParser::match_single_do_co_mo_prefixed_field("BODY:", &rawText, false).unwrap_or_default();
Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(tos, Vec::new(), Vec::new(), subject, body)))
}
let subject = ResultParser::match_single_do_co_mo_prefixed_field("SUB:", &rawText, false)
.unwrap_or_default();
let body = ResultParser::match_single_do_co_mo_prefixed_field("BODY:", &rawText, false)
.unwrap_or_default();
Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(tos, Vec::new(), Vec::new(), subject, body),
))
}
/**
* This implements only the most basic checking for an email address's validity -- that it contains
* an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of
* validity. We want to generally be lenient here since this class is only intended to encapsulate what's
* in a barcode, not "judge" it.
*/
pub fn isBasicallyValidEmailAddress( email:&str, regex:&Regex)-> bool {
/**
* This implements only the most basic checking for an email address's validity -- that it contains
* an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of
* validity. We want to generally be lenient here since this class is only intended to encapsulate what's
* in a barcode, not "judge" it.
*/
pub fn isBasicallyValidEmailAddress(email: &str, regex: &Regex) -> bool {
let email_exists = !email.is_empty();
let email_has_at = matches!(email.find('@'),Some(_));
let email_has_at = matches!(email.find('@'), Some(_));
let email_alphamatcher = if let Some(mtch) = regex.find(email) {
mtch.start() ==0 && mtch.end() == email.len()
}else{
false
mtch.start() == 0 && mtch.end() == email.len()
} else {
false
};
email_exists && email_alphamatcher && email_has_at
// return email != null && ATEXT_ALPHANUMERIC.matcher(email).matches() && email.indexOf('@') >= 0;
}
}

View File

@@ -29,7 +29,7 @@
// import java.util.Map;
// import java.util.Objects;
use std::{collections::HashMap};
use std::collections::HashMap;
use super::{ParsedRXingResult, ParsedRXingResultType};

View File

@@ -42,10 +42,7 @@
use std::collections::HashMap;
use crate::{
client::result::{ParsedClientResult},
RXingResult, BarcodeFormat,
};
use crate::{client::result::ParsedClientResult, BarcodeFormat, RXingResult};
use super::ExpandedProductResultParser;

View File

@@ -41,7 +41,6 @@ pub fn testGeo1() {
//doTest("geo:1,2", 1.0, 2.0, 0.0, "", "geo:1.0,2.0");
// I think 1.0 and 1 and 2.0 and 2 are similar enough here, correct me if i'm wrong.
doTest("geo:1,2", 1.0, 2.0, 0.0, "", "geo:1,2");
}
#[test]
pub fn testGeo2() {

View File

@@ -21,12 +21,12 @@
// import java.util.regex.Matcher;
// import java.util.regex.Pattern;
use super::{GeoParsedRXingResult, ParsedClientResult, ResultParser};
use super::{GeoParsedRXingResult, ParsedClientResult, ResultParser};
use lazy_static::lazy_static;
lazy_static! {
static ref GEO_URL :regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap();
static ref GEO_URL: regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap();
}
const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?";
@@ -42,89 +42,89 @@ const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9
// pub struct GeoRXingResultParser {}
// impl RXingResultParser for GeoRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
let rawText = ResultParser::getMassagedText(theRXingResult);
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
let rawText = ResultParser::getMassagedText(theRXingResult);
if let Some(captures) = GEO_URL.captures(&rawText.to_lowercase()) {
let query = if let Some(q) = captures.get(4) {
q.as_str()
} else {
""
};
if let Some(captures) = GEO_URL.captures(&rawText.to_lowercase()) {
let query = if let Some(q) = captures.get(4) {
q.as_str()
} else {
""
};
let latitude = if let Some(la) = captures.get(1) {
if let Ok(laf64) = la.as_str().parse::<f64>() {
if laf64 > 90.0 || laf64 < -90.0 {
return None;
}
laf64
} else {
let latitude = if let Some(la) = captures.get(1) {
if let Ok(laf64) = la.as_str().parse::<f64>() {
if laf64 > 90.0 || laf64 < -90.0 {
return None;
}
laf64
} else {
return None;
};
let longitude = if let Some(lo) = captures.get(2) {
if let Ok(lof64) = lo.as_str().parse::<f64>() {
if lof64 > 180.0 || lof64 < -180.0 {
return None;
}
lof64
} else {
return None;
}
} else {
return None;
};
let altitude = if let Some(al) = captures.get(3) {
if let Ok(alf64) = al.as_str().parse::<f64>() {
if alf64 < 0.0 {
return None;
}
alf64
} else {
return None;
}
} else {
0.0
};
// let longitude;
// let altitude;
// try {
// // latitude = Double.parseDouble(matcher.group(1));
// // if (latitude > 90.0 || latitude < -90.0) {
// // return null;
// // }
// // longitude = Double.parseDouble(matcher.group(2));
// // if (longitude > 180.0 || longitude < -180.0) {
// // return null;
// // }
// // if (matcher.group(3) == null) {
// // altitude = 0.0;
// // } else {
// // altitude = Double.parseDouble(matcher.group(3));
// // if (altitude < 0.0) {
// // return null;
// // }
// // }
// } catch (NumberFormatException ignored) {
// return null;
// }
Some(ParsedClientResult::GeoResult(GeoParsedRXingResult::new(
latitude,
longitude,
altitude,
String::from(query),
)))
}
} else {
return None;
}
};
// Matcher matcher = GEO_URL_PATTERN.matcher(rawText);
// if (!matcher.matches()) {
let longitude = if let Some(lo) = captures.get(2) {
if let Ok(lof64) = lo.as_str().parse::<f64>() {
if lof64 > 180.0 || lof64 < -180.0 {
return None;
}
lof64
} else {
return None;
}
} else {
return None;
};
let altitude = if let Some(al) = captures.get(3) {
if let Ok(alf64) = al.as_str().parse::<f64>() {
if alf64 < 0.0 {
return None;
}
alf64
} else {
return None;
}
} else {
0.0
};
// let longitude;
// let altitude;
// try {
// // latitude = Double.parseDouble(matcher.group(1));
// // if (latitude > 90.0 || latitude < -90.0) {
// // return null;
// // }
// // longitude = Double.parseDouble(matcher.group(2));
// // if (longitude > 180.0 || longitude < -180.0) {
// // return null;
// // }
// // if (matcher.group(3) == null) {
// // altitude = 0.0;
// // } else {
// // altitude = Double.parseDouble(matcher.group(3));
// // if (altitude < 0.0) {
// // return null;
// // }
// // }
// } catch (NumberFormatException ignored) {
// return null;
// }
Some(ParsedClientResult::GeoResult(GeoParsedRXingResult::new(
latitude,
longitude,
altitude,
String::from(query),
)))
} else {
return None;
}
// Matcher matcher = GEO_URL_PATTERN.matcher(rawText);
// if (!matcher.matches()) {
// return null;
// }
}
// }

View File

@@ -23,11 +23,10 @@ use super::ParsedRXingResult;
*
* @author jbreiden@google.com (Jeff Breidenbach)
*/
pub struct ISBNParsedRXingResult {
isbn:String,
pub struct ISBNParsedRXingResult {
isbn: String,
}
impl ParsedRXingResult for ISBNParsedRXingResult {
impl ParsedRXingResult for ISBNParsedRXingResult {
fn getType(&self) -> super::ParsedRXingResultType {
super::ParsedRXingResultType::ISBN
}
@@ -37,14 +36,12 @@ pub struct ISBNParsedRXingResult {
}
}
impl ISBNParsedRXingResult {
pub fn new( isbn:String)->Self {
Self{ isbn }
}
pub fn getISBN(&self) -> &str{
&self.isbn
}
impl ISBNParsedRXingResult {
pub fn new(isbn: String) -> Self {
Self { isbn }
}
pub fn getISBN(&self) -> &str {
&self.isbn
}
}

View File

@@ -21,33 +21,35 @@
use crate::BarcodeFormat;
use super::{ ResultParser, ISBNParsedRXingResult, ParsedClientResult};
use super::{ISBNParsedRXingResult, ParsedClientResult, ResultParser};
/**
* Parses strings of digits that represent a ISBN.
*
*
* @author jbreiden@google.com (Jeff Breidenbach)
*/
// pub struct ISBNRXingResultParser {}
// impl RXingResultParser for ISBNRXingResultParser {
/**
* See <a href="http://www.bisg.org/isbn-13/for.dummies.html">ISBN-13 For Dummies</a>
*/
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
let format = theRXingResult.getBarcodeFormat();
if *format != BarcodeFormat::EAN_13 {
/**
* See <a href="http://www.bisg.org/isbn-13/for.dummies.html">ISBN-13 For Dummies</a>
*/
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
let format = theRXingResult.getBarcodeFormat();
if *format != BarcodeFormat::EAN_13 {
return None;
}
let rawText = ResultParser::getMassagedText(theRXingResult);
let length = rawText.len();
if length != 13 {
return None;
}
if !rawText.starts_with("978") && !rawText.starts_with("979") {
return None;
}
Some(ParsedClientResult::ISBNResult(ISBNParsedRXingResult::new(rawText)))
}
let rawText = ResultParser::getMassagedText(theRXingResult);
let length = rawText.len();
if length != 13 {
return None;
}
if !rawText.starts_with("978") && !rawText.starts_with("979") {
return None;
}
Some(ParsedClientResult::ISBNResult(ISBNParsedRXingResult::new(
rawText,
)))
}
// }

View File

@@ -22,20 +22,18 @@
*
* @author Sean Owen
*/
#[derive(Debug,PartialEq, Eq,Hash)]
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum ParsedRXingResultType {
ADDRESSBOOK,
EMAIL_ADDRESS,
PRODUCT,
URI,
TEXT,
GEO,
TEL,
SMS,
CALENDAR,
WIFI,
ISBN,
VIN,
ADDRESSBOOK,
EMAIL_ADDRESS,
PRODUCT,
URI,
TEXT,
GEO,
TEL,
SMS,
CALENDAR,
WIFI,
ISBN,
VIN,
}

View File

@@ -23,15 +23,13 @@ use super::{ParsedRXingResult, ParsedRXingResultType};
*
* @author dswitkin@google.com (Daniel Switkin)
*/
pub struct ProductParsedRXingResult {
product_id:String,
normalized_product_id:String,
pub struct ProductParsedRXingResult {
product_id: String,
normalized_product_id: String,
}
impl ParsedRXingResult for ProductParsedRXingResult {
fn getType(&self) -> super::ParsedRXingResultType {
ParsedRXingResultType::PRODUCT
ParsedRXingResultType::PRODUCT
}
fn getDisplayRXingResult(&self) -> String {
@@ -39,23 +37,22 @@ impl ParsedRXingResult for ProductParsedRXingResult {
}
}
impl ProductParsedRXingResult {
pub fn new(product_id:String) -> Self {
Self::with_normalized_id(product_id.clone(), product_id)
}
pub fn with_normalized_id( product_id: String, normalized_product_id:String) -> Self {
Self{
product_id,
normalized_product_id,
pub fn new(product_id: String) -> Self {
Self::with_normalized_id(product_id.clone(), product_id)
}
}
pub fn getProductID(&self) -> &str{
&self.product_id
}
pub fn with_normalized_id(product_id: String, normalized_product_id: String) -> Self {
Self {
product_id,
normalized_product_id,
}
}
pub fn getNormalizedProductID(&self) -> &str {
&self.normalized_product_id
}
pub fn getProductID(&self) -> &str {
&self.product_id
}
pub fn getNormalizedProductID(&self) -> &str {
&self.normalized_product_id
}
}

View File

@@ -27,31 +27,32 @@
* @author Sean Owen
*/
// public final class ProductParsedRXingResultTestCase extends Assert {
use crate::{BarcodeFormat, RXingResult, client::result::{ParsedRXingResult, ParsedRXingResultType, ParsedClientResult}};
use crate::{
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType},
BarcodeFormat, RXingResult,
};
use super::ResultParser;
#[test]
fn test_product() {
#[test]
fn test_product() {
do_test("123456789012", "123456789012", BarcodeFormat::UPC_A);
do_test("00393157", "00393157", BarcodeFormat::EAN_8);
do_test("5051140178499", "5051140178499", BarcodeFormat::EAN_13);
do_test("01234565", "012345000065", BarcodeFormat::UPC_E);
}
}
fn do_test( contents:&str, normalized:&str, format:BarcodeFormat) {
let fake_rxing_result = RXingResult::new(contents, Vec::new(), Vec::new(), format);
fn do_test(contents: &str, normalized: &str, format: BarcodeFormat) {
let fake_rxing_result = RXingResult::new(contents, Vec::new(), Vec::new(), format);
let result = ResultParser::parseRXingResult(&fake_rxing_result);
assert_eq!(ParsedRXingResultType::PRODUCT, result.getType());
if let ParsedClientResult::ProductResult(product_rxing_result) = result {
assert_eq!(contents, product_rxing_result.getProductID());
assert_eq!(normalized, product_rxing_result.getNormalizedProductID());
}else{
panic!("Expected ParsedClientResult::ProductResult")
assert_eq!(contents, product_rxing_result.getProductID());
assert_eq!(normalized, product_rxing_result.getNormalizedProductID());
} else {
panic!("Expected ParsedClientResult::ProductResult")
}
}
}
// }
// }

View File

@@ -20,38 +20,42 @@
// import com.google.zxing.RXingResult;
// import com.google.zxing.oned.UPCEReader;
use crate::{RXingResult, BarcodeFormat};
use crate::{BarcodeFormat, RXingResult};
use super::{ParsedClientResult, ProductParsedRXingResult, ResultParser};
/**
* Parses strings of digits that represent a UPC code.
*
*
* @author dswitkin@google.com (Daniel Switkin)
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes.
// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes.
let format = result.getBarcodeFormat();
if !(format == &BarcodeFormat::UPC_A || format == &BarcodeFormat::UPC_E ||
format == &BarcodeFormat::EAN_8 || format == &BarcodeFormat::EAN_13) {
return None;
let format = result.getBarcodeFormat();
if !(format == &BarcodeFormat::UPC_A
|| format == &BarcodeFormat::UPC_E
|| format == &BarcodeFormat::EAN_8
|| format == &BarcodeFormat::EAN_13)
{
return None;
}
let rawText = ResultParser::getMassagedText(result);
if !ResultParser::isStringOfDigits(&rawText, rawText.len()) {
return None;
return None;
}
// Not actually checking the checksum again here
// Not actually checking the checksum again here
let normalizedProductID;
// Expand UPC-E for purposes of searching
if format == &BarcodeFormat::UPC_E && rawText.len() == 8 {
unimplemented!("UPCEReader is required to parse this");
//normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText);
unimplemented!("UPCEReader is required to parse this");
//normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText);
} else {
normalizedProductID = rawText.clone();
normalizedProductID = rawText.clone();
}
Some(ParsedClientResult::ProductResult(ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID)))
}
Some(ParsedClientResult::ProductResult(
ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID),
))
}

View File

@@ -38,9 +38,10 @@ use crate::{exceptions::Exceptions, RXingResult};
use super::{
AddressBookAUResultParser, AddressBookDoCoMoResultParser, BizcardResultParser,
BookmarkDoCoMoResultParser, EmailAddressResultParser, EmailDoCoMoResultParser,
ExpandedProductResultParser, GeoResultParser, ISBNResultParser, ParsedClientResult, ProductResultParser, SMSMMSResultParser, SMTPResultParser, TelResultParser,
TextParsedRXingResult, URIResultParser, URLTOResultParser, VCardResultParser,
VEventResultParser, VINResultParser, WifiResultParser, SMSTOMMSTOResultParser,
ExpandedProductResultParser, GeoResultParser, ISBNResultParser, ParsedClientResult,
ProductResultParser, SMSMMSResultParser, SMSTOMMSTOResultParser, SMTPResultParser,
TelResultParser, TextParsedRXingResult, URIResultParser, URLTOResultParser, VCardResultParser,
VEventResultParser, VINResultParser, WifiResultParser,
};
/**
@@ -92,7 +93,7 @@ use super::{
pub type ParserFunction = dyn Fn(&RXingResult) -> Option<ParsedClientResult>;
lazy_static! {
static ref DIGITS :Regex = Regex::new("\\d+").unwrap();
static ref DIGITS: Regex = Regex::new("\\d+").unwrap();
}
// const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+");

View File

@@ -84,11 +84,7 @@ fn do_test(contents: &str, number: &str, subject: &str, body: &str, via: &str, p
assert_eq!(&vec![number], smsRXingResult.getNumbers());
assert_eq!(subject, smsRXingResult.getSubject());
assert_eq!(body, smsRXingResult.getBody());
let vec_via = if via.is_empty() {
vec![]
}else {
vec![via]
};
let vec_via = if via.is_empty() { vec![] } else { vec![via] };
assert_eq!(&vec_via, smsRXingResult.getVias());
assert_eq!(parsedURI, smsRXingResult.getSMSURI());
} else {

View File

@@ -95,7 +95,11 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
add_number_via(
&mut numbers,
&mut vias,
&sms_uriwithout_query[(if last_comma > 0 { last_comma + 1} else {last_comma}) as usize..],
&sms_uriwithout_query[(if last_comma > 0 {
last_comma + 1
} else {
last_comma
}) as usize..],
);
Some(ParsedClientResult::SMSResult(
@@ -110,7 +114,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
fn add_number_via(numbers: &mut Vec<String>, vias: &mut Vec<String>, number_part: &str) {
if number_part.is_empty() {
return
return;
}
if let Some(number_end) = number_part.find(';') {
// if numberEnd < 0 {

View File

@@ -32,25 +32,35 @@ use super::{ParsedClientResult, ResultParser, SMSParsedRXingResult};
*
* @author Sean Owen
*/
pub fn parse(result:&RXingResult) -> Option<ParsedClientResult> {
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if !(rawText.starts_with("smsto:") || rawText.starts_with("SMSTO:") ||
rawText.starts_with("mmsto:") || rawText.starts_with("MMSTO:")) {
return None;
if !(rawText.starts_with("smsto:")
|| rawText.starts_with("SMSTO:")
|| rawText.starts_with("mmsto:")
|| rawText.starts_with("MMSTO:"))
{
return None;
}
// Thanks to dominik.wild for suggesting this enhancement to support
// smsto:number:body URIs
let mut number = &rawText[6..];
let mut body = "";
if let Some(body_start) = number.find(':') {
body = &number[body_start + 1..];
number = &number[..body_start];
body = &number[body_start + 1..];
number = &number[..body_start];
}
// let bodyStart = number.indexOf(':');
// if (bodyStart >= 0) {
// body = number.substring(bodyStart + 1);
// number = number.substring(0, bodyStart);
// }
Some(ParsedClientResult::SMSResult(SMSParsedRXingResult::with_singles(number.to_owned(), String::from(""), String::from(""), body.to_owned())))
Some(ParsedClientResult::SMSResult(
SMSParsedRXingResult::with_singles(
number.to_owned(),
String::from(""),
String::from(""),
body.to_owned(),
),
))
// return new SMSParsedRXingResult(number, null, null, body);
}
}

View File

@@ -20,7 +20,7 @@
use crate::RXingResult;
use super::{ResultParser, ParsedClientResult, EmailAddressParsedRXingResult};
use super::{EmailAddressParsedRXingResult, ParsedClientResult, ResultParser};
/**
* <p>Parses an "smtp:" URI result, whose format is not standardized but appears to be like:
@@ -31,18 +31,18 @@ use super::{ResultParser, ParsedClientResult, EmailAddressParsedRXingResult};
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if !(rawText.starts_with("smtp:") || rawText.starts_with("SMTP:")) {
return None;
return None;
}
let mut emailAddress = &rawText[5..];
let mut subject = "";
let mut body = "";
if let Some(colon) = emailAddress.find(':') {
subject = &emailAddress[colon+1..];
emailAddress = &emailAddress[..colon];
if let Some(new_colon) = subject.find(':') {
body = &subject[new_colon+1..];
subject = &subject[..new_colon];
}
subject = &emailAddress[colon + 1..];
emailAddress = &emailAddress[..colon];
if let Some(new_colon) = subject.find(':') {
body = &subject[new_colon + 1..];
subject = &subject[..new_colon];
}
}
// let colon = emailAddress.indexOf(':');
// if (colon >= 0) {
@@ -54,10 +54,18 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// subject = subject.substring(0, colon);
// }
// }
Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(vec![emailAddress.to_owned()],Vec::new(), Vec::new(), subject.to_owned(), body.to_owned())))
Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(
vec![emailAddress.to_owned()],
Vec::new(),
Vec::new(),
subject.to_owned(),
body.to_owned(),
),
))
// return new EmailAddressParsedRXingResult(new String[] {emailAddress},
// null,
// null,
// subject,
// body);
}
}

View File

@@ -27,12 +27,8 @@
* @author Sean Owen
*/
// public final class TelParsedRXingResultTestCase extends Assert {
use crate::{
client::result::{
ParsedClientResult, ParsedRXingResult, ParsedRXingResultType,
},
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType},
BarcodeFormat, RXingResult,
};

View File

@@ -18,7 +18,7 @@
// import com.google.zxing.RXingResult;
use super::{TelParsedRXingResult, ParsedClientResult, ResultParser};
use super::{ParsedClientResult, ResultParser, TelParsedRXingResult};
/**
* Parses a "tel:" URI result, which specifies a phone number.
@@ -29,21 +29,29 @@ use super::{TelParsedRXingResult, ParsedClientResult, ResultParser};
// impl RXingResultParser for TelRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(theRXingResult);
if !rawText.starts_with("tel:") && !rawText.starts_with("TEL:") {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(theRXingResult);
if !rawText.starts_with("tel:") && !rawText.starts_with("TEL:") {
return None;
}
// Normalize "TEL:" to "tel:"
let telURI = if rawText.starts_with("TEL:") {format!("tel:{}", &rawText[4..])} else {rawText.clone()};
// Drop tel, query portion
let queryStart = rawText[4..].find('?');
let number = if let Some(v) = queryStart {
&rawText[4..v+4]
}else {
&rawText[4..]
};
// let number = queryStart < 0 ? : ;
Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(number.to_owned(), telURI.to_owned(), "".to_owned())))
}
// }
// Normalize "TEL:" to "tel:"
let telURI = if rawText.starts_with("TEL:") {
format!("tel:{}", &rawText[4..])
} else {
rawText.clone()
};
// Drop tel, query portion
let queryStart = rawText[4..].find('?');
let number = if let Some(v) = queryStart {
&rawText[4..v + 4]
} else {
&rawText[4..]
};
// let number = queryStart < 0 ? : ;
Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(
number.to_owned(),
telURI.to_owned(),
"".to_owned(),
)))
}
// }

View File

@@ -41,9 +41,9 @@ impl ParsedRXingResult for URIParsedRXingResult {
}
impl URIParsedRXingResult {
pub fn new(uri: String, title: String) -> Self {
Self {
uri: Self::massage_uri(&uri),
title
Self {
uri: Self::massage_uri(&uri),
title,
}
}
@@ -79,8 +79,8 @@ impl URIParsedRXingResult {
uri = format!("http://{}", &uri);
// uri = updated_uri.as_str()
}
}else {
uri = format!("http://{}", &uri);
} else {
uri = format!("http://{}", &uri);
}
uri

View File

@@ -21,6 +21,7 @@
// import java.util.regex.Matcher;
// import java.util.regex.Pattern;
use lazy_static::lazy_static;
/**
* Tries to parse results that are a URI of some kind.
*
@@ -28,17 +29,19 @@
*/
// public final class URIRXingResultParser extends RXingResultParser {
use regex::Regex;
use lazy_static::lazy_static;
use crate::RXingResult;
use super::{ParsedClientResult, ResultParser, URIParsedRXingResult};
lazy_static! {
static ref ALLOWED_URI_CHARS :Regex = Regex::new( ALLOWED_URI_CHARS_PATTERN).expect("Regex patterns should always copile");
static ref USER_IN_HOST :Regex = Regex::new(":/*([^/@]+)@[^/]+").expect("Regex patterns should always copile");
static ref URL_WITH_PROTOCOL_PATTERN : Regex = Regex::new("[a-zA-Z][a-zA-Z0-9+-.]+:").unwrap();
static ref URL_WITHOUT_PROTOCOL_PATTERN :Regex = Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap();
static ref ALLOWED_URI_CHARS: Regex =
Regex::new(ALLOWED_URI_CHARS_PATTERN).expect("Regex patterns should always copile");
static ref USER_IN_HOST: Regex =
Regex::new(":/*([^/@]+)@[^/]+").expect("Regex patterns should always copile");
static ref URL_WITH_PROTOCOL_PATTERN: Regex = Regex::new("[a-zA-Z][a-zA-Z0-9+-.]+:").unwrap();
static ref URL_WITHOUT_PROTOCOL_PATTERN: Regex =
Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap();
}
const ALLOWED_URI_CHARS_PATTERN: &'static str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+";
@@ -79,15 +82,14 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
* to connect to yourbank.com at first glance.
*/
pub fn is_possibly_malicious_uri(uri: &str) -> bool {
let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri){
if fnd.start() == 0 && fnd.end() == uri.len() {
true
}else {
let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) {
if fnd.start() == 0 && fnd.end() == uri.len() {
true
} else {
false
}
} else {
false
}
}else{
false
};
let user = USER_IN_HOST.is_match(uri);

View File

@@ -41,14 +41,15 @@ use uriparse::URI;
use super::{AddressBookParsedRXingResult, ParsedClientResult, ResultParser};
lazy_static! {
static ref BEGIN_VCARD :Regex= Regex::new("(?i:BEGIN:VCARD)").unwrap();
static ref VCARD_LIKE_DATE : Regex = Regex::new("\\d{4}-?\\d{2}-?\\d{2}").unwrap();
static ref CR_LF_SPACE_TAB : Regex = Regex::new("\r\n[ \t]").unwrap();
static ref NEWLINE_ESCAPE : Regex = Regex::new("\\\\[nN]").unwrap();
static ref VCARD_ESCAPE : Regex = Regex::new("\\\\([,;\\\\])").unwrap();
static ref EQUALS : Regex = Regex::new("=").unwrap();
static ref UNESCAPED_SEMICOLONS : fancy_regex::Regex = fancy_regex::Regex::new("(?<!\\\\);+").unwrap();
static ref SEMICOLON_OR_COMMA : Regex = Regex::new("[;,]").unwrap();
static ref BEGIN_VCARD: Regex = Regex::new("(?i:BEGIN:VCARD)").unwrap();
static ref VCARD_LIKE_DATE: Regex = Regex::new("\\d{4}-?\\d{2}-?\\d{2}").unwrap();
static ref CR_LF_SPACE_TAB: Regex = Regex::new("\r\n[ \t]").unwrap();
static ref NEWLINE_ESCAPE: Regex = Regex::new("\\\\[nN]").unwrap();
static ref VCARD_ESCAPE: Regex = Regex::new("\\\\([,;\\\\])").unwrap();
static ref EQUALS: Regex = Regex::new("=").unwrap();
static ref UNESCAPED_SEMICOLONS: fancy_regex::Regex =
fancy_regex::Regex::new("(?<!\\\\);+").unwrap();
static ref SEMICOLON_OR_COMMA: Regex = Regex::new("[;,]").unwrap();
}
// const BEGIN_VCARD: &'static str = "(?i:BEGIN:VCARD)"; //, Pattern.CASE_INSENSITIVE);
@@ -238,7 +239,7 @@ pub fn matchVCardPrefixedField(
while let Some(pos) = rawText[i as usize..].find('\n') {
// Really, end in \r\n
i += pos as isize; // + i;
// while (i = rawText.indexOf('\n', i)) >= 0 { // Really, end in \r\n
// while (i = rawText.indexOf('\n', i)) >= 0 { // Really, end in \r\n
if i < rawText.len() as isize- 1 && // But if followed by tab or space,
(rawText.chars().nth(i as usize+ 1)? == ' ' || // this is only a continuation
rawText.chars().nth(i as usize+ 1)? == '\t')
@@ -262,7 +263,7 @@ pub fn matchVCardPrefixedField(
// if matches == null {
// matches = new ArrayList<>(1); // lazy init
// }
if i >= 1 && rawText.chars().nth(i as usize- 1)? == '\r' {
if i >= 1 && rawText.chars().nth(i as usize - 1)? == '\r' {
i -= 1; // Back up over \r, which really should be there
}
let mut element = rawText[matchStart as usize..i as usize].to_owned();
@@ -293,7 +294,10 @@ pub fn matchVCardPrefixedField(
.replace_all(&element, "")
.to_mut()
.to_owned();
element = NEWLINE_ESCAPE.replace_all(&element, "\n").to_mut().to_owned();
element = NEWLINE_ESCAPE
.replace_all(&element, "\n")
.to_mut()
.to_owned();
element = VCARD_ESCAPE.replace_all(&element, "$1").to_mut().to_owned();
// element = CR_LF_SPACE_TAB.matcher(element).replaceAll("");
// element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n");

View File

@@ -131,20 +131,20 @@ fn matchSingleVCardPrefixedField(prefix: &str, rawText: &str) -> String {
"".to_owned()
} else {
let tz_mod = if values.len() > 1 {
if let Some(v) = values.get(values.len()-2) {
if let Some(v) = values.get(values.len() - 2) {
if let Some(tz_loc) = v.find("TZID=") {
v[tz_loc+5..].to_owned()
}else {
v[tz_loc + 5..].to_owned()
} else {
"".to_owned()
}
}else {
} else {
"".to_owned()
}
}else {
} else {
"".to_owned()
};
let root_time = values.last().unwrap().clone();
format!("{}{}",root_time,tz_mod)
format!("{}{}", root_time, tz_mod)
}
} else {
"".to_owned()

View File

@@ -32,7 +32,7 @@ use super::ParsedClientResult;
use lazy_static::lazy_static;
lazy_static! {
static ref IOQ_MATCHER : Regex = Regex::new(IOQ).unwrap();
static ref IOQ_MATCHER: Regex = Regex::new(IOQ).unwrap();
static ref AZ09_MATCHER: Regex = Regex::new(AZ09).unwrap();
}
@@ -45,7 +45,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
if result.getBarcodeFormat() != &BarcodeFormat::CODE_39 {
return None;
}
let raw_text_res = result.getText().trim();
let raw_text = IOQ_MATCHER.replace_all(raw_text_res, "").to_string();
// rawText = IOQ.matcher(rawText).replaceAll("").trim();

View File

@@ -27,74 +27,139 @@
* @author Vikram Aggarwal
*/
// public final class WifiParsedRXingResultTestCase extends Assert {
use crate::{RXingResult, BarcodeFormat, client::result::{ParsedRXingResultType, ParsedRXingResult, ParsedClientResult}};
use crate::{
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType},
BarcodeFormat, RXingResult,
};
use super::ResultParser;
#[test]
fn testNoPassword() {
#[test]
fn testNoPassword() {
doTest("WIFI:S:NoPassword;P:;T:;;", "NoPassword", "", "nopass");
doTest("WIFI:S:No Password;P:;T:;;", "No Password", "", "nopass");
}
}
#[test]
fn testWep() {
doTest("WIFI:S:TenChars;P:0123456789;T:WEP;;", "TenChars", "0123456789", "WEP");
doTest("WIFI:S:TenChars;P:abcde56789;T:WEP;;", "TenChars", "abcde56789", "WEP");
#[test]
fn testWep() {
doTest(
"WIFI:S:TenChars;P:0123456789;T:WEP;;",
"TenChars",
"0123456789",
"WEP",
);
doTest(
"WIFI:S:TenChars;P:abcde56789;T:WEP;;",
"TenChars",
"abcde56789",
"WEP",
);
// Non hex should not fail at this level
doTest("WIFI:S:TenChars;P:hellothere;T:WEP;;", "TenChars", "hellothere", "WEP");
doTest(
"WIFI:S:TenChars;P:hellothere;T:WEP;;",
"TenChars",
"hellothere",
"WEP",
);
// Escaped semicolons
doTest("WIFI:S:Ten\\;\\;Chars;P:0123456789;T:WEP;;", "Ten;;Chars", "0123456789", "WEP");
doTest(
"WIFI:S:Ten\\;\\;Chars;P:0123456789;T:WEP;;",
"Ten;;Chars",
"0123456789",
"WEP",
);
// Escaped colons
doTest("WIFI:S:Ten\\:\\:Chars;P:0123456789;T:WEP;;", "Ten::Chars", "0123456789", "WEP");
doTest(
"WIFI:S:Ten\\:\\:Chars;P:0123456789;T:WEP;;",
"Ten::Chars",
"0123456789",
"WEP",
);
// TODO(vikrama) Need a test for SB as well.
}
}
/**
* Put in checks for the length of the password for wep.
*/
#[test]
fn testWpa() {
/**
* Put in checks for the length of the password for wep.
*/
#[test]
fn testWpa() {
doTest("WIFI:S:TenChars;P:wow;T:WPA;;", "TenChars", "wow", "WPA");
doTest("WIFI:S:TenChars;P:space is silent;T:WPA;;", "TenChars", "space is silent", "WPA");
doTest("WIFI:S:TenChars;P:hellothere;T:WEP;;", "TenChars", "hellothere", "WEP");
doTest(
"WIFI:S:TenChars;P:space is silent;T:WPA;;",
"TenChars",
"space is silent",
"WPA",
);
doTest(
"WIFI:S:TenChars;P:hellothere;T:WEP;;",
"TenChars",
"hellothere",
"WEP",
);
// Escaped semicolons
doTest("WIFI:S:TenChars;P:hello\\;there;T:WEP;;", "TenChars", "hello;there", "WEP");
doTest(
"WIFI:S:TenChars;P:hello\\;there;T:WEP;;",
"TenChars",
"hello;there",
"WEP",
);
// Escaped colons
doTest("WIFI:S:TenChars;P:hello\\:there;T:WEP;;", "TenChars", "hello:there", "WEP");
}
doTest(
"WIFI:S:TenChars;P:hello\\:there;T:WEP;;",
"TenChars",
"hello:there",
"WEP",
);
}
#[test]
fn testEscape() {
doTest("WIFI:T:WPA;S:test;P:my_password\\\\;;", "test", "my_password\\", "WPA");
doTest("WIFI:T:WPA;S:My_WiFi_SSID;P:abc123/;;", "My_WiFi_SSID", "abc123/", "WPA");
doTest("WIFI:T:WPA;S:\"foo\\;bar\\\\baz\";;", "\"foo;bar\\baz\"", "", "WPA");
doTest("WIFI:T:WPA;S:test;P:\\\"abcd\\\";;", "test", "\"abcd\"", "WPA");
}
#[test]
fn testEscape() {
doTest(
"WIFI:T:WPA;S:test;P:my_password\\\\;;",
"test",
"my_password\\",
"WPA",
);
doTest(
"WIFI:T:WPA;S:My_WiFi_SSID;P:abc123/;;",
"My_WiFi_SSID",
"abc123/",
"WPA",
);
doTest(
"WIFI:T:WPA;S:\"foo\\;bar\\\\baz\";;",
"\"foo;bar\\baz\"",
"",
"WPA",
);
doTest(
"WIFI:T:WPA;S:test;P:\\\"abcd\\\";;",
"test",
"\"abcd\"",
"WPA",
);
}
/**
* Given the string contents for the barcode, check that it matches our expectations
*/
fn doTest( contents:&str,
ssid:&str,
password:&str,
n_type:&str) {
let fakeRXingResult = RXingResult::new(contents, Vec::new(), Vec::new(), BarcodeFormat::QR_CODE);
/**
* Given the string contents for the barcode, check that it matches our expectations
*/
fn doTest(contents: &str, ssid: &str, password: &str, n_type: &str) {
let fakeRXingResult =
RXingResult::new(contents, Vec::new(), Vec::new(), BarcodeFormat::QR_CODE);
let result = ResultParser::parseRXingResult(&fakeRXingResult);
// Ensure it is a wifi code
assert_eq!(ParsedRXingResultType::WIFI, result.getType());
if let ParsedClientResult::WiFiResult(wifiRXingResult) = result{
assert_eq!(ssid, wifiRXingResult.getSsid());
assert_eq!(password, wifiRXingResult.getPassword());
assert_eq!(n_type, wifiRXingResult.getNetworkEncryption());
}else {
panic!("Expected WIFI");
if let ParsedClientResult::WiFiResult(wifiRXingResult) = result {
assert_eq!(ssid, wifiRXingResult.getSsid());
assert_eq!(password, wifiRXingResult.getPassword());
assert_eq!(n_type, wifiRXingResult.getNetworkEncryption());
} else {
panic!("Expected WIFI");
}
}
}
// }

View File

@@ -18,9 +18,9 @@
// import com.google.zxing.RXingResult;
use crate::client::result::{WifiParsedRXingResult, ParsedClientResult};
use crate::client::result::{ParsedClientResult, WifiParsedRXingResult};
use super::{ResultParser};
use super::ResultParser;
// @SuppressWarnings("checkstyle:lineLength")
/**
@@ -43,46 +43,65 @@ use super::{ResultParser};
// pub struct WifiRXingResultParser {}
// impl RXingResultParser for WifiRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
const WIFI_TEST : &'static str = "WIFI:";
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
const WIFI_TEST: &'static str = "WIFI:";
let rawText_unstripped = ResultParser::getMassagedText(theRXingResult);
if !rawText_unstripped.starts_with(WIFI_TEST) {
let rawText_unstripped = ResultParser::getMassagedText(theRXingResult);
if !rawText_unstripped.starts_with(WIFI_TEST) {
return None;
}
let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned();
let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false).unwrap_or(String::from(""));
if ssid.is_empty() {
}
let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned();
let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false)
.unwrap_or(String::from(""));
if ssid.is_empty() {
return None;
}
let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false).unwrap_or(String::from(""));
let n_type = if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false){
nt
}else {
String::from("nopass")
};
// Unfortunately, in the past, H: was not just used for boolean 'hidden', but 'phase 2 method'.
// To try to retain backwards compatibility, we set one or the other based on whether the string
// is 'true' or 'false':
let mut hidden = false;
let mut phase2Method = ResultParser::matchSinglePrefixedField("PH2:", &rawText, ';', false);
let hValue = if let Some(hv) = ResultParser::matchSinglePrefixedField("H:", &rawText, ';', false){
}
let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false)
.unwrap_or(String::from(""));
let n_type =
if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false) {
nt
} else {
String::from("nopass")
};
// Unfortunately, in the past, H: was not just used for boolean 'hidden', but 'phase 2 method'.
// To try to retain backwards compatibility, we set one or the other based on whether the string
// is 'true' or 'false':
let mut hidden = false;
let mut phase2Method = ResultParser::matchSinglePrefixedField("PH2:", &rawText, ';', false);
let hValue = if let Some(hv) =
ResultParser::matchSinglePrefixedField("H:", &rawText, ';', false)
{
// If PH2 was specified separately, or if the value is clearly boolean, interpret it as 'hidden'
if phase2Method.is_some() || "true" == hv.to_lowercase() || "false" == hv.to_lowercase() {
hidden = hv.parse().unwrap();//Boolean.parseBoolean(hValue);
hidden = hv.parse().unwrap(); //Boolean.parseBoolean(hValue);
} else {
phase2Method = Some(hv.clone());
phase2Method = Some(hv.clone());
}
hv
}else {
} else {
String::from("")
};
let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false).unwrap_or(String::from(""));
let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false).unwrap_or(String::from(""));
let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false).unwrap_or(String::from(""));
Some(ParsedClientResult::WiFiResult(WifiParsedRXingResult::with_details(n_type, ssid, pass, hidden, identity, anonymousIdentity, eapMethod, phase2Method.unwrap_or(String::from("")))))
}
};
let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false)
.unwrap_or(String::from(""));
let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false)
.unwrap_or(String::from(""));
let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false)
.unwrap_or(String::from(""));
Some(ParsedClientResult::WiFiResult(
WifiParsedRXingResult::with_details(
n_type,
ssid,
pass,
hidden,
identity,
anonymousIdentity,
eapMethod,
phase2Method.unwrap_or(String::from("")),
),
))
}
// }

View File

@@ -1,48 +1,48 @@
mod ParsedResult;
mod ResultParser;
mod TelParsedResult;
mod TextParsedResult;
mod ParsedResultType;
mod TelResultParser;
mod ISBNParsedResult;
mod ISBNResultParser;
mod WifiParsedResult;
mod WifiResultParser;
mod GeoResultParser;
mod GeoParsedResult;
mod SMSParsedResult;
mod SMSMMSResultParser;
mod ProductParsedResult;
mod ProductResultParser;
mod URIParsedResult;
mod URIResultParser;
mod URLTOResultParser;
mod AbstractDoCoMoResultParser;
mod AddressBookAUResultParser;
mod AddressBookDoCoMoResultParser;
mod AddressBookParsedResult;
mod BizcardResultParser;
mod BookmarkDoCoMoResultParser;
mod SMSTOMMSTOResultParser;
mod CalendarParsedResult;
mod EmailAddressParsedResult;
mod EmailAddressResultParser;
mod EmailDoCoMoResultParser;
mod SMTPResultParser;
mod VINParsedResult;
mod VINResultParser;
mod AddressBookParsedResult;
mod AddressBookDoCoMoResultParser;
mod AddressBookAUResultParser;
mod VCardResultParser;
mod BizcardResultParser;
mod CalendarParsedResult;
mod VEventResultParser;
mod ExpandedProductParsedResult;
mod ExpandedProductResultParser;
mod GeoParsedResult;
mod GeoResultParser;
mod ISBNParsedResult;
mod ISBNResultParser;
mod ParsedResult;
mod ParsedResultType;
mod ProductParsedResult;
mod ProductResultParser;
mod ResultParser;
mod SMSMMSResultParser;
mod SMSParsedResult;
mod SMSTOMMSTOResultParser;
mod SMTPResultParser;
mod TelParsedResult;
mod TelResultParser;
mod TextParsedResult;
mod URIParsedResult;
mod URIResultParser;
mod URLTOResultParser;
mod VCardResultParser;
mod VEventResultParser;
mod VINParsedResult;
mod VINResultParser;
mod WifiParsedResult;
mod WifiResultParser;
use std::fmt;
pub use ParsedResult::*;
pub use ParsedResultType::*;
pub use ResultParser::*;
pub use TelParsedResult::*;
pub use TextParsedResult::*;
pub use ParsedResult::*;
// pub use TelResultParser::*;
pub use ISBNParsedResult::*;
// pub use ISBNResultParser::*;
@@ -50,42 +50,42 @@ pub use WifiParsedResult::*;
// pub use WifiResultParser::*;
pub use GeoParsedResult::*;
// pub use GeoResultParser::*;
pub use SMSParsedResult::*;
pub use ProductParsedResult::*;
pub use URIParsedResult::*;
pub use EmailAddressParsedResult::*;
pub use VINParsedResult::*;
pub use AddressBookParsedResult::*;
pub use CalendarParsedResult::*;
pub use CalendarParsedResult::*;
pub use EmailAddressParsedResult::*;
pub use ExpandedProductParsedResult::*;
pub use ProductParsedResult::*;
pub use SMSParsedResult::*;
pub use URIParsedResult::*;
pub use VINParsedResult::*;
#[cfg(test)]
mod TelParsedResultTestCase;
#[cfg(test)]
mod ISBNParsedResultTestCase;
#[cfg(test)]
mod WifiParsedResultTestCase;
#[cfg(test)]
mod GeoParsedResultTestCase;
#[cfg(test)]
mod SMSMMSParsedResultTestCase;
#[cfg(test)]
mod ProductParsedResultTestCase;
#[cfg(test)]
mod URIParsedResultTestCase;
#[cfg(test)]
mod EmailAddressParsedResultTestCase;
#[cfg(test)]
mod VINParsedResultTestCase;
#[cfg(test)]
mod AddressBookParsedResultTestCase;
#[cfg(test)]
mod CalendarParsedResultTestCase;
#[cfg(test)]
mod EmailAddressParsedResultTestCase;
#[cfg(test)]
mod ExpandedProductParsedResultTestCase;
#[cfg(test)]
mod GeoParsedResultTestCase;
#[cfg(test)]
mod ISBNParsedResultTestCase;
#[cfg(test)]
mod ParsedReaderResultTestCase;
#[cfg(test)]
mod ProductParsedResultTestCase;
#[cfg(test)]
mod SMSMMSParsedResultTestCase;
#[cfg(test)]
mod TelParsedResultTestCase;
#[cfg(test)]
mod URIParsedResultTestCase;
#[cfg(test)]
mod VINParsedResultTestCase;
#[cfg(test)]
mod WifiParsedResultTestCase;
pub enum ParsedClientResult {
TextResult(TextParsedRXingResult),
@@ -143,6 +143,6 @@ impl ParsedRXingResult for ParsedClientResult {
impl fmt::Display for ParsedClientResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f,"{}", self.getDisplayRXingResult())
write!(f, "{}", self.getDisplayRXingResult())
}
}
}