scam-police/src/keywords.rs
2023-04-11 23:06:14 -04:00

89 lines
2.0 KiB
Rust

use serde_json::Value;
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeywordCategory {
Verb,
Currency,
Social,
}
impl std::fmt::Display for KeywordCategory {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use KeywordCategory::*;
match self {
Verb => write!(f, "Verb"),
Currency => write!(f, "Currency"),
Social => write!(f, "Social"),
}
}
}
impl KeywordCategory {
pub fn to_json_var(&self) -> &str {
use KeywordCategory::*;
match self {
Verb => "verbs",
Currency => "currencies",
Social => "socials",
}
}
pub fn from_json_var(var: &str) -> Result<Self,()> {
use KeywordCategory::*;
match var {
"verbs" => Ok(Verb),
"currencies" => Ok(Currency),
"socials" => Ok(Social),
_ => Err(())
}
}
pub fn create_counter_map() -> HashMap<KeywordCategory,u64> {
use KeywordCategory::*;
let mut map: HashMap<KeywordCategory,u64> = HashMap::new();
map.insert(Verb, 0);
map.insert(Currency, 0);
map.insert(Social, 0);
map
}
}
pub struct Keywords {
pub category: KeywordCategory,
pub words: Vec<Value>
}
impl Keywords {
pub fn create(name: &str, v: &Value) -> Self {
let v = v.as_array().unwrap();
let Ok(category) = KeywordCategory::from_json_var(name) else {
panic!("Couldn't translate \"{name}\" to KeywordCategory");
};
Self {
category,
words: v.to_vec()
}
}
pub fn find(&self, hay: &str) -> u64 {
let mut hits: u64 = 0;
for kw in self.words.to_owned().into_iter() {
let kw = kw.as_str().unwrap();
if hay.contains(kw) {
hits += 1
}
}
hits
}
}