feat: implement write_cards & support Qingque

This commit is contained in:
2024-01-07 01:05:47 +07:00
parent bd1d54e202
commit b16c0dadab
11 changed files with 676 additions and 46 deletions

View File

@ -1,2 +1,3 @@
pub const KATANA_ID: u64 = 646937666251915264;
pub const SOFA_ID: u64 = 853629533855809596;
pub const QINGQUE_ID: u64 = 772642704257187840;

View File

@ -3,8 +3,10 @@ use crate::structs::Card;
use mongodb::Collection;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::task;
use tracing::trace;
static KATANA: OnceLock<Collection<Card>> = OnceLock::new();
pub static KATANA: OnceLock<Collection<Card>> = OnceLock::new();
///
/// Initialize the "katana" collection in MongoDB
@ -39,8 +41,7 @@ pub async fn query_card(name: &str, series: &str) -> Option<Card> {
.unwrap()
}
pub async fn write_card(mut card: Card) {
// todo!("Write card to database");
pub async fn write_card(mut card: Card) -> Result<(), String> {
let old_card = KATANA
.get()
.unwrap()
@ -59,7 +60,7 @@ pub async fn write_card(mut card: Card) {
.expect("Time went backwards");
card.last_update_ts = current_time_ts.as_secs() as i64;
if old_card.is_some() {
KATANA
match KATANA
.get()
.unwrap()
.replace_one(
@ -71,8 +72,96 @@ pub async fn write_card(mut card: Card) {
None,
)
.await
.unwrap();
{
Ok(_) => {
return Ok(());
}
Err(e) => {
return Err(format!("Failed to update card: {}", e));
}
}
} else {
KATANA.get().unwrap().insert_one(card, None).await.unwrap();
match KATANA.get().unwrap().insert_one(card, None).await {
Ok(_) => {
return Ok(());
}
Err(e) => {
return Err(format!("Failed to insert card: {}", e));
}
}
}
}
pub async fn write_cards(cards: Vec<Card>) -> Result<(), String> {
let mut new_cards: Vec<Card> = Vec::new();
let mut handles: Vec<task::JoinHandle<Result<Option<Card>, String>>> = Vec::new();
for mut card in cards {
trace!("Writing card: {:?}", card);
handles.push(task::spawn(async {
let old_card = KATANA
.get()
.unwrap()
.find_one(
mongodb::bson::doc! {
"name": card.name.clone(),
"series": card.series.clone()
},
None,
)
.await
.unwrap();
let start = SystemTime::now();
let current_time_ts = start
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
card.last_update_ts = current_time_ts.as_secs() as i64;
if old_card.is_some() {
match KATANA
.get()
.unwrap()
.replace_one(
mongodb::bson::doc! {
"name": card.name.clone(),
"series": card.series.clone()
},
card,
None,
)
.await
{
Ok(_) => {
return Ok(None);
}
Err(e) => {
return Err(format!("Failed to update card: {}", e));
}
}
} else {
return Ok(Some(card));
};
}));
}
for handle in handles {
match handle.await.unwrap() {
Ok(card) => {
if card.is_some() {
new_cards.push(card.unwrap());
}
}
Err(e) => {
return Err(format!("Failed to update card: {}", e));
}
}
}
if new_cards.len() > 0 {
match KATANA.get().unwrap().insert_many(new_cards, None).await {
Ok(_) => {
return Ok(());
}
Err(e) => {
return Err(format!("Failed to insert card: {}", e));
}
}
}
Ok(())
}

View File

@ -1,4 +1,5 @@
#![feature(lazy_cell)]
#![feature(string_remove_matches)]
pub use log;
pub use tracing::{debug, error, info, trace, warn};
use tracing_subscriber::{self, fmt, EnvFilter};
@ -6,6 +7,7 @@ pub mod constants;
pub mod database;
pub mod structs;
pub mod tesseract;
pub mod utils;
pub fn setup_logger(level: &str) -> Result<(), ()> {
let formatter = fmt::format()

View File

@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Card {
pub wishlist: Option<i32>,
pub wishlist: Option<u32>,
pub name: String,
pub series: String,
pub print: i32,

View File

@ -1,3 +1,61 @@
fn parse_card() {
}
use crate::structs::Card;
use log::{error, trace};
pub fn parse_cards_from_qingque_atopwl(content: &String) -> Vec<Card> {
let mut cards: Vec<Card> = Vec::new();
for line in content.split("\n") {
trace!("Parsing line: {}", line);
let mut line_split = line.split(" · ");
let wishlist = match line_split.nth(1) {
Some(wishlist_str) => {
let mut wl_string = wishlist_str.to_string();
// Remove `
wl_string.remove(0);
// Remove ❤ (Double because heart is 2 bytes)
wl_string.remove(0);
wl_string.remove(0);
// Remove last ``
wl_string.pop();
// Remove "," in the number
wl_string.remove_matches(",");
// Remove whitespace
wl_string = wl_string
.split_whitespace()
.collect::<String>()
.trim()
.to_string();
trace!("Formatted wishlist number:{}", wl_string);
match wl_string.parse::<u32>() {
Ok(wishlist) => wishlist,
Err(_) => {
error!("Failed to parse wishlist number: {}", wishlist_str);
continue;
}
}
}
None => continue,
};
let series = match line_split.next() {
Some(series) => series.to_string(),
None => continue,
};
let name = match line_split.next() {
Some(name) => {
let mut name_string = name.to_string();
name_string.remove_matches("**");
name_string
}
None => continue,
};
let card = Card {
wishlist: Some(wishlist),
name,
series,
print: 0,
last_update_ts: 0,
};
trace!("Parsed card: {:?}", card);
cards.push(card);
}
cards
}

View File

@ -0,0 +1 @@
pub mod katana;