Author SHA1 Message Date
micialware 1406fc8f21 Change TEXT to INTEGER in card_stats 2026-08-20 18:53:13 +03:00
micialware e8c9e37ca1 Fix semirandom srs bug 2026-08-20 18:27:05 +03:00
micialware c5c1f34e1c Fix history bug 2026-08-20 18:18:14 +03:00
micialware 9456eec2af Rename DictionaryTest to DictionaryQuiz 2026-08-20 17:48:03 +03:00
15 changed files with 106 additions and 90 deletions

No files matched your search

-1
View File
@@ -1,3 +1,2 @@
/target /target
.idea .idea
.DS_Store
+2 -2
View File
@@ -5,9 +5,9 @@ create table card_stats
word_id INTEGER not null word_id INTEGER not null
references words references words
on delete cascade, on delete cascade,
set_id TEXT not null set_id INTEGER not null
references card_set references card_set
on delete cascade, on delete cascade,
score INTEGER default 1 not null, score INTEGER default 1 not null,
last_opened integer not null last_opened INTEGER not null
); );
+1 -10
View File
@@ -73,15 +73,6 @@ pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
println!("Updated stat: {}", time.elapsed().as_millis()); println!("Updated stat: {}", time.elapsed().as_millis());
} }
pub fn delete_stat(stat: &CardStatistics, connection: &Connection) {
if !stat.id.is_valid() {
return;
}
connection
.execute("DELETE FROM card_stats WHERE id = ?1", (&stat.id,))
.unwrap();
}
pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) { pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) {
if stat.is_empty() { if stat.is_empty() {
return; return;
@@ -93,7 +84,7 @@ pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) {
.join(", "); .join(", ");
connection connection
.execute( .execute(
format!("DELETE FROM card_stats WHERE id in {ids}").as_str(), format!("DELETE FROM card_stats WHERE id in ({ids})").as_str(),
(), (),
) )
.unwrap(); .unwrap();
+1 -1
View File
@@ -39,7 +39,7 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
continue; continue;
} }
items.push(HistoryItem { items.push(HistoryItem {
timestamp: DateTime::from_timestamp(time.parse().unwrap_or_default(), 0).unwrap(), timestamp: DateTime::from_timestamp(time.parse().unwrap_or_default(), 0).unwrap_or_default(),
word_id: id, word_id: id,
mode: match mode.parse::<u8>().unwrap_or_default() { mode: match mode.parse::<u8>().unwrap_or_default() {
2 => WordOpenMode::Hard, 2 => WordOpenMode::Hard,
+22 -18
View File
@@ -40,25 +40,29 @@ pub fn load_groups(connection: &Connection) -> ImportData {
.collect::<Vec<(i64, i64)>>(); .collect::<Vec<(i64, i64)>>();
for (_, collection) in sets { for (_, collection) in sets {
let fields = collection["flds"] let fields_property = collection.get("fields");
.as_array() if let Some(fields_property) = fields_property {
.unwrap() let fields = fields_property
.iter() .as_array()
.map(|x| x["name"].as_str().unwrap().to_string()) .unwrap()
.collect(); .iter()
let mut group = ImportGroup { .map(|x| x["name"].as_str().unwrap().to_string())
id: collection["id"].as_u64().unwrap(), .collect();
name: collection["name"].as_str().unwrap().to_string(), let mut group = ImportGroup {
fields, id: collection["id"].as_u64().unwrap(),
mapping: Default::default(), name: collection["name"].as_str().unwrap().to_string(),
length: 0, fields,
imported: false, mapping: Default::default(),
}; length: 0,
if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) { imported: false,
group.length = *count as u64 };
if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) {
group.length = *count as u64
}
println!("{:?}", group);
total_data.0.push(group);
} }
println!("{:?}", group);
total_data.0.push(group);
} }
total_data total_data
} }
+18 -21
View File
@@ -1,5 +1,6 @@
use crate::dictionary::app_data_dir; use crate::dictionary::app_data_dir;
use std::io; use std::io;
use reqwest::Error;
use tokio::fs::{File, OpenOptions}; use tokio::fs::{File, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder}; use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
@@ -7,10 +8,10 @@ use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
// const API_URL: &str = "http://127.0.0.1:8089/"; // const API_URL: &str = "http://127.0.0.1:8089/";
const API_URL: &str = "https://learning.micialware.ru/"; const API_URL: &str = "https://learning.micialware.ru/";
pub async fn send_data(id: String) { pub async fn send_data(id: String) -> Result<(), ()> {
let path = app_data_dir(); let path = app_data_dir();
let db_file = path.join("data.db"); let db_file = path.join("data.db");
let data = tokio::fs::read(db_file).await.unwrap(); let data = tokio::fs::read(db_file).await.map_err(|_| ())?;
let data = compress(data); let data = compress(data);
let api_url = API_URL.to_string(); let api_url = API_URL.to_string();
@@ -21,12 +22,11 @@ pub async fn send_data(id: String) {
.post(&id_url) .post(&id_url)
.body(data) .body(data)
.send() .send()
.await .await.map_err(|_| ())?
.unwrap()
.text() .text()
.await .await.map_err(|_| ())?;
.unwrap();
set_local_version(new_version.parse::<u32>().unwrap()).await; set_local_version(new_version.parse::<u32>().unwrap()).await;
Ok(())
} }
fn compress(data: Vec<u8>) -> Vec<u8> { fn compress(data: Vec<u8>) -> Vec<u8> {
@@ -35,18 +35,16 @@ fn compress(data: Vec<u8>) -> Vec<u8> {
encoder.finish().unwrap() encoder.finish().unwrap()
} }
pub async fn load_data(id: String, temp: bool) { pub async fn load_data(id: String, temp: bool) -> Result<(), Error> {
let api_url = API_URL.to_string(); let api_url = API_URL.to_string();
let id_url = format!("{api_url}download/{id}"); let id_url = format!("{api_url}download/{id}");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let data = client let data = client
.get(&id_url) .get(&id_url)
.send() .send()
.await .await?
.unwrap()
.bytes() .bytes()
.await .await?
.unwrap()
.to_vec(); .to_vec();
let data = decompress(data); let data = decompress(data);
@@ -60,12 +58,11 @@ pub async fn load_data(id: String, temp: bool) {
let version = client let version = client
.get(&version_url) .get(&version_url)
.send() .send()
.await .await?
.unwrap()
.text() .text()
.await .await?;
.unwrap(); set_local_version(version.parse::<u32>().unwrap_or_default()).await;
set_local_version(version.parse::<u32>().unwrap()).await; Ok(())
} }
pub fn decompress(data: Vec<u8>) -> Vec<u8> { pub fn decompress(data: Vec<u8>) -> Vec<u8> {
@@ -78,7 +75,7 @@ pub fn decompress(data: Vec<u8>) -> Vec<u8> {
decompressed decompressed
} }
pub async fn first_sync() -> String { pub async fn first_sync() -> Result<String, ()> {
let id_url = API_URL.to_string() + "generate"; let id_url = API_URL.to_string() + "generate";
let client = reqwest::Client::new(); let client = reqwest::Client::new();
@@ -86,12 +83,12 @@ pub async fn first_sync() -> String {
.get(&id_url) .get(&id_url)
.send() .send()
.await .await
.unwrap() .map_err(|_| ())?
.text() .text()
.await .await
.unwrap(); .map_err(|_| ())?;
println!("id: {}", id); println!("id: {}", id);
id Ok(id)
} }
pub async fn get_web_version(key: &str) -> Result<u32, reqwest::Error> { pub async fn get_web_version(key: &str) -> Result<u32, reqwest::Error> {
@@ -112,7 +109,7 @@ pub async fn get_local_version() -> u32 {
.read_to_string(&mut data) .read_to_string(&mut data)
.await .await
.unwrap(); .unwrap();
return data.parse::<u32>().unwrap(); return data.parse::<u32>().unwrap_or_default();
} }
let mut file = OpenOptions::new() let mut file = OpenOptions::new()
+1 -1
View File
@@ -1,6 +1,6 @@
use crate::data_provider::words::{delete_group, delete_word, update_group, update_word}; use crate::data_provider::words::{delete_group, delete_word, update_group, update_word};
use crate::dictionary::DictionaryMessage::*; use crate::dictionary::DictionaryMessage::*;
use crate::dictionary_test::DictionaryQuizState; use crate::dictionary_quiz::DictionaryQuizState;
use crate::import::ImportState; use crate::import::ImportState;
use crate::lang::{WordData, WordGroup}; use crate::lang::{WordData, WordGroup};
use crate::navigation::Page::{Import, Word}; use crate::navigation::Page::{Import, Word};
@@ -1,6 +1,6 @@
use crate::RootMessage; use crate::RootMessage;
use crate::dictionary::split_with_coma; use crate::dictionary::split_with_coma;
use crate::dictionary_test::DictionaryQuizMessage::*; use crate::dictionary_quiz::DictionaryQuizMessage::*;
use crate::lang::WordData; use crate::lang::WordData;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::*; use crate::navigation::*;
+17 -6
View File
@@ -1,9 +1,8 @@
use crate::data_provider::history::{HistoryItem, get_history_of_set}; use crate::data_provider::history::{get_history_of_set, HistoryItem};
use crate::lang::WordData; use crate::lang::{WordData, INVALID_ID};
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::styling::*; use crate::styling::*;
use crate::{AppState, RootMessage}; use crate::{AppState, RootMessage};
use HistoryMessage::Back;
use chrono::Local; use chrono::Local;
use iced::alignment::Horizontal::Center; use iced::alignment::Horizontal::Center;
use iced::widget::space::horizontal; use iced::widget::space::horizontal;
@@ -11,6 +10,7 @@ use iced::widget::*;
use iced::{Element, Fill, FillPortion, Task}; use iced::{Element, Fill, FillPortion, Task};
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
use HistoryMessage::Back;
#[derive(Clone)] #[derive(Clone)]
pub struct HistoryState { pub struct HistoryState {
@@ -52,8 +52,19 @@ impl HistoryState {
let history = get_history_of_set(id); let history = get_history_of_set(id);
let words = history let words = history
.iter() .iter()
.filter_map(|item| state.dictionary.iter().find(|w| w.id == item.word_id)) .map(
.cloned() |item| match state.dictionary.iter().find(|w| w.id == item.word_id) {
None => WordData {
id,
key: "Удаленное слово".to_string(),
value: "Удаленное слово".to_string(),
tags: "Удаленное слово".to_string(),
additional: Default::default(),
group_id: INVALID_ID,
},
Some(word) => word.clone(),
},
)
.collect(); .collect();
Self { Self {
@@ -64,7 +75,7 @@ impl HistoryState {
fn history_lines(&self) -> Column<'_, HistoryMessage> { fn history_lines(&self) -> Column<'_, HistoryMessage> {
let mut column = Column::new(); let mut column = Column::new();
for (item, index) in self.list.iter().zip(0..self.list.len()) { for (index, item) in self.list.iter().enumerate() {
column = column.push( column = column.push(
row![ row![
iced::widget::column![ iced::widget::column![
+1 -1
View File
@@ -489,7 +489,7 @@ impl ImportState {
add_words(word, connection); add_words(word, connection);
index += 1; index += 1;
let mut progress = progress.lock(); let mut progress = progress.lock();
*progress = index as f32 / total_len; *progress = (index as f32 / total_len).min(1.0);
} }
state.dictionary.append(&mut words_list); state.dictionary.append(&mut words_list);
+6 -5
View File
@@ -1,10 +1,11 @@
use crate::data_provider::card_stats::load_stats_of_deck;
use crate::data_provider::card_stats::update_stat_score;
use crate::data_provider::history::{push_note, HistoryItem};
use crate::AppState; use crate::AppState;
use crate::data_provider::card_stats::{delete_stat, load_stats_of_deck, update_stat_score};
use crate::data_provider::history::{HistoryItem, push_note};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use parking_lot::Mutex; use parking_lot::Mutex;
use rand::distr::Distribution;
use rand::distr::weighted::WeightedIndex; use rand::distr::weighted::WeightedIndex;
use rand::distr::Distribution;
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
use rand::rng; use rand::rng;
use rand::rngs::ThreadRng; use rand::rngs::ThreadRng;
@@ -12,8 +13,8 @@ use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator; use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator; use rayon::iter::ParallelIterator;
use rhai::{Engine, Scope}; use rhai::{Engine, Scope};
use rusqlite::ToSql;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef}; use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
use rusqlite::ToSql;
use std::cmp::PartialEq; use std::cmp::PartialEq;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
@@ -541,7 +542,7 @@ impl SRSModule for SemiRandomSRSModule {
fn next(&mut self, set: &mut DeckData) -> usize { fn next(&mut self, set: &mut DeckData) -> usize {
let index = self.last_weights.sample(&mut self.generator); let index = self.last_weights.sample(&mut self.generator);
if self.history.contains(&index) { if self.history.contains(&index) && self.history.len() != 1 {
return self.next(set); return self.next(set);
} }
+1 -1
View File
@@ -1,7 +1,7 @@
#![windows_subsystem = "windows"] #![windows_subsystem = "windows"]
mod data_provider; mod data_provider;
mod dictionary; mod dictionary;
mod dictionary_test; mod dictionary_quiz;
mod history; mod history;
pub mod import; pub mod import;
mod lang; mod lang;
+3 -5
View File
@@ -1,10 +1,8 @@
use crate::data_provider::history::{get_history_of_set, history_dir}; use crate::data_provider::history::{get_history_of_set, history_dir};
use crate::data_provider::sqlite::{create_db, default_connection}; use crate::data_provider::sqlite::{create_db, default_connection};
use crate::data_provider::web_api::{ use crate::data_provider::web_api::{get_local_version, get_web_version, load_data, set_local_version};
get_local_version, get_web_version, load_data, set_local_version,
};
use crate::dictionary::{DictionaryMessage, DictionaryState, app_data_dir}; use crate::dictionary::{DictionaryMessage, DictionaryState, app_data_dir};
use crate::dictionary_test::{DictionaryQuizMessage, DictionaryQuizState}; use crate::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState};
use crate::history::{HistoryMessage, HistoryState}; use crate::history::{HistoryMessage, HistoryState};
use crate::import::{ImportMessage, ImportState}; use crate::import::{ImportMessage, ImportState};
use crate::lang::Id; use crate::lang::Id;
@@ -154,7 +152,7 @@ impl ScreenState {
println!("{} {}", local, web); println!("{} {}", local, web);
if web > local { if web > local {
println!("Web version is newer than local version"); println!("Web version is newer than local version");
load_data(string, true).await; load_data(string, true).await?;
set_local_version(web).await; set_local_version(web).await;
} else { } else {
return Ok(false); return Ok(false);
+21 -11
View File
@@ -9,8 +9,8 @@ use chrono::Local;
use iced::alignment::Horizontal::Center; use iced::alignment::Horizontal::Center;
use iced::keyboard::key::Physical::Code; use iced::keyboard::key::Physical::Code;
use iced::widget::text::Style; use iced::widget::text::Style;
use iced::widget::{Column, button, column, container, row, rule, space, text, tooltip}; use iced::widget::{button, column, container, row, rule, space, text, tooltip, Column};
use iced::{Element, Fill, Task, Theme, alignment, keyboard}; use iced::{alignment, keyboard, Element, Fill, Task, Theme};
use parking_lot::Mutex; use parking_lot::Mutex;
use rodio::MixerDeviceSink; use rodio::MixerDeviceSink;
use std::collections::HashSet; use std::collections::HashSet;
@@ -25,7 +25,7 @@ pub struct RepetitionState {
current_statistic: CardStatistics, current_statistic: CardStatistics,
open: bool, open: bool,
can_play: bool, can_play: bool,
sink: Arc<MixerDeviceSink>, sink: Arc<Option<MixerDeviceSink>>,
opened: HashSet<Id>, opened: HashSet<Id>,
} }
@@ -100,7 +100,12 @@ impl RepetitionState {
pub(crate) fn new(set: DeckSettings, state: Arc<Mutex<AppState>>) -> RepetitionState { pub(crate) fn new(set: DeckSettings, state: Arc<Mutex<AppState>>) -> RepetitionState {
let mut card_set = DeckData::new(&set, state.clone()); let mut card_set = DeckData::new(&set, state.clone());
let (word, stat) = card_set.next(); let (word, stat) = card_set.next();
let sink_handle = rodio::DeviceSinkBuilder::open_default_sink().unwrap();
let sink_handle = if set.forward.contains("speech") || set.backward.contains("speech") {
rodio::DeviceSinkBuilder::open_default_sink().ok()
} else {
None
};
RepetitionState { RepetitionState {
state, state,
@@ -138,11 +143,12 @@ impl RepetitionState {
self.current_word = next.0; self.current_word = next.0;
self.current_statistic = next.1; self.current_statistic = next.1;
if self.settings.require_speech() { if self.settings.require_speech() && self.sink.is_some() {
return Task::perform( let sink = self.sink.clone();
play_sound(self.sink.clone(), self.current_word.key.clone()), let task = play_sound(sink, self.current_word.key.clone());
|_| RootMessage::Repetition(RepetitionMessage::PlayFinished), return Task::perform(task, |_| {
); RootMessage::Repetition(RepetitionMessage::PlayFinished)
});
} }
self.increment_counter(); self.increment_counter();
Task::none() Task::none()
@@ -316,10 +322,14 @@ pub enum RepetitionMessage {
PlayFinished, PlayFinished,
} }
async fn play_sound(sink: Arc<MixerDeviceSink>, text: String) { async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) {
if let Ok(data) = get_voice(text.as_str()).await { if let Ok(data) = get_voice(text.as_str()).await {
spawn_blocking(move || { spawn_blocking(move || {
rodio::play(sink.mixer(), data).unwrap().sleep_until_end(); if let Some(sink) = sink.as_ref()
&& let Ok(play) = rodio::play(sink.mixer(), data)
{
play.sleep_until_end()
}
}) })
.await .await
.unwrap(); .unwrap();
+11 -6
View File
@@ -4,7 +4,7 @@ use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::styling::*; use crate::styling::*;
use crate::sync::SyncMessage::*; use crate::sync::SyncMessage::*;
use crate::{AppState, RootMessage, fill_state}; use crate::{fill_state, AppState, RootMessage};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::container::rounded_box; use iced::widget::container::rounded_box;
use iced::widget::{button, column, container, progress_bar, row, space, text, toggler}; use iced::widget::{button, column, container, progress_bar, row, space, text, toggler};
@@ -59,7 +59,12 @@ impl NavigatedPage<SyncMessage> for SyncState {
.map(|_val: String| RootMessage::Sync(KeyCopied)); .map(|_val: String| RootMessage::Sync(KeyCopied));
} }
InitSync => { InitSync => {
return Task::perform(first_sync(), |id| RootMessage::Sync(IdReceived(id))); return Task::perform(first_sync(), |id| {
match id {
Ok(id) => RootMessage::Sync(IdReceived(id)),
Err(_) => RootMessage::None
}
});
} }
GetKey => { GetKey => {
return iced::clipboard::read() return iced::clipboard::read()
@@ -218,10 +223,10 @@ impl SyncState {
] ]
} }
} }
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.align_x(Center) .align_x(Center)
.width(Length::Shrink) .width(Length::Shrink)
.into() .into()
} }
/* fn app_updater(&self) -> Element<'_, SyncMessage> { /* fn app_updater(&self) -> Element<'_, SyncMessage> {